blob_id
stringlengths 40
40
| directory_id
stringlengths 40
40
| path
stringlengths 3
264
| content_id
stringlengths 40
40
| detected_licenses
sequencelengths 0
85
| license_type
stringclasses 2
values | repo_name
stringlengths 5
140
| snapshot_id
stringlengths 40
40
| revision_id
stringlengths 40
40
| branch_name
stringclasses 905
values | visit_date
timestamp[us]date 2015-08-09 11:21:18
2023-09-06 10:45:07
| revision_date
timestamp[us]date 1997-09-14 05:04:47
2023-09-17 19:19:19
| committer_date
timestamp[us]date 1997-09-14 05:04:47
2023-09-06 06:22:19
| github_id
int64 3.89k
681M
⌀ | star_events_count
int64 0
209k
| fork_events_count
int64 0
110k
| gha_license_id
stringclasses 22
values | gha_event_created_at
timestamp[us]date 2012-06-07 00:51:45
2023-09-14 21:58:39
⌀ | gha_created_at
timestamp[us]date 2008-03-27 23:40:48
2023-08-21 23:17:38
⌀ | gha_language
stringclasses 141
values | src_encoding
stringclasses 34
values | language
stringclasses 1
value | is_vendor
bool 1
class | is_generated
bool 2
classes | length_bytes
int64 3
10.4M
| extension
stringclasses 115
values | content
stringlengths 3
10.4M
| authors
sequencelengths 1
1
| author_id
stringlengths 0
158
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
c091083b3a7f291150ee76232f9d0218c29b1626 | 3b04925b4271fe921020cff037b86e4a5a2ae649 | /windows_embedded_ce_6_r3_170331/WINCE600/PRIVATE/TEST/BASEOS/DRIVERS/BATTERY/API/BATAPITEST/tuxmain.cpp | 430a376a061f20cea6e8a5c8bd88f9ac3f3a2ea8 | [] | no_license | fanzcsoft/windows_embedded_ce_6_r3_170331 | e3a4d11bf2356630a937cbc2b7b4e25d2717000e | eccf906d61a36431d3a37fb146a5d04c5f4057a2 | refs/heads/master | 2022-12-27T17:14:39.430205 | 2020-09-28T20:09:22 | 2020-09-28T20:09:22 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 8,488 | cpp | //
// Copyright (c) Microsoft Corporation. All rights reserved.
//
//
// Use of this source code is subject to the terms of the Microsoft shared
// source or premium shared source license agreement under which you licensed
// this source code. If you did not accept the terms of the license agreement,
// you are not authorized to use this source code. For the terms of the license,
// please see the license agreement between you and Microsoft or, if applicable,
// see the SOURCE.RTF on your install media or the root of your tools installation.
// THE SOURCE CODE IS PROVIDED "AS IS", WITH NO WARRANTIES.
//
#include "TuxMain.h"
#include "Testmain.h"
// debugging
#define Debug NKDbgPrintfW
// Global CKato logging object. Set while processing SPM_LOAD_DLL message.
CKato *g_pKato = NULL;
// Global shell info structure. Set while processing SPM_SHELL_INFO message.
SPS_SHELL_INFO *g_pShellInfo;
// extern "C"
#ifdef __cplusplus
extern "C" {
#endif
// --------------------------------------------------------------------
// Tux testproc function table
//
FUNCTION_TABLE_ENTRY g_lpFTE[] = {
_T("Battery API test"), 0, 0, 0, NULL,
_T("GetSystemPowerStatusEx2"), 1, 0, 1001, Tst_GetSystemPowerStatusEx2,
_T("BatteryDrvrGetLevels"), 1, 0, 1002, Tst_BatteryDrvrGetLevels,
_T("BatteryDrvrSupportsChangeNotification"), 1, 0, 1003, Tst_BatteryDrvrSupportsChangeNotification,
_T("BatteryGetLifeTimeInfo"), 1, 0, 1004, Tst_BatteryGetLifeTimeInfo,
NULL, 0, 0, 0, NULL
};
// --------------------------------------------------------------------
// --------------------------------------------------------------------
BOOL WINAPI
DllMain(
HANDLE hInstance,
ULONG dwReason,
LPVOID lpReserved )
// --------------------------------------------------------------------
{
UNREFERENCED_PARAMETER(hInstance);
UNREFERENCED_PARAMETER(lpReserved);
switch( dwReason )
{
case DLL_PROCESS_ATTACH:
Debug(TEXT("%s: DLL_PROCESS_ATTACH\r\n"), MODULE_NAME);
return TRUE;
case DLL_PROCESS_DETACH:
Debug(TEXT("%s: DLL_PROCESS_DETACH\r\n"), MODULE_NAME);
return TRUE;
}
return FALSE;
}
#ifdef __cplusplus
} // end extern "C"
#endif
// --------------------------------------------------------------------
void LOG(LPWSTR szFmt, ...)
// --------------------------------------------------------------------
{
va_list va;
if(g_pKato)
{
va_start(va, szFmt);
g_pKato->LogV( LOG_DETAIL, szFmt, va);
va_end(va);
}
}
// --------------------------------------------------------------------
void FAILLOG(LPWSTR szFmt, ...)
// --------------------------------------------------------------------
{
va_list va;
if(g_pKato)
{
va_start(va, szFmt);
g_pKato->LogV( LOG_FAIL, szFmt, va);
va_end(va);
}
}
// --------------------------------------------------------------------
SHELLPROCAPI
ShellProc(
UINT uMsg,
SPPARAM spParam )
// --------------------------------------------------------------------
{
LPSPS_BEGIN_TEST pBT = {0};
LPSPS_END_TEST pET = {0};
switch (uMsg) {
// --------------------------------------------------------------------
// Message: SPM_LOAD_DLL
//
case SPM_LOAD_DLL:
Debug(_T("ShellProc(SPM_LOAD_DLL, ...) called\r\n"));
// If we are UNICODE, then tell Tux this by setting the following flag.
#ifdef UNICODE
((LPSPS_LOAD_DLL)spParam)->fUnicode = TRUE;
#endif
// turn on kato debugging
KatoDebug(1, KATO_MAX_VERBOSITY,KATO_MAX_VERBOSITY,KATO_MAX_LEVEL);
// Get/Create our global logging object.
g_pKato = (CKato*)KatoGetDefaultObject();
GetBatteryFunctionEntries();
return SPR_HANDLED;
// --------------------------------------------------------------------
// Message: SPM_UNLOAD_DLL
//
case SPM_UNLOAD_DLL:
Debug(_T("ShellProc(SPM_UNLOAD_DLL, ...) called"));
FreeCoreDll();
return SPR_HANDLED;
// --------------------------------------------------------------------
// Message: SPM_SHELL_INFO
//
case SPM_SHELL_INFO:
Debug(_T("ShellProc(SPM_SHELL_INFO, ...) called\r\n"));
// Store a pointer to our shell info for later use.
g_pShellInfo = (LPSPS_SHELL_INFO)spParam;
// handle command line parsing
return SPR_HANDLED;
// --------------------------------------------------------------------
// Message: SPM_REGISTER
//
case SPM_REGISTER:
Debug(_T("ShellProc(SPM_REGISTER, ...) called\r\n"));
((LPSPS_REGISTER)spParam)->lpFunctionTable = g_lpFTE;
#ifdef UNICODE
return SPR_HANDLED | SPF_UNICODE;
#else
return SPR_HANDLED;
#endif
// --------------------------------------------------------------------
// Message: SPM_START_SCRIPT
//
case SPM_START_SCRIPT:
Debug(_T("ShellProc(SPM_START_SCRIPT, ...) called\r\n"));
return SPR_HANDLED;
// --------------------------------------------------------------------
// Message: SPM_STOP_SCRIPT
//
case SPM_STOP_SCRIPT:
return SPR_HANDLED;
// --------------------------------------------------------------------
// Message: SPM_BEGIN_GROUP
//
case SPM_BEGIN_GROUP:
Debug(_T("ShellProc(SPM_BEGIN_GROUP, ...) called\r\n"));
g_pKato->BeginLevel(0, _T("BEGIN GROUP: FSDTEST.DLL"));
return SPR_HANDLED;
// --------------------------------------------------------------------
// Message: SPM_END_GROUP
//
case SPM_END_GROUP:
Debug(_T("ShellProc(SPM_END_GROUP, ...) called\r\n"));
g_pKato->EndLevel(_T("END GROUP: TUXDEMO.DLL"));
return SPR_HANDLED;
// --------------------------------------------------------------------
// Message: SPM_BEGIN_TEST
//
case SPM_BEGIN_TEST:
Debug(_T("ShellProc(SPM_BEGIN_TEST, ...) called\r\n"));
// Start our logging level.
pBT = (LPSPS_BEGIN_TEST)spParam;
g_pKato->BeginLevel(pBT->lpFTE->dwUniqueID,
_T("BEGIN TEST: \"%s\", Threads=%u, Seed=%u"),
pBT->lpFTE->lpDescription, pBT->dwThreadCount,
pBT->dwRandomSeed);
return SPR_HANDLED;
// --------------------------------------------------------------------
// Message: SPM_END_TEST
//
case SPM_END_TEST:
Debug(_T("ShellProc(SPM_END_TEST, ...) called\r\n"));
// End our logging level.
pET = (LPSPS_END_TEST)spParam;
g_pKato->EndLevel(_T("END TEST: \"%s\", %s, Time=%u.%03u"),
pET->lpFTE->lpDescription,
pET->dwResult == TPR_SKIP ? _T("SKIPPED") :
pET->dwResult == TPR_PASS ? _T("PASSED") :
pET->dwResult == TPR_FAIL ? _T("FAILED") : _T("ABORTED"),
pET->dwExecutionTime / 1000, pET->dwExecutionTime % 1000);
return SPR_HANDLED;
// --------------------------------------------------------------------
// Message: SPM_EXCEPTION
//
case SPM_EXCEPTION:
Debug(_T("ShellProc(SPM_EXCEPTION, ...) called\r\n"));
g_pKato->Log(LOG_EXCEPTION, _T("Exception occurred!"));
return SPR_HANDLED;
default:
Debug(_T("ShellProc received bad message: 0x%X\r\n"), uMsg);
ASSERT(!"Default case reached in ShellProc!");
return SPR_NOT_HANDLED;
}
}
| [
"[email protected]"
] | |
6c899eff116c3dd03e8f6042a95f6179fbd2bc44 | 1a351f213843f01c12fc39025427bc21049b298a | /L1-030/main.cpp | 511a638057b40590e50f1d3ad0b6fbd52542f2b2 | [] | no_license | microjun/CCCC-GPLT | 1c040ace5837c2472542cd8e191a0f46bee9c4d5 | 379ad8db29d006f755a50706940c299544046131 | refs/heads/master | 2020-03-21T23:01:57.394909 | 2018-08-12T04:42:54 | 2018-08-12T04:42:54 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 661 | cpp | #include <iostream>
#include <vector>
using namespace std;
int main()
{
int num;
cin>>num;
int a[num];
string student[num];
for(int i= 0 ;i< num ;i++ )
{
cin>>a[i]>>student[i];
}
int k = num-1 , z = num-1;
for(int i = 0 ;i< num/2 ;i++ )
{
if(a[i] == 0)
{
while(a[k] != 1)
k--;
cout<<student[i]<<" "<<student[k]<<endl;
k--;
} else
{
while(a[z] != 0)
z--;
cout<<student[i]<<" "<<student[z]<<endl;
z--;
}
}
return 0;
}
| [
"[email protected]"
] | |
af646e8e9f37da927a0a1e2357c70e9b0ed17d2a | e5a55c978188e8898955bf301d6fef608915682e | /ConsoleApplication37/szescian.cpp | aad01252fd7ab86fba7230bb44e0a889b3e39638 | [] | no_license | olipop210/informatyka_klasy_geometria | aa342c797ec0d5a30d7d24f29c5d259f0ac9a284 | ed4105918e58219de9ca1a4ffd9b3b0b8190b8e0 | refs/heads/main | 2023-04-07T08:52:19.324333 | 2021-04-12T17:53:25 | 2021-04-12T17:53:25 | 357,262,890 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 512 | cpp | #include "szescian.h"
#include <iostream>
szescian::szescian()
{
this->bok1 = 0;
this->pole = 0;
this->objetosc = 0;
std::cout << "pole szescianu wynosi " << pole << " a objetosc " << objetosc << std::endl;
}
szescian::szescian(unsigned int bok1)
{
this->bok1 = bok1;
this->pole = bok1 * bok1 * 6;
this->objetosc = bok1 * bok1 * bok1;
std::cout << "pole szescianu wynosi " << pole << " a objetosc " << objetosc << std::endl;
}
szescian::~szescian()
{
}
int szescian::getobjetosc()
{
return objetosc;
} | [
"[email protected]"
] | |
9ff7ce771206e98236c01c15e776f6aad145810c | dd80a584130ef1a0333429ba76c1cee0eb40df73 | /external/clang/test/SemaCXX/primary-base.cpp | 0b6aaef493cbfaa17a0fd999f87648b06ec71099 | [
"MIT",
"NCSA"
] | permissive | karunmatharu/Android-4.4-Pay-by-Data | 466f4e169ede13c5835424c78e8c30ce58f885c1 | fcb778e92d4aad525ef7a995660580f948d40bc9 | refs/heads/master | 2021-03-24T13:33:01.721868 | 2017-02-18T17:48:49 | 2017-02-18T17:48:49 | 81,847,777 | 0 | 2 | MIT | 2020-03-09T00:02:12 | 2017-02-13T16:47:00 | null | UTF-8 | C++ | false | false | 312 | cpp | // RUN: %clang_cc1 -fsyntax-only -verify %s
// expected-no-diagnostics
class A { virtual void f(); };
class B : virtual A { };
class C : B { };
// Since A is already a primary base class, C should be the primary base class
// of F.
class F : virtual A, virtual C { };
int sa[sizeof(F) == sizeof(A) ? 1 : -1];
| [
"[email protected]"
] | |
3c5bf6bbb1d18088f43189d1ae8d0d59a87fc581 | e99e9c08f9b60909b9880ab42943a9d1c654df37 | /CoordinateSystems/main.cpp | f307379240c96862d555108e3d0e852610f117b9 | [] | no_license | stac21/OpenGL-Demos | 5063184ed4e7bbe2d9dc6f33b9a07ade36a846b3 | 531051f08b476a3064e6f78fdc492b48a6e7cabc | refs/heads/master | 2020-08-02T15:15:07.409546 | 2019-09-27T21:21:53 | 2019-09-27T21:21:53 | 211,403,063 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 16,521 | cpp | #include <glad/glad.h>
#include <glfw3.h>
#include <glm/glm.hpp>
#include <glm/gtc/matrix_transform.hpp>
#include <glm/gtc/type_ptr.hpp>
#include <iostream>
#include "shader.h"
#include "stb_image.h"
void framebuffer_size_callback(GLFWwindow* window, int width, int height);
void mouse_callback(GLFWwindow* window, double xpos, double ypos);
void scroll_callback(GLFWwindow* window, double x_offset, double y_offset);
void process_input(GLFWwindow* window);
float get_delta_time();
int window_width = 800;
int window_height = 600;
constexpr float PLANE_DISTANCE = 100.0f;
float mixValue = 0.2f;
constexpr float camera_speed = 2.5f;
float sensitivity = 0.05f;
glm::vec3 camera_pos = glm::vec3(0.0f, 0.0f, 3.0f);
glm::vec3 camera_front = glm::vec3(0.0f, 0.0f, -1.0f);
glm::vec3 camera_up = glm::vec3(0.0f, 1.0f, 0.0f);
float current_frame_time = 0.0f;
float last_frame_time = 0.0f;
float last_x, last_y;
float pitch = 0.0f;
/*
yaw is initialized to -90.0 degrees since a yaw of 0.0 results in a direction vector pointing to
the right so we initially rotate a bit to the left
*/
float yaw = -90.0f;
float fov = 45.0f;
int main() {
glfwInit();
glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3);
glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
#ifdef __APPLE__
glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE);
#endif
GLFWwindow* window = glfwCreateWindow(window_width, window_height, "Coordinate Systems", NULL, NULL);
if (window == NULL) {
std::cout << "Failed to create window" << std::endl;
glfwTerminate();
return -1;
}
glfwMakeContextCurrent(window);
glfwSetFramebufferSizeCallback(window, framebuffer_size_callback);
glfwSetCursorPosCallback(window, mouse_callback);
glfwSetScrollCallback(window, scroll_callback);
int temp_x, temp_y;
glfwGetFramebufferSize(window, &temp_x, &temp_y);
last_x = (float)temp_x;
last_y = (float)temp_y;
if (!gladLoadGLLoader((GLADloadproc)glfwGetProcAddress)) {
std::cout << "Failed to initlalize GLAD" << std::endl;
return -1;
}
// Hides the mouse cursor and prevents it from leaving the window
glfwSetInputMode(window, GLFW_CURSOR, GLFW_CURSOR_DISABLED);
float vertices[] = {
-0.5f, -0.5f, -0.5f, 0.0f, 0.0f,
0.5f, -0.5f, -0.5f, 1.0f, 0.0f,
0.5f, 0.5f, -0.5f, 1.0f, 1.0f,
0.5f, 0.5f, -0.5f, 1.0f, 1.0f,
-0.5f, 0.5f, -0.5f, 0.0f, 1.0f,
-0.5f, -0.5f, -0.5f, 0.0f, 0.0f,
-0.5f, -0.5f, 0.5f, 0.0f, 0.0f,
0.5f, -0.5f, 0.5f, 1.0f, 0.0f,
0.5f, 0.5f, 0.5f, 1.0f, 1.0f,
0.5f, 0.5f, 0.5f, 1.0f, 1.0f,
-0.5f, 0.5f, 0.5f, 0.0f, 1.0f,
-0.5f, -0.5f, 0.5f, 0.0f, 0.0f,
-0.5f, 0.5f, 0.5f, 1.0f, 0.0f,
-0.5f, 0.5f, -0.5f, 1.0f, 1.0f,
-0.5f, -0.5f, -0.5f, 0.0f, 1.0f,
-0.5f, -0.5f, -0.5f, 0.0f, 1.0f,
-0.5f, -0.5f, 0.5f, 0.0f, 0.0f,
-0.5f, 0.5f, 0.5f, 1.0f, 0.0f,
0.5f, 0.5f, 0.5f, 1.0f, 0.0f,
0.5f, 0.5f, -0.5f, 1.0f, 1.0f,
0.5f, -0.5f, -0.5f, 0.0f, 1.0f,
0.5f, -0.5f, -0.5f, 0.0f, 1.0f,
0.5f, -0.5f, 0.5f, 0.0f, 0.0f,
0.5f, 0.5f, 0.5f, 1.0f, 0.0f,
-0.5f, -0.5f, -0.5f, 0.0f, 1.0f,
0.5f, -0.5f, -0.5f, 1.0f, 1.0f,
0.5f, -0.5f, 0.5f, 1.0f, 0.0f,
0.5f, -0.5f, 0.5f, 1.0f, 0.0f,
-0.5f, -0.5f, 0.5f, 0.0f, 0.0f,
-0.5f, -0.5f, -0.5f, 0.0f, 1.0f,
-0.5f, 0.5f, -0.5f, 0.0f, 1.0f,
0.5f, 0.5f, -0.5f, 1.0f, 1.0f,
0.5f, 0.5f, 0.5f, 1.0f, 0.0f,
0.5f, 0.5f, 0.5f, 1.0f, 0.0f,
-0.5f, 0.5f, 0.5f, 0.0f, 0.0f,
-0.5f, 0.5f, -0.5f, 0.0f, 1.0f
};
glm::vec3 cubePositions[] = {
glm::vec3(0.0f, 0.0f, 0.0f),
glm::vec3(2.0f, 5.0f, -15.0f),
glm::vec3(-1.5f, -2.2f, -2.5f),
glm::vec3(-3.8f, -2.0f, -12.3f),
glm::vec3(2.4f, -0.4f, -3.5f),
glm::vec3(-1.7f, 3.0f, -7.5f),
glm::vec3(1.3f, -2.0f, -2.5f),
glm::vec3(1.5f, 2.0f, -2.5f),
glm::vec3(1.5f, 0.2f, -1.5f),
glm::vec3(-1.3f, 1.0f, -1.5f)
};
Shader shader("C:\\Users\\Grant\\LearnOpenGL Files\\CoordinateSystems\\vertexShader.txt", "C:\\Users\\Grant\\LearnOpenGL Files\\CoordinateSystems\\fragmentShader.txt");
// load the image of the container and assign the widht, height, and num_channels to those of the image
int width, height, num_channels;
unsigned char* data1 = stbi_load("C:\\Users\\Grant\\LearnOpenGL Files\\CoordinateSystems\\container.jpg", &width, &height, &num_channels, 0);
unsigned int texture1;
glGenTextures(1, &texture1); // just like any other objects in OpenGL, textures are referenced with an ID
glBindTexture(GL_TEXTURE_2D, texture1);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
// set the texture filtering method for downscaling then upscaling (don't know if GL_NEAREST_MIPMAP_LINEAR is good to use)
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST_MIPMAP_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
if (data1) {
/*
now that the texture is bound, we can start generating a texture using the previously loaded
image data
The first argument specifies the texture target; setting this to GL_TEXTURE_2D means that this
operation will generate a texture on the currently bound texture object at the same target
(so any textures bound to targets GL_TEXTURE_1D or GL_TEXTURE_3D will not be affected
The second argument specifies the mipmap level for which we want to create a texture for if you
want to set each mipmap level manually, but we'll leave it at the base level which is 0
The third argument tells OpenGL in what kind of format we want to store the texture. Our image
has only RGB values so we'll store the texture with RGB values as well
The 4th and 5th arguments set the width and height of the resulting texture. We stored
those earlier when loading the image so we'll use the corresponding variables
The next argument should always be 0 (some legacy stuff, apparently)
The 7th and 8th arguments specify the format and datatype of the source image. We loaded the
image with RGB values and stored them as chars (bytes) so we'll pass in the corresponding values
The final argument is the actual image data
*/
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, width, height, 0, GL_RGB, GL_UNSIGNED_BYTE, data1);
glGenerateMipmap(GL_TEXTURE_2D);
} else {
std::cout << "Failed to load texture" << std::endl;
}
// free the image memory, since we don't need it anymore after generating the texture
stbi_image_free(data1);
unsigned int texture2;
// otherwise the image of the face will be upsidedown (just how it is, yaknow)
stbi_set_flip_vertically_on_load(true);
unsigned char* data2 = stbi_load("C:\\Users\\Grant\\LearnOpenGL Files\\CoordinateSystems\\awesomeface.png", &width, &height, &num_channels, 0);
glGenTextures(1, &texture2);
glBindTexture(GL_TEXTURE_2D, texture2);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST_MIPMAP_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
if (data2) {
// awesomeface.png has transparency and thus an alpha channel, so the data type is GL_RGBA
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, width, height, 0, GL_RGBA, GL_UNSIGNED_BYTE, data2);
glGenerateMipmap(GL_TEXTURE_2D);
} else {
std::cout << "Failed to load texture" << std::endl;
}
// free the image memory, because we don't need it anymore after generating the texture
stbi_image_free(data2);
// Generatea vertex buffer with a buffer ID
unsigned int VBO, VAO;
glGenVertexArrays(1, &VAO);
glGenBuffers(1, &VBO);
// bind the VAO first, then bind and set vertex buffer(s), then congigure vertex attribute(s)
glBindVertexArray(VAO);
// bind the newly created buffer to the GL_ARRAY_BUFFER target
glBindBuffer(GL_ARRAY_BUFFER, VBO);
glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices, GL_STATIC_DRAW);
/*
glVertexAttribPointer tells OpenGL how it should interpret the vertex data per vertex attribute
The first argument specifies which vertex attribute we want to configure (the vertex shader's
position was set in the shading language with layout (location = 0)
Second argument specifies the size of the vertex attribute. Since the vertex attribute is a
vec3 in the shading language, it is composed of 3 values
Third argument specifies the type of data which is GL_FLOAT, because a pointer to a vec in GLSL
consists of floating point values
Fourth argument specifies if we want the data to be normalized. If we set this to GL_TRUE,
all the data that has a value not between 0 (or -1 for signed data) and 1 will be mapped to those
values.
Fifth argument is known as the stride and tells us the space between consecutive vertex attribute
sets. We just multiply the size of the vertex attributes by the size of their type, in this case
6 * sizeof(float) (6 because we have to move six floats to the right to obtain the next
vertex attribute (three for the position values and three for the color values))
Sixth argument is the offset of where the position data begins in the buffer
*/
// position attribute
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 5 * sizeof(float), (void*)0);
/*
Vertex attributes are disabled by default so we have to enable it here. The argument is the
shader's position (0 in this case)
*/
glEnableVertexAttribArray(0);
glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, 5 * sizeof(float), (void*)(3 * sizeof(float)));
glEnableVertexAttribArray(1);
glBindBuffer(GL_ARRAY_BUFFER, 0);
glBindVertexArray(0);
/*
Tell OpenGL which texture unit each shader sampler belongs to by setting each sampler
using glUniform1i. Only needs to be set once so we can do this before we enter the render loop
*/
shader.use();
glUniform1i(glGetUniformLocation(shader.ID, "texture1"), 0); // set it manually
shader.set_int("texture2", 1); // set it with the function in the shader class (no difference in outcome, just done different ways for example)
/*
Create the model matrix, which consists of translations, scalings, and/or rotations we'd like
to apply to transform all object's vertices to the global world space. Here we transform
our plane a bit by rotating it on the x-axis so it looks like it's laying on the floor
By multiplying the vertex coordinates with this model matrix we're transforming the vertex
coordinates to world coordinates. Our plane that is slightly on the floor thus represents
the plane in the global world
*/
glm::mat4 view, proj;
/*
We want to move the camera in the positive z-direction (since we're moving backwards),
so it is good to note that we're translating the scene in the reverse direction of where
we want to move because the world's objects move in the opposite direction of the camera
*/
// enable depth testing, since it is disabled by OpenGL by default
glEnable(GL_DEPTH_TEST);
while (!glfwWindowShouldClose(window)) {
last_frame_time = current_frame_time;
current_frame_time = glfwGetTime();
// input
process_input(window);
// render
glClearColor(0.2f, 0.3f, 0.3f, 1.0f);
/*
Since we're using a depth buffer we also want to clear the depth buffer before each
render iteration (otherwise the depth information of the previous frame stays in the buffer)
in addition to clearing the last frame's color buffer
*/
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
// output (draw the shape)
/*
float time_value = glfwGetTime();
float green_value = sin(time_value) / 2.0f + 0.5f;
int vertex_color_location = glGetUniformLocation(shader_program, "ourColor");
glUniform4f(vertex_color_location, 0.0f, green_value, 0.0f, 1.0f);
*/
// bind the textures to their corresponding texture unit
glActiveTexture(GL_TEXTURE0);
glBindTexture(GL_TEXTURE_2D, texture1);
glActiveTexture(GL_TEXTURE1);
glBindTexture(GL_TEXTURE_2D, texture2);
shader.use(); // be sure to activate the shader before any calls to glUniform
shader.set_float("mixValue", mixValue);
glBindVertexArray(VAO);
/*
setting the direction to cameraPos + cameraFront ensures that however we move, the camera
keeps looking at the target direction
*/
view = glm::lookAt(camera_pos, camera_pos + camera_front, camera_up);
/*
create a perspective projection matrix
First parameter determines the FOV (field of view)
Second parameter determines the aspect ratio, so just divide the width by the height of the window
Third and fourth parameters determine the near and far planes of the frustum
*/
proj = glm::perspective(glm::radians(fov), (float)window_width / (float)window_height, 0.1f, PLANE_DISTANCE);
/*
if we do not reset the values then the cube will continue to translate by the value
of the variable every frame
*/
glUniformMatrix4fv(glGetUniformLocation(shader.ID, "view"), 1, GL_FALSE, &view[0][0]);
glUniformMatrix4fv(glGetUniformLocation(shader.ID, "projection"), 1, GL_FALSE,
glm::value_ptr(proj));
for (int i = 0; i < 10; i++) {
glm::mat4 model;
model = glm::translate(model, cubePositions[i]);
model = glm::rotate(model, (float)sin(glfwGetTime()) * glm::radians(50.0f),
glm::vec3(0.5f, 1.0f, 0.0f));
glUniformMatrix4fv(glGetUniformLocation(shader.ID, "model"), 1, GL_FALSE,
glm::value_ptr(model));
glDrawArrays(GL_TRIANGLES, 0, 36);
}
//glDrawElements(GL_TRIANGLES, 6, GL_UNSIGNED_INT, 0);
glBindVertexArray(0);
// glfw: swap buffers and poll IO events (keys pressed/released, mouse moved, etc.)
glfwSwapBuffers(window);
glfwPollEvents();
}
glDeleteVertexArrays(1, &VAO);
glDeleteBuffers(1, &VBO);
glfwTerminate();
return 0;
}
void framebuffer_size_callback(GLFWwindow* window, int width, int height) {
window_width = width;
window_height = height;
glViewport(0, 0, width, height);
}
/*
When handling mouse input for an FPS style camera there are several steps we must take before
eventually retrieving the direction vector
1. Calculate the mouse's offset since the last frame
2. Add the offset values to the camera's yaw and pitch values
3. Add some constraints to the max/min yaw/pitch values
4. Calculate the direction vector
*/
void mouse_callback(GLFWwindow* window, double xpos, double ypos) {
// 1. Calculate the mouse's offset since the last frame
float x_offset = sensitivity * ((float)xpos - last_x);
float y_offset = sensitivity * (last_y - (float)ypos); // reversed since y-coordinates range from bottom to top
last_x = (float)xpos;
last_y = (float)ypos;
// 2. Add the offset values to teh camera's yaw and pitch values
// 3. Add some constraints to the min/max yaw/pitch values
yaw += x_offset;
// prevents the user from going past the very top of the sky/their feet
if (pitch < 89.0f && pitch > -89.0f) {
pitch += y_offset;
}
glm::vec3 front;
front.x = cos(glm::radians(pitch)) * cos(glm::radians(yaw));
front.y = sin(glm::radians(pitch));
front.z = cos(glm::radians(pitch)) * sin(glm::radians(yaw));
camera_front = glm::normalize(front);
}
void scroll_callback(GLFWwindow* window, double x_offset, double y_offset) {
if (fov >= 1.0f) {
fov += y_offset;
} else if (fov <= 60.0f) {
fov -= y_offset;
}
}
void process_input(GLFWwindow* window) {
if (glfwGetKey(window, GLFW_KEY_ESCAPE) == GLFW_PRESS) {
glfwSetWindowShouldClose(window, true);
} else if (glfwGetKey(window, GLFW_KEY_UP) == GLFW_PRESS && mixValue < 1.0f) {
mixValue += 0.05f;
} else if (glfwGetKey(window, GLFW_KEY_DOWN) == GLFW_PRESS && mixValue > 0.0f) {
mixValue -= 0.05f;
} else if (glfwGetKey(window, GLFW_KEY_W) == GLFW_PRESS) {
camera_pos += camera_speed * get_delta_time() * camera_front;
} else if (glfwGetKey(window, GLFW_KEY_S) == GLFW_PRESS) {
camera_pos -= camera_speed * get_delta_time() * camera_front;
} else if (glfwGetKey(window, GLFW_KEY_A) == GLFW_PRESS) {
camera_pos -= camera_speed * get_delta_time() * glm::normalize(glm::cross(camera_front, camera_up));
} else if (glfwGetKey(window, GLFW_KEY_D) == GLFW_PRESS) {
camera_pos += camera_speed * get_delta_time() * glm::normalize(glm::cross(camera_front, camera_up));
} else if (glfwGetKey(window, GLFW_KEY_SPACE) == GLFW_PRESS) {
camera_pos += camera_speed * get_delta_time() * camera_up;
} else if (glfwGetKey(window, GLFW_KEY_LEFT_CONTROL) == GLFW_PRESS) {
camera_pos -= camera_speed * get_delta_time() * camera_up;
}
}
float get_delta_time() {
return current_frame_time - last_frame_time;
} | [
"[email protected]"
] | |
dc0c2bf6470b3e704b2f61c614fde71daa14cb23 | 8afb5afd38548c631f6f9536846039ef6cb297b9 | /_REPO/MICROSOFT/react-native-windows/vnext/Shared/Modules/SourceCodeModule.cpp | a3c277ffb8adbe24ba464893682e63b457fa3798 | [
"MIT"
] | permissive | bgoonz/UsefulResourceRepo2.0 | d87588ffd668bb498f7787b896cc7b20d83ce0ad | 2cb4b45dd14a230aa0e800042e893f8dfb23beda | refs/heads/master | 2023-03-17T01:22:05.254751 | 2022-08-11T03:18:22 | 2022-08-11T03:18:22 | 382,628,698 | 10 | 12 | MIT | 2022-10-10T14:13:54 | 2021-07-03T13:58:52 | null | UTF-8 | C++ | false | false | 886 | cpp | // Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
#include "SourceCodeModule.h"
using namespace folly;
using namespace facebook::xplat;
namespace facebook {
namespace react {
const char *SourceCodeModule::Name = "SourceCode";
SourceCodeModule::SourceCodeModule(const std::string &bundleUrl) : m_bundleUrl(bundleUrl) {}
std::string SourceCodeModule::getName() {
return Name;
}
auto SourceCodeModule::getConstants() -> std::map<std::string, dynamic> {
return {{"scriptURL", m_bundleUrl.empty() ? "" : m_bundleUrl}};
}
auto SourceCodeModule::getMethods() -> std::vector<Method> {
return {};
}
} // namespace react
} // namespace facebook
// By convention, the function name should be the same as the class
// name.
extern "C" facebook::xplat::module::CxxModule *SourceCodeModule() {
return new facebook::react::SourceCodeModule(std::string());
}
| [
"[email protected]"
] | |
9e271d350e9336ff8ef989bc76dbafc643a4f33f | 4b365afe486a2185d31cfdb1a035ac2f49908a69 | /tests/Factory_TEST.cpp | 48540545e5c8bf4fd62e9302bd9f33610df9d7c7 | [
"BSD-2-Clause"
] | permissive | jslee02/noriter | 44dd5a5a614ddb755adbaf494af9bba6a9ef71d4 | c6ad1644c01520653ea8e8973f03fcea71a406e3 | refs/heads/master | 2021-01-10T09:25:35.364329 | 2016-10-27T12:47:35 | 2016-10-27T12:47:35 | 46,693,349 | 0 | 0 | null | 2016-03-22T20:23:03 | 2015-11-23T03:02:08 | C++ | UTF-8 | C++ | false | false | 1,146 | cpp | #include <gtest/gtest.h>
#include "noriter/noriter.h"
using namespace nrt;
enum ObjectTypeTestEnum
{
OET_Link,
OET_Skeleton
};
enum class ObjectTypeTestEnumClass
{
Link,
Skeleton
};
NORITER_REGISTER_OBJECT_TO_FACTORY(std::string, "Link", Serializable, Link)
NORITER_REGISTER_OBJECT_TO_FACTORY(ObjectTypeTestEnumClass, ObjectTypeTestEnumClass::Link, Serializable, Link)
NORITER_REGISTER_OBJECT_TO_FACTORY(unsigned int, OET_Link, Serializable, Link)
//==============================================================================
TEST(Factory, Basic)
{
Serializable* link1 = Factory<std::string, Serializable>::create("Link");
// Serializable* link2 = Factory<ObjectEnumClassType, Serializable>::create(ObjectEnumClassType::Link);
// Serializable* link3 = Factory<unsigned int, Serializable>::create(OET_Link);
EXPECT_NE(link1, nullptr);
// EXPECT_NE(link2, nullptr);
// EXPECT_NE(link3, nullptr);
using new_type = decltype(link1);
}
//==============================================================================
int main(int argc, char* argv[])
{
::testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}
| [
"[email protected]"
] | |
0e0e88a1ce4b4727a52448671a6d97a87213729e | a1cc8e0976f296192b1002e279d66a6a3dada28f | /visual_utility/test/FrameEstimatorTest.cc | 9a10dda4dc0319abd70bb265209c542a700c3a37 | [
"MIT"
] | permissive | MRSD2018/reefbot-1 | 40ef435ac4e1664858f225fde1d9ee995d55f235 | a595ca718d0cda277726894a3105815cef000475 | refs/heads/master | 2021-04-09T10:26:25.455651 | 2018-04-01T19:13:43 | 2018-04-01T19:13:43 | 125,381,499 | 0 | 0 | MIT | 2018-04-01T15:24:29 | 2018-03-15T14:41:59 | C++ | UTF-8 | C++ | false | false | 1,648 | cc | #include "visual_utility/FrameEstimator.h"
#include "visual_utility/VisualUtilityMosaic.h"
#include <gtest/gtest.h>
#include <boost/scoped_ptr.hpp>
using namespace cv;
using namespace std;
using namespace boost;
using namespace cv_blobs;
namespace visual_utility {
class MaxPointConstantFramesizeTest : public ::testing::Test {
protected:
scoped_ptr<VisualUtilityMosaic> mosaic;
scoped_ptr<FrameEstimator> frameEstimator;
vector<FrameOfInterest> frames;
virtual void SetUp() {
mosaic.reset(new NullVUMosaic(0,0));
frameEstimator.reset(new MaxPointConstantFramesize(Size_<int>(3,2)));
frames.clear();
}
};
TEST_F(MaxPointConstantFramesizeTest, SingleMaxPointInCenter) {
Mat_<double> frame = Mat_<double>::ones(6,8);
frame[2][4] = 10;
frame[0][5] = -16;
mosaic->AddFrame(frame, NULL);
frameEstimator->FindInterestingFrames(*mosaic, &frames);
ASSERT_EQ(frames.size(), 1u);
EXPECT_FLOAT_EQ(frames[0].height, 2);
EXPECT_FLOAT_EQ(frames[0].width, 3);
EXPECT_FLOAT_EQ(frames[0].xCenter, 0);
EXPECT_FLOAT_EQ(frames[0].yCenter, -1);
}
TEST_F(MaxPointConstantFramesizeTest, SingleMaxPointOnLeftEdge) {
Mat_<double> frame = Mat_<double>::ones(6,8);
frame[2][0] = 10;
frame[0][5] = -16;
mosaic->AddFrame(frame, NULL);
frameEstimator->FindInterestingFrames(*mosaic, &frames);
ASSERT_EQ(frames.size(), 1u);
EXPECT_FLOAT_EQ(frames[0].height, 2);
EXPECT_FLOAT_EQ(frames[0].width, 3);
EXPECT_FLOAT_EQ(frames[0].xCenter, -4);
EXPECT_FLOAT_EQ(frames[0].yCenter, -1);
}
} // namespace
int main(int argc, char **argv) {
::testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}
| [
"[email protected]"
] | |
e59c303ab7c181e8ea335ace5093eeccdddc5044 | 12cd186216e40e62686134ca4a160456da9b3e65 | /sorting/insertion_sort_array.cpp | d8b3e5be705e7969225752a32211f2cc75889f20 | [
"MIT"
] | permissive | ndahiya3/algos-and-datastructures | 58770bf25defeb3e37238e1a2eb461650bce37aa | 0bde17d2438eac4cd39d9f63aa1cec884c5b5775 | refs/heads/master | 2020-03-17T15:02:58.740264 | 2018-06-08T22:23:49 | 2018-06-08T22:23:49 | 133,696,429 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,359 | cpp | #include "insertion_sort_array.h"
template <class T> void insertionSort<T>::insertion_sort_asc() {
// Insertion sort array based list in Ascending order
// Starting from the 2nd element to the last element
// insert the element towards the left at its appropriate
// position by moving the out of order elements down by one
for (int i = 1; i < length; i++) {
T value = list[i]; // This creates a hole
int hole = i;
while (hole > 0 && list[hole - 1] > value) {
list[hole] = list[hole - 1]; // Move the hole upwards or left to
hole--; // the appropriate location
}
list[hole] = value; // Fill the hole with the correct value
}
}
template <class T> void insertionSort<T>::insertion_sort_des() {
// Insertion sort array based list in Descending order
// Starting from the 2nd element to the last element
// insert the element towards the left at its appropriate
// position by moving the out of order elements down by one
for (int i = 1; i < length; i++) {
T value = list[i]; // This creates a hole
int hole = i;
while (hole > 0 && list[hole - 1] < value) {
list[hole] = list[hole - 1]; // Move the hole upwards or left to
hole--; // the appropriate location
}
list[hole] = value; // Fill the hole with the correct value
}
}
| [
"[email protected]"
] | |
4ee2606683b7c97044bea9c5c7302d7d27c55f81 | f0cbae95b782f62e4373ac36bb6f9413103b5ef7 | /RegExp.h | 9656d2aed6cd04b7ab67c04b1384a00e3f3ecbcd | [] | no_license | yar-tal-de-we/CrimsonEditor | 67302aa4c9e0729ea61fe76bf341f5cb1888efac | 7e75573c51813364b38b4739fe3243275d9be06f | refs/heads/master | 2021-01-11T08:15:50.365898 | 2014-02-24T09:43:49 | 2014-02-24T09:43:49 | null | 0 | 0 | null | null | null | null | MacCentralEurope | C++ | false | false | 3,209 | h | ////////////////////////////////////////////////////////////////////////
// RegExp.h
//
// This code has been derived from work by Henry Spencer.
// The main changes are
// 1. All char variables and functions have been changed to TCHAR
// counterparts
// 2. Added GetFindLen() & GetReplaceString() to enable search
// and replace operations.
// 3. And of course, added the C++ Wrapper
//
// The original copyright notice follows:
//
// Copyright (c) 1986, 1993, 1995 by University of Toronto.
// Written by Henry Spencer. Not derived from licensed software.
//
// Permission is granted to anyone to use this software for any
// purpose on any computer system, and to redistribute it in any way,
// subject to the following restrictions:
//
// 1. The author is not responsible for the consequences of use of
// this software, no matter how awful, even if they arise
// from defects in it.
//
// 2. The origin of this software must not be misrepresented, either
// by explicit claim or by omission.
//
// 3. Altered versions must be plainly marked as such, and must not
// be misrepresented (by explicit claim or omission) as being
// the original software.
//
// 4. This notice must not be removed or altered.
/////////////////////////////////////////////////////////////////////////////
#ifndef __REGEXP_H_
#define __REGEXP_H_
#define NSUBEXP 10
class CRegExp
{
public:
CRegExp();
~CRegExp();
CRegExp * RegComp(const TCHAR * re);
int RegFind(const TCHAR * str);
TCHAR * GetReplaceString(const TCHAR * sReplaceExp);
int GetFoundLength();
BOOL GetFoundString(CString & szFoundString);
BOOL GetReplaceString(LPCTSTR lpszReplaceExp, CString & szReplaceString);
private:
TCHAR *regnext(TCHAR *node);
void reginsert(TCHAR op, TCHAR *opnd);
int regtry(TCHAR *string);
int regmatch(TCHAR *prog);
size_t regrepeat(TCHAR *node);
TCHAR *reg(int paren, int *flagp);
TCHAR *regbranch(int *flagp);
void regtail(TCHAR *p, TCHAR *val);
void regoptail(TCHAR *p, TCHAR *val);
TCHAR *regpiece(int *flagp);
TCHAR *regatom(int *flagp);
// Inline functions
private:
TCHAR OP(TCHAR *p) {return *p;};
TCHAR *OPERAND( TCHAR *p) {return (TCHAR*)((short *)(p+1)+1); };
// regc - emit (if appropriate) a byte of code
void regc(TCHAR b)
{
if (bEmitCode)
*regcode++ = b;
else
regsize++;
};
// regnode - emit a node
TCHAR * regnode(TCHAR op)
{
if (!bEmitCode) {
regsize += 3;
return regcode;
}
*regcode++ = op;
*regcode++ = _T('\0'); /* Null next pointer. */
*regcode++ = _T('\0');
return regcode-3;
};
private:
BOOL bEmitCode;
BOOL bCompiled;
TCHAR *sFoundText;
TCHAR *startp[NSUBEXP];
TCHAR *endp[NSUBEXP];
TCHAR regstart; // Internal use only.
TCHAR reganch; // Internal use only.
TCHAR *regmust; // Internal use only.
int regmlen; // Internal use only.
TCHAR *program; // Unwarranted chumminess with compiler.
TCHAR *regparse; // Input-scan pointer.
int regnpar; // () count.
TCHAR *regcode; // Code-emit pointer; ĘÁdummy = don't.
TCHAR regdummy[3]; // NOTHING, 0 next ptr
long regsize; // Code size.
TCHAR *reginput; // String-input pointer.
TCHAR *regbol; // Beginning of input, for ^ check.
};
#endif // __REGEXP_H_
| [
"[email protected]"
] | |
b15f22f7fa79c9a74b592de4eecb34de77301553 | da94c300d052a5bc9aaa9bff664f1f857f967af7 | /04_CountingElements/MaxCounters.cpp | 2e634c9e66fa9924e0a97eb15c01f43a4e9f7948 | [] | no_license | kurdybacha/codility | cbce2422f6bc7ee3daa7f11bd28637e6b23014d9 | e343d4fbfb53abcbc112c507e15c8efc2e96616b | refs/heads/master | 2021-01-21T23:54:08.183044 | 2016-01-07T00:53:09 | 2016-01-07T00:53:09 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 792 | cpp | #include <iostream>
#include <vector>
#include <algorithm>
std::vector<int> solution(int N, std::vector<int> &A)
{
std::vector<int> counters(N);
int max = 0;
int adjust = 0;
std::for_each(A.cbegin(), A.cend(), [&](const int &a) {
if (a <= N) {
counters[a-1] = std::max(counters[a-1], adjust) + 1;
max = std::max(max, counters[a-1]);
} else {
adjust = max;
}
});
std::for_each(counters.begin(), counters.end(), [&adjust](int &c) {
c = std::max(c, adjust);
});
return counters;
}
int main()
{
std::vector<int> data = {3, 4, 4, 6, 1, 4, 4};
std::vector<int> result = solution(5, data);
for (const auto& i : result)
std::cout << i << " ";
std::cout << "\n";
}
| [
"[email protected]"
] | |
0a69efbf6a548a353fefdebedcdf17d30f4aaabb | 3b7f0c1c6bd86d3544ad452071e141b5178d4ab7 | /src/events/gameevent_manager.h | 7ac5beea634466901e77e88a3469c9899f9ce879 | [] | no_license | Ktwu/gcs-sun-magic | 30b250269bf2930d8c9ccb48befa728becec2ad3 | 2455ae546a9a9329108f54d4febc9f1099d05c6b | refs/heads/master | 2020-04-06T07:11:31.944463 | 2012-12-21T12:20:31 | 2012-12-21T12:20:31 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 594 | h | #pragma once
#include "stdafx.h"
#include "events/gameevent.h"
#include "states/machine_state.h"
namespace sun_magic {
class GameEventManager {
public:
GameEventManager();
~GameEventManager();
static GameEventManager* GetInstance();
bool Set(GameEvent event, bool did_occur);
bool Get(GameEvent event);
int NumOverlap(std::set<GameEvent> events);
bool AreAllTrue(std::set<GameEvent> events);
bool AreAllFalse(std::set<GameEvent> events);
bool& operator [](GameEvent event);
private:
static GameEventManager* instance_;
bool events_[GameEvent::NUM_EVENTS];
};
} | [
"[email protected]"
] | |
52c5f6f6f282598853a367402144c3b09e7f0a58 | 98b1e51f55fe389379b0db00365402359309186a | /homework_6/problem_2/100x100/0.41/U | 81358073e05644e6173fd814d20c13adad69de4c | [] | no_license | taddyb/597-009 | f14c0e75a03ae2fd741905c4c0bc92440d10adda | 5f67e7d3910e3ec115fb3f3dc89a21dcc9a1b927 | refs/heads/main | 2023-01-23T08:14:47.028429 | 2020-12-03T13:24:27 | 2020-12-03T13:24:27 | 311,713,551 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,146 | /*--------------------------------*- C++ -*----------------------------------*\
========= |
\\ / F ield | OpenFOAM: The Open Source CFD Toolbox
\\ / O peration | Website: https://openfoam.org
\\ / A nd | Version: 8
\\/ M anipulation |
\*---------------------------------------------------------------------------*/
FoamFile
{
version 2.0;
format ascii;
class volVectorField;
location "0.41";
object U;
}
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
dimensions [0 1 -1 0 0 0 0];
internalField uniform (2 2 0);
boundaryField
{
left
{
type fixedValue;
value uniform (2 2 0);
}
right
{
type zeroGradient;
}
up
{
type zeroGradient;
}
down
{
type fixedValue;
value uniform (2 2 0);
}
frontAndBack
{
type empty;
}
}
// ************************************************************************* //
| [
"[email protected]"
] | ||
56c47c813b21e9133062001c2a00d78128f2f21c | c66b76f4f537c34e38b7645a9bd3eb6018aabfb8 | /compute_norm/plot.cpp | 0182b028e8fdab359982e629da3c19c8a557dc50 | [] | no_license | andrewcrabb/hrrt_reconstruction | 4a42ffb1e0dbc9e55c4c261b6e0bc9f3528f22da | 1a3f0e2fe2607b3860acfe8804932be4882a3581 | refs/heads/master | 2020-07-19T08:42:16.473462 | 2019-09-04T21:50:56 | 2019-09-04T21:50:56 | 206,412,167 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,344 | cpp | #include "norm_globals.h"
#include <stdio.h>
void plot(const char *basename, const float *y, int size, const char *title)
{
FILE *fp = fopen(basename, "wb");
if (fp != NULL)
{
if (title != NULL) fprintf(fp, "# %s\n", title);
for (int x=0; x<size; x++) fprintf(fp, "%d\t%g\n", x+1, y[x]);
fclose(fp);
}
}
void plot(const char *basename, const float *y, int count, int size, const char *title)
{
FILE *fp = fopen(basename, "wb");
if (fp != NULL)
{
if (title != NULL) fprintf(fp, "# %s\n", title);
for (int x=0; x<size; x++)
{
for (int i=0; i<count; i++)
fprintf(fp, "\t%g", y[i*size + x]);
fprintf(fp, "\n");
}
fclose(fp);
}
}
void plot(const char *basename, const float *x, const float *y, int size,
const char *title)
{
FILE *fp = fopen(basename, "wb");
if (fp != NULL)
{
if (title != NULL) fprintf(fp, "# %s\n", title);
for (int i=0; i<size; i++) fprintf(fp, "%g\t%g\n", x[i], y[i]);
fclose(fp);
}
}
void plot(const char *basename, const float *y1, const float *y2, int count, int size,
const char *title)
{
FILE *fp = fopen(basename, "wb");
if (fp != NULL)
{
if (title != NULL) fprintf(fp, "# %s\n", title);
for (int x=0; x<size; x++)
{
for (int i=0; i<count; i++)
fprintf(fp, "\t%g\t%g", y1[i*size + x], y2[i*size + x] );
fprintf(fp, "\n");
}
fclose(fp);
}
}
| [
"[email protected]"
] | |
9cfc2e5f519f900ac108dceb690853903c5c5399 | b7f3edb5b7c62174bed808079c3b21fb9ea51d52 | /third_party/openvr/src/src/vrcommon/vrpathregistry_public.cpp | 7b165286d5baa6632a4cda46dd7d10a2f921d3b9 | [
"LGPL-2.0-or-later",
"GPL-1.0-or-later",
"MIT",
"Apache-2.0",
"BSD-3-Clause"
] | permissive | otcshare/chromium-src | 26a7372773b53b236784c51677c566dc0ad839e4 | 64bee65c921db7e78e25d08f1e98da2668b57be5 | refs/heads/webml | 2023-03-21T03:20:15.377034 | 2020-11-16T01:40:14 | 2020-11-16T01:40:14 | 209,262,645 | 18 | 21 | BSD-3-Clause | 2023-03-23T06:20:07 | 2019-09-18T08:52:07 | null | UTF-8 | C++ | false | false | 11,528 | cpp | //========= Copyright Valve Corporation ============//
#include "vrpathregistry_public.h"
#include "json/json.h"
#include "pathtools_public.h"
#include "envvartools_public.h"
#include "strtools_public.h"
#include "dirtools_public.h"
#if defined( WIN32 )
#include <windows.h>
#include <shlobj.h>
#undef GetEnvironmentVariable
#elif defined OSX
#include <Foundation/Foundation.h>
#include <AppKit/AppKit.h>
#elif defined(LINUX)
#include <dlfcn.h>
#include <stdio.h>
#endif
#include <algorithm>
#ifndef VRLog
#undef VRLog
#endif
#define VRLog(...)
/** Returns the root of the directory the system wants us to store user config data in */
static std::string GetAppSettingsPath()
{
#if defined( WIN32 )
WCHAR rwchPath[MAX_PATH];
if( !SUCCEEDED( SHGetFolderPathW( NULL, CSIDL_LOCAL_APPDATA | CSIDL_FLAG_CREATE, NULL, 0, rwchPath ) ) )
{
return "";
}
// Convert the path to UTF-8 and store in the output
std::string sUserPath = UTF16to8( rwchPath );
return sUserPath;
#elif defined( OSX )
std::string sSettingsDir;
@autoreleasepool {
// Search for the path
NSArray *paths = NSSearchPathForDirectoriesInDomains( NSApplicationSupportDirectory, NSUserDomainMask, YES );
if ( [paths count] == 0 )
{
return "";
}
NSString *resolvedPath = [paths objectAtIndex:0];
resolvedPath = [resolvedPath stringByAppendingPathComponent: @"OpenVR"];
if ( ![[NSFileManager defaultManager] createDirectoryAtPath: resolvedPath withIntermediateDirectories:YES attributes:nil error:nil] )
{
return "";
}
sSettingsDir.assign( [resolvedPath UTF8String] );
}
return sSettingsDir;
#elif defined( LINUX )
// As defined by XDG Base Directory Specification
// https://specifications.freedesktop.org/basedir-spec/basedir-spec-latest.html
const char *pchHome = getenv("XDG_CONFIG_HOME");
if ( ( pchHome != NULL) && ( pchHome[0] != '\0' ) )
{
return pchHome;
}
//
// XDG_CONFIG_HOME is not defined, use ~/.config instead
//
pchHome = getenv( "HOME" );
if ( pchHome == NULL )
{
return "";
}
std::string sUserPath( pchHome );
sUserPath = Path_Join( sUserPath, ".config" );
return sUserPath;
#else
#warning "Unsupported platform"
#endif
}
// ---------------------------------------------------------------------------
// Purpose: Constructor
// ---------------------------------------------------------------------------
CVRPathRegistry_Public::CVRPathRegistry_Public()
{
}
// ---------------------------------------------------------------------------
// Purpose: Computes the registry filename
// ---------------------------------------------------------------------------
std::string CVRPathRegistry_Public::GetOpenVRConfigPath()
{
std::string sConfigPath = GetAppSettingsPath();
if( sConfigPath.empty() )
return "";
#if defined( _WIN32 ) || defined( LINUX )
sConfigPath = Path_Join( sConfigPath, "openvr" );
#elif defined ( OSX )
sConfigPath = Path_Join( sConfigPath, ".openvr" );
#else
#warning "Unsupported platform"
#endif
sConfigPath = Path_FixSlashes( sConfigPath );
return sConfigPath;
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
std::string CVRPathRegistry_Public::GetVRPathRegistryFilename()
{
std::string sOverridePath = GetEnvironmentVariable( "VR_PATHREG_OVERRIDE" );
if ( !sOverridePath.empty() )
return sOverridePath;
std::string sPath = GetOpenVRConfigPath();
if ( sPath.empty() )
return "";
#if defined( _WIN32 )
sPath = Path_Join( sPath, "openvrpaths.vrpath" );
#elif defined ( POSIX )
sPath = Path_Join( sPath, "openvrpaths.vrpath" );
#else
#error "Unsupported platform"
#endif
sPath = Path_FixSlashes( sPath );
return sPath;
}
// ---------------------------------------------------------------------------
// Purpose: Converts JSON to a history array
// ---------------------------------------------------------------------------
static void ParseStringListFromJson( std::vector< std::string > *pvecHistory, const Json::Value & root, const char *pchArrayName )
{
if( !root.isMember( pchArrayName ) )
return;
const Json::Value & arrayNode = root[ pchArrayName ];
if( !arrayNode )
{
VRLog( "VR Path Registry node %s is not an array\n", pchArrayName );
return;
}
pvecHistory->clear();
pvecHistory->reserve( arrayNode.size() );
for( uint32_t unIndex = 0; unIndex < arrayNode.size(); unIndex++ )
{
std::string sPath( arrayNode[ unIndex ].asString() );
pvecHistory->push_back( sPath );
}
}
// ---------------------------------------------------------------------------
// Purpose: Converts a history array to JSON
// ---------------------------------------------------------------------------
static void StringListToJson( const std::vector< std::string > & vecHistory, Json::Value & root, const char *pchArrayName )
{
Json::Value & arrayNode = root[ pchArrayName ];
for( auto i = vecHistory.begin(); i != vecHistory.end(); i++ )
{
arrayNode.append( *i );
}
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
bool CVRPathRegistry_Public::ToJsonString( std::string &sJsonString )
{
std::string sRegPath = GetVRPathRegistryFilename();
if( sRegPath.empty() )
return false;
std::string sRegistryContents = Path_ReadTextFile( sRegPath );
if( sRegistryContents.empty() )
return false;
sJsonString = sRegistryContents;
return true;
}
// ---------------------------------------------------------------------------
// Purpose: Loads the config file from its well known location
// ---------------------------------------------------------------------------
bool CVRPathRegistry_Public::BLoadFromFile()
{
std::string sRegPath = GetVRPathRegistryFilename();
if( sRegPath.empty() )
{
VRLog( "Unable to determine VR Path Registry filename\n" );
return false;
}
std::string sRegistryContents = Path_ReadTextFile( sRegPath );
if( sRegistryContents.empty() )
{
VRLog( "Unable to read VR Path Registry from %s\n", sRegPath.c_str() );
return false;
}
Json::Value root;
Json::Reader reader;
#if JSON_USE_EXCEPTION
try {
#endif // JSON_USE_EXCEPTION
if ( !reader.parse( sRegistryContents, root ) )
{
VRLog( "Unable to parse %s: %s\n", sRegPath.c_str(), reader.getFormattedErrorMessages().c_str() );
return false;
}
ParseStringListFromJson( &m_vecRuntimePath, root, "runtime" );
ParseStringListFromJson( &m_vecConfigPath, root, "config" );
ParseStringListFromJson( &m_vecLogPath, root, "log" );
if ( root.isMember( "external_drivers" ) && root["external_drivers"].isArray() )
{
ParseStringListFromJson( &m_vecExternalDrivers, root, "external_drivers" );
}
#if JSON_USE_EXCEPTION
}
catch ( ... )
{
VRLog( "Unable to parse %s: %s\n", sRegPath.c_str(), "exception thrown in JSON library" );
return false;
}
#endif // JSON_USE_EXCEPTION
return true;
}
// ---------------------------------------------------------------------------
// Purpose: Saves the config file to its well known location
// ---------------------------------------------------------------------------
bool CVRPathRegistry_Public::BSaveToFile() const
{
#if defined( DASHBOARD_BUILD_MODE )
return false;
#else
std::string sRegPath = GetVRPathRegistryFilename();
if( sRegPath.empty() )
return false;
Json::Value root;
root[ "version" ] = 1;
root[ "jsonid" ] = "vrpathreg";
StringListToJson( m_vecRuntimePath, root, "runtime" );
StringListToJson( m_vecConfigPath, root, "config" );
StringListToJson( m_vecLogPath, root, "log" );
StringListToJson( m_vecExternalDrivers, root, "external_drivers" );
Json::StyledWriter writer;
std::string sRegistryContents = writer.write( root );
// make sure the directory we're writing into actually exists
std::string sRegDirectory = Path_StripFilename( sRegPath );
if( !BCreateDirectoryRecursive( sRegDirectory.c_str() ) )
{
VRLog( "Unable to create path registry directory %s\n", sRegDirectory.c_str() );
return false;
}
if( !Path_WriteStringToTextFile( sRegPath, sRegistryContents.c_str() ) )
{
VRLog( "Unable to write VR path registry to %s\n", sRegPath.c_str() );
return false;
}
return true;
#endif
}
// ---------------------------------------------------------------------------
// Purpose: Returns the current runtime path or NULL if no path is configured.
// ---------------------------------------------------------------------------
std::string CVRPathRegistry_Public::GetRuntimePath() const
{
if( m_vecRuntimePath.empty() )
return "";
else
return m_vecRuntimePath.front().c_str();
}
// ---------------------------------------------------------------------------
// Purpose: Returns the current config path or NULL if no path is configured.
// ---------------------------------------------------------------------------
std::string CVRPathRegistry_Public::GetConfigPath() const
{
if( m_vecConfigPath.empty() )
return "";
else
return m_vecConfigPath.front().c_str();
}
// ---------------------------------------------------------------------------
// Purpose: Returns the current log path or NULL if no path is configured.
// ---------------------------------------------------------------------------
std::string CVRPathRegistry_Public::GetLogPath() const
{
if( m_vecLogPath.empty() )
return "";
else
return m_vecLogPath.front().c_str();
}
// ---------------------------------------------------------------------------
// Purpose: Returns paths using the path registry and the provided override
// values. Pass NULL for any paths you don't care about.
// ---------------------------------------------------------------------------
bool CVRPathRegistry_Public::GetPaths( std::string *psRuntimePath, std::string *psConfigPath, std::string *psLogPath, const char *pchConfigPathOverride, const char *pchLogPathOverride, std::vector<std::string> *pvecExternalDrivers )
{
CVRPathRegistry_Public pathReg;
bool bLoadedRegistry = pathReg.BLoadFromFile();
int nCountEnvironmentVariables = 0;
if( psRuntimePath )
{
if ( GetEnvironmentVariable( k_pchRuntimeOverrideVar ).length() != 0 )
{
*psRuntimePath = GetEnvironmentVariable( k_pchRuntimeOverrideVar );
nCountEnvironmentVariables++;
}
else if( !pathReg.GetRuntimePath().empty() )
{
*psRuntimePath = pathReg.GetRuntimePath();
}
else
{
*psRuntimePath = "";
}
}
if( psConfigPath )
{
if ( GetEnvironmentVariable( k_pchConfigOverrideVar ).length() != 0 )
{
*psConfigPath = GetEnvironmentVariable( k_pchConfigOverrideVar );
nCountEnvironmentVariables++;
}
else if( pchConfigPathOverride )
{
*psConfigPath = pchConfigPathOverride;
}
else if( !pathReg.GetConfigPath().empty() )
{
*psConfigPath = pathReg.GetConfigPath();
}
else
{
*psConfigPath = "";
}
}
if( psLogPath )
{
if ( GetEnvironmentVariable( k_pchLogOverrideVar ).length() != 0 )
{
*psLogPath = GetEnvironmentVariable( k_pchLogOverrideVar );
nCountEnvironmentVariables++;
}
else if( pchLogPathOverride )
{
*psLogPath = pchLogPathOverride;
}
else if( !pathReg.GetLogPath().empty() )
{
*psLogPath = pathReg.GetLogPath();
}
else
{
*psLogPath = "";
}
}
if ( pvecExternalDrivers )
{
*pvecExternalDrivers = pathReg.m_vecExternalDrivers;
}
if ( nCountEnvironmentVariables == 3 )
{
// all three environment variables were set, so we don't need the physical file
return true;
}
return bLoadedRegistry;
}
| [
"[email protected]"
] | |
741dea76218d688f5e47ece6210f120d5f98466d | 4f610a7615cc28364b5eefb965a2685d117dceca | /fileManager/analyze_execute_command/analizeexecutecommandinfo.h | a5139c5ab4036d8943e203ca1f05dfb9fe56fb5c | [] | no_license | Alexcei88/Client-GixAnnex | e1aaff49e9ec3064a3115a826fde5755b6e29921 | d71002fdc9a5c0df60a84e2c90af254f9d4a3351 | refs/heads/master | 2021-01-22T13:57:49.357485 | 2014-04-23T17:55:18 | 2014-04-23T17:55:18 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 504 | h | #ifndef ANALIZEEXECUTECOMMANDInfo_H
#define ANALIZEEXECUTECOMMANDInfo_H
#include "analyzeexecutecommand.h"
#include <QVariantMap>
namespace AnalyzeCommand
{
class FacadeAnalyzeCommand;
class AnalizeExecuteCommandInfo : public AnalyzeExecuteCommand
{
public:
AnalizeExecuteCommandInfo(FacadeAnalyzeCommand& facadeAnalizeCommand);
void SetInfoRepository(const QVariantMap& values);
void WasErrorGetInfoRepository();
};
}
#endif // ANALIZEEXECUTECOMMANDInfo_H
| [
"[email protected]"
] | |
c3b869fb38aefd2c04f02eb558e6ef9a017d31d5 | 09fc85cd58c0ed10e8ad780a5b19e3c0fcde667d | /src/centurion/video/color.hpp | ae0142ae4309d2728bf3fcda2aa04a470773306c | [
"MIT"
] | permissive | Watch-Later/centurion | 40edb7c359c7bb1f4f8f7f819180166a2e033923 | cc71543b6a07b4fb1f9cb24e1f39ac852bc66a3b | refs/heads/main | 2023-06-04T07:45:48.814126 | 2021-05-26T09:47:15 | 2021-05-26T09:47:15 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 16,896 | hpp | #ifndef CENTURION_COLOR_HEADER
#define CENTURION_COLOR_HEADER
#include <SDL.h>
#include <cassert> // assert
#include <cmath> // round, fabs, fmod
#include <ostream> // ostream
#include <string> // string
#include "../core/integers.hpp"
#include "../detail/to_string.hpp"
namespace cen {
/// \addtogroup video
/// \{
/**
* \class color
*
* \brief An 8-bit accuracy RGBA color.
*
* \details This class is designed to interact with the SDL colors, i.e. `SDL_Color` and
* `SDL_MessageBoxColor`. For convenience, there are approximately 140 color constants
* provided in the `cen::colors` namespace,
*
* \since 3.0.0
*/
class color final
{
public:
/// \name Construction
/// \{
/**
* \brief Creates a color. The created color will be equal to #000000FF.
*
* \since 3.0.0
*/
constexpr color() noexcept = default;
/**
* \brief Creates a color.
*
* \param red the red component value, in the range [0, 255].
* \param green the green component value, in the range [0, 255].
* \param blue the blue component value, in the range [0, 255].
* \param alpha the alpha component value, in the rage [0, 255]. Defaults to 255.
*
* \since 3.0.0
*/
constexpr color(const u8 red,
const u8 green,
const u8 blue,
const u8 alpha = max()) noexcept
: m_color{red, green, blue, alpha}
{}
/**
* \brief Creates a color that is a copy of the supplied `SDL_Color`.
*
* \param color the `SDL_Color` that will be copied.
*
* \since 3.0.0
*/
constexpr explicit color(const SDL_Color& color) noexcept : m_color{color}
{}
/**
* \brief Creates a color that is a copy of the supplied SDL_MessageBoxColor.
*
* \details Message box colors don't have an alpha component so the created color will
* feature an alpha value of 255.
*
* \param color the message box color that will be copied.
*
* \since 3.0.0
*/
constexpr explicit color(const SDL_MessageBoxColor& color) noexcept
: m_color{color.r, color.g, color.b, max()}
{}
/**
* \brief Creates a color from HSV-encoded values.
*
* \pre `hue` must be in the range [0, 360].
* \pre `saturation` must be in the range [0, 100].
* \pre `value` must be in the range [0, 100].
*
* \param hue the hue of the color, in the range [0, 360].
* \param saturation the saturation of the color, in the range [0, 100].
* \param value the value of the color, in the range [0, 100].
*
* \return an RGBA color converted from the HSV values.
*
* \since 5.3.0
*/
[[nodiscard]] static auto from_hsv(const double hue,
const double saturation,
const double value) -> color
{
assert(hue >= 0);
assert(hue <= 360);
assert(saturation >= 0);
assert(saturation <= 100);
assert(value >= 0);
assert(value <= 100);
const auto v = (value / 100.0);
const auto chroma = v * (saturation / 100.0);
const auto hp = hue / 60.0;
const auto x = chroma * (1.0 - std::fabs(std::fmod(hp, 2.0) - 1.0));
double red{};
double green{};
double blue{};
if (0 <= hp && hp <= 1)
{
red = chroma;
green = x;
blue = 0;
}
else if (1 < hp && hp <= 2)
{
red = x;
green = chroma;
blue = 0.0;
}
else if (2 < hp && hp <= 3)
{
red = 0;
green = chroma;
blue = x;
}
else if (3 < hp && hp <= 4)
{
red = 0;
green = x;
blue = chroma;
}
else if (4 < hp && hp <= 5)
{
red = x;
green = 0;
blue = chroma;
}
else if (5 < hp && hp <= 6)
{
red = chroma;
green = 0;
blue = x;
}
const auto m = v - chroma;
const auto r = static_cast<u8>(std::round((red + m) * 255.0));
const auto g = static_cast<u8>(std::round((green + m) * 255.0));
const auto b = static_cast<u8>(std::round((blue + m) * 255.0));
return color{r, g, b};
}
/**
* \brief Creates a color from HSL-encoded values.
*
* \pre `hue` must be in the range [0, 360].
* \pre `saturation` must be in the range [0, 100].
* \pre `lightness` must be in the range [0, 100].
*
* \param hue the hue of the color, in the range [0, 360].
* \param saturation the saturation of the color, in the range [0, 100].
* \param lightness the lightness of the color, in the range [0, 100].
*
* \return an RGBA color converted from the HSL values.
*
* \since 5.3.0
*/
[[nodiscard]] static auto from_hsl(const double hue,
const double saturation,
const double lightness) -> color
{
assert(hue >= 0);
assert(hue <= 360);
assert(saturation >= 0);
assert(saturation <= 100);
assert(lightness >= 0);
assert(lightness <= 100);
const auto s = saturation / 100.0;
const auto l = lightness / 100.0;
const auto chroma = (1.0 - std::fabs(2.0 * l - 1)) * s;
const auto hp = hue / 60.0;
const auto x = chroma * (1 - std::fabs(std::fmod(hp, 2.0) - 1.0));
double red{};
double green{};
double blue{};
if (0 <= hp && hp < 1)
{
red = chroma;
green = x;
blue = 0;
}
else if (1 <= hp && hp < 2)
{
red = x;
green = chroma;
blue = 0;
}
else if (2 <= hp && hp < 3)
{
red = 0;
green = chroma;
blue = x;
}
else if (3 <= hp && hp < 4)
{
red = 0;
green = x;
blue = chroma;
}
else if (4 <= hp && hp < 5)
{
red = x;
green = 0;
blue = chroma;
}
else if (5 <= hp && hp < 6)
{
red = chroma;
green = 0;
blue = x;
}
const auto m = l - (chroma / 2.0);
const auto r = static_cast<u8>(std::round((red + m) * 255.0));
const auto g = static_cast<u8>(std::round((green + m) * 255.0));
const auto b = static_cast<u8>(std::round((blue + m) * 255.0));
return color{r, g, b};
}
/// \} End of construction
/// \name Setters
/// \{
/**
* \brief Sets the value of the red component.
*
* \param red the new value of the red component.
*
* \since 3.0.0
*/
constexpr void set_red(const u8 red) noexcept
{
m_color.r = red;
}
/**
* \brief Sets the value of the green component.
*
* \param green the new value of the green component.
*
* \since 3.0.0
*/
constexpr void set_green(const u8 green) noexcept
{
m_color.g = green;
}
/**
* \brief Sets the value of the blue component.
*
* \param blue the new value of the blue component.
*
* \since 3.0.0
*/
constexpr void set_blue(const u8 blue) noexcept
{
m_color.b = blue;
}
/**
* \brief Sets the value of the alpha component.
*
* \param alpha the new value of the alpha component.
*
* \since 3.0.0
*/
constexpr void set_alpha(const u8 alpha) noexcept
{
m_color.a = alpha;
}
/// \} End of setters
/// \name Getters
/// \{
/**
* \brief Returns the value of the red component.
*
* \return the value of the red component, in the range [0, 255].
*
* \since 3.0.0
*/
[[nodiscard]] constexpr auto red() const noexcept -> u8
{
return m_color.r;
}
/**
* \brief Returns the value of the green component.
*
* \return the value of the green component, in the range [0, 255].
*
* \since 3.0.0
*/
[[nodiscard]] constexpr auto green() const noexcept -> u8
{
return m_color.g;
}
/**
* \brief Returns the value of the blue component.
*
* \return the value of the blue component, in the range [0, 255].
*
* \since 3.0.0
*/
[[nodiscard]] constexpr auto blue() const noexcept -> u8
{
return m_color.b;
}
/**
* \brief Returns the value of the alpha component.
*
* \return the value of the alpha component, in the range [0, 255].
*
* \since 3.0.0
*/
[[nodiscard]] constexpr auto alpha() const noexcept -> u8
{
return m_color.a;
}
/**
* \brief Returns a pointer to the internal SDL color.
*
* \warning Do not cache the returned pointer!
*
* \return a pointer to the internal color instance.
*
* \since 6.0.0
*/
[[nodiscard]] auto data() noexcept -> SDL_Color*
{
return &m_color;
}
/// \copydoc data()
[[nodiscard]] auto data() const noexcept -> const SDL_Color*
{
return &m_color;
}
/**
* \brief Returns the internal color instance.
*
* \return a reference to the internal color.
*
* \since 5.0.0
*/
[[nodiscard]] auto get() const noexcept -> const SDL_Color&
{
return m_color;
}
/// \} End of getters
/// \name Conversions
/// \{
/**
* \brief Converts the the color into an `SDL_Color`.
*
* \return an `SDL_Color` that is equivalent to this color.
*
* \since 3.0.0
*/
[[nodiscard]] explicit constexpr operator SDL_Color() const noexcept
{
return {red(), green(), blue(), alpha()};
}
/**
* \brief Converts the the color into an `SDL_MessageBoxColor`.
*
* \note Message box colors don't feature an alpha value!
*
* \return an `SDL_MessageBoxColor` that is equivalent to this color.
*
* \since 3.0.0
*/
[[nodiscard]] explicit constexpr operator SDL_MessageBoxColor() const noexcept
{
return {red(), green(), blue()};
}
/**
* \brief Converts the color to `SDL_Color*`.
*
* \warning The returned pointer is not to be freed or stored away!
*
* \return a pointer to the internal color instance.
*
* \since 4.0,0
*/
[[nodiscard]] explicit operator SDL_Color*() noexcept
{
return &m_color;
}
/**
* \brief Converts the color to `const SDL_Color*`.
*
* \warning The returned pointer is not to be freed or stored away!
*
* \return a pointer to the internal color instance.
*
* \since 4.0,0
*/
[[nodiscard]] explicit operator const SDL_Color*() const noexcept
{
return &m_color;
}
/// \} End of conversions
/**
* \brief Serializes the color.
*
* \details This function expects that the archive provides an overloaded `operator()`,
* used for serializing data. This API is based on the Cereal serialization library.
*
* \tparam Archive the type of the archive.
*
* \param archive the archive used to serialize the color.
*
* \since 5.3.0
*/
template <typename Archive>
void serialize(Archive& archive)
{
archive(m_color.r, m_color.g, m_color.b, m_color.a);
}
/**
* \brief Returns a copy of the color with the specified alpha value.
*
* \param alpha the alpha component value that will be used by the new color.
*
* \return a color that is identical to the color except for the alpha component.
*
* \since 5.0.0
*/
[[nodiscard]] constexpr auto with_alpha(const u8 alpha) const noexcept -> color
{
return {red(), green(), blue(), alpha};
}
/**
* \brief Returns the maximum possible value of a color component.
*
* \return the maximum possible value of a color component.
*
* \since 5.0.0
*/
[[nodiscard]] constexpr static auto max() noexcept -> u8
{
return 0xFF;
}
private:
SDL_Color m_color{0, 0, 0, max()};
};
/**
* \brief Returns a textual representation of the color.
*
* \param color the color that will be converted.
*
* \return a textual representation of the color.
*
* \since 5.0.0
*/
[[nodiscard]] inline auto to_string(const color& color) -> std::string
{
return "color{r: " + detail::to_string(color.red()).value() +
", g: " + detail::to_string(color.green()).value() +
", b: " + detail::to_string(color.blue()).value() +
", a: " + detail::to_string(color.alpha()).value() + "}";
}
/**
* \brief Prints a textual representation of a color.
*
* \param stream the stream that will be used.
* \param color the color that will be printed.
*
* \return the used stream.
*
* \since 5.0.0
*/
inline auto operator<<(std::ostream& stream, const color& color) -> std::ostream&
{
return stream << to_string(color);
}
/**
* \brief Blends two colors according to the specified bias.
*
* \pre `bias` should be in the range [0, 1].
*
* \details This function applies a linear interpolation for each color component to
* obtain the blended color. The bias parameter is the "alpha" for the interpolation,
* which determines how the input colors are blended. For example, a bias of 0 or 1 will
* simply result in the first or second color being returned, respectively.
* Subsequently, a bias of 0.5 will blend the two colors evenly.
*
* \param a the first color.
* \param b the second color.
* \param bias the bias that determines how the colors are blended, in the range [0, 1].
*
* \return a color obtained by blending the two supplied colors.
*
* \since 6.0.0
*/
[[nodiscard]] inline auto blend(const color& a, const color& b, const double bias = 0.5)
-> color
{
assert(bias >= 0);
assert(bias <= 1.0);
const auto invBias = 1.0 - bias;
const auto red = (a.red() * invBias) + (b.red() * bias);
const auto green = (a.green() * invBias) + (b.green() * bias);
const auto blue = (a.blue() * invBias) + (b.blue() * bias);
const auto alpha = (a.alpha() * invBias) + (b.alpha() * bias);
return color{static_cast<u8>(std::round(red)),
static_cast<u8>(std::round(green)),
static_cast<u8>(std::round(blue)),
static_cast<u8>(std::round(alpha))};
}
/// \name Color comparison operators
/// \{
/**
* \brief Indicates whether or not the two colors are equal.
*
* \param lhs the left-hand side color.
* \param rhs the right-hand side color.
*
* \return `true` if the colors are equal; `false` otherwise.
*
* \since 3.0.0
*/
[[nodiscard]] constexpr auto operator==(const color& lhs, const color& rhs) noexcept
-> bool
{
return (lhs.red() == rhs.red()) && (lhs.green() == rhs.green()) &&
(lhs.blue() == rhs.blue()) && (lhs.alpha() == rhs.alpha());
}
/// \copydoc operator==(const color&, const color&)
[[nodiscard]] constexpr auto operator==(const color& lhs, const SDL_Color& rhs) noexcept
-> bool
{
return (lhs.red() == rhs.r) && (lhs.green() == rhs.g) && (lhs.blue() == rhs.b) &&
(lhs.alpha() == rhs.a);
}
/// \copydoc operator==(const color&, const color&)
[[nodiscard]] constexpr auto operator==(const SDL_Color& lhs, const color& rhs) noexcept
-> bool
{
return rhs == lhs;
}
/**
* \copybrief operator==(const color&, const color&)
*
* \note The alpha components are not taken into account.
*
* \param lhs the left-hand side color.
* \param rhs the right-hand side color.
*
* \return `true` if the colors are equal; `false` otherwise.
*
* \since 3.0.0
*/
[[nodiscard]] constexpr auto operator==(const color& lhs,
const SDL_MessageBoxColor& rhs) noexcept -> bool
{
return (lhs.red() == rhs.r) && (lhs.green() == rhs.g) && (lhs.blue() == rhs.b);
}
/// \copydoc operator==(const color&, const SDL_MessageBoxColor&)
[[nodiscard]] constexpr auto operator==(const SDL_MessageBoxColor& lhs,
const color& rhs) noexcept -> bool
{
return rhs == lhs;
}
/**
* \brief Indicates whether or not the two colors aren't equal.
*
* \param lhs the left-hand side color.
* \param rhs the right-hand side color.
*
* \return `true` if the colors aren't equal; `false` otherwise.
*
* \since 3.0.0
*/
[[nodiscard]] constexpr auto operator!=(const color& lhs, const color& rhs) noexcept
-> bool
{
return !(lhs == rhs);
}
/// \copydoc operator!=(const color&, const color&)
[[nodiscard]] constexpr auto operator!=(const color& lhs, const SDL_Color& rhs) noexcept
-> bool
{
return !(lhs == rhs);
}
/// \copydoc operator!=(const color&, const color&)
[[nodiscard]] constexpr auto operator!=(const SDL_Color& lhs, const color& rhs) noexcept
-> bool
{
return !(lhs == rhs);
}
/**
* \copybrief operator!=(const color&, const color&)
*
* \note The alpha components are not taken into account.
*
* \param lhs the left-hand side color.
* \param rhs the right-hand side color.
*
* \return `true` if the colors aren't equal; `false` otherwise.
*
* \since 3.0.0
*/
[[nodiscard]] constexpr auto operator!=(const color& lhs,
const SDL_MessageBoxColor& rhs) noexcept -> bool
{
return !(lhs == rhs);
}
/// \copydoc operator!=(const color&, const SDL_MessageBoxColor&)
[[nodiscard]] constexpr auto operator!=(const SDL_MessageBoxColor& lhs,
const color& rhs) noexcept -> bool
{
return !(lhs == rhs);
}
/// \} End of color comparison operators
/// \} End of group video
} // namespace cen
#endif // CENTURION_COLOR_HEADER
| [
"[email protected]"
] | |
de3bce94deb3df0d6608e3df2e4791aa8003eb95 | 48da3cf76d6932e643824e8538bfad5529cf335a | /trunk/chat_server/local_time/local_time_manager.hpp | dd24d057d46a42c4b0c94769a86e6cd1692cba4f | [] | no_license | daxingyou/sg_server | 932c84317210f7096b97f06c837e9e15e73809bd | 2bd0a812f0baeb31dc09192d0e88d47fde916a2b | refs/heads/master | 2021-09-19T16:01:37.630704 | 2018-07-28T09:27:09 | 2018-07-28T09:27:09 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 438 | hpp | #ifndef __GAME_LOCAL_TIME_MANAGER_H__
#define __GAME_LOCAL_TIME_MANAGER_H__
#include <boost/date_time/posix_time/posix_time.hpp>
#include <boost/locale/date_time.hpp>
class local_time_manager_t
{
public:
static uint64_t get_loacl_seconds();
static uint64_t get_loacl_microseconds();
static boost::posix_time::ptime get_loacl_day_time(uint32_t hour = 0, uint32_t minutes = 0);
};
#endif // !__GAME_LOCAL_TIME_MANAGER_H__ | [
"major@fun2"
] | major@fun2 |
1ddf2704ba6f46f2cc17e44c88aa962dd795f24d | c92dd32d138fcbd1890a2cd5d7308ec6fea35ef1 | /BitEngine/BitEngine-Core/src/maths/vec3.cpp | a8a122195e3b485e62f476310e33f3877000600d | [] | no_license | MadlyTV/BitEngine | f5b52dbec8b73c14d153ed99472bc839080f8df5 | 922abaa345a243e35ffc0a90c2762a6f85e820dd | refs/heads/master | 2021-04-03T08:35:42.243692 | 2018-03-14T10:50:00 | 2018-03-14T10:50:00 | 61,152,475 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,306 | cpp | #include "vec3.h"
namespace BitEngine { namespace maths {
vec3::vec3()
: x(0.0f), y(0.0f), z(0.0f)
{
}
vec3::vec3(const float& x, const float& y, const float& z)
: x(x), y(y), z(z)
{
}
vec3::vec3(const vec2& vector)
: x(vector.x), y(vector.y), z(0.0f)
{
}
vec3& vec3::add(const vec3& other) {
x += other.x;
y += other.y;
z += other.z;
return *this;
}
vec3& vec3::subtract(const vec3& other) {
x -= other.x;
y -= other.y;
z -= other.z;
return *this;
}
vec3& vec3::multiply(const vec3& other) {
x *= other.x;
y *= other.y;
z *= other.z;
return *this;
}
vec3& vec3::devide(const vec3& other) {
x /= other.x;
y /= other.y;
z /= other.z;
return *this;
}
vec3& vec3::add(float other) {
x += other;
y += other;
z += other;
return *this;
}
vec3& vec3::subtract(float other) {
x -= other;
y -= other;
z -= other;
return *this;
}
vec3& vec3::multiply(float other) {
x *= other;
y *= other;
z *= other;
return *this;
}
vec3& vec3::devide(float other) {
x /= other;
y /= other;
z /= other;
return *this;
}
vec3 operator+(vec3 left, const vec3& right) {
return left.add(right);
}
vec3 operator-(vec3 left, const vec3& right) {
return left.subtract(right);
}
vec3 operator*(vec3 left, const vec3& right) {
return left.multiply(right);
}
vec3 operator/(vec3 left, const vec3& right) {
return left.devide(right);
}
vec3 operator+(vec3 left, float right) {
return left.add(right);
}
vec3 operator-(vec3 left, float right) {
return left.subtract(right);
}
vec3 operator*(vec3 left, float right) {
return left.multiply(right);
}
vec3 operator/(vec3 left, float right) {
return left.devide(right);
}
vec3& vec3::operator+=(const vec3& other) {
return add(other);
}
vec3& vec3::operator-=(const vec3& other) {
return subtract(other);
}
vec3& vec3::operator*=(const vec3& other) {
return multiply(other);
}
vec3& vec3::operator/=(const vec3& other) {
return devide(other);
}
vec3& vec3::operator+=(const vec2& other) {
return add(vec3(other));
}
vec3& vec3::operator-=(const vec2& other) {
return subtract(vec3(other));
}
vec3& vec3::operator*=(const vec2& other) {
return multiply(vec3(other));
}
vec3& vec3::operator/=(const vec2& other) {
return devide(vec3(other));
}
bool vec3::operator==(const vec3& other) const{
return x == other.x && y == other.y && z == other.z;
}
bool vec3::operator!=(const vec3& other) const{
return !(*this == other);
}
bool vec3::operator<(const vec3& other) const {
return x < other.x && y < other.y && z < other.z;
}
bool vec3::operator<=(const vec3& other) const {
return x <= other.x && y <= other.y && z <= other.z;
}
bool vec3::operator>(const vec3& other) const {
return x > other.x && y > other.y && z > other.z;
}
bool vec3::operator>=(const vec3& other) const {
return x >= other.x && y >= other.y && z >= other.z;
}
float vec3::Distance(const vec3& other) const
{
float a = x - other.x;
float b = y - other.y;
float c = z - other.z;
return sqrt(a * a + b * b + c * c);
}
std::ostream& operator<<(std::ostream stream, const vec3& vector) {
stream << "vec3: (" << vector.x << ", " << vector.y << ", " << vector.z << ")";
return stream;
}
} } | [
"[email protected]"
] | |
a379d12e83d226e53847504027cff32f01a87c78 | 88881f70bbb9ff42970796a8ec89c82e666d55bc | /CodeChefLunchMay20/CONVSTR.cpp | dc04b43e4728360982a12777df66192293311b3b | [] | no_license | uhini0201/CodeChefChallenges | e7f7c5e7e036ca3cf84ea04d23931b79819371a3 | 21d270675a7fb10cbc929ffddccdb5f960e1c073 | refs/heads/master | 2023-02-01T09:00:33.105552 | 2020-12-14T10:19:07 | 2020-12-14T10:19:07 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,770 | cpp | // Problem Link: https://www.codechef.com/LTIME84B/problems/CONVSTR
#include <bits/stdc++.h>
#include <unordered_map>
using namespace std;
#define whatis(x) cerr << #x << " is : " << x <<endl;
typedef long long ll;
typedef unsigned long long ull;
int main(){
int t;
cin >> t;
while(t--){
int n;
cin >> n;
int ca[26] = {0};
string a,b;
cin >> a >> b;
for(int i=0; i<n; i++){
ca[a[i] - 'a'] = 1;
}
bool flag = false;
for(int i=0; i<n; i++){
if(a[i] < b[i])
flag = true;
}
for(int i=0; i<n; i++){
if(!ca[b[i]-'a'])
flag = true;
}
if(flag){
cout << -1 << endl;
}else{
vector< vector<int> > ans;
for(char c='z'; c >='a'; c--){
vector<int> v;
for(int i=0; i<n; i++){
if(a[i] != c and b[i] == c)
v.push_back(i);
}
if(!v.empty()){
for(int i=0; i<n; i++){
if(a[i] == c){
v.push_back(i);
break;
}
}
}
if(!v.empty())
ans.push_back(v);
for(int i=0; i<v.size(); i++){
a[v[i]] = c;
}
}
cout << ans.size() << endl;
for(int i=0; i<ans.size(); i++){
cout << ans[i].size() << " ";
for(int &x : ans[i])
cout << x << " ";
cout << endl;
}
}
}
return 0;
} | [
"[email protected]"
] | |
35b3ada7b7f065766afa0cbb4913cd1a9d5abc21 | 5a63bd6870346aa6593233b990303e743cdb8861 | /SDK/BP_WeaponBase_functions.cpp | 34e92e2bb3fbc7fc3cdec133eee7411906bdd20f | [] | no_license | zH4x-SDK/zBlazingSails-SDK | dc486c4893a8aa14f760bdeff51cea11ff1838b5 | 5e6d42df14ac57fb934ec0dabbca88d495db46dd | refs/heads/main | 2023-07-10T12:34:06.824910 | 2021-08-27T13:42:23 | 2021-08-27T13:42:23 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 9,288 | cpp |
#include "../SDK.h"
// Name: BS, Version: 1.536.0
#ifdef _MSC_VER
#pragma pack(push, 0x8)
#endif
namespace SDK
{
//---------------------------------------------------------------------------
// Functions
//---------------------------------------------------------------------------
// Function BP_WeaponBase.BP_WeaponBase_C.ApplyDamage
// (Public, BlueprintCallable, BlueprintEvent)
// Parameters:
// int damage (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, IsPlainOldData)
void ABP_WeaponBase_C::ApplyDamage(int damage)
{
static auto fn = UObject::FindObject<UFunction>("Function BP_WeaponBase.BP_WeaponBase_C.ApplyDamage");
ABP_WeaponBase_C_ApplyDamage_Params params;
params.damage = damage;
auto flags = fn->FunctionFlags;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
}
// Function BP_WeaponBase.BP_WeaponBase_C.OnRep_Holstered
// (BlueprintCallable, BlueprintEvent)
void ABP_WeaponBase_C::OnRep_Holstered()
{
static auto fn = UObject::FindObject<UFunction>("Function BP_WeaponBase.BP_WeaponBase_C.OnRep_Holstered");
ABP_WeaponBase_C_OnRep_Holstered_Params params;
auto flags = fn->FunctionFlags;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
}
// Function BP_WeaponBase.BP_WeaponBase_C.ResetTransform
// (Public, HasDefaults, BlueprintCallable, BlueprintEvent)
void ABP_WeaponBase_C::ResetTransform()
{
static auto fn = UObject::FindObject<UFunction>("Function BP_WeaponBase.BP_WeaponBase_C.ResetTransform");
ABP_WeaponBase_C_ResetTransform_Params params;
auto flags = fn->FunctionFlags;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
}
// Function BP_WeaponBase.BP_WeaponBase_C.SetCustomHolsterTransform
// (Public, HasDefaults, BlueprintCallable, BlueprintEvent)
void ABP_WeaponBase_C::SetCustomHolsterTransform()
{
static auto fn = UObject::FindObject<UFunction>("Function BP_WeaponBase.BP_WeaponBase_C.SetCustomHolsterTransform");
ABP_WeaponBase_C_SetCustomHolsterTransform_Params params;
auto flags = fn->FunctionFlags;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
}
// Function BP_WeaponBase.BP_WeaponBase_C.UserConstructionScript
// (Event, Public, BlueprintCallable, BlueprintEvent)
void ABP_WeaponBase_C::UserConstructionScript()
{
static auto fn = UObject::FindObject<UFunction>("Function BP_WeaponBase.BP_WeaponBase_C.UserConstructionScript");
ABP_WeaponBase_C_UserConstructionScript_Params params;
auto flags = fn->FunctionFlags;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
}
// Function BP_WeaponBase.BP_WeaponBase_C.ReceiveBeginPlay
// (Event, Protected, BlueprintEvent)
void ABP_WeaponBase_C::ReceiveBeginPlay()
{
static auto fn = UObject::FindObject<UFunction>("Function BP_WeaponBase.BP_WeaponBase_C.ReceiveBeginPlay");
ABP_WeaponBase_C_ReceiveBeginPlay_Params params;
auto flags = fn->FunctionFlags;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
}
// Function BP_WeaponBase.BP_WeaponBase_C.ReceiveTick
// (Event, Public, BlueprintEvent)
// Parameters:
// float DeltaSeconds (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, IsPlainOldData)
void ABP_WeaponBase_C::ReceiveTick(float DeltaSeconds)
{
static auto fn = UObject::FindObject<UFunction>("Function BP_WeaponBase.BP_WeaponBase_C.ReceiveTick");
ABP_WeaponBase_C_ReceiveTick_Params params;
params.DeltaSeconds = DeltaSeconds;
auto flags = fn->FunctionFlags;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
}
// Function BP_WeaponBase.BP_WeaponBase_C.MC_DamagedEffects
// (Net, NetMulticast, BlueprintCallable, BlueprintEvent)
void ABP_WeaponBase_C::MC_DamagedEffects()
{
static auto fn = UObject::FindObject<UFunction>("Function BP_WeaponBase.BP_WeaponBase_C.MC_DamagedEffects");
ABP_WeaponBase_C_MC_DamagedEffects_Params params;
auto flags = fn->FunctionFlags;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
}
// Function BP_WeaponBase.BP_WeaponBase_C.SpawnDualWeaponLeft
// (BlueprintCallable, BlueprintEvent)
void ABP_WeaponBase_C::SpawnDualWeaponLeft()
{
static auto fn = UObject::FindObject<UFunction>("Function BP_WeaponBase.BP_WeaponBase_C.SpawnDualWeaponLeft");
ABP_WeaponBase_C_SpawnDualWeaponLeft_Params params;
auto flags = fn->FunctionFlags;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
}
// Function BP_WeaponBase.BP_WeaponBase_C.ReceiveDestroyed
// (Event, Public, BlueprintEvent)
void ABP_WeaponBase_C::ReceiveDestroyed()
{
static auto fn = UObject::FindObject<UFunction>("Function BP_WeaponBase.BP_WeaponBase_C.ReceiveDestroyed");
ABP_WeaponBase_C_ReceiveDestroyed_Params params;
auto flags = fn->FunctionFlags;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
}
// Function BP_WeaponBase.BP_WeaponBase_C.PrimaryFire
// (BlueprintCallable, BlueprintEvent)
// Parameters:
// struct FVector CameraLocation (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, IsPlainOldData)
// struct FVector Direction (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, IsPlainOldData)
// bool FullPrecision (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, IsPlainOldData)
// bool WasSprinting (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, IsPlainOldData)
void ABP_WeaponBase_C::PrimaryFire(const struct FVector& CameraLocation, const struct FVector& Direction, bool FullPrecision, bool WasSprinting)
{
static auto fn = UObject::FindObject<UFunction>("Function BP_WeaponBase.BP_WeaponBase_C.PrimaryFire");
ABP_WeaponBase_C_PrimaryFire_Params params;
params.CameraLocation = CameraLocation;
params.Direction = Direction;
params.FullPrecision = FullPrecision;
params.WasSprinting = WasSprinting;
auto flags = fn->FunctionFlags;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
}
// Function BP_WeaponBase.BP_WeaponBase_C.StopPrimaryFire
// (BlueprintCallable, BlueprintEvent)
void ABP_WeaponBase_C::StopPrimaryFire()
{
static auto fn = UObject::FindObject<UFunction>("Function BP_WeaponBase.BP_WeaponBase_C.StopPrimaryFire");
ABP_WeaponBase_C_StopPrimaryFire_Params params;
auto flags = fn->FunctionFlags;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
}
// Function BP_WeaponBase.BP_WeaponBase_C.SecondaryFire
// (BlueprintCallable, BlueprintEvent)
// Parameters:
// struct FVector CameraLocation (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, IsPlainOldData)
// struct FVector Direction (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, IsPlainOldData)
void ABP_WeaponBase_C::SecondaryFire(const struct FVector& CameraLocation, const struct FVector& Direction)
{
static auto fn = UObject::FindObject<UFunction>("Function BP_WeaponBase.BP_WeaponBase_C.SecondaryFire");
ABP_WeaponBase_C_SecondaryFire_Params params;
params.CameraLocation = CameraLocation;
params.Direction = Direction;
auto flags = fn->FunctionFlags;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
}
// Function BP_WeaponBase.BP_WeaponBase_C.StopSecondaryFire
// (BlueprintCallable, BlueprintEvent)
// Parameters:
// struct FVector CameraLocation (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, IsPlainOldData)
// struct FVector Direction (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, IsPlainOldData)
void ABP_WeaponBase_C::StopSecondaryFire(const struct FVector& CameraLocation, const struct FVector& Direction)
{
static auto fn = UObject::FindObject<UFunction>("Function BP_WeaponBase.BP_WeaponBase_C.StopSecondaryFire");
ABP_WeaponBase_C_StopSecondaryFire_Params params;
params.CameraLocation = CameraLocation;
params.Direction = Direction;
auto flags = fn->FunctionFlags;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
}
// Function BP_WeaponBase.BP_WeaponBase_C.HolsteredEvent
// (BlueprintCallable, BlueprintEvent)
void ABP_WeaponBase_C::HolsteredEvent()
{
static auto fn = UObject::FindObject<UFunction>("Function BP_WeaponBase.BP_WeaponBase_C.HolsteredEvent");
ABP_WeaponBase_C_HolsteredEvent_Params params;
auto flags = fn->FunctionFlags;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
}
// Function BP_WeaponBase.BP_WeaponBase_C.ExecuteUbergraph_BP_WeaponBase
// (Final, HasDefaults)
// Parameters:
// int EntryPoint (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, IsPlainOldData)
void ABP_WeaponBase_C::ExecuteUbergraph_BP_WeaponBase(int EntryPoint)
{
static auto fn = UObject::FindObject<UFunction>("Function BP_WeaponBase.BP_WeaponBase_C.ExecuteUbergraph_BP_WeaponBase");
ABP_WeaponBase_C_ExecuteUbergraph_BP_WeaponBase_Params params;
params.EntryPoint = EntryPoint;
auto flags = fn->FunctionFlags;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
}
}
#ifdef _MSC_VER
#pragma pack(pop)
#endif
| [
"[email protected]"
] | |
ebd18f6d9189041b4207d1fc2845448100f79c76 | 44d182fc5f463cedfbdb6f124974e48f4f6393f5 | /DataControlServer/ListUser.cpp | bb23b7761f24102ce4b9b1275d7c071f20c7e9b0 | [] | no_license | jf4210/src2-test | a967a96f5b1e637bc43ed115580deee28e56b087 | debcea226f13adb56113769110627aa2c0760c70 | refs/heads/master | 2021-01-23T13:09:21.666323 | 2019-07-12T02:34:36 | 2019-07-12T02:34:36 | 59,100,155 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 1,508 | cpp | #include "ListUser.h"
CListUser* CListUser::m_pInstance = NULL;
CListUser::CListUser(void)
{
// InitializeCriticalSection(&m_Lock);
}
CListUser::~CListUser(void)
{
ClearUser();
// DeleteCriticalSection(&m_Lock);
}
void CListUser::Lock(void)
{
// EnterCriticalSection(&m_Lock);
m_listLock.lock();
}
void CListUser::UnLock(void)
{
// LeaveCriticalSection(&m_Lock);
m_listLock.unlock();
}
int CListUser::AddUser(CNetUser* pUser)
{
if (!pUser)
{
return -1;
}
Lock();
m_UserList.push_back(pUser);
UnLock();
return 0;
}
void CListUser::RemoveUser(CNetUser* pUser)
{
if (!pUser)
{
return;
}
Lock();
list<CNetUser*>::iterator it = m_UserList.begin();
for (; it != m_UserList.end(); it++)
{
if ((*it) == pUser)
{
m_UserList.erase(it);
break;
}
}
UnLock();
}
CListUser* CListUser::GetInstance(void)
{
if (!m_pInstance)
{
m_pInstance = new CListUser();
}
return m_pInstance;
}
void CListUser::ReleaseInstance(void)
{
if (m_pInstance)
{
delete m_pInstance;
m_pInstance = NULL;
}
}
void CListUser::ClearUser(void)
{
Lock();
list<CNetUser*>::iterator it = m_UserList.begin();
for (; it != m_UserList.end(); it++)
{
if (*it)
{
delete *it;
}
}
m_UserList.clear();
UnLock();
}
CNetUser* CListUser::FindUser(char* pUserNo)
{
Lock();
list<CNetUser*>::iterator it = m_UserList.begin();
for (; it != m_UserList.end(); it++)
{
CNetUser* p = *it;
if (!strcmp(p->m_Name, pUserNo))
{
UnLock();
return p;
}
}
UnLock();
return NULL;
}
| [
"[email protected]"
] | |
768742c9896776b568d2fd66f3087eae069ca69b | a64a086ec2058f2e68c81dbbfd9eafa3d20fded7 | /src/Subsystems/RobotLift.cpp | 134634f2c644d8fc62e245ae2e5a8a14131638b9 | [] | no_license | 1164/2017Test | 064d591dda910425649b8b66f159bb35f0cd12d4 | 7248a37fd440bd9d8676bb3a43c7a97a4118e5a8 | refs/heads/master | 2021-01-13T17:13:42.798464 | 2017-03-01T02:41:05 | 2017-03-01T02:41:05 | 81,764,258 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 744 | cpp | /*
* RobotLift.cpp
*
* Created on: Feb 15, 2017
* Author: neoadmin
*/
#include "WPILib.h"
#include <Subsystems/RobotLift.h>
RobotLift::RobotLift(Constant *Sarah) :
Subsystem("RobbotLift")
{
constants = Sarah;
LiftSC = new VictorSP(constants->Get("RobotLifterMotor")); //PWM Channel
LiftSC->SetInverted(constants->Get("RobotLifterInverted")== 1);
LimitTop = new DigitalInput(constants->Get("LifterTopLimitIOPort"));
LimitBottom = new DigitalInput(constants->Get("LifterBottomLimitIOPort"));
} // of RobotLift Constructor
void RobotLift::Set(double climb){
if (climb > 0.05 && LimitTop->Get()){
LiftSC->Set(climb);
}
else if(climb < -0.05 && LimitBottom->Get()){
LiftSC->Set(climb);
}
else{
LiftSC->Set(0.0);
}
}
| [
"[email protected]"
] | |
07151a6e2dcafbf65c046c2724ce894b955125ee | d7f95e5fb7bbf220b9f8dc700970ca42a1deb7dc | /examples/audio.cpp | 8c30f91de739c25bddcdb69b314bfcc69057c7d3 | [] | no_license | TheVaffel/HConLib | 9952b36e6b8f682f386c0bc06196ebe60a2a40a2 | 4db4a540661c11514a7208451504da94b5ccb978 | refs/heads/master | 2023-05-11T16:58:38.486934 | 2023-04-30T20:28:28 | 2023-04-30T20:28:28 | 75,107,118 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 743 | cpp | #include <iostream>
#include <Flaudio.hpp>
#define _USE_MATH_DEFINES
#include <math.h>
using namespace std;
int main(){
Flaudio fl;
int sampleRate = fl.getSampleRate();
int numSamples = 1*sampleRate;
int samplesPerStep = fl.getSamplesPerStep();
int16_t* samples = new int16_t[samplesPerStep];
float freq = 440;
float maxVol = 1<<13;
for(int j = 0; j < numSamples/samplesPerStep; j++){
for(int i = 0; i < samplesPerStep; i++){
samples[i] = (int16_t)(maxVol*sin(freq*(j*samplesPerStep + i)/sampleRate*2*M_PI));
}
fl.enqueueToChannel(samples, samplesPerStep, 0);
fl.playStep();
}
/*for(int i = 0; i < numSamples/samplesPerStep; i++){
fl.playStep();
}*/
return 0;
}
| [
"[email protected]"
] | |
9de3f19e3d354518e4ac196abbda9fa82e45a200 | 1bf8b46afad5402fe6fa74293b464e1ca5ee5fd7 | /Demo/Shenmue3SDK/SDK/BP_ACTrigger_parameters.h | 6f1e8de1d38de9d7ddb05dcd45df5c8c5d9ce7ea | [] | no_license | LemonHaze420/ShenmueIIISDK | a4857eebefc7e66dba9f667efa43301c5efcdb62 | 47a433b5e94f171bbf5256e3ff4471dcec2c7d7e | refs/heads/master | 2021-06-30T17:33:06.034662 | 2021-01-19T20:33:33 | 2021-01-19T20:33:33 | 214,824,713 | 4 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 8,719 | h | #pragma once
#include "../SDK.h"
// Name: S3Demo, Version: 0.90.0
#ifdef _MSC_VER
#pragma pack(push, 0x8)
#endif
namespace SDK
{
//---------------------------------------------------------------------------
// Parameters
//---------------------------------------------------------------------------
// Function BP_ACTrigger.BP_ACTrigger_C.BehaviorControl
struct ABP_ACTrigger_C_BehaviorControl_Params
{
bool NoChangeBehavior; // (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, IsPlainOldData)
};
// Function BP_ACTrigger.BP_ACTrigger_C.CheckSavedConditions
struct ABP_ACTrigger_C_CheckSavedConditions_Params
{
bool ReturnValue; // (Parm, OutParm, ZeroConstructor, ReturnParm, IsPlainOldData)
};
// Function BP_ACTrigger.BP_ACTrigger_C.CheckPlayCount
struct ABP_ACTrigger_C_CheckPlayCount_Params
{
bool ReturnValue; // (Parm, OutParm, ZeroConstructor, ReturnParm, IsPlainOldData)
};
// Function BP_ACTrigger.BP_ACTrigger_C.TriggerEnable
struct ABP_ACTrigger_C_TriggerEnable_Params
{
bool Enable; // (Parm, OutParm, ZeroConstructor, IsPlainOldData)
};
// Function BP_ACTrigger.BP_ACTrigger_C.ShutDownActionFunc
struct ABP_ACTrigger_C_ShutDownActionFunc_Params
{
};
// Function BP_ACTrigger.BP_ACTrigger_C.IsForward
struct ABP_ACTrigger_C_IsForward_Params
{
struct FVector HitLocation; // (BlueprintVisible, BlueprintReadOnly, Parm, IsPlainOldData)
bool Play; // (Parm, OutParm, ZeroConstructor, IsPlainOldData)
};
// Function BP_ACTrigger.BP_ACTrigger_C.ShouldDelayFadeIn
struct ABP_ACTrigger_C_ShouldDelayFadeIn_Params
{
bool DisableIt; // (Parm, OutParm, ZeroConstructor, IsPlainOldData)
};
// Function BP_ACTrigger.BP_ACTrigger_C.ShouldDisablePlayerControl
struct ABP_ACTrigger_C_ShouldDisablePlayerControl_Params
{
bool DisableIt; // (Parm, OutParm, ZeroConstructor, IsPlainOldData)
};
// Function BP_ACTrigger.BP_ACTrigger_C.ApplyLog
struct ABP_ACTrigger_C_ApplyLog_Params
{
};
// Function BP_ACTrigger.BP_ACTrigger_C.ResetLog
struct ABP_ACTrigger_C_ResetLog_Params
{
};
// Function BP_ACTrigger.BP_ACTrigger_C.CheckReset
struct ABP_ACTrigger_C_CheckReset_Params
{
bool Reset; // (Parm, OutParm, ZeroConstructor, IsPlainOldData)
};
// Function BP_ACTrigger.BP_ACTrigger_C.SaveLog
struct ABP_ACTrigger_C_SaveLog_Params
{
};
// Function BP_ACTrigger.BP_ACTrigger_C.CanPlay
struct ABP_ACTrigger_C_CanPlay_Params
{
bool CAN; // (Parm, OutParm, ZeroConstructor, IsPlainOldData)
};
// Function BP_ACTrigger.BP_ACTrigger_C.TeleportPlayer
struct ABP_ACTrigger_C_TeleportPlayer_Params
{
};
// Function BP_ACTrigger.BP_ACTrigger_C.SetPlayerControl
struct ABP_ACTrigger_C_SetPlayerControl_Params
{
bool Enable; // (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, IsPlainOldData)
};
// Function BP_ACTrigger.BP_ACTrigger_C.PlayAction
struct ABP_ACTrigger_C_PlayAction_Params
{
bool Success; // (Parm, OutParm, ZeroConstructor, IsPlainOldData)
};
// Function BP_ACTrigger.BP_ACTrigger_C.UserConstructionScript
struct ABP_ACTrigger_C_UserConstructionScript_Params
{
};
// Function BP_ACTrigger.BP_ACTrigger_C.OnLoaded_3DE5C7A6450AC770771EC1A18B8E6811
struct ABP_ACTrigger_C_OnLoaded_3DE5C7A6450AC770771EC1A18B8E6811_Params
{
class UObject* Loaded; // (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, IsPlainOldData)
};
// Function BP_ACTrigger.BP_ACTrigger_C.ReceiveTick
struct ABP_ACTrigger_C_ReceiveTick_Params
{
float* DeltaSeconds; // (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, IsPlainOldData)
};
// Function BP_ACTrigger.BP_ACTrigger_C.BndEvt__CollisionComponent_K2Node_ComponentBoundEvent_1_ComponentBeginOverlapSignature__DelegateSignature
struct ABP_ACTrigger_C_BndEvt__CollisionComponent_K2Node_ComponentBoundEvent_1_ComponentBeginOverlapSignature__DelegateSignature_Params
{
class UPrimitiveComponent* OverlappedComponent; // (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, InstancedReference, IsPlainOldData)
class AActor* OtherActor; // (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, IsPlainOldData)
class UPrimitiveComponent* OtherComp; // (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, InstancedReference, IsPlainOldData)
int OtherBodyIndex; // (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, IsPlainOldData)
bool bFromSweep; // (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, IsPlainOldData)
struct FHitResult SweepResult; // (ConstParm, BlueprintVisible, BlueprintReadOnly, Parm, OutParm, ReferenceParm, IsPlainOldData)
};
// Function BP_ACTrigger.BP_ACTrigger_C.BndEvt__CollisionComponent_K2Node_ComponentBoundEvent_0_ComponentEndOverlapSignature__DelegateSignature
struct ABP_ACTrigger_C_BndEvt__CollisionComponent_K2Node_ComponentBoundEvent_0_ComponentEndOverlapSignature__DelegateSignature_Params
{
class UPrimitiveComponent* OverlappedComponent; // (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, InstancedReference, IsPlainOldData)
class AActor* OtherActor; // (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, IsPlainOldData)
class UPrimitiveComponent* OtherComp; // (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, InstancedReference, IsPlainOldData)
int OtherBodyIndex; // (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, IsPlainOldData)
};
// Function BP_ACTrigger.BP_ACTrigger_C.ReceiveBeginPlay
struct ABP_ACTrigger_C_ReceiveBeginPlay_Params
{
};
// Function BP_ACTrigger.BP_ACTrigger_C.ReceiveEndPlay
struct ABP_ACTrigger_C_ReceiveEndPlay_Params
{
TEnumAsByte<EEndPlayReason>* EndPlayReason; // (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, IsPlainOldData)
};
// Function BP_ACTrigger.BP_ACTrigger_C.PlayACEvent
struct ABP_ACTrigger_C_PlayACEvent_Params
{
};
// Function BP_ACTrigger.BP_ACTrigger_C.CheckCanPlay
struct ABP_ACTrigger_C_CheckCanPlay_Params
{
};
// Function BP_ACTrigger.BP_ACTrigger_C.CustomEvent
struct ABP_ACTrigger_C_CustomEvent_Params
{
int SetSteps; // (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, IsPlainOldData)
};
// Function BP_ACTrigger.BP_ACTrigger_C.LoadTalkScript
struct ABP_ACTrigger_C_LoadTalkScript_Params
{
};
// Function BP_ACTrigger.BP_ACTrigger_C.ExecuteUbergraph_BP_ACTrigger
struct ABP_ACTrigger_C_ExecuteUbergraph_BP_ACTrigger_Params
{
int EntryPoint; // (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, IsPlainOldData)
};
}
#ifdef _MSC_VER
#pragma pack(pop)
#endif
| [
"[email protected]"
] | |
0e2351a62ccc37aa4e669ff2fe20e72ca2910e14 | 14dd3dac67e002fd36ddc7b661b1382e8daa0bb2 | /src/util/message.cpp | e2faf20c4318b3dfc0c7df3b091a60cfd9eeb1ef | [] | no_license | MuAnsari96/slatewm | c0f4e6aa07e6eb2a89337efa2690c5ae2539d267 | 6424fa5847203fd66e819be722589b1d2f91f06a | refs/heads/master | 2021-01-22T15:50:05.770157 | 2016-10-15T14:46:11 | 2016-10-15T14:46:11 | 59,691,078 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,196 | cpp | #include "message.h"
namespace Message {
zmq::socket_t* client;
}
void Message::PopulateMessage(json *j, const slate_state_t &state, const XEvent &e) {
/* Creates a standard update message to the client. From here, additional components can be appended to
* the message to send it all the information necessary to an event. This will ultimately be abstracted away
*/
(*j)["Event"] = ToClient::DEFAULT;
(*j)["Client"] = state.focused_client;
(*j)["Workspace"] = 0;
(*j)["Screen"] = 0;
(*j)["Keys"] = {
{"Meta", state.meta},
{"Shift", state.shift},
{"Ctl", state.ctl},
{"Alt", state.alt},
{"Space", state.space},
{"Enter", state.enter},
{"Keymask", state.keymask},
{"Delta", ""}
};
}
void Message::AppendToMessage(json *j, const Tile& tile) {
/* Appends the information of a single tile to a message
*/
(*j)["Window"] = {
{"style", tile.getStyle()},
{"styleType", tile.getStyleType()},
{"xmin", tile.getXLimits().first},
{"xmax", tile.getXLimits().second},
{"ymin", tile.getYLimits().first},
{"ymax", tile.getYLimits().second},
{"primaryID", tile.getID()}
};
}
void Message::AppendToMessage(json *j, const Tile &toSplit, const Tile &primary, const Tile &secondary) {
/* Appends a tile and its children to a message.
*/
(*j)["Window"] = {
{"style", toSplit.getStyle()},
{"styleType", toSplit.getStyleType()},
{"xmin", toSplit.getXLimits().first},
{"xmax", toSplit.getXLimits().second},
{"ymin", toSplit.getYLimits().first},
{"ymax", toSplit.getYLimits().second},
{"primaryID", primary.getID()},
{"secondaryID", secondary.getID()}
};
}
void Message::InitClientSocket(zmq::socket_t* toClient) {
client = toClient;
}
void Message::SendToClient(json *j) {
std::string jmsg_str = j->dump();
zmq::message_t msg(jmsg_str.size());
memcpy(msg.data(), jmsg_str.c_str(), jmsg_str.size());
Message::client->send(msg, ZMQ_NOBLOCK);
} | [
"[email protected]"
] | |
01795c91eb211b3782418e4dc9e156325b4f0844 | fbab3827e5335373f8db3dcc027c3b59019cde41 | /Datagram.cpp | b944cf11edd67169220ace2dd2f1690af06087e4 | [
"BSD-3-Clause"
] | permissive | Frankie-666/i2pd | 922bf06422ad6a83147a8cfc4b2ad58f544ea431 | 58124ebaab8b8960ea3dbdb8bd7d489d555ec8de | refs/heads/openssl | 2021-01-15T08:04:52.796555 | 2015-12-05T08:40:24 | 2015-12-05T11:55:27 | 47,505,171 | 1 | 0 | null | 2015-12-06T16:51:49 | 2015-12-06T16:51:48 | null | UTF-8 | C++ | false | false | 4,795 | cpp | #include <string.h>
#include <vector>
#include <openssl/sha.h>
#include <openssl/rand.h>
#include "Log.h"
#include "TunnelBase.h"
#include "RouterContext.h"
#include "Destination.h"
#include "Datagram.h"
namespace i2p
{
namespace datagram
{
DatagramDestination::DatagramDestination (std::shared_ptr<i2p::client::ClientDestination> owner):
m_Owner (owner), m_Receiver (nullptr)
{
}
DatagramDestination::~DatagramDestination ()
{
}
void DatagramDestination::SendDatagramTo (const uint8_t * payload, size_t len, const i2p::data::IdentHash& ident, uint16_t fromPort, uint16_t toPort)
{
uint8_t buf[MAX_DATAGRAM_SIZE];
auto identityLen = m_Owner->GetIdentity ()->ToBuffer (buf, MAX_DATAGRAM_SIZE);
uint8_t * signature = buf + identityLen;
auto signatureLen = m_Owner->GetIdentity ()->GetSignatureLen ();
uint8_t * buf1 = signature + signatureLen;
size_t headerLen = identityLen + signatureLen;
memcpy (buf1, payload, len);
if (m_Owner->GetIdentity ()->GetSigningKeyType () == i2p::data::SIGNING_KEY_TYPE_DSA_SHA1)
{
uint8_t hash[32];
SHA256(buf1, len, hash);
m_Owner->Sign (hash, 32, signature);
}
else
m_Owner->Sign (buf1, len, signature);
auto msg = CreateDataMessage (buf, len + headerLen, fromPort, toPort);
auto remote = m_Owner->FindLeaseSet (ident);
if (remote)
m_Owner->GetService ().post (std::bind (&DatagramDestination::SendMsg, this, msg, remote));
else
m_Owner->RequestDestination (ident, std::bind (&DatagramDestination::HandleLeaseSetRequestComplete, this, std::placeholders::_1, msg));
}
void DatagramDestination::HandleLeaseSetRequestComplete (std::shared_ptr<i2p::data::LeaseSet> remote, std::shared_ptr<I2NPMessage> msg)
{
if (remote)
SendMsg (msg, remote);
}
void DatagramDestination::SendMsg (std::shared_ptr<I2NPMessage> msg, std::shared_ptr<const i2p::data::LeaseSet> remote)
{
auto outboundTunnel = m_Owner->GetTunnelPool ()->GetNextOutboundTunnel ();
auto leases = remote->GetNonExpiredLeases ();
if (!leases.empty () && outboundTunnel)
{
std::vector<i2p::tunnel::TunnelMessageBlock> msgs;
uint32_t i = rand () % leases.size ();
auto garlic = m_Owner->WrapMessage (remote, msg, true);
msgs.push_back (i2p::tunnel::TunnelMessageBlock
{
i2p::tunnel::eDeliveryTypeTunnel,
leases[i].tunnelGateway, leases[i].tunnelID,
garlic
});
outboundTunnel->SendTunnelDataMsg (msgs);
}
else
{
if (outboundTunnel)
LogPrint (eLogWarning, "Failed to send datagram. All leases expired");
else
LogPrint (eLogWarning, "Failed to send datagram. No outbound tunnels");
}
}
void DatagramDestination::HandleDatagram (uint16_t fromPort, uint16_t toPort, const uint8_t * buf, size_t len)
{
i2p::data::IdentityEx identity;
size_t identityLen = identity.FromBuffer (buf, len);
const uint8_t * signature = buf + identityLen;
size_t headerLen = identityLen + identity.GetSignatureLen ();
bool verified = false;
if (identity.GetSigningKeyType () == i2p::data::SIGNING_KEY_TYPE_DSA_SHA1)
{
uint8_t hash[32];
SHA256(buf + headerLen, len - headerLen, hash);
verified = identity.Verify (hash, 32, signature);
}
else
verified = identity.Verify (buf + headerLen, len - headerLen, signature);
if (verified)
{
auto it = m_ReceiversByPorts.find (toPort);
if (it != m_ReceiversByPorts.end ())
it->second (identity, fromPort, toPort, buf + headerLen, len -headerLen);
else if (m_Receiver != nullptr)
m_Receiver (identity, fromPort, toPort, buf + headerLen, len -headerLen);
else
LogPrint (eLogWarning, "Receiver for datagram is not set");
}
else
LogPrint (eLogWarning, "Datagram signature verification failed");
}
void DatagramDestination::HandleDataMessagePayload (uint16_t fromPort, uint16_t toPort, const uint8_t * buf, size_t len)
{
// unzip it
uint8_t uncompressed[MAX_DATAGRAM_SIZE];
size_t uncompressedLen = m_Inflator.Inflate (buf, len, uncompressed, MAX_DATAGRAM_SIZE);
if (uncompressedLen)
HandleDatagram (fromPort, toPort, uncompressed, uncompressedLen);
}
std::shared_ptr<I2NPMessage> DatagramDestination::CreateDataMessage (const uint8_t * payload, size_t len, uint16_t fromPort, uint16_t toPort)
{
auto msg = NewI2NPMessage ();
uint8_t * buf = msg->GetPayload ();
buf += 4; // reserve for length
size_t size = m_Deflator.Deflate (payload, len, buf, msg->maxLen - msg->len);
if (size)
{
htobe32buf (msg->GetPayload (), size); // length
htobe16buf (buf + 4, fromPort); // source port
htobe16buf (buf + 6, toPort); // destination port
buf[9] = i2p::client::PROTOCOL_TYPE_DATAGRAM; // datagram protocol
msg->len += size + 4;
msg->FillI2NPMessageHeader (eI2NPData);
}
else
msg = nullptr;
return msg;
}
}
}
| [
"[email protected]"
] | |
b4e6df218ae2072788c0f0f0d9ef873bc3438c99 | 2f98c60a171b8f6df0f411255589ee6f26737cfb | /web/WWSAPI/OneWayTcpClient/OneWayTcpClient.cpp | 550a8c0f9ff2b388146cd614deac91f42f70e30f | [] | no_license | bbesbes/WindowsSDK7-Samples | 4df1d7f2c6fae7bd84411b4c13751a4085144af9 | 14e1c3daff5927791c9e17083ea455ba3de84444 | refs/heads/master | 2021-09-23T10:05:42.764049 | 2021-09-16T19:45:25 | 2021-09-16T19:45:25 | 118,103,268 | 0 | 0 | null | 2018-01-19T09:12:39 | 2018-01-19T09:12:39 | null | UTF-8 | C++ | false | false | 4,120 | cpp | //------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
//------------------------------------------------------------
#ifndef UNICODE
#define UNICODE
#endif
#include "WebServices.h"
#include "process.h"
#include "stdio.h"
#include "string.h"
#include "PurchaseOrder.wsdl.h"
// Print out rich error info
void PrintError(HRESULT errorCode, WS_ERROR* error)
{
wprintf(L"Failure: errorCode=0x%lx\n", errorCode);
if (errorCode == E_INVALIDARG || errorCode == WS_E_INVALID_OPERATION)
{
// Correct use of the APIs should never generate these errors
wprintf(L"The error was due to an invalid use of an API. This is likely due to a bug in the program.\n");
DebugBreak();
}
HRESULT hr = NOERROR;
if (error != NULL)
{
ULONG errorCount;
hr = WsGetErrorProperty(error, WS_ERROR_PROPERTY_STRING_COUNT, &errorCount, sizeof(errorCount));
if (FAILED(hr))
{
goto Exit;
}
for (ULONG i = 0; i < errorCount; i++)
{
WS_STRING string;
hr = WsGetErrorString(error, i, &string);
if (FAILED(hr))
{
goto Exit;
}
wprintf(L"%.*s\n", string.length, string.chars);
}
}
Exit:
if (FAILED(hr))
{
wprintf(L"Could not get error string (errorCode=0x%lx)\n", hr);
}
}
// Main entry point
int __cdecl wmain(int argc, __in_ecount(argc) wchar_t **argv)
{
UNREFERENCED_PARAMETER(argc);
UNREFERENCED_PARAMETER(argv);
HRESULT hr = NOERROR;
WS_ERROR* error = NULL;
WS_CHANNEL* channel = NULL;
WS_MESSAGE* message = NULL;
// Create an error object for storing rich error information
hr = WsCreateError(
NULL,
0,
&error);
if (FAILED(hr))
{
goto Exit;
}
// Create a TCP duplex session channel
hr = WsCreateChannel(
WS_CHANNEL_TYPE_DUPLEX_SESSION,
WS_TCP_CHANNEL_BINDING,
NULL,
0,
NULL,
&channel,
error);
if (FAILED(hr))
{
goto Exit;
}
// Initialize address of service
WS_ENDPOINT_ADDRESS address;
address.url.chars = L"net.tcp://localhost/example";
address.url.length = (ULONG)::wcslen(address.url.chars);
address.headers = NULL;
address.extensions = NULL;
address.identity = NULL;
// Open channel to address
hr = WsOpenChannel(
channel,
&address,
NULL,
error);
if (FAILED(hr))
{
goto Exit;
}
hr = WsCreateMessageForChannel(
channel,
NULL,
0,
&message,
error);
if (FAILED(hr))
{
goto Exit;
}
// Send some messages
for (int i = 0; i < 100; i++)
{
// Initialize body data
_PurchaseOrderType purchaseOrder;
purchaseOrder.quantity = 100;
purchaseOrder.productName = L"Pencil";
// Send a message
hr = WsSendMessage(
channel,
message,
&PurchaseOrder_wsdl.messages.PurchaseOrder,
WS_WRITE_REQUIRED_VALUE,
&purchaseOrder,
sizeof(purchaseOrder),
NULL,
error);
if (FAILED(hr))
{
goto Exit;
}
// Reset message so it can be used again
hr = WsResetMessage(message, error);
if (FAILED(hr))
{
goto Exit;
}
}
Exit:
if (FAILED(hr))
{
// Print out the error
PrintError(hr, error);
}
fflush(
stdout);
if (channel != NULL)
{
// Close the channel
WsCloseChannel(channel, NULL, error);
}
if (message != NULL)
{
WsFreeMessage(message);
}
if (channel != NULL)
{
WsFreeChannel(channel);
}
if (error != NULL)
{
WsFreeError(error);
}
fflush(stdout);
return SUCCEEDED(hr) ? 0 : -1;
}
| [
"[email protected]"
] | |
940aa839af6c0b0fb4d37231aa5875ac96157c4f | 21553f6afd6b81ae8403549467230cdc378f32c9 | /arm/cortex/Freescale/MK60DZ10/include/arch/reg/axbs.hpp | 619873bac6acc3864b21fd7454a813a933869966 | [] | no_license | digint/openmptl-reg-arm-cortex | 3246b68dcb60d4f7c95a46423563cab68cb02b5e | 88e105766edc9299348ccc8d2ff7a9c34cddacd3 | refs/heads/master | 2021-07-18T19:56:42.569685 | 2017-10-26T11:11:35 | 2017-10-26T11:11:35 | 108,407,162 | 3 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 3,283 | hpp | /*
* OpenMPTL - C++ Microprocessor Template Library
*
* This program is a derivative representation of a CMSIS System View
* Description (SVD) file, and is subject to the corresponding license
* (see "Freescale CMSIS-SVD License Agreement.pdf" in the parent directory).
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
*/
////////////////////////////////////////////////////////////////////////
//
// Import from CMSIS-SVD: "Freescale/MK60DZ10.svd"
//
// vendor: Freescale Semiconductor, Inc.
// vendorID: Freescale
// name: MK60DZ10
// series: Kinetis_K
// version: 1.6
// description: MK60DZ10 Freescale Microcontroller
// --------------------------------------------------------------------
//
// C++ Header file, containing architecture specific register
// declarations for use in OpenMPTL. It has been converted directly
// from a CMSIS-SVD file.
//
// https://digint.ch/openmptl
// https://github.com/posborne/cmsis-svd
//
#ifndef ARCH_REG_AXBS_HPP_INCLUDED
#define ARCH_REG_AXBS_HPP_INCLUDED
#warning "using untested register declarations"
#include <register.hpp>
namespace mptl {
/**
* Crossbar switch
*/
struct AXBS
{
static constexpr reg_addr_t base_addr = 0x40004000;
/**
* Priority Registers Slave
*/
struct PRS%s
: public reg< uint32_t, base_addr + 0, rw, 0x76543210 >
{
using type = reg< uint32_t, base_addr + 0, rw, 0x76543210 >;
using M0 = regbits< type, 0, 3 >; /**< Master 0 priority. Sets the arbitration priority for this port on the associated slave port. */
using M1 = regbits< type, 4, 3 >; /**< Master 1 priority. Sets the arbitration priority for this port on the associated slave port. */
using M2 = regbits< type, 8, 3 >; /**< Master 2 priority. Sets the arbitration priority for this port on the associated slave port. */
using M3 = regbits< type, 12, 3 >; /**< Master 3 priority. Sets the arbitration priority for this port on the associated slave port. */
using M4 = regbits< type, 16, 3 >; /**< Master 4 priority. Sets the arbitration priority for this port on the associated slave port. */
using M5 = regbits< type, 20, 3 >; /**< Master 5 priority. Sets the arbitration priority for this port on the associated slave port. */
};
/**
* Control Register
*/
struct CRS%s
: public reg< uint32_t, base_addr + 0x10, rw, 0 >
{
using type = reg< uint32_t, base_addr + 0x10, rw, 0 >;
using PARK = regbits< type, 0, 3 >; /**< Park */
using PCTL = regbits< type, 4, 2 >; /**< Parking control */
using ARB = regbits< type, 8, 2 >; /**< Arbitration mode */
using HLP = regbits< type, 30, 1 >; /**< Halt low priority */
using RO = regbits< type, 31, 1 >; /**< Read only */
};
/**
* Master General Purpose Control Register
*/
struct MGPCR%s
: public reg< uint32_t, base_addr + 0x800, rw, 0 >
{
using type = reg< uint32_t, base_addr + 0x800, rw, 0 >;
using AULB = regbits< type, 0, 3 >; /**< Arbitrates on undefined length bursts */
};
};
} // namespace mptl
#endif // ARCH_REG_AXBS_HPP_INCLUDED
| [
"[email protected]"
] | |
4875244087d770662bb8639d46e67fab4031d135 | 462a1136f8454e7496ddfb9d50e76f8a34e7e7e1 | /CSGOSimple/valve_sdk/csgostructs.cpp | aba732e4c9b390b9fe6b91d30842e3906080cb1d | [] | no_license | winterhvh/CSGOSimple | fe5cfc3646ba850ee854b308f6fc87d1997404df | 89bf25fc8a3e8ef80043d851eb0264ddff60b17d | refs/heads/master | 2020-03-15T21:47:12.662786 | 2017-08-02T00:18:59 | 2017-08-02T00:18:59 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,224 | cpp | #include "csgostructs.hpp"
#include "../Helpers/Math.hpp"
#include "../Helpers/Utils.hpp"
bool C_BaseEntity::IsPlayer()
{
//index: 152
//ref: "effects/nightvision"
//sig: 8B 92 ? ? ? ? FF D2 84 C0 0F 45 F7 85 F6
return CallVFunction<bool(__thiscall*)(C_BaseEntity*)>(this, 152)(this);
}
bool C_BaseEntity::IsWeapon()
{
//index: 160
//ref: "CNewParticleEffect::DrawModel"
//sig: 8B 80 ? ? ? ? FF D0 84 C0 74 6F 8B 4D A4
return CallVFunction<bool(__thiscall*)(C_BaseEntity*)>(this, 160)(this);
}
bool C_BaseEntity::IsPlantedC4()
{
return GetClientClass()->m_ClassID == ClassId_CPlantedC4;
}
bool C_BaseEntity::IsDefuseKit()
{
return GetClientClass()->m_ClassID == ClassId_CBaseAnimating;
}
CCSWeaponInfo* C_BaseCombatWeapon::GetCSWeaponData()
{
static auto fnGetWpnData
= reinterpret_cast<CCSWeaponInfo*(__thiscall*)(void*)>(
Utils::PatternScan(GetModuleHandleW(L"client.dll"), "55 8B EC 81 EC ? ? ? ? B8 ? ? ? ? 57")
);
return fnGetWpnData(this);
}
bool C_BaseCombatWeapon::HasBullets()
{
return !IsReloading() && m_iClip1() > 0;
}
bool C_BaseCombatWeapon::CanFire()
{
if(IsReloading() || m_iClip1() <= 0)
return false;
if(!g_LocalPlayer)
return false;
float flServerTime = g_LocalPlayer->m_nTickBase() * g_GlobalVars->interval_per_tick;
return m_flNextPrimaryAttack() <= flServerTime;
}
bool C_BaseCombatWeapon::IsGrenade()
{
return GetCSWeaponData()->m_WeaponType == WEAPONTYPE_GRENADE;
}
bool C_BaseCombatWeapon::IsKnife()
{
return GetCSWeaponData()->m_WeaponType == WEAPONTYPE_KNIFE;
}
bool C_BaseCombatWeapon::IsRifle()
{
switch (GetCSWeaponData()->m_WeaponType)
{
case WEAPONTYPE_RIFLE:
return true;
case WEAPONTYPE_SUBMACHINEGUN:
return true;
case WEAPONTYPE_SHOTGUN:
return true;
case WEAPONTYPE_MACHINEGUN:
return true;
default:
return false;
}
}
bool C_BaseCombatWeapon::IsPistol()
{
switch (GetCSWeaponData()->m_WeaponType)
{
case WEAPONTYPE_PISTOL:
return true;
default:
return false;
}
}
bool C_BaseCombatWeapon::IsSniper()
{
switch (GetCSWeaponData()->m_WeaponType)
{
case WEAPONTYPE_SNIPER_RIFLE:
return true;
default:
return false;
}
}
bool C_BaseCombatWeapon::IsReloading()
{
static auto inReload = *(uint32_t*)(Utils::PatternScan(GetModuleHandleW(L"client.dll"), "C6 87 ? ? ? ? ? 8B 06 8B CE FF 90") + 2);
return *(bool*)((uintptr_t)this + inReload);
}
float C_BaseCombatWeapon::GetInaccuracy()
{
return CallVFunction<float(__thiscall*)(void*)>(this, 484)(this);
}
float C_BaseCombatWeapon::GetSpread()
{
return CallVFunction<float(__thiscall*)(void*)>(this, 485)(this);
}
void C_BaseCombatWeapon::UpdateAccuracyPenalty()
{
CallVFunction<void(__thiscall*)(void*)>(this, 486)(this);
}
CUserCmd*& C_BasePlayer::m_pCurrentCommand()
{
static auto currentCommand = *(uint32_t*)(Utils::PatternScan(GetModuleHandleW(L"client.dll"), "89 9F ? ? ? ? E8 ? ? ? ? 85 DB") + 2);
return *(CUserCmd**)((uintptr_t)this + currentCommand);
}
Vector C_BasePlayer::GetEyePos()
{
return m_vecOrigin() + m_vecViewOffset();
}
player_info_t C_BasePlayer::GetPlayerInfo()
{
player_info_t info;
g_EngineClient->GetPlayerInfo(EntIndex(), &info);
return info;
}
bool C_BasePlayer::IsAlive()
{
return m_lifeState() == LIFE_ALIVE;
}
bool C_BasePlayer::HasC4()
{
static auto fnHasC4
= reinterpret_cast<bool(__thiscall*)(void*)>(
Utils::PatternScan(GetModuleHandleW(L"client.dll"), "56 8B F1 85 F6 74 31")
);
return fnHasC4(this);
}
Vector C_BasePlayer::GetHitboxPos(int hitbox_id)
{
matrix3x4_t boneMatrix[MAXSTUDIOBONES];
if(SetupBones(boneMatrix, MAXSTUDIOBONES, BONE_USED_BY_HITBOX, 0.0f)) {
auto studio_model = g_MdlInfo->GetStudiomodel(GetModel());
if(studio_model) {
auto hitbox = studio_model->GetHitboxSet(0)->GetHitbox(hitbox_id);
if(hitbox) {
auto
min = Vector{},
max = Vector{};
Math::VectorTransform(hitbox->bbmin, boneMatrix[hitbox->bone], min);
Math::VectorTransform(hitbox->bbmax, boneMatrix[hitbox->bone], max);
return (min + max) / 2.0f;
}
}
}
return Vector{};
}
bool C_BasePlayer::GetHitboxPos(int hitbox, Vector &output)
{
if(hitbox >= HITBOX_MAX)
return false;
const model_t *model = this->GetModel();
if(!model)
return false;
studiohdr_t *studioHdr = g_MdlInfo->GetStudiomodel(model);
if(!studioHdr)
return false;
matrix3x4_t matrix[MAXSTUDIOBONES];
if(!this->SetupBones(matrix, MAXSTUDIOBONES, 0x100, 0))
return false;
mstudiobbox_t *studioBox = studioHdr->GetHitboxSet(0)->GetHitbox(hitbox);
if(!studioBox)
return false;
Vector min, max;
Math::VectorTransform(studioBox->bbmin, matrix[studioBox->bone], min);
Math::VectorTransform(studioBox->bbmax, matrix[studioBox->bone], max);
output = (min + max) * 0.5f;
return true;
}
Vector C_BasePlayer::GetBonePos(int bone)
{
matrix3x4_t boneMatrix[MAXSTUDIOBONES];
if(SetupBones(boneMatrix, MAXSTUDIOBONES, BONE_USED_BY_ANYTHING, 0.0f)) {
return Vector{ boneMatrix[bone].at(0) };
}
return Vector{};
}
bool C_BasePlayer::CanSeePlayer(C_BasePlayer* player, int hitbox)
{
CGameTrace tr;
Ray_t ray;
CTraceFilter filter;
filter.pSkip = this;
auto endpos = player->GetHitboxPos(hitbox);
ray.Init(GetEyePos(), endpos);
g_EngineTrace->TraceRay(ray, MASK_SHOT | CONTENTS_GRATE, &filter, &tr);
return tr.hit_entity == player || tr.fraction > 0.97f;
}
bool C_BasePlayer::CanSeePlayer(C_BasePlayer* player, const Vector& pos)
{
CGameTrace tr;
Ray_t ray;
CTraceFilter filter;
filter.pSkip = this;
auto start = GetEyePos();
auto dir = (pos - start).Normalized();
ray.Init(start, pos);
g_EngineTrace->TraceRay(ray, MASK_SHOT | CONTENTS_GRATE, &filter, &tr);
return tr.hit_entity == player || tr.fraction > 0.97f;
}
| [
"[email protected]"
] | |
119d77528e624272c5eb3cceffb7cf8f3440687d | 4183598a94774bc20922f6196d8e785b87cec075 | /LAB4/diceroll.cpp | f32ee70660645f61c35eeef3f51d6b9542db1855 | [] | no_license | 29iA/csc2100-2101 | 2e4c23068a8fbf3c94d5733cb26fdfbdad7bfb52 | 878dfa89210d24f6f5c5ef39aca0d2b8dd248d90 | refs/heads/master | 2016-09-01T16:08:39.400951 | 2016-04-23T01:16:50 | 2016-04-23T01:16:50 | 54,795,241 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 728 | cpp | /*
Title: diceroll.cpp
Author: PUT YOUR NAME HERE!!!!
Date: PUT THE DATE HERE!!!!
Purpose: write if/else if/else statement from a switch statement
*/
#include <iostream>
using namespace std;
int main()
{
short diceRoll;
cout << "What did you roll?\n";
cin >> diceRoll;
if (diceRoll == 1) {
cout << "You fell in a trap!\n";
}
else if (diceRoll == 2) {
cout << "You lose a turn!\n";
}
else if (diceRoll == 3) {
cout << "Roll again!\n";
}
else if (diceRoll == 4) {
cout << "Move forward 1 space!\n";
}
else if (diceRoll == 5) {
cout << "Move forward 2 spaces!\n";
}
else if (diceRoll == 6) {
cout << "You win the game!\n";
}
else {
cout << "Invalid dice roll. Try again.\n";
}
return 0;
} | [
"[email protected]"
] | |
c26e2f6a2fbef21ccdb8b92c4a2b2b71d3d25e36 | e9fa019c878a4bbe8d32a6c760692501ac3069ab | /systems/ReaderWriter/ReaderWriter.cpp | f5aec4c5be6d445c268b8006a83b00e623d57468 | [] | no_license | liux0229/scratch | 6faa9413fdba1aa9694a0d6b6192bf18da0a37c7 | ab22e7367104d1b4a9cddc1797d293d9eebe21f8 | refs/heads/master | 2021-01-23T07:09:29.694570 | 2019-04-14T15:47:25 | 2019-04-14T15:47:25 | 4,477,441 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 7,629 | cpp | // FLAGS: -pthread -g -O3
#include <condition_variable>
#include <mutex>
#include <cassert>
#include <atomic>
#include <chrono>
#include <cstdlib>
#include <vector>
#include <thread>
#include <iostream>
using namespace std;
using namespace std::chrono;
class ReaderWriterLockReaderPreferredWeak {
public:
void lockReader() {
unique_lock<mutex> lock(m_);
while (nWriter_ > 0) {
cv_.wait(lock);
}
++nReader_;
// read exclusivity obtained (I incremented nReader_)
// cout << "accquiring reader lock; nReader_ = " << nReader_ << endl;
}
void unlockReader() {
unique_lock<mutex> lock(m_);
assert(nWriter_ == 0);
assert(nReader_ > 0);
if (--nReader_ == 0) {
cv_.notify_one();
}
// cout << "release reader lock: " << nReader_ << endl;
}
void lockWriter() {
unique_lock<mutex> lock(m_);
while (nWriter_ > 0 || nReader_ > 0) {
cv_.wait(lock);
}
++nWriter_;
// write exclusivity obtained (I changed nWriter_ from 0 to 1)
// cout << "accquiring writer lock; nWriter = " << nWriter_ << endl;
}
void unlockWriter() {
unique_lock<mutex> lock(m_);
assert(nWriter_ == 1);
--nWriter_;
cv_.notify_one();
// cout << "release writer lock: " << nWriter_ << endl;
}
private:
mutex m_;
condition_variable cv_;
int nReader_{0};
int nWriter_{0};
};
class ReaderWriterLockReaderPreferredWeakMutex {
public:
void lockReader() {
lock_guard<mutex> lock(cm_);
if (readers_++ == 0) {
// Need to exclude writers
rm_.lock();
}
}
void unlockReader() {
lock_guard<mutex> lock(cm_);
if (--readers_ == 0) {
// open up for writers
rm_.unlock();
}
}
void lockWriter() {
rm_.lock();
}
void unlockWriter() {
rm_.unlock();
}
private:
mutex rm_;
mutex cm_;
int readers_{0};
};
class ReaderWriterLockReaderPreferredStrongMutex {
public:
void lockReader() {
lock_guard<mutex> lock(cm_);
if (readers_++ == 0) {
// Need to exclude writers
rm_.lock();
}
}
void unlockReader() {
lock_guard<mutex> lock(cm_);
if (--readers_ == 0) {
// open up for writers
rm_.unlock();
}
}
void lockWriter() {
wm_.lock();
rm_.lock();
}
void unlockWriter() {
rm_.unlock();
wm_.unlock();
}
private:
mutex rm_;
mutex wm_;
mutex cm_;
int readers_{0};
};
class ReaderWriterLockWriterPreferredSlow {
public:
void lockReader() {
unique_lock<mutex> lock(m_);
// nWWaiter_ > 0 implies nWriter_ > 0
while (nWWaiter_ > 0) {
cv_.wait(lock);
}
++nReader_;
}
void unlockReader() {
unique_lock<mutex> lock(m_);
assert(nWriter_ == 0);
assert(nReader_ > 0);
if (--nReader_ == 0) {
// must notify all readers and writers
// as a notified reader may not be able to make progress
// notify threads which are waiting for the above condition
cv_.notify_all();
}
}
void lockWriter() {
unique_lock<mutex> lock(m_);
++nWWaiter_;
while (nWriter_ > 0 || nReader_ > 0) {
cv_.wait(lock);
}
++nWriter_;
// We could have decremented nWWaiter_ at this point; but doing so would not
// readers making progress, as they would still be blocked by this writer.
// So let's delay its execution.
}
void unlockWriter() {
unique_lock<mutex> lock(m_);
assert(nWriter_ == 1);
--nWriter_;
--nWWaiter_;
// notify all readers and writers, as a notified reader may not be able to
// make progress
cv_.notify_all();
}
private:
mutex m_;
condition_variable cv_;
int nReader_{0};
int nWriter_{0};
int nWWaiter_{0};
};
class ReaderWriterLockWriterPreferred {
public:
void lockReader() {
unique_lock<mutex> lock(m_);
// nWWaiter_ > 0 implies nWriter_ > 0
while (nWWaiter_ > 0) {
cvReader_.wait(lock);
}
++nReader_;
}
void unlockReader() {
unique_lock<mutex> lock(m_);
assert(nWriter_ == 0);
assert(nReader_ > 0);
if (--nReader_ == 0) {
// writers are waiting for this condition
cvWriter_.notify_one();
}
}
void lockWriter() {
unique_lock<mutex> lock(m_);
++nWWaiter_;
while (nWriter_ > 0 || nReader_ > 0) {
cvWriter_.wait(lock);
}
++nWriter_;
// We could have decremented nWWaiter_ at this point; but doing so would not
// readers making progress, as they would still be blocked by this writer.
// So let's delay its execution.
}
void unlockWriter() {
unique_lock<mutex> lock(m_);
assert(nWriter_ == 1);
--nWriter_;
--nWWaiter_;
if (nWWaiter_ > 0) {
// notify a reader would not help
// but there is a writer we could notify
cvWriter_.notify_one();
} else {
// no writer waiting currently, so notify all readers (if any).
// note after this point it's still possible for a writer to claim
// `m_` and preempt the notified readers, before the readers can claim the
// lock, but that is fine.
// All note that we must notify all the waiting readers in the queue
// as they can all make progress and if we don't notify all of them,
// they may not be notified in the future at all.
cvReader_.notify_all();
}
}
private:
mutex m_;
// think of them as queues of waiters waiting for a condition to happen
condition_variable cvReader_;
condition_variable cvWriter_;
int nReader_{0};
int nWriter_{0};
int nWWaiter_{0};
};
class Runner {
public:
using Clock = high_resolution_clock;
using Duration = Clock::duration;
void run(int nReader, int nWriter) {
vector<thread> v;
for (int i = 0; i < nReader; ++i) {
v.emplace_back([this]() {
for (int i = 0; i < 100; i++) {
reader();
}
});
}
for (int i = 0; i < nWriter; ++i) {
v.emplace_back([this]() {
for (int i = 0; i < 100; i++) {
writer();
}
});
}
for (auto& t : v) {
t.join();
}
assert(nReader_ == 0);
assert(nWriter_ == 0);
#if 0
cout << "reader: " << duration_cast<milliseconds>(readerDuration_).count()
<< " ms; writer: "
<< duration_cast<milliseconds>(writerDuration_).count() << " ms"
<< endl;
#endif
}
Duration readerDuration() const {
return readerDuration_;
}
Duration writerDuration() const {
return writerDuration_;
}
private:
void reader() {
// delay 0.1 - 100 us
this_thread::sleep_for(nanoseconds(rand() % 1000 * 100));
auto now = Clock::now();
lock_.lockReader();
readerDuration_ += Clock::now() - now;
assert(nWriter_ == 0);
++nReader_;
work();
--nReader_;
lock_.unlockReader();
}
void writer() {
// delay 0.1 - 100 us
this_thread::sleep_for(nanoseconds(rand() % 1000 * 100));
auto now = Clock::now();
lock_.lockWriter();
writerDuration_ += Clock::now() - now;
assert(nWriter_ == 0);
assert(nReader_ == 0);
++nWriter_;
work();
--nWriter_;
lock_.unlockWriter();
}
void work() {
int t = rand() % 1000;
this_thread::sleep_for(nanoseconds(t));
}
ReaderWriterLockReaderPreferredStrongMutex lock_;
Duration readerDuration_{};
Duration writerDuration_{};
atomic<int> nReader_{0};
atomic<int> nWriter_{0};
};
int main() {
int nReader, nWriter;
cin >> nReader >> nWriter;
double ratio = 0;
for (int i = 0; i < 3; ++i) {
Runner runner;
runner.run(nReader, nWriter);
ratio += 1.0 * runner.readerDuration() / runner.writerDuration();
}
cout << ratio / 3 << endl;
}
| [
"[email protected]"
] | |
73ddd4b29abf548a55a3af01e8242201fef76569 | f9c397ee58ed47494f1948de541b56343a75b02b | /MiddleApi/SppuUsbDll/stdafx.cpp | 035364a62c85261381f981b7349e97ffcd70ff93 | [] | no_license | puneetlft2793/puneet_work | cad4742d0e46e6edf8e5b7821b6910c3f9499a0c | 6b912b60b54ccd3fba65deb14b65bd0f402503c3 | refs/heads/master | 2020-03-27T15:14:21.077190 | 2018-09-01T10:10:19 | 2018-09-01T10:10:19 | 146,705,790 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 289 | cpp | // stdafx.cpp : source file that includes just the standard includes
// SppuUsbDll.pch will be the pre-compiled header
// stdafx.obj will contain the pre-compiled type information
#include "stdafx.h"
// TODO: reference any additional headers you need in STDAFX.H
// and not in this file
| [
"[email protected]"
] | |
a8c0c0cd0f6acbac806e9a4fb5a23d8941afd7ee | 91f4ae584d7e8f762f4be0dff60748aa64dd0c00 | /Source/DelayLine.cpp | 81efe2586189c7702790230e67ee5c64e0585bd5 | [] | no_license | hkmogul/LMSNoiseCancellation | 920baa43814b522a8fd3239e0670595156fe30a9 | 3b8f76195f2c8348aa8a538c78d374de33510251 | refs/heads/master | 2020-03-11T05:14:01.036541 | 2018-04-24T20:30:21 | 2018-04-24T20:30:21 | 129,796,575 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 828 | cpp | #include "DelayLine.h"
#include <cstring>
#include <JuceHeader.h>
DelayLine::DelayLine(int len)
{
currentPos = 0;
dLen = len;
memset(buffer, 0, MAXLEN * sizeof(float));
}
float DelayLine::process(float x)
{
int writePos = (currentPos + dLen) % MAXLEN;
buffer[writePos] = x;
float y = buffer[currentPos];
// update read position
currentPos = (currentPos + 1) % MAXLEN;
return y;
}
float DelayLine::readReverse(int idx)
{
// idx = 0 corresponds to write position
// idx = dLen corresponds to read position
// should get buffer[dLen - idx]
// read from end of buffer
if (idx > dLen)
{
return 0.0f;
}
int pos = (currentPos + dLen - idx) % MAXLEN;
return buffer[pos];
}
float DelayLine::read(int idx)
{
int readIdx = (currentPos + idx) % MAXLEN;
return buffer[readIdx];
}
DelayLine::~DelayLine()
{
}
| [
"[email protected]"
] | |
7c7ae93442ed316267a9b561ce71f29679cef745 | 4ac71ef9f0193770844f04b914b496ba0675d6d8 | /Searching/bfs.cpp | c120137a607f83fcc87d022b665930ad1d82119a | [] | no_license | taronegeorage/AlgorithmTraining | 9002d8f7cd6112d63087a60e7b72be4d3e82a2ae | 8f179d6e304a9a0be1530cefab2728152ca92a22 | refs/heads/master | 2021-07-09T17:55:01.408919 | 2020-07-19T17:04:04 | 2020-07-19T17:04:04 | 168,528,260 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,628 | cpp | #include <iostream>
#include <queue>
#include <vector>
#include <iomanip>
using namespace std;
class Graph {
public:
Graph(int num_nodes)
:adj_list(num_nodes), dist(num_nodes, -1){}
void add_edge(int start, int end);
vector<vector<int>> adj_list;
vector<int> dist;
};
void BFS(Graph& g, int source);
void print(const Graph& g);
int main(){
int nodes, edges, source;
cin >> nodes >> edges >> source;
Graph g(nodes);
for(int i = 0; i < edges; i++){
int start, end;
cin >> start >> end;
g.add_edge(start, end);
}
BFS(g, source);
cout << "Source: " << source << endl;
print(g);
return 0;
}
void Graph::add_edge(int start, int end){
adj_list[start].push_back(end);
}
void print(const Graph& g){
cout << "node ids: " << endl;
for(unsigned int i = 0; i < g.adj_list.size(); i++){
cout << setw(3) << i << " ";
}
cout << endl << "distance: ";
for(auto distance : g.dist){
cout << setw(3) << distance << " ";
}
cout << endl;
}
void BFS(Graph& g, int source) {
vector<bool> visited(g.adj_list.size(), false);
queue<int> q;
q.push(source);
// initialize visited and dist vector
visited[source] = true;
g.dist[source] = 0;
while(!q.empty()) {
int cur_node = q.front();
vector<int> cur_node_adj = g.adj_list[cur_node];
// iterate through cur_node's adj_list
for (unsigned int i = 0; i < cur_node_adj.size(); ++i) {
int adj_node = cur_node_adj[i];
if (visited[adj_node] == false) {
visited[adj_node] = true;
g.dist[adj_node] = g.dist[cur_node] + 1;
q.push(adj_node);
}
}
q.pop();
} // end while q is not empty
}
| [
"[email protected]"
] | |
d98a0a97578cbe5cd63c35cc9d9cccb2284df9d9 | d7c2916f674e30ce177c76eeded0ebe17e027d7c | /src/components/config.cpp | f57aae853218834ed2e316a7ba91ae46de5cc410 | [
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | owcz/lemonbuddy | 7a90a3acc806e21babc678ece7a84ff0d1af72d1 | 8758206ba35288f17da633a192d1264aa06d91ef | refs/heads/master | 2020-07-01T10:10:06.253541 | 2016-11-16T11:00:18 | 2016-11-16T11:00:52 | 74,085,948 | 0 | 0 | null | 2016-11-18T02:06:13 | 2016-11-18T02:06:13 | null | UTF-8 | C++ | false | false | 1,712 | cpp | #include "components/config.hpp"
#include "utils/file.hpp"
LEMONBUDDY_NS
/**
* Load configuration and validate bar section
*
* This is done outside the constructor due to boost::di noexcept
*/
void config::load(string file, string barname) {
m_file = file;
m_current_bar = barname;
if (!file_util::exists(file))
throw application_error("Could not find config file: " + file);
try {
boost::property_tree::read_ini(file, m_ptree);
} catch (const std::exception& e) {
throw application_error(e.what());
}
auto bars = defined_bars();
if (std::find(bars.begin(), bars.end(), m_current_bar) == bars.end())
throw application_error("Undefined bar: " + m_current_bar);
if (has_env("XDG_CONFIG_HOME"))
file = string_util::replace(file, read_env("XDG_CONFIG_HOME"), "$XDG_CONFIG_HOME");
if (has_env("HOME"))
file = string_util::replace(file, read_env("HOME"), "~");
m_logger.trace("config: Loaded %s", file);
m_logger.trace("config: Current bar section: [%s]", bar_section());
}
/**
* Get path of loaded file
*/
string config::filepath() const {
return m_file;
}
/**
* Get the section name of the bar in use
*/
string config::bar_section() const {
return "bar/" + m_current_bar;
}
/**
* Get a list of defined bar sections in the current config
*/
vector<string> config::defined_bars() const {
vector<string> bars;
for (auto&& p : m_ptree) {
if (p.first.compare(0, 4, "bar/") == 0)
bars.emplace_back(p.first.substr(4));
}
return bars;
}
/**
* Build path used to find a parameter in the given section
*/
string config::build_path(const string& section, const string& key) const {
return section + "." + key;
}
LEMONBUDDY_NS_END
| [
"[email protected]"
] | |
240f75ad157c5abf1cfaec30fb4c943e23cc664a | c01033791350d8774512719dc355ab3108961010 | /NTupleMaker/bin/AnalysisMacro_ZTauTauMuMu.cpp | 0f064934bf4b72f30bdfd3ef89f884be18649ca1 | [] | no_license | bobovnii/Stau | 6a89180e686785e51d9d65064b569ddb3966c985 | f442a26fb5c5f94190ee45f74f8184dc20861e8d | refs/heads/8020 | 2021-01-11T18:32:12.304538 | 2018-09-28T10:12:23 | 2018-09-28T10:12:23 | 79,561,902 | 1 | 1 | null | 2019-06-06T10:41:09 | 2017-01-20T13:36:42 | C++ | UTF-8 | C++ | false | false | 53,623 | cpp | #include <string>
#include <iostream>
#include <fstream>
#include <cmath>
#include <vector>
#include <sstream>
#include "TFile.h"
#include "TH1.h"
#include "TH2.h"
#include "TGraph.h"
#include "TTree.h"
#include "TROOT.h"
#include "TLorentzVector.h"
#include "TVector3.h"
#include "TRFIOFile.h"
#include "TH1D.h"
#include "TH1D.h"
#include "TChain.h"
#include "TMath.h"
#include "TProfile2D.h"
#include "TLorentzVector.h"
#include "TGraphAsymmErrors.h"
#include "TRandom.h"
#include "DesyTauAnalyses/NTupleMaker/interface/Config.h"
#include "DesyTauAnalyses/NTupleMaker/interface/AC1B.h"
#include "DesyTauAnalyses/NTupleMaker/interface/json.h"
#include "DesyTauAnalyses/NTupleMaker/interface/EventWeight.h"
const float electronMass = 0;
const float muonMass = 0.10565837;
const float pionMass = 0.1396;
int binNumber(float x, int nbins, float * bins) {
int binN = 0;
for (int iB=0; iB<nbins; ++iB) {
if (x>=bins[iB]&&x<bins[iB+1]) {
binN = iB;
break;
}
}
return binN;
}
float effBin(float x, int nbins, float * bins, float * eff) {
int bin = binNumber(x, nbins, bins);
return eff[bin];
}
double cosRestFrame(TLorentzVector boost, TLorentzVector vect) {
double bx = -boost.Px()/boost.E();
double by = -boost.Py()/boost.E();
double bz = -boost.Pz()/boost.E();
vect.Boost(bx,by,bz);
double prod = -vect.Px()*bx-vect.Py()*by-vect.Pz()*bz;
double modBeta = TMath::Sqrt(bx*bx+by*by+bz*bz);
double modVect = TMath::Sqrt(vect.Px()*vect.Px()+vect.Py()*vect.Py()+vect.Pz()*vect.Pz());
double cosinus = prod/(modBeta*modVect);
return cosinus;
}
double QToEta(double Q) {
double Eta = - TMath::Log(TMath::Tan(0.5*Q));
return Eta;
}
double EtaToQ(double Eta) {
double Q = 2.0*TMath::ATan(TMath::Exp(-Eta));
if (Q<0.0) Q += TMath::Pi();
return Q;
}
double PtoEta(double Px, double Py, double Pz) {
double P = TMath::Sqrt(Px*Px+Py*Py+Pz*Pz);
double cosQ = Pz/P;
double Q = TMath::ACos(cosQ);
double Eta = - TMath::Log(TMath::Tan(0.5*Q));
return Eta;
}
double PtoPhi(double Px, double Py) {
return TMath::ATan2(Py,Px);
}
double PtoPt(double Px, double Py) {
return TMath::Sqrt(Px*Px+Py*Py);
}
double dPhiFrom2P(double Px1, double Py1,
double Px2, double Py2) {
double prod = Px1*Px2 + Py1*Py2;
double mod1 = TMath::Sqrt(Px1*Px1+Py1*Py1);
double mod2 = TMath::Sqrt(Px2*Px2+Py2*Py2);
double cosDPhi = prod/(mod1*mod2);
return TMath::ACos(cosDPhi);
}
double deltaEta(double Px1, double Py1, double Pz1,
double Px2, double Py2, double Pz2) {
double eta1 = PtoEta(Px1,Py1,Pz1);
double eta2 = PtoEta(Px2,Py2,Pz2);
double dEta = eta1 - eta2;
return dEta;
}
double deltaR(double Eta1, double Phi1,
double Eta2, double Phi2) {
double Px1 = TMath::Cos(Phi1);
double Py1 = TMath::Sin(Phi1);
double Px2 = TMath::Cos(Phi2);
double Py2 = TMath::Sin(Phi2);
double dPhi = dPhiFrom2P(Px1,Py1,Px2,Py2);
double dEta = Eta1 - Eta2;
double dR = TMath::Sqrt(dPhi*dPhi+dEta*dEta);
return dR;
}
double PtEtaToP(double Pt, double Eta) {
// double Q = EtaToQ(Eta);
//double P = Pt/TMath::Sin(Q);
double P = Pt*TMath::CosH(Eta);
return P;
}
double Px(double Pt, double Phi){
double Px=Pt*TMath::Cos(Phi);
return Px;
}
double Py(double Pt, double Phi){
double Py=Pt*TMath::Sin(Phi);
return Py;
}
double Pz(double Pt, double Eta){
double Pz=Pt*TMath::SinH(Eta);
return Pz;
}
double InvariantMass(double energy,double Px,double Py, double Pz){
double M_2=energy*energy-Px*Px-Py*Py-Pz*Pz;
double M=TMath::Sqrt(M_2);
return M;
}
double EFromPandM0(double M0,double Pt,double Eta){
double E_2=M0*M0+PtEtaToP(Pt,Eta)*PtEtaToP(Pt,Eta);
double E =TMath::Sqrt(E_2);
return E;
}
bool electronMvaIdTight(float eta, float mva) {
float absEta = fabs(eta);
bool passed = false;
if (absEta<0.8) {
if (mva>0.73) passed = true;
}
else if (absEta<1.479) {
if (mva>0.57) passed = true;
}
else {
if (mva>0.05) passed = true;
}
return passed;
}
bool electronMvaIdLoose(float eta, float mva) {
float absEta = fabs(eta);
bool passed = false;
if (absEta<0.8) {
if (mva>0.35) passed = true;
}
else if (absEta<1.479) {
if (mva>0.20) passed = true;
}
else {
if (mva>-0.52) passed = true;
}
return passed;
}
bool electronMvaIdWP80(float pt, float eta, float mva) {
float absEta = fabs(eta);
bool passed = false;
if (absEta<0.8) {
if (pt<10)
passed = mva > -0.253;
else
passed = mva > 0.965;
}
else if (absEta<1.479) {
if (pt<10)
passed = mva > 0.081;
else
passed = mva > 0.917;
}
else {
if (pt<10)
passed = mva > -0.081;
else
passed = mva > 0.683;
}
return passed;
}
bool electronMvaIdWP90(float pt, float eta, float mva) {
float absEta = fabs(eta);
bool passed = false;
if (absEta<0.8) {
if (pt<10)
passed = mva > -0.483;
else
passed = mva > 0.933;
}
else if (absEta<1.479) {
if (pt<10)
passed = mva > -0.267;
else
passed = mva > 0.825;
}
else {
if (pt<10)
passed = mva > -0.323;
else
passed = mva > 0.337;
}
return passed;
}
struct myclass {
bool operator() (int i,int j) { return (i<j);}
} myobject, myobjectX;
int main(int argc, char * argv[]) {
// first argument - config file
// second argument - filelist
using namespace std;
// **** configuration
Config cfg(argv[1]);
const bool isData = cfg.get<bool>("IsData");
//PUreweighting
const bool applyPUreweighting = cfg.get<bool>("ApplyPUreweighting");
const bool applyMEtRecoilCorrections = cfg.get<bool>("ApplyMEtRecoilCorrections");
const bool applyLeptonSF = cfg.get<bool>("ApplyLeptonSF");
// kinematic cuts on muons
const float ptMuonLowCut = cfg.get<float>("ptMuonLowCut");
const float ptMuonHighCut = cfg.get<float>("ptMuonHighCut");
const float etaMuonHighCut = cfg.get<float>("etaMuonHighCut");
const float etaMuonLowCut = cfg.get<float>("etaMuonLowCut");
const float dxyMuonCut = cfg.get<float>("dxyMuonCut");
const float dzMuonCut = cfg.get<float>("dzMuonCut");
const float isoMuonCut = cfg.get<float>("isoMuonCut");
const bool applyTauTauSelection = cfg.get<bool>("ApplyTauTauSelection");
const bool selectZToTauTauMuMu = cfg.get<bool>("SelectZToTauTauMuMu");
// topological cuts
const float dRleptonsCut = cfg.get<float>("dRleptonsCut");
const float DRTrigMatch = cfg.get<float>("DRTrigMatch");
const bool oppositeSign = cfg.get<bool>("OppositeSign");
// trigger
const bool doubleMuonTrigger = cfg.get<bool>("DoubleMuonTrigger");
const string muonTriggerName = cfg.get<string>("MuonTriggerName");
const string muonFilterName = cfg.get<string>("MuonFilterName");
const string doubleMuonHighPtFilterName = cfg.get<string>("DoubleMuonHighPtFilterName");
const string doubleMuonLowPtFilterName = cfg.get<string>("DoubleMuonLowPtFilterName");
TString MuonTriggerName(muonTriggerName);
TString MuonFilterName(muonFilterName);
TString DoubleMuonHighPtFilterName(doubleMuonHighPtFilterName);
TString DoubleMuonLowPtFilterName(doubleMuonLowPtFilterName);
// vertex cuts
const float ndofVertexCut = cfg.get<float>("NdofVertexCut");
const float zVertexCut = cfg.get<float>("ZVertexCut");
const float dVertexCut = cfg.get<float>("DVertexCut");
// jet related cuts
const float jetEtaCut = cfg.get<float>("JetEtaCut");
const float jetEtaTrkCut = cfg.get<float>("JetEtaTrkCut");
const float jetPtHighCut = cfg.get<float>("JetPtHighCut");
const float jetPtLowCut = cfg.get<float>("JetPtLowCut");
const float dRJetLeptonCut = cfg.get<float>("dRJetLeptonCut");
// vertex distributions filenames and histname
const string vertDataFileName = cfg.get<string>("VertexDataFileName");
const string vertMcFileName = cfg.get<string>("VertexMcFileName");
const string vertHistName = cfg.get<string>("VertexHistName");
const string recoilFileName = cfg.get<string>("RecoilFileName");
TString RecoilFileName(recoilFileName);
//Run-lumi selector
const string jsonFile = cfg.get<string>("jsonFile");
// lepton scale factors
const string muonSfData = cfg.get<string>("MuonSfData");
const string muonSfMC = cfg.get<string>("MuonSfMC");
// Run range
const unsigned int RunRangeMin = cfg.get<unsigned int>("RunRangeMin");
const unsigned int RunRangeMax = cfg.get<unsigned int>("RunRangeMax");
const bool fillBDTNTuple = cfg.get<bool>("FillBDTNTuple");
// **** end of configuration
string cmsswBase = (getenv ("CMSSW_BASE"));
TString fullDir = TString(cmsswBase)+TString("/src/DesyTauAnalyses/NTupleMaker/data/");
//Run-lumi selector
// std:: vector<Period> periods;
// string fullPathToJsonFile = cmsswBase + "/src/DesyTauAnalyses/NTupleMaker/test/json/" + jsonFile;
int nDPtBins = 9;
float DPtBins[10] = {0,10,15,20,25,30,40,50,60,1000};
TString dPtBins[9] = {"Pt0to10",
"Pt10to15",
"Pt15to20",
"Pt20to25",
"Pt25to30",
"Pt30to40",
"Pt40to50",
"Pt50to60",
"PtGt60"};
int nDEtaBins = 4;
float DEtaBins[5]= {0,0.9,1.2,2.1,2.4};
TString dEtaBins[4] = {"Eta0to0p9",
"Eta0p9to1p2",
"Eta1p2to2p1",
"Eta2p1to2p4"};
TH1D * dxyMu1[4][9];
TH1D * dxyMu2[4][9];
TH1D * dzMu1[4][9];
TH1D * dzMu2[4][9];
/*
TH1D * dxyMu1_m70to110[5][9];
TH1D * dxyMu2_m70to110[5][9];
TH1D * dzMu1_m70to110[5][9];
TH1D * dzMu2_m70to110[5][9];
*/
EventWeight * eventWeight = new EventWeight(fullDir);
int nJetBins = 3;
int nZPtBins = 5;
float zPtBins[6] = {0,10,20,30,50,1000};
TString NJetBins[3] = {"NJet0","NJet1","NJetGe2"};
TString ZPtBins[5] = {"Pt0to10H",
"Pt10to20H",
"Pt20to30H",
"Pt30to50H",
"PtGt50H"};
TH1D * recoilZParalH[3];
TH1D * recoilZPerpH[3];
TH1D * recoilZParal_Ptbins_nJetsH[3][5];
TH1D * recoilZPerp_Ptbins_nJetsH[3][5];
TH1D * ptRatio_nJetsH[3];
TString RecoilZParal("recoilZParal_");
TString RecoilZPerp("recoilZPerp_");
eventWeight->InitMEtWeights(RecoilFileName,
RecoilZPerp,
RecoilZParal,
nZPtBins,
zPtBins,
ZPtBins,
nJetBins,
NJetBins);
// reading vertex weights
TFile * fileDataNVert = new TFile(fullDir+vertDataFileName);
TFile * fileMcNVert = new TFile(fullDir+vertMcFileName);
bool vertexFileFound = true;
if (fileDataNVert->IsZombie()) {
// std::cout << "File " << fullDir << vertDataFileName << " is not found" << std::endl;
vertexFileFound = false;
}
if (fileMcNVert->IsZombie()) {
// std::cout << "File " << fullDir << vertMcFileName << " is not found" << std::endl;
vertexFileFound = false;
}
if (!vertexFileFound)
exit(-1);
TH1D * vertexDataH = (TH1D*)fileDataNVert->Get(TString(vertHistName));
TH1D * vertexMcH = (TH1D*)fileMcNVert->Get(TString(vertHistName));
if (vertexDataH==NULL||vertexMcH==NULL) {
std::cout << "Vertex distribution histogram " << vertHistName << " is not found" << std::endl;
exit(-1);
}
float normVertexData = vertexDataH->GetSumOfWeights();
float normVertexMc = vertexMcH->GetSumOfWeights();
vertexDataH->Scale(1/normVertexData);
vertexMcH->Scale(1/normVertexMc);
int nPtBins = 7;
float ptBins[8] = {10,15,20,25,30,40,60,1000};
int nEtaBins = 3;
float etaBins[4] = {-0.1,0.9,1.2,2.4};
TString PtBins[7] = {"Pt10to15",
"Pt15to20",
"Pt20to25",
"Pt25to30",
"Pt30to40",
"Pt40to60",
"PtGt60"};
TString EtaBins[3] = {"EtaLt0p9",
"Eta0p9to1p2",
"EtaGt1p2"};
TFile *fdata = new TFile(fullDir+muonSfData);
TFile *fmc = new TFile(fullDir+muonSfMC);
if (fdata->IsZombie()) {
// std::cout << "Muon efficiency file " << fullDir << muonSfData << " does not exist" << std::endl;
exit(-1);
}
if (fmc->IsZombie()) {
// std::cout << "Muon efficiency file " << fullDir << muonSfMC << " does not exist" << std::endl;
exit(-1);
}
float mueffData[3][10];
float mueffMC[3][10];
float mueffSF[3][10];
int nPtBinsSF = nPtBins;
float ptBinsSF[10];
for (int iEta=0; iEta<3; ++iEta) {
TGraphAsymmErrors* hEffDataEtaBin = (TGraphAsymmErrors*)fdata->Get("ZMass"+EtaBins[iEta]);
TGraphAsymmErrors* hEffMCEtaBin = (TGraphAsymmErrors*)fmc->Get("ZMass"+EtaBins[iEta]);
if (hEffDataEtaBin==NULL || hEffMCEtaBin==NULL) {
std::cout << "Efficiency graph ZMass" << EtaBins[iEta] << " not found" << std::endl;
exit(-1);
}
double * effData = new double[10];
double * effMC = new double[10];
double * xbins = new double[10];
double * exbins = new double[10];
effData = hEffDataEtaBin->GetY();
effMC = hEffMCEtaBin->GetY();
xbins = hEffDataEtaBin->GetX();
exbins = hEffDataEtaBin->GetEXhigh();
nPtBinsSF = hEffDataEtaBin->GetN();
for (int iPt=0; iPt<nPtBinsSF;++iPt) {
mueffData[iEta][iPt] = float(effData[iPt]);
mueffMC[iEta][iPt] = float(effMC[iPt]);
mueffSF[iEta][iPt] = mueffData[iEta][iPt]/mueffMC[iEta][iPt];
if (iEta==0) {
ptBinsSF[iPt] = (xbins[iPt] - exbins[iPt]);
}
}
}
ptBinsSF[nPtBinsSF] = 1000000;
/*
// Run-lumi selector
std::vector<Period> periods;
std::fstream inputFileStream("temp", std::ios::in);
for(std::string s; std::getline(inputFileStream, s); )
{
periods.push_back(Period());
std::stringstream ss(s);
ss >> periods.back();
}
*/ //This part is commented out, since we using direct jsonfiles
// file name and tree name
std::string rootFileName(argv[2]);
std::ifstream fileList(argv[2]);
std::ifstream fileList0(argv[2]);
std::string ntupleName("makeroottree/AC1B");
TString TStrName(rootFileName);
std::cout <<TStrName <<std::endl;
TFile * file = new TFile(TStrName+TString(".root"),"recreate");
file->cd("");
TH1D * inputEventsH = new TH1D("inputEventsH","",1,-0.5,0.5);
TH1D * histWeightsH = new TH1D("histWeightsH","",1,-0.5,0.5);
// Histograms after selecting unique dimuon pair
TH1D * ptLeadingMuSelH = new TH1D("ptLeadingMuSelH","",100,0,200);
TH1D * ptTrailingMuSelH = new TH1D("ptTrailingMuSelH","",100,0,200);
TH2F * ptScatter =new TH2F("ptScatter","",100,0,200,100,0,200);
TProfile2D *hprof2D_pt = new TProfile2D("hprof2D_pt","",100,0,200,100,0,200);
TH1D * etaLeadingMuSelH = new TH1D("etaLeadingMuSelH","",50,-2.5,2.5);
TH1D * etaTrailingMuSelH = new TH1D("etaTrailingMuSelH","",50,-2.5,2.5);
TH1D * massSelH = new TH1D("massSelH","",200,0,200);
TH1D * metSelH = new TH1D("metSelH","",200,0,400);
TH1D * nJets30SelH = new TH1D("nJets30SelH","",11,-0.5,10.5);
TH1D * nJets30etaCutSelH = new TH1D("nJets30etaCutSelH","",11,-0.5,10.5);
TH1D * nJets20SelH = new TH1D("nJets20SelH","",11,-0.5,10.5);
TH1D * nJets20etaCutSelH = new TH1D("nJets20etaCutSelH","",11,-0.5,10.5);
TH1D * HT30SelH = new TH1D("HT30SelH","",50,0,500);
TH1D * HT30etaCutSelH = new TH1D("HT30etaCutSelH","",50,0,500);
TH1D * HT20SelH = new TH1D("HT20SelH","",50,0,500);
TH1D * HT20etaCutSelH = new TH1D("HT20etaCutSelH","",50,0,500);
//Discriminiant histos
TH1D * h_dimuonEta = new TH1D("dimuonEta","",50,-6,+6);//21Aug
// TH1D * h_dimuonEta_genMuMatch = new TH1D("dimuonEta_genMuMatch","",50,-6,+6);//21Aug
TH1D * h_ptRatio = new TH1D ("ptRatio","",50,0,1);
TH1D * h_ptRatio_test = new TH1D ("ptRatio_test","",50,0,1);
TH1D * h_dxy_muon1 =new TH1D ("dxy_muon1","",50,-0.02,0.02);
TH1D * h_dxy_muon2 =new TH1D ("dxy_muon2","",50,-0.02,0.02);
TH1D * h_dz_muon1 = new TH1D ("dz_muon1","",50,-0.1,0.1);
TH1D * h_dz_muon2 = new TH1D ("dz_muon2","",50,-0.1,0.1);
TH1D * h_dxy_mu1_mlt70 =new TH1D ("dxy_m1_mlt70","",50,-0.02,0.02);
TH1D * h_dxy_mu2_mlt70 =new TH1D ("dxy_mu2_mlt70","",50,-0.02,0.02);
TH1D * h_dz_mu1_mlt70 = new TH1D ("dz_mu1_mlt70","",50,-0.1,0.1);
TH1D * h_dz_mu2_mlt70 = new TH1D ("dz_mu2_mlt70","",50,-0.1,0.1);
TH1D * h_dxy_mu1_mgt70 =new TH1D ("dxy_m1_mgt70","",50,-0.02,0.02);
TH1D * h_dxy_mu2_mgt70 =new TH1D ("dxy_mu2_mgt70","",50,-0.02,0.02);
TH1D * h_dz_mu1_mgt70 = new TH1D ("dz_mu1_mgt70","",50,-0.1,0.1);
TH1D * h_dz_mu2_mgt70 = new TH1D ("dz_mu2_mgt70","",50,-0.1,0.1);
// TH1D * h_dcaSigdxy_mu1 = new TH1D ("dcaSigdxy_mu1","",50,-12,12);
//TH1D * h_dcaSigdxy_mu2 = new TH1D ("dcaSigdxy_mu2","",50,-12,12);
//TH1D * h_dcaSigdz_mu1 = new TH1D ("dcaSigdz_mu1","",50,-12,12);
//TH1D * h_dcaSigdz_mu2 = new TH1D ("dcaSigdz_mu2","",50,-12,12);
TH1D * h_dcaSigdxy_muon1 = new TH1D ("dcaSigdxy_muon1","",50,-4,4);
TH1D * h_dcaSigdxy_muon2 = new TH1D ("dcaSigdxy_muon2","",50,-4,4);
TH1D * h_dcaSigdz_muon1 = new TH1D ("dcaSigdz_muon1","",50,-4,4);
TH1D * h_dcaSigdz_muon2 = new TH1D ("dcaSigdz_muon2","",50,-4,4);
//TH1D * h_dcaSigdxy_mu1_genMuMatch = new TH1D ("dcaSigdxy_mu1_genMuMatch","",50,-4,4);
//TH1D * h_dcaSigdxy_mu2_genMuMatch = new TH1D ("dcaSigdxy_mu2_genMuMatch","",50,-4,4);
// TH1D * h_dcaSigdz_mu1_genMuMatch = new TH1D ("dcaSigdz_mu1_genMuMatch","",50,-4,4);
//TH1D * h_dcaSigdz_mu2_genMuMatch = new TH1D ("dcaSigdz_mu2_genMuMatch","",50,-4,4);
TH1D * h_phi_leadingMu_MET =new TH1D ("phi_leadingMu_MET","",50,0,3);
TH1D * h_phi_trailingMu_MET =new TH1D ("phi_trailingMu_MET","",50,0,3);
TH1D * h_phi_PosMu_MET =new TH1D ("phi_PosMu_MET","",50,0,3);
TH1D * h_phi_TwoMu = new TH1D ("phi_TwoMu","",50,0,3);
//TH1D * h_dxy_muon1_dcaCut =new TH1D ("dxy_muon1_dcaCut","",50,-0.02,0.02);
//TH1D * h_dxy_muon2_dcaCut =new TH1D ("dxy_muon2_dcaCut","",50,-0.02,0.02);
//TH1D * h_dimuonEta_dcaCut = new TH1D("dimuonEta_dcaCut","",50,-6,+6);
//TH1D * h_ptRatio_dcaCut = new TH1D ("ptRatio_dcaCut","",50,0,1);
TH1D * h_DZeta = new TH1D("DZeta","",100,-400,200);
TH1D * h_Njets = new TH1D("Njets","",100,0,10);
//Booking variables in Tree for BDT training
Float_t n_genWeight;
Float_t n_dimuonEta;
Float_t n_ptRatio;
Float_t n_dcaSigdxy1;
Float_t n_dcaSigdxy2;
Float_t n_phiangle;
Float_t n_twomuPhi;
Float_t n_dxy_muon1;
Float_t n_dxy_muon2;
Float_t n_dz_muon1;
Float_t n_dz_muon2;
//Float_t n_dcaSigdxy_mu1;
//Float_t n_dcaSigdxy_mu2;
Float_t n_dcaSigdz1;
Float_t n_dcaSigdz2;
//Float_t n_dcaSigdz_mu1;
//Float_t n_dcaSigdz_mu2;
Float_t n_MissingEt;
Float_t n_DZeta;
Float_t n_dimuonMass; Float_t n_met;
Float_t genWeight;
TTree * TW = new TTree("TW","Weights");
TW->Branch("genWeight",&genWeight,"genWeight/F");
TTree * T = new TTree("T","Discriminant variables for BDT");
T->Branch("dimuonEta",&n_dimuonEta,"n_dimuonEta/F");
T->Branch("ptRatio",&n_ptRatio,"n_ptRatio/F");
T->Branch("dxy_muon1",&n_dxy_muon1,"n_dxy_muon1/F");
T->Branch("dxy_muon2",&n_dxy_muon2,"n_dxy_muon2/F");
T->Branch("dz_muon1",&n_dz_muon1,"n_dz_muon1/F");
T->Branch("dz_muon2",&n_dz_muon2,"n_dz_muon2/F");
T->Branch("dcaSigdxy_muon1",&n_dcaSigdxy1,"n_dcaSigdxy1/F");
T->Branch("dcaSigdxy_muon2",&n_dcaSigdxy2,"n_dcaSigdxy2/F");
// T->Branch("dcaSigdxy_m1",&n_dcaSigdxy_mu1,"n_dcaSigdxy_mu1/F");
// T->Branch("dcaSigdxy_mu2",&n_dcaSigdxy_mu2,"n_dcaSigdxy_mu2/F");
T->Branch("dcaSigdz_muon1",&n_dcaSigdz1,"n_dcaSigdz1/F");
T->Branch("dcaSigdz_muon2",&n_dcaSigdz2,"n_dcaSigdz2/F");
//T->Branch("dcaSigdz_m1",&n_dcaSigdz_mu1,"n_dcaSigdz_mu1/F");
//T->Branch("dcaSigdz_mu2",&n_dcaSigdz_mu2,"n_dcaSigdz_mu2/F");
T->Branch("MissingET",&n_MissingEt,"n_MissingEt/F");
T->Branch("phi_PosMu_MET",&n_phiangle, "n_phiangle/F");
T->Branch("phi_TwoMu",&n_twomuPhi,"n_twomuPhi/F");
T->Branch("DZeta",&n_DZeta,"n_DZeta/F");
T->Branch("genWeight",&n_genWeight,"n_genWeight/F");
T->Branch("dimuonMass",&n_dimuonMass,"n_dimuonMass/F");
T->Branch("met",&n_met,"n_met/F");
TH1D * NumberOfVerticesH = new TH1D("NumberOfVerticesH","",50,-0.5,50.5);
TH1D * ZMassEtaPtPass[3][7];
TH1D * ZMassEtaPtFail[3][7];
for (int iEta=0; iEta<nEtaBins; ++iEta) {
for (int iPt=0; iPt<nPtBins; ++iPt) {
ZMassEtaPtPass[iEta][iPt] = new TH1D("ZMass"+EtaBins[iEta]+PtBins[iPt]+"Pass","",60,60,120);
ZMassEtaPtFail[iEta][iPt] = new TH1D("ZMass"+EtaBins[iEta]+PtBins[iPt]+"Fail","",60,60,120);
}
}
for (int iBin=0; iBin<nJetBins; ++iBin) {
recoilZParalH[iBin] = new TH1D(RecoilZParal+NJetBins[iBin]+"H","",100,-200,200);
recoilZPerpH[iBin] = new TH1D(RecoilZPerp+NJetBins[iBin]+"H","",100,-200,200);
}
for (int iJets=0; iJets<nJetBins; ++iJets) {
for (int iPtBins=0; iPtBins<nZPtBins; ++iPtBins){
recoilZParal_Ptbins_nJetsH[iJets][iPtBins] = new TH1D(RecoilZParal+NJetBins[iJets]+ZPtBins[iPtBins],"",100,-200,200);
recoilZPerp_Ptbins_nJetsH[iJets][iPtBins] = new TH1D(RecoilZPerp+NJetBins[iJets]+ZPtBins[iPtBins],"",100,-200,200);
}
}
for (int iJetBin=0; iJetBin<nJetBins; ++iJetBin) {
ptRatio_nJetsH[iJetBin]= new TH1D("ptRatio_nJets"+NJetBins[iJetBin]+"H","",100,0,1);
}
for (int iEta=0; iEta<nDEtaBins; ++iEta){
for (int iPt=0; iPt<nDPtBins; ++iPt){
std::cout<< "iEta =" <<iEta<< " and iPt =" << iPt<<std::endl;
dxyMu1[iEta][iPt]= new TH1D("dxyMu1_"+dEtaBins[iEta]+"_"+dPtBins[iPt],"",50,-0.02,0.02);
dxyMu2[iEta][iPt]= new TH1D("dxyMu2_"+dEtaBins[iEta]+"_"+dPtBins[iPt],"",50,-0.02,0.02);
dzMu1[iEta][iPt]= new TH1D("dzMu1_"+dEtaBins[iEta]+"_"+dPtBins[iPt],"",50,-0.2,0.2);
dzMu2[iEta][iPt]= new TH1D("dzMu2_"+dEtaBins[iEta]+"_"+dPtBins[iPt],"",50,-0.2,0.2);
/*
dxyMu1_m70to110[iEta][iPt]= new TH1D("dxyMu1_m70to110"+dEtaBins[iEta]+dPtBins[iPt],"",50,-0.02,0.02);
dxyMu2_m70to110[iEta][iPt]= new TH1D("dxyMu2_m70to110"+dEtaBins[iEta]+dPtBins[iPt],"",50,-0.02,0.02);
dzMu1_m70to110[iEta][iPt]= new TH1D("dzMu1_m70to110"+dEtaBins[iEta]+dPtBins[iPt],"",50,-0.2,0.2);
dzMu2_m70to110[iEta][iPt]= new TH1D("dzMu2_m70to110"+dEtaBins[iEta]+dPtBins[iPt],"",50,-0.2,0.2);
*/
}
}
int nFiles = 0;
int nEvents = 0;
int selEventsAllMuons = 0;
int selEventsIdMuons = 0;
int selEventsIsoMuons = 0;
int nTotalFiles = 0;
std::string dummy;
// count number of files --->
while (fileList0 >> dummy) nTotalFiles++;
unsigned int RunMin = 9999999;
unsigned int RunMax = 0;
std::vector<unsigned int> allRuns; allRuns.clear();
//----Attention----//
//if(XSec!=1) nTotalFiles=20;
//nTotalFiles=5;
for (int iF=0; iF<nTotalFiles; ++iF) {
std::string filen;
fileList >> filen;
std::cout << "file " << iF+1 << " out of " << nTotalFiles << " filename : " << filen << std::endl;
TFile * file_ = TFile::Open(TString(filen));
TTree * _tree = NULL;
_tree = (TTree*)file_->Get(TString(ntupleName));
if (_tree==NULL) continue;
TH1D * histoInputEvents = NULL;
histoInputEvents = (TH1D*)file_->Get("makeroottree/nEvents");
if (histoInputEvents==NULL) continue;
int NE = int(histoInputEvents->GetEntries());
std::cout << " number of input events = " << NE << std::endl;
for (int iE=0;iE<NE;++iE)
inputEventsH->Fill(0.);
AC1B analysisTree(_tree);
Long64_t numberOfEntries = analysisTree.GetEntries();
std::cout << " number of entries in Tree = " << numberOfEntries << std::endl;
for (Long64_t iEntry=0; iEntry<numberOfEntries; iEntry++) {
analysisTree.GetEntry(iEntry);
nEvents++;
if (nEvents%10000==0)
cout << " processed " << nEvents << " events" << endl;
float weight = 1;
float pfmet_ex = analysisTree.pfmet_ex;
float pfmet_ey = analysisTree.pfmet_ey;
float pfmet_phi = analysisTree.pfmet_phi;
//------------------------------------------------
if (!isData) {
genWeight = 1;
if (analysisTree.genweight<0)
genWeight = -1;
// std::cout << "GenWeight = " << analysisTree.genweight << std::endl;
weight *= genWeight;
TW->Fill();
}
histWeightsH->Fill(float(0),weight);
if (!isData) {
if (applyPUreweighting) {
int binNvert = vertexDataH->FindBin(analysisTree.primvertex_count);
float_t dataNvert = vertexDataH->GetBinContent(binNvert);
float_t mcNvert = vertexMcH->GetBinContent(binNvert);
if (mcNvert < 1e-10){mcNvert=1e-10;}
float_t vertWeight = dataNvert/mcNvert;
weight *= vertWeight;
// cout << "NVert = " << analysisTree.primvertex_count << " weight = " << vertWeight << endl;
}
if (applyTauTauSelection) {
unsigned int nTaus = 0;
if (analysisTree.gentau_count>0) {
// cout << "Generated taus present" << endl;
for (unsigned int itau = 0; itau < analysisTree.gentau_count; ++itau) {
// cout << itau << " : pt = "
// << analysisTree.gentau_visible_pt[itau]
// << " eta = " << analysisTree.gentau_visible_eta[itau]
// << " mother = " << int(analysisTree.gentau_mother[itau]) << endl;
if (int(analysisTree.gentau_mother[itau])==3) nTaus++;
}
}
bool notTauTau = nTaus < 2;
// std::cout << "nTaus = " << nTaus << std::endl;
if (selectZToTauTauMuMu&¬TauTau) {
// std::cout << "Skipping event..." << std::endl;
// cout << endl;
continue;
}
if (!selectZToTauTauMuMu&&!notTauTau) {
// std::cout << "Skipping event..." << std::endl;
// cout << endl;
continue;
}
// cout << endl;
}
}
std:: vector<Period> periods;
string fullPathToJsonFile = cmsswBase + "/src/DesyTauAnalyses/NTupleMaker/test/json/" + jsonFile;
if (isData){
std:: fstream inputFileStream(fullPathToJsonFile.c_str(), std::ios::in);
if (inputFileStream.fail()) {
std:: cout << "Error: cannot find json file " << fullPathToJsonFile <<
std::endl;
std:: cout << "please check" << std::endl;
std:: cout << "quitting program" << std::endl;
exit(-1);
}
for(std::string s; std::getline(inputFileStream, s); )
{
periods.push_back(Period());
std:: stringstream ss(s);
ss >> periods.back();
}
bool lumi = false;
int n=analysisTree.event_run;
int lum = analysisTree.event_luminosityblock;
std::string num = std::to_string(n);
std::string lnum = std::to_string(lum);
for(const auto& a : periods)
{
if ( num.c_str() == a.name ) {
//std::cout<< " Eureka "<<num<<" "<<a.name<<" ";
// std::cout <<"min "<< last->lower << "- max last " << last->bigger << std::endl;
for(auto b = a.ranges.begin(); b != std::prev(a.ranges.end()); ++b) {
// cout<<b->lower<<" "<<b->bigger<<endl;
if (lum >= b->lower && lum <= b->bigger ) lumi = true;
}
auto last = std::prev(a.ranges.end());
// std::cout <<"min "<< last->lower << "- max last " << last->bigger << std::endl;
if ( (lum >=last->lower && lum <= last->bigger )) lumi=true;
}
}
if (!lumi) continue;
//if (lumi ) cout<<" ============= Found good run"<<" "<<n<<" "<<lum<<endl;
//std::remove("myinputfile");
}
if (analysisTree.event_run<RunMin)
RunMin = analysisTree.event_run;
if (analysisTree.event_run>RunMax)
RunMax = analysisTree.event_run;
//std::cout << " Run : " << analysisTree.event_run << std::endl;
bool isNewRun = true;
if (allRuns.size()>0) {
for (unsigned int iR=0; iR<allRuns.size(); ++iR) {
if (analysisTree.event_run==allRuns.at(iR)) {
isNewRun = false;
break;
}
}
}
if (isNewRun)
allRuns.push_back(analysisTree.event_run);
bool isTriggerMuon = false;
for (std::map<string,int>::iterator it=analysisTree.hltriggerresults->begin(); it!=analysisTree.hltriggerresults->end(); ++it) {
TString trigName(it->first);
if (trigName.Contains(MuonTriggerName)) {
if (it->second==1)
isTriggerMuon = true;
}
}
if (!isTriggerMuon) continue;
unsigned int nMuonFilter = 0;
bool isMuonFilter = false;
unsigned int nDoubleMuonHighPtFilter = 0;
bool isDoubleMuonHighPtFilter = false;
unsigned int nDoubleMuonLowPtFilter = 0;
bool isDoubleMuonLowPtFilter = false;
unsigned int nfilters = analysisTree.run_hltfilters->size();
for (unsigned int i=0; i<nfilters; ++i) {
TString HLTFilter(analysisTree.run_hltfilters->at(i));
if (HLTFilter==MuonFilterName) {
nMuonFilter = i;
isMuonFilter = true;
}
if (HLTFilter==DoubleMuonHighPtFilterName) {
nDoubleMuonHighPtFilter = i;
isDoubleMuonHighPtFilter = true;
}
if (HLTFilter==DoubleMuonLowPtFilterName) {
nDoubleMuonLowPtFilter = i;
isDoubleMuonLowPtFilter = true;
}
}
if (!isMuonFilter) {
cout << "Filter " << MuonFilterName << " not found " << endl;
exit(-1);
}
if (!isDoubleMuonHighPtFilter) {
cout << "Filter " << DoubleMuonHighPtFilterName << " not found " << endl;
exit(-1);
}
if (!isDoubleMuonLowPtFilter) {
cout << "Filter " << DoubleMuonLowPtFilterName << " not found " << endl;
exit(-1);
}
// vertex cuts
if (fabs(analysisTree.primvertex_z)>zVertexCut) continue;
if (analysisTree.primvertex_ndof<ndofVertexCut) continue;
float dVertex = (analysisTree.primvertex_x*analysisTree.primvertex_x+
analysisTree.primvertex_y*analysisTree.primvertex_y);
if (dVertex>dVertexCut) continue;
// muon selection
vector<unsigned int> allMuons; allMuons.clear();
vector<unsigned int> idMuons; idMuons.clear();
vector<unsigned int> isoMuons; isoMuons.clear();
vector<float> isoMuonsValue; isoMuonsValue.clear();
vector<bool> isMuonPassedIdIso; isMuonPassedIdIso.clear();
for (unsigned int im = 0; im<analysisTree.muon_count; ++im) {
allMuons.push_back(im);
bool muPassed = true;
if (analysisTree.muon_pt[im]<ptMuonLowCut) muPassed = false;
if (fabs(analysisTree.muon_eta[im])>etaMuonLowCut) muPassed = false;
if (fabs(analysisTree.muon_dxy[im])>dxyMuonCut) muPassed = false;
if (fabs(analysisTree.muon_dz[im])>dzMuonCut) muPassed = false;
if (!analysisTree.muon_isMedium[im]) muPassed = false;
if (muPassed) idMuons.push_back(im);
float absIso = analysisTree.muon_r03_sumChargedHadronPt[im];
float neutralIso = analysisTree.muon_r03_sumNeutralHadronEt[im] +
analysisTree.muon_r03_sumPhotonEt[im] -
0.5*analysisTree.muon_r03_sumPUPt[im];
neutralIso = TMath::Max(float(0),neutralIso);
absIso += neutralIso;
float relIso = absIso/analysisTree.muon_pt[im];
if (relIso>isoMuonCut) muPassed = false;
if (muPassed) {
isoMuons.push_back(im);
isoMuonsValue.push_back(relIso);
}
// cout << "pt:" << analysisTree.muon_pt[im] << " passed:" << muPassed << endl;
isMuonPassedIdIso.push_back(muPassed);
}
unsigned int indx1 = 0;
unsigned int indx2 = 0;
bool isIsoMuonsPair = false;
float isoMin = 9999;
if (isoMuons.size()>0) {
for (unsigned int im1=0; im1<isoMuons.size(); ++im1) {
unsigned int index1 = isoMuons[im1];
bool isMu1matched = false;
bool isMu1HighPtmatched = false;
bool isMu1LowPtmatched = false;
for (unsigned int iT=0; iT<analysisTree.trigobject_count; ++iT) {
float dRtrig = deltaR(analysisTree.muon_eta[index1],analysisTree.muon_phi[index1],
analysisTree.trigobject_eta[iT],analysisTree.trigobject_phi[iT]);
if (dRtrig>DRTrigMatch) continue;
if (analysisTree.trigobject_filters[iT][nMuonFilter] &&
analysisTree.muon_pt[index1] > ptMuonHighCut &&
fabs(analysisTree.muon_eta[index1]) < etaMuonHighCut)
isMu1matched = true;
if (analysisTree.trigobject_filters[iT][nDoubleMuonHighPtFilter] &&
analysisTree.muon_pt[index1] > ptMuonHighCut &&
fabs(analysisTree.muon_eta[index1]) < etaMuonHighCut)
isMu1HighPtmatched = true;
if (analysisTree.trigobject_filters[iT][nDoubleMuonLowPtFilter] &&
analysisTree.muon_pt[index1] > ptMuonLowCut &&
fabs(analysisTree.muon_eta[index1]) < etaMuonLowCut)
isMu1LowPtmatched = true;
}
if (isMu1matched) {
for (unsigned int iMu=0; iMu<allMuons.size(); ++iMu) {
unsigned int indexProbe = allMuons[iMu];
if (index1==indexProbe) continue;
float q1 = analysisTree.muon_charge[index1];
float q2 = analysisTree.muon_charge[indexProbe];
if (q1*q2>0) continue;
float dR = deltaR(analysisTree.muon_eta[index1],analysisTree.muon_phi[index1],
analysisTree.muon_eta[indexProbe],analysisTree.muon_phi[indexProbe]);
if (dR<dRleptonsCut) continue;
float ptProbe = TMath::Min(float(analysisTree.muon_pt[indexProbe]),float(ptBins[nPtBins]-0.1));
float absEtaProbe = fabs(analysisTree.muon_eta[indexProbe]);
int ptBin = binNumber(ptProbe,nPtBins,ptBins);
int etaBin = binNumber(absEtaProbe,nEtaBins,etaBins);
TLorentzVector muon1; muon1.SetXYZM(analysisTree.muon_px[index1],
analysisTree.muon_py[index1],
analysisTree.muon_pz[index1],
muonMass);
TLorentzVector muon2; muon2.SetXYZM(analysisTree.muon_px[indexProbe],
analysisTree.muon_py[indexProbe],
analysisTree.muon_pz[indexProbe],
muonMass);
float mass = (muon1+muon2).M();
if (isMuonPassedIdIso[iMu])
ZMassEtaPtPass[etaBin][ptBin]->Fill(mass,weight);
else
ZMassEtaPtFail[etaBin][ptBin]->Fill(mass,weight);
}
}
for (unsigned int im2=im1+1; im2<isoMuons.size(); ++im2) {
unsigned int index2 = isoMuons[im2];
float q1 = analysisTree.muon_charge[index1];
float q2 = analysisTree.muon_charge[index2];
bool isMu2matched = false;
bool isMu2HighPtmatched = false;
bool isMu2LowPtmatched = false;
for (unsigned int iT=0; iT<analysisTree.trigobject_count; ++iT) {
float dRtrig = deltaR(analysisTree.muon_eta[index2],analysisTree.muon_phi[index2],
analysisTree.trigobject_eta[iT],analysisTree.trigobject_phi[iT]);
if (dRtrig>DRTrigMatch) continue;
if (analysisTree.trigobject_filters[iT][nMuonFilter] &&
analysisTree.muon_pt[index2] > ptMuonHighCut &&
fabs(analysisTree.muon_eta[index2]) < etaMuonHighCut)
isMu2matched = true;
if (analysisTree.trigobject_filters[iT][nDoubleMuonHighPtFilter] &&
analysisTree.muon_pt[index2] > ptMuonHighCut &&
fabs(analysisTree.muon_eta[index2]) < etaMuonHighCut)
isMu2HighPtmatched = true;
if (analysisTree.trigobject_filters[iT][nDoubleMuonLowPtFilter] &&
analysisTree.muon_pt[index2] > ptMuonLowCut &&
fabs(analysisTree.muon_eta[index2]) < etaMuonLowCut)
isMu2LowPtmatched = true;
}
bool isPairSelected = q1*q2 > 0;
if (oppositeSign) isPairSelected = q1*q2 < 0;
bool isTriggerMatch = (isMu1matched || isMu2matched);
if (doubleMuonTrigger)
isTriggerMatch = (isMu1LowPtmatched && isMu2HighPtmatched) || (isMu2LowPtmatched && isMu1HighPtmatched);
float dRmumu = deltaR(analysisTree.muon_eta[index1],analysisTree.muon_phi[index1],
analysisTree.muon_eta[index2],analysisTree.muon_phi[index2]);
if (isTriggerMatch && isPairSelected && dRmumu>dRleptonsCut) {
bool sumIso = isoMuonsValue[im1]+isoMuonsValue[im2];
if (sumIso<isoMin) {
isIsoMuonsPair = true;
isoMin = sumIso;
if (analysisTree.muon_pt[index1]>analysisTree.muon_pt[index2]) {
indx1 = index1;
indx2 = index2;
}
else {
indx2 = index1;
indx1 = index2;
}
}
}
}
}
}
if (isIsoMuonsPair) {
//match to genparticles
TLorentzVector genZ;// genZ.SetXYZM(0,0,0,91.2);
if (!isData) {
for (unsigned int igen=0; igen<analysisTree.genparticles_count; ++igen) {
if (analysisTree.genparticles_pdgid[igen]==23 && analysisTree.genparticles_status[igen]==62)
// cout << "(Px,Py,Pz)=("
// << analysisTree.genparticles_px[igen] << ","
// << analysisTree.genparticles_py[igen] << ","
// << analysisTree.genparticles_pz[igen] << ") status = "
// << analysisTree.genparticles_status[igen] << std::endl;
genZ.SetXYZT(analysisTree.genparticles_px[igen],
analysisTree.genparticles_py[igen],
analysisTree.genparticles_pz[igen],
analysisTree.genparticles_e[igen]);
if (fabs(analysisTree.genparticles_pdgid[igen])==13 &&
analysisTree.genparticles_status[igen]==1) {
TLorentzVector gen_mu1; gen_mu1.SetPxPyPzE(analysisTree.genparticles_px[igen],
analysisTree.genparticles_py[igen],
analysisTree.genparticles_pz[igen],
analysisTree.genparticles_e[igen]);
TLorentzVector gen_mu2; gen_mu2.SetPxPyPzE(analysisTree.genparticles_px[igen],
analysisTree.genparticles_py[igen],
analysisTree.genparticles_pz[igen],
analysisTree.genparticles_e[igen]);
}
}
}
// selecting good jets --->
// HT variables
float HT30 = 0;
float HT20 = 0;
float HT30etaCut = 0;
float HT20etaCut = 0;
// number of jets
int nJets30 = 0;
int nJets20 = 0;
int nJets30etaCut = 0;
int nJets20etaCut = 0;
for (unsigned int jet=0; jet<analysisTree.pfjet_count; ++jet) {
float absJetEta = fabs(analysisTree.pfjet_eta[jet]);
if (absJetEta>jetEtaCut) continue;
float dR1 = deltaR(analysisTree.pfjet_eta[jet],analysisTree.pfjet_phi[jet],
analysisTree.muon_eta[indx1],analysisTree.muon_phi[indx1]);
if (dR1<dRJetLeptonCut) continue;
float dR2 = deltaR(analysisTree.pfjet_eta[jet],analysisTree.pfjet_phi[jet],
analysisTree.muon_eta[indx2],analysisTree.muon_phi[indx2]);
if (dR2<dRJetLeptonCut) continue;
// pfJetId
float energy = analysisTree.pfjet_e[jet];
float chf = analysisTree.pfjet_chargedhadronicenergy[jet]/energy;
float nhf = analysisTree.pfjet_neutralhadronicenergy[jet]/energy;
float phf = analysisTree.pfjet_neutralemenergy[jet]/energy;
float elf = analysisTree.pfjet_chargedemenergy[jet]/energy;
float chm = analysisTree.pfjet_chargedmulti[jet];
float npr = analysisTree.pfjet_chargedmulti[jet] + analysisTree.pfjet_neutralmulti[jet];
bool isPFJetId = (npr>1 && phf<0.99 && nhf<0.99) && (absJetEta>2.4 || (elf<0.99 && chf>0 && chm>0));
if (!isPFJetId) continue;
if (analysisTree.pfjet_pt[jet]>jetPtHighCut) {
nJets30++;
HT30 += analysisTree.pfjet_pt[jet];
if (fabs(analysisTree.pfjet_eta[jet])<jetEtaTrkCut) {
HT30etaCut += analysisTree.pfjet_pt[jet];
nJets30etaCut++;
}
}
if (analysisTree.pfjet_pt[jet]>jetPtLowCut) {
nJets20++;
HT20 += analysisTree.pfjet_pt[jet];
if (fabs(analysisTree.pfjet_eta[jet])<jetEtaTrkCut) {
HT20etaCut += analysisTree.pfjet_pt[jet];
nJets20etaCut++;
}
}
}
TLorentzVector mu1; mu1.SetXYZM(analysisTree.muon_px[indx1],
analysisTree.muon_py[indx1],
analysisTree.muon_pz[indx1],
muonMass);
TLorentzVector mu2; mu2.SetXYZM(analysisTree.muon_px[indx2],
analysisTree.muon_py[indx2],
analysisTree.muon_pz[indx2],
muonMass);
TLorentzVector dimuon = mu1 + mu2;
// std::cout << "Before corrections : MetX = " << pfmet_ex << " MetY = " << pfmet_ey << " Met_Phi = " << pfmet_phi << std::endl;
if (!isData) {
if (applyLeptonSF) {
float pt1 = mu1.Pt();
if (pt1>1000) pt1 = 999;
float eta1 = TMath::Abs(mu1.Eta());
if (eta1>2.4) eta1 = 2.39;
int ptBin1 = binNumber(pt1,nPtBinsSF,ptBinsSF);
int etaBin1 = binNumber(eta1,nEtaBins,etaBins);
float sf1 = mueffSF[etaBin1][ptBin1];
// std::cout << "mu1 : pt=" << mu1.Pt() << " (" << ptBin1 << ")"
// << " eta=" << mu1.Eta() << " (" << etaBin1 << ")"
// << " eff(data)=" << mueffData[etaBin1][ptBin1]
// << " eff(MC)=" << mueffMC[etaBin1][ptBin1]
// << " SF=" << mueffSF[etaBin1][ptBin1] << std::endl;
float pt2 = mu2.Pt();
if (pt2>1000) pt2 = 999;
float eta2 = TMath::Abs(mu2.Eta());
if (eta2>2.4) eta2 = 2.39;
int ptBin2 = binNumber(pt2,nPtBinsSF,ptBinsSF);
int etaBin2 = binNumber(eta2,nEtaBins,etaBins);
float sf2 = mueffSF[etaBin2][ptBin2];
// std::cout << "mu2 : pt=" << mu2.Pt() << " (" << ptBin2 << ")"
// << " eta=" << mu2.Eta() << " (" << etaBin2 << ")"
// << " eff(data)=" << mueffData[etaBin2][ptBin2]
// << " eff(MC)=" << mueffMC[etaBin2][ptBin2]
// << " SF=" << mueffSF[etaBin2][ptBin2] << std::endl;
float sf = sf1 * sf2;
weight *= sf;
std::cout << std::endl;
}
if (applyMEtRecoilCorrections) {
eventWeight->RecoilCorrected(pfmet_ex,pfmet_ey,genZ.Px(),genZ.Py(),dimuon.Px(),dimuon.Py(),nJets30,1);
pfmet_phi = TMath::ATan2(pfmet_ey,pfmet_ex);
}
// std::cout << "After corrections : MetX = " << pfmet_ex << " MetY = " << pfmet_ey << " Met_Phi = " << pfmet_phi << std::endl;
}
float massSel = dimuon.M();
//bisector of dimuon transerve momenta
float mu1UnitX = mu1.Px()/mu1.Pt();
float mu1UnitY = mu1.Py()/mu1.Pt();
float mu2UnitX = mu2.Px()/mu2.Pt();
float mu2UnitY = mu2.Py()/mu2.Pt();
float zetaX = mu1UnitX + mu2UnitX;
float zetaY = mu1UnitY + mu2UnitY;
float normZeta = TMath::Sqrt(zetaX*zetaX+zetaY*zetaY);
zetaX = zetaX/normZeta;
zetaY = zetaY/normZeta;
float vectorX = pfmet_ex + mu2.Px() + mu1.Px();
float vectorY = pfmet_ey + mu2.Py() + mu1.Py();
float vectorVisX = mu2.Px() + mu1.Px();
float vectorVisY = mu2.Py() + mu1.Py();
// computation of DZeta variable
float PZeta = vectorX*zetaX + vectorY*zetaY;
float PVisZeta = vectorVisX*zetaX + vectorVisY*zetaY;
float DZeta = PZeta - 1.85*PVisZeta;
if (massSel>0) {
massSelH->Fill(massSel,weight);
ptLeadingMuSelH->Fill(analysisTree.muon_pt[indx1],weight);
ptTrailingMuSelH->Fill(analysisTree.muon_pt[indx2],weight);
etaLeadingMuSelH->Fill(analysisTree.muon_eta[indx1],weight);
etaTrailingMuSelH->Fill(analysisTree.muon_eta[indx2],weight);
ptScatter->Fill(analysisTree.muon_pt[indx1],analysisTree.muon_pt[indx2],weight);
hprof2D_pt->Fill(analysisTree.muon_pt[indx1],analysisTree.muon_pt[indx2],weight);
nJets30SelH->Fill(double(nJets30),weight);
nJets20SelH->Fill(double(nJets20),weight);
nJets30etaCutSelH->Fill(double(nJets30etaCut),weight);
nJets20etaCutSelH->Fill(double(nJets20etaCut),weight);
HT30SelH->Fill(double(HT30),weight);
HT20SelH->Fill(double(HT20),weight);
HT30etaCutSelH->Fill(double(HT30etaCut),weight);
HT20etaCutSelH->Fill(double(HT20etaCut),weight);
// cout << "dxy (mu1) = " << analysisTree.muon_dxy[indx1] << " error = " << analysisTree.muon_dxyerr[indx1] << std::endl;
//cout << "dxy (mu2) = " << analysisTree.muon_dxy[indx2] << " error = " << analysisTree.muon_dxyerr[indx2] << std::endl;
// vector<int>indexMuTau; indexMuTau.clear();
// if (selectZToTauTauMuMu && indexMuTau.size()!=2) continue;
float dimuonEta = dimuon.Eta();
float dimuonPt = dimuon.Pt();
float sumMuonPt = (mu1.Pt()+mu2.Pt());
float ptRatio = 0.0;
float ptRatio_test = 0.0;
if (sumMuonPt != 0){
ptRatio = (dimuonPt/sumMuonPt);
ptRatio_test = (dimuonPt/sumMuonPt);
}
float dcaSigdxy_muon1 = 0.0;
float dcaSigdxy_muon2 = 0.0;
float dcaSigdz_muon1 = 0.0;
float dcaSigdz_muon2 =0.0;
//float dcaSigdxy_mu1 = 0.0;
//float dcaSigdxy_mu2 = 0.0;
//float dcaSigdz_mu1 = 0.0;
//float dcaSigdz_mu2 =0.0;
//float dcaSigdxy_mu1_genMuMatch = 0.0;
//float dcaSigdxy_mu2_genMuMatch = 0.0;
//float dcaSigdz_mu1_genMuMatch = 0.0;
//float dcaSigdz_mu2_genMuMatch =0.0;
float phi_LeadingMu_MET= 0.0;
float phi_TrailingMu_MET =0.0;
float phi_PosMu_MET =0.0;
float phi_TwoMu =0.0;
if (analysisTree.muon_dxyerr[indx1] != 0){
//dcaSigdxy_mu1=(analysisTree.muon_dxy[indx1]/analysisTree.muon_dxyerr[indx1]);
dcaSigdxy_muon1= log10(fabs(analysisTree.muon_dxy[indx1]/analysisTree.muon_dxyerr[indx1]));
// std::cout << "dcaSigdxy_muon1 is "<< dcaSigdxy_muon1 <<" and before log is "<< dcaSigdxy_mu1<< " nan is " << isnan(dcaSigdxy_muon1)<< endl;
}
if (analysisTree.muon_dxyerr[indx2] != 0){
//dcaSigdxy_mu2=(analysisTree.muon_dxy[indx2]/analysisTree.muon_dxyerr[indx2]);
dcaSigdxy_muon2= log10(fabs(analysisTree.muon_dxy[indx2]/analysisTree.muon_dxyerr[indx2]));
}
if (analysisTree.muon_dzerr[indx1] != 0){
//dcaSigdz_mu1 =(analysisTree.muon_dz[indx1]/analysisTree.muon_dzerr[indx1]);
dcaSigdz_muon1 = log10(fabs(analysisTree.muon_dz[indx1]/analysisTree.muon_dzerr[indx1]));
}
if (analysisTree.muon_dzerr[indx2] != 0){
//dcaSigdz_mu2 = (analysisTree.muon_dz[indx2]/analysisTree.muon_dzerr[indx2]);
dcaSigdz_muon2 = log10(fabs(analysisTree.muon_dz[indx2]/analysisTree.muon_dzerr[indx2]));
}
//filling the histograms for discriminators
h_dimuonEta->Fill(dimuonEta,weight);
// if (genmatch_m1 && genmatch_m2) h_dimuonEta_genMuMatch->Fill(dimuonEta,weight);
h_ptRatio->Fill(ptRatio,weight);
h_dxy_muon1->Fill(analysisTree.muon_dxy[indx1],weight);
h_dxy_muon2->Fill(analysisTree.muon_dxy[indx2],weight);
h_dz_muon1->Fill(analysisTree.muon_dz[indx1],weight);
h_dz_muon2->Fill(analysisTree.muon_dz[indx2],weight);
int iEta=0, iPt=0;
if (dimuonEta < 0.9) iEta = 0;
if (dimuonEta>0.9 && dimuonEta<1.2) iEta = 1;
if (dimuonEta>1.2 && dimuonEta<2.1) iEta = 2;
if (dimuonEta>2.1 && dimuonEta<2.4) iEta = 3;
//if (dimuonEta>2.4) iEta = 4;
if (dimuonPt < 10) iPt = 0;
if (dimuonPt>10 && dimuonPt<15) iPt = 1;
if (dimuonPt>15 && dimuonPt<20) iPt = 2;
if (dimuonPt>20 && dimuonPt<25) iPt = 3;
if (dimuonPt>25 && dimuonPt<30) iPt = 4;
if (dimuonPt>30 && dimuonPt<40) iPt = 5;
if (dimuonPt>40 && dimuonPt<50) iPt = 6;
if (dimuonPt>50 && dimuonPt<60) iPt = 7;
if (dimuonPt>60) iPt = 8;
dxyMu1[iEta][iPt]->Fill(analysisTree.muon_dxy[indx1],weight);
dxyMu2[iEta][iPt]->Fill(analysisTree.muon_dxy[indx2],weight);
dzMu1[iEta][iPt]->Fill(analysisTree.muon_dz[indx1],weight);
dzMu2[iEta][iPt]->Fill(analysisTree.muon_dz[indx2],weight);
/* if (massSel>70&&massSel<110){
dxyMu1_m70to110[iEta][iPt]->Fill(analysisTree.muon_dxy[indx1],weight);
dxyMu2_m70to110[iEta][iPt]->Fill(analysisTree.muon_dxy[indx2],weight);
dzMu1_m70to110[iEta][iPt]->Fill(analysisTree.muon_dz[indx1],weight);
dzMu2_m70to110[iEta][iPt]->Fill(analysisTree.muon_dz[indx2],weight);
}
*/
if (massSel< 70){
h_dxy_mu1_mlt70->Fill(analysisTree.muon_dxy[indx1],weight);
h_dxy_mu2_mlt70->Fill(analysisTree.muon_dxy[indx2],weight);
h_dz_mu1_mlt70->Fill(analysisTree.muon_dz[indx1],weight);
h_dz_mu2_mlt70->Fill(analysisTree.muon_dz[indx2],weight);
}
if (massSel> 70){
h_dxy_mu1_mgt70->Fill(analysisTree.muon_dxy[indx1],weight);
h_dxy_mu2_mgt70->Fill(analysisTree.muon_dxy[indx2],weight);
h_dz_mu1_mgt70->Fill(analysisTree.muon_dz[indx1],weight);
h_dz_mu2_mgt70->Fill(analysisTree.muon_dz[indx2],weight);
}
h_dcaSigdxy_muon1->Fill(dcaSigdxy_muon1,weight);
h_dcaSigdxy_muon2->Fill(dcaSigdxy_muon2,weight);
h_dcaSigdz_muon1->Fill(dcaSigdz_muon1,weight);
h_dcaSigdz_muon2->Fill(dcaSigdz_muon2,weight);
// h_dcaSigdxy_mu1->Fill(dcaSigdxy_mu1,weight);
//h_dcaSigdxy_mu2->Fill(dcaSigdxy_mu2,weight);
//h_dcaSigdz_mu1->Fill(dcaSigdz_mu1,weight);
//h_dcaSigdz_mu2->Fill(dcaSigdz_mu2,weight);
// if(genmatch_m1 && genmatch_mu2)
//h_dcaSigdxy_mu1_genMuMatch->Fill(analysisTree.muon_dxy[indx1]/analysisTree.muon_dxyerr[indx1]);
//if (genmatch_m1 && genmatch_m2) h_dcaSigdxy_mu1_genMuMatch->Fill(dcaSigdxy_mu1,weight);
//if (genmatch_m1 && genmatch_m2) h_dcaSigdxy_mu2_genMuMatch->Fill(dcaSigdxy_mu2,weight);
//if (genmatch_m1 && genmatch_m2) h_dcaSigdz_mu1_genMuMatch->Fill(dcaSigdz_mu1,weight);
//if (genmatch_m1 && genmatch_m2) h_dcaSigdz_mu2_genMuMatch->Fill(dcaSigdz_mu2,weight);
// h_phi_leadingMu_MET->Fill((analysisTree.muon_phi[indx1]-pfmet_phi),weight);
// h_phi_trailingMu_MET->Fill((analysisTree.muon_phi[indx2]-pfmet_phi),weight);
float q1 = analysisTree.muon_charge[indx1];
float q2 = analysisTree.muon_charge[indx2];
// phi_LeadingMu_MET = (analysisTree.muon_phi[indx1]-pfmet_phi);
// if (fabs(phi_LeadingMu_MET)> TMath::Pi()) phi_LeadingMu_MET = (2*TMath::Pi()- fabs(phi_LeadingMu_MET));
phi_LeadingMu_MET = dPhiFrom2P(analysisTree.muon_px[indx1],analysisTree.muon_py[indx1],
pfmet_ex,pfmet_ey);
h_phi_leadingMu_MET->Fill(fabs(phi_LeadingMu_MET),weight);
// phi_TrailingMu_MET = (analysisTree.muon_phi[indx2]-pfmet_phi);
// if (fabs(phi_TrailingMu_MET)> TMath::Pi())phi_TrailingMu_MET = 2*TMath::Pi()- fabs(phi_TrailingMu_MET);
phi_TrailingMu_MET = dPhiFrom2P(analysisTree.muon_px[indx2],analysisTree.muon_py[indx2],
pfmet_ex,pfmet_ey);
h_phi_trailingMu_MET->Fill(fabs(phi_TrailingMu_MET),weight);
if (q1>0)
phi_PosMu_MET = phi_LeadingMu_MET;
else
phi_PosMu_MET = phi_TrailingMu_MET;
// if (fabs(phi_PosMu_MET)> TMath::Pi()) phi_PosMu_MET = (2*TMath::Pi()- fabs(phi_PosMu_MET));
h_phi_PosMu_MET->Fill(fabs(phi_PosMu_MET),weight);
// phi_TwoMu = (analysisTree.muon_phi[indx1]-analysisTree.muon_phi[indx2]);
// if (fabs(phi_Two)> TMath::Pi()) phi_PosMu_MET = (2*TMath::Pi()- fabs(phi_PosMu_MET));
phi_TwoMu = dPhiFrom2P(analysisTree.muon_px[indx1],analysisTree.muon_py[indx1],
analysisTree.muon_px[indx2],analysisTree.muon_py[indx2]);
h_phi_TwoMu->Fill(phi_TwoMu,weight);
if (fabs(phi_TwoMu)>2)
h_ptRatio_test-> Fill (ptRatio_test, weight);
h_DZeta->Fill(DZeta,weight);
h_Njets->Fill(analysisTree.pfjet_count,weight);
/* if(!isData){
if (dcaSigdxy_muon1<1.8 && dcaSigdxy_muon1>0.2) h_dxy_muon1_dcaCut->Fill(analysisTree.muon_dxy[indx1],weight);
if (dcaSigdxy_muon1<1.8 && dcaSigdxy_muon1>0.2) h_dxy_muon2_dcaCut->Fill(analysisTree.muon_dxy[indx2],weight);
if (dcaSigdxy_muon1<1.8 && dcaSigdxy_muon1>0.2) h_dimuonEta_dcaCut->Fill(dimuonEta,weight);
if (dcaSigdxy_muon1<1.8 && dcaSigdxy_muon1>0.2) h_ptRatio_dcaCut->Fill(ptRatio,weight);
}
*/
NumberOfVerticesH->Fill(float(analysisTree.primvertex_count),weight);
float metSel = sqrt(pfmet_ex*pfmet_ex+pfmet_ey*pfmet_ey);
metSelH->Fill(metSel,weight);
// fill ntuples for BDT training
n_dimuonEta=dimuonEta;
n_ptRatio=ptRatio;
n_dxy_muon1= analysisTree.muon_dxy[indx1];
n_dxy_muon2= analysisTree.muon_dxy[indx2];
n_dz_muon1= analysisTree.muon_dz[indx1];
n_dz_muon2= analysisTree.muon_dz[indx2];
n_dcaSigdxy1=dcaSigdxy_muon1;
n_dcaSigdxy2=dcaSigdxy_muon2;
// n_dcaSigdxy_mu1=dcaSigdxy_mu1;
//n_dcaSigdxy_mu2=dcaSigdxy_mu2;
n_dcaSigdz1=dcaSigdz_muon1;
n_dcaSigdz2=dcaSigdz_muon2;
//n_dcaSigdz_mu1=dcaSigdz_mu1;
//n_dcaSigdz_mu2=dcaSigdz_mu2;
n_MissingEt=metSel;
n_phiangle=fabs(phi_PosMu_MET);
n_twomuPhi=fabs(phi_TwoMu);
n_DZeta = DZeta;
n_genWeight = weight;
n_dimuonMass = massSel;
n_met= metSel;
if (fillBDTNTuple)
T->Fill();
if (massSel>70&&massSel<110) {
float unitX = dimuon.Px()/dimuon.Pt();
float unitY = dimuon.Py()/dimuon.Pt();
float phiUnit = TMath::ATan2(unitY,unitX);
float recoilParal = pfmet_ex*unitX + pfmet_ey*unitY;
float perpUnitX = TMath::Cos(phiUnit+0.5*TMath::Pi());
float perpUnitY = TMath::Sin(phiUnit+0.5*TMath::Pi());
float recoilPerp = pfmet_ex*perpUnitX + pfmet_ey*perpUnitY;
int jetBin = 0;
if (nJets30==1)
jetBin = 1;
else if (nJets30>1)
jetBin = 2;
recoilZParalH[jetBin]->Fill(recoilParal,weight);
recoilZPerpH[jetBin]->Fill(recoilPerp,weight);
int iJets=0, iPtBins=0;
if (nJets30==1) iJets = 1;
if (nJets30>=2) iJets = 2;
if (dimuonPt < 10) iPtBins = 0;
if (dimuonPt>10 && dimuonPt<20) iPtBins = 1;
if (dimuonPt>20 && dimuonPt<30) iPtBins = 2;
if (dimuonPt>30 && dimuonPt<50) iPtBins = 3;
if (dimuonPt>50) iPtBins = 4;
recoilZParal_Ptbins_nJetsH[iJets][iPtBins]->Fill(recoilParal,weight);
recoilZPerp_Ptbins_nJetsH[iJets][iPtBins]->Fill(recoilPerp,weight);
int iJetBin=0;
if (nJets30==1)
iJetBin = 1;
else if (nJets30>1)
iJetBin = 2;
ptRatio_nJetsH[iJetBin]->Fill(ptRatio,weight);
}
}
}
if (isIsoMuonsPair) selEventsIsoMuons++;
} // end of file processing (loop over events in one file)
nFiles++;
delete _tree;
file_->Close();
delete file_;
}
std::cout << std::endl;
int allEvents = int(inputEventsH->GetEntries());
std::cout << "Total number of input events = " << allEvents << std::endl;
std::cout << "Total number of events in Tree = " << nEvents << std::endl;
std::cout << "Total number of selected events (iso muon pairs) = " << selEventsIsoMuons << std::endl;
std::cout << std::endl;
std::cout << "RunMin = " << RunMin << std::endl;
std::cout << "RunMax = " << RunMax << std::endl;
//cout << "weight used:" << weight << std::endl;
// using object as comp
std::sort (allRuns.begin(), allRuns.end(), myobject);
std::cout << "Runs : ";
for (unsigned int iR=0; iR<allRuns.size(); ++iR)
std::cout << " " << allRuns.at(iR);
std::cout << std::endl;
file->Write();
file->Close();
delete file;
}
| [
"[email protected]"
] | |
1662fdfdc28a52c232e2b0990a804cfb988876f7 | 2945d889bec36a8be79a27ee5058366bfa7dfc32 | /src/GameObject/Category/Buildings/BuildingBase/BuildingBase.cpp | 6100985b632269309642f7b4ee206cda9c719471 | [] | no_license | peperontino39/FactoryTown | b8c35464e5866019b5e26034e32cc21b5f95d781 | 3990bb28a2d828f1b4e00f23e503e85bec97f8e8 | refs/heads/master | 2021-01-22T21:37:11.553225 | 2017-03-20T08:53:05 | 2017-03-20T08:53:05 | 85,445,646 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 57 | cpp | #include "BuildingBase.h"
void BuildingBase::draw()
{
}
| [
"[email protected]"
] | |
1174b8cb8dbd3a3af5a19f2a29c4c331ade435bd | 6b40e9dccf2edc767c44df3acd9b626fcd586b4d | /NT/net/mmc/wlanmon/addserv.cpp | 1b891e8e6ceced00bc31cbf1c54d3a9e1e7c8269 | [] | no_license | jjzhang166/WinNT5_src_20201004 | 712894fcf94fb82c49e5cd09d719da00740e0436 | b2db264153b80fbb91ef5fc9f57b387e223dbfc2 | refs/heads/Win2K3 | 2023-08-12T01:31:59.670176 | 2021-10-14T15:14:37 | 2021-10-14T15:14:37 | 586,134,273 | 1 | 0 | null | 2023-01-07T03:47:45 | 2023-01-07T03:47:44 | null | UTF-8 | C++ | false | false | 2,703 | cpp | /**********************************************************************/
/** Microsoft Windows/NT **/
/** Copyright(c) Microsoft Corporation, 1997 - 1999 **/
/**********************************************************************/
/*
edituser.h
Edit user dialog implementation file
FILE HISTORY:
*/
#include "stdafx.h"
#include "AddServ.h"
#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif
/////////////////////////////////////////////////////////////////////////////
// CAddServ dialog
CAddServ::CAddServ(CWnd* pParent /*=NULL*/)
: CBaseDialog(CAddServ::IDD, pParent)
{
//{{AFX_DATA_INIT(CAddServ)
// NOTE: the ClassWizard will add member initialization here
//}}AFX_DATA_INIT
}
void CAddServ::DoDataExchange(CDataExchange* pDX)
{
CBaseDialog::DoDataExchange(pDX);
//{{AFX_DATA_MAP(CAddServ)
DDX_Control(pDX, IDC_ADD_EDIT_NAME, m_editComputerName);
//}}AFX_DATA_MAP
}
BEGIN_MESSAGE_MAP(CAddServ, CBaseDialog)
//{{AFX_MSG_MAP(CAddServ)
ON_BN_CLICKED(IDC_BTN_BROWSE, OnButtonBrowse)
ON_BN_CLICKED(IDC_ADD_LOCAL, OnRadioBtnClicked)
ON_BN_CLICKED(IDC_ADD_OTHER, OnRadioBtnClicked)
//}}AFX_MSG_MAP
END_MESSAGE_MAP()
/////////////////////////////////////////////////////////////////////////////
// CAddServ message handlers
BOOL CAddServ::OnInitDialog()
{
CBaseDialog::OnInitDialog();
CheckDlgButton(IDC_ADD_OTHER, BST_CHECKED);
m_editComputerName.SetFocus();
OnRadioBtnClicked();
return FALSE; // return TRUE unless you set the focus to a control
// EXCEPTION: OCX Property Pages should return FALSE
}
void CAddServ::OnButtonBrowse()
{
CGetComputer getComputer;
if (!getComputer.GetComputer(GetSafeHwnd()))
return;
CString strTemp = getComputer.m_strComputerName;
m_editComputerName.SetWindowText(strTemp);
}
void CAddServ::OnRadioBtnClicked()
{
BOOL fEnable = IsDlgButtonChecked(IDC_ADD_OTHER);
m_editComputerName.EnableWindow(fEnable);
GetDlgItem(IDC_BTN_BROWSE)->EnableWindow(fEnable);
}
void CAddServ::OnOK()
{
DWORD dwLength;
if (IsDlgButtonChecked(IDC_ADD_OTHER))
{
dwLength = m_editComputerName.GetWindowTextLength() + 1;
if (dwLength <= 1)
{
AfxMessageBox(IDS_ERR_EMPTY_NAME);
return;
}
m_editComputerName.GetWindowText(m_stComputerName.GetBuffer(dwLength), dwLength);
}
else
{
dwLength = MAX_COMPUTERNAME_LENGTH + 1;
GetComputerName(m_stComputerName.GetBuffer(dwLength), &dwLength);
}
m_stComputerName.ReleaseBuffer();
CBaseDialog::OnOK();
}
| [
"[email protected]"
] | |
1dbe3279dfbbf2ad8d6ffc2ab445e1e49f4e3f60 | ecf46e4de7d2ea27b3208be95a011d21b0f7f089 | /src/ariel/rosed3d11.cpp | 605e42c726471b7fa6e96dc3f24b35fffaf22371 | [
"MIT"
] | permissive | lymastee/gslib | e9b012c00ad00cdb41509b6365021ddf7510c5a6 | e6c1c0e55cd85254e5254d0c93699746c7a0721b | refs/heads/master | 2022-08-22T06:31:54.871375 | 2022-08-08T01:25:17 | 2022-08-08T01:25:17 | 71,218,073 | 9 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 11,417 | cpp | /*
* Copyright (c) 2016-2021 lymastee, All rights reserved.
* Contact: [email protected]
*
* This file is part of the gslib project.
*
* 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.
*/
#include <ariel/rose.h>
#include <ariel/rendersysd3d11.h>
#include "rose_psf_cr.h"
#include "rose_psf_klm_cr.h"
#include "rose_psf_klm_tex.h"
#include "rose_pss_coef_cr.h"
#include "rose_pss_coef_tex.h"
#include "rose_vsf_cr.h"
#include "rose_vsf_klm_cr.h"
#include "rose_vsf_klm_tex.h"
#include "rose_vss_coef_cr.h"
#include "rose_vss_coef_tex.h"
__ariel_begin__
template<class c>
static void release_any(c& cptr)
{
if(cptr) {
cptr->Release();
cptr = nullptr;
}
}
static void debug_save_texture(texture2d* p, const string& path)
{
assert(p);
image img;
textureop::convert_to_image(img, p);
img.save(path);
}
template<class stream_type>
int rose_batch::template_buffering(stream_type& stm, rendersys* rsys)
{
assert(rsys);
assert(!_vertex_buffer);
int c = (int)stm.size();
_vertex_buffer = rsys->create_vertex_buffer(sizeof(stream_type::value_type), c, false, false, D3D11_USAGE_DEFAULT, &stm.front());
assert(_vertex_buffer);
return c;
}
int rose_fill_batch_cr::buffering(rendersys* rsys)
{
return template_buffering(_vertices, rsys);
}
void rose_fill_batch_cr::draw(rendersys* rsys)
{
assert(rsys);
setup_vs_and_ps(rsys);
setup_vf_and_topology(rsys, D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST);
rsys->set_vertex_buffer(_vertex_buffer, sizeof(vertex_info_cr), 0);
int c = (int)_vertices.size();
assert(c % 3 == 0);
rsys->draw(c, 0);
}
int rose_fill_batch_klm_cr::buffering(rendersys* rsys)
{
return template_buffering(_vertices, rsys);
}
void rose_fill_batch_klm_cr::draw(rendersys* rsys)
{
assert(rsys);
setup_vs_and_ps(rsys);
setup_vf_and_topology(rsys, D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST);
rsys->set_vertex_buffer(_vertex_buffer, sizeof(vertex_info_klm_cr), 0);
int c = (int)_vertices.size();
assert(c % 3 == 0);
rsys->draw(c, 0);
}
int rose_fill_batch_klm_tex::buffering(rendersys* rsys)
{
assert(!_tex && !_srv);
_tex = _texbatch.create_texture(rsys);
assert(_tex);
_srv = rsys->create_shader_resource_view(convert_to_resource(_tex));
assert(_srv);
return template_buffering(_vertices, rsys);
}
void rose_fill_batch_klm_tex::draw(rendersys* rsys)
{
assert(rsys);
setup_vs_and_ps(rsys);
setup_vf_and_topology(rsys, D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST);
rsys->set_vertex_buffer(_vertex_buffer, sizeof(vertex_info_klm_tex), 0);
rsys->set_sampler_state(0, _sstate, st_pixel_shader);
rsys->set_shader_resource(0, _srv, st_pixel_shader);
int c = (int)_vertices.size();
assert(c % 3 == 0);
rsys->draw(c, 0);
}
void rose_fill_batch_klm_tex::destroy()
{
release_any(_sstate);
release_any(_tex);
release_any(_srv);
}
int rose_stroke_batch_coef_cr::buffering(rendersys* rsys)
{
return template_buffering(_vertices, rsys);
}
void rose_stroke_batch_coef_cr::draw(rendersys* rsys)
{
assert(rsys);
setup_vs_and_ps(rsys);
setup_vf_and_topology(rsys, D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST);
rsys->set_vertex_buffer(_vertex_buffer, sizeof(vertex_info_coef_cr), 0);
int c = (int)_vertices.size();
assert(c % 3 == 0);
rsys->draw(c, 0);
}
int rose_stroke_batch_coef_tex::buffering(rendersys* rsys)
{
assert(!_tex && !_srv);
_tex = _texbatch.create_texture(rsys);
assert(_tex);
_srv = rsys->create_shader_resource_view(convert_to_resource(_tex));
assert(_srv);
return template_buffering(_vertices, rsys);
}
void rose_stroke_batch_coef_tex::draw(rendersys* rsys)
{
assert(rsys);
setup_vs_and_ps(rsys);
setup_vf_and_topology(rsys, D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST);
rsys->set_vertex_buffer(_vertex_buffer, sizeof(vertex_info_coef_tex), 0);
rsys->set_sampler_state(0, _sstate, st_pixel_shader);
rsys->set_shader_resource(0, _srv, st_pixel_shader);
int c = (int)_vertices.size();
assert(c % 3 == 0);
rsys->draw(c, 0);
}
void rose_stroke_batch_coef_tex::destroy()
{
release_any(_sstate);
release_any(_tex);
release_any(_srv);
}
int rose_stroke_batch_assoc_with_klm_tex::buffering(rendersys* rsys)
{
assert(!_tex && !_srv);
assert(_assoc);
_tex = _assoc->_tex;
_srv = _assoc->_srv;
assert(_tex && _srv);
return template_buffering(_vertices, rsys);
}
void rose::setup(rendersys* rsys)
{
assert(rsys);
_rsys = rsys;
rendersys::vertex_format_desc descf_cr[] =
{
{ "POSITION", 0, DXGI_FORMAT_R32G32_FLOAT, 0, 0, D3D11_INPUT_PER_VERTEX_DATA, 0 },
{ "COLOR", 0, DXGI_FORMAT_R32G32B32A32_FLOAT, 0, D3D11_APPEND_ALIGNED_ELEMENT, D3D11_INPUT_PER_VERTEX_DATA, 0 }
};
rendersys::vertex_format_desc descf_klm_cr[] =
{
{ "POSITION", 0, DXGI_FORMAT_R32G32_FLOAT, 0, 0, D3D11_INPUT_PER_VERTEX_DATA, 0 },
{ "TEXCOORD", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, D3D11_APPEND_ALIGNED_ELEMENT, D3D11_INPUT_PER_VERTEX_DATA, 0 },
{ "COLOR", 0, DXGI_FORMAT_R32G32B32A32_FLOAT, 0, D3D11_APPEND_ALIGNED_ELEMENT, D3D11_INPUT_PER_VERTEX_DATA, 0 }
};
rendersys::vertex_format_desc descs_coef_cr[] =
{
{ "POSITION", 0, DXGI_FORMAT_R32G32_FLOAT, 0, 0, D3D11_INPUT_PER_VERTEX_DATA, 0 },
{ "TEXCOORD", 0, DXGI_FORMAT_R32G32B32A32_FLOAT, 0, D3D11_APPEND_ALIGNED_ELEMENT, D3D11_INPUT_PER_VERTEX_DATA, 0 },
{ "COLOR", 0, DXGI_FORMAT_R32G32B32A32_FLOAT, 0, D3D11_APPEND_ALIGNED_ELEMENT, D3D11_INPUT_PER_VERTEX_DATA, 0 },
};
rendersys::vertex_format_desc descf_klm_tex[] =
{
{ "POSITION", 0, DXGI_FORMAT_R32G32_FLOAT, 0, 0, D3D11_INPUT_PER_VERTEX_DATA, 0 },
{ "TEXCOORD", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, D3D11_APPEND_ALIGNED_ELEMENT, D3D11_INPUT_PER_VERTEX_DATA, 0 },
{ "TEXCOORD", 1, DXGI_FORMAT_R32G32_FLOAT, 0, D3D11_APPEND_ALIGNED_ELEMENT, D3D11_INPUT_PER_VERTEX_DATA, 0 }
};
rendersys::vertex_format_desc descs_coef_tex[] =
{
{ "POSITION", 0, DXGI_FORMAT_R32G32_FLOAT, 0, 0, D3D11_INPUT_PER_VERTEX_DATA, 0 },
{ "TEXCOORD", 0, DXGI_FORMAT_R32G32B32A32_FLOAT, 0, D3D11_APPEND_ALIGNED_ELEMENT, D3D11_INPUT_PER_VERTEX_DATA, 0 },
{ "TEXCOORD", 1, DXGI_FORMAT_R32G32_FLOAT, 0, D3D11_APPEND_ALIGNED_ELEMENT, D3D11_INPUT_PER_VERTEX_DATA, 0 },
};
/* create shader cr */
_vsf_cr = _rsys->create_vertex_shader(g_rose_vsf_cr, sizeof(g_rose_vsf_cr));
assert(_vsf_cr);
_vf_cr = _rsys->create_vertex_format(g_rose_vsf_cr, sizeof(g_rose_vsf_cr), descf_cr, _countof(descf_cr));
assert(_vf_cr);
_psf_cr = _rsys->create_pixel_shader(g_rose_psf_cr, sizeof(g_rose_psf_cr));
assert(_psf_cr);
/* create shader klm cr */
_vsf_klm_cr = _rsys->create_vertex_shader(g_rose_vsf_klm_cr, sizeof(g_rose_vsf_klm_cr));
assert(_vsf_klm_cr);
_vf_klm_cr = _rsys->create_vertex_format(g_rose_vsf_klm_cr, sizeof(g_rose_vsf_klm_cr), descf_klm_cr, _countof(descf_klm_cr));
assert(_vf_klm_cr);
_psf_klm_cr = _rsys->create_pixel_shader(g_rose_psf_klm_cr, sizeof(g_rose_psf_klm_cr));
assert(_psf_klm_cr);
/* create shader coef cr */
_vss_coef_cr = _rsys->create_vertex_shader(g_rose_vss_coef_cr, sizeof(g_rose_vss_coef_cr));
assert(_vss_coef_cr);
_vf_coef_cr = _rsys->create_vertex_format(g_rose_vss_coef_cr, sizeof(g_rose_vss_coef_cr), descs_coef_cr, _countof(descs_coef_cr));
assert(_vf_coef_cr);
_pss_coef_cr = _rsys->create_pixel_shader(g_rose_pss_coef_cr, sizeof(g_rose_pss_coef_cr));
assert(_pss_coef_cr);
/* create shader klm tex */
_vsf_klm_tex = _rsys->create_vertex_shader(g_rose_vsf_klm_tex, sizeof(g_rose_vsf_klm_tex));
assert(_vsf_klm_tex);
_vf_klm_tex = _rsys->create_vertex_format(g_rose_vsf_klm_tex, sizeof(g_rose_vsf_klm_tex), descf_klm_tex, _countof(descf_klm_tex));
assert(_vf_klm_tex);
_psf_klm_tex = _rsys->create_pixel_shader(g_rose_psf_klm_tex, sizeof(g_rose_psf_klm_tex));
assert(_psf_klm_tex);
/* create shader coef tex */
_vss_coef_tex = _rsys->create_vertex_shader(g_rose_vss_coef_tex, sizeof(g_rose_vss_coef_tex));
assert(_vss_coef_tex);
_vf_coef_tex = _rsys->create_vertex_format(g_rose_vss_coef_tex, sizeof(g_rose_vss_coef_tex), descs_coef_tex, _countof(descs_coef_tex));
assert(_vf_coef_tex);
_pss_coef_tex = _rsys->create_pixel_shader(g_rose_pss_coef_tex, sizeof(g_rose_pss_coef_tex));
assert(_pss_coef_tex);
/* create sampler state */
_sampler_state = _rsys->create_sampler_state(ssf_linear);
assert(_sampler_state);
/* create cb_configs */
assert(!_cb_configs);
_cb_configs = _rsys->create_constant_buffer(pack_cb_size<rose_configs>(), false, true);
assert(_cb_configs);
setup_configs();
}
void rose::initialize()
{
_vsf_cr = nullptr;
_vsf_klm_cr = nullptr;
_vsf_klm_tex = nullptr;
_psf_cr = nullptr;
_psf_klm_cr = nullptr;
_psf_klm_tex = nullptr;
_vf_cr = nullptr;
_vf_klm_cr = nullptr;
_vf_klm_tex = nullptr;
_vss_coef_cr = nullptr;
_vss_coef_tex = nullptr;
_pss_coef_cr = nullptr;
_pss_coef_tex = nullptr;
_vf_coef_cr = nullptr;
_vf_coef_tex = nullptr;
_cb_configs = nullptr;
_sampler_state = nullptr;
_cb_config_slot = 0;
}
void rose::destroy_miscs()
{
release_constant_buffer(_cb_configs);
release_any(_sampler_state);
release_any(_vf_cr);
release_any(_vf_klm_cr);
release_any(_vf_klm_tex);
release_any(_vsf_cr);
release_any(_vsf_klm_cr);
release_any(_vsf_klm_tex);
release_any(_psf_cr);
release_any(_psf_klm_cr);
release_any(_psf_klm_tex);
release_any(_vf_coef_cr);
release_any(_vf_coef_tex);
release_any(_vss_coef_cr);
release_any(_pss_coef_cr);
release_any(_vss_coef_tex);
release_any(_pss_coef_tex);
_cb_configs = 0;
}
render_sampler_state* rose::acquire_default_sampler_state()
{
assert(_sampler_state);
_sampler_state->AddRef();
return _sampler_state;
}
__ariel_end__
| [
"[email protected]"
] | |
eec4b113ab74225a0b7c0ce45e344bfb63a8295f | f50a347491a7ff5db2715f72bb6df34c27866fa5 | /onity/onity_propctrl_flip.h | d6dd81c39d917ccad7c578ae7477d3a01c1c05f4 | [] | no_license | jeffcai8888/xui_kit | 182181a981f58975c0612a01a9a4d8a3cb967cd9 | ec32e374ce72efc8fd2063d109a66115c28731b8 | refs/heads/master | 2021-01-13T03:47:19.061176 | 2017-01-02T16:04:58 | 2017-01-02T16:04:58 | 77,228,876 | 1 | 0 | null | 2016-12-23T14:00:04 | 2016-12-23T14:00:04 | null | UTF-8 | C++ | false | false | 789 | h | #ifndef __onity_propctrl_flip_h__
#define __onity_propctrl_flip_h__
#include "xui_propctrl.h"
class onity_propctrl_flip : public xui_propctrl
{
xui_declare_rtti
public:
/*
//create
*/
static xui_propctrl* create ( xui_propdata* propdata );
/*
//constructor
*/
onity_propctrl_flip( xui_propdata* propdata );
/*
//override
*/
virtual void on_linkpropdata ( bool selfupdate = false );
virtual void on_editvalue ( xui_propedit* sender );
protected:
/*
//callback
*/
virtual void on_perform ( xui_method_args& args );
/*
//event
*/
void on_toggleclick ( xui_component* sender, xui_method_args& args );
/*
//member
*/
xui_drawer* m_namectrl;
xui_toggle* m_horzctrl;
xui_toggle* m_vertctrl;
};
#endif//__onity_propctrl_flip_h__ | [
"[email protected]"
] | |
fba67006102a6a44c4e62ba8ac3003895f3c4101 | 5d83739af703fb400857cecc69aadaf02e07f8d1 | /Archive2/a9/172b63a1a3acc4/main.cpp | 3959d0f4b4737173ac0f0d18191b7be96fe712bb | [] | no_license | WhiZTiM/coliru | 3a6c4c0bdac566d1aa1c21818118ba70479b0f40 | 2c72c048846c082f943e6c7f9fa8d94aee76979f | refs/heads/master | 2021-01-01T05:10:33.812560 | 2015-08-24T19:09:22 | 2015-08-24T19:09:22 | 56,789,706 | 3 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 65 | cpp | int main()
{
auto const& t = "αβγ";
return sizeof t;
} | [
"francis.rammeloo@36614edc-3e3a-acb8-9062-c8ae0e4185df"
] | francis.rammeloo@36614edc-3e3a-acb8-9062-c8ae0e4185df |
886f0d51a9f8b73e2fca8cca466be6d53fad3394 | 0eff74b05b60098333ad66cf801bdd93becc9ea4 | /second/download/squid/gumtree/squid_old_log_331.cpp | 2e1b9de60dd06240e3d5c76e7b816a601f1a9736 | [] | no_license | niuxu18/logTracker-old | 97543445ea7e414ed40bdc681239365d33418975 | f2b060f13a0295387fe02187543db124916eb446 | refs/heads/master | 2021-09-13T21:39:37.686481 | 2017-12-11T03:36:34 | 2017-12-11T03:36:34 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 114 | cpp | storeAppendPrintf(sentry, "\t%6lu StoreEntries\n",
(unsigned long)StoreEntry::inUseCount()); | [
"[email protected]"
] | |
a02608499ce9e6768f43ade99ad82c54f48947b6 | 2c3f9daaee6e136b1d52495b3b538dc0d11dd362 | /dms-enterprise/src/Dms-enterpriseClient.cc | 137eac6f9ad27f8cbaf40f1a9e921ab6faf73eef | [
"Apache-2.0"
] | permissive | wqn/aliyun-openapi-cpp-sdk | 180c74c8bee01a5b505dbc6dfaecec87c01e97c2 | d3ce4be157e880ad1f099b3d83cfd25d80832932 | refs/heads/master | 2022-12-16T05:54:34.436079 | 2020-09-07T11:13:16 | 2020-09-07T11:13:16 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 62,189 | cc | /*
* Copyright 2009-2017 Alibaba Cloud All rights reserved.
*
* 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.
*/
#include <alibabacloud/dms-enterprise/Dms_enterpriseClient.h>
#include <alibabacloud/core/SimpleCredentialsProvider.h>
using namespace AlibabaCloud;
using namespace AlibabaCloud::Location;
using namespace AlibabaCloud::Dms_enterprise;
using namespace AlibabaCloud::Dms_enterprise::Model;
namespace
{
const std::string SERVICE_NAME = "dms-enterprise";
}
Dms_enterpriseClient::Dms_enterpriseClient(const Credentials &credentials, const ClientConfiguration &configuration) :
RpcServiceClient(SERVICE_NAME, std::make_shared<SimpleCredentialsProvider>(credentials), configuration)
{
auto locationClient = std::make_shared<LocationClient>(credentials, configuration);
endpointProvider_ = std::make_shared<EndpointProvider>(locationClient, configuration.regionId(), SERVICE_NAME, "dmsenterprise");
}
Dms_enterpriseClient::Dms_enterpriseClient(const std::shared_ptr<CredentialsProvider>& credentialsProvider, const ClientConfiguration & configuration) :
RpcServiceClient(SERVICE_NAME, credentialsProvider, configuration)
{
auto locationClient = std::make_shared<LocationClient>(credentialsProvider, configuration);
endpointProvider_ = std::make_shared<EndpointProvider>(locationClient, configuration.regionId(), SERVICE_NAME, "dmsenterprise");
}
Dms_enterpriseClient::Dms_enterpriseClient(const std::string & accessKeyId, const std::string & accessKeySecret, const ClientConfiguration & configuration) :
RpcServiceClient(SERVICE_NAME, std::make_shared<SimpleCredentialsProvider>(accessKeyId, accessKeySecret), configuration)
{
auto locationClient = std::make_shared<LocationClient>(accessKeyId, accessKeySecret, configuration);
endpointProvider_ = std::make_shared<EndpointProvider>(locationClient, configuration.regionId(), SERVICE_NAME, "dmsenterprise");
}
Dms_enterpriseClient::~Dms_enterpriseClient()
{}
Dms_enterpriseClient::ApproveOrderOutcome Dms_enterpriseClient::approveOrder(const ApproveOrderRequest &request) const
{
auto endpointOutcome = endpointProvider_->getEndpoint();
if (!endpointOutcome.isSuccess())
return ApproveOrderOutcome(endpointOutcome.error());
auto outcome = makeRequest(endpointOutcome.result(), request);
if (outcome.isSuccess())
return ApproveOrderOutcome(ApproveOrderResult(outcome.result()));
else
return ApproveOrderOutcome(outcome.error());
}
void Dms_enterpriseClient::approveOrderAsync(const ApproveOrderRequest& request, const ApproveOrderAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context) const
{
auto fn = [this, request, handler, context]()
{
handler(this, request, approveOrder(request), context);
};
asyncExecute(new Runnable(fn));
}
Dms_enterpriseClient::ApproveOrderOutcomeCallable Dms_enterpriseClient::approveOrderCallable(const ApproveOrderRequest &request) const
{
auto task = std::make_shared<std::packaged_task<ApproveOrderOutcome()>>(
[this, request]()
{
return this->approveOrder(request);
});
asyncExecute(new Runnable([task]() { (*task)(); }));
return task->get_future();
}
Dms_enterpriseClient::CloseOrderOutcome Dms_enterpriseClient::closeOrder(const CloseOrderRequest &request) const
{
auto endpointOutcome = endpointProvider_->getEndpoint();
if (!endpointOutcome.isSuccess())
return CloseOrderOutcome(endpointOutcome.error());
auto outcome = makeRequest(endpointOutcome.result(), request);
if (outcome.isSuccess())
return CloseOrderOutcome(CloseOrderResult(outcome.result()));
else
return CloseOrderOutcome(outcome.error());
}
void Dms_enterpriseClient::closeOrderAsync(const CloseOrderRequest& request, const CloseOrderAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context) const
{
auto fn = [this, request, handler, context]()
{
handler(this, request, closeOrder(request), context);
};
asyncExecute(new Runnable(fn));
}
Dms_enterpriseClient::CloseOrderOutcomeCallable Dms_enterpriseClient::closeOrderCallable(const CloseOrderRequest &request) const
{
auto task = std::make_shared<std::packaged_task<CloseOrderOutcome()>>(
[this, request]()
{
return this->closeOrder(request);
});
asyncExecute(new Runnable([task]() { (*task)(); }));
return task->get_future();
}
Dms_enterpriseClient::CreateOrderOutcome Dms_enterpriseClient::createOrder(const CreateOrderRequest &request) const
{
auto endpointOutcome = endpointProvider_->getEndpoint();
if (!endpointOutcome.isSuccess())
return CreateOrderOutcome(endpointOutcome.error());
auto outcome = makeRequest(endpointOutcome.result(), request);
if (outcome.isSuccess())
return CreateOrderOutcome(CreateOrderResult(outcome.result()));
else
return CreateOrderOutcome(outcome.error());
}
void Dms_enterpriseClient::createOrderAsync(const CreateOrderRequest& request, const CreateOrderAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context) const
{
auto fn = [this, request, handler, context]()
{
handler(this, request, createOrder(request), context);
};
asyncExecute(new Runnable(fn));
}
Dms_enterpriseClient::CreateOrderOutcomeCallable Dms_enterpriseClient::createOrderCallable(const CreateOrderRequest &request) const
{
auto task = std::make_shared<std::packaged_task<CreateOrderOutcome()>>(
[this, request]()
{
return this->createOrder(request);
});
asyncExecute(new Runnable([task]() { (*task)(); }));
return task->get_future();
}
Dms_enterpriseClient::CreatePublishGroupTaskOutcome Dms_enterpriseClient::createPublishGroupTask(const CreatePublishGroupTaskRequest &request) const
{
auto endpointOutcome = endpointProvider_->getEndpoint();
if (!endpointOutcome.isSuccess())
return CreatePublishGroupTaskOutcome(endpointOutcome.error());
auto outcome = makeRequest(endpointOutcome.result(), request);
if (outcome.isSuccess())
return CreatePublishGroupTaskOutcome(CreatePublishGroupTaskResult(outcome.result()));
else
return CreatePublishGroupTaskOutcome(outcome.error());
}
void Dms_enterpriseClient::createPublishGroupTaskAsync(const CreatePublishGroupTaskRequest& request, const CreatePublishGroupTaskAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context) const
{
auto fn = [this, request, handler, context]()
{
handler(this, request, createPublishGroupTask(request), context);
};
asyncExecute(new Runnable(fn));
}
Dms_enterpriseClient::CreatePublishGroupTaskOutcomeCallable Dms_enterpriseClient::createPublishGroupTaskCallable(const CreatePublishGroupTaskRequest &request) const
{
auto task = std::make_shared<std::packaged_task<CreatePublishGroupTaskOutcome()>>(
[this, request]()
{
return this->createPublishGroupTask(request);
});
asyncExecute(new Runnable([task]() { (*task)(); }));
return task->get_future();
}
Dms_enterpriseClient::DeleteInstanceOutcome Dms_enterpriseClient::deleteInstance(const DeleteInstanceRequest &request) const
{
auto endpointOutcome = endpointProvider_->getEndpoint();
if (!endpointOutcome.isSuccess())
return DeleteInstanceOutcome(endpointOutcome.error());
auto outcome = makeRequest(endpointOutcome.result(), request);
if (outcome.isSuccess())
return DeleteInstanceOutcome(DeleteInstanceResult(outcome.result()));
else
return DeleteInstanceOutcome(outcome.error());
}
void Dms_enterpriseClient::deleteInstanceAsync(const DeleteInstanceRequest& request, const DeleteInstanceAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context) const
{
auto fn = [this, request, handler, context]()
{
handler(this, request, deleteInstance(request), context);
};
asyncExecute(new Runnable(fn));
}
Dms_enterpriseClient::DeleteInstanceOutcomeCallable Dms_enterpriseClient::deleteInstanceCallable(const DeleteInstanceRequest &request) const
{
auto task = std::make_shared<std::packaged_task<DeleteInstanceOutcome()>>(
[this, request]()
{
return this->deleteInstance(request);
});
asyncExecute(new Runnable([task]() { (*task)(); }));
return task->get_future();
}
Dms_enterpriseClient::DeleteUserOutcome Dms_enterpriseClient::deleteUser(const DeleteUserRequest &request) const
{
auto endpointOutcome = endpointProvider_->getEndpoint();
if (!endpointOutcome.isSuccess())
return DeleteUserOutcome(endpointOutcome.error());
auto outcome = makeRequest(endpointOutcome.result(), request);
if (outcome.isSuccess())
return DeleteUserOutcome(DeleteUserResult(outcome.result()));
else
return DeleteUserOutcome(outcome.error());
}
void Dms_enterpriseClient::deleteUserAsync(const DeleteUserRequest& request, const DeleteUserAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context) const
{
auto fn = [this, request, handler, context]()
{
handler(this, request, deleteUser(request), context);
};
asyncExecute(new Runnable(fn));
}
Dms_enterpriseClient::DeleteUserOutcomeCallable Dms_enterpriseClient::deleteUserCallable(const DeleteUserRequest &request) const
{
auto task = std::make_shared<std::packaged_task<DeleteUserOutcome()>>(
[this, request]()
{
return this->deleteUser(request);
});
asyncExecute(new Runnable([task]() { (*task)(); }));
return task->get_future();
}
Dms_enterpriseClient::DisableUserOutcome Dms_enterpriseClient::disableUser(const DisableUserRequest &request) const
{
auto endpointOutcome = endpointProvider_->getEndpoint();
if (!endpointOutcome.isSuccess())
return DisableUserOutcome(endpointOutcome.error());
auto outcome = makeRequest(endpointOutcome.result(), request);
if (outcome.isSuccess())
return DisableUserOutcome(DisableUserResult(outcome.result()));
else
return DisableUserOutcome(outcome.error());
}
void Dms_enterpriseClient::disableUserAsync(const DisableUserRequest& request, const DisableUserAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context) const
{
auto fn = [this, request, handler, context]()
{
handler(this, request, disableUser(request), context);
};
asyncExecute(new Runnable(fn));
}
Dms_enterpriseClient::DisableUserOutcomeCallable Dms_enterpriseClient::disableUserCallable(const DisableUserRequest &request) const
{
auto task = std::make_shared<std::packaged_task<DisableUserOutcome()>>(
[this, request]()
{
return this->disableUser(request);
});
asyncExecute(new Runnable([task]() { (*task)(); }));
return task->get_future();
}
Dms_enterpriseClient::EnableUserOutcome Dms_enterpriseClient::enableUser(const EnableUserRequest &request) const
{
auto endpointOutcome = endpointProvider_->getEndpoint();
if (!endpointOutcome.isSuccess())
return EnableUserOutcome(endpointOutcome.error());
auto outcome = makeRequest(endpointOutcome.result(), request);
if (outcome.isSuccess())
return EnableUserOutcome(EnableUserResult(outcome.result()));
else
return EnableUserOutcome(outcome.error());
}
void Dms_enterpriseClient::enableUserAsync(const EnableUserRequest& request, const EnableUserAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context) const
{
auto fn = [this, request, handler, context]()
{
handler(this, request, enableUser(request), context);
};
asyncExecute(new Runnable(fn));
}
Dms_enterpriseClient::EnableUserOutcomeCallable Dms_enterpriseClient::enableUserCallable(const EnableUserRequest &request) const
{
auto task = std::make_shared<std::packaged_task<EnableUserOutcome()>>(
[this, request]()
{
return this->enableUser(request);
});
asyncExecute(new Runnable([task]() { (*task)(); }));
return task->get_future();
}
Dms_enterpriseClient::ExecuteDataCorrectOutcome Dms_enterpriseClient::executeDataCorrect(const ExecuteDataCorrectRequest &request) const
{
auto endpointOutcome = endpointProvider_->getEndpoint();
if (!endpointOutcome.isSuccess())
return ExecuteDataCorrectOutcome(endpointOutcome.error());
auto outcome = makeRequest(endpointOutcome.result(), request);
if (outcome.isSuccess())
return ExecuteDataCorrectOutcome(ExecuteDataCorrectResult(outcome.result()));
else
return ExecuteDataCorrectOutcome(outcome.error());
}
void Dms_enterpriseClient::executeDataCorrectAsync(const ExecuteDataCorrectRequest& request, const ExecuteDataCorrectAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context) const
{
auto fn = [this, request, handler, context]()
{
handler(this, request, executeDataCorrect(request), context);
};
asyncExecute(new Runnable(fn));
}
Dms_enterpriseClient::ExecuteDataCorrectOutcomeCallable Dms_enterpriseClient::executeDataCorrectCallable(const ExecuteDataCorrectRequest &request) const
{
auto task = std::make_shared<std::packaged_task<ExecuteDataCorrectOutcome()>>(
[this, request]()
{
return this->executeDataCorrect(request);
});
asyncExecute(new Runnable([task]() { (*task)(); }));
return task->get_future();
}
Dms_enterpriseClient::ExecuteDataExportOutcome Dms_enterpriseClient::executeDataExport(const ExecuteDataExportRequest &request) const
{
auto endpointOutcome = endpointProvider_->getEndpoint();
if (!endpointOutcome.isSuccess())
return ExecuteDataExportOutcome(endpointOutcome.error());
auto outcome = makeRequest(endpointOutcome.result(), request);
if (outcome.isSuccess())
return ExecuteDataExportOutcome(ExecuteDataExportResult(outcome.result()));
else
return ExecuteDataExportOutcome(outcome.error());
}
void Dms_enterpriseClient::executeDataExportAsync(const ExecuteDataExportRequest& request, const ExecuteDataExportAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context) const
{
auto fn = [this, request, handler, context]()
{
handler(this, request, executeDataExport(request), context);
};
asyncExecute(new Runnable(fn));
}
Dms_enterpriseClient::ExecuteDataExportOutcomeCallable Dms_enterpriseClient::executeDataExportCallable(const ExecuteDataExportRequest &request) const
{
auto task = std::make_shared<std::packaged_task<ExecuteDataExportOutcome()>>(
[this, request]()
{
return this->executeDataExport(request);
});
asyncExecute(new Runnable([task]() { (*task)(); }));
return task->get_future();
}
Dms_enterpriseClient::GetApprovalDetailOutcome Dms_enterpriseClient::getApprovalDetail(const GetApprovalDetailRequest &request) const
{
auto endpointOutcome = endpointProvider_->getEndpoint();
if (!endpointOutcome.isSuccess())
return GetApprovalDetailOutcome(endpointOutcome.error());
auto outcome = makeRequest(endpointOutcome.result(), request);
if (outcome.isSuccess())
return GetApprovalDetailOutcome(GetApprovalDetailResult(outcome.result()));
else
return GetApprovalDetailOutcome(outcome.error());
}
void Dms_enterpriseClient::getApprovalDetailAsync(const GetApprovalDetailRequest& request, const GetApprovalDetailAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context) const
{
auto fn = [this, request, handler, context]()
{
handler(this, request, getApprovalDetail(request), context);
};
asyncExecute(new Runnable(fn));
}
Dms_enterpriseClient::GetApprovalDetailOutcomeCallable Dms_enterpriseClient::getApprovalDetailCallable(const GetApprovalDetailRequest &request) const
{
auto task = std::make_shared<std::packaged_task<GetApprovalDetailOutcome()>>(
[this, request]()
{
return this->getApprovalDetail(request);
});
asyncExecute(new Runnable([task]() { (*task)(); }));
return task->get_future();
}
Dms_enterpriseClient::GetDataCorrectBackupFilesOutcome Dms_enterpriseClient::getDataCorrectBackupFiles(const GetDataCorrectBackupFilesRequest &request) const
{
auto endpointOutcome = endpointProvider_->getEndpoint();
if (!endpointOutcome.isSuccess())
return GetDataCorrectBackupFilesOutcome(endpointOutcome.error());
auto outcome = makeRequest(endpointOutcome.result(), request);
if (outcome.isSuccess())
return GetDataCorrectBackupFilesOutcome(GetDataCorrectBackupFilesResult(outcome.result()));
else
return GetDataCorrectBackupFilesOutcome(outcome.error());
}
void Dms_enterpriseClient::getDataCorrectBackupFilesAsync(const GetDataCorrectBackupFilesRequest& request, const GetDataCorrectBackupFilesAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context) const
{
auto fn = [this, request, handler, context]()
{
handler(this, request, getDataCorrectBackupFiles(request), context);
};
asyncExecute(new Runnable(fn));
}
Dms_enterpriseClient::GetDataCorrectBackupFilesOutcomeCallable Dms_enterpriseClient::getDataCorrectBackupFilesCallable(const GetDataCorrectBackupFilesRequest &request) const
{
auto task = std::make_shared<std::packaged_task<GetDataCorrectBackupFilesOutcome()>>(
[this, request]()
{
return this->getDataCorrectBackupFiles(request);
});
asyncExecute(new Runnable([task]() { (*task)(); }));
return task->get_future();
}
Dms_enterpriseClient::GetDataCorrectOrderDetailOutcome Dms_enterpriseClient::getDataCorrectOrderDetail(const GetDataCorrectOrderDetailRequest &request) const
{
auto endpointOutcome = endpointProvider_->getEndpoint();
if (!endpointOutcome.isSuccess())
return GetDataCorrectOrderDetailOutcome(endpointOutcome.error());
auto outcome = makeRequest(endpointOutcome.result(), request);
if (outcome.isSuccess())
return GetDataCorrectOrderDetailOutcome(GetDataCorrectOrderDetailResult(outcome.result()));
else
return GetDataCorrectOrderDetailOutcome(outcome.error());
}
void Dms_enterpriseClient::getDataCorrectOrderDetailAsync(const GetDataCorrectOrderDetailRequest& request, const GetDataCorrectOrderDetailAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context) const
{
auto fn = [this, request, handler, context]()
{
handler(this, request, getDataCorrectOrderDetail(request), context);
};
asyncExecute(new Runnable(fn));
}
Dms_enterpriseClient::GetDataCorrectOrderDetailOutcomeCallable Dms_enterpriseClient::getDataCorrectOrderDetailCallable(const GetDataCorrectOrderDetailRequest &request) const
{
auto task = std::make_shared<std::packaged_task<GetDataCorrectOrderDetailOutcome()>>(
[this, request]()
{
return this->getDataCorrectOrderDetail(request);
});
asyncExecute(new Runnable([task]() { (*task)(); }));
return task->get_future();
}
Dms_enterpriseClient::GetDataExportDownloadURLOutcome Dms_enterpriseClient::getDataExportDownloadURL(const GetDataExportDownloadURLRequest &request) const
{
auto endpointOutcome = endpointProvider_->getEndpoint();
if (!endpointOutcome.isSuccess())
return GetDataExportDownloadURLOutcome(endpointOutcome.error());
auto outcome = makeRequest(endpointOutcome.result(), request);
if (outcome.isSuccess())
return GetDataExportDownloadURLOutcome(GetDataExportDownloadURLResult(outcome.result()));
else
return GetDataExportDownloadURLOutcome(outcome.error());
}
void Dms_enterpriseClient::getDataExportDownloadURLAsync(const GetDataExportDownloadURLRequest& request, const GetDataExportDownloadURLAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context) const
{
auto fn = [this, request, handler, context]()
{
handler(this, request, getDataExportDownloadURL(request), context);
};
asyncExecute(new Runnable(fn));
}
Dms_enterpriseClient::GetDataExportDownloadURLOutcomeCallable Dms_enterpriseClient::getDataExportDownloadURLCallable(const GetDataExportDownloadURLRequest &request) const
{
auto task = std::make_shared<std::packaged_task<GetDataExportDownloadURLOutcome()>>(
[this, request]()
{
return this->getDataExportDownloadURL(request);
});
asyncExecute(new Runnable([task]() { (*task)(); }));
return task->get_future();
}
Dms_enterpriseClient::GetDataExportOrderDetailOutcome Dms_enterpriseClient::getDataExportOrderDetail(const GetDataExportOrderDetailRequest &request) const
{
auto endpointOutcome = endpointProvider_->getEndpoint();
if (!endpointOutcome.isSuccess())
return GetDataExportOrderDetailOutcome(endpointOutcome.error());
auto outcome = makeRequest(endpointOutcome.result(), request);
if (outcome.isSuccess())
return GetDataExportOrderDetailOutcome(GetDataExportOrderDetailResult(outcome.result()));
else
return GetDataExportOrderDetailOutcome(outcome.error());
}
void Dms_enterpriseClient::getDataExportOrderDetailAsync(const GetDataExportOrderDetailRequest& request, const GetDataExportOrderDetailAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context) const
{
auto fn = [this, request, handler, context]()
{
handler(this, request, getDataExportOrderDetail(request), context);
};
asyncExecute(new Runnable(fn));
}
Dms_enterpriseClient::GetDataExportOrderDetailOutcomeCallable Dms_enterpriseClient::getDataExportOrderDetailCallable(const GetDataExportOrderDetailRequest &request) const
{
auto task = std::make_shared<std::packaged_task<GetDataExportOrderDetailOutcome()>>(
[this, request]()
{
return this->getDataExportOrderDetail(request);
});
asyncExecute(new Runnable([task]() { (*task)(); }));
return task->get_future();
}
Dms_enterpriseClient::GetDatabaseOutcome Dms_enterpriseClient::getDatabase(const GetDatabaseRequest &request) const
{
auto endpointOutcome = endpointProvider_->getEndpoint();
if (!endpointOutcome.isSuccess())
return GetDatabaseOutcome(endpointOutcome.error());
auto outcome = makeRequest(endpointOutcome.result(), request);
if (outcome.isSuccess())
return GetDatabaseOutcome(GetDatabaseResult(outcome.result()));
else
return GetDatabaseOutcome(outcome.error());
}
void Dms_enterpriseClient::getDatabaseAsync(const GetDatabaseRequest& request, const GetDatabaseAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context) const
{
auto fn = [this, request, handler, context]()
{
handler(this, request, getDatabase(request), context);
};
asyncExecute(new Runnable(fn));
}
Dms_enterpriseClient::GetDatabaseOutcomeCallable Dms_enterpriseClient::getDatabaseCallable(const GetDatabaseRequest &request) const
{
auto task = std::make_shared<std::packaged_task<GetDatabaseOutcome()>>(
[this, request]()
{
return this->getDatabase(request);
});
asyncExecute(new Runnable([task]() { (*task)(); }));
return task->get_future();
}
Dms_enterpriseClient::GetInstanceOutcome Dms_enterpriseClient::getInstance(const GetInstanceRequest &request) const
{
auto endpointOutcome = endpointProvider_->getEndpoint();
if (!endpointOutcome.isSuccess())
return GetInstanceOutcome(endpointOutcome.error());
auto outcome = makeRequest(endpointOutcome.result(), request);
if (outcome.isSuccess())
return GetInstanceOutcome(GetInstanceResult(outcome.result()));
else
return GetInstanceOutcome(outcome.error());
}
void Dms_enterpriseClient::getInstanceAsync(const GetInstanceRequest& request, const GetInstanceAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context) const
{
auto fn = [this, request, handler, context]()
{
handler(this, request, getInstance(request), context);
};
asyncExecute(new Runnable(fn));
}
Dms_enterpriseClient::GetInstanceOutcomeCallable Dms_enterpriseClient::getInstanceCallable(const GetInstanceRequest &request) const
{
auto task = std::make_shared<std::packaged_task<GetInstanceOutcome()>>(
[this, request]()
{
return this->getInstance(request);
});
asyncExecute(new Runnable([task]() { (*task)(); }));
return task->get_future();
}
Dms_enterpriseClient::GetLogicDatabaseOutcome Dms_enterpriseClient::getLogicDatabase(const GetLogicDatabaseRequest &request) const
{
auto endpointOutcome = endpointProvider_->getEndpoint();
if (!endpointOutcome.isSuccess())
return GetLogicDatabaseOutcome(endpointOutcome.error());
auto outcome = makeRequest(endpointOutcome.result(), request);
if (outcome.isSuccess())
return GetLogicDatabaseOutcome(GetLogicDatabaseResult(outcome.result()));
else
return GetLogicDatabaseOutcome(outcome.error());
}
void Dms_enterpriseClient::getLogicDatabaseAsync(const GetLogicDatabaseRequest& request, const GetLogicDatabaseAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context) const
{
auto fn = [this, request, handler, context]()
{
handler(this, request, getLogicDatabase(request), context);
};
asyncExecute(new Runnable(fn));
}
Dms_enterpriseClient::GetLogicDatabaseOutcomeCallable Dms_enterpriseClient::getLogicDatabaseCallable(const GetLogicDatabaseRequest &request) const
{
auto task = std::make_shared<std::packaged_task<GetLogicDatabaseOutcome()>>(
[this, request]()
{
return this->getLogicDatabase(request);
});
asyncExecute(new Runnable([task]() { (*task)(); }));
return task->get_future();
}
Dms_enterpriseClient::GetOpLogOutcome Dms_enterpriseClient::getOpLog(const GetOpLogRequest &request) const
{
auto endpointOutcome = endpointProvider_->getEndpoint();
if (!endpointOutcome.isSuccess())
return GetOpLogOutcome(endpointOutcome.error());
auto outcome = makeRequest(endpointOutcome.result(), request);
if (outcome.isSuccess())
return GetOpLogOutcome(GetOpLogResult(outcome.result()));
else
return GetOpLogOutcome(outcome.error());
}
void Dms_enterpriseClient::getOpLogAsync(const GetOpLogRequest& request, const GetOpLogAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context) const
{
auto fn = [this, request, handler, context]()
{
handler(this, request, getOpLog(request), context);
};
asyncExecute(new Runnable(fn));
}
Dms_enterpriseClient::GetOpLogOutcomeCallable Dms_enterpriseClient::getOpLogCallable(const GetOpLogRequest &request) const
{
auto task = std::make_shared<std::packaged_task<GetOpLogOutcome()>>(
[this, request]()
{
return this->getOpLog(request);
});
asyncExecute(new Runnable([task]() { (*task)(); }));
return task->get_future();
}
Dms_enterpriseClient::GetOrderBaseInfoOutcome Dms_enterpriseClient::getOrderBaseInfo(const GetOrderBaseInfoRequest &request) const
{
auto endpointOutcome = endpointProvider_->getEndpoint();
if (!endpointOutcome.isSuccess())
return GetOrderBaseInfoOutcome(endpointOutcome.error());
auto outcome = makeRequest(endpointOutcome.result(), request);
if (outcome.isSuccess())
return GetOrderBaseInfoOutcome(GetOrderBaseInfoResult(outcome.result()));
else
return GetOrderBaseInfoOutcome(outcome.error());
}
void Dms_enterpriseClient::getOrderBaseInfoAsync(const GetOrderBaseInfoRequest& request, const GetOrderBaseInfoAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context) const
{
auto fn = [this, request, handler, context]()
{
handler(this, request, getOrderBaseInfo(request), context);
};
asyncExecute(new Runnable(fn));
}
Dms_enterpriseClient::GetOrderBaseInfoOutcomeCallable Dms_enterpriseClient::getOrderBaseInfoCallable(const GetOrderBaseInfoRequest &request) const
{
auto task = std::make_shared<std::packaged_task<GetOrderBaseInfoOutcome()>>(
[this, request]()
{
return this->getOrderBaseInfo(request);
});
asyncExecute(new Runnable([task]() { (*task)(); }));
return task->get_future();
}
Dms_enterpriseClient::GetUserOutcome Dms_enterpriseClient::getUser(const GetUserRequest &request) const
{
auto endpointOutcome = endpointProvider_->getEndpoint();
if (!endpointOutcome.isSuccess())
return GetUserOutcome(endpointOutcome.error());
auto outcome = makeRequest(endpointOutcome.result(), request);
if (outcome.isSuccess())
return GetUserOutcome(GetUserResult(outcome.result()));
else
return GetUserOutcome(outcome.error());
}
void Dms_enterpriseClient::getUserAsync(const GetUserRequest& request, const GetUserAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context) const
{
auto fn = [this, request, handler, context]()
{
handler(this, request, getUser(request), context);
};
asyncExecute(new Runnable(fn));
}
Dms_enterpriseClient::GetUserOutcomeCallable Dms_enterpriseClient::getUserCallable(const GetUserRequest &request) const
{
auto task = std::make_shared<std::packaged_task<GetUserOutcome()>>(
[this, request]()
{
return this->getUser(request);
});
asyncExecute(new Runnable([task]() { (*task)(); }));
return task->get_future();
}
Dms_enterpriseClient::GrantUserPermissionOutcome Dms_enterpriseClient::grantUserPermission(const GrantUserPermissionRequest &request) const
{
auto endpointOutcome = endpointProvider_->getEndpoint();
if (!endpointOutcome.isSuccess())
return GrantUserPermissionOutcome(endpointOutcome.error());
auto outcome = makeRequest(endpointOutcome.result(), request);
if (outcome.isSuccess())
return GrantUserPermissionOutcome(GrantUserPermissionResult(outcome.result()));
else
return GrantUserPermissionOutcome(outcome.error());
}
void Dms_enterpriseClient::grantUserPermissionAsync(const GrantUserPermissionRequest& request, const GrantUserPermissionAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context) const
{
auto fn = [this, request, handler, context]()
{
handler(this, request, grantUserPermission(request), context);
};
asyncExecute(new Runnable(fn));
}
Dms_enterpriseClient::GrantUserPermissionOutcomeCallable Dms_enterpriseClient::grantUserPermissionCallable(const GrantUserPermissionRequest &request) const
{
auto task = std::make_shared<std::packaged_task<GrantUserPermissionOutcome()>>(
[this, request]()
{
return this->grantUserPermission(request);
});
asyncExecute(new Runnable([task]() { (*task)(); }));
return task->get_future();
}
Dms_enterpriseClient::ListColumnsOutcome Dms_enterpriseClient::listColumns(const ListColumnsRequest &request) const
{
auto endpointOutcome = endpointProvider_->getEndpoint();
if (!endpointOutcome.isSuccess())
return ListColumnsOutcome(endpointOutcome.error());
auto outcome = makeRequest(endpointOutcome.result(), request);
if (outcome.isSuccess())
return ListColumnsOutcome(ListColumnsResult(outcome.result()));
else
return ListColumnsOutcome(outcome.error());
}
void Dms_enterpriseClient::listColumnsAsync(const ListColumnsRequest& request, const ListColumnsAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context) const
{
auto fn = [this, request, handler, context]()
{
handler(this, request, listColumns(request), context);
};
asyncExecute(new Runnable(fn));
}
Dms_enterpriseClient::ListColumnsOutcomeCallable Dms_enterpriseClient::listColumnsCallable(const ListColumnsRequest &request) const
{
auto task = std::make_shared<std::packaged_task<ListColumnsOutcome()>>(
[this, request]()
{
return this->listColumns(request);
});
asyncExecute(new Runnable([task]() { (*task)(); }));
return task->get_future();
}
Dms_enterpriseClient::ListDatabaseUserPermssionsOutcome Dms_enterpriseClient::listDatabaseUserPermssions(const ListDatabaseUserPermssionsRequest &request) const
{
auto endpointOutcome = endpointProvider_->getEndpoint();
if (!endpointOutcome.isSuccess())
return ListDatabaseUserPermssionsOutcome(endpointOutcome.error());
auto outcome = makeRequest(endpointOutcome.result(), request);
if (outcome.isSuccess())
return ListDatabaseUserPermssionsOutcome(ListDatabaseUserPermssionsResult(outcome.result()));
else
return ListDatabaseUserPermssionsOutcome(outcome.error());
}
void Dms_enterpriseClient::listDatabaseUserPermssionsAsync(const ListDatabaseUserPermssionsRequest& request, const ListDatabaseUserPermssionsAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context) const
{
auto fn = [this, request, handler, context]()
{
handler(this, request, listDatabaseUserPermssions(request), context);
};
asyncExecute(new Runnable(fn));
}
Dms_enterpriseClient::ListDatabaseUserPermssionsOutcomeCallable Dms_enterpriseClient::listDatabaseUserPermssionsCallable(const ListDatabaseUserPermssionsRequest &request) const
{
auto task = std::make_shared<std::packaged_task<ListDatabaseUserPermssionsOutcome()>>(
[this, request]()
{
return this->listDatabaseUserPermssions(request);
});
asyncExecute(new Runnable([task]() { (*task)(); }));
return task->get_future();
}
Dms_enterpriseClient::ListDatabasesOutcome Dms_enterpriseClient::listDatabases(const ListDatabasesRequest &request) const
{
auto endpointOutcome = endpointProvider_->getEndpoint();
if (!endpointOutcome.isSuccess())
return ListDatabasesOutcome(endpointOutcome.error());
auto outcome = makeRequest(endpointOutcome.result(), request);
if (outcome.isSuccess())
return ListDatabasesOutcome(ListDatabasesResult(outcome.result()));
else
return ListDatabasesOutcome(outcome.error());
}
void Dms_enterpriseClient::listDatabasesAsync(const ListDatabasesRequest& request, const ListDatabasesAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context) const
{
auto fn = [this, request, handler, context]()
{
handler(this, request, listDatabases(request), context);
};
asyncExecute(new Runnable(fn));
}
Dms_enterpriseClient::ListDatabasesOutcomeCallable Dms_enterpriseClient::listDatabasesCallable(const ListDatabasesRequest &request) const
{
auto task = std::make_shared<std::packaged_task<ListDatabasesOutcome()>>(
[this, request]()
{
return this->listDatabases(request);
});
asyncExecute(new Runnable([task]() { (*task)(); }));
return task->get_future();
}
Dms_enterpriseClient::ListIndexesOutcome Dms_enterpriseClient::listIndexes(const ListIndexesRequest &request) const
{
auto endpointOutcome = endpointProvider_->getEndpoint();
if (!endpointOutcome.isSuccess())
return ListIndexesOutcome(endpointOutcome.error());
auto outcome = makeRequest(endpointOutcome.result(), request);
if (outcome.isSuccess())
return ListIndexesOutcome(ListIndexesResult(outcome.result()));
else
return ListIndexesOutcome(outcome.error());
}
void Dms_enterpriseClient::listIndexesAsync(const ListIndexesRequest& request, const ListIndexesAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context) const
{
auto fn = [this, request, handler, context]()
{
handler(this, request, listIndexes(request), context);
};
asyncExecute(new Runnable(fn));
}
Dms_enterpriseClient::ListIndexesOutcomeCallable Dms_enterpriseClient::listIndexesCallable(const ListIndexesRequest &request) const
{
auto task = std::make_shared<std::packaged_task<ListIndexesOutcome()>>(
[this, request]()
{
return this->listIndexes(request);
});
asyncExecute(new Runnable([task]() { (*task)(); }));
return task->get_future();
}
Dms_enterpriseClient::ListInstancesOutcome Dms_enterpriseClient::listInstances(const ListInstancesRequest &request) const
{
auto endpointOutcome = endpointProvider_->getEndpoint();
if (!endpointOutcome.isSuccess())
return ListInstancesOutcome(endpointOutcome.error());
auto outcome = makeRequest(endpointOutcome.result(), request);
if (outcome.isSuccess())
return ListInstancesOutcome(ListInstancesResult(outcome.result()));
else
return ListInstancesOutcome(outcome.error());
}
void Dms_enterpriseClient::listInstancesAsync(const ListInstancesRequest& request, const ListInstancesAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context) const
{
auto fn = [this, request, handler, context]()
{
handler(this, request, listInstances(request), context);
};
asyncExecute(new Runnable(fn));
}
Dms_enterpriseClient::ListInstancesOutcomeCallable Dms_enterpriseClient::listInstancesCallable(const ListInstancesRequest &request) const
{
auto task = std::make_shared<std::packaged_task<ListInstancesOutcome()>>(
[this, request]()
{
return this->listInstances(request);
});
asyncExecute(new Runnable([task]() { (*task)(); }));
return task->get_future();
}
Dms_enterpriseClient::ListLogicDatabasesOutcome Dms_enterpriseClient::listLogicDatabases(const ListLogicDatabasesRequest &request) const
{
auto endpointOutcome = endpointProvider_->getEndpoint();
if (!endpointOutcome.isSuccess())
return ListLogicDatabasesOutcome(endpointOutcome.error());
auto outcome = makeRequest(endpointOutcome.result(), request);
if (outcome.isSuccess())
return ListLogicDatabasesOutcome(ListLogicDatabasesResult(outcome.result()));
else
return ListLogicDatabasesOutcome(outcome.error());
}
void Dms_enterpriseClient::listLogicDatabasesAsync(const ListLogicDatabasesRequest& request, const ListLogicDatabasesAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context) const
{
auto fn = [this, request, handler, context]()
{
handler(this, request, listLogicDatabases(request), context);
};
asyncExecute(new Runnable(fn));
}
Dms_enterpriseClient::ListLogicDatabasesOutcomeCallable Dms_enterpriseClient::listLogicDatabasesCallable(const ListLogicDatabasesRequest &request) const
{
auto task = std::make_shared<std::packaged_task<ListLogicDatabasesOutcome()>>(
[this, request]()
{
return this->listLogicDatabases(request);
});
asyncExecute(new Runnable([task]() { (*task)(); }));
return task->get_future();
}
Dms_enterpriseClient::ListLogicTablesOutcome Dms_enterpriseClient::listLogicTables(const ListLogicTablesRequest &request) const
{
auto endpointOutcome = endpointProvider_->getEndpoint();
if (!endpointOutcome.isSuccess())
return ListLogicTablesOutcome(endpointOutcome.error());
auto outcome = makeRequest(endpointOutcome.result(), request);
if (outcome.isSuccess())
return ListLogicTablesOutcome(ListLogicTablesResult(outcome.result()));
else
return ListLogicTablesOutcome(outcome.error());
}
void Dms_enterpriseClient::listLogicTablesAsync(const ListLogicTablesRequest& request, const ListLogicTablesAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context) const
{
auto fn = [this, request, handler, context]()
{
handler(this, request, listLogicTables(request), context);
};
asyncExecute(new Runnable(fn));
}
Dms_enterpriseClient::ListLogicTablesOutcomeCallable Dms_enterpriseClient::listLogicTablesCallable(const ListLogicTablesRequest &request) const
{
auto task = std::make_shared<std::packaged_task<ListLogicTablesOutcome()>>(
[this, request]()
{
return this->listLogicTables(request);
});
asyncExecute(new Runnable([task]() { (*task)(); }));
return task->get_future();
}
Dms_enterpriseClient::ListOrdersOutcome Dms_enterpriseClient::listOrders(const ListOrdersRequest &request) const
{
auto endpointOutcome = endpointProvider_->getEndpoint();
if (!endpointOutcome.isSuccess())
return ListOrdersOutcome(endpointOutcome.error());
auto outcome = makeRequest(endpointOutcome.result(), request);
if (outcome.isSuccess())
return ListOrdersOutcome(ListOrdersResult(outcome.result()));
else
return ListOrdersOutcome(outcome.error());
}
void Dms_enterpriseClient::listOrdersAsync(const ListOrdersRequest& request, const ListOrdersAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context) const
{
auto fn = [this, request, handler, context]()
{
handler(this, request, listOrders(request), context);
};
asyncExecute(new Runnable(fn));
}
Dms_enterpriseClient::ListOrdersOutcomeCallable Dms_enterpriseClient::listOrdersCallable(const ListOrdersRequest &request) const
{
auto task = std::make_shared<std::packaged_task<ListOrdersOutcome()>>(
[this, request]()
{
return this->listOrders(request);
});
asyncExecute(new Runnable([task]() { (*task)(); }));
return task->get_future();
}
Dms_enterpriseClient::ListSensitiveColumnsOutcome Dms_enterpriseClient::listSensitiveColumns(const ListSensitiveColumnsRequest &request) const
{
auto endpointOutcome = endpointProvider_->getEndpoint();
if (!endpointOutcome.isSuccess())
return ListSensitiveColumnsOutcome(endpointOutcome.error());
auto outcome = makeRequest(endpointOutcome.result(), request);
if (outcome.isSuccess())
return ListSensitiveColumnsOutcome(ListSensitiveColumnsResult(outcome.result()));
else
return ListSensitiveColumnsOutcome(outcome.error());
}
void Dms_enterpriseClient::listSensitiveColumnsAsync(const ListSensitiveColumnsRequest& request, const ListSensitiveColumnsAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context) const
{
auto fn = [this, request, handler, context]()
{
handler(this, request, listSensitiveColumns(request), context);
};
asyncExecute(new Runnable(fn));
}
Dms_enterpriseClient::ListSensitiveColumnsOutcomeCallable Dms_enterpriseClient::listSensitiveColumnsCallable(const ListSensitiveColumnsRequest &request) const
{
auto task = std::make_shared<std::packaged_task<ListSensitiveColumnsOutcome()>>(
[this, request]()
{
return this->listSensitiveColumns(request);
});
asyncExecute(new Runnable([task]() { (*task)(); }));
return task->get_future();
}
Dms_enterpriseClient::ListSensitiveColumnsDetailOutcome Dms_enterpriseClient::listSensitiveColumnsDetail(const ListSensitiveColumnsDetailRequest &request) const
{
auto endpointOutcome = endpointProvider_->getEndpoint();
if (!endpointOutcome.isSuccess())
return ListSensitiveColumnsDetailOutcome(endpointOutcome.error());
auto outcome = makeRequest(endpointOutcome.result(), request);
if (outcome.isSuccess())
return ListSensitiveColumnsDetailOutcome(ListSensitiveColumnsDetailResult(outcome.result()));
else
return ListSensitiveColumnsDetailOutcome(outcome.error());
}
void Dms_enterpriseClient::listSensitiveColumnsDetailAsync(const ListSensitiveColumnsDetailRequest& request, const ListSensitiveColumnsDetailAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context) const
{
auto fn = [this, request, handler, context]()
{
handler(this, request, listSensitiveColumnsDetail(request), context);
};
asyncExecute(new Runnable(fn));
}
Dms_enterpriseClient::ListSensitiveColumnsDetailOutcomeCallable Dms_enterpriseClient::listSensitiveColumnsDetailCallable(const ListSensitiveColumnsDetailRequest &request) const
{
auto task = std::make_shared<std::packaged_task<ListSensitiveColumnsDetailOutcome()>>(
[this, request]()
{
return this->listSensitiveColumnsDetail(request);
});
asyncExecute(new Runnable([task]() { (*task)(); }));
return task->get_future();
}
Dms_enterpriseClient::ListTablesOutcome Dms_enterpriseClient::listTables(const ListTablesRequest &request) const
{
auto endpointOutcome = endpointProvider_->getEndpoint();
if (!endpointOutcome.isSuccess())
return ListTablesOutcome(endpointOutcome.error());
auto outcome = makeRequest(endpointOutcome.result(), request);
if (outcome.isSuccess())
return ListTablesOutcome(ListTablesResult(outcome.result()));
else
return ListTablesOutcome(outcome.error());
}
void Dms_enterpriseClient::listTablesAsync(const ListTablesRequest& request, const ListTablesAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context) const
{
auto fn = [this, request, handler, context]()
{
handler(this, request, listTables(request), context);
};
asyncExecute(new Runnable(fn));
}
Dms_enterpriseClient::ListTablesOutcomeCallable Dms_enterpriseClient::listTablesCallable(const ListTablesRequest &request) const
{
auto task = std::make_shared<std::packaged_task<ListTablesOutcome()>>(
[this, request]()
{
return this->listTables(request);
});
asyncExecute(new Runnable([task]() { (*task)(); }));
return task->get_future();
}
Dms_enterpriseClient::ListUserPermissionsOutcome Dms_enterpriseClient::listUserPermissions(const ListUserPermissionsRequest &request) const
{
auto endpointOutcome = endpointProvider_->getEndpoint();
if (!endpointOutcome.isSuccess())
return ListUserPermissionsOutcome(endpointOutcome.error());
auto outcome = makeRequest(endpointOutcome.result(), request);
if (outcome.isSuccess())
return ListUserPermissionsOutcome(ListUserPermissionsResult(outcome.result()));
else
return ListUserPermissionsOutcome(outcome.error());
}
void Dms_enterpriseClient::listUserPermissionsAsync(const ListUserPermissionsRequest& request, const ListUserPermissionsAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context) const
{
auto fn = [this, request, handler, context]()
{
handler(this, request, listUserPermissions(request), context);
};
asyncExecute(new Runnable(fn));
}
Dms_enterpriseClient::ListUserPermissionsOutcomeCallable Dms_enterpriseClient::listUserPermissionsCallable(const ListUserPermissionsRequest &request) const
{
auto task = std::make_shared<std::packaged_task<ListUserPermissionsOutcome()>>(
[this, request]()
{
return this->listUserPermissions(request);
});
asyncExecute(new Runnable([task]() { (*task)(); }));
return task->get_future();
}
Dms_enterpriseClient::ListUsersOutcome Dms_enterpriseClient::listUsers(const ListUsersRequest &request) const
{
auto endpointOutcome = endpointProvider_->getEndpoint();
if (!endpointOutcome.isSuccess())
return ListUsersOutcome(endpointOutcome.error());
auto outcome = makeRequest(endpointOutcome.result(), request);
if (outcome.isSuccess())
return ListUsersOutcome(ListUsersResult(outcome.result()));
else
return ListUsersOutcome(outcome.error());
}
void Dms_enterpriseClient::listUsersAsync(const ListUsersRequest& request, const ListUsersAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context) const
{
auto fn = [this, request, handler, context]()
{
handler(this, request, listUsers(request), context);
};
asyncExecute(new Runnable(fn));
}
Dms_enterpriseClient::ListUsersOutcomeCallable Dms_enterpriseClient::listUsersCallable(const ListUsersRequest &request) const
{
auto task = std::make_shared<std::packaged_task<ListUsersOutcome()>>(
[this, request]()
{
return this->listUsers(request);
});
asyncExecute(new Runnable([task]() { (*task)(); }));
return task->get_future();
}
Dms_enterpriseClient::ListWorkFlowNodesOutcome Dms_enterpriseClient::listWorkFlowNodes(const ListWorkFlowNodesRequest &request) const
{
auto endpointOutcome = endpointProvider_->getEndpoint();
if (!endpointOutcome.isSuccess())
return ListWorkFlowNodesOutcome(endpointOutcome.error());
auto outcome = makeRequest(endpointOutcome.result(), request);
if (outcome.isSuccess())
return ListWorkFlowNodesOutcome(ListWorkFlowNodesResult(outcome.result()));
else
return ListWorkFlowNodesOutcome(outcome.error());
}
void Dms_enterpriseClient::listWorkFlowNodesAsync(const ListWorkFlowNodesRequest& request, const ListWorkFlowNodesAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context) const
{
auto fn = [this, request, handler, context]()
{
handler(this, request, listWorkFlowNodes(request), context);
};
asyncExecute(new Runnable(fn));
}
Dms_enterpriseClient::ListWorkFlowNodesOutcomeCallable Dms_enterpriseClient::listWorkFlowNodesCallable(const ListWorkFlowNodesRequest &request) const
{
auto task = std::make_shared<std::packaged_task<ListWorkFlowNodesOutcome()>>(
[this, request]()
{
return this->listWorkFlowNodes(request);
});
asyncExecute(new Runnable([task]() { (*task)(); }));
return task->get_future();
}
Dms_enterpriseClient::ListWorkFlowTemplatesOutcome Dms_enterpriseClient::listWorkFlowTemplates(const ListWorkFlowTemplatesRequest &request) const
{
auto endpointOutcome = endpointProvider_->getEndpoint();
if (!endpointOutcome.isSuccess())
return ListWorkFlowTemplatesOutcome(endpointOutcome.error());
auto outcome = makeRequest(endpointOutcome.result(), request);
if (outcome.isSuccess())
return ListWorkFlowTemplatesOutcome(ListWorkFlowTemplatesResult(outcome.result()));
else
return ListWorkFlowTemplatesOutcome(outcome.error());
}
void Dms_enterpriseClient::listWorkFlowTemplatesAsync(const ListWorkFlowTemplatesRequest& request, const ListWorkFlowTemplatesAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context) const
{
auto fn = [this, request, handler, context]()
{
handler(this, request, listWorkFlowTemplates(request), context);
};
asyncExecute(new Runnable(fn));
}
Dms_enterpriseClient::ListWorkFlowTemplatesOutcomeCallable Dms_enterpriseClient::listWorkFlowTemplatesCallable(const ListWorkFlowTemplatesRequest &request) const
{
auto task = std::make_shared<std::packaged_task<ListWorkFlowTemplatesOutcome()>>(
[this, request]()
{
return this->listWorkFlowTemplates(request);
});
asyncExecute(new Runnable([task]() { (*task)(); }));
return task->get_future();
}
Dms_enterpriseClient::RegisterInstanceOutcome Dms_enterpriseClient::registerInstance(const RegisterInstanceRequest &request) const
{
auto endpointOutcome = endpointProvider_->getEndpoint();
if (!endpointOutcome.isSuccess())
return RegisterInstanceOutcome(endpointOutcome.error());
auto outcome = makeRequest(endpointOutcome.result(), request);
if (outcome.isSuccess())
return RegisterInstanceOutcome(RegisterInstanceResult(outcome.result()));
else
return RegisterInstanceOutcome(outcome.error());
}
void Dms_enterpriseClient::registerInstanceAsync(const RegisterInstanceRequest& request, const RegisterInstanceAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context) const
{
auto fn = [this, request, handler, context]()
{
handler(this, request, registerInstance(request), context);
};
asyncExecute(new Runnable(fn));
}
Dms_enterpriseClient::RegisterInstanceOutcomeCallable Dms_enterpriseClient::registerInstanceCallable(const RegisterInstanceRequest &request) const
{
auto task = std::make_shared<std::packaged_task<RegisterInstanceOutcome()>>(
[this, request]()
{
return this->registerInstance(request);
});
asyncExecute(new Runnable([task]() { (*task)(); }));
return task->get_future();
}
Dms_enterpriseClient::RegisterUserOutcome Dms_enterpriseClient::registerUser(const RegisterUserRequest &request) const
{
auto endpointOutcome = endpointProvider_->getEndpoint();
if (!endpointOutcome.isSuccess())
return RegisterUserOutcome(endpointOutcome.error());
auto outcome = makeRequest(endpointOutcome.result(), request);
if (outcome.isSuccess())
return RegisterUserOutcome(RegisterUserResult(outcome.result()));
else
return RegisterUserOutcome(outcome.error());
}
void Dms_enterpriseClient::registerUserAsync(const RegisterUserRequest& request, const RegisterUserAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context) const
{
auto fn = [this, request, handler, context]()
{
handler(this, request, registerUser(request), context);
};
asyncExecute(new Runnable(fn));
}
Dms_enterpriseClient::RegisterUserOutcomeCallable Dms_enterpriseClient::registerUserCallable(const RegisterUserRequest &request) const
{
auto task = std::make_shared<std::packaged_task<RegisterUserOutcome()>>(
[this, request]()
{
return this->registerUser(request);
});
asyncExecute(new Runnable([task]() { (*task)(); }));
return task->get_future();
}
Dms_enterpriseClient::RevokeUserPermissionOutcome Dms_enterpriseClient::revokeUserPermission(const RevokeUserPermissionRequest &request) const
{
auto endpointOutcome = endpointProvider_->getEndpoint();
if (!endpointOutcome.isSuccess())
return RevokeUserPermissionOutcome(endpointOutcome.error());
auto outcome = makeRequest(endpointOutcome.result(), request);
if (outcome.isSuccess())
return RevokeUserPermissionOutcome(RevokeUserPermissionResult(outcome.result()));
else
return RevokeUserPermissionOutcome(outcome.error());
}
void Dms_enterpriseClient::revokeUserPermissionAsync(const RevokeUserPermissionRequest& request, const RevokeUserPermissionAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context) const
{
auto fn = [this, request, handler, context]()
{
handler(this, request, revokeUserPermission(request), context);
};
asyncExecute(new Runnable(fn));
}
Dms_enterpriseClient::RevokeUserPermissionOutcomeCallable Dms_enterpriseClient::revokeUserPermissionCallable(const RevokeUserPermissionRequest &request) const
{
auto task = std::make_shared<std::packaged_task<RevokeUserPermissionOutcome()>>(
[this, request]()
{
return this->revokeUserPermission(request);
});
asyncExecute(new Runnable([task]() { (*task)(); }));
return task->get_future();
}
Dms_enterpriseClient::SearchDatabaseOutcome Dms_enterpriseClient::searchDatabase(const SearchDatabaseRequest &request) const
{
auto endpointOutcome = endpointProvider_->getEndpoint();
if (!endpointOutcome.isSuccess())
return SearchDatabaseOutcome(endpointOutcome.error());
auto outcome = makeRequest(endpointOutcome.result(), request);
if (outcome.isSuccess())
return SearchDatabaseOutcome(SearchDatabaseResult(outcome.result()));
else
return SearchDatabaseOutcome(outcome.error());
}
void Dms_enterpriseClient::searchDatabaseAsync(const SearchDatabaseRequest& request, const SearchDatabaseAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context) const
{
auto fn = [this, request, handler, context]()
{
handler(this, request, searchDatabase(request), context);
};
asyncExecute(new Runnable(fn));
}
Dms_enterpriseClient::SearchDatabaseOutcomeCallable Dms_enterpriseClient::searchDatabaseCallable(const SearchDatabaseRequest &request) const
{
auto task = std::make_shared<std::packaged_task<SearchDatabaseOutcome()>>(
[this, request]()
{
return this->searchDatabase(request);
});
asyncExecute(new Runnable([task]() { (*task)(); }));
return task->get_future();
}
Dms_enterpriseClient::SearchTableOutcome Dms_enterpriseClient::searchTable(const SearchTableRequest &request) const
{
auto endpointOutcome = endpointProvider_->getEndpoint();
if (!endpointOutcome.isSuccess())
return SearchTableOutcome(endpointOutcome.error());
auto outcome = makeRequest(endpointOutcome.result(), request);
if (outcome.isSuccess())
return SearchTableOutcome(SearchTableResult(outcome.result()));
else
return SearchTableOutcome(outcome.error());
}
void Dms_enterpriseClient::searchTableAsync(const SearchTableRequest& request, const SearchTableAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context) const
{
auto fn = [this, request, handler, context]()
{
handler(this, request, searchTable(request), context);
};
asyncExecute(new Runnable(fn));
}
Dms_enterpriseClient::SearchTableOutcomeCallable Dms_enterpriseClient::searchTableCallable(const SearchTableRequest &request) const
{
auto task = std::make_shared<std::packaged_task<SearchTableOutcome()>>(
[this, request]()
{
return this->searchTable(request);
});
asyncExecute(new Runnable([task]() { (*task)(); }));
return task->get_future();
}
Dms_enterpriseClient::SetOwnersOutcome Dms_enterpriseClient::setOwners(const SetOwnersRequest &request) const
{
auto endpointOutcome = endpointProvider_->getEndpoint();
if (!endpointOutcome.isSuccess())
return SetOwnersOutcome(endpointOutcome.error());
auto outcome = makeRequest(endpointOutcome.result(), request);
if (outcome.isSuccess())
return SetOwnersOutcome(SetOwnersResult(outcome.result()));
else
return SetOwnersOutcome(outcome.error());
}
void Dms_enterpriseClient::setOwnersAsync(const SetOwnersRequest& request, const SetOwnersAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context) const
{
auto fn = [this, request, handler, context]()
{
handler(this, request, setOwners(request), context);
};
asyncExecute(new Runnable(fn));
}
Dms_enterpriseClient::SetOwnersOutcomeCallable Dms_enterpriseClient::setOwnersCallable(const SetOwnersRequest &request) const
{
auto task = std::make_shared<std::packaged_task<SetOwnersOutcome()>>(
[this, request]()
{
return this->setOwners(request);
});
asyncExecute(new Runnable([task]() { (*task)(); }));
return task->get_future();
}
Dms_enterpriseClient::SubmitOrderApprovalOutcome Dms_enterpriseClient::submitOrderApproval(const SubmitOrderApprovalRequest &request) const
{
auto endpointOutcome = endpointProvider_->getEndpoint();
if (!endpointOutcome.isSuccess())
return SubmitOrderApprovalOutcome(endpointOutcome.error());
auto outcome = makeRequest(endpointOutcome.result(), request);
if (outcome.isSuccess())
return SubmitOrderApprovalOutcome(SubmitOrderApprovalResult(outcome.result()));
else
return SubmitOrderApprovalOutcome(outcome.error());
}
void Dms_enterpriseClient::submitOrderApprovalAsync(const SubmitOrderApprovalRequest& request, const SubmitOrderApprovalAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context) const
{
auto fn = [this, request, handler, context]()
{
handler(this, request, submitOrderApproval(request), context);
};
asyncExecute(new Runnable(fn));
}
Dms_enterpriseClient::SubmitOrderApprovalOutcomeCallable Dms_enterpriseClient::submitOrderApprovalCallable(const SubmitOrderApprovalRequest &request) const
{
auto task = std::make_shared<std::packaged_task<SubmitOrderApprovalOutcome()>>(
[this, request]()
{
return this->submitOrderApproval(request);
});
asyncExecute(new Runnable([task]() { (*task)(); }));
return task->get_future();
}
Dms_enterpriseClient::SyncDatabaseMetaOutcome Dms_enterpriseClient::syncDatabaseMeta(const SyncDatabaseMetaRequest &request) const
{
auto endpointOutcome = endpointProvider_->getEndpoint();
if (!endpointOutcome.isSuccess())
return SyncDatabaseMetaOutcome(endpointOutcome.error());
auto outcome = makeRequest(endpointOutcome.result(), request);
if (outcome.isSuccess())
return SyncDatabaseMetaOutcome(SyncDatabaseMetaResult(outcome.result()));
else
return SyncDatabaseMetaOutcome(outcome.error());
}
void Dms_enterpriseClient::syncDatabaseMetaAsync(const SyncDatabaseMetaRequest& request, const SyncDatabaseMetaAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context) const
{
auto fn = [this, request, handler, context]()
{
handler(this, request, syncDatabaseMeta(request), context);
};
asyncExecute(new Runnable(fn));
}
Dms_enterpriseClient::SyncDatabaseMetaOutcomeCallable Dms_enterpriseClient::syncDatabaseMetaCallable(const SyncDatabaseMetaRequest &request) const
{
auto task = std::make_shared<std::packaged_task<SyncDatabaseMetaOutcome()>>(
[this, request]()
{
return this->syncDatabaseMeta(request);
});
asyncExecute(new Runnable([task]() { (*task)(); }));
return task->get_future();
}
Dms_enterpriseClient::SyncInstanceMetaOutcome Dms_enterpriseClient::syncInstanceMeta(const SyncInstanceMetaRequest &request) const
{
auto endpointOutcome = endpointProvider_->getEndpoint();
if (!endpointOutcome.isSuccess())
return SyncInstanceMetaOutcome(endpointOutcome.error());
auto outcome = makeRequest(endpointOutcome.result(), request);
if (outcome.isSuccess())
return SyncInstanceMetaOutcome(SyncInstanceMetaResult(outcome.result()));
else
return SyncInstanceMetaOutcome(outcome.error());
}
void Dms_enterpriseClient::syncInstanceMetaAsync(const SyncInstanceMetaRequest& request, const SyncInstanceMetaAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context) const
{
auto fn = [this, request, handler, context]()
{
handler(this, request, syncInstanceMeta(request), context);
};
asyncExecute(new Runnable(fn));
}
Dms_enterpriseClient::SyncInstanceMetaOutcomeCallable Dms_enterpriseClient::syncInstanceMetaCallable(const SyncInstanceMetaRequest &request) const
{
auto task = std::make_shared<std::packaged_task<SyncInstanceMetaOutcome()>>(
[this, request]()
{
return this->syncInstanceMeta(request);
});
asyncExecute(new Runnable([task]() { (*task)(); }));
return task->get_future();
}
Dms_enterpriseClient::UpdateInstanceOutcome Dms_enterpriseClient::updateInstance(const UpdateInstanceRequest &request) const
{
auto endpointOutcome = endpointProvider_->getEndpoint();
if (!endpointOutcome.isSuccess())
return UpdateInstanceOutcome(endpointOutcome.error());
auto outcome = makeRequest(endpointOutcome.result(), request);
if (outcome.isSuccess())
return UpdateInstanceOutcome(UpdateInstanceResult(outcome.result()));
else
return UpdateInstanceOutcome(outcome.error());
}
void Dms_enterpriseClient::updateInstanceAsync(const UpdateInstanceRequest& request, const UpdateInstanceAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context) const
{
auto fn = [this, request, handler, context]()
{
handler(this, request, updateInstance(request), context);
};
asyncExecute(new Runnable(fn));
}
Dms_enterpriseClient::UpdateInstanceOutcomeCallable Dms_enterpriseClient::updateInstanceCallable(const UpdateInstanceRequest &request) const
{
auto task = std::make_shared<std::packaged_task<UpdateInstanceOutcome()>>(
[this, request]()
{
return this->updateInstance(request);
});
asyncExecute(new Runnable([task]() { (*task)(); }));
return task->get_future();
}
Dms_enterpriseClient::UpdateUserOutcome Dms_enterpriseClient::updateUser(const UpdateUserRequest &request) const
{
auto endpointOutcome = endpointProvider_->getEndpoint();
if (!endpointOutcome.isSuccess())
return UpdateUserOutcome(endpointOutcome.error());
auto outcome = makeRequest(endpointOutcome.result(), request);
if (outcome.isSuccess())
return UpdateUserOutcome(UpdateUserResult(outcome.result()));
else
return UpdateUserOutcome(outcome.error());
}
void Dms_enterpriseClient::updateUserAsync(const UpdateUserRequest& request, const UpdateUserAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context) const
{
auto fn = [this, request, handler, context]()
{
handler(this, request, updateUser(request), context);
};
asyncExecute(new Runnable(fn));
}
Dms_enterpriseClient::UpdateUserOutcomeCallable Dms_enterpriseClient::updateUserCallable(const UpdateUserRequest &request) const
{
auto task = std::make_shared<std::packaged_task<UpdateUserOutcome()>>(
[this, request]()
{
return this->updateUser(request);
});
asyncExecute(new Runnable([task]() { (*task)(); }));
return task->get_future();
}
| [
"[email protected]"
] | |
96f7aaf2e200b78b3d0601d180ee960c8ec90836 | 0eff74b05b60098333ad66cf801bdd93becc9ea4 | /second/download/git/gumtree/git_repos_function_3519_git-2.11.4.cpp | c636962f1512374bc1ae15c608e0e4a6e09c96e4 | [] | no_license | niuxu18/logTracker-old | 97543445ea7e414ed40bdc681239365d33418975 | f2b060f13a0295387fe02187543db124916eb446 | refs/heads/master | 2021-09-13T21:39:37.686481 | 2017-12-11T03:36:34 | 2017-12-11T03:36:34 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 286 | cpp | static void merge_recursive_config(struct merge_options *o)
{
git_config_get_int("merge.verbosity", &o->verbosity);
git_config_get_int("diff.renamelimit", &o->diff_rename_limit);
git_config_get_int("merge.renamelimit", &o->merge_rename_limit);
git_config(git_xmerge_config, NULL);
} | [
"[email protected]"
] | |
bc0a075426d366fe45bd8f25647c61ad99ea1436 | 55ae9643ce366b1d5e05328703cd82af5bf2bde3 | /1918.cpp | b92e9dba9d0330eb5b4c1c60216709b627568615 | [] | no_license | thextroid/edunote | 486a9030cc60e1aca454d55d8228babe4d7cedf8 | 8fe6ac5929ce3fc322a2196ab716d4cc9136786e | refs/heads/master | 2021-01-19T21:40:43.428088 | 2017-04-19T01:59:11 | 2017-04-19T01:59:11 | 88,685,790 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 665 | cpp | #include <iostream>
#include <vector>
#include <cstdio>
#define MAX 1e9
using namespace std;
vector<int> w;
// build binary numbers less or equals 1e9
void build(int bit,int num,int pos){
if(pos==10){
w.push_back(num);
return ;
}
int x = num * 10 + 1;
if(x<=MAX){
build(1,x,pos+1);
}
x = num * 10 + 0;
if(x<=MAX){
build(0,x,pos+1);
}
}
int main(){
freopen("data.in","r",stdin);
freopen("data.out","w",stdout);
int n,x,cont=0;
w.push_back(MAX);
build(0,0,0);
scanf("%d",&n);
while(n--){
cont=0;
scanf("%d",&x);
for (int i = w.size()-2 ; i>0;i--){
if(w[i]<=x)
cont++;
else
break;
}
printf("%d\n", cont);
}
return 0;
} | [
"[email protected]"
] | |
73143596bfbd8829d4778416113d404acfcb9ab0 | e739fef761a61048b35709c58eed39a15874a34f | /Regexp/Parsing/Parser.cpp | e02589d81c924a74f1fde2a6e70eee76f7e1ce99 | [
"MIT"
] | permissive | skostrov/regexp | a9db38e579103779368ac8a7ced965d9c6a3a8a8 | 1a04e6e31bc6676e6f271d6e5cec6ba114c1bc99 | refs/heads/master | 2020-04-30T15:31:28.609908 | 2015-09-03T11:41:14 | 2015-09-03T11:41:14 | 41,741,806 | 0 | 0 | null | 2015-09-01T14:35:17 | 2015-09-01T13:57:38 | null | UTF-8 | C++ | false | false | 6,192 | cpp |
#include <wchar.h>
#include "Parser.h"
#include "Scanner.h"
namespace RegexpParsing {
void Parser::SynErr(int n) {
if (errDist >= minErrDist) errors->SynErr(la->line, la->col, n);
errDist = 0;
}
void Parser::SemErr(const wchar_t* msg) {
if (errDist >= minErrDist) errors->Error(t->line, t->col, msg);
errDist = 0;
}
void Parser::Get() {
for (;;) {
t = la;
la = scanner->Scan();
if (la->kind <= maxT) { ++errDist; break; }
if (dummyToken != t) {
dummyToken->kind = t->kind;
dummyToken->pos = t->pos;
dummyToken->col = t->col;
dummyToken->line = t->line;
dummyToken->next = NULL;
coco_string_delete(dummyToken->val);
dummyToken->val = coco_string_create(t->val);
t = dummyToken;
}
la = t;
}
}
void Parser::Expect(int n) {
if (la->kind==n) Get(); else { SynErr(n); }
}
void Parser::ExpectWeak(int n, int follow) {
if (la->kind == n) Get();
else {
SynErr(n);
while (!StartOf(follow)) Get();
}
}
bool Parser::WeakSeparator(int n, int syFol, int repFol) {
if (la->kind == n) {Get(); return true;}
else if (StartOf(repFol)) {return false;}
else {
SynErr(n);
while (!(StartOf(syFol) || StartOf(repFol) || StartOf(0))) {
Get();
}
return StartOf(syFol);
}
}
void Parser::Regexp() {
UnionExpression();
}
void Parser::UnionExpression() {
ConcatenationExpression();
if (la->kind == _Union) {
Get();
UnionExpression();
PushUnion();
}
}
void Parser::ConcatenationExpression() {
ClosureExpression();
if (la->kind == _Symbol || la->kind == _LeftRoundBracket) {
ConcatenationExpression();
PushConcatenation();
}
}
void Parser::ClosureExpression() {
Expression();
if (la->kind == _Closure) {
Get();
PushClosure();
}
}
void Parser::Expression() {
if (la->kind == _LeftRoundBracket) {
Get();
UnionExpression();
Expect(_RightRoundBracket);
} else if (la->kind == _Symbol) {
Get();
PushTerminal( t->val );
} else SynErr(7);
}
// If the user declared a method Init and a mehtod Destroy they should
// be called in the contructur and the destructor respctively.
//
// The following templates are used to recognize if the user declared
// the methods Init and Destroy.
template<typename T>
struct ParserInitExistsRecognizer {
template<typename U, void (U::*)() = &U::Init>
struct ExistsIfInitIsDefinedMarker{};
struct InitIsMissingType {
char dummy1;
};
struct InitExistsType {
char dummy1; char dummy2;
};
// exists always
template<typename U>
static InitIsMissingType is_here(...);
// exist only if ExistsIfInitIsDefinedMarker is defined
template<typename U>
static InitExistsType is_here(ExistsIfInitIsDefinedMarker<U>*);
enum { InitExists = (sizeof(is_here<T>(NULL)) == sizeof(InitExistsType)) };
};
template<typename T>
struct ParserDestroyExistsRecognizer {
template<typename U, void (U::*)() = &U::Destroy>
struct ExistsIfDestroyIsDefinedMarker{};
struct DestroyIsMissingType {
char dummy1;
};
struct DestroyExistsType {
char dummy1; char dummy2;
};
// exists always
template<typename U>
static DestroyIsMissingType is_here(...);
// exist only if ExistsIfDestroyIsDefinedMarker is defined
template<typename U>
static DestroyExistsType is_here(ExistsIfDestroyIsDefinedMarker<U>*);
enum { DestroyExists = (sizeof(is_here<T>(NULL)) == sizeof(DestroyExistsType)) };
};
// The folloing templates are used to call the Init and Destroy methods if they exist.
// Generic case of the ParserInitCaller, gets used if the Init method is missing
template<typename T, bool = ParserInitExistsRecognizer<T>::InitExists>
struct ParserInitCaller {
static void CallInit(T *t) {
// nothing to do
}
};
// True case of the ParserInitCaller, gets used if the Init method exists
template<typename T>
struct ParserInitCaller<T, true> {
static void CallInit(T *t) {
t->Init();
}
};
// Generic case of the ParserDestroyCaller, gets used if the Destroy method is missing
template<typename T, bool = ParserDestroyExistsRecognizer<T>::DestroyExists>
struct ParserDestroyCaller {
static void CallDestroy(T *t) {
// nothing to do
}
};
// True case of the ParserDestroyCaller, gets used if the Destroy method exists
template<typename T>
struct ParserDestroyCaller<T, true> {
static void CallDestroy(T *t) {
t->Destroy();
}
};
void Parser::Parse() {
t = NULL;
la = dummyToken = new Token();
la->val = coco_string_create(L"Dummy Token");
Get();
Regexp();
Expect(0);
}
Parser::Parser(Scanner *scanner) {
maxT = 6;
ParserInitCaller<Parser>::CallInit(this);
dummyToken = NULL;
t = la = NULL;
minErrDist = 2;
errDist = minErrDist;
this->scanner = scanner;
errors = new Errors();
}
bool Parser::StartOf(int s) {
const bool T = true;
const bool x = false;
static bool set[1][8] = {
{T,x,x,x, x,x,x,x}
};
return set[s][la->kind];
}
Parser::~Parser() {
ParserDestroyCaller<Parser>::CallDestroy(this);
delete errors;
delete dummyToken;
}
Errors::Errors() {
count = 0;
}
void Errors::SynErr(int line, int col, int n) {
wchar_t* s;
switch (n) {
case 0: s = coco_string_create(L"EOF expected"); break;
case 1: s = coco_string_create(L"Union expected"); break;
case 2: s = coco_string_create(L"Closure expected"); break;
case 3: s = coco_string_create(L"Symbol expected"); break;
case 4: s = coco_string_create(L"LeftRoundBracket expected"); break;
case 5: s = coco_string_create(L"RightRoundBracket expected"); break;
case 6: s = coco_string_create(L"??? expected"); break;
case 7: s = coco_string_create(L"invalid Expression"); break;
default:
{
wchar_t format[20];
coco_swprintf(format, 20, L"error %d", n);
s = coco_string_create(format);
}
break;
}
//wprintf(L"-- line %d col %d: %ls\n", line, col, s);
coco_string_delete(s);
count++;
}
void Errors::Error(int line, int col, const wchar_t *s) {
//wprintf(L"-- line %d col %d: %ls\n", line, col, s);
count++;
}
void Errors::Warning(int line, int col, const wchar_t *s) {
//wprintf(L"-- line %d col %d: %ls\n", line, col, s);
}
void Errors::Warning(const wchar_t *s) {
//wprintf(L"%ls\n", s);
}
void Errors::Exception(const wchar_t* s) {
//wprintf(L"%ls", s);
//exit(1);
}
} // namespace
| [
"[email protected]"
] | |
0aaa626bb0bbbf3782287d05b1a7cf415faa9bb8 | 6272d48fbfe9b8a3607adb1c9ecaed62cf78efed | /initialization/arguments.hh | f2c560de70c4f90369cf66ab36f1210c5fd2adb4 | [] | no_license | dlfurse/midge | 8f48d115123dbfc4ba6c4facb63e424d16721518 | c94a8ca6426b3280f87791174a8fd41472ab6fb3 | refs/heads/master | 2021-04-09T17:28:47.557208 | 2015-01-09T19:02:43 | 2015-01-09T19:02:43 | 7,711,287 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 2,107 | hh | #ifndef _midge_arguments_hh_
#define _midge_arguments_hh_
#include "error.hh"
#include <string>
using std::string;
#include <sstream>
using std::stringstream;
#include <set>
using std::set;
#include <map>
using std::map;
#include <utility>
using std::pair;
namespace midge
{
class arguments
{
public:
arguments();
~arguments();
public:
void required( const string& p_key );
void optional( const string& p_key, const string& p_default );
void start( int p_count, char** p_values );
void stop();
string value() const;
template< class x_type >
x_type value( const string& p_key ) const;
private:
string f_value;
set< string > f_required_values;
map< string, string > f_optional_values;
mutable map< string, string > f_unused_values;
mutable map< string, string > f_used_values;
};
inline string arguments::value() const
{
return f_value;
}
template< class x_type >
inline x_type arguments::value( const string& p_key ) const
{
x_type t_value;
map< string, string >::const_iterator t_it;
t_it = f_used_values.find( p_key );
if( t_it != f_used_values.end() )
{
stringstream t_converter;
t_converter << t_it->second;
t_converter >> t_value;
return t_value;
}
t_it = f_unused_values.find( p_key );
if( t_it != f_unused_values.end() )
{
stringstream t_converter;
t_converter << t_it->second;
t_converter >> t_value;
f_used_values.insert( pair< string, string >( t_it->first, t_it->second ) );
f_unused_values.erase( t_it );
return t_value;
}
throw error() << "requested argument <" << p_key << "> not found";
stringstream t_converter;
t_converter << t_it->second;
t_converter >> t_value;
return t_value;
}
}
#endif
| [
"[email protected]"
] | |
a0e49a0c1e54305f370bc61fa448a2f17ba271bb | 0bd01a90685472aecd6bd7c10957ca98578097d0 | /code/subset-sum.cpp | fbc21a77f6fa70214021001fc47a2b80cecafb72 | [] | no_license | iwccsbfb/leetcode | c450493da7585a6b9871ebd464c43b15e900135f | c119e05bcd4dced6f5f662562a5d6a8dc1f50f14 | refs/heads/master | 2021-05-24T04:21:12.054670 | 2021-01-18T01:27:36 | 2021-01-18T01:27:36 | 62,474,923 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,771 | cpp | #include <iostream>
#include <string>
#include <vector>
#include <cmath>
using namespace std;
/*
Set 4 (Subset Sum)
Subset sum problem is to find subset of elements that are selected from a given set whose sum adds up to a given number K. We are considering the set contains non-negative values. It is assumed that the input set is unique (no duplicates are presented).
Exhaustive Search Algorithm for Subset Sum
One way to find subsets that sum to K is to consider all possible subsets. A power set contains all those subsets generated from a given set. The size of such a power set is 2N.
Backtracking Algorithm for Subset Sum
Using exhaustive search we consider all subsets irrespective of whether they satisfy given constraints or not. Backtracking can be used to make a systematic consideration of the elements to be selected.
*/
struct ReturnType {
vector<int> values;
bool flag;
ReturnType(bool _flag) : flag(_flag) {}
ReturnType(vector<int> &sol, bool _flag) :
values(sol), flag(_flag) {}
};
ReturnType helper(vector<int> &v, vector<int> &sol, int cur_sum, int idx, int sum) {
int sz = v.size();
if (idx >= sz) return false;
for (int i = idx; i<sz; i++) {
cur_sum += v[i];
sol.push_back(v[i]);
if (cur_sum == sum)
return ReturnType(sol, true);
if (cur_sum < sum) {
auto res = helper(v, sol, cur_sum, i + 1, sum);
if (res.flag)
return res;
}
cur_sum -= v[i];
sol.pop_back();
}
return ReturnType(false);
}
bool subset_sum(vector<int> &v, int sum) {
vector<int> sol;
auto res = helper(v, sol, 0, 0, sum);
if (res.flag) {
for (auto &i : res.values) {
cout << i << ' ';
}
}
return res.flag;
}
int main() {
vector<int> v{ 1,2,5,8,23 };
cout << subset_sum(v, 28) << endl;
return 0;
}
| [
"[email protected]"
] | |
c6407ec248d6b52d07afccc7e72dbd5da008cbd5 | cfe6224c42673f349c0a20e112fc0cf9e5907701 | /exo_algos.cpp | 8e8918753d3a7864ad9f33aadb4d377d1048a41b | [] | no_license | u0078867/ankle-exoskeleton | 2e18e4b9fe3c83f40ff0c5b8d1538884c1f0c29d | 6dc2bc30710955e92a3f0dd44703ee31cc3920ab | refs/heads/master | 2021-04-15T17:46:19.655560 | 2018-03-25T16:52:02 | 2018-03-25T16:52:02 | 126,718,819 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 18,406 | cpp |
#include "exo_algos.h"
#include <math.h>
bool detectHS(exo_meas *m, exo_params *p) {
bool detected;
/* // C++ only
static exo_state_HS dHS = {
.COND = VAC_AND_FVAN_1_HS,
...
};
*/
static exo_state_HS dHS;
static bool init = true;
if (init) {
dHS.COND = VAC_AND_FVAN_1_HS;
dHS.CONT = 0;
dHS.VAC = PATTERN_NONE;
dHS.FVAN = PATTERN_NONE;
dHS.PREV_FVAN = 0.;
dHS.PREV_VAC = 0.;
dHS.PREV_FVAN_DIFF = 0.;
dHS.PREV_VAC_DIFF = 0;
init = false;
}
dHS.TH_FVAN = p->FVANTHS;
dHS.TH_VAC = p->VACTHS;
dHS.TH_CONT = 30;
#if SUBJECT_TYPE == 1
detected = detectHS_CHILD_NORMAL(m, &dHS);
#endif
return detected;
}
bool detectTO(exo_meas *m, exo_params *p) {
bool detected;
static exo_state_TO dTO;
static bool init = true;
if (init) {
dTO.COND = VAC_AND_FVAN_1_TO;
dTO.CONT = 0;
dTO.VAC = PATTERN_NONE;
dTO.FVAN = PATTERN_NONE;
dTO.PREV_FVAN = 0.;
dTO.PREV_VAC = 0.;
dTO.PREV_FVAN_DIFF = 0.;
dTO.PREV_VAC_DIFF = 0.;
init = false;
}
dTO.TH_FVAN = p->FVANTTO;
dTO.TH_VAC = p->VACTTO;
dTO.TH_CONT = 30;
#if SUBJECT_TYPE == 1
detected = detectTO_CHILD_NORMAL(m, &dTO);
#endif
return detected;
}
bool detectHO(exo_meas *m, exo_params *p) {
bool detected;
static exo_state_HO dHO;
static bool init = true;
if (init) {
dHO.CONT = 0;
dHO.AAN = PATTERN_NONE;
dHO.FVAN = PATTERN_NONE;
dHO.SVAN = PATTERN_NONE;
dHO.PREV_FVAN = 0.;
dHO.PREV_SVAN = 0.;
dHO.PREV_AAN = 0.;
dHO.PREV_AAN_DIFF = 0.;
init = false;
}
dHO.TH_FVAN = p->FVANTHO;
dHO.TH_SVAN = p->SVANTHO;
if (p->HOMOD == 1) {
dHO.COND = FVAN_AND_AAN_1_HO;
} else if (p->HOMOD == 2) {
dHO.COND = SVAN_ONLY_1_HO;
} else if (p->HOMOD == 3) {
dHO.COND = SVAN_ONLY_2_HO;
} else if (p->HOMOD == 4) {
dHO.COND = FVAN_ONLY_1_HO;
}
dHO.TH_CONT = 30;
#if SUBJECT_TYPE == 1
detected = detectHO_CHILD_NORMAL(m, &dHO);
#endif
return detected;
}
float calcMTP(float AANT, exo_meas *m, exo_params *p) {
double Kp;
float MTP;
double dGamma, dTeta, cGamma, cTeta;
double quadB;
dGamma = DEG_TO_RAD * (AANT - m->AAN);
cGamma = DEG_TO_RAD * (m->AAN + m->AANG);
quadB = (double)m->QUADB;
#if SERVO_POS_MEASURE == 1
cTeta = DEG_TO_RAD * POS_SERVO_TO_TETA(m->MP);
#elif SERVO_POS_MEASURE == 2
double quadAlpha, quadP;
cTeta = gamma_to_teta_theor(QUADRL_A, quadB, QUADRL_C, m->SPC, cGamma, &quadAlpha, &quadP);
#endif
//if (cTeta < (DEG_TO_RAD * 146.)) {
if (cTeta < (DEG_TO_RAD * POS_SERVO_TO_TETA(AAN_MIN_BLOCK_POS))) {
// Apply quadrilateral trigonometry
#if GAMMA_TO_TETA_DELTA == 1
dTeta = gamma_to_teta_delta(QUADRL_A, quadB, QUADRL_C, m->SPC, dGamma, cGamma, cTeta);
#elif GAMMA_TO_TETA_DELTA == 2
#if(SIDE)
dTeta = gamma_to_teta_delta_R(m->SPC, dGamma, cGamma, cTeta);
#else
dTeta = gamma_to_teta_delta_L(m->SPC, dGamma, cGamma, cTeta);
#endif
#elif GAMMA_TO_TETA_DELTA == 3
dTeta = gamma_to_teta_delta_cse_ofast(QUADRL_A, quadB, QUADRL_C, m->SPC, dGamma, cGamma, cTeta);
#endif
// Apply PID
#if GAMMA_TO_TETA_DELTA == 4
Kp = ALGO_PID_KP;
#else
Kp = dTeta / dGamma;
#endif
dTeta = PID(dGamma, Kp, ALGO_PID_KI, ALGO_PID_KD, m->TS);
MTP = (float)TETA_TO_POS_SERVO(RAD_TO_DEG * (cTeta + dTeta));
} else {
// Can't apply quadrilateral trigonometry. Make teta bit lower than 180 deg
//MTP = (float)TETA_TO_POS_SERVO(146.); // no vibration
MTP = (float)AAN_MIN_BLOCK_POS; // no vibration
}
#ifdef DEBUG_ALGO
#ifdef SERVO_POS_MEASURE == 2
DEBUG_PRINT("quadB: ");
DEBUG_PRINTLN(quadB);
DEBUG_PRINT("quadP: ");
DEBUG_PRINTLN(quadP);
DEBUG_PRINT("quadAlpha: ");
DEBUG_PRINTLN(quadAlpha * RAD_TO_DEG);
#endif
DEBUG_PRINT("dGamma: ");
DEBUG_PRINTLN(dGamma * RAD_TO_DEG);
DEBUG_PRINT("cGamma: ");
DEBUG_PRINTLN(cGamma * RAD_TO_DEG);
DEBUG_PRINT("cTeta: ");
DEBUG_PRINTLN(cTeta * RAD_TO_DEG);
DEBUG_PRINT("dTeta: ");
DEBUG_PRINTLN(dTeta * RAD_TO_DEG);
DEBUG_PRINT("Old MP: ");
DEBUG_PRINTLN(m->MP);
DEBUG_PRINT("New MP: ");
DEBUG_PRINTLN(MTP);
#endif
return MTP;
}
float AANMLinearFixedValues(unsigned long TS, exo_params *p, exo_params *pv, exo_output * o) {
float m, q, res;
if (o->GP == 2) {
#ifdef DEBUG_ALGO
DEBUG_PRINT("Model MAD: ");
DEBUG_PRINTLN(p->MAD);
DEBUG_PRINT("Model AANE1R: ");
DEBUG_PRINTLN(pv->AANE1R);
DEBUG_PRINT("Model E2R: ");
DEBUG_PRINTLN(p->E2R);
DEBUG_PRINT("Model E1R: ");
DEBUG_PRINTLN(pv->E1R);
#endif
m = (p->MAD - pv->AANE1R) / (p->E2R - pv->E1R);
q = pv->AANE1R;
res = m * (TS - pv->E1R) + q;
} else if (o->GP == 3) {
#ifdef DEBUG_ALGO
DEBUG_PRINT("Model MAP: ");
DEBUG_PRINTLN(p->MAP);
DEBUG_PRINT("Model MAD: ");
DEBUG_PRINTLN(pv->MAD);
DEBUG_PRINT("Model E3R: ");
DEBUG_PRINTLN(p->E3R);
DEBUG_PRINT("Model E2R: ");
DEBUG_PRINTLN(pv->E2R);
#endif
m = (p->MAP - pv->MAD) / (p->E3R - pv->E2R);
q = pv->MAD;
res = m * (TS - pv->E2R) + q;
} else if (o->GP == 4) {
#ifdef DEBUG_ALGO
DEBUG_PRINT("Model MASW: ");
DEBUG_PRINTLN(p->MASW);
DEBUG_PRINT("Model MAP: ");
DEBUG_PRINTLN(pv->MAP);
DEBUG_PRINT("Model E1SW: ");
DEBUG_PRINTLN(p->E1SW);
DEBUG_PRINT("Model E3R: ");
DEBUG_PRINTLN(pv->E3R);
#endif
m = (p->MASW - pv->MAP) / (p->E1SW - pv->E3R);
q = pv->MAP;
res = m * (TS - pv->E3R) + q;
}
#ifdef DEBUG_ALGO
DEBUG_PRINT("Model m: ");
DEBUG_PRINTLN(m);
DEBUG_PRINT("Model q: ");
DEBUG_PRINTLN(q);
#endif
return res;
}
float AANMLinearFixedSlopes(unsigned long TS, exo_params *p, exo_params *pv, exo_output * o) {
float m, q, res;
if (o->GP == 2) {
#ifdef DEBUG_ALGO
DEBUG_PRINT("Model MAD: ");
DEBUG_PRINTLN(p->MAD);
DEBUG_PRINT("Model AANE1R: ");
DEBUG_PRINTLN(p->AANE1R);
DEBUG_PRINT("Model E2R: ");
DEBUG_PRINTLN(p->E2R);
DEBUG_PRINT("Model E1R: ");
DEBUG_PRINTLN(pv->E1R);
#endif
m = (p->MAD - p->AANE1R) / (p->E2R - pv->E1R); // E1R must be variable
q = pv->AANE1R;
res = m * (TS - pv->E1R) + q;
} else if (o->GP == 3) {
#ifdef DEBUG_ALGO
DEBUG_PRINT("Model MAP: ");
DEBUG_PRINTLN(p->MAP);
DEBUG_PRINT("Model MAD: ");
DEBUG_PRINTLN(p->MAD);
DEBUG_PRINT("Model E3R: ");
DEBUG_PRINTLN(p->E3R);
DEBUG_PRINT("Model E2R: ");
DEBUG_PRINTLN(p->E2R);
#endif
m = (p->MAP - p->MAD) / (p->E3R - p->E2R);
q = pv->MAD;
res = m * (TS - pv->E2R) + q;
} else if (o->GP == 4) {
#ifdef DEBUG_ALGO
DEBUG_PRINT("Model MASW: ");
DEBUG_PRINTLN(p->MASW);
DEBUG_PRINT("Model MAP: ");
DEBUG_PRINTLN(p->MAP);
DEBUG_PRINT("Model E1SW: ");
DEBUG_PRINTLN(p->E1SW);
DEBUG_PRINT("Model E3R: ");
DEBUG_PRINTLN(p->E3R);
#endif
m = (p->MASW - p->MAP) / (p->E1SW - p->E3R);
q = pv->MAP;
res = m * (TS - pv->E3R) + q;
}
#ifdef DEBUG_ALGO
DEBUG_PRINT("Model m: ");
DEBUG_PRINTLN(m);
DEBUG_PRINT("Model q: ");
DEBUG_PRINTLN(q);
#endif
return res;
}
float AANMLinearAdaptive(unsigned long TS, exo_params *p, exo_params *pv, exo_output * o) {
float m, q, res;
if (o->GP == 2) {
#ifdef DEBUG_ALGO
DEBUG_PRINT("Model MAD: ");
DEBUG_PRINTLN(pv->MAD);
DEBUG_PRINT("Model AANE1R: ");
DEBUG_PRINTLN(pv->AANE1R);
DEBUG_PRINT("Model E2R: ");
DEBUG_PRINTLN(pv->E2R);
DEBUG_PRINT("Model E1R: ");
DEBUG_PRINTLN(pv->E1R);
#endif
m = (pv->MAD - pv->AANE1R) / (pv->E2R - pv->E1R);
q = pv->AANE1R;
res = m * (TS - pv->E1R) + q;
} else if (o->GP == 3) {
#ifdef DEBUG_ALGO
DEBUG_PRINT("Model MAP: ");
DEBUG_PRINTLN(pv->MAP);
DEBUG_PRINT("Model MAD: ");
DEBUG_PRINTLN(pv->MAD);
DEBUG_PRINT("Model E3R: ");
DEBUG_PRINTLN(pv->E3R);
DEBUG_PRINT("Model E2R: ");
DEBUG_PRINTLN(pv->E2R);
#endif
m = (pv->MAP - pv->MAD) / (pv->E3R - pv->E2R);
q = pv->MAD;
res = m * (TS - pv->E2R) + q;
} else if (o->GP == 4) {
#ifdef DEBUG_ALGO
DEBUG_PRINT("Model MASW: ");
DEBUG_PRINTLN(pv->MASW);
DEBUG_PRINT("Model MAP: ");
DEBUG_PRINTLN(pv->MAP);
DEBUG_PRINT("Model E1SW: ");
DEBUG_PRINTLN(pv->E1SW);
DEBUG_PRINT("Model E3R: ");
DEBUG_PRINTLN(pv->E3R);
#endif
m = (pv->MASW - pv->MAP) / (pv->E1SW - pv->E3R);
q = pv->MAP;
res = m * (TS - pv->E3R) + q;
}
#ifdef DEBUG_ALGO
DEBUG_PRINT("Model m: ");
DEBUG_PRINTLN(m);
DEBUG_PRINT("Model q: ");
DEBUG_PRINTLN(q);
#endif
return res;
}
float AANMLinearMixed1(unsigned long TS, exo_params *p, exo_params *pv, exo_output * o) {
float m, q, res;
if (o->GP == 2) {
#ifdef DEBUG_ALGO
DEBUG_PRINT("Model MAD: ");
DEBUG_PRINTLN(p->MAD);
DEBUG_PRINT("Model AANE1R: ");
DEBUG_PRINTLN(p->AANE1R);
DEBUG_PRINT("Model E2R: ");
DEBUG_PRINTLN(p->E2R);
DEBUG_PRINT("Model E1R: ");
DEBUG_PRINTLN(pv->E1R);
#endif
m = (p->MAD - p->AANE1R) / (p->E2R - pv->E1R); // E1R must be variable
q = pv->AANE1R;
res = m * (TS - pv->E1R) + q;
} else if (o->GP == 3) {
#ifdef DEBUG_ALGO
DEBUG_PRINT("Model MAP: ");
DEBUG_PRINTLN(p->MAP);
DEBUG_PRINT("Model MAD: ");
DEBUG_PRINTLN(pv->MAD);
DEBUG_PRINT("Model E3R: ");
DEBUG_PRINTLN(p->E3R);
DEBUG_PRINT("Model E2R: ");
DEBUG_PRINTLN(p->E2R);
#endif
m = (p->MAP - pv->MAD) / (p->E3R - p->E2R);
q = pv->MAD;
res = m * (TS - pv->E2R) + q;
if (res < p->MAP) {
res = p->MAP;
}
} else if (o->GP == 4) {
#ifdef DEBUG_ALGO
DEBUG_PRINT("Model MASW: ");
DEBUG_PRINTLN(p->MASW);
DEBUG_PRINT("Model MAP: ");
DEBUG_PRINTLN(p->MAP);
DEBUG_PRINT("Model E1SW: ");
DEBUG_PRINTLN(p->E1SW);
DEBUG_PRINT("Model E3R: ");
DEBUG_PRINTLN(p->E3R);
#endif
m = (p->MASW - p->MAP) / (p->E1SW - p->E3R);
q = p->MAP;
res = m * (TS - pv->E3R) + q;
}
#ifdef DEBUG_ALGO
DEBUG_PRINT("Model m: ");
DEBUG_PRINTLN(m);
DEBUG_PRINT("Model q: ");
DEBUG_PRINTLN(q);
#endif
return res;
}
void algo1(exo_meas *m, exo_output *o, exo_params *p, exo_params *pv, float (*AANM)(unsigned long, exo_params *, exo_params *, exo_output *)) {
// Local variables
static unsigned long TS0, TS2;
unsigned long TS;
float pct, AANT, MTP;
bool HS, HO, canDetectHO, TO;
// Handle states
if (o->GP > 0) {
TS = m->TS - TS0;
pct = TS / p->ST * 100.;
}
// Detect events
HS = detectHS(m, p);
HO = detectHO(m, p);
TO = detectTO(m, p);
#ifdef DEBUG_ALGO
// Print debug messages
DEBUG_PRINT("TS: ");
DEBUG_PRINTLN(TS);
DEBUG_PRINT("GP: ");
DEBUG_PRINTLN(o->GP);
#endif
switch(o->GP) {
case 0: // waiting for step
// Detect HS
if (HS) {
TS0 = m->TS;
o->GP = 1;
}
o->MDET = true;
break;
case 1: // 1st rocker
// Detect end of 1st rocker
if (m->SVAN > 0) {
o->GP = 2;
pv->AANE1R = m->AAN;
pv->E1R = TS;
TS2 = TS;
}
o->MDET = true;
break;
case 2: // 2nd rocker
// Calculate targets for ankle and motor
AANT = (*AANM)(TS, p, pv, o);
#ifdef DEBUG_ALGO
DEBUG_PRINT("AANT: ");
DEBUG_PRINTLN(AANT);
#endif
o->AANT = AANT;
MTP = calcMTP(AANT, m, p);
o->MTP = MTP;
// Decide if to detach motor or not
if ((m->AAN - AANT) > p->AANE) {
o->MDET = false;
} else {
o->MDET = true;
}
// Detect HO
canDetectHO = false;
if ((TS - TS2) > p->TWNOHO) {
canDetectHO = true;
}
if (canDetectHO && HO) {
o->GP = 3;
pv->MAD = m->AAN;
pv->E2R = TS;
}
break;
case 3: // 3rd rocker
// Calculate targets for ankle and motor
AANT = (*AANM)(TS, p, pv, o);
#ifdef DEBUG_ALGO
DEBUG_PRINT("AANT: ");
DEBUG_PRINTLN(AANT);
#endif
o->AANT = AANT;
MTP = calcMTP(AANT, m, p);
o->MTP = MTP;
// Decide if to detach motor or not
if ((m->AAN - AANT) > p->AANE) {
o->MDET = false;
} else {
o->MDET = true;
}
// Detect TO
if (TO) {
o->GP = 4;
pv->MAP = m->AAN;
pv->E3R = TS;
}
break;
case 4: // swing (dorsiflexing)
// Calculate targets for ankle and motor
AANT = (*AANM)(TS, p, pv, o);
#ifdef DEBUG_ALGO
DEBUG_PRINT("AANT: ");
DEBUG_PRINTLN(AANT);
#endif
o->AANT = AANT;
MTP = calcMTP(AANT, m, p);
o->MTP = MTP;
// Decide if to detach motor or not
if ((AANT - m->AAN) > p->AANE) {
o->MDET = false;
} else {
o->MDET = true;
}
// Detect time after dorsiflexion
if ((TS - pv->E3R) > (p->E1SW - p->E3R)) {
o->GP = 5;
pv->MASW = m->AAN;
pv->E1SW = TS;
}
break;
case 5: // swing (dorsiflexed)
// Calculate targets for ankle and motor
AANT = p->MASW;
#ifdef DEBUG_ALGO
DEBUG_PRINT("AANT: ");
DEBUG_PRINTLN(AANT);
#endif
o->AANT = AANT;
MTP = calcMTP(AANT, m, p);
o->MTP = MTP;
// Decide if to detach motor or not
if ((AANT - m->AAN) > p->AANE) {
o->MDET = false;
} else {
o->MDET = true;
}
// Detect HS
if (HS) {
TS0 = m->TS;
o->GP = 1;
}
break;
case 6: // idle
if (p->ALGMOD == 1) {
o->GP = 0;
}
o->MDET = true;
break;
}
// Check if algo mode is on idle
if (p->ALGMOD == 0) {
o->GP = 6;
}
}
void algoTrackAANM(exo_meas *m, exo_output *o, exo_params *p, exo_params *pv, float (*AANM)(unsigned long, exo_params *, exo_params *, exo_output *)) {
// Local variables
static unsigned long TS0;
unsigned long TS;
float pct, AANT, MTP;
// Handle states
if (o->GP > 0) {
TS = m->TS - TS0;
pct = TS / p->ST * 100.;
}
#ifdef DEBUG_ALGO
// Print debug messages
DEBUG_PRINT("TS: ");
DEBUG_PRINTLN(TS);
DEBUG_PRINT("GP: ");
DEBUG_PRINTLN(o->GP);
#endif
switch(o->GP) {
case 0: // waiting for step
// Pass to next state immediately
TS0 = m->TS;
o->GP = 1;
break;
case 1: // 1st rocker
// Set end of 1st rocker immediately
o->GP = 2;
pv->AANE1R = m->AAN;
pv->E1R = TS;
break;
case 2: // 2nd rocker
// Calculate targets for ankle and motor
AANT = (*AANM)(TS, p, pv, o);
#ifdef DEBUG_ALGO
DEBUG_PRINT("AANT: ");
DEBUG_PRINTLN(AANT);
#endif
o->AANT = AANT;
MTP = calcMTP(AANT, m, p);
o->MTP = MTP;
// Detect end of 2nd rocker
if (TS > p->E2R) {
o->GP = 3;
pv->MAD = m->AAN;
pv->E2R = TS;
}
break;
case 3: // 3rd rocker
// Calculate targets for ankle and motor
AANT = (*AANM)(TS, p, pv, o);
#ifdef DEBUG_ALGO
DEBUG_PRINT("AANT: ");
DEBUG_PRINTLN(AANT);
#endif
o->AANT = AANT;
MTP = calcMTP(AANT, m, p);
o->MTP = MTP;
// Detect TO
if (TS > p->E3R) {
o->GP = 4;
pv->MAP = m->AAN;
pv->E3R = TS;
}
break;
case 4: // swing (dorsiflexing)
// Calculate targets for ankle and motor
AANT = (*AANM)(TS, p, pv, o);
#ifdef DEBUG_ALGO
DEBUG_PRINT("AANT: ");
DEBUG_PRINTLN(AANT);
#endif
o->AANT = AANT;
MTP = calcMTP(AANT, m, p);
o->MTP = MTP;
// Detect time after dorsiflexion
if ((TS - pv->E3R) > (p->E1SW - p->E3R)) {
o->GP = 5;
pv->MASW = m->AAN;
pv->E1SW = TS;
}
break;
case 5: // swing (dorsiflexed)
// Calculate targets for ankle and motor
AANT = p->MASW;
#ifdef DEBUG_ALGO
DEBUG_PRINT("AANT: ");
DEBUG_PRINTLN(AANT);
#endif
o->AANT = AANT;
MTP = calcMTP(AANT, m, p);
o->MTP = MTP;
// Detect end of 3rd rocker
if (TS > p->ST) {
TS0 = m->TS;
o->GP = 1;
}
break;
case 6: // idle
if (p->ALGMOD == 1) {
o->GP = 0;
}
//o->MDET = true;
break;
}
// Check if algo mode is on idle
if (p->ALGMOD == 0) {
o->GP = 6;
}
// Impose servo always active (but idle state)
if (o->GP == 6) {
o->MDET = true;
} else {
o->MDET = false;
}
}
| [
"[email protected]"
] | |
a31e5c89064dbfbf435c9b8a1f708cd769f083bc | d3bd964354ef8d662cd9857e245b0ff393b00b9c | /modules/base/rotation/spicerotation.cpp | 709292554da4254514de0362c1c70f4f954ed245 | [
"MIT"
] | permissive | emiax/OpenSpace | 5da75a56b684885e1e573177686e8aad03a6a3e4 | 17540472f5bd23f5c38ee4dd6c9e00b439b241a0 | refs/heads/master | 2021-01-12T08:08:45.232711 | 2016-12-12T12:50:55 | 2016-12-12T12:50:55 | 76,476,293 | 0 | 0 | null | 2016-12-14T16:18:18 | 2016-12-14T16:18:18 | null | UTF-8 | C++ | false | false | 4,282 | cpp | /*****************************************************************************************
* *
* OpenSpace *
* *
* Copyright (c) 2014-2016 *
* *
* 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. *
****************************************************************************************/
#include <modules/base/rotation/spicerotation.h>
#include <openspace/util/spicemanager.h>
#include <openspace/util/time.h>
namespace {
const std::string _loggerCat = "SpiceRotation";
//const std::string keyGhosting = "EphmerisGhosting";
const std::string KeySourceFrame = "SourceFrame";
const std::string KeyDestinationFrame = "DestinationFrame";
const std::string KeyKernels = "Kernels";
}
namespace openspace {
SpiceRotation::SpiceRotation(const ghoul::Dictionary& dictionary)
: _sourceFrame("")
, _destinationFrame("")
, _rotationMatrix(1.0)
, _kernelsLoadedSuccessfully(true)
{
const bool hasSourceFrame = dictionary.getValue(KeySourceFrame, _sourceFrame);
if (!hasSourceFrame)
LERROR("SpiceRotation does not contain the key '" << KeySourceFrame << "'");
const bool hasDestinationFrame = dictionary.getValue(KeyDestinationFrame, _destinationFrame);
if (!hasDestinationFrame)
LERROR("SpiceRotation does not contain the key '" << KeyDestinationFrame << "'");
ghoul::Dictionary kernels;
dictionary.getValue(KeyKernels, kernels);
for (size_t i = 1; i <= kernels.size(); ++i) {
std::string kernel;
bool success = kernels.getValue(std::to_string(i), kernel);
if (!success)
LERROR("'" << KeyKernels << "' has to be an array-style table");
try {
SpiceManager::ref().loadKernel(kernel);
_kernelsLoadedSuccessfully = true;
}
catch (const SpiceManager::SpiceException& e) {
LERROR("Could not load SPICE kernel: " << e.what());
_kernelsLoadedSuccessfully = false;
}
}
}
const glm::dmat3& SpiceRotation::matrix() const {
return _rotationMatrix;
}
void SpiceRotation::update(const UpdateData& data) {
if (!_kernelsLoadedSuccessfully)
return;
try {
_rotationMatrix = SpiceManager::ref().positionTransformMatrix(
_sourceFrame,
_destinationFrame,
data.time);
}
catch (const ghoul::RuntimeError&) {
// In case of missing coverage
_rotationMatrix = glm::dmat3(1);
}
}
} // namespace openspace | [
"[email protected]"
] | |
b70d04a35222cb813197fb9282625ca5abbb89e7 | 316b07bfa0c1cf69438062b7968fa6105f475b5b | /src/app/document_property_group.cpp | 24b987b75dbd38665ef781bcdcc2fb3aa20bd76c | [
"LicenseRef-scancode-unknown-license-reference",
"BSD-2-Clause"
] | permissive | fougue/mayo | 8dca0601c83386fe90a692be05ec445be2c7e4cd | 7df8642142c22492395f5d2ccce8eeb788dc5a92 | refs/heads/develop | 2023-08-09T04:02:06.493073 | 2023-08-02T10:32:20 | 2023-08-02T10:33:36 | 64,474,598 | 940 | 213 | BSD-2-Clause | 2023-09-11T07:34:18 | 2016-07-29T11:07:36 | C++ | UTF-8 | C++ | false | false | 1,596 | cpp | /****************************************************************************
** Copyright (c) 2022, Fougue Ltd. <http://www.fougue.pro>
** All rights reserved.
** See license at https://github.com/fougue/mayo/blob/master/LICENSE.txt
****************************************************************************/
#include "document_property_group.h"
#include "app_module.h"
#include "filepath_conv.h"
#include "qstring_conv.h"
#include "qstring_utils.h"
#include "../base/application.h"
#include <QtCore/QDateTime>
#include <QtCore/QFileInfo>
namespace Mayo {
DocumentPropertyGroup::DocumentPropertyGroup(const DocumentPtr& doc)
{
this->filePath.setValue(filepathCanonical(doc->filePath()));
const auto fileSize = filepathFileSize(doc->filePath());
auto appModule = AppModule::get();
const QString qstrFileSize = QStringUtils::bytesText(fileSize, appModule->qtLocale());
this->strFileSize.setValue(to_stdString(qstrFileSize));
const QFileInfo fileInfo = filepathTo<QFileInfo>(doc->filePath());
const QString strCreated = appModule->qtLocale().toString(fileInfo.birthTime(), QLocale::ShortFormat);
const QString strModified = appModule->qtLocale().toString(fileInfo.lastModified(), QLocale::ShortFormat);
this->strCreatedDateTime.setValue(to_stdString(strCreated));
this->strModifiedDateTime.setValue(to_stdString(strModified));
this->strOwner.setValue(to_stdString(fileInfo.owner()));
this->entityCount.setValue(doc->entityCount());
for (Property* prop : this->properties())
prop->setUserReadOnly(true);
}
} // namespace Mayo
| [
"[email protected]"
] | |
eea9d199f904f1d5aa8484f3c4f8ff370c6c9b19 | 6e364e2a3ca93b9116d35c6cedcd4342d4f30943 | /src/utils/wrappers.cpp | 0d8566830803bb47586fad7827ee54bbf422303c | [] | no_license | danielsf/Dalex | de0a49f9a216b6b5263a455560e44e3a4307e6c7 | cb7c4bc894c8e84cc8fa084c0c6f96c98d3fd37e | refs/heads/master | 2021-06-26T09:41:42.362251 | 2019-04-09T17:15:04 | 2019-04-09T17:15:04 | 29,041,814 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 386 | cpp | #include "wrappers.h"
function_wrapper::function_wrapper(){}
function_wrapper::~function_wrapper(){}
double function_wrapper::operator()(const array_1d<double> &vv){
printf("WARNING calling un-implemented function_wrapper operator\n");
exit(1);
}
int function_wrapper::get_called(){
printf("WARNING calling un-implemented function_wrapper get_called\n");
exit(1);
}
| [
"[email protected]"
] | |
e5f0817a7c00af1546706e08aef239c42fe53485 | a715c5ecea5574d40f2794e586c56c0e7871ea34 | /lab2/Observer/WeatherStationDuo/Observer.h | 04602144fca4cd86493fb62831be4900eca5bdc4 | [] | no_license | GreatHorizon/ood | 7a41919e298a62a0b6af9867d2dc45465f136356 | a8acc97a7da24ceba09237db6a8691d9b95d4857 | refs/heads/master | 2023-02-10T04:00:41.762966 | 2021-01-06T17:08:39 | 2021-01-06T17:08:39 | 293,723,992 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,471 | h | #pragma once
#include <set>
#include <functional>
#include <iterator>
#include <vector>
#include <map>
template <typename T>
class IObservable;
template <typename T>
class IObserver
{
public:
virtual void Update(T const& data, IObservable<T> const& observable) = 0;
virtual ~IObserver() = default;
};
template <typename T>
class IObservable
{
public:
virtual ~IObservable() = default;
virtual void RegisterObserver(IObserver<T>& observer, int priority) = 0;
virtual void NotifyObservers() = 0;
virtual void RemoveObserver(IObserver<T>& observer) = 0;
};
template <class T>
class CObservable : public IObservable<T>
{
public:
typedef IObserver<T> ObserverType;
void RegisterObserver(ObserverType& observer, int priority) override
{
for (auto it = m_observers.begin(); it != m_observers.end(); it++)
{
if (it->second == &observer)
{
return;
}
}
m_observers.emplace(priority, &observer);
}
void NotifyObservers() override
{
T data = GetChangedData();
auto observers = m_observers;
for (auto it = observers.rbegin(); it != observers.rend(); it++)
{
it->second->Update(data, *this);
}
}
void RemoveObserver(ObserverType& observer) override
{
for (auto it = m_observers.begin(); it != m_observers.end(); it++)
{
if (it->second == &observer)
{
m_observers.erase(it);
break;
}
}
}
protected:
virtual T GetChangedData()const = 0;
private:
std::multimap<unsigned, ObserverType*> m_observers;
};
| [
"[email protected]"
] | |
3643bb832cb02d9d0ed0cb27a161e35fc58a9721 | d310d812d8a1e1818aac46ec2294070ac1372a01 | /gummy/gummy/ObjSnkscr.h | 62e0e6495bcd77e317c3901dbb9c352b73934cbb | [] | no_license | okada255/- | a87360534fc71b985af56a038000e22c96b2e1dc | b7e41a50751bff24d0f3c227bb75443b2ccc749b | refs/heads/master | 2023-03-06T04:57:56.965863 | 2021-02-10T13:06:16 | 2021-02-10T13:06:16 | 303,906,648 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 301 | h | #pragma once
#include"GameL/SceneObjManager.h"
#include"GameL/DrawTexture.h"
using namespace GameL;
class CObjSnkscr : public CObj
{
public:
CObjSnkscr(float x, float y);//{}
~CObjSnkscr() {};
void Action();
void Init();
void Draw();
//
private:
float x;
float y;
float m_x;
float m_y;
};
| [
"[email protected]"
] | |
4ed61649e0b542ee0b096a4d890815e777d7415e | d4ba636068fc2ffbb45f313012103afb9080c4e3 | /NuGenDimension/NuGenDimension/NuGenDimension/RayTracing/RTDialog.h | ac489a5c6b1dc870b87b95fe142a19b43eae5ea6 | [] | no_license | SHAREVIEW/GenXSource | 785ae187531e757860748a2e49d9b6a175c97402 | 5e5fe1d5816560ac41a117210fd40a314536f7a4 | refs/heads/master | 2020-07-20T22:05:24.794801 | 2019-09-06T05:00:39 | 2019-09-06T05:00:39 | 206,716,265 | 0 | 0 | null | 2019-09-06T05:00:12 | 2019-09-06T05:00:12 | null | UTF-8 | C++ | false | false | 963 | h | #if !defined(AFX_INPUTBOX_H__0BE6B01B_C74A_45FE_AF35_D6E8E4B65A1B__INCLUDED_)
#define AFX_INPUTBOX_H__0BE6B01B_C74A_45FE_AF35_D6E8E4B65A1B__INCLUDED_
#if _MSC_VER > 1000
#pragma once
#endif // _MSC_VER > 1000
#include "..//OpenGLView//3dCamera.h"
class CRTDialog
{
static HFONT m_hFont;
static HWND m_hWndDialog;
static HWND m_hWndParent;
static HWND m_hWndStart;
static HWND m_hWndStop;
static HWND m_hWndFrame;
static HDC m_FrameDC;
static HINSTANCE m_hInst;
static C3dCamera* m_camera;
static LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam);
static void OnSize(int cx, int cy);
static void OnDestroy();
static void OnStart();
static void OnStop();
public:
CRTDialog(HWND hWndParent, C3dCamera* cam);
virtual ~CRTDialog();
BOOL DoModal();
};
#endif // !defined(AFX_INPUTBOX_H__0BE6B01B_C74A_45FE_AF35_D6E8E4B65A1B__INCLUDED_)
| [
"[email protected]"
] | |
98ed2bd911859f61d351106987c7748baf7c154e | d0719de640c11c314d9cf18fa2b4aa507d5dd104 | /support/src/ProgData.cpp | 4512d810dc7050e36c4d39e014d18599f8de0857 | [
"LicenseRef-scancode-warranty-disclaimer"
] | no_license | YChuan1115/GSAP | c7df00557b85cb61aefc0dbadb051c8e6595a0dd | c87b7eec9b94ccce8f140b09a827443fecac5d3d | refs/heads/master | 2020-03-08T03:16:15.355916 | 2018-02-22T20:58:38 | 2018-02-22T20:58:38 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,707 | cpp | /** Prognostic Data Structure- Body
* @file Prognostic Data Structure Classes
* @ingroup GPIC++
* @ingroup ProgData
*
* @brief Prognostic Data Structure Classes - Classes used for storing, distributing, and manipulation prognostic data
*
* @author Chris Teubert
* @version 0.1.0
*
* @pre Prognostic Configuration File and Prognoster Configuration Files
*
* Contact: Chris Teubert ([email protected])
* Created: December 8, 2015
*
* @copyright Copyright (c) 2013-2016 United States Government as represented by
* the Administrator of the National Aeronautics and Space Administration.
* All Rights Reserved.
*/
#include <cmath> // For NAN
#include "ProgData.h"
#include "DataPoints.h"
namespace PCOE {
//*------------------------------------------------------------------*
//| Public Functions |
//*------------------------------------------------------------------*
ProgData::ProgData() : componentName(""),
prognoserName(""),
uniqueId("") {
}
ProgData::ProgData(const std::string & progName,
const std::string & compName,
const std::string & uId)
: componentName(compName),
prognoserName(progName),
uniqueId(uId) {
}
void ProgData::setUncertainty(const UType uncertType) {
// Set uncertainty at each lower level.
events.setUncertainty(uncertType);
sysTrajectories.setUncertainty(uncertType);
futureInputs.setUncertainty(uncertType);
}
void ProgData::setPredictions(const double interval, const unsigned int nPredictions) {
// Set number of predictions at each lower level
events.setNTimes(nPredictions);
sysTrajectories.setNTimes(nPredictions);
futureInputs.setNTimes(nPredictions);
times.resize(nPredictions + 1);
for (unsigned int i = 0; i <= nPredictions; i++) {
times[i] = i*interval;
}
}
void ProgData::setPredictions(const std::vector<double> & pred) {
// Set number of predictions at each lower level
events.setNTimes(static_cast<unsigned int>(pred.size()));
sysTrajectories.setNTimes(static_cast<unsigned int>(pred.size()));
futureInputs.setNTimes(static_cast<unsigned int>(pred.size()));
times.resize(pred.size() + 1);
for (unsigned int i = 1; i <= pred.size(); i++) {
// @note: times[0] is allways current time
times[i] = pred[i - 1];
}
}
void ProgData::setupOccurrence(const unsigned int nSamples) {
auto eventList = events.getLabels();
// For each event
for (const auto & it : eventList) {
// Done this way so DataPoints can stay generic
events[it].setNumOccurrenceSamples(nSamples);
}
}
void ProgData::addEvents(const std::vector<std::string> & names) {
// Add vector of events
for (const auto & it : names) {
events.addNew(it, ""); // Note: No description
}
}
void ProgData::addSystemTrajectories(const std::vector<std::string> & names) {
for (const auto & it : names) {
sysTrajectories.addNew(it, "");
}
}
void ProgData::addInternals(const std::vector<std::string> & names) {
for (const auto & it : names) {
internals[it] = NAN;
}
}
std::vector<std::string> ProgData::getInternalNames() const {
std::vector<std::string> Labels;
for (const auto & it : internals) {
Labels.push_back(it.first);
}
return Labels;
}
}
| [
"[email protected]"
] | |
a1b0201a216b1bb1405a371d03fa32bf2689349a | 86e739fee9a2aae7813b0fbc171a2585295d3461 | /leetcode/editor/cn/36-valid-sudoku.cpp | c8f48ffada04c9a9c04311cc2079da64596069af | [] | no_license | Modesty-Li/leetcode | 222f53fe30a26f40775a58eba5d892fbe5f6d98f | 79851c62a286ebc4c6eb8d75d259baff3f797f34 | refs/heads/master | 2023-08-03T01:45:32.454838 | 2021-09-17T11:07:28 | 2021-09-17T11:07:28 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,943 | cpp | //请你判断一个 9x9 的数独是否有效。只需要 根据以下规则 ,验证已经填入的数字是否有效即可。
//
//
// 数字 1-9 在每一行只能出现一次。
// 数字 1-9 在每一列只能出现一次。
// 数字 1-9 在每一个以粗实线分隔的 3x3 宫内只能出现一次。(请参考示例图)
//
//
// 数独部分空格内已填入了数字,空白格用 '.' 表示。
//
// 注意:
//
//
// 一个有效的数独(部分已被填充)不一定是可解的。
// 只需要根据以上规则,验证已经填入的数字是否有效即可。
//
//
//
//
// 示例 1:
//
//
//输入:board =
//[["5","3",".",".","7",".",".",".","."]
//,["6",".",".","1","9","5",".",".","."]
//,[".","9","8",".",".",".",".","6","."]
//,["8",".",".",".","6",".",".",".","3"]
//,["4",".",".","8",".","3",".",".","1"]
//,["7",".",".",".","2",".",".",".","6"]
//,[".","6",".",".",".",".","2","8","."]
//,[".",".",".","4","1","9",".",".","5"]
//,[".",".",".",".","8",".",".","7","9"]]
//输出:true
//
//
// 示例 2:
//
//
//输入:board =
//[["8","3",".",".","7",".",".",".","."]
//,["6",".",".","1","9","5",".",".","."]
//,[".","9","8",".",".",".",".","6","."]
//,["8",".",".",".","6",".",".",".","3"]
//,["4",".",".","8",".","3",".",".","1"]
//,["7",".",".",".","2",".",".",".","6"]
//,[".","6",".",".",".",".","2","8","."]
//,[".",".",".","4","1","9",".",".","5"]
//,[".",".",".",".","8",".",".","7","9"]]
//输出:false
//解释:除了第一行的第一个数字从 5 改为 8 以外,空格内其他数字均与 示例1 相同。 但由于位于左上角的 3x3 宫内有两个 8 存在, 因此这个数独是无
//效的。
//
//
//
// 提示:
//
//
// board.length == 9
// board[i].length == 9
// board[i][j] 是一位数字或者 '.'
//
// Related Topics 哈希表
// 👍 533 👎 0
#include "include/headers.h"
using namespace std;
//leetcode submit region begin(Prohibit modification and deletion)
class Solution {
public:
bool isValidSudoku(vector<vector<char>> &board) {
vector<vector<int>> row(9, vector<int>(9,0));
vector<vector<int>> col(9, vector<int>(9,0));
vector<vector<int>> box(9, vector<int>(9,0));
int val, box_pos;
for (int i = 0; i < 9; ++i) {
for (int j = 0; j < 9; ++j) {
if (board[i][j] == '.') {
continue;
}
val = board[i][j] - '1';
box_pos = (i / 3) * 3 + j / 3;
if (row[i][val] == 0 && col[j][val] == 0 && box[box_pos][val] == 0) {
row[i][val] = 1;
col[j][val] = 1;
box[box_pos][val] = 1;
} else {
return false;
}
}
}
return true;
}
};
//leetcode submit region end(Prohibit modification and deletion)
int main() {
Solution s;
} | [
"[email protected]"
] | |
98970687c7453761f1f841d81387dcdeadc861a0 | d0fb46aecc3b69983e7f6244331a81dff42d9595 | /ccc/src/model/ListPersonalNumbersOfUserResult.cc | 7b0a3653080b7cc42db9082698fc849e5813af07 | [
"Apache-2.0"
] | permissive | aliyun/aliyun-openapi-cpp-sdk | 3d8d051d44ad00753a429817dd03957614c0c66a | e862bd03c844bcb7ccaa90571bceaa2802c7f135 | refs/heads/master | 2023-08-29T11:54:00.525102 | 2023-08-29T03:32:48 | 2023-08-29T03:32:48 | 115,379,460 | 104 | 82 | NOASSERTION | 2023-09-14T06:13:33 | 2017-12-26T02:53:27 | C++ | UTF-8 | C++ | false | false | 3,231 | cc | /*
* Copyright 2009-2017 Alibaba Cloud All rights reserved.
*
* 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.
*/
#include <alibabacloud/ccc/model/ListPersonalNumbersOfUserResult.h>
#include <json/json.h>
using namespace AlibabaCloud::CCC;
using namespace AlibabaCloud::CCC::Model;
ListPersonalNumbersOfUserResult::ListPersonalNumbersOfUserResult() :
ServiceResult()
{}
ListPersonalNumbersOfUserResult::ListPersonalNumbersOfUserResult(const std::string &payload) :
ServiceResult()
{
parse(payload);
}
ListPersonalNumbersOfUserResult::~ListPersonalNumbersOfUserResult()
{}
void ListPersonalNumbersOfUserResult::parse(const std::string &payload)
{
Json::Reader reader;
Json::Value value;
reader.parse(payload, value);
setRequestId(value["RequestId"].asString());
auto dataNode = value["Data"];
if(!dataNode["PageNumber"].isNull())
data_.pageNumber = std::stoi(dataNode["PageNumber"].asString());
if(!dataNode["PageSize"].isNull())
data_.pageSize = std::stoi(dataNode["PageSize"].asString());
if(!dataNode["TotalCount"].isNull())
data_.totalCount = std::stoi(dataNode["TotalCount"].asString());
auto allListNode = dataNode["List"]["PhoneNumber"];
for (auto dataNodeListPhoneNumber : allListNode)
{
Data::PhoneNumber phoneNumberObject;
if(!dataNodeListPhoneNumber["Active"].isNull())
phoneNumberObject.active = dataNodeListPhoneNumber["Active"].asString() == "true";
if(!dataNodeListPhoneNumber["Number"].isNull())
phoneNumberObject.number = dataNodeListPhoneNumber["Number"].asString();
if(!dataNodeListPhoneNumber["City"].isNull())
phoneNumberObject.city = dataNodeListPhoneNumber["City"].asString();
if(!dataNodeListPhoneNumber["InstanceId"].isNull())
phoneNumberObject.instanceId = dataNodeListPhoneNumber["InstanceId"].asString();
if(!dataNodeListPhoneNumber["ContactFlowId"].isNull())
phoneNumberObject.contactFlowId = dataNodeListPhoneNumber["ContactFlowId"].asString();
if(!dataNodeListPhoneNumber["Province"].isNull())
phoneNumberObject.province = dataNodeListPhoneNumber["Province"].asString();
data_.list.push_back(phoneNumberObject);
}
if(!value["Code"].isNull())
code_ = value["Code"].asString();
if(!value["HttpStatusCode"].isNull())
httpStatusCode_ = std::stoi(value["HttpStatusCode"].asString());
if(!value["Message"].isNull())
message_ = value["Message"].asString();
}
std::string ListPersonalNumbersOfUserResult::getMessage()const
{
return message_;
}
int ListPersonalNumbersOfUserResult::getHttpStatusCode()const
{
return httpStatusCode_;
}
ListPersonalNumbersOfUserResult::Data ListPersonalNumbersOfUserResult::getData()const
{
return data_;
}
std::string ListPersonalNumbersOfUserResult::getCode()const
{
return code_;
}
| [
"[email protected]"
] | |
f465afa0c58cf245e7c44193d6f1029656d0f707 | 59cb42fceb22245d72b8cdd463449392b3507b37 | /mega/Synthesis/Fnd_since_EEPROM_SPI_I2C/ShiftRegisert.ino | 6ccc8c762e9e93af19323d6bb1e9098465b262d9 | [] | no_license | isaiahIM/arduino_study | 30d03485a83874e622edb3185c8917552c94b16b | 713acd439709834e3439a9fd5b75d88cb8e20377 | refs/heads/master | 2020-04-22T17:23:18.268855 | 2019-02-13T16:30:11 | 2019-02-13T16:30:11 | 170,539,452 | 1 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 1,419 | ino | void Init_Shift(int dataPin, int clockPin, int latchPin)
{
pinMode(dataPin, OUTPUT);
pinMode(clockPin, OUTPUT);
pinMode(latchPin, OUTPUT);
}
void Init_SiftEnable(int enablePin)
{
pinMode(enablePin, OUTPUT);
}
void ShiftEnable(int enablePin)
{
digitalWrite(enablePin, 0);
}
void ShiftDisable(int enablePin)
{
digitalWrite(enablePin, 1);
}
void ShiftByte(int dataPin, int clockPin, int latchPin, int type, uint8_t Data)
{
uint8_t mask, i;
digitalWrite(latchPin, 0);
if(type==LSB_FIRST)
{
mask=0x01;
for(i=0; i<8; i++)
{
digitalWrite(dataPin, Data&mask);
digitalWrite(clockPin, 1);
digitalWrite(clockPin, 0);
mask<<=1;
}
}
else if(type==MSB_FIRST)
{
mask=0x80;
for(i=0; i<8; i++)
{
digitalWrite(dataPin, Data&mask);
digitalWrite(clockPin, 1);
digitalWrite(clockPin, 0);
mask>>=1;
}
}
digitalWrite(latchPin, 1);
}
int Chk_ShiftPWM(uint32_t cycle_us, double duty, uint32_t Time_us, uint32_t *PWM_Time_us)
{
if(Time_us-(*PWM_Time_us)<= cycle_us )
{
if(Time_us-(*PWM_Time_us)<= cycle_us*(duty/100) )
{
return RUN_PWM;
}
else
{
return STOP_PWM;
}
}
else
{
*PWM_Time_us=Time_us;
}
}
| [
"[email protected]"
] | |
642611fcecb1ed3a4d120df04b447293a8d51452 | 642227f9a45c71299f833be42301485771ee6968 | /luogu/线性状态动态规划/最长公共子序列.cpp | 1d5a1cbc1d5a23409072039043178e6e151fb600 | [] | no_license | Laizl95/Algorithm | f1fe0309d76424d4af923f0f91532a5c4a7b7e85 | f92a25de18f0dae922e3ecf3ed0b71b59126d4ac | refs/heads/master | 2021-12-26T04:32:22.470220 | 2021-08-16T14:25:56 | 2021-08-16T14:25:56 | 176,264,425 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 871 | cpp | #include<bits/stdc++.h>
#define rep(i,x,y) for(int i=x;i<y;++i)
#define per(i,x,y) for(int i=y-1;i>=x;--i)
#define ms(x,y) memset(x,y,sizeof(x))
#define pb(x) push_back(x)
#define mp(x,y) make_pair(x,y)
#define pii pair<int,int>
#define fi first
#define se second
using namespace std;
const int N=1e5+5,inf=1e6+5;
typedef long long LL;
int dp[N],a[N],b[N];
int solve(const int &x,const int &_l,const int &_r){
int l=_l,r=_r;
while(l<=r){
int mid=l+r>>1;
if(dp[mid]>=x) r=mid-1;
else l=mid+1;
}
return l;
}
int main(){
int n,x;
scanf("%d",&n);
rep(i,0,n) scanf("%d",&a[i+1]);
rep(i,1,n+1) {
scanf("%d",&x);
b[x]=i;
}
int len=0;
rep(i,1,n+1){
int p=solve(b[a[i]],1,len);
if(p>len){++len;dp[len]=b[a[i]];}
else dp[p]=b[a[i]];
}
cout<<len<<endl;
return 0;
}
| [
"[email protected]"
] | |
0f8958d711576a1c1046148092fb9c3f3afa06a5 | 902e56e5eb4dcf96da2b8c926c63e9a0cc30bf96 | /LibsExternes/Includes/boost/spirit/home/qi/string.hpp | 37156390de645c5756830bb3e13a5a465d4d6e35 | [
"BSD-3-Clause"
] | permissive | benkaraban/anima-games-engine | d4e26c80f1025dcef05418a071c0c9cbd18a5670 | 8aa7a5368933f1b82c90f24814f1447119346c3b | refs/heads/master | 2016-08-04T18:31:46.790039 | 2015-03-22T08:13:55 | 2015-03-22T08:13:55 | 32,633,432 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 637 | hpp | /*=============================================================================
Copyright (c) 2001-2010 Joel de Guzman
Distributed under the Boost Software License, Version 1.0. (See accompanying
file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
==============================================================================*/
#if !defined(BOOST_SPIRIT_STRING_FEBRUARY_03_2007_0355PM)
#define BOOST_SPIRIT_STRING_FEBRUARY_03_2007_0355PM
#if defined(_MSC_VER)
#pragma once
#endif
#include <boost/spirit/home/qi/string/lit.hpp>
#include <boost/spirit/home/qi/string/symbols.hpp>
#endif
| [
"[email protected]@bd273c4a-bd8d-77bb-0e36-6aa87360798c"
] | [email protected]@bd273c4a-bd8d-77bb-0e36-6aa87360798c |
7a07ea4166f0dc28cbdf1312085d80281608d2d5 | daa23399160510bbcef608546ef4347916fb51c0 | /attribute_copy/attribute_copy/attributecopy.h | 39151f8ca67889d1f4ddf32b9cb1fa3bdb9a4fdc | [] | no_license | sknewgiser/repo | ec41d79123094526d3ce8fdfa05e9f7f08366618 | afe4b2d8e72684b398273229ca6f5cbea69c4377 | refs/heads/master | 2021-01-01T16:53:39.001182 | 2017-07-21T12:14:33 | 2017-07-21T12:14:33 | 97,944,473 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,412 | h | /***************************************************************************
* Copyright (C) 2003 by Tim Sutton *
* [email protected] *
* *
* This is a plugin generated from the QGIS plugin template *
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation; either version 2 of the License, or *
* (at your option) any later version. *
***************************************************************************/
#ifndef attributecopy_H
#define attributecopy_H
#include <QDialog>
#include <ui_attributecopy.h>
#include <qgsmapcanvas.h>
#include <qtablewidget.h>
#include <qgsfield.h>
#include <qgisinterface.h>
#include <qmutex.h>
#include "qgsspatialindex.h"
/**
@author Tim Sutton
*/
class attributecopy : public QDialog, private Ui::AttributeCopyForm
{
Q_OBJECT
public:
attributecopy( QWidget* parent = 0, Qt::WindowFlags fl = 0 );
~ attributecopy();
//QgsVectorLayer *mLayer;
QMutex mLayerMutex;
QMutex mIndexMutex;
QgsSpatialIndex mIndex;
private:
QgisInterface *mQGisIface;
static const int context_id = 0;
void initUiEvents();
void GetLayersName();
void initUiLists();
void initSource();
bool selectedOnly;
void readXml();
//void splitCopy(QgsFeatureIterator srcIter,QgsFeatureIterator targetIter,QMap<QString,QString> *fieldMap);
//void clipCopy(QgsFeatureIterator srcIter,QgsFeatureIterator targetIter,QMap<QString,QString> *fieldMap);
//void copyLyrToLyr(QgsFeatureIterator srcIter,QgsFeatureIterator targetIter,QMap<QString,QString> *fieldMap);
//int getAreaMax(QList<double> areaList);
//void copyattribute(QgsFields srcFields,QTableWidget tableField);
QgsFeature copyattributes(QgsFeature srcFeature,QgsFields *srcFields,QgsFeature targetFeature,QgsFields *targetFields,QMap<QString,QString> *fieldMap);
void updateFeature( QgsFeature& feature,QgsVectorLayer *mLayer);
private slots:
void on_buttonBox_accepted();
void on_buttonBox_rejected();
void on_buttonBox_helpRequested();
void on_hand_match_click();
void on_auto_match_click();
void on_all_match_click();
void on_delete_relation_click();
//void copyattribute(QgsFields *srcFields,QgsFields *targetFields,QTableWidget *tableField);
//void on_comBox_currentIndexChanged(int Index);
void on_srcComBox_activated(const QString &text);
void on_updateComBox_activated(const QString &text);
void on_srcComBox_EditTextChanged(const QString &text);
void on_updateComBox_EditTextChanged(const QString &text);
void on_table_cellclicked(int row,int column);
void on_select_all_click();
void on_sure_click();
void on_close();
// void timerDone();
void on_checkbox_changed(int row,int column);
void on_src_activated(const QString &text);
void on_upd_activated(const QString &text);
void onRadioClicked();
void onAddSet();
void onSaveSet();
void onDeleteSet();
void on_TabWidget_CurrentChanged(int index);
//void on_cbxConfigList_EditTextChanged(const QString &text);
void on_cbxConfigList_activated(const QString &text);
};
#endif
| [
"[email protected]"
] | |
ea3f3ab26f3ab47b2864427e31e35651d64b541d | 888ff1ff4f76c61e0a2cff281f3fae2c9a4dcb7b | /1000/1700/1760/1769.cpp | 7e7a1e44d29e32e1dd33d2a0a241f960ca691f2c | [] | no_license | sanjusss/leetcode-cpp | 59e243fa41cd5a1e59fc1f0c6ec13161fae9a85b | 8bdf45a26f343b221caaf5be9d052c9819f29258 | refs/heads/master | 2023-08-18T01:02:47.798498 | 2023-08-15T00:30:51 | 2023-08-15T00:30:51 | 179,413,256 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 730 | cpp | /*
* @Author: sanjusss
* @Date: 2022-12-02 08:24:47
* @LastEditors: sanjusss
* @LastEditTime: 2022-12-02 08:31:31
* @FilePath: \1000\1700\1760\1769.cpp
*/
#include "leetcode.h"
class Solution {
public:
vector<int> minOperations(string boxes) {
int n = boxes.size();
vector<int> ans(n);
int prev = 0;
int cnt = 0;
for (int i = 0; i < n; ++i) {
prev += cnt;
ans[i] += prev;
cnt += boxes[i] - '0';
}
prev = 0;
cnt = 0;
for (int i = n - 1; i >= 0; --i) {
prev += cnt;
ans[i] += prev;
cnt += boxes[i] - '0';
}
return ans;
}
};
TEST(&Solution::minOperations) | [
"[email protected]"
] | |
0e5c8cc5bff5d99cf780cbf8577e27e5eb048517 | 381d605da20ca3342687e26c5bd00936fe7a46e7 | /Topcoder/LotteryTicket.cpp | ad0e41df190fc6cbaf0ffdce47cc64712bd2bad7 | [] | no_license | z0CoolCS/CompetitiveProgramming | 4a4c278533001a0a4e8440ecfba9c7a4bb8132db | 0894645c918f316c2ce6ddc5fd5fb20af6c8b071 | refs/heads/master | 2023-04-28T08:15:29.245592 | 2021-04-20T01:02:28 | 2021-04-20T01:02:28 | 228,505,384 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 551 | cpp | #include<bits/stdc++.h>
using namespace std;
class LotteryTicket {
public:
bool bt (vector<int>&v, int ind, int cost) {
if (cost == 0) { return true; }
if (cost < 0) { return false; }
if (ind == 4) { return false; }
if (bt (v, ind + 1, cost - v[ind])) {
return true;
}
return bt (v, ind + 1, cost);
}
string buy (int cost, int b1, int b2, int b3, int b4){
vector<int> v = {b1, b2, b3, b4};
if (bt(v, 0, cost)) {
return "POSSIBLE";
}
return "IMPOSSIBLE";
}
};
| [
"Gio@"
] | Gio@ |
16371edbf19d0d5d04c380199f6fe37b798bafe3 | 17351ee942ab61898e56a1844b1822a51b3ac67d | /UnrealEngine/Meteor/Source/Meteor/Public/Common/MeteorSingleton.h | 9c631c4a20132865fcc0b82072546d08d5ae0e12 | [] | no_license | HangRuan/Meteor | 36c7e209614d3f87decacb2435cec4509235f2a9 | b4d6578bff0ead6753d61d9e566e3600fd128602 | refs/heads/master | 2023-03-16T17:16:02.705489 | 2018-02-11T16:38:30 | 2018-02-11T16:38:30 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 521 | h | // Copyright IceRiver. All Rights Reserved.
#pragma once
#include "CoreMinimal.h"
#include "UObject/NoExportTypes.h"
#include "Engine/StreamableManager.h"
#include "MeteorSingleton.generated.h"
/**
*
*/
UCLASS(Blueprintable, BlueprintType)
class METEOR_API UMeteorSingleton : public UObject
{
GENERATED_BODY()
public:
UMeteorSingleton(const FObjectInitializer& ObjectInitializer);
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "Meteor Global")
int32 FrameCount;
FStreamableManager StreamMgr;
};
| [
"[email protected]"
] | |
fb02e2134c82934b7f9ddba78d9efc1a44157915 | 963451d6561400a36bb8ff81981b29e8e7912046 | /Source/TowerDefense/Private/UI/Style/RepairWidgetStyle.h | 2b56fb92eb498a41c6c60eb08fc5bb4a6eae218d | [] | no_license | haiaimi/TowerDefense | ded5420f3007d58324672e06c49e473b3dbe4f4e | baadeebee577bb8ab0c03c3f876360fb5beda0d9 | refs/heads/master | 2020-04-11T18:55:45.946148 | 2019-03-22T13:03:05 | 2019-03-22T13:03:05 | 162,017,023 | 8 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,289 | h | // Fill out your copyright notice in the Description page of Project Settings.
#pragma once
#include "CoreMinimal.h"
#include "Styling/SlateWidgetStyle.h"
#include "SlateWidgetStyleContainerBase.h"
#include <SlateBrush.h>
#include "RepairWidgetStyle.generated.h"
/**
*
*/
USTRUCT()
struct FRepairStyle : public FSlateWidgetStyle
{
GENERATED_USTRUCT_BODY()
FRepairStyle();
virtual ~FRepairStyle();
// FSlateWidgetStyle
virtual void GetResources(TArray<const FSlateBrush*>& OutBrushes) const override;
static const FName TypeName;
virtual const FName GetTypeName() const override { return TypeName; };
static const FRepairStyle& GetDefault();
UPROPERTY(EditAnywhere, Category = Appearance)
struct FSlateBrush RepairIcon;
UPROPERTY(EditAnywhere, Category = Appearance)
struct FSlateBrush RepairAction;
};
/**
*/
UCLASS(hidecategories=Object, MinimalAPI)
class URepairWidgetStyle : public USlateWidgetStyleContainerBase
{
GENERATED_BODY()
public:
/** The actual data describing the widget appearance. */
UPROPERTY(Category=Appearance, EditAnywhere, meta=(ShowOnlyInnerProperties))
FRepairStyle WidgetStyle;
virtual const struct FSlateWidgetStyle* const GetStyle() const override
{
return static_cast< const struct FSlateWidgetStyle* >( &WidgetStyle );
}
};
| [
"[email protected]"
] | |
6d5014ea910277ae7c3d37c6e76836878e221361 | 45364deefe009a0df9e745a4dd4b680dcedea42b | /SDK/FSD_BP_HUD_SpaceRig_classes.hpp | 9de0e08ef07e561fba06efb70ccd78d2b15f591c | [] | no_license | RussellJerome/DeepRockGalacticSDK | 5ae9b59c7324f2a97035f28545f92773526ed99e | f13d9d8879a645c3de89ad7dc6756f4a7a94607e | refs/heads/master | 2022-11-26T17:55:08.185666 | 2020-07-26T21:39:30 | 2020-07-26T21:39:30 | 277,796,048 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,234 | hpp | #pragma once
// DeepRockGalactic SDK
#ifdef _MSC_VER
#pragma pack(push, 0x8)
#endif
#include "FSD_BP_HUD_SpaceRig_structs.hpp"
namespace SDK
{
//---------------------------------------------------------------------------
//Classes
//---------------------------------------------------------------------------
// BlueprintGeneratedClass BP_HUD_SpaceRig.BP_HUD_SpaceRig_C
// 0x0078 (0x04B0 - 0x0438)
class ABP_HUD_SpaceRig_C : public AFSDHUD
{
public:
struct FPointerToUberGraphFrame UberGraphFrame; // 0x0438(0x0008) (ZeroConstructor, Transient, DuplicateTransient)
class USceneComponent* DefaultSceneRoot; // 0x0440(0x0008) (BlueprintVisible, ZeroConstructor, InstancedReference, IsPlainOldData)
class APlayerCharacter* PlayerCharacter; // 0x0448(0x0008) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnTemplate, DisableEditOnInstance, IsPlainOldData)
class UHUD_SpaceRig_C* HUD; // 0x0450(0x0008) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, InstancedReference, IsPlainOldData)
TArray<class UUserWidget*> OwnedWidgets; // 0x0458(0x0010) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance)
TArray<TSoftObjectPtr<class UClass>> PendingWindows; // 0x0468(0x0010) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance)
TArray<struct FClaimableRewardEntry> PendingPromotionRewards; // 0x0478(0x0010) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance)
bool PendingFirstPromotion; // 0x0488(0x0001) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
unsigned char UnknownData00[0x7]; // 0x0489(0x0007) MISSED OFFSET
TArray<class UFSDEvent*> PendingEventRewards; // 0x0490(0x0010) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance)
class UGameDLCSettings* DLCSettings; // 0x04A0(0x0008) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
class UWindowWidget* CheatMenu; // 0x04A8(0x0008) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, InstancedReference, IsPlainOldData)
static UClass* StaticClass()
{
static auto ptr = UObject::FindClass("BlueprintGeneratedClass BP_HUD_SpaceRig.BP_HUD_SpaceRig_C");
return ptr;
}
void FetchPromotionRewards(bool* OutSuccess);
void HasSelectedCharacterBeenPromoted(bool* IsPromoted);
void ShowNextQueuedWindow();
void EnqueueWindow(TSoftObjectPtr<class UClass>* WidgetClass);
void PlayerSpawned(class APlayerCharacter** Player);
void OnVisibilityChanged();
void ReceiveDestroyed();
void ReceiveBeginPlay();
void OnCountdownCompleted();
void Update_Visibility();
void Handle_Count_Down();
void Setup_Campaign_Notifications();
void OnCampaignNotification_Event(class UCampaignNotification** Notification);
void Setup_Retirement_Shouts();
void OnEligibleForRetirementAssignment(class UBP_GameInstance_C** GameInstance);
void Setup_Spacerig_Notifications();
void Setup_UI_Notifications();
void Setup_Promotion_Rewards();
void OnLastWindowClosed();
void Setup_First_Infused_Core();
void Setup_Pending_Rewards();
void Setup_FSD_Events();
void OnFSDEventActiveChanged(class UFSDEvent** InFsdEvent, bool* InIsActive);
void SetupTutorialMessage();
void CheckForTutorialPrompt();
void Stop_Check_For_Tutorial_Prompt();
void Setup_Game_DLC_Announcements();
void CheatMenuRequest();
void ExecuteUbergraph_BP_HUD_SpaceRig(int* EntryPoint);
};
}
#ifdef _MSC_VER
#pragma pack(pop)
#endif
| [
"[email protected]"
] | |
1a4883d241cba0d04096eca18447e263d85ab5cd | d83c0b74be0e582cc60ebbbc1352e522c149fbc6 | /src/faceCommon/src/facedata/surfaceprocessor.cpp | 12f7dbc764f15a9ad4c9b45535df38bd26d31015 | [] | no_license | stepanmracek/face | 89de43cfe3959b1042730c346bdbd56624e768b3 | 45b800821f6cb89b9ccf75e57c5f21ba2d54f760 | refs/heads/master | 2021-01-21T10:08:53.863594 | 2017-05-23T09:41:42 | 2017-05-23T09:41:42 | 6,517,713 | 9 | 7 | null | 2017-05-23T09:41:44 | 2012-11-03T08:39:52 | C++ | UTF-8 | C++ | false | false | 20,184 | cpp | #include "faceCommon/facedata/surfaceprocessor.h"
#include <math.h>
#include <limits>
#include "faceCommon/facedata/util.h"
#include "faceCommon/linalg/pca.h"
#include "faceCommon/facedata/mdenoise/mdenoise.h"
using namespace Face::FaceData;
void SurfaceProcessor::smooth(Mesh &mesh, double alpha, int steps)
{
std::map<int, std::set<int>> neighbours;
int pc = mesh.pointsMat.rows;
int tc = mesh.triangles.size();
for (int i = 0; i < tc; i++)
{
neighbours[mesh.triangles[i][0]].insert(mesh.triangles[i][1]);
neighbours[mesh.triangles[i][0]].insert(mesh.triangles[i][2]);
neighbours[mesh.triangles[i][1]].insert(mesh.triangles[i][0]);
neighbours[mesh.triangles[i][1]].insert(mesh.triangles[i][2]);
neighbours[mesh.triangles[i][2]].insert(mesh.triangles[i][0]);
neighbours[mesh.triangles[i][2]].insert(mesh.triangles[i][1]);
}
double * newx = new double[pc];
double * newy = new double[pc];
double * newz = new double[pc];
for (int i = 0; i < steps; i++)
{
for (int j = 0; j < pc; j++)
{
double sumx = 0.0;
double sumy = 0.0;
double sumz = 0.0;
for (int neighbour : neighbours[j])
{
sumx += (mesh.pointsMat(neighbour, 0) - mesh.pointsMat(j, 0));
sumy += (mesh.pointsMat(neighbour, 1) - mesh.pointsMat(j, 1));
sumz += (mesh.pointsMat(neighbour, 2) - mesh.pointsMat(j, 2));
}
newx[j] = sumx/neighbours[j].size();
newy[j] = sumy/neighbours[j].size();
newz[j] = sumz/neighbours[j].size();
}
for (int j = 0; j < pc; j++)
{
mesh.pointsMat(j, 0) += alpha * newx[j];
mesh.pointsMat(j, 1) += alpha * newy[j];
mesh.pointsMat(j, 2) += alpha * newz[j];
}
}
delete [] newx;
delete [] newy;
delete [] newz;
}
void SurfaceProcessor::zsmooth(Mesh &mesh, double alpha, int steps)
{
std::map<int, std::set<int>> neighbours;
int pc = mesh.pointsMat.rows;
int tc = mesh.triangles.size();
for (int i = 0; i < tc; i++)
{
neighbours[mesh.triangles[i][0]].insert(mesh.triangles[i][1]);
neighbours[mesh.triangles[i][0]].insert(mesh.triangles[i][2]);
neighbours[mesh.triangles[i][1]].insert(mesh.triangles[i][0]);
neighbours[mesh.triangles[i][1]].insert(mesh.triangles[i][2]);
neighbours[mesh.triangles[i][2]].insert(mesh.triangles[i][0]);
neighbours[mesh.triangles[i][2]].insert(mesh.triangles[i][1]);
}
std::vector<double> newz(pc);
for (int i = 0; i < steps; i++)
{
for (int j = 0; j < pc; j++)
{
double sumz = 0.0;
for (int neighbour : neighbours[j])
{
sumz += (mesh.pointsMat(neighbour, 2) - mesh.pointsMat(j, 2));
}
newz[j] = sumz/neighbours[j].size();
}
for (int j = 0; j < pc; j++)
{
mesh.pointsMat(j, 2) += alpha * newz[j];
}
}
}
void SurfaceProcessor::anisotropicDiffusionSmooth(Mesh &mesh, AnisotropicDiffusionType type, double edgeThresh, int steps, double dt) {
std::map<int, std::set<int>> neighbours;
int pc = mesh.pointsMat.rows;
int tc = mesh.triangles.size();
for (int i = 0; i < tc; i++)
{
neighbours[mesh.triangles[i][0]].insert(mesh.triangles[i][1]);
neighbours[mesh.triangles[i][0]].insert(mesh.triangles[i][2]);
neighbours[mesh.triangles[i][1]].insert(mesh.triangles[i][0]);
neighbours[mesh.triangles[i][1]].insert(mesh.triangles[i][2]);
neighbours[mesh.triangles[i][2]].insert(mesh.triangles[i][0]);
neighbours[mesh.triangles[i][2]].insert(mesh.triangles[i][1]);
}
for (int i = 0; i < steps; i++)
{
Mesh mesh0(mesh);
Mesh tmpMesh(mesh);
cv::GaussianBlur(mesh.pointsMat, tmpMesh.pointsMat, cv::Size(5, 5), 0.5);
for (int j = 0; j < pc; j++)
{
double gradient;
double diffusionCoef;
double rawGradient;
double stepCoef = 0.0;
for (int neighbour : neighbours[j])
{
gradient = tmpMesh.pointsMat(neighbour, 2) - tmpMesh.pointsMat(j, 2);
rawGradient = mesh0.pointsMat(neighbour, 2) - mesh0.pointsMat(j, 2);
diffusionCoef = edgeThresh;
if (type == PeronaMalic) {
diffusionCoef = 1.0 / (1.0 + (gradient*gradient) / (edgeThresh*edgeThresh));
}
stepCoef += rawGradient * diffusionCoef;
}
mesh.pointsMat(j, 2) = mesh0.pointsMat(j, 2) + dt * stepCoef;
}
}
}
void SurfaceProcessor::mdenoising(Mesh &mesh, float sigma, int normalIterations, int vertexIterations) {
MDenoise::MDenoise mdenoise;
mdenoise.importModel(mesh);
mdenoise.denoise(true, sigma, normalIterations, vertexIterations);
mdenoise.exportVertices(mesh);
}
namespace {
inline double min(double a, double b, double c)
{
double m = a < b ? a : b;
return m < c ? m : c;
}
inline double max(double a, double b, double c)
{
double m = a > b ? a : b;
return m > c ? m : c;
}
inline int convert3DmodelToMap(double value, double minVal, double maxVal, double resultSize)
{
return (value-minVal)/(maxVal-minVal) * resultSize;
}
inline double linearInterpolation(double x1, double y1, double z1,
double x2, double y2, double z2,
double x3, double y3, double z3,
double x, double y)
{
if (x1 == x2 && y1 == y2 && x1 == x3 && y1 == y3)
{
return (z1+z2+z3)/3;
}
// Ax + By + Cz + D = 0
double A = y1*(z2 - z3) + y2*(z3 - z1) + y3*(z1 - z2);
double B = z1*(x2 - x3) + z2*(x3 - x1) + z3*(x1 - x2);
double C = x1*(y2 - y3) + x2*(y3 - y1) + x3*(y1 - y2);
double D = -A*x1 - B*y1 - C*z1;
double result = -(A/C)*x - (B/C)*y - D/C;
if (result != result)
{
return (z1+z2+z3)/3;
}
return result;
}
}
void SurfaceProcessor::depthmap(const Mesh &mesh, Map &map, cv::Point2d meshStart, cv::Point2d meshEnd, SurfaceDataToProcess dataToProcess)
{
Map zmap(map.w, map.h);
int c = mesh.triangles.size();
for (int i = 0; i < c; i++)
{
const cv::Vec3i &t = mesh.triangles[i];
double x1d = mesh.pointsMat(t[0], 0);
double y1d = mesh.pointsMat(t[0], 1);
double x2d = mesh.pointsMat(t[1], 0);
double y2d = mesh.pointsMat(t[1], 1);
double x3d = mesh.pointsMat(t[2], 0);
double y3d = mesh.pointsMat(t[2], 1);
double v1d, v2d, v3d;
switch (dataToProcess)
{
case ZCoord:
v1d = mesh.pointsMat(t[0], 2);
v2d = mesh.pointsMat(t[1], 2);
v3d = mesh.pointsMat(t[2], 2);
break;
case Texture_I:
v1d = 0.299*mesh.colors[t[0]][2] + 0.587*mesh.colors[t[0]][1] + 0.114*mesh.colors[t[0]][0];
v2d = 0.299*mesh.colors[t[1]][2] + 0.587*mesh.colors[t[1]][1] + 0.114*mesh.colors[t[1]][0];
v3d = 0.299*mesh.colors[t[2]][2] + 0.587*mesh.colors[t[2]][1] + 0.114*mesh.colors[t[2]][0];
break;
case Texture_R:
v1d = mesh.colors[t[0]][2];
v2d = mesh.colors[t[1]][2];
v3d = mesh.colors[t[2]][2];
break;
case Texture_G:
v1d = mesh.colors[t[0]][1];
v2d = mesh.colors[t[1]][1];
v3d = mesh.colors[t[2]][1];
break;
case Texture_B:
default:
v1d = mesh.colors[t[0]][0];
v2d = mesh.colors[t[1]][0];
v3d = mesh.colors[t[2]][0];
break;
}
double z1d = mesh.pointsMat(t[0], 2);
double z2d = mesh.pointsMat(t[1], 2);
double z3d = mesh.pointsMat(t[2], 2);
int x1 = convert3DmodelToMap(x1d, meshStart.x, meshEnd.x, map.w);
int y1 = convert3DmodelToMap(y1d, meshStart.y, meshEnd.y, map.h);
int x2 = convert3DmodelToMap(x2d, meshStart.x, meshEnd.x, map.w);
int y2 = convert3DmodelToMap(y2d, meshStart.y, meshEnd.y, map.h);
int x3 = convert3DmodelToMap(x3d, meshStart.x, meshEnd.x, map.w);
int y3 = convert3DmodelToMap(y3d, meshStart.y, meshEnd.y, map.h);
int triangleMinX = min(x1, x2, x3);
int triangleMinY = min(y1, y2, y3);
int triangleMaxX = max(x1, x2, x3);
int triangleMaxY = max(y1, y2, y3);
int dx1 = x2-x1; int dy1 = y2-y1;
int dx2 = x3-x2; int dy2 = y3-y2;
int dx3 = x1-x3; int dy3 = y1-y3;
// vyplnovani...
for (int y = triangleMinY; y <= triangleMaxY; ++y)
{
// inicilizace hranove fce v bode [minx, y]
int e1 = (triangleMinX-x1)*dy1 - (y-y1)*dx1;
int e2 = (triangleMinX-x2)*dy2 - (y-y2)*dx2;
int e3 = (triangleMinX-x3)*dy3 - (y-y3)*dx3;
for (int x = triangleMinX; x <= triangleMaxX; ++x)
{
if( e1 <= 0 && e2 <= 0 && e3 <= 0 )
{
if (x >= 0 && x < map.w && y >= 0 && y < map.h)
{
double v = linearInterpolation(x1, y1, v1d,
x2, y2, v2d,
x3, y3, v3d,
x, y);
double z = linearInterpolation(x1, y1, z1d,
x2, y2, z2d,
x3, y3, z3d,
x, y);
int y2 = (map.h-1)-y;
if (!zmap.flags(y2, x) || (zmap.flags(y2, x) && zmap.values(y2, x) < z))
{
zmap.set(x, y2, z);
map.set(x, y2, v);
}
}
}
// hranova fce o pixel vedle
e1 += dy1;
e2 += dy2;
e3 += dy3;
}
}
}
}
Map SurfaceProcessor::depthmap(const Mesh &mesh, MapConverter &converter,
cv::Point2d meshStart, cv::Point2d meshEnd,
double scaleCoef, SurfaceDataToProcess dataToProcess)
{
converter.meshStart = meshStart;
converter.meshSize = meshEnd - meshStart;
Map map(converter.meshSize.x * scaleCoef , converter.meshSize.y * scaleCoef);
depthmap(mesh, map, converter.meshStart, meshEnd, dataToProcess);
return map;
}
Map SurfaceProcessor::depthmap(const Mesh &mesh, MapConverter &converter, double scaleCoef, SurfaceDataToProcess dataToProcess)
{
converter.meshStart = cv::Point2d(mesh.minx, mesh.miny);
converter.meshSize = cv::Point2d(mesh.maxx - mesh.minx, mesh.maxy - mesh.miny);
Map map(converter.meshSize.x * scaleCoef , converter.meshSize.y * scaleCoef);
depthmap(mesh, map, converter.meshStart, cv::Point2d(mesh.maxx, mesh.maxy), dataToProcess);
return map;
}
double dist(double x1, double y1, double x2, double y2)
{
return sqrt(pow(x1-y1, 2) + pow(x2-y2, 2));
}
CurvatureStruct SurfaceProcessor::calculateCurvatures(Map &depthmap, bool pcl)
{
CurvatureStruct c;
c.curvatureGauss.init(depthmap.w, depthmap.h);
c.curvatureIndex.init(depthmap.w, depthmap.h);
c.curvaturePcl.init(depthmap.w, depthmap.h);
c.curvatureK1.init(depthmap.w, depthmap.h);
c.curvatureK2.init(depthmap.w, depthmap.h);
c.curvatureMean.init(depthmap.w, depthmap.h);
c.peaks.init(depthmap.w, depthmap.h);
c.pits.init(depthmap.w, depthmap.h);
c.saddles.init(depthmap.w, depthmap.h);
c.valleys.init(depthmap.w, depthmap.h);
double k1;
double k2;
//qDebug() << "calculating curvatures - k1, k2, pcl";
for (int x = 0; x < depthmap.w; x++)
{
for (int y = 0; y < depthmap.h; y++)
{
c.curvatureK1.unset(x, y);
c.curvatureK2.unset(x, y);
if (depthmap.isSet(x,y) && depthmap.has8neigbours(x,y))
{
double point[] = {(double)x, (double)y, depthmap.get(x, y)};
// left - right direction
double first[] = {(double)(x-1), (double)y, depthmap.get(x-1, y)};
double second[] = {(double)(x+1), (double)y, depthmap.get(x+1, y)};
double vec1[] = {first[0]-point[0], first[1]-point[1], first[2]-point[2]};
double vec2[] = {second[0]-point[0], second[1]-point[1], second[2]-point[2]};
double angle = Util::angle(vec1,vec2,3);
k1 = M_PI - angle;
double delta = (first[2]+second[2])/2;
if (point[2] < delta)
k1 = -k1;
// top - down direction
first[0] = x; first[1] = y+1; first[2] = depthmap.get(x, y+1);
second[0] = x; second[1] = y-1; second[2] = depthmap.get(x, y-1);
vec1[0] = first[0]-point[0]; vec1[1]=first[1]-point[1]; vec1[2]=first[2]-point[2];
vec2[0] = second[0]-point[0]; vec2[1]=second[1]-point[1]; vec2[2]=second[2]-point[2];
angle = Util::angle(vec1,vec2,3);
k2 = M_PI - angle;
delta = (first[2]+second[2])/2;
if (point[2] < delta)
k2 = -k2;
if (k1 < k2)
{
double tmp = k1;
k1 = k2;
k2 = tmp;
}
k1 = -k1;
k2 = -k2;
c.curvatureK1.set(x, y, k1);
c.curvatureK2.set(x, y, k2);
// PCL
if (pcl)
{
Matrix pcaData(3, 9);
pcaData(0, 0) = x-1; pcaData(1, 0) = y-1; pcaData(2, 0) = depthmap.get(x-1, y-1);
pcaData(0, 1) = x ; pcaData(1, 1) = y-1; pcaData(2, 1) = depthmap.get(x , y-1);
pcaData(0, 2) = x+1; pcaData(1, 2) = y-1; pcaData(2, 2) = depthmap.get(x+1, y-1);
pcaData(0, 3) = x-1; pcaData(1, 3) = y ; pcaData(2, 3) = depthmap.get(x-1, y );
pcaData(0, 4) = x ; pcaData(1, 4) = y ; pcaData(2, 4) = depthmap.get(x , y );
pcaData(0, 5) = x+1; pcaData(1, 5) = y ; pcaData(2, 5) = depthmap.get(x+1, y );
pcaData(0, 6) = x-1; pcaData(1, 6) = y+1; pcaData(2, 6) = depthmap.get(x-1, y+1);
pcaData(0, 7) = x ; pcaData(1, 7) = y+1; pcaData(2, 7) = depthmap.get(x , y+1);
pcaData(0, 8) = x+1; pcaData(1, 8) = y+1; pcaData(2, 8) = depthmap.get(x+1, y+1);
cv::PCA cvPca(pcaData, cv::Mat(), CV_PCA_DATA_AS_COL);
double l0 = cvPca.eigenvalues.at<double>(2);
double l1 = cvPca.eigenvalues.at<double>(1);
double l2 = cvPca.eigenvalues.at<double>(0);
double pclCurvature = l0/(l0+l1+l2);
c.curvaturePcl.set(x, y, pclCurvature);
}
}
}
}
for (int x = 0; x < depthmap.w; x++)
{
for (int y = 0; y < depthmap.h; y++)
{
c.curvatureMean.unset(x, y);
c.curvatureGauss.unset(x, y);
c.curvatureIndex.unset(x, y);
c.peaks.unset(x, y);
c.pits.unset(x, y);
c.saddles.unset(x, y);
c.valleys.unset(x, y);
if (c.curvatureK1.isSet(x,y) && c.curvatureK2.isSet(x,y))
{
double k1 = c.curvatureK1.get(x,y);
double k2 = c.curvatureK2.get(x,y);
double mean = (k1 + k2)/2;
double gauss = k1 * k2;
c.curvatureMean.set(x, y, mean);
c.curvatureGauss.set(x, y, gauss);
if (k1 != k2)
{
double index = 0.5 - M_1_PI*atan((k1+k2)/(k2-k1));
c.curvatureIndex.set(x, y, index);
}
if (gauss > 0.004 && mean < -0.005)
c.peaks.set(x, y, 1);
if (gauss > 0.001 && mean > 0.001)
c.pits.set(x, y, 1);
if (gauss < -0.002)
c.saddles.set(x, y, 1);
if (fabs(gauss) < 0.001 && mean > 0.006)
c.valleys.set(x, y, 1);
}
}
}
return c;
}
Matrix CurvatureStruct::gaussMatrix()
{
return curvatureGauss.toMatrix(0, -0.01, 0.01);
}
Matrix CurvatureStruct::indexMatrix()
{
return curvatureIndex.toMatrix(0, 0, 1);
}
Matrix CurvatureStruct::meanMatrix()
{
return curvatureMean.toMatrix(0, -0.1, 0.1);
}
Matrix CurvatureStruct::pclMatrix()
{
return curvaturePcl.toMatrix(0, 0, 0.0025);
}
std::vector<cv::Point3d> SurfaceProcessor::surfaceCurve(const Map &map, const MapConverter &converter, cv::Point3d start,
cv::Point3d end, int samples, double mapScaleFactor)
{
if (samples <= 1) throw FACELIB_EXCEPTION("invalid samples count");
double nan = NAN;
std::vector<cv::Point3d> result;
for (int i = 0; i < samples; i++)
{
double t = (double)i/(samples-1.0);
cv::Point3d p = start + (t*(end-start));
cv::Point2d mapPoint = converter.MeshToMapCoords(map, p);
bool success;
double z = map.get(mapPoint.x, mapPoint.y, &success) * mapScaleFactor;
if (success)
{
p.z = z;
}
else
{
p == cv::Point3d(nan, nan, nan);
}
result.push_back(p);
}
return result;
}
std::vector<cv::Point3d> SurfaceProcessor::isoGeodeticCurve(const Map &map, const MapConverter &converter,
const cv::Point3d center, double distance, int samples,
double mapScaleFactor)
{
cv::Point2d mapCenter = converter.MeshToMapCoords(map, cv::Point2d(center.x, center.y));
std::vector<cv::Point3d> result;
for (int i = 0; i < samples; i++)
{
double angle = ((double)i) / samples * 2 * M_PI;
double dx = sin(angle);
double dy = -cos(angle);
cv::Point2d prevPoint(mapCenter.x, mapCenter.y);
cv::Point2d currentPoint(mapCenter.x, mapCenter.y);
double prevZ = map.get(mapCenter.x, mapCenter.y) * mapScaleFactor;
double currentZ = prevZ;
double cumulativeDistance = 0.0;
bool hitOutsideMap = false;
while (cumulativeDistance < distance)
{
prevZ = currentZ;
prevPoint = currentPoint;
currentPoint.x += dx;
currentPoint.y += dy;
bool success;
currentZ = map.get(currentPoint.x, currentPoint.y, &success) * mapScaleFactor;
if (!success)
{
hitOutsideMap = true;
break;
}
double d = sqrt((currentZ-prevZ)*(currentZ-prevZ) +
(currentPoint.x - prevPoint.x)*(currentPoint.x - prevPoint.x) +
(currentPoint.y - prevPoint.y)*(currentPoint.y - prevPoint.y)) / mapScaleFactor;
cumulativeDistance += d;
}
if (hitOutsideMap)
{
double nan = NAN;
result.push_back(cv::Point3d(nan, nan, nan));
}
else
{
result.push_back(converter.MapToMeshCoords(map, currentPoint));
}
}
return result;
}
std::vector<double> SurfaceProcessor::isoGeodeticCurveToEuclDistance(const std::vector<cv::Point3d> &isoCuvre, cv::Point3d center)
{
std::vector<double> result;
for (const cv::Point3d &p : isoCuvre)
{
result.push_back(Face::LinAlg::euclideanDistance(p, center));
}
return result;
}
| [
"[email protected]"
] | |
47b103cb1a010a50c67df2493b5ef8c899ec71e0 | 381d6dbaf01cdd9a0a4ae70234d7ea3eae407d2e | /TMZPlayer/bottombar.cpp | a22a65e0faba78254a69d1d5007ed76e4a09282a | [] | no_license | zhoujiayingvana/TMZPlayer | 5e152a7c2ccaff58a1eef4b4b5b92a5b52cb90b6 | 8a161228fe059df33cfc4c66f60a611106fd4de1 | refs/heads/master | 2020-07-06T16:55:21.780457 | 2019-09-11T11:38:47 | 2019-09-11T11:38:47 | 203,083,848 | 2 | 3 | null | 2019-09-09T01:56:04 | 2019-08-19T02:27:17 | C | UTF-8 | C++ | false | false | 25,888 | cpp | #include "bottombar.h"
#include<QDebug>
#include<QToolTip>
/*
*Author:LY
*Function:实现底部栏
*/
BottomBar::BottomBar(QWidget *parent) : QWidget(parent)
{
this->setAttribute(Qt::WA_StyledBackground);
multiplyingPower=1;//倍速播放,默认1倍速
setFixedHeight(60);
lastButton = new QPushButton(this);//上一个按钮
pauseButton = new QPushButton(this);//暂停/播放按钮
nextButton = new QPushButton(this);//下一个按钮
currentPos = new QLabel(this);//播放到的时间
playSlider = new MySlider(this);//播放条
totalTime = new QLabel(this);//总时长
volumeButton = new BottomButton(this);//静音/恢复音量按钮
volumeSlider = new MySlider(this);//音量条
volumeSlider->setValue(10);
playModeButton = new QPushButton(this);//播放模式按钮
switchModeButton = new QPushButton(this);//切换音乐/视频模式按钮
space = new QLabel ();//底部空白
definitionButton = new BottomButton();//清晰度按钮
settingsButton = new BottomButton();//视频设置按钮
full_screenButton = new QPushButton();//全屏/恢复按钮
//使Button、Slider不接受由Tab、鼠标中键产生焦点
lastButton->setFocusPolicy(Qt::NoFocus);
pauseButton->setFocusPolicy(Qt::NoFocus);
nextButton->setFocusPolicy(Qt::NoFocus);
playSlider->setFocusPolicy(Qt::NoFocus);
volumeButton->setFocusPolicy(Qt::NoFocus);
volumeSlider->setFocusPolicy(Qt::NoFocus);
playModeButton->setFocusPolicy(Qt::NoFocus);
switchModeButton->setFocusPolicy(Qt::NoFocus);
definitionButton->setFocusPolicy(Qt::NoFocus);
settingsButton->setFocusPolicy(Qt::NoFocus);
full_screenButton->setFocusPolicy(Qt::NoFocus);
currentPos->setAlignment(Qt::AlignRight|Qt::AlignVCenter);
playSlider->setOrientation(Qt::Horizontal);
volumeSlider->setOrientation(Qt::Horizontal);
/*
* playSlider还需设最大值
*/
playSlider->setMaximum(6009); //test
volumeSlider->setMaximum(100);
lastButton->setObjectName("lastButton");
pauseButton->setObjectName("pauseButton");
nextButton->setObjectName("nextButton");
currentPos->setObjectName("currentPos");
playSlider->setObjectName("playSlider");
totalTime->setObjectName("totalTime");
volumeButton->setObjectName("volumeButton");
volumeSlider->setObjectName("volumeScrollBar");
playModeButton->setObjectName("playModeButton");
switchModeButton->setObjectName("switchModeButton");
definitionButton->setObjectName("definitionButton");
settingsButton->setObjectName("settingsButton");
full_screenButton->setObjectName("full_screenButton");
//固定按钮大小
lastButton->setFixedSize(40, 40);
pauseButton->setFixedSize(40, 40);
nextButton->setFixedSize(40, 40);
currentPos->setFixedSize(36, 30);
playSlider->setFixedHeight(20);
totalTime->setFixedSize(42, 30);
volumeButton->setFixedSize(30, 30);
volumeSlider->setFixedSize(60, 20);
playModeButton->setFixedSize(30, 30);
switchModeButton->setFixedSize(30, 30);
definitionButton->setFixedSize(30, 30);
settingsButton->setFixedSize(30, 30);
full_screenButton->setFixedSize(30, 30);
lastButton->setFlat(true);
pauseButton->setFlat(true);
nextButton->setFlat(true);
volumeButton->setFlat(true);
playModeButton->setFlat(true);
switchModeButton->setFlat(true);
definitionButton->setFlat(true);
settingsButton->setFlat(true);
full_screenButton->setFlat(true);
lastButton->setStyleSheet("QPushButton{ border-image: url(:/image/image/bottomBar/last.png); }");
pauseButton->setStyleSheet("QPushButton{ border-image: url(:/image/image/bottomBar/pause.png); }");
nextButton->setStyleSheet("QPushButton{ border-image: url(:/image/image/bottomBar/next.png); }");
currentPos->setText(QStringLiteral("00:00"));
totalTime->setText(QStringLiteral("4:00"));
volumeButton->setStyleSheet("QPushButton{ border-image: url(:/image/image/bottomBar/volume.png); }");
playModeButton->setStyleSheet("QPushButton{ border-image: url(:/image/image/bottomBar/order.png); }");
switchModeButton->setText(QStringLiteral("切换"));
definitionButton->setText(QStringLiteral("清晰度"));
settingsButton->setStyleSheet("QPushButton{ border-image: url(:/image/image/bottomBar/settings.png); }");
full_screenButton->setStyleSheet("QPushButton{ border-image: url(:/image/image/bottomBar/fullScreen.png); }");
//TEST
volume = 10;
//鼠标悬停在按钮上显示提示条
lastButton->setToolTip(QStringLiteral("上一个"));
pauseButton->setToolTip(QStringLiteral("播放"));
nextButton->setToolTip(QStringLiteral("下一个"));
volumeButton->setToolTip(QStringLiteral("静音"));
volumeSlider->setToolTip(QStringLiteral("音量调节(Up/Down)"));
playModeButton->setToolTip(QStringLiteral("播放模式"));
switchModeButton->setToolTip(QStringLiteral("全屏"));
definitionButton->setToolTip(QStringLiteral("清晰度"));
settingsButton->setToolTip(QStringLiteral("设置"));
full_screenButton->setToolTip(QStringLiteral("全屏"));
//改变光标样式
lastButton->setCursor(Qt::PointingHandCursor);
pauseButton->setCursor(Qt::PointingHandCursor);
nextButton->setCursor(Qt::PointingHandCursor);
playSlider->setCursor(Qt::PointingHandCursor);
volumeButton->setCursor(Qt::PointingHandCursor);
volumeSlider->setCursor(Qt::PointingHandCursor);
playModeButton->setCursor(Qt::PointingHandCursor);
switchModeButton->setCursor(Qt::PointingHandCursor);
definitionButton->setCursor(Qt::PointingHandCursor);
settingsButton->setCursor(Qt::PointingHandCursor);
full_screenButton->setCursor(Qt::PointingHandCursor);
BottomLayout = new QVBoxLayout(this);
BmBottomLayout = new QHBoxLayout();
BmBottomLayout->addWidget(lastButton);
BmBottomLayout->addWidget(pauseButton);
BmBottomLayout->addWidget(nextButton);
BmBottomLayout->addWidget(currentPos);
BmBottomLayout->addWidget(playSlider);
BmBottomLayout->addWidget(totalTime);
BmBottomLayout->addWidget(volumeButton);
BmBottomLayout->addWidget(volumeSlider);
BmBottomLayout->addWidget(playModeButton);
BmBottomLayout->addWidget(switchModeButton);
BmBottomLayout->setContentsMargins(0, 5, 0, 5);
BmBottomLayout->setSpacing(0);
BottomLayout->addLayout(BmBottomLayout);
BottomLayout->setContentsMargins(0, 0, 0, 0);
BottomLayout->setSpacing(0);
volumeWidget = new Widget(parent);//视频模式音量窗口
volumeWidget->setObjectName(QString::fromUtf8("volumeWidget"));
volumeWidget->setAutoFillBackground(true);//test
volumeWidget->setPalette(QPalette(Qt::black));//test
volumeWidget->setGeometry(200, 200, 30, 70);//test
volumeWidget->hide();
volumeLayout =new QVBoxLayout(volumeWidget);//视频模式音量窗口的布局
volumeLayout->setContentsMargins(5, 5, 5, 5);
definitionWidget = new Widget(parent);//视频模式清晰度窗口
definitionWidget->setObjectName(QString::fromUtf8("definitionWidget"));
definitionWidget->setAutoFillBackground(true);//test
definitionWidget->setPalette(QPalette(Qt::black));//test
definitionWidget->setGeometry(200, 200, 40, 90);//test
definitionWidget->hide();
//视频模式清晰度窗口下各清晰度按钮
autoDefinitionButton = new QPushButton(definitionWidget);
p360DefinitionButton = new QPushButton(definitionWidget);
p480DefinitionButton = new QPushButton(definitionWidget);
p720DefinitionButton = new QPushButton(definitionWidget);
autoDefinitionButton->setFocusPolicy(Qt::NoFocus);
p360DefinitionButton->setFocusPolicy(Qt::NoFocus);
p480DefinitionButton->setFocusPolicy(Qt::NoFocus);
p720DefinitionButton->setFocusPolicy(Qt::NoFocus);
autoDefinitionButton->setObjectName("autoDefinitionButton");
p360DefinitionButton->setObjectName("p360DefinitionButton");
p480DefinitionButton->setObjectName("p480DefinitionButton");
p720DefinitionButton->setObjectName("p720DefinitionButton");
autoDefinitionButton->setFixedSize(30,20);
p360DefinitionButton->setFixedSize(30,20);
p480DefinitionButton->setFixedSize(30,20);
p720DefinitionButton->setFixedSize(30,20);
autoDefinitionButton->setFlat(true);
p360DefinitionButton->setFlat(true);
p480DefinitionButton->setFlat(true);
p720DefinitionButton->setFlat(true);
autoDefinitionButton->setText(QStringLiteral("自动"));//TEST
p360DefinitionButton->setText(QStringLiteral("普通"));//TEST
p480DefinitionButton->setText(QStringLiteral("清晰"));//TEST
p720DefinitionButton->setText(QStringLiteral("高清"));//TEST
definitionLayout =new QVBoxLayout(definitionWidget);//视频模式清晰度窗口的布局
definitionLayout->addWidget(p720DefinitionButton);
definitionLayout->addWidget(p480DefinitionButton);
definitionLayout->addWidget(p360DefinitionButton);
definitionLayout->addWidget(autoDefinitionButton);
definitionLayout->setContentsMargins(5, 5, 5, 5);
definitionLayout->setSpacing(0);
settingsWidget = new Widget(parent);//视频模式设置窗口
settingsWidget->setObjectName(QString::fromUtf8("settingsWidget"));
settingsWidget->setAutoFillBackground(true);//test
settingsWidget->setPalette(QPalette(Qt::black));//test
settingsWidget->setGeometry(200, 200, 100, 165);//test
settingsWidget->hide();
//视频模式设置窗口下各按钮
playModeLabel = new QLabel(settingsWidget);
playModeButton_1 = new QPushButton(settingsWidget);
playModeButton_2 = new QPushButton(settingsWidget);
playModeButton_3 = new QPushButton(settingsWidget);
playSpeedLabel = new QLabel(settingsWidget);
multiplyingPowerLabel = new QLabel(settingsWidget);
playSpeedSlider = new MySlider(settingsWidget);
videoRatioLabel = new QLabel(settingsWidget);
autoRatioButton = new QPushButton(settingsWidget);
ratio4_3Button = new QPushButton(settingsWidget);
ratio16_9Button = new QPushButton(settingsWidget);
othersLabel = new QLabel(settingsWidget);
someFunctionButton = new QPushButton(settingsWidget);//test
playSpeedSlider->setMaximum(3);
playSpeedSlider->setValue(1);//倍速播放默认一倍速
playModeButton_1->setFocusPolicy(Qt::NoFocus);
playModeButton_2->setFocusPolicy(Qt::NoFocus);
playModeButton_3->setFocusPolicy(Qt::NoFocus);
playSpeedSlider->setFocusPolicy(Qt::NoFocus);
autoRatioButton->setFocusPolicy(Qt::NoFocus);
ratio4_3Button->setFocusPolicy(Qt::NoFocus);
ratio16_9Button->setFocusPolicy(Qt::NoFocus);
someFunctionButton->setFocusPolicy(Qt::NoFocus);
playSpeedSlider->setOrientation(Qt::Horizontal);
playModeLabel->setObjectName("playModeLabel");
playModeButton_1->setObjectName("playModeButton_1");
playModeButton_2->setObjectName("playModeButton_2");
playModeButton_3->setObjectName("playModeButton_3");
playSpeedLabel->setObjectName("playSpeedLabel");
multiplyingPowerLabel->setObjectName("multiplyingPowerLabel");
playSpeedSlider->setObjectName("playSpeedSlider");
videoRatioLabel->setObjectName("videoRatioLabel");
autoRatioButton->setObjectName("autoRatioButton");
ratio4_3Button->setObjectName("ratio4_3Button");
ratio16_9Button->setObjectName("ratio16_9Button");
othersLabel->setObjectName("othersLabel");
someFunctionButton->setObjectName("someFunctionButton");
playModeLabel->setFixedSize(90,15);
playModeButton_1->setFixedSize(30,20);
playModeButton_2->setFixedSize(30,20);
playModeButton_3->setFixedSize(30,20);
playSpeedLabel->setFixedSize(90,15);
multiplyingPowerLabel->setFixedSize(90,15);
playSpeedSlider->setFixedSize(90,20);
videoRatioLabel->setFixedSize(30,15);
autoRatioButton->setFixedSize(30,20);
ratio4_3Button->setFixedSize(30,20);
ratio16_9Button->setFixedSize(30,20);
othersLabel->setFixedSize(30,15);
someFunctionButton->setFixedSize(30,20);
playModeButton_1->setFlat(true);
playModeButton_2->setFlat(true);
playModeButton_3->setFlat(true);
autoRatioButton->setFlat(true);
ratio4_3Button->setFlat(true);
ratio16_9Button->setFlat(true);
someFunctionButton->setFlat(true);
playModeLabel->setText(QStringLiteral("播放方式"));
playModeButton_1->setText(QStringLiteral("默认"));
playModeButton_2->setText(QStringLiteral("循环"));
playModeButton_3->setText(QStringLiteral("播完暂停"));
playSpeedLabel->setText(QStringLiteral("播放速度"));
multiplyingPowerLabel->setText(QStringLiteral("0.5 1.0 1.25 1.5 2.0"));
videoRatioLabel->setText(QStringLiteral("视频比例"));
autoRatioButton->setText(QStringLiteral("自动"));
ratio4_3Button->setText(QStringLiteral("4:3"));
ratio16_9Button->setText(QStringLiteral("16:9"));
othersLabel->setText(QStringLiteral("其他"));
someFunctionButton->setText(QStringLiteral("其他"));
settingsLayout =new QVBoxLayout(settingsWidget);//视频模式设置窗口的布局
settingsLayout->addWidget(playModeLabel);
QHBoxLayout * playModeLayout = new QHBoxLayout();
playModeLayout->addWidget(playModeButton_1);
playModeLayout->addWidget(playModeButton_2);
playModeLayout->addWidget(playModeButton_3);
playModeLayout->setContentsMargins(0, 0, 0, 0);
playModeLayout->setSpacing(0);
settingsLayout->addLayout(playModeLayout);
settingsLayout->addWidget(playSpeedLabel);
settingsLayout->addWidget(multiplyingPowerLabel);
settingsLayout->addWidget(playSpeedSlider);
settingsLayout->addWidget(videoRatioLabel);
QHBoxLayout * videoRatioLayout = new QHBoxLayout();
videoRatioLayout->addWidget(autoRatioButton);
videoRatioLayout->addWidget(ratio4_3Button);
videoRatioLayout->addWidget(ratio16_9Button);
videoRatioLayout->setContentsMargins(0, 0, 0, 0);
videoRatioLayout->setSpacing(0);
settingsLayout->addLayout(videoRatioLayout);
settingsLayout->addWidget(othersLabel);
settingsLayout->addWidget(someFunctionButton);
settingsLayout->setContentsMargins(5, 5, 5, 5);
settingsLayout->setSpacing(0);
connect(playSlider,SIGNAL(valueChanged(int)),this,SLOT(on_playSlider_valueChanged(int)));
connect(volumeButton,SIGNAL(clicked(bool)),this,SLOT(on_volumeButton_clicked()));
connect(volumeSlider,SIGNAL(valueChanged(int)),this,SLOT(on_volumeSlider_valueChanged(int)));
connect(switchModeButton,SIGNAL(clicked(bool)),this,SLOT(on_switchModeButton_clicked()));
connect(volumeButton,SIGNAL(leaveSignal()),this,SLOT(volumeWidgetDetection()));
connect(definitionButton,SIGNAL(enterSignal(int ,int)),definitionWidget,SLOT(display(int,int)));
connect(definitionButton,SIGNAL(leaveSignal()),this,SLOT(definitionWidgetDetection()));
connect(settingsButton,SIGNAL(enterSignal(int ,int)),settingsWidget,SLOT(display(int,int)));
connect(settingsButton,SIGNAL(leaveSignal()),this,SLOT(settingsWidgetDetection()));
connect(full_screenButton,SIGNAL(clicked(bool)),this,SLOT(on_full_screenButton_clicked()));
connect(full_screenButton, SIGNAL(clicked(bool)), this, SLOT(changeButtonSize()));
connect(this, SIGNAL(wheelMoving(int, int)), volumeWidget, SLOT(display(int, int)));
}
void BottomBar::on_playSlider_valueChanged(int val)
{
if(val/60>=10&&val%60>=10)
{
currentPos->setText(QString::number(val/60) + ":" + QString::number(val%60));
}
else if (val/60<10&&val%60>=10)
{
currentPos->setText("0" + QString::number(val/60) + ":" + QString::number(val%60));
}
else if (val/60>=10&&val%60<10)
{
currentPos->setText(QString::number(val/60) + ":" + "0" + QString::number(val%60));
}
else
{
currentPos->setText("0" + QString::number(val/60) + ":" + "0" + QString::number(val%60));
}
}
void BottomBar::on_pauseButton_clicked()
{
}
void BottomBar::on_volumeButton_clicked()//点击按钮实现静音与恢复音量
{
if(volumeSlider->value() == 0)
{
volume = 10;
volumeSlider->setValue(10);
volumeButton->setStyleSheet("QPushButton{ border-image: url(:/image/image/bottomBar/volume.png); }");
volumeButton->setToolTip(QStringLiteral("静音"));
}
else
{
volume = 0;
volumeButton->setStyleSheet("QPushButton{ border-image: url(:/image/image/bottomBar/mute.png); }");
volumeButton->setToolTip(QStringLiteral("恢复音量"));
}
emit volumeSlider->valueChanged(volume);
}
void BottomBar::on_volumeSlider_valueChanged(int vol)//拖拽改变音量时用tooltip显示当前音量
{
QToolTip::showText(QCursor::pos(), "音量:" + QString::number(vol), this);
if (vol == 0)
{
volumeButton->setStyleSheet("QPushButton{ border-image: url(:/image/image/bottomBar/mute.png); }");
}
else
{
volumeButton->setStyleSheet("QPushButton{ border-image: url(:/image/image/bottomBar/volume.png); }");
}
}
void BottomBar::on_switchModeButton_clicked()//点击切换音乐/视频模式
{
if(volumeSlider->orientation()==Qt::Horizontal)
{
setFixedHeight(70);
definitionButton->show();
settingsButton->show();
full_screenButton->show();
playModeButton->hide();
volumeSlider->setOrientation(Qt::Vertical);
volumeSlider->setFixedSize(20,50);
totalTime->setText("/04:00");//test
BmBottomLayout->removeWidget(switchModeButton);
BmBottomLayout->removeWidget(playSlider);
BmBottomLayout->removeWidget(volumeButton);
BottomLayout->removeItem(BmBottomLayout);
BottomLayout->addWidget(playSlider);
BottomLayout->addLayout(BmBottomLayout);
BmBottomLayout->addWidget(space);
BmBottomLayout->addWidget(volumeButton);
BmBottomLayout->addWidget(definitionButton);
BmBottomLayout->addWidget(settingsButton);
BmBottomLayout->addWidget(switchModeButton);
BmBottomLayout->addWidget(full_screenButton);
volumeLayout->addWidget(volumeSlider);
connect(volumeButton,SIGNAL(enterSignal(int ,int)),volumeWidget,SLOT(display(int,int)));
}
else if (volumeSlider->orientation()==Qt::Vertical)
{
setFixedHeight(50);
playModeButton->show();
definitionButton->hide();
settingsButton->hide();
full_screenButton->hide();
volumeSlider->setOrientation(Qt::Horizontal);
volumeSlider->setFixedSize(60,20);
totalTime->setText("04:00");//test
BottomLayout->removeWidget(playSlider);
BmBottomLayout->removeWidget(switchModeButton);
BmBottomLayout->removeWidget(volumeButton);
BmBottomLayout->removeWidget(space);
BmBottomLayout->removeWidget(totalTime);
BmBottomLayout->addWidget(playSlider);
BmBottomLayout->addWidget(totalTime);
BmBottomLayout->addWidget(volumeButton);
BmBottomLayout->addWidget(volumeSlider);
BmBottomLayout->addWidget(playModeButton);
BmBottomLayout->addWidget(switchModeButton);
disconnect(volumeButton,SIGNAL(enterSignal(int ,int)),volumeWidget,SLOT(display(int,int)));
}
else
{
}
}
void BottomBar::volumeWidgetDetection()
{
isatWidget(volumeWidget);
}
void BottomBar::definitionWidgetDetection()
{
isatWidget(definitionWidget);
}
void BottomBar::settingsWidgetDetection()
{
isatWidget(settingsWidget);
}
void BottomBar::on_full_screenButton_clicked()
{
emit full_screenButton_clicked();
volumeWidget->hide();
}
void BottomBar::wheelMoved(QWheelEvent *event)//滚轮改变音量
{
if (volumeSlider->orientation() == Qt::Vertical)
{
emit wheelMoving(volumeButton->x(), volumeButton->y());
}
else
{
}
int max = volumeSlider->maximum();
int min = volumeSlider->minimum();
int value = volumeSlider->value();
int change;
if ((max - min) <= 10)
{
change = 1;
}
else if ((max - min) <= 100)
{
change = 3;
}
else
{
change = 5;
}
//滚轮向上滚动增加vlaue
if (event->delta() >= 120)
{
value = volumeSlider->value() + change;
if (value > max)
value = max;
volumeSlider->setValue(value);
}
//滚轮向下滚动减少vlaue
else if (event->delta() <= -120)
{
value = volumeSlider->value() - change;
if (value < min)
value = min;
volumeSlider->setValue(value);
}
else
{
}
}
void BottomBar::isatWidget(QWidget *suspensionindow)
{
if(this->window()->childAt(QPoint(QCursor::pos().x()-this->window()->x(),QCursor::pos().y()-this->window()->y()))==suspensionindow)
{
}
else
{
suspensionindow->hide();
}
}
void BottomBar::changeButtonSize()
{
if (this->window()->isFullScreen())
{
volumeButton->setFixedSize(40, 40);
volumeSlider->setFixedSize(30, 80);
volumeWidget->setGeometry(0, 0, 40, 90);
playModeButton->setFixedSize(40, 40);
switchModeButton->setFixedSize(40, 40);
definitionButton->setFixedSize(40, 40);
settingsButton->setFixedSize(40, 40);
full_screenButton->setFixedSize(40, 40);
}
else
{
volumeButton->setFixedSize(30, 30);
volumeSlider->setFixedSize(20, 60);
volumeWidget->setGeometry(0, 0, 30, 80);
playModeButton->setFixedSize(30, 30);
switchModeButton->setFixedSize(30, 30);
definitionButton->setFixedSize(30, 30);
settingsButton->setFixedSize(30, 30);
full_screenButton->setFixedSize(30, 30);
}
}
void BottomBar::changeVolume(int vol)//改变音量
{
if (vol == volumeSlider->value())
{
}
else
{
volumeSlider->setValue(vol);
}
}
void BottomBar::hideVolumeWidget()
{
volumeWidget->hide();
}
void BottomBar::volumeSliderValueAdd()
{
volumeSlider->setValue(volumeSlider->value()+5);
}
void BottomBar::volumeSliderValueSub()
{
volumeSlider->setValue(volumeSlider->value()-5);
}
/**
* @method BottomBar::connectSettingAndBottom
* @brief 连接设置界面
* @author 涂晴昊
* @date 2019-08-31
*/
void BottomBar::connectSettingAndBottom(SettingWindow *settingWindow)
{
connect(settingWindow,SIGNAL(sigActionShortcut(QString)),//换暂停播放快捷键
this,SLOT(changeActionShortcut(QString)));
connect(settingWindow,SIGNAL(sigLastShortcut(QString)),//换上一首快捷键
this,SLOT(changeLastShortcut(QString)));
connect(settingWindow,SIGNAL(sigNextShortcut(QString)),//换下一首快捷键
this,SLOT(changeNextShortcut(QString)));
connect(settingWindow,SIGNAL(sigLouderShortcut(QString)),//换音量增快捷键
this,SLOT(changeLouderShortcut(QString)));
connect(settingWindow,SIGNAL(sigLowerShortcut(QString)),//换音量减快捷键
this,SLOT(changeLowerShortcut(QString)));
connect(settingWindow,SIGNAL(sigVolumeOnOffShortcut(QString)),//换静音复音快捷键
this,SLOT(changeVolumeOnOffShortcut(QString)));
connect(settingWindow,SIGNAL(sigSpeedChange(int)),//设置界面修改主界面倍速
this,SLOT(changeMultiplyingPower(int)));
connect(settingWindow,SIGNAL(sigDefinitionChange(int)),//设置界面修改主界面清晰度
this,SLOT(changeDefinition(int)));
connect(p360DefinitionButton,SIGNAL(clicked()),//主界面->设置界面普通清晰度
settingWindow,SLOT(lv1DefinitionChange()));
connect(p480DefinitionButton,SIGNAL(clicked()),//主界面->设置界面清晰清晰度
settingWindow,SLOT(lv2DefinitionChange()));
connect(p720DefinitionButton,SIGNAL(clicked()),//主界面->设置界面高清清晰度
settingWindow,SLOT(lv3DefinitionChange()));
connect(autoDefinitionButton,SIGNAL(clicked()),//主界面->设置界面自动清晰度
settingWindow,SLOT(lv1DefinitionChange()));
connect(this->playSpeedSlider,SIGNAL(valueChanged(int)),//主界面修改设置界面倍速
settingWindow,SLOT(speedChange(int)));
}
/**
* @method BottomBar::changeActionShortcut
* @brief 暂停播放快捷键修改
* @param QSTRING
* @return VOID
* @author 涂晴昊
* @date 2019-08-29
*/
void BottomBar::changeActionShortcut(QString str)
{
pauseButton->setShortcut(QKeySequence(str.toLatin1().data()));
}
/**
* @method BottomBar::changeLastShortcut
* @brief 上一首快捷键修改
* @param QSTRING
* @return VOID
* @author 涂晴昊
* @date 2019-08-29
*/
void BottomBar::changeLastShortcut(QString str)
{
lastButton->setShortcut(QKeySequence(str.toLatin1().data()));
}
/**
* @method BottomBar::changeNextShortcut
* @brief 下一首快捷键修改
* @param QSTRING
* @return VOID
* @author 涂晴昊
* @date 2019-08-29
*/
void BottomBar::changeNextShortcut(QString str)
{
nextButton->setShortcut(QKeySequence(str.toLatin1().data()));
}
/**
* @method BottomBar::changeVolumeOnOffShortcut
* @brief 静音复音快捷键修改
* @param QSTRING
* @return VOID
* @author 涂晴昊
* @date 2019-09-05
*/
void BottomBar::changeVolumeOnOffShortcut(QString str)
{
volumeButton->setShortcut(QKeySequence(str.toLatin1().data()));
}
/**
* @method BottomBar::changeMultiplyingPower
* @brief 改变主界面播放倍速
* @param INT
* @return VOID
* @author 涂晴昊
* @date 2019-09-04
*/
void BottomBar::changeMultiplyingPower(int mul)
{
multiplyingPower=mul;
playSpeedSlider->setValue(mul-1);
}
/**
* @method BottomBar::changeDefinition
* @brief 改变主界面清晰度
* @param INT
* @return VOID
* @author 涂晴昊
* @date 2019-09-05
*/
void BottomBar::changeDefinition(int d)
{
if(d==1)
p360DefinitionButton->click();
else if(d==2)
p480DefinitionButton->click();
else
p720DefinitionButton->click();
}
| [
"[email protected]"
] | |
dc4c55d53b9c21ae467bce710a93a7f95a2ec467 | 3966bdaa82deff3f5007ce8e5ca0c7b81fbc3e81 | /yukicoder/41.cpp | 845c4e73ac093543b505895a7189482d52f888ce | [] | no_license | sogapalag/contest | be955b61af67f1c104862e10ed51da9cea596016 | c1a2a8268d269c559d937148e7c7fa8c236a61ad | refs/heads/master | 2023-03-18T04:51:39.882314 | 2021-03-08T00:16:04 | 2021-03-08T00:16:04 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 739 | cpp | #include <algorithm>
#include <bitset>
#include <cassert>
#include <deque>
#include <functional>
#include <iostream>
#include <string>
#include <vector>
#define REP(i,s,n) for(int i=(int)(s);i<(int)(n);i++)
using namespace std;
typedef long long int ll;
typedef vector<int> VI;
typedef pair<int, int> PI;
const double EPS=1e-9;
const ll mod = 1e9 + 9;
const int N = 10, M = 100000;
ll dp[N][M];
int main(void){
int t;
cin >> t;
REP(j, 0, M) {
dp[0][j] = 1;
}
REP (i, 1, N) {
REP(j, 0, M) {
ll s = 0;
if (j >= i) {
s += dp[i][j - i];
}
s += dp[i - 1][j];
s %= mod;
dp[i][j] = s;
}
}
REP (trial, 0, t) {
ll m;
cin >> m;
cout << dp[9][m / 111111] << endl;
}
}
| [
"[email protected]"
] | |
07ed718475a8fcccce951789588fdafc403e0c2b | 46d4712c82816290417d611a75b604d51b046ecc | /Samples/Win7Samples/multimedia/wia/getimage/DataCallback.h | 0f62afc40dfa896c2b07bf50a3841f39577a6805 | [
"MIT"
] | permissive | ennoherr/Windows-classic-samples | 00edd65e4808c21ca73def0a9bb2af9fa78b4f77 | a26f029a1385c7bea1c500b7f182d41fb6bcf571 | refs/heads/master | 2022-12-09T20:11:56.456977 | 2022-12-04T16:46:55 | 2022-12-04T16:46:55 | 156,835,248 | 1 | 0 | NOASSERTION | 2022-12-04T16:46:55 | 2018-11-09T08:50:41 | null | UTF-8 | C++ | false | false | 2,728 | h | /*++
Copyright (c) Microsoft Corporation. All rights reserved.
--*/
#ifndef __DATACALLBACK__
#define __DATACALLBACK__
#include "WiaWrap.h"
namespace WiaWrap
{
//////////////////////////////////////////////////////////////////////////
//
// CDataCallback
//
/*++
CDataCallback implements a WIA data callback object that stores the
transferred data in an array of stream objects.
Methods
CDataCallback
Initializes the object
BandedDataCallback
This method is called periodically during data transfers. It can be
called for one of these reasons;
IT_MSG_DATA_HEADER: The method tries to allocate memory for the
image if the size is given in the header
IT_MSG_DATA: The method adjusts the stream size and copies the new
data to the stream.
case IT_MSG_STATUS: The method invoke the progress callback function.
IT_MSG_TERMINATION or IT_MSG_NEW_PAGE: For BMP images, calculates the
image height if it is not given in the image header, fills in the
BITMAPFILEHEADER and stores this stream in the successfully
transferred images array
ReAllocBuffer
Increases the size of the current stream object, or creates a
new stream object if this is the first call.
CopyToBuffer
Copies new data to the current stream.
StoreBuffer
Stores the current stream in the array of successfully transferred
images.
--*/
class CDataCallback : public IWiaDataCallback
{
public:
CDataCallback(
PFNPROGRESSCALLBACK pfnProgressCallback,
PVOID pProgressCallbackParam,
LONG *plCount,
IStream ***pppStream
);
// IUnknown interface
STDMETHOD(QueryInterface)(REFIID iid, LPVOID *ppvObj);
STDMETHOD_(ULONG, AddRef)();
STDMETHOD_(ULONG, Release)();
// IWiaDataCallback interface
STDMETHOD(BandedDataCallback) (
LONG lReason,
LONG lStatus,
LONG lPercentComplete,
LONG lOffset,
LONG lLength,
LONG lReserved,
LONG lResLength,
PBYTE pbBuffer
);
// CDataCallback methods
private:
HRESULT ReAllocBuffer(ULONG nBufferSize);
HRESULT CopyToBuffer(ULONG nOffset, LPCVOID pBuffer, ULONG nSize);
HRESULT StoreBuffer();
private:
LONG m_cRef;
BOOL m_bBMP;
LONG m_nHeaderSize;
LONG m_nDataSize;
CComPtr<IStream> m_pStream;
PFNPROGRESSCALLBACK m_pfnProgressCallback;
PVOID m_pProgressCallbackParam;
LONG *m_plCount;
IStream ***m_pppStream;
};
}; // namespace WiaWrap
#endif //__DATACALLBACK__
| [
"[email protected]"
] | |
cebedc33347194ea0ed6d9fbbba6badcbddf93c8 | 6b40e9dccf2edc767c44df3acd9b626fcd586b4d | /NT/inetsrv/query/admin/propsht.cxx | 95c32c27be060881b9aee2de034ba15a83dcf5d2 | [] | no_license | jjzhang166/WinNT5_src_20201004 | 712894fcf94fb82c49e5cd09d719da00740e0436 | b2db264153b80fbb91ef5fc9f57b387e223dbfc2 | refs/heads/Win2K3 | 2023-08-12T01:31:59.670176 | 2021-10-14T15:14:37 | 2021-10-14T15:14:37 | 586,134,273 | 1 | 0 | null | 2023-01-07T03:47:45 | 2023-01-07T03:47:44 | null | UTF-8 | C++ | false | false | 72,618 | cxx | //+-------------------------------------------------------------------------
//
// Microsoft Windows
// Copyright (C) Microsoft Corporation, 1996 - 2000.
//
// File: Propsht.cxx
//
// Contents: Property sheets for for CI snapin.
//
// History: 26-Nov-1996 KyleP Created
//
//--------------------------------------------------------------------------
#include <pch.cxx>
#pragma hdrstop
#include <cimbmgr.hxx>
#include <strres.hxx>
#include <ciares.h>
#include <propsht.hxx>
#include <catalog.hxx>
#include <prop.hxx>
#include <strings.hxx>
//
// Local prototypes
//
void InitVTList( HWND hwndCombo );
void InitVSList( HWND hwndComboVS, HWND hwndComboNNTP, CCatalog const & cat,
ULONG & cVServers, ULONG & cNNTPServers );
void InitStorageLevelList( HWND hwndCombo );
void DisplayError( HWND hwnd, CException & e );
BOOL GetDlgItemXArrayText( HWND hwndDlg, USHORT idCtrl, XArray<WCHAR> & xawcText );
DWORD VSToIndex( HWND hwndDlg, DWORD dwItem, ULONG ulVS, BOOL fTrack );
UINT DBTypeToVT(UINT uidbt);
CIndexSrvPropertySheet0::CIndexSrvPropertySheet0( HINSTANCE hInstance,
LONG_PTR hMmcNotify,
CCatalogs * pCats )
: _pCats( pCats ),
_fFirstActive( TRUE ),
_hMmcNotify( hMmcNotify )
{
_PropSheet.dwSize = sizeof( *this );
_PropSheet.dwFlags = PSP_USETITLE;
_PropSheet.hInstance = hInstance;
_PropSheet.pszTemplate = MAKEINTRESOURCE(IDP_IS_PAGE0);
_PropSheet.pszTitle = MAKEINTRESOURCE(IDP_IS_PAGE0_TITLE);
_PropSheet.pfnDlgProc = CIndexSrvPropertySheet0::DlgProc;
_PropSheet.lParam = (LPARAM)this;
_hPropSheet = CreatePropertySheetPage( &_PropSheet );
}
CIndexSrvPropertySheet0::~CIndexSrvPropertySheet0()
{
}
INT_PTR APIENTRY CIndexSrvPropertySheet0::DlgProc( HWND hwndDlg,
UINT message,
WPARAM wParam,
LPARAM lParam )
{
BOOL fRet = FALSE;
TRY
{
switch ( message )
{
case WM_INITDIALOG:
{
ciaDebugOut(( DEB_ITRACE, "CIndexSrvPropertySheet0::DlgProc -- WM_INITDIALOG\n" ));
LONG_PTR lthis = ((CIndexSrvPropertySheet0 *)lParam)->_PropSheet.lParam;
CIndexSrvPropertySheet0 * pthis = (CIndexSrvPropertySheet0 *)lthis;
SetWindowLongPtr( hwndDlg, DWLP_USER, lthis );
//
// Default to local machine.
//
CheckRadioButton( hwndDlg,
IDDI_LOCAL_COMPUTER,
IDDI_REMOTE_COMPUTER,
IDDI_LOCAL_COMPUTER );
EnableWindow( GetDlgItem( hwndDlg, IDDI_COMPNAME ), FALSE );
fRet = TRUE;
break;
}
case WM_COMMAND:
{
switch ( LOWORD( wParam ) )
{
case IDDI_LOCAL_COMPUTER:
{
if ( BN_CLICKED == HIWORD(wParam) )
{
EnableWindow( GetDlgItem( hwndDlg, IDDI_COMPNAME ), FALSE );
PropSheet_SetWizButtons( GetParent(hwndDlg), PSWIZB_FINISH );
fRet = TRUE;
}
break;
}
case IDDI_REMOTE_COMPUTER:
{
if ( BN_CLICKED == HIWORD(wParam) )
{
EnableWindow( GetDlgItem( hwndDlg, IDDI_COMPNAME ), TRUE );
//
// If we have a string, then enable finish button.
//
XArray<WCHAR> xawcTemp;
if ( GetDlgItemXArrayText( hwndDlg, IDDI_COMPNAME, xawcTemp ) &&
xawcTemp.Count() > 0 )
{
PropSheet_SetWizButtons( GetParent(hwndDlg), PSWIZB_FINISH );
}
else
{
PropSheet_SetWizButtons( GetParent(hwndDlg), PSWIZB_DISABLEDFINISH );
}
fRet = TRUE;
}
break;
}
case IDDI_COMPNAME:
{
if ( EN_CHANGE == HIWORD(wParam) )
{
//
// If we have a string, then enable finish button.
//
XArray<WCHAR> xawcTemp;
if ( GetDlgItemXArrayText( hwndDlg, IDDI_COMPNAME, xawcTemp ) &&
xawcTemp.Count() > 0 )
{
PropSheet_SetWizButtons( GetParent(hwndDlg), PSWIZB_FINISH );
}
else
{
PropSheet_SetWizButtons( GetParent(hwndDlg), PSWIZB_DISABLEDFINISH );
}
fRet = TRUE;
}
break;
}
/* Help is not being used...
case IDHELP:
{
DisplayHelp( hwndDlg, HIDD_CONNECT_TO_COMPUTER );
break;
}
*/
} // switch
break;
}
case WM_HELP:
{
HELPINFO *phi = (HELPINFO *) lParam;
ciaDebugOut(( DEB_ITRACE, "CIndexSrvPropertySheet0 WM_HELP contexttype: '%s', ctlid: %d, contextid: %d\n",
phi->iContextType == HELPINFO_MENUITEM ? "menu" : "window",
phi->iCtrlId, phi->dwContextId ));
if ( HELPINFO_WINDOW == phi->iContextType )
{
switch ( phi->iCtrlId )
{
case IDDI_STATIC:
break;
default :
DisplayPopupHelp((HWND)((LPHELPINFO) lParam)->hItemHandle, HELP_WM_HELP);
break;
}
}
break;
}
case WM_CONTEXTMENU:
{
DisplayPopupHelp((HWND)wParam, HELP_CONTEXTMENU);
break;
}
case WM_NOTIFY:
{
CIndexSrvPropertySheet0 * pthis = (CIndexSrvPropertySheet0 *)GetWindowLongPtr( hwndDlg, DWLP_USER );
switch ( ((LPNMHDR) lParam)->code )
{
case PSN_KILLACTIVE:
{
// Allow loss of activation
SetWindowLongPtr( hwndDlg, DWLP_MSGRESULT, FALSE );
fRet = TRUE;
break;
}
case PSN_SETACTIVE:
{
if ( pthis->_fFirstActive )
{
PropSheet_SetWizButtons( GetParent(hwndDlg), PSWIZB_FINISH );
pthis->_fFirstActive = FALSE;
}
else
{
// Go to next page
SetWindowLongPtr( hwndDlg, DWLP_MSGRESULT, -1 );
}
fRet = TRUE;
break;
}
case PSN_WIZBACK:
{
// Allow previous page
SetWindowLongPtr( hwndDlg, DWLP_MSGRESULT, PSNRET_NOERROR );
fRet = TRUE;
break;
}
case PSN_WIZNEXT:
{
// Allow next page
SetWindowLongPtr( hwndDlg, DWLP_MSGRESULT, PSNRET_NOERROR );
fRet = TRUE;
break;
}
case PSN_WIZFINISH:
{
TRY
{
XArray<WCHAR> xawcCompName;
if ( IsDlgButtonChecked( hwndDlg, IDDI_LOCAL_COMPUTER ) )
pthis->_pCats->SetMachine( L"." );
else
{
if ( GetDlgItemXArrayText( hwndDlg, IDDI_COMPNAME, xawcCompName ) )
{
pthis->_pCats->SetMachine( xawcCompName.GetPointer() );
}
}
MMCPropertyChangeNotify( pthis->_hMmcNotify, 0 );
fRet = TRUE;
}
CATCH( CException, e )
{
// The only error caught here is a result of an invalid
// machine name.
Win4Assert(e.GetErrorCode() == E_INVALIDARG);
MessageBox( hwndDlg,
STRINGRESOURCE( srInvalidComputerName ),
STRINGRESOURCE( srIndexServerCmpManage ),
MB_OK | MB_ICONINFORMATION );
}
END_CATCH
break;
}
} // switch
break;
}
case WM_DESTROY:
{
CIndexSrvPropertySheet0 * pthis = (CIndexSrvPropertySheet0 *)GetWindowLongPtr( hwndDlg, DWLP_USER );
MMCFreeNotifyHandle( pthis->_hMmcNotify );
delete pthis;
fRet = TRUE;
break;
}
} // switch
}
CATCH( CException, e )
{
ciaDebugOut(( DEB_ERROR, "CIndexSrvPropertySheet0: Caught 0x%x\n", e.GetErrorCode() ));
fRet = FALSE;
}
END_CATCH
return fRet;
}
CIndexSrvPropertySheet1::CIndexSrvPropertySheet1( HINSTANCE hInstance,
LONG_PTR hMmcNotify,
CCatalog * pCat )
: _pCat( pCat ),
_pCats( 0 ),
_hMmcNotify( hMmcNotify )
{
_PropSheet.dwSize = sizeof( *this );
_PropSheet.dwFlags = PSP_USETITLE;
_PropSheet.hInstance = hInstance;
_PropSheet.pszTemplate = MAKEINTRESOURCE(IDP_IS_PAGE1);
_PropSheet.pszTitle = MAKEINTRESOURCE(IDP_IS_PAGE1_TITLE);
_PropSheet.pfnDlgProc = CIndexSrvPropertySheet1::DlgProc;
_PropSheet.lParam = (LPARAM)this;
_hPropSheet = CreatePropertySheetPage( &_PropSheet );
}
CIndexSrvPropertySheet1::CIndexSrvPropertySheet1( HINSTANCE hInstance,
LONG_PTR hMmcNotify,
CCatalogs * pCats )
: _pCat( 0 ),
_pCats( pCats ),
_hMmcNotify( hMmcNotify )
{
_PropSheet.dwSize = sizeof( *this );
_PropSheet.dwFlags = PSP_USETITLE;
_PropSheet.hInstance = hInstance;
_PropSheet.pszTemplate = MAKEINTRESOURCE(IDP_IS_PAGE1);
_PropSheet.pszTitle = MAKEINTRESOURCE(IDP_IS_PAGE1_TITLE);
_PropSheet.pfnDlgProc = CIndexSrvPropertySheet1::DlgProc;
_PropSheet.lParam = (LPARAM)this;
_hPropSheet = CreatePropertySheetPage( &_PropSheet );
}
CIndexSrvPropertySheet1::~CIndexSrvPropertySheet1()
{
}
INT_PTR APIENTRY CIndexSrvPropertySheet1::DlgProc( HWND hwndDlg,
UINT message,
WPARAM wParam,
LPARAM lParam )
{
BOOL fRet = FALSE;
TRY
{
switch ( message )
{
case WM_HELP:
{
HELPINFO *phi = (HELPINFO *) lParam;
ciaDebugOut(( DEB_ITRACE, "CIndexSrvPropertySheet1 WM_HELP contexttype: '%s', ctlid: %d, contextid: %d\n",
phi->iContextType == HELPINFO_MENUITEM ? "menu" : "window",
phi->iCtrlId, phi->dwContextId ));
if ( HELPINFO_WINDOW == phi->iContextType )
{
switch ( phi->iCtrlId )
{
case IDDI_STATIC:
break;
default :
DisplayPopupHelp((HWND)((LPHELPINFO) lParam)->hItemHandle, HELP_WM_HELP);
break;
}
}
break;
}
case WM_CONTEXTMENU:
{
DisplayPopupHelp((HWND)wParam, HELP_CONTEXTMENU);
break;
}
case WM_INITDIALOG:
{
ciaDebugOut(( DEB_ITRACE, "CIndexSrvPropertySheet1::DlgProc -- WM_INITDIALOG\n" ));
LONG_PTR lthis = ((CIndexSrvPropertySheet1 *)lParam)->_PropSheet.lParam;
CIndexSrvPropertySheet1 * pthis = (CIndexSrvPropertySheet1 *)lthis;
SetWindowLongPtr( hwndDlg, DWLP_USER, lthis );
BOOL fUnknown;
BOOL fGenerateCharacterization;
ULONG ccCharacterization;
if ( pthis->IsTrackingCatalog() )
{
pthis->_pCat->GetGeneration( fUnknown, fGenerateCharacterization, ccCharacterization );
// Look in the registry for Group1 params. If at least one of them is listed
// we should uncheck the "Inherit" checkbox. Otherwise
// (if none of them is listed), we should check the box.
SendDlgItemMessage( hwndDlg,
IDDI_INHERIT1,
BM_SETCHECK,
pthis->_pCat->DoGroup1SettingsExist() ? BST_UNCHECKED : BST_CHECKED,
0 );
// If at least one setting exists, add the others in the group.
// We don't want to have an incomplete set.
if (pthis->_pCat->DoGroup1SettingsExist())
pthis->_pCat->FillGroup1Settings();
}
else
{
// Hide the "Inherit" checkbox because it is not applicable here
ShowWindow(GetDlgItem(hwndDlg, IDDI_INHERIT1), SW_HIDE);
pthis->_pCats->GetGeneration( fUnknown, fGenerateCharacterization, ccCharacterization );
}
SendDlgItemMessage( hwndDlg,
IDDI_FILTER_UNKNOWN,
BM_SETCHECK,
fUnknown ? BST_CHECKED : BST_UNCHECKED,
0 );
SendDlgItemMessage( hwndDlg,
IDDI_CHARACTERIZATION,
BM_SETCHECK,
fGenerateCharacterization ? BST_CHECKED : BST_UNCHECKED,
0 );
WCHAR wcsSize[120];
_ultow( ccCharacterization, wcsSize, 10 );
SetDlgItemText( hwndDlg, IDDI_CHARACTERIZATION_SIZE, wcsSize );
SendDlgItemMessage( hwndDlg,
IDDI_SPIN_CHARACTERIZATION,
UDM_SETRANGE,
0,
(LPARAM) MAKELONG( 10000, 10) );
// If the generate characterization checkbox is unchecked, we should disable the
// characterization size controls
if (!fGenerateCharacterization)
{
EnableWindow(GetDlgItem(hwndDlg, IDDI_CHARACTERIZATION_SIZE), FALSE);
EnableWindow(GetDlgItem(hwndDlg, IDDI_SPIN_CHARACTERIZATION), FALSE);
EnableWindow(GetDlgItem(hwndDlg, IDDI_STATIC2), FALSE);
}
// If we are inheriting, we should disable the local setting.
if ( pthis->IsTrackingCatalog() && !pthis->_pCat->DoGroup1SettingsExist())
{
EnableWindow(GetDlgItem(hwndDlg, IDDI_FILTER_UNKNOWN), FALSE);
EnableWindow(GetDlgItem(hwndDlg, IDDI_CHARACTERIZATION), FALSE);
EnableWindow(GetDlgItem(hwndDlg, IDDI_CHARACTERIZATION_SIZE), FALSE);
EnableWindow(GetDlgItem(hwndDlg, IDDI_SPIN_CHARACTERIZATION), FALSE);
EnableWindow(GetDlgItem(hwndDlg, IDDI_STATIC2), FALSE);
}
fRet = TRUE;
break;
}
case WM_COMMAND:
{
BOOL fChanged = FALSE;
BOOL fCorrected = TRUE;
switch ( LOWORD( wParam ) )
{
case IDDI_CHARACTERIZATION:
if (BN_CLICKED == HIWORD(wParam))
{
BOOL fGenChar = ( BST_CHECKED == SendDlgItemMessage( hwndDlg,
IDDI_CHARACTERIZATION,
BM_GETCHECK, 0, 0 ) );
EnableWindow(GetDlgItem(hwndDlg, IDDI_CHARACTERIZATION_SIZE), fGenChar);
EnableWindow(GetDlgItem(hwndDlg, IDDI_SPIN_CHARACTERIZATION), fGenChar);
EnableWindow(GetDlgItem(hwndDlg, IDDI_STATIC2), fGenChar);
if( 0 != GetWindowLongPtr( hwndDlg, DWLP_USER ) )
{
fChanged = TRUE;
fRet = TRUE;
}
}
break;
case IDDI_FILTER_UNKNOWN:
{
if ( BN_CLICKED == HIWORD(wParam) )
fChanged = TRUE;
// Fall through
}
case IDDI_CHARACTERIZATION_SIZE:
{
if ( EN_KILLFOCUS == HIWORD(wParam) && LOWORD( wParam ) == IDDI_CHARACTERIZATION_SIZE )
{
fRet = TRUE;
ULONG ulVal = 10;
// Validate the number
XArray<WCHAR> xawcTemp;
if ( (LOWORD(wParam) == IDDI_CHARACTERIZATION_SIZE) &&
GetDlgItemXArrayText( hwndDlg, IDDI_CHARACTERIZATION_SIZE, xawcTemp ) &&
xawcTemp.Count() > 0 )
{
// verify that all characters are digits
ULONG ulLen = wcslen(xawcTemp.GetPointer());
// When correcting, let's do our best
ulVal = _wtoi(xawcTemp.GetPointer());
for (ULONG i = 0; i < ulLen; i++)
{
if (!iswdigit(xawcTemp[i]))
break;
}
if (i == ulLen)
{
// verify that the number is within range
ulVal = _wtoi(xawcTemp.GetPointer());
if (ulVal <= 10000 && ulVal >= 10)
{
fCorrected = FALSE;
}
else
ulVal = (ulVal < 10) ? 10 : 10000;
}
}
if (fCorrected)
{
WCHAR wszBuff[20]; // use this instead of a potentially empty xawcTemp
ciaDebugOut((DEB_ITRACE, "%ws is NOT a valid number\n", xawcTemp.GetPointer()));
MessageBeep(MB_ICONHAND);
SetWindowText((HWND)lParam, _itow(ulVal, wszBuff, 10));
SendMessage((HWND)lParam, EM_SETSEL, 0, -1);
}
}
else if ( EN_CHANGE == HIWORD(wParam) && ( 0 != GetWindowLongPtr( hwndDlg, DWLP_USER )) )
{
fChanged = TRUE;
fRet = TRUE;
}
break;
}
case IDDI_INHERIT1:
{
if ( EN_CHANGE == HIWORD(wParam) || BN_CLICKED == HIWORD(wParam) )
{
if ( 0 != GetWindowLongPtr( hwndDlg, DWLP_USER ) )
{
fChanged = TRUE;
fRet = TRUE;
// If the Inherit Settings button is checked, we should remove the registry entries from the catalog's
// settings so the values will be inherited from the service.
BOOL fInherit = ( BST_CHECKED == SendDlgItemMessage( hwndDlg, IDDI_INHERIT1, BM_GETCHECK, 0, 0 ) );
BOOL fUnknown = FALSE, fGenerateCharacterization = FALSE;
DWORD ccCharacterization = 0;
CIndexSrvPropertySheet1 * pthis = (CIndexSrvPropertySheet1 *)GetWindowLongPtr( hwndDlg, DWLP_USER );
if ( !pthis->IsTrackingCatalog() )
break;
if (fInherit)
{
Win4Assert(pthis->IsTrackingCatalog());
pthis->_pCat->GetParent().GetGeneration( fUnknown, fGenerateCharacterization, ccCharacterization );
}
else
{
pthis->_pCat->GetGeneration( fUnknown, fGenerateCharacterization, ccCharacterization );
// Enable so we can set controls
EnableWindow(GetDlgItem(hwndDlg, IDDI_FILTER_UNKNOWN), TRUE);
EnableWindow(GetDlgItem(hwndDlg, IDDI_CHARACTERIZATION), TRUE);
EnableWindow(GetDlgItem(hwndDlg, IDDI_CHARACTERIZATION_SIZE), TRUE);
EnableWindow(GetDlgItem(hwndDlg, IDDI_SPIN_CHARACTERIZATION), TRUE);
EnableWindow(GetDlgItem(hwndDlg, IDDI_STATIC2), TRUE);
}
SendDlgItemMessage( hwndDlg,
IDDI_FILTER_UNKNOWN,
BM_SETCHECK,
fUnknown ? BST_CHECKED : BST_UNCHECKED,
0 );
SendDlgItemMessage( hwndDlg,
IDDI_CHARACTERIZATION,
BM_SETCHECK,
fGenerateCharacterization ? BST_CHECKED : BST_UNCHECKED,
0 );
WCHAR wcsSize[12];
_ultow( ccCharacterization, wcsSize, 10 );
SetDlgItemText( hwndDlg, IDDI_CHARACTERIZATION_SIZE, wcsSize );
// Enable/Disable controls if we need to
EnableWindow(GetDlgItem(hwndDlg, IDDI_FILTER_UNKNOWN), !fInherit);
EnableWindow(GetDlgItem(hwndDlg, IDDI_CHARACTERIZATION), !fInherit);
EnableWindow(GetDlgItem(hwndDlg, IDDI_CHARACTERIZATION_SIZE), !fInherit);
EnableWindow(GetDlgItem(hwndDlg, IDDI_SPIN_CHARACTERIZATION), !fInherit);
EnableWindow(GetDlgItem(hwndDlg, IDDI_STATIC2), !fInherit);
}
}
}
} // switch
if ( fChanged )
PropSheet_Changed( GetParent(hwndDlg), hwndDlg );
break;
} // case
case WM_NOTIFY:
{
switch ( ((LPNMHDR) lParam)->code )
{
case PSN_APPLY:
{
TRY
{
CIndexSrvPropertySheet1 * pthis = (CIndexSrvPropertySheet1 *)GetWindowLongPtr( hwndDlg, DWLP_USER );
BOOL fUnknown = ( BST_CHECKED == SendDlgItemMessage( hwndDlg, IDDI_FILTER_UNKNOWN, BM_GETSTATE, 0, 0 ) );
BOOL fGenerateCharacterization = ( BST_CHECKED == SendDlgItemMessage( hwndDlg, IDDI_CHARACTERIZATION, BM_GETSTATE, 0, 0 ) );
WCHAR wcsSize[12];
GetDlgItemText( hwndDlg, IDDI_CHARACTERIZATION_SIZE, wcsSize, sizeof(wcsSize)/sizeof(WCHAR) );
ULONG ccCharacterization = wcstoul( wcsSize, 0, 10 );
if ( pthis->IsTrackingCatalog() )
{
// If the Inherit Settings button is checked, we should remove the registry entries from the catalog's
// settings so the values will be inherited from the service.
BOOL fInherit = ( BST_CHECKED == SendDlgItemMessage( hwndDlg, IDDI_INHERIT1, BM_GETSTATE, 0, 0 ) );
if (fInherit)
pthis->_pCat->DeleteGroup1Settings();
else
pthis->_pCat->SetGeneration( fUnknown, fGenerateCharacterization, ccCharacterization );
// Set the values and enable or disable the local controls as appropriate
pthis->_pCat->GetGeneration( fUnknown, fGenerateCharacterization, ccCharacterization );
SendDlgItemMessage( hwndDlg,
IDDI_FILTER_UNKNOWN,
BM_SETCHECK,
fUnknown ? BST_CHECKED : BST_UNCHECKED,
0 );
SendDlgItemMessage( hwndDlg,
IDDI_CHARACTERIZATION,
BM_SETCHECK,
fGenerateCharacterization ? BST_CHECKED : BST_UNCHECKED,
0 );
WCHAR wcsSize[12];
_ultow( ccCharacterization, wcsSize, 10 );
SetDlgItemText( hwndDlg, IDDI_CHARACTERIZATION_SIZE, wcsSize);
EnableWindow(GetDlgItem(hwndDlg, IDDI_FILTER_UNKNOWN), !fInherit);
EnableWindow(GetDlgItem(hwndDlg, IDDI_CHARACTERIZATION), !fInherit);
EnableWindow(GetDlgItem(hwndDlg, IDDI_CHARACTERIZATION_SIZE), !fInherit);
EnableWindow(GetDlgItem(hwndDlg, IDDI_SPIN_CHARACTERIZATION), !fInherit);
EnableWindow(GetDlgItem(hwndDlg, IDDI_STATIC2), !fInherit);
}
else
pthis->_pCats->SetGeneration( fUnknown, fGenerateCharacterization, ccCharacterization );
MMCPropertyChangeNotify( pthis->_hMmcNotify, 0 );
fRet = TRUE;
}
CATCH( CException, e )
{
DisplayError( hwndDlg, e );
}
END_CATCH
break;
}
} // switch
break;
}
case WM_DESTROY:
{
CIndexSrvPropertySheet1 * pthis = (CIndexSrvPropertySheet1 *)GetWindowLongPtr( hwndDlg, DWLP_USER );
//
// Only gets called on *one* property page!
//
// MMCFreeNotifyHandle( pthis->_hMmcNotify );
delete pthis;
fRet = TRUE;
break;
}
} // switch
}
CATCH( CException, e )
{
ciaDebugOut(( DEB_ERROR, "CIndexSrvPropertySheet1: Caught 0x%x\n", e.GetErrorCode() ));
fRet = FALSE;
}
END_CATCH
return fRet;
}
CCatalogBasicPropertySheet::CCatalogBasicPropertySheet( HINSTANCE hInstance,
LONG_PTR hMmcNotify,
CCatalog const * pCat )
: _pCat( pCat ),
_hMmcNotify( hMmcNotify )
{
_PropSheet.dwSize = sizeof( *this );
_PropSheet.dwFlags = PSP_USETITLE;
_PropSheet.hInstance = hInstance;
_PropSheet.pszTemplate = MAKEINTRESOURCE(IDP_CATALOG_PAGE1);
_PropSheet.pszTitle = MAKEINTRESOURCE(IDP_CATALOG_PAGE1_TITLE);
_PropSheet.pfnDlgProc = CCatalogBasicPropertySheet::DlgProc;
_PropSheet.lParam = (LPARAM)this;
_hPropSheet = CreatePropertySheetPage( &_PropSheet );
}
CCatalogBasicPropertySheet::~CCatalogBasicPropertySheet()
{
}
INT_PTR APIENTRY CCatalogBasicPropertySheet::DlgProc( HWND hwndDlg,
UINT message,
WPARAM wParam,
LPARAM lParam )
{
BOOL fRet = FALSE;
TRY
{
switch ( message )
{
case WM_HELP:
{
HELPINFO *phi = (HELPINFO *) lParam;
ciaDebugOut(( DEB_ITRACE,
"CCatalogBasicPropertySheet::DlgProc -- WM_HELP: wp 0x%x, lp 0x%x\n",
wParam, lParam ));
if ( HELPINFO_WINDOW == phi->iContextType )
{
switch ( phi->iCtrlId )
{
case IDDI_STATIC:
break;
default :
DisplayPopupHelp((HWND)((LPHELPINFO) lParam)->hItemHandle, HELP_WM_HELP);
break;
}
}
break;
}
case WM_CONTEXTMENU:
{
DisplayPopupHelp((HWND)wParam, HELP_CONTEXTMENU);
break;
}
case WM_INITDIALOG:
{
ciaDebugOut(( DEB_ITRACE, "CCatalogBasicPropertySheet::DlgProc -- WM_INITDIALOG\n" ));
LONG_PTR lthis = ((CCatalogBasicPropertySheet *)lParam)->_PropSheet.lParam;
SetWindowLongPtr( hwndDlg, DWLP_USER, lthis );
CCatalog const * pCat = ((CCatalogBasicPropertySheet *)lParam)->_pCat;
SetDlgItemText( hwndDlg, IDDI_CATNAME, pCat->GetCat( TRUE ) );
SetDlgItemText( hwndDlg, IDDI_SIZE, pCat->GetSize( TRUE ) );
SetDlgItemText( hwndDlg, IDDI_PATH, pCat->GetDrive( TRUE ) );
SetDlgItemText( hwndDlg, IDDI_PROPCACHE_SIZE, pCat->GetPropCacheSize( TRUE ) );
fRet = TRUE;
break;
}
case WM_DESTROY:
{
CCatalogBasicPropertySheet * pthis = (CCatalogBasicPropertySheet *)GetWindowLongPtr( hwndDlg, DWLP_USER );
//
// Only gets called on *one* property page!
//
// MMCFreeNotifyHandle( pthis->_hMmcNotify );
delete pthis;
fRet = TRUE;
break;
}
} // switch
}
CATCH( CException, e )
{
ciaDebugOut(( DEB_ERROR, "CCatalogBasicPropertySheet: Caught 0x%x\n", e.GetErrorCode() ));
fRet = FALSE;
}
END_CATCH
return fRet;
}
CIndexSrvPropertySheet2::CIndexSrvPropertySheet2( HINSTANCE hInstance,
LONG_PTR hMmcNotify,
CCatalog * pCat )
: _pCat( pCat ),
_pCats( 0 ),
_hMmcNotify( hMmcNotify ),
_fNNTPServer( FALSE ),
_fWebServer( FALSE )
{
_PropSheet.dwSize = sizeof( *this );
_PropSheet.dwFlags = PSP_USETITLE;
_PropSheet.hInstance = hInstance;
_PropSheet.pszTemplate = MAKEINTRESOURCE(IDP_CATALOG_PAGE2);
_PropSheet.pszTitle = MAKEINTRESOURCE(IDP_CATALOG_PAGE2_TITLE);
_PropSheet.pfnDlgProc = CIndexSrvPropertySheet2::DlgProc;
_PropSheet.lParam = (LPARAM)this;
_hPropSheet = CreatePropertySheetPage( &_PropSheet );
}
CIndexSrvPropertySheet2::CIndexSrvPropertySheet2( HINSTANCE hInstance,
LONG_PTR hMmcNotify,
CCatalogs * pCats )
: _pCat( 0 ),
_pCats( pCats ),
_hMmcNotify( hMmcNotify )
{
_PropSheet.dwSize = sizeof( *this );
_PropSheet.dwFlags = PSP_USETITLE;
_PropSheet.hInstance = hInstance;
_PropSheet.pszTemplate = MAKEINTRESOURCE(IDP_CATALOG_PAGE2);
_PropSheet.pszTitle = MAKEINTRESOURCE(IDP_CATALOG_PAGE2_TITLE);
_PropSheet.pfnDlgProc = CIndexSrvPropertySheet2::DlgProc;
_PropSheet.lParam = (LPARAM)this;
_hPropSheet = CreatePropertySheetPage( &_PropSheet );
}
CIndexSrvPropertySheet2::~CIndexSrvPropertySheet2()
{
}
INT_PTR APIENTRY CIndexSrvPropertySheet2::DlgProc( HWND hwndDlg,
UINT message,
WPARAM wParam,
LPARAM lParam )
{
BOOL fRet = FALSE;
TRY
{
switch ( message )
{
case WM_HELP:
{
HELPINFO *phi = (HELPINFO *) lParam;
ciaDebugOut(( DEB_ITRACE, "CIndexSrvPropertySheet2 WM_HELP contexttype: '%s', ctlid: %d, contextid: %d\n",
phi->iContextType == HELPINFO_MENUITEM ? "menu" : "window",
phi->iCtrlId, phi->dwContextId ));
if ( HELPINFO_WINDOW == phi->iContextType )
{
switch ( phi->iCtrlId )
{
case IDDI_STATIC:
break;
default :
DisplayPopupHelp((HWND)((LPHELPINFO) lParam)->hItemHandle, HELP_WM_HELP);
break;
}
}
break;
}
case WM_CONTEXTMENU:
{
DisplayPopupHelp((HWND)wParam, HELP_CONTEXTMENU);
break;
}
case WM_INITDIALOG:
{
ciaDebugOut(( DEB_ITRACE, "CIndexSrvPropertySheet2::DlgProc -- WM_INITDIALOG\n" ));
LONG_PTR lthis = ((CIndexSrvPropertySheet2 *)lParam)->_PropSheet.lParam;
CIndexSrvPropertySheet2 * pthis = (CIndexSrvPropertySheet2 *)lthis;
SetWindowLongPtr( hwndDlg, DWLP_USER, lthis );
BOOL fAutoAlias;
BOOL fVirtualRoots;
BOOL fNNTPRoots;
ULONG iVirtualServer;
ULONG iNNTPServer;
// It is important to initialize the counters here to guarantee that
// they will remain 0 if we don't get to invoke the enumerators that
// count the number of servers.
ULONG cVServers = 0, cNNTPServers = 0;
ShowWindow(GetDlgItem(hwndDlg, IDDI_VIRTUAL_SERVER), FALSE);
ShowWindow(GetDlgItem(hwndDlg, IDDI_NNTP_SERVER), FALSE);
ShowWindow(GetDlgItem(hwndDlg, IDDI_VSERVER_STATIC), FALSE);
ShowWindow(GetDlgItem(hwndDlg, IDDI_NNTP_STATIC), FALSE);
if ( 0 != pthis->_pCat )
{
if ( AreServersAvailable( *(pthis->_pCat) ) )
{
pthis->_pCat->GetWeb( fVirtualRoots,
fNNTPRoots,
iVirtualServer,
iNNTPServer );
InitVSList( GetDlgItem(hwndDlg, IDDI_VIRTUAL_SERVER),
GetDlgItem(hwndDlg, IDDI_NNTP_SERVER),
*(pthis->_pCat),
cVServers,
cNNTPServers );
}
pthis->_pCat->GetTracking( fAutoAlias );
// Look in the registry for Group2 params. If at least one of them is listed
// we should uncheck the "Inherit" checkbox. Otherwise
// (if none of them is listed), we should check the box.
SendDlgItemMessage( hwndDlg,
IDDI_INHERIT2,
BM_SETCHECK,
pthis->_pCat->DoGroup2SettingsExist() ? BST_UNCHECKED : BST_CHECKED,
0 );
// If all the settings don't exist, then delete the others in the group.
// We don't want to have part of the group inherited and part local.
if (pthis->_pCat->DoGroup2SettingsExist())
pthis->_pCat->FillGroup2Settings();
}
else
{
// Hide the "Inherit" checkbox because it is not applicable here
ShowWindow(GetDlgItem(hwndDlg, IDDI_INHERIT2), SW_HIDE);
pthis->_pCats->GetTracking( fAutoAlias );
}
if (cVServers)
{
ShowWindow(GetDlgItem(hwndDlg, IDDI_VIRTUAL_SERVER), TRUE);
ShowWindow(GetDlgItem(hwndDlg, IDDI_VSERVER_STATIC), TRUE);
pthis->_fWebServer = TRUE;
SendDlgItemMessage( hwndDlg,
IDDI_VIRTUAL_SERVER,
CB_SETCURSEL,
VSToIndex( hwndDlg, IDDI_VIRTUAL_SERVER,
iVirtualServer, fVirtualRoots ), 0 );
}
if (cNNTPServers)
{
ShowWindow(GetDlgItem(hwndDlg, IDDI_NNTP_SERVER), TRUE);
ShowWindow(GetDlgItem(hwndDlg, IDDI_NNTP_STATIC), TRUE);
pthis->_fNNTPServer = TRUE;
SendDlgItemMessage( hwndDlg,
IDDI_NNTP_SERVER,
CB_SETCURSEL,
VSToIndex( hwndDlg, IDDI_NNTP_SERVER,
iNNTPServer, fNNTPRoots ), 0 );
}
SendDlgItemMessage( hwndDlg,
IDDI_AUTO_ALIAS,
BM_SETCHECK,
fAutoAlias ? BST_CHECKED : BST_UNCHECKED,
0 );
// If we are inheriting, we should disable the local setting.
if ( 0 != pthis->_pCat && !pthis->_pCat->DoGroup2SettingsExist())
EnableWindow(GetDlgItem(hwndDlg, IDDI_AUTO_ALIAS), FALSE);
fRet = TRUE;
break;
}
case WM_COMMAND:
{
BOOL fChanged = FALSE;
switch ( LOWORD( wParam ) )
{
case IDDI_VIRTUAL_SERVER:
case IDDI_NNTP_SERVER:
{
if ( CBN_SELCHANGE == HIWORD(wParam) )
{
if ( 0 != GetWindowLongPtr( hwndDlg, DWLP_USER ) )
{
fChanged = TRUE;
fRet = TRUE;
}
}
break;
}
case IDDI_AUTO_ALIAS:
{
if ( EN_CHANGE == HIWORD(wParam) || BN_CLICKED == HIWORD(wParam) )
{
if ( 0 != GetWindowLongPtr( hwndDlg, DWLP_USER ) )
{
fChanged = TRUE;
fRet = TRUE;
}
}
break;
}
case IDDI_INHERIT2:
{
if ( EN_CHANGE == HIWORD(wParam) || BN_CLICKED == HIWORD(wParam) )
{
if ( 0 != GetWindowLongPtr( hwndDlg, DWLP_USER ) )
{
fChanged = TRUE;
fRet = TRUE;
BOOL fInherit = ( BST_CHECKED == SendDlgItemMessage( hwndDlg, IDDI_INHERIT2, BM_GETCHECK, 0, 0 ) );
BOOL fAutoAlias = FALSE;
CIndexSrvPropertySheet2 * pthis = (CIndexSrvPropertySheet2 *)GetWindowLongPtr( hwndDlg, DWLP_USER );
if (fInherit)
{
Win4Assert(pthis->IsTrackingCatalog());
pthis->_pCat->GetParent().GetTracking(fAutoAlias);
}
else
{
pthis->_pCat->GetTracking(fAutoAlias);
// Enable so we can set controls
EnableWindow(GetDlgItem(hwndDlg, IDDI_AUTO_ALIAS), TRUE);
}
SendDlgItemMessage( hwndDlg,
IDDI_AUTO_ALIAS,
BM_SETCHECK,
fAutoAlias ? BST_CHECKED : BST_UNCHECKED,
0 );
// Disable controls if we need to
if (fInherit)
EnableWindow(GetDlgItem(hwndDlg, IDDI_AUTO_ALIAS), FALSE);
}
}
}
} // switch
if ( fChanged )
PropSheet_Changed( GetParent(hwndDlg), hwndDlg );
break;
}
case WM_NOTIFY:
{
switch ( ((LPNMHDR) lParam)->code )
{
case PSN_APPLY:
{
TRY
{
CIndexSrvPropertySheet2 * pthis = (CIndexSrvPropertySheet2 *)GetWindowLongPtr( hwndDlg, DWLP_USER );
BOOL fAutoAlias = ( BST_CHECKED == SendDlgItemMessage( hwndDlg, IDDI_AUTO_ALIAS, BM_GETSTATE, 0, 0 ) );
if ( 0 != pthis->_pCat )
{
BOOL fVirtualRoots = FALSE;
ULONG iVirtualServer = 0;
if ( pthis->_fWebServer )
{
iVirtualServer = (ULONG)SendDlgItemMessage( hwndDlg, IDDI_VIRTUAL_SERVER, CB_GETCURSEL, 0, 0 );
fVirtualRoots = ( 0 != iVirtualServer );
iVirtualServer = (ULONG)SendDlgItemMessage( hwndDlg, IDDI_VIRTUAL_SERVER, CB_GETITEMDATA, iVirtualServer, 0 );
}
BOOL fNNTPRoots = FALSE;
ULONG iNNTPServer = 0;
if ( pthis->_fNNTPServer )
{
iNNTPServer = (ULONG)SendDlgItemMessage( hwndDlg, IDDI_NNTP_SERVER, CB_GETCURSEL, 0, 0 );
fNNTPRoots = ( 0 != iNNTPServer );
iNNTPServer = (ULONG)SendDlgItemMessage( hwndDlg, IDDI_NNTP_SERVER, CB_GETITEMDATA, iNNTPServer, 0 );
}
pthis->_pCat->SetWeb( fVirtualRoots, fNNTPRoots, iVirtualServer, iNNTPServer );
// If the Inherit Settings button is checked, we should remove the registry entries from the catalog's
// settings so the values will be inherited from the service.
BOOL fInherit = ( BST_CHECKED == SendDlgItemMessage( hwndDlg, IDDI_INHERIT2, BM_GETSTATE, 0, 0 ) );
if (fInherit)
pthis->_pCat->DeleteGroup2Settings();
else
pthis->_pCat->SetTracking( fAutoAlias );
// Set the current values and set state of the local controls
BOOL fAutoAlias;
pthis->_pCat->GetTracking( fAutoAlias );
SendDlgItemMessage( hwndDlg,
IDDI_AUTO_ALIAS,
BM_SETCHECK,
fAutoAlias ? BST_CHECKED : BST_UNCHECKED,
0 );
EnableWindow(GetDlgItem(hwndDlg, IDDI_AUTO_ALIAS), !fInherit);
}
else
pthis->_pCats->SetTracking( fAutoAlias );
MMCPropertyChangeNotify( pthis->_hMmcNotify, 0 );
fRet = TRUE;
}
CATCH( CException, e )
{
DisplayError( hwndDlg, e );
}
END_CATCH
break;
}
} // switch
break;
}
case WM_DESTROY:
{
CIndexSrvPropertySheet2 * pthis = (CIndexSrvPropertySheet2 *)GetWindowLongPtr( hwndDlg, DWLP_USER );
//
// Only gets called on *one* property page!
//
// MMCFreeNotifyHandle( pthis->_hMmcNotify );
delete pthis;
fRet = TRUE;
break;
}
} // switch
}
CATCH( CException, e )
{
ciaDebugOut(( DEB_ERROR, "CIndexSrvPropertySheet2: Caught 0x%x\n", e.GetErrorCode() ));
fRet = FALSE;
}
END_CATCH
return fRet;
}
CPropertyPropertySheet1::CPropertyPropertySheet1( HINSTANCE hInstance,
LONG_PTR hMmcNotify,
CCachedProperty * pProperty,
CCatalog * pCat )
: _pProperty( pProperty ),
_propNew( *pProperty ),
_hMmcNotify( hMmcNotify ),
_pCat( pCat )
{
_PropSheet.dwSize = sizeof( _PropSheet ) + sizeof( this );
_PropSheet.dwFlags = PSP_USETITLE;
_PropSheet.hInstance = hInstance;
_PropSheet.pszTemplate = MAKEINTRESOURCE(IDP_PROPERTY_PAGE1);
_PropSheet.pszTitle = MAKEINTRESOURCE(IDP_PROPERTY_PAGE1_TITLE);
_PropSheet.pfnDlgProc = CPropertyPropertySheet1::DlgProc;
_PropSheet.lParam = (LPARAM)this;
_hPropSheet = CreatePropertySheetPage( &_PropSheet );
}
CPropertyPropertySheet1::~CPropertyPropertySheet1()
{
}
INT_PTR APIENTRY CPropertyPropertySheet1::DlgProc( HWND hwndDlg,
UINT message,
WPARAM wParam,
LPARAM lParam )
{
BOOL fRet = FALSE;
TRY
{
switch ( message )
{
case WM_HELP:
{
HELPINFO *phi = (HELPINFO *) lParam;
ciaDebugOut(( DEB_ITRACE,
"CPropertyPropertySheet1 WM_HELP contexttype: '%s', ctlid: %d, contextid: %d\n",
phi->iContextType == HELPINFO_MENUITEM ? "menu" : "window",
phi->iCtrlId, phi->dwContextId ));
if ( HELPINFO_WINDOW == phi->iContextType )
{
switch ( phi->iCtrlId )
{
case IDDI_STATIC:
break;
default :
DisplayPopupHelp((HWND)((LPHELPINFO) lParam)->hItemHandle, HELP_WM_HELP);
break;
}
}
break;
}
case WM_CONTEXTMENU:
{
DisplayPopupHelp((HWND)wParam, HELP_CONTEXTMENU);
break;
}
case WM_INITDIALOG:
{
ciaDebugOut(( DEB_ITRACE, "CPropertyPropertySheet1::DlgProc -- WM_INITDIALOG\n" ));
LONG_PTR lthis = ((CPropertyPropertySheet1 *)lParam)->_PropSheet.lParam;
SetWindowLongPtr( hwndDlg, DWLP_USER, lthis );
CCachedProperty const & prop = ((CPropertyPropertySheet1 *)lthis)->_propNew;
SetDlgItemText( hwndDlg, IDDI_PROPSET, prop.GetPropSet() );
SetDlgItemText( hwndDlg, IDDI_PROPERTY, prop.GetProperty() );
SendDlgItemMessage( hwndDlg,
IDDI_SPIN_CACHEDSIZE,
UDM_SETRANGE,
0,
(LPARAM) MAKELONG( 500, 4) );
InitVTList( GetDlgItem(hwndDlg, IDDI_DATATYPE) );
InitStorageLevelList( GetDlgItem(hwndDlg, IDDI_STORAGELEVEL) );
if ( prop.IsCached() )
{
SendDlgItemMessage( hwndDlg, IDDI_CACHED, BM_SETCHECK, BST_CHECKED, 0 );
SendDlgItemMessage( hwndDlg, IDDI_DATATYPE, CB_SETCURSEL, aulTypeIndex[ prop.GetVT() & ~VT_VECTOR ], 0 );
// StoreLevel() is 0 for primary, 1 for secondary, which is the sequence in which we added them.
// So using StoreLevel() as in index will work fine!
SendDlgItemMessage( hwndDlg, IDDI_STORAGELEVEL, CB_SETCURSEL, prop.StoreLevel(), 0 );
SetDlgItemText( hwndDlg, IDDI_CACHEDSIZE, prop.GetAllocation() );
// Currently we do not allow the storage level to be changed after initial setting
EnableWindow( GetDlgItem( hwndDlg, IDDI_STORAGELEVEL), FALSE );
}
else
{
SendDlgItemMessage( hwndDlg, IDDI_CACHED, BM_SETCHECK, BST_UNCHECKED, 0 );
EnableWindow( GetDlgItem( hwndDlg, IDDI_DATATYPE ), FALSE );
EnableWindow( GetDlgItem( hwndDlg, IDDI_STORAGELEVEL), FALSE );
EnableWindow( GetDlgItem( hwndDlg, IDDI_CACHEDSIZE ), FALSE );
EnableWindow( GetDlgItem( hwndDlg, IDDI_SPIN_CACHEDSIZE ), FALSE );
EnableWindow( GetDlgItem( GetParent(hwndDlg), IDOK), FALSE );
}
// If properties cannot be modified, disable all controls
// Only cached properties can be resitant to modifications!
if (!prop.IsModifiable() && prop.IsCached())
{
EnableWindow( GetDlgItem( hwndDlg, IDDI_CACHED), FALSE );
EnableWindow( GetDlgItem( hwndDlg, IDDI_DATATYPE ), FALSE );
EnableWindow( GetDlgItem( hwndDlg, IDDI_STORAGELEVEL), FALSE );
EnableWindow( GetDlgItem( hwndDlg, IDDI_CACHEDSIZE ), FALSE );
EnableWindow( GetDlgItem( hwndDlg, IDDI_SPIN_CACHEDSIZE ), FALSE );
EnableWindow( GetDlgItem( GetParent(hwndDlg), IDOK), FALSE );
}
fRet = TRUE;
break;
}
case WM_COMMAND:
{
BOOL fChanged = FALSE;
BOOL fCorrected = TRUE;
switch ( LOWORD( wParam ) )
{
case IDDI_DATATYPE:
{
if ( CBN_CLOSEUP == HIWORD(wParam) )
{
CPropertyPropertySheet1 * pthis = (CPropertyPropertySheet1 *)GetWindowLongPtr( hwndDlg, DWLP_USER );
fChanged = pthis->Refresh( hwndDlg, TRUE );
if ( pthis->_propNew.IsFixed() )
{
SetDlgItemText( hwndDlg, IDDI_CACHEDSIZE, pthis->_propNew.GetAllocation() );
// Disable the size control
EnableWindow( GetDlgItem( hwndDlg, IDDI_CACHEDSIZE ), FALSE );
EnableWindow( GetDlgItem( hwndDlg, IDDI_SPIN_CACHEDSIZE ), FALSE );
}
else
{
SetDlgItemText( hwndDlg, IDDI_CACHEDSIZE, L"4" );
// Enable the size control. Variable props can be resized.
EnableWindow( GetDlgItem( hwndDlg, IDDI_CACHEDSIZE ), TRUE );
EnableWindow( GetDlgItem( hwndDlg, IDDI_SPIN_CACHEDSIZE ), TRUE );
}
fRet = TRUE;
}
break;
}
case IDDI_STORAGELEVEL:
{
CPropertyPropertySheet1 * pthis = (CPropertyPropertySheet1 *)GetWindowLongPtr( hwndDlg, DWLP_USER );
if ( CBN_CLOSEUP == HIWORD(wParam) )
{
fChanged = pthis->Refresh( hwndDlg, TRUE );
fRet = TRUE;
}
break;
}
case IDDI_CACHEDSIZE:
{
if ( EN_KILLFOCUS == HIWORD(wParam) )
{
fRet = TRUE;
ULONG ulVal = 4;
// Validate the number
XArray<WCHAR> xawcTemp;
if ( GetDlgItemXArrayText( hwndDlg, IDDI_CACHEDSIZE, xawcTemp ) &&
xawcTemp.Count() > 0 )
{
// verify that all characters are digits
ULONG ulLen = wcslen(xawcTemp.GetPointer());
// When correcting, let's do our best.
ulVal = _wtoi(xawcTemp.GetPointer());
for (ULONG i = 0; i < ulLen; i++)
{
if (!iswdigit(xawcTemp[i]))
break;
}
if (i == ulLen)
{
// verify that the number is within range
ulVal = _wtoi(xawcTemp.GetPointer());
ciaDebugOut((DEB_ERROR, "number is %d, string is %ws\n",
ulVal, xawcTemp.GetPointer()));
if (ulVal <= 500)
fCorrected = FALSE;
else if (ulVal > 500)
ulVal = 500;
}
}
// if we are dealing with a vble property, we should ensure that the
// size is at least 4 bytes
if (ulVal < 4)
{
CPropertyPropertySheet1 * pthis = (CPropertyPropertySheet1 *)GetWindowLongPtr( hwndDlg, DWLP_USER );
if ( 0 != pthis )
{
if (pthis->_propNew.IsCached() && !pthis->_propNew.IsFixed())
{
ulVal = 4;
fCorrected = TRUE;
}
}
}
if (fCorrected)
{
MessageBeep(MB_ICONHAND);
// xawcTemp may not have a buffer, so don't use it for _itow. Use a temp vble
WCHAR wszBuff[20];
SetWindowText((HWND)lParam, _itow(ulVal, wszBuff, 10));
SendMessage((HWND)lParam, EM_SETSEL, 0, -1);
}
}
else if ( EN_CHANGE == HIWORD(wParam) && ( 0 != GetWindowLongPtr( hwndDlg, DWLP_USER )) )
{
CPropertyPropertySheet1 * pthis = (CPropertyPropertySheet1 *)GetWindowLongPtr( hwndDlg, DWLP_USER );
if ( 0 != pthis )
{
fChanged = pthis->Refresh( hwndDlg, FALSE );
fRet = TRUE;
}
}
break;
}
case IDDI_CACHED:
{
if ( BN_CLICKED == HIWORD(wParam) )
{
CPropertyPropertySheet1 * pthis = (CPropertyPropertySheet1 *)GetWindowLongPtr( hwndDlg, DWLP_USER );
ULONG fChecked = (ULONG)SendDlgItemMessage( hwndDlg, IDDI_CACHED, BM_GETSTATE, 0, 0 );
if ( fChecked & BST_CHECKED )
{
pthis->Refresh( hwndDlg, FALSE );
EnableWindow( GetDlgItem( hwndDlg, IDDI_DATATYPE ), TRUE );
EnableWindow( GetDlgItem( hwndDlg, IDDI_CACHEDSIZE ), TRUE );
EnableWindow( GetDlgItem( hwndDlg, IDDI_SPIN_CACHEDSIZE ), TRUE );
// If this property is currently being cached in the property store (as indicated
// by CCachedProperty), we do not let it's store level be changed. This ensures
// that a user cannot change a property between store levels.
if (pthis->_propNew.IsCached() && INVALID_STORE_LEVEL != pthis->_propNew.StoreLevel())
{
SendDlgItemMessage( hwndDlg, IDDI_STORAGELEVEL, CB_SETCURSEL,
pthis->_propNew.StoreLevel(), 0 );
EnableWindow( GetDlgItem( hwndDlg, IDDI_STORAGELEVEL), FALSE );
}
else
{
// enable and display the storage level. Default to secondary,
// if none is available
if (PRIMARY_STORE != pthis->_propNew.StoreLevel())
pthis->_propNew.SetStoreLevel(SECONDARY_STORE);
SendDlgItemMessage( hwndDlg, IDDI_STORAGELEVEL, CB_SETCURSEL,
pthis->_propNew.StoreLevel(), 0 );
EnableWindow( GetDlgItem( hwndDlg, IDDI_STORAGELEVEL), TRUE );
}
// if no item is currently selected, set lpwstr by default
if (VT_EMPTY == pthis->_propNew.GetVT() || 0 == pthis->_propNew.Allocation())
{
UINT uiType = DBTypeToVT(pthis->_propNew.GetDefaultType());
if (uiType != VT_EMPTY)
{
ciaDebugOut((DEB_ITRACE, "DIALOG: %ws has type %d (==> %d)\n",
pthis->_propNew.GetFName(), pthis->_propNew.GetDefaultType(),
DBTypeToVT(pthis->_propNew.GetDefaultType())));
pthis->_propNew.SetVT( uiType );
pthis->_propNew.SetAllocation( pthis->_propNew.GetDefaultSize() );
}
else
{
// default datatype should be LPWSTR
pthis->_propNew.SetVT( VT_LPWSTR );
pthis->_propNew.SetAllocation( 4 );
}
}
// Assert that the property is now marked cached
Win4Assert( pthis->_propNew.IsCached() );
// now display it
SendDlgItemMessage( hwndDlg, IDDI_DATATYPE, CB_SETCURSEL,
aulTypeIndex[ pthis->_propNew.GetVT() & ~VT_VECTOR ], 0 );
SetDlgItemText( hwndDlg, IDDI_CACHEDSIZE, pthis->_propNew.GetAllocation() );
// in case OK was disabled, enable it
EnableWindow( GetDlgItem( GetParent(hwndDlg), IDOK), TRUE );
}
else
{
pthis->_propNew.SetVT( VT_EMPTY );
pthis->_propNew.SetAllocation( 0 );
// IMPORTANT: Don't set storage level to invalid. We need to
// know where to delete this from!
//pthis->_propNew.SetStoreLevel(INVALID_STORE_LEVEL);
EnableWindow( GetDlgItem( hwndDlg, IDDI_DATATYPE ), FALSE );
EnableWindow( GetDlgItem( hwndDlg, IDDI_STORAGELEVEL), FALSE );
EnableWindow( GetDlgItem( hwndDlg, IDDI_CACHEDSIZE ), FALSE );
EnableWindow( GetDlgItem( hwndDlg, IDDI_SPIN_CACHEDSIZE ), FALSE );
}
fChanged = TRUE;
fRet = TRUE;
}
break;
}
} // switch
if ( fChanged )
{
CPropertyPropertySheet1 * pthis = (CPropertyPropertySheet1 *)GetWindowLongPtr( hwndDlg, DWLP_USER );
PropSheet_Changed( GetParent(hwndDlg), hwndDlg );
}
break;
}
case WM_NOTIFY:
{
switch ( ((LPNMHDR) lParam)->code )
{
case PSN_APPLY:
{
TRY
{
CPropertyPropertySheet1 * pthis = (CPropertyPropertySheet1 *)GetWindowLongPtr( hwndDlg, DWLP_USER );
*pthis->_pProperty = pthis->_propNew;
pthis->_pProperty->MakeUnappliedChange();
pthis->_pCat->UpdateCachedProperty(pthis->_pProperty);
MMCPropertyChangeNotify( pthis->_hMmcNotify, (LONG_PTR)pthis->_pProperty );
MessageBox( hwndDlg,
STRINGRESOURCE( srPendingProps ),
STRINGRESOURCE( srPendingPropsTitle ),
MB_OK | MB_ICONINFORMATION );
fRet = TRUE;
ciaDebugOut((DEB_ITRACE, "VarType is %d, Allocation size is %d, Store level is %d\n",
pthis->_pProperty->GetVT(), pthis->_pProperty->Allocation(),
pthis->_pProperty->StoreLevel() ));
}
CATCH( CException, e )
{
DisplayError( hwndDlg, e );
}
END_CATCH
break;
}
} // switch
break;
}
case WM_DESTROY:
{
CPropertyPropertySheet1 * pthis = (CPropertyPropertySheet1 *)GetWindowLongPtr( hwndDlg, DWLP_USER );
// Freeing this will cause a double-delete since it's shared across instances of this page
#if 0
DbgPrint( "WM_DESTROY CPropertyPropertySheet1 this %#x, _hMmcNotify: %#x\n", pthis, pthis->_hMmcNotify );
MMCFreeNotifyHandle( pthis->_hMmcNotify );
pthis->_hMmcNotify = 0;
#endif
delete pthis;
fRet = TRUE;
break;
}
default:
fRet = FALSE;
break;
}
}
CATCH( CException, e )
{
ciaDebugOut(( DEB_ERROR, "CPropertyPropertySheet1: Caught 0x%x\n", e.GetErrorCode() ));
fRet = FALSE;
}
END_CATCH
return fRet;
}
BOOL CPropertyPropertySheet1::Refresh( HWND hwndDlg, BOOL fVTOnly )
{
BOOL fChanged = FALSE;
DWORD dwIndex = (DWORD)SendDlgItemMessage( hwndDlg, IDDI_DATATYPE, CB_GETCURSEL, 0, 0 );
ULONG vt = (ULONG)SendDlgItemMessage( hwndDlg, IDDI_DATATYPE, CB_GETITEMDATA, dwIndex, 0 );
if ( vt != _propNew.GetVT() )
fChanged = TRUE;
_propNew.SetVT( vt );
dwIndex = (DWORD)SendDlgItemMessage( hwndDlg, IDDI_STORAGELEVEL, CB_GETCURSEL, 0, 0 );
DWORD dwStoreLevel = (DWORD)SendDlgItemMessage( hwndDlg, IDDI_STORAGELEVEL, CB_GETITEMDATA, dwIndex, 0 );
if ( dwStoreLevel != _propNew.StoreLevel() )
fChanged = TRUE;
_propNew.SetStoreLevel( dwStoreLevel );
if ( !fVTOnly )
{
XArray<WCHAR> xawcSize;
if ( GetDlgItemXArrayText( hwndDlg, IDDI_CACHEDSIZE, xawcSize ) && xawcSize.Count() > 0)
{
ULONG cb = wcstoul( xawcSize.Get(), 0, 10 );
if ( cb != _propNew.Allocation() )
fChanged = TRUE;
_propNew.SetAllocation( cb );
}
}
return fChanged;
}
void InitVTList( HWND hwndCombo )
{
DWORD dwIndex;
//
// Add an item for each type group.
//
int j = 0;
for ( int i = 0; i < cType; i++ )
{
if ( 0 != awcsType[i] )
{
dwIndex = (DWORD)SendMessage( hwndCombo, CB_ADDSTRING, 0, (LPARAM)awcsType[i] );
SendMessage(hwndCombo, CB_SETITEMDATA, dwIndex, i );
j++;
}
}
//
// NOTE: After the first property box, this just sets identical values.
//
for ( j--; j >= 0; j-- )
{
dwIndex = (DWORD)SendMessage( hwndCombo, CB_GETITEMDATA, j, 0 );
aulTypeIndex[dwIndex] = j;
}
}
void InitStorageLevelList( HWND hwndCombo )
{
DWORD dwIndex;
//
// Add an item for each of the two levels.
//
dwIndex = (DWORD)SendMessage( hwndCombo, CB_ADDSTRING, 0, (LPARAM)STRINGRESOURCE(srPrimaryStore) );
SendMessage(hwndCombo, CB_SETITEMDATA, dwIndex, PRIMARY_STORE );
dwIndex = (DWORD)SendMessage( hwndCombo, CB_ADDSTRING, 0, (LPARAM)STRINGRESOURCE(srSecondaryStore) );
SendMessage(hwndCombo, CB_SETITEMDATA, dwIndex, SECONDARY_STORE );
}
//
// Helper class for virtual server callback.
//
//+---------------------------------------------------------------------------
//
// Class: CMetaDataVirtualServerCallBack
//
// Purpose: Pure virtual for vroot enumeration
//
// History: 07-Feb-1997 dlee Created
//
//----------------------------------------------------------------------------
class CVSComboBox : public CMetaDataVirtualServerCallBack
{
public:
CVSComboBox( HWND hwndCombo ) :
_hwndCombo( hwndCombo ),
cEntries( 0 )
{
}
virtual SCODE CallBack( DWORD iInstance, WCHAR const * pwcInstance );
virtual ~CVSComboBox() {}
ULONG EntryCount() { return cEntries; }
private:
HWND _hwndCombo;
ULONG cEntries;
};
SCODE CVSComboBox::CallBack( DWORD iInstance, WCHAR const * pwcInstance )
{
// We pass NULL for _hwndCombo when we only need a count of entries.
if (NULL != _hwndCombo)
{
DWORD dwIndex = (DWORD)SendMessage( _hwndCombo, CB_ADDSTRING, 0, (LPARAM)pwcInstance );
SendMessage( _hwndCombo, CB_SETITEMDATA, dwIndex, (LPARAM)iInstance );
}
cEntries++;
return S_OK;
}
BOOL AreServersAvailable( CCatalog const & cat )
{
BOOL fEntriesInList = FALSE;
//
// Virtual Server(s)
//
TRY
{
//
// Add an item for each type group.
//
CMetaDataMgr mgr( TRUE, W3VRoot, 0xffffffff, cat.GetMachine() );
CVSComboBox vsc( NULL );
mgr.EnumVServers( vsc );
fEntriesInList = (0 == vsc.EntryCount()) ? FALSE : TRUE;
}
CATCH( CException, e )
{
ciaDebugOut(( DEB_ERROR, "Couldn't enumerate virtual servers.\n" ));
}
END_CATCH
//
// Virtual NNTP Server(s)
//
TRY
{
//
// Add an item for each type group.
//
CMetaDataMgr mgr( TRUE, NNTPVRoot, 0xffffffff, cat.GetMachine() );
CVSComboBox vsc( NULL );
mgr.EnumVServers( vsc );
fEntriesInList = fEntriesInList || ( (0 == vsc.EntryCount()) ? FALSE : TRUE );
}
CATCH( CException, e )
{
ciaDebugOut(( DEB_ERROR, "Couldn't enumerate virtual servers.\n" ));
}
END_CATCH
return fEntriesInList;
}
void InitVSList( HWND hwndComboVS, HWND hwndComboNNTP, CCatalog const & cat,
ULONG & cVServers, ULONG & cNNTPServers )
{
//
// Virtual Server(s)
//
TRY
{
SendMessage( hwndComboVS, CB_ADDSTRING, 0,
(LPARAM) STRINGRESOURCE( srNoneSelected.wsz ) );
//
// Add an item for each type group.
//
CMetaDataMgr mgr( TRUE, W3VRoot, 0xffffffff, cat.GetMachine() );
CVSComboBox vsc( hwndComboVS );
Win4Assert(0 == vsc.EntryCount());
mgr.EnumVServers( vsc );
cVServers = vsc.EntryCount();
}
CATCH( CException, e )
{
ciaDebugOut(( DEB_ERROR, "Couldn't enumerate virtual servers.\n" ));
}
END_CATCH
//
// Virtual NNTP Server(s)
//
TRY
{
SendMessage( hwndComboNNTP, CB_ADDSTRING, 0,
(LPARAM) STRINGRESOURCE( srNoneSelected.wsz ) );
//
// Add an item for each type group.
//
CMetaDataMgr mgr( TRUE, NNTPVRoot, 0xffffffff, cat.GetMachine() );
CVSComboBox vsc( hwndComboNNTP );
Win4Assert(0 == vsc.EntryCount());
mgr.EnumVServers( vsc );
cNNTPServers = vsc.EntryCount();
}
CATCH( CException, e )
{
ciaDebugOut(( DEB_ERROR, "Couldn't enumerate virtual servers.\n" ));
}
END_CATCH
#if 0
//
// Virtual IMAP Server(s)
//
TRY
{
//
// Add an item for each type group.
//
CMetaDataMgr mgr( TRUE, IMAPVRoot, 0xffffffff, cat.GetMachine() );
DWORD dwIndex = SendMessage( hwndComboIMAP, CB_ADDSTRING, 0,
(LPARAM) STRINGRESOURCE( srNoneSelected.wsz ) );
CVSComboBox vsc( hwndComboIMAP );
mgr.EnumVServers( vsc );
}
CATCH( CException, e )
{
ciaDebugOut(( DEB_ERROR, "Couldn't enumerate virtual servers.\n" ));
}
END_CATCH
#endif
}
void DisplayError( HWND hwnd, CException & e )
{
WCHAR wcsError[MAX_PATH];
if ( !FormatMessage( FORMAT_MESSAGE_FROM_HMODULE,
GetModuleHandle(L"query.dll"),
GetOleError( e ),
GetSystemDefaultLCID(),
wcsError,
sizeof(wcsError) / sizeof(WCHAR),
0 ) )
{
wsprintf( wcsError,
STRINGRESOURCE(srGenericError),
GetOleError( e ) );
}
MessageBox( hwnd,
wcsError,
STRINGRESOURCE( srIndexServerCmpManage ),
MB_OK | MB_ICONERROR );
}
DWORD VSToIndex( HWND hwndDlg, DWORD dwItem, ULONG ulVS, BOOL fTrack )
{
if ( !fTrack )
return 0;
unsigned cItem = (unsigned)SendDlgItemMessage( hwndDlg,
dwItem,
CB_GETCOUNT, 0, 0 );
for ( unsigned i = 1; i < cItem; i++ )
{
ULONG ulItem = (ULONG)SendDlgItemMessage( hwndDlg,
dwItem,
CB_GETITEMDATA, i, 0 );
if ( ulVS == ulItem )
break;
}
return i;
} //VSToIndex
// Return of VT_EMPTY could imply an unknown conversion.
UINT DBTypeToVT(UINT uidbt)
{
if (uidbt <= DBTYPE_GUID)
return uidbt;
// Some conversions
DBTYPE dbtSimpler = uidbt &~ DBTYPE_VECTOR &~ DBTYPE_ARRAY &~ DBTYPE_BYREF;
switch (dbtSimpler)
{
case DBTYPE_WSTR:
return VT_LPWSTR;
case DBTYPE_STR:
return VT_LPSTR;
case DBTYPE_FILETIME:
return VT_FILETIME;
default:
return VT_EMPTY;
}
}
| [
"[email protected]"
] | |
a75475b03658507fec5b390e42dc71ffc9a7329e | 8184cba46a3e468faac1ff6c792e92c2720405f3 | /src/main/cpp/Balau/Logging/Impl/LoggerHolder.cpp | 8374d41981b286f5e447935c6eaa4a834ed42824 | [
"Apache-2.0"
] | permissive | borasoftware/balau | 32a08cd5e68df768805cde906fb15a86d957c1b9 | 8bb82e9cbf7aa8193880eda1de5cbca4db1e1c14 | refs/heads/master | 2021-06-07T23:27:32.126536 | 2021-06-01T08:22:39 | 2021-06-01T08:22:39 | 143,303,458 | 16 | 3 | BSL-1.0 | 2019-06-16T17:21:00 | 2018-08-02T14:10:12 | C++ | UTF-8 | C++ | false | false | 810 | cpp | // @formatter:off
//
// Balau core C++ library
//
// Copyright (C) 2008 Bora Software ([email protected])
//
// 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.
//
#include "LoggerHolder.hpp"
namespace Balau::LoggingSystem {
Logger LoggerHolder::backupLogger;
} // namespace Balau::LoggingSystem
| [
"[email protected]"
] | |
124dc6bc70d5e3d68db8900efdf12e63afd2aaba | 0681d156fb995dc7fc356c76ffc1388e8ba23442 | /marinus/Marinus/bmdraw.ino | b764fc5ff934af8d14e6650bc9de06846b5200a8 | [
"MIT"
] | permissive | edgecollective/eink-map | 51f598541ed10aa5eb714c1654f777340fc2cb9d | 669b8a9ed8e254b0fa0314ffede42efee74f05f1 | refs/heads/main | 2023-01-24T11:48:06.443821 | 2020-11-25T16:22:10 | 2020-11-25T16:22:10 | 311,683,675 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 5,988 | ino |
/***************************************************
This is an example sketch for the Adafruit 1.8" SPI display.
This library works with the Adafruit 1.8" TFT Breakout w/SD card
----> http://www.adafruit.com/products/358
as well as Adafruit raw 1.8" TFT display
----> http://www.adafruit.com/products/618
Check out the links above for our tutorials and wiring diagrams
These displays use SPI to communicate, 4 or 5 pins are required to
interface (RST is optional)
Adafruit invests time and resources providing this open source code,
please support Adafruit and open-source hardware by purchasing
products from Adafruit!
Written by Limor Fried/Ladyada for Adafruit Industries.
MIT license, all text above must be included in any redistribution
****************************************************/
// This function opens a Windows Bitmap (BMP) file and
// displays it at the given coordinates. It's sped up
// by reading many pixels worth of data at a time
// (rather than pixel by pixel). Increasing the buffer
// size takes more of the Arduino's precious RAM but
// makes loading a little faster. 20 pixels seems a
// good balance.
#define BUFFPIXEL 20
void bmpDraw(char *filename, uint8_t x, uint8_t y) {
File bmpFile;
int bmpWidth, bmpHeight; // W+H in pixels
uint8_t bmpDepth; // Bit depth (currently must be 24)
uint32_t bmpImageoffset; // Start of image data in file
uint32_t rowSize; // Not always = bmpWidth; may have padding
uint8_t sdbuffer[3*BUFFPIXEL]; // pixel buffer (R+G+B per pixel)
uint8_t buffidx = sizeof(sdbuffer); // Current position in sdbuffer
boolean goodBmp = false; // Set to true on valid header parse
boolean flip = true; // BMP is stored bottom-to-top
int w, h, row, col;
uint8_t r, g, b;
uint32_t pos = 0, startTime = millis();
if((x >= tft.width()) || (y >= tft.height())) return;
// Open requested file on SD card
if ((bmpFile = SD.open(filename)) == NULL) {
// Serial.print(F(" File not found"));
return;
}
// Parse BMP header
if(read16(bmpFile) == 0x4D42) { // BMP signature
int bmpSize = read32(bmpFile);
// Serial.print(" File size: "); Serial.println(bmpSize);
(void)read32(bmpFile); // Read & ignore creator bytes
bmpImageoffset = read32(bmpFile); // Start of image data
// Serial.print(" Image Offset: "); Serial.println(bmpImageoffset, DEC);
// Read DIB header
int bmpHeaderSize = read32(bmpFile);
// Serial.print(" Header size: "); Serial.println(bmpHeaderSize);
bmpWidth = read32(bmpFile);
bmpHeight = read32(bmpFile);
if(read16(bmpFile) == 1) { // # planes -- must be '1'
bmpDepth = read16(bmpFile); // bits per pixel
// Serial.print(" Bit Depth: "); Serial.println(bmpDepth);
if((bmpDepth == 24) && (read32(bmpFile) == 0)) { // 0 = uncompressed
goodBmp = true; // Supported BMP format -- proceed!
// Serial.print(" Image size: ");
// Serial.print(bmpWidth);
// Serial.print('x');
// Serial.println(bmpHeight);
// BMP rows are padded (if needed) to 4-byte boundary
rowSize = (bmpWidth * 3 + 3) & ~3;
// If bmpHeight is negative, image is in top-down order.
// This is not canon but has been observed in the wild.
if(bmpHeight < 0) {
bmpHeight = -bmpHeight;
flip = false;
}
// Crop area to be loaded
w = bmpWidth;
h = bmpHeight;
if((x+w-1) >= tft.width()) w = tft.width() - x;
if((y+h-1) >= tft.height()) h = tft.height() - y;
// Set TFT address window to clipped image bounds
tft.setAddrWindow(x, y, x+w-1, y+h-1);
for (row=0; row<h; row++) { // For each scanline...
// Seek to start of scan line. It might seem labor-
// intensive to be doing this on every line, but this
// method covers a lot of gritty details like cropping
// and scanline padding. Also, the seek only takes
// place if the file position actually needs to change
// (avoids a lot of cluster math in SD library).
if(flip) // Bitmap is stored bottom-to-top order (normal BMP)
pos = bmpImageoffset + (bmpHeight - 1 - row) * rowSize;
else // Bitmap is stored top-to-bottom
pos = bmpImageoffset + row * rowSize;
if(bmpFile.position() != pos) { // Need seek?
bmpFile.seek(pos);
buffidx = sizeof(sdbuffer); // Force buffer reload
}
for (col=0; col<w; col++) { // For each pixel...
// Time to read more pixel data?
if (buffidx >= sizeof(sdbuffer)) { // Indeed
bmpFile.read(sdbuffer, sizeof(sdbuffer));
buffidx = 0; // Set index to beginning
}
// Convert pixel from BMP to TFT format, push to display
b = sdbuffer[buffidx++];
g = sdbuffer[buffidx++];
r = sdbuffer[buffidx++];
tft.pushColor(tft.Color565(r,g,b));
} // end pixel
} // end scanline
// Serial.print(" Loaded in ");
// Serial.print(millis() - startTime);
// Serial.println(" ms");
} // end goodBmp
}
}
bmpFile.close();
if(!goodBmp) {
// Serial.println(" BMP format not recognized.");
}
}
// These read 16- and 32-bit types from the SD card file.
// BMP data is stored little-endian, Arduino is little-endian too.
// May need to reverse subscript order if porting elsewhere.
uint16_t read16(File f) {
uint16_t result;
((uint8_t *)&result)[0] = f.read(); // LSB
((uint8_t *)&result)[1] = f.read(); // MSB
return result;
}
uint32_t read32(File f) {
uint32_t result;
((uint8_t *)&result)[0] = f.read(); // LSB
((uint8_t *)&result)[1] = f.read();
((uint8_t *)&result)[2] = f.read();
((uint8_t *)&result)[3] = f.read(); // MSB
return result;
}
| [
"[email protected]"
] | |
a10e5c3d1a917970bc62ea48361647dbd2646d36 | 66039e70d4ee0b9421165745ab67dfb001c0beab | /SdlOsc/imgui/imgui.cpp | 25ff851ca4cecb218109d71cefbe3975a9c5aa0d | [
"Apache-2.0"
] | permissive | hzshenlijun/SdlOsc | 2f2a0c7eafe56c22684dd97b8f7b744c53d57579 | 27dd38e9d8a61045fcc80a40092a92585b535483 | refs/heads/master | 2023-05-24T21:31:15.045087 | 2017-04-25T09:32:13 | 2017-04-25T09:32:13 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 427,120 | cpp | // dear imgui, v1.50 WIP
// (main code and documentation)
// See ImGui::ShowTestWindow() in imgui_demo.cpp for demo code.
// Newcomers, read 'Programmer guide' below for notes on how to setup ImGui in your codebase.
// Get latest version at https://github.com/ocornut/imgui
// Releases change-log at https://github.com/ocornut/imgui/releases
// Developed by Omar Cornut and every direct or indirect contributors to the GitHub.
// This library is free but I need your support to sustain development and maintenance.
// If you work for a company, please consider financial support, e.g: https://www.patreon.com/imgui
/*
Index
- MISSION STATEMENT
- END-USER GUIDE
- PROGRAMMER GUIDE (read me!)
- API BREAKING CHANGES (read me when you update!)
- FREQUENTLY ASKED QUESTIONS (FAQ), TIPS
- How can I help?
- How do I update to a newer version of ImGui?
- What is ImTextureID and how do I display an image?
- I integrated ImGui in my engine and the text or lines are blurry..
- I integrated ImGui in my engine and some elements are clipping or disappearing when I move windows around..
- How can I have multiple widgets with the same label? Can I have widget without a label? (Yes). A primer on the purpose of labels/IDs.
- How can I tell when ImGui wants my mouse/keyboard inputs and when I can pass them to my application?
- How can I load a different font than the default?
- How can I load multiple fonts?
- How can I display and input non-latin characters such as Chinese, Japanese, Korean, Cyrillic?
- How can I use the drawing facilities without an ImGui window? (using ImDrawList API)
- ISSUES & TODO-LIST
- CODE
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 (NB- we do allocate when "growing" content - creating a window / opening a tree node for the first time, etc. - but a typical frame won't allocate anything)
- read about immediate-mode gui principles @ http://mollyrocket.com/861, http://mollyrocket.com/forums/index.html
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
- occasionally uses statically sized buffers for string manipulations - won't crash, but some very long pieces of text may be clipped. functions like ImGui::TextUnformatted() don't have such restriction.
END-USER GUIDE
==============
- double-click 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
- click and drag on any empty space to move window
- double-click/double-tap on lower right corner grip to auto-fit to content
- TAB/SHIFT+TAB to cycle through keyboard editable fields
- use mouse wheel to scroll
- use CTRL+mouse wheel to zoom window contents (if IO.FontAllowScaling is true)
- CTRL+Click on a slider or drag box to input value as text
- 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!)
PROGRAMMER GUIDE
================
- read the FAQ below this section!
- your code creates the UI, if your code doesn't run the UI is gone! == very dynamic UI, no construction/destructions steps, less data retention on your side, no state duplication, less sync, less bugs.
- call and read ImGui::ShowTestWindow() for demo code demonstrating most features.
- see examples/ folder for standalone sample applications. Prefer reading examples/opengl_example/ first as it is the simplest.
you may be able to grab and copy a ready made imgui_impl_*** file from the examples/.
- customization: PushStyleColor()/PushStyleVar() or the style editor to tweak the look of the interface (e.g. if you want a more compact UI or a different color scheme).
- getting started:
- init: call ImGui::GetIO() to retrieve the ImGuiIO structure and fill the fields marked 'Settings'.
- init: call io.Fonts->GetTexDataAsRGBA32(...) and load the font texture pixels into graphics memory.
- every frame:
1/ in your mainloop or right after you got your keyboard/mouse info, call ImGui::GetIO() and fill the fields marked 'Input'
2/ call ImGui::NewFrame() as early as you can!
3/ use any ImGui function you want between NewFrame() and Render()
4/ call ImGui::Render() as late as you can to end the frame and finalize render data. it will call your RenderDrawListFn handler that you set in the IO structure.
(if you don't need to render, you still need to call Render() and ignore the callback, or call EndFrame() instead. if you call neither some aspects of windows focusing/moving will appear broken.)
- all rendering information are stored into command-lists until ImGui::Render() is called.
- ImGui never touches or know about your GPU state. the only function that knows about GPU is the RenderDrawListFn handler 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.
- refer to the examples applications in the examples/ folder for instruction on how to setup your code.
- a typical application skeleton may be:
// Application init
ImGuiIO& io = ImGui::GetIO();
io.DisplaySize.x = 1920.0f;
io.DisplaySize.y = 1280.0f;
io.IniFilename = "imgui.ini";
io.RenderDrawListsFn = my_render_function; // Setup a render function, or set to NULL and call GetDrawData() after Render() to access the render data.
// TODO: Fill others settings of the io structure
// Load texture atlas
// There is a default font so you don't need to care about choosing a font yet
unsigned char* pixels;
int width, height;
io.Fonts->GetTexDataAsRGBA32(pixels, &width, &height);
// TODO: At this points you've got a texture pointed to by 'pixels' and you need to upload that your your graphic system
// TODO: Store your texture pointer/identifier (whatever your engine uses) in 'io.Fonts->TexID'
// Application main loop
while (true)
{
// 1) get low-level inputs (e.g. on Win32, GetKeyboardState(), or poll your events, etc.)
// TODO: fill all fields of IO structure and call NewFrame
ImGuiIO& io = ImGui::GetIO();
io.DeltaTime = 1.0f/60.0f;
io.MousePos = mouse_pos;
io.MouseDown[0] = mouse_button_0;
io.MouseDown[1] = mouse_button_1;
io.KeysDown[i] = ...
// 2) call NewFrame(), after this point you can use ImGui::* functions anytime
ImGui::NewFrame();
// 3) most of your application code here
MyGameUpdate(); // may use any ImGui functions, e.g. ImGui::Begin("My window"); ImGui::Text("Hello, world!"); ImGui::End();
MyGameRender(); // may use any ImGui functions
// 4) render & swap video buffers
ImGui::Render();
SwapBuffers();
}
- You can read back 'io.WantCaptureMouse', 'io.WantCaptureKeybord' etc. flags from the IO structure to tell how ImGui intends to use your
inputs and to know if you should share them or hide them from the rest of your application. Read the FAQ below for more information.
API BREAKING CHANGES
====================
Occasionally introducing changes that are breaking the API. The breakage are generally minor and easy to fix.
Here is a change-log of API breaking changes, if you are using one of the functions listed, expect to have to fix some code.
Also read releases logs https://github.com/ocornut/imgui/releases for more details.
- 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.
However 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 ImDraw::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!
ImGui_XXXX_RenderDrawLists(ImDrawList** const cmd_lists, int cmd_lists_count)
became:
ImGui_XXXX_RenderDrawLists(ImDrawData* draw_data).
argument 'cmd_lists' -> 'draw_data->CmdLists'
argument 'cmd_lists_count' -> 'draw_data->CmdListsCount'
ImDrawList 'commands' -> 'CmdBuffer'
ImDrawList 'vtx_buffer' -> 'VtxBuffer'
ImDrawList n/a -> 'IdxBuffer' (new)
ImDrawCmd 'vtx_count' -> 'ElemCount'
ImDrawCmd 'clip_rect' -> 'ClipRect'
ImDrawCmd 'user_callback' -> 'UserCallback'
ImDrawCmd 'texture_id' -> '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 (will obsolete).
- 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 (will obsolete).
- 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 (will obsolete).
- 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 (will obsolete).
- 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.
this sequence:
const void* png_data;
unsigned int png_size;
ImGui::GetDefaultFontData(NULL, NULL, &png_data, &png_size);
// <Copy to GPU>
became:
unsigned char* pixels;
int width, height;
io.Fonts->GetTexDataAsRGBA32(&pixels, &width, &height);
// <Copy to GPU>
io.Fonts->TexID = (your_texture_identifier);
you now have much 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: How can I help?
A: - If you are experienced enough with ImGui and with C/C++, look at the todo list and see how you want/can help!
- Become a Patron/donate. Convince your company to become a Patron or provide serious funding for development time.
Q: How do I update to a newer version of ImGui?
A: Overwrite the following files:
imgui.cpp
imgui.h
imgui_demo.cpp
imgui_draw.cpp
imgui_internal.h
stb_rect_pack.h
stb_textedit.h
stb_truetype.h
Don't overwrite imconfig.h if you have made modification to your copy.
Check the "API BREAKING CHANGES" sections for a list of occasional API breaking changes. If you have a problem with a function, search for its name
in the code, there will likely be a comment about it. Please report any issue to the GitHub page!
Q: What is ImTextureID and how do I display an image?
A: ImTextureID is a void* used to pass renderer-agnostic texture references around until it hits your render function.
ImGui knows nothing about what those bits represent, it just passes them around. It is up to you to decide what you want the void* to carry!
It could be an identifier to your OpenGL texture (cast GLuint to void*), a pointer to your custom engine material (cast MyMaterial* to void*), etc.
At the end of the chain, your renderer takes this void* to cast it back into whatever it needs to select a current texture to render.
Refer to examples applications, where each renderer (in a imgui_impl_xxxx.cpp file) is treating ImTextureID as a different thing.
(c++ tip: OpenGL uses integers to identify textures. You can safely store an integer into a void*, just cast it to void*, don't take it's address!)
To display a custom image/texture within an ImGui window, you may use ImGui::Image(), ImGui::ImageButton(), ImDrawList::AddImage() functions.
ImGui will generate the geometry and draw calls using the ImTextureID that you passed and which your renderer can use.
It is your responsibility to get textures uploaded to your GPU.
Q: I integrated 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 ImGui in my engine and some elements are clipping or disappearing when I move windows around..
A: Most likely you are mishandling the clipping rectangles in your render function. Rectangles provided by ImGui are defined as (x1,y1,x2,y2) and NOT as (x1,y1,width,height).
Q: Can I have multiple widgets with the same label? Can I have widget without a label? (Yes)
A: Yes. A primer on the use of labels/IDs in ImGui..
- Elements that are not clickable, such as Text() items don't need an ID.
- Interactive widgets require state to be carried over multiple frames (most typically ImGui often needs to remember what is the "active" widget).
to do so they need an unique ID. unique ID are typically derived from a string label, an integer index or a pointer.
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. so no conflict can happen if you have two buttons called "OK" in two different windows
or in two different locations of a tree.
- If you have a same ID twice in the same location, you'll have a conflict:
Button("OK");
Button("OK"); // ID collision! Both buttons will be treated as the same.
Fear not! this is easy to solve and there are many ways to solve it!
- When passing a label you can optionally specify extra unique ID information within string itself. This helps solving the simpler collision cases.
use "##" to pass a complement to the ID that won't be visible to the end-user:
Button("Play"); // Label = "Play", ID = hash of "Play"
Button("Play##foo1"); // Label = "Play", ID = hash of "Play##foo1" (different from above)
Button("Play##foo2"); // Label = "Play", ID = hash of "Play##foo2" (different from above)
- If you want to completely hide the label, but still need an ID:
Checkbox("##On", &b); // Label = "", ID = hash of "##On" (no label!)
- 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 (and windows are uniquely identified by their ID.. obviously)
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)
sprintf(buf, "My game (%f FPS)###MyGame");
Begin(buf); // Variable label, ID = hash of "MyGame"
- Use PushID() / PopID() to create scopes and avoid ID conflicts within the same Window.
This is the most convenient way of distinguishing ID if you are iterating and creating many UI elements.
You can push a pointer, a string or an integer value. Remember that ID are formed from the concatenation of everything in the ID stack!
for (int i = 0; i < 100; i++)
{
PushID(i);
Button("Click"); // Label = "Click", ID = hash of integer + "label" (unique)
PopID();
}
for (int i = 0; i < 100; i++)
{
MyObject* obj = Objects[i];
PushID(obj);
Button("Click"); // Label = "Click", ID = hash of pointer + "label" (unique)
PopID();
}
for (int i = 0; i < 100; i++)
{
MyObject* obj = Objects[i];
PushID(obj->Name);
Button("Click"); // Label = "Click", ID = hash of string + "label" (unique)
PopID();
}
- More example showing that 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" + 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"))
{
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 displaying a single object that may change over time (1-1 relationship), 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. experiment and see what makes more sense!
Q: How can I tell when ImGui wants my mouse/keyboard inputs and when I can pass them to my application?
A: You can read the 'io.WantCaptureXXX' flags in the ImGuiIO structure. Preferably read them after calling ImGui::NewFrame() to avoid those flags lagging by one frame, but either should be fine.
When 'io.WantCaptureMouse' or 'io.WantCaptureKeyboard' flags are set you may want to discard/hide the inputs from the rest of your application.
When 'io.WantInputsCharacters' is set to may want to notify your OS to popup an on-screen keyboard, if available.
ImGui is tracking dragging and widget activity that may occur outside the boundary of a window, so 'io.WantCaptureMouse' is a more accurate and complete than testing for ImGui::IsMouseHoveringAnyWindow().
(Advanced note: text input releases focus on Return 'KeyDown', so the following 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 for ImGui (e.g. with an array of bool) and filter out the corresponding key-ups.)
Q: How can I load a different font than the default? (default is an embedded version of ProggyClean.ttf, rendered at size 13)
A: Use the font atlas to load the TTF file you want:
ImGuiIO& io = ImGui::GetIO();
io.Fonts->AddFontFromFileTTF("myfontfile.ttf", size_in_pixels);
io.Fonts->GetTexDataAsRGBA32() or GetTexDataAsAlpha8()
Q: How can I load multiple fonts?
A: Use the font atlas to pack them into a single texture:
(Read extra_fonts/README.txt 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 = 3;
config.OversampleV = 1;
config.GlyphExtraSpacing.x = 1.0f;
io.Fonts->LoadFromFileTTF("myfontfile.ttf", size_pixels, &config);
// Combine multiple fonts into one
ImWchar ranges[] = { 0xf000, 0xf3ff, 0 };
ImFontConfig config;
config.MergeMode = true;
io.Fonts->AddFontDefault();
io.Fonts->LoadFromFileTTF("fontawesome-webfont.ttf", 16.0f, &config, ranges);
io.Fonts->LoadFromFileTTF("myfontfile.ttf", size_pixels, NULL, &config, io.Fonts->GetGlyphRangesJapanese());
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.
All your strings needs to use UTF-8 encoding. 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.
In C++11 you can encode a string literal in UTF-8 by using the u8"hello" syntax. Otherwise you can convert yourself to UTF-8 or load text data from file already saved as UTF-8.
You can also try to remap your local codepage characters to their Unicode codepoint using font->AddRemapChar(), but international users may have problems reading/editing your source code.
io.Fonts->AddFontFromFileTTF("myfontfile.ttf", size_in_pixels, NULL, io.Fonts->GetGlyphRangesJapanese()); // Load Japanese characters
io.Fonts->GetTexDataAsRGBA32() or GetTexDataAsAlpha8()
io.ImeWindowHandle = MY_HWND; // To input using Microsoft IME, give ImGui the hwnd of your application
As for text input, depends on you passing the right character code to io.AddInputCharacter(). The example applications do that.
Q: How can I use the drawing facilities without an ImGui window? (using ImDrawList API)
A: The easiest way is to create a dummy window. Call Begin() with NoTitleBar|NoResize|NoMove|NoScrollbar|NoSavedSettings|NoInputs flag, zero background alpha,
then retrieve the ImDrawList* via GetWindowDrawList() and draw to it in any way you like.
- tip: the construct 'IMGUI_ONCE_UPON_A_FRAME { ... }' will 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 create widgets without a Begin()/End() block, they will go in an implicit window called "Debug"
- 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 call Render() multiple times (e.g for VR renders).
- tip: call and read the ShowTestWindow() code in imgui_demo.cpp for more example of how to use ImGui!
ISSUES & TODO-LIST
==================
Issue numbers (#) refer to github issues listed at https://github.com/ocornut/imgui/issues
The list below consist mostly of notes of things to do before they are requested/discussed by users (at that point it usually happens on the github)
- doc: add a proper documentation+regression testing system (#435)
- window: add a way for very transient windows (non-saved, temporary overlay over hundreds of objects) to "clean" up from the global window list. perhaps a lightweight explicit cleanup pass.
- window: calling SetNextWindowSize() every frame with <= 0 doesn't do anything, may be useful to allow (particularly when used for a single axis) (#690)
- window: auto-fit feedback loop when user relies on any dynamic layout (window width multiplier, column) appears weird to end-user. clarify.
- window: allow resizing of child windows (possibly given min/max for each axis?)
- window: background options for child windows, border option (disable rounding)
- window: add a way to clear an existing window instead of appending (e.g. for tooltip override using a consistent api rather than the deferred tooltip)
- window: resizing from any sides? + mouse cursor directives for app.
!- window: begin with *p_open == false should return false.
- window: get size/pos helpers given names (see discussion in #249)
- window: a collapsed window can be stuck behind the main menu bar?
- window: when window is small, prioritize resize button over close button.
- window: detect extra End() call that pop the "Debug" window out and assert at call site instead of later.
- window/tooltip: allow to set the width of a tooltip to allow TextWrapped() etc. while keeping the height automatic.
- window: increase minimum size of a window with menus or fix the menu rendering so that it doesn't look odd.
- draw-list: maintaining bounding box per command would allow to merge draw command when clipping isn't relied on (typical non-scrolling window or non-overflowing column would merge with previous command).
!- scrolling: allow immediately effective change of scroll if we haven't appended items yet
- splitter/separator: formalize the splitter idiom into an official api (we want to handle n-way split) (#319)
- widgets: display mode: widget-label, label-widget (aligned on column or using fixed size), label-newline-tab-widget etc.
- widgets: clean up widgets internal toward exposing everything.
- widgets: add disabled and read-only modes (#211)
- main: considering adding an Init() function? some constructs are awkward in the implementation because of the lack of them.
!- main: make it so that a frame with no window registered won't refocus every window on subsequent frames (~bump LastFrameActive of all windows).
- main: IsItemHovered() make it more consistent for various type of widgets, widgets with multiple components, etc. also effectively IsHovered() region sometimes differs from hot region, e.g tree nodes
- main: IsItemHovered() info stored in a stack? so that 'if TreeNode() { Text; TreePop; } if IsHovered' return the hover state of the TreeNode?
- input text: clean up the mess caused by converting UTF-8 <> wchar. the code is rather inefficient right now.
- input text: reorganize event handling, allow CharFilter to modify buffers, allow multiple events? (#541)
- input text: flag to disable live update of the user buffer (also applies to float/int text input)
- input text: resize behavior - field could stretch when being edited? hover tooltip shows more text?
- input text: add ImGuiInputTextFlags_EnterToApply? (off #218)
- input text: add discard flag (e.g. ImGuiInputTextFlags_DiscardActiveBuffer) or make it easier to clear active focus for text replacement during edition (#725)
- input text multi-line: don't directly call AddText() which does an unnecessary vertex reserve for character count prior to clipping. and/or more line-based clipping to AddText(). and/or reorganize TextUnformatted/RenderText for more efficiency for large text (e.g TextUnformatted could clip and log separately, etc).
- input text multi-line: way to dynamically grow the buffer without forcing the user to initially allocate for worse case (follow up on #200)
- input text multi-line: line numbers? status bar? (follow up on #200)
- input text multi-line: behave better when user changes input buffer while editing is active (even though it is illegal behavior). namely, the change of buffer can create a scrollbar glitch (#725)
- input text: allow centering/positioning text so that ctrl+clicking Drag or Slider keeps the textual value at the same pixel position.
- input number: optional range min/max for Input*() functions
- input number: holding [-]/[+] buttons could increase the step speed non-linearly (or user-controlled)
- input number: use mouse wheel to step up/down
- input number: applying arithmetics ops (+,-,*,/) messes up with text edit undo stack.
- button: provide a button that looks framed.
- text: proper alignment options
- image/image button: misalignment on padded/bordered button?
- image/image button: parameters are confusing, image() has tint_col,border_col whereas imagebutton() has bg_col/tint_col. Even thou they are different parameters ordering could be more consistent. can we fix that?
- layout: horizontal layout helper (#97)
- layout: horizontal flow until no space left (#404)
- layout: more generic alignment state (left/right/centered) for single items?
- layout: clean up the InputFloatN/SliderFloatN/ColorEdit4 layout code. item width should include frame padding.
- layout: BeginGroup() needs a border option.
- columns: declare column set (each column: fixed size, %, fill, distribute default size among fills) (#513, #125)
- columns: add a conditional parameter to SetColumnOffset() (#513, #125)
- columns: separator function or parameter that works within the column (currently Separator() bypass all columns) (#125)
- columns: columns header to act as button (~sort op) and allow resize/reorder (#513, #125)
- columns: user specify columns size (#513, #125)
- columns: flag to add horizontal separator above/below?
- columns/layout: setup minimum line height (equivalent of automatically calling AlignFirstTextHeightToWidgets)
- combo: sparse combo boxes (via function call?) / iterators
- combo: contents should extends to fit label if combo widget is small
- combo/listbox: keyboard control. need InputText-like non-active focus + key handling. considering keyboard for custom listbox (pr #203)
- listbox: multiple selection
- listbox: user may want to initial scroll to focus on the one selected value?
- listbox: keyboard navigation.
- listbox: scrolling should track modified selection.
!- popups/menus: clarify usage of popups id, how MenuItem/Selectable closing parent popups affects the ID, etc. this is quite fishy needs improvement! (#331, #402)
- popups: add variant using global identifier similar to Begin/End (#402)
- popups: border options. richer api like BeginChild() perhaps? (#197)
- tooltip: tooltip that doesn't fit in entire screen seems to lose their "last prefered button" and may teleport when moving mouse
- menus: local shortcuts, global shortcuts (#456, #126)
- menus: icons
- menus: menubars: some sort of priority / effect of main menu-bar on desktop size?
- menus: calling BeginMenu() twice with a same name doesn't seem to append nicely
- statusbar: add a per-window status bar helper similar to what menubar does.
- tabs (#261, #351)
- separator: separator on the initial position of a window is not visible (cursorpos.y <= clippos.y)
!- color: the color helpers/typing is a mess and needs sorting out.
- color: add a better color picker (#346)
- node/graph editor (#306)
- pie menus patterns (#434)
- drag'n drop, dragging helpers (carry dragging info, visualize drag source before clicking, drop target, etc.) (#143, #479)
- plot: PlotLines() should use the polygon-stroke facilities (currently issues with averaging normals)
- plot: make it easier for user to draw extra stuff into the graph (e.g: draw basis, highlight certain points, 2d plots, multiple plots)
- plot: "smooth" automatic scale over time, user give an input 0.0(full user scale) 1.0(full derived from value)
- plot: add a helper e.g. Plot(char* label, float value, float time_span=2.0f) that stores values and Plot them for you - probably another function name. and/or automatically allow to plot ANY displayed value (more reliance on stable ID)
- slider: allow using the [-]/[+] buttons used by InputFloat()/InputInt()
- slider: initial absolute click is imprecise. change to relative movement slider (same as scrollbar).
- slider: add dragging-based widgets to edit values with mouse (on 2 axises), saving screen real-estate.
- slider: tint background based on value (e.g. v_min -> v_max, or use 0.0f either side of the sign)
- slider & drag: int data passing through a float
- drag float: up/down axis
- drag float: added leeway on edge (e.g. a few invisible steps past the clamp limits)
- tree node / optimization: avoid formatting when clipped.
- tree node: tree-node/header right-most side doesn't take account of horizontal scrolling.
- tree node: add treenode/treepush int variants? not there because (void*) cast from int warns on some platforms/settings?
- tree node: try to apply scrolling at time of TreePop() if node was just opened and end of node is past scrolling limits?
- tree node / selectable render mismatch which is visible if you use them both next to each other (e.g. cf. property viewer)
- tree node: tweak color scheme to distinguish headers from selected tree node (#581)
- textwrapped: figure out better way to use TextWrapped() in an always auto-resize context (tooltip, etc.) (#249)
- settings: write more decent code to allow saving/loading new fields
- settings: api for per-tool simple persistent data (bool,int,float,columns sizes,etc.) in .ini file
- style: add window shadows.
- style/optimization: store rounded corners in texture to use 1 quad per corner (filled and wireframe) to lower the cost of rounding.
- style: color-box not always square?
- style: a concept of "compact style" that the end-user can easily rely on (e.g. PushStyleCompact()?) that maps to other settings? avoid implementing duplicate helpers such as SmallCheckbox(), etc.
- style: try to make PushStyleVar() more robust to incorrect parameters (to be more friendly to edit & continues situation).
- style/opt: PopStyleVar could be optimized by having GetStyleVar returns the type, using a table mapping stylevar enum to data type.
- style: global scale setting.
- style: WindowPadding needs to be EVEN needs the 0.5 multiplier probably have a subtle effect on clip rectangle
- text: simple markup language for color change?
- font: dynamic font atlas to avoid baking huge ranges into bitmap and make scaling easier.
- font: small opt: for monospace font (like the defalt one) we can trim IndexXAdvance as long as trailing value is == FallbackXAdvance
- font: add support for kerning, probably optional. perhaps default to (32..128)^2 matrix ~ 36KB then hash fallback.
- font: add a simpler CalcTextSizeA() api? current one ok but not welcome if user needs to call it directly (without going through ImGui::CalcTextSize)
- font: fix AddRemapChar() to work before font has been built.
- log: LogButtons() options for specifying depth and/or hiding depth slider
- log: have more control over the log scope (e.g. stop logging when leaving current tree node scope)
- log: be able to log anything (e.g. right-click on a window/tree-node, shows context menu? log into tty/file/clipboard)
- log: let user copy any window content to clipboard easily (CTRL+C on windows? while moving it? context menu?). code is commented because it fails with multiple Begin/End pairs.
- filters: set a current filter that tree node can automatically query to hide themselves
- filters: handle wildcards (with implicit leading/trailing *), regexps
- shortcuts: add a shortcut api, e.g. parse "&Save" and/or "Save (CTRL+S)", pass in to widgets or provide simple ways to use (button=activate, input=focus)
!- keyboard: tooltip & combo boxes are messing up / not honoring keyboard tabbing
- keyboard: full keyboard navigation and focus. (#323)
- focus: preserve ActiveId/focus stack state, e.g. when opening a menu and close it, previously selected InputText() focus gets restored (#622)
- focus: SetKeyboardFocusHere() on with >= 0 offset could be done on same frame (else latch and modulate on beginning of next frame)
- input: rework IO system to be able to pass actual ordered/timestamped events. (~#335, #71)
- input: allow to decide and pass explicit double-clicks (e.g. for windows by the CS_DBLCLKS style).
- input: support track pad style scrolling & slider edit.
- misc: provide a way to compile out the entire implementation while providing a dummy API (e.g. #define IMGUI_DUMMY_IMPL)
- misc: double-clicking on title bar to minimize isn't consistent, perhaps move to single-click on left-most collapse icon?
- misc: provide HoveredTime and ActivatedTime to ease the creation of animations.
- style editor: have a more global HSV setter (e.g. alter hue on all elements). consider replacing active/hovered by offset in HSV space? (#438)
- style editor: color child window height expressed in multiple of line height.
- remote: make a system like RemoteImGui first-class citizen/project (#75)
- drawlist: move Font, FontSize, FontTexUvWhitePixel inside ImDrawList and make it self-contained (apart from drawing settings?)
- drawlist: end-user probably can't call Clear() directly because we expect a texture to be pushed in the stack.
- examples: directx9: save/restore device state more thoroughly.
- examples: window minimize, maximize (#583)
- optimization: add a flag to disable most of rendering, for the case where the user expect to skip it (#335)
- optimization: use another hash function than crc32, e.g. FNV1a
- optimization/render: merge command-lists with same clip-rect into one even if they aren't sequential? (as long as in-between clip rectangle don't overlap)?
- optimization: turn some the various stack vectors into statically-sized arrays
- optimization: better clipping for multi-component widgets
*/
#include "stdafx.h"
#if defined(_MSC_VER) && !defined(_CRT_SECURE_NO_WARNINGS)
#define _CRT_SECURE_NO_WARNINGS
#endif
#include "imgui.h"
#define IMGUI_DEFINE_MATH_OPERATORS
#define IMGUI_DEFINE_PLACEMENT_NEW
#include "imgui_internal.h"
#include <ctype.h> // toupper, isprint
#include <stdlib.h> // NULL, malloc, free, qsort, atoi
#include <stdio.h> // vsnprintf, sscanf, printf
#include <limits.h> // INT_MIN, INT_MAX
#if defined(_MSC_VER) && _MSC_VER <= 1500 // MSVC 2008 or earlier
#include <stddef.h> // intptr_t
#else
#include <stdint.h> // intptr_t
#endif
#ifdef _MSC_VER
#pragma warning (disable: 4127) // condition expression is constant
#pragma warning (disable: 4505) // unreferenced local function has been removed (stb stuff)
#pragma warning (disable: 4996) // 'This function or variable may be unsafe': strcpy, strdup, sprintf, vsnprintf, sscanf, fopen
#endif
// Clang warnings with -Weverything
#ifdef __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 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 it.
#pragma clang diagnostic ignored "-Wsign-conversion" // warning : implicit conversion changes signedness //
#pragma clang diagnostic ignored "-Wint-to-void-pointer-cast" // warning : cast to 'void *' from smaller integer type 'int' //
#elif defined(__GNUC__)
#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
#endif
//-------------------------------------------------------------------------
// Forward Declarations
//-------------------------------------------------------------------------
static void LogRenderedText(const ImVec2& ref_pos, const char* text, const char* text_end = NULL);
static void PushMultiItemsWidths(int components, float w_full = 0.0f);
static float GetDraggedColumnOffset(int column_index);
static bool IsKeyPressedMap(ImGuiKey key, bool repeat = true);
static void SetCurrentFont(ImFont* font);
static void SetCurrentWindow(ImGuiWindow* window);
static void SetWindowScrollY(ImGuiWindow* window, float new_scroll_y);
static void SetWindowPos(ImGuiWindow* window, const ImVec2& pos, ImGuiSetCond cond);
static void SetWindowSize(ImGuiWindow* window, const ImVec2& size, ImGuiSetCond cond);
static void SetWindowCollapsed(ImGuiWindow* window, bool collapsed, ImGuiSetCond cond);
static ImGuiWindow* FindHoveredWindow(ImVec2 pos, bool excluding_childs);
static ImGuiWindow* CreateNewWindow(const char* name, ImVec2 size, ImGuiWindowFlags flags);
static inline bool IsWindowContentHoverable(ImGuiWindow* window);
static void ClearSetNextWindowData();
static void CheckStacksSize(ImGuiWindow* window, bool write);
static void Scrollbar(ImGuiWindow* window, bool horizontal);
static void AddDrawListToRenderList(ImVector<ImDrawList*>& out_render_list, ImDrawList* draw_list);
static void AddWindowToRenderList(ImVector<ImDrawList*>& out_render_list, ImGuiWindow* window);
static void AddWindowToSortedBuffer(ImVector<ImGuiWindow*>& out_sorted_windows, ImGuiWindow* window);
static ImGuiIniData* FindWindowSettings(const char* name);
static ImGuiIniData* AddWindowSettings(const char* name);
static void LoadSettings();
static void SaveSettings();
static void MarkSettingsDirty();
static void PushColumnClipRect(int column_index = -1);
static ImRect GetVisibleRect();
static bool BeginPopupEx(const char* str_id, ImGuiWindowFlags extra_flags);
static void CloseInactivePopups();
static void ClosePopupToLevel(int remaining);
static void ClosePopup(ImGuiID id);
static bool IsPopupOpen(ImGuiID id);
static ImGuiWindow* GetFrontMostModalRootWindow();
static ImVec2 FindBestPopupWindowPos(const ImVec2& base_pos, const ImVec2& size, int* last_dir, const ImRect& rect_to_avoid);
static bool InputTextFilterCharacter(unsigned int* p_char, ImGuiInputTextFlags flags, ImGuiTextEditCallback 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);
static inline void DataTypeFormatString(ImGuiDataType data_type, void* data_ptr, const char* display_format, char* buf, int buf_size);
static inline void DataTypeFormatString(ImGuiDataType data_type, void* data_ptr, int decimal_precision, char* buf, int buf_size);
static void DataTypeApplyOp(ImGuiDataType data_type, int op, void* value1, const void* value2);
static bool DataTypeApplyOpFromText(const char* buf, const char* initial_value_buf, ImGuiDataType data_type, void* data_ptr, const char* scalar_format);
//-----------------------------------------------------------------------------
// Platform dependent default implementations
//-----------------------------------------------------------------------------
static const char* GetClipboardTextFn_DefaultImpl();
static void SetClipboardTextFn_DefaultImpl(const char* text);
static void ImeSetInputScreenPosFn_DefaultImpl(int x, int y);
//-----------------------------------------------------------------------------
// Context
//-----------------------------------------------------------------------------
// Default context, default font atlas.
// New contexts always point by default to this font atlas. It can be changed by reassigning the GetIO().Fonts variable.
static ImGuiContext GImDefaultContext;
static ImFontAtlas GImDefaultFontAtlas;
// Current context pointer. Implicitely used by all ImGui functions. Always assumed to be != NULL. Change to a different context by calling ImGui::SetCurrentContext()
// ImGui is currently not thread-safe because of this variable. If you want thread-safety to allow N threads to access N different contexts, you might work around it by (A) having two instances of the ImGui code under different namespaces or (B) change this variable to be TLS. Further development aim to make this context pointer explicit to all calls. Also read https://github.com/ocornut/imgui/issues/586
ImGuiContext* GImGui = &GImDefaultContext;
//-----------------------------------------------------------------------------
// User facing structures
//-----------------------------------------------------------------------------
ImGuiStyle::ImGuiStyle()
{
Alpha = 1.0f; // Global alpha applies to everything in ImGui
WindowPadding = ImVec2(8,8); // Padding within a window
WindowMinSize = ImVec2(32,32); // Minimum window size
WindowRounding = 9.0f; // Radius of window corners rounding. Set to 0.0f to have rectangular windows
WindowTitleAlign = ImGuiAlign_Left; // Alignment for title bar text
ChildWindowRounding = 0.0f; // Radius of child window corners rounding. Set to 0.0f to have rectangular child windows
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).
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
ScrollbarSize = 16.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.
DisplayWindowPadding = ImVec2(22,22); // Window positions are clamped to be visible within the display area by at least this amount. Only covers regular windows.
DisplaySafeAreaPadding = ImVec2(4,4); // 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.
AntiAliasedLines = true; // Enable anti-aliasing on lines/borders. Disable if you are really short on CPU/GPU.
AntiAliasedShapes = true; // Enable anti-aliasing on filled shapes (rounded rectangles, circles, etc.)
CurveTessellationTol = 1.25f; // Tessellation tolerance. Decrease for highly tessellated curves (higher quality, more polygons), increase to reduce quality.
Colors[ImGuiCol_Text] = ImVec4(0.90f, 0.90f, 0.90f, 1.00f);
Colors[ImGuiCol_TextDisabled] = ImVec4(0.60f, 0.60f, 0.60f, 1.00f);
Colors[ImGuiCol_WindowBg] = ImVec4(0.00f, 0.00f, 0.00f, 0.70f);
Colors[ImGuiCol_ChildWindowBg] = ImVec4(0.00f, 0.00f, 0.00f, 0.00f);
Colors[ImGuiCol_PopupBg] = ImVec4(0.05f, 0.05f, 0.10f, 0.90f);
Colors[ImGuiCol_Border] = ImVec4(0.70f, 0.70f, 0.70f, 0.65f);
Colors[ImGuiCol_BorderShadow] = ImVec4(0.00f, 0.00f, 0.00f, 0.00f);
Colors[ImGuiCol_FrameBg] = ImVec4(0.80f, 0.80f, 0.80f, 0.30f); // Background of checkbox, radio button, plot, slider, text input
Colors[ImGuiCol_FrameBgHovered] = ImVec4(0.90f, 0.80f, 0.80f, 0.40f);
Colors[ImGuiCol_FrameBgActive] = ImVec4(0.90f, 0.65f, 0.65f, 0.45f);
Colors[ImGuiCol_TitleBg] = ImVec4(0.27f, 0.27f, 0.54f, 0.83f);
Colors[ImGuiCol_TitleBgCollapsed] = ImVec4(0.40f, 0.40f, 0.80f, 0.20f);
Colors[ImGuiCol_TitleBgActive] = ImVec4(0.32f, 0.32f, 0.63f, 0.87f);
Colors[ImGuiCol_MenuBarBg] = ImVec4(0.40f, 0.40f, 0.55f, 0.80f);
Colors[ImGuiCol_ScrollbarBg] = ImVec4(0.20f, 0.25f, 0.30f, 0.60f);
Colors[ImGuiCol_ScrollbarGrab] = ImVec4(0.40f, 0.40f, 0.80f, 0.30f);
Colors[ImGuiCol_ScrollbarGrabHovered] = ImVec4(0.40f, 0.40f, 0.80f, 0.40f);
Colors[ImGuiCol_ScrollbarGrabActive] = ImVec4(0.80f, 0.50f, 0.50f, 0.40f);
Colors[ImGuiCol_ComboBg] = ImVec4(0.20f, 0.20f, 0.20f, 0.99f);
Colors[ImGuiCol_CheckMark] = ImVec4(0.90f, 0.90f, 0.90f, 0.50f);
Colors[ImGuiCol_SliderGrab] = ImVec4(1.00f, 1.00f, 1.00f, 0.30f);
Colors[ImGuiCol_SliderGrabActive] = ImVec4(0.80f, 0.50f, 0.50f, 1.00f);
Colors[ImGuiCol_Button] = ImVec4(0.67f, 0.40f, 0.40f, 0.60f);
Colors[ImGuiCol_ButtonHovered] = ImVec4(0.67f, 0.40f, 0.40f, 1.00f);
Colors[ImGuiCol_ButtonActive] = ImVec4(0.80f, 0.50f, 0.50f, 1.00f);
Colors[ImGuiCol_Header] = ImVec4(0.40f, 0.40f, 0.90f, 0.45f);
Colors[ImGuiCol_HeaderHovered] = ImVec4(0.45f, 0.45f, 0.90f, 0.80f);
Colors[ImGuiCol_HeaderActive] = ImVec4(0.53f, 0.53f, 0.87f, 0.80f);
Colors[ImGuiCol_Column] = ImVec4(0.50f, 0.50f, 0.50f, 1.00f);
Colors[ImGuiCol_ColumnHovered] = ImVec4(0.70f, 0.60f, 0.60f, 1.00f);
Colors[ImGuiCol_ColumnActive] = ImVec4(0.90f, 0.70f, 0.70f, 1.00f);
Colors[ImGuiCol_ResizeGrip] = ImVec4(1.00f, 1.00f, 1.00f, 0.30f);
Colors[ImGuiCol_ResizeGripHovered] = ImVec4(1.00f, 1.00f, 1.00f, 0.60f);
Colors[ImGuiCol_ResizeGripActive] = ImVec4(1.00f, 1.00f, 1.00f, 0.90f);
Colors[ImGuiCol_CloseButton] = ImVec4(0.50f, 0.50f, 0.90f, 0.50f);
Colors[ImGuiCol_CloseButtonHovered] = ImVec4(0.70f, 0.70f, 0.90f, 0.60f);
Colors[ImGuiCol_CloseButtonActive] = ImVec4(0.70f, 0.70f, 0.70f, 1.00f);
Colors[ImGuiCol_PlotLines] = ImVec4(1.00f, 1.00f, 1.00f, 1.00f);
Colors[ImGuiCol_PlotLinesHovered] = ImVec4(0.90f, 0.70f, 0.00f, 1.00f);
Colors[ImGuiCol_PlotHistogram] = ImVec4(0.90f, 0.70f, 0.00f, 1.00f);
Colors[ImGuiCol_PlotHistogramHovered] = ImVec4(1.00f, 0.60f, 0.00f, 1.00f);
Colors[ImGuiCol_TextSelectedBg] = ImVec4(0.00f, 0.00f, 1.00f, 0.35f);
Colors[ImGuiCol_ModalWindowDarkening] = ImVec4(0.20f, 0.20f, 0.20f, 0.35f);
}
ImGuiIO::ImGuiIO()
{
// Most fields are initialized with zero
memset(this, 0, sizeof(*this));
DisplaySize = ImVec2(-1.0f, -1.0f);
DeltaTime = 1.0f/60.0f;
IniSavingRate = 5.0f;
IniFilename = "imgui.ini";
LogFilename = "imgui_log.txt";
Fonts = &GImDefaultFontAtlas;
FontGlobalScale = 1.0f;
DisplayFramebufferScale = ImVec2(1.0f, 1.0f);
MousePos = ImVec2(-1,-1);
MousePosPrev = ImVec2(-1,-1);
MouseDoubleClickTime = 0.30f;
MouseDoubleClickMaxDist = 6.0f;
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 < ImGuiKey_COUNT; i++)
KeyMap[i] = -1;
KeyRepeatDelay = 0.250f;
KeyRepeatRate = 0.050f;
UserData = NULL;
// User functions
RenderDrawListsFn = NULL;
MemAllocFn = malloc;
MemFreeFn = free;
GetClipboardTextFn = GetClipboardTextFn_DefaultImpl; // Platform dependent default implementations
SetClipboardTextFn = SetClipboardTextFn_DefaultImpl;
ImeSetInputScreenPosFn = ImeSetInputScreenPosFn_DefaultImpl;
// Set OS X style defaults based on __APPLE__ compile time flag
#ifdef __APPLE__
OSXBehaviors = true;
#endif
}
// 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(ImWchar c)
{
const int n = ImStrlenW(InputCharacters);
if (n + 1 < IM_ARRAYSIZE(InputCharacters))
{
InputCharacters[n] = c;
InputCharacters[n+1] = '\0';
}
}
void ImGuiIO::AddInputCharactersUTF8(const char* utf8_chars)
{
// We can't pass more wchars than ImGuiIO::InputCharacters[] can hold so don't convert more
const int wchars_buf_len = sizeof(ImGuiIO::InputCharacters) / sizeof(ImWchar);
ImWchar wchars[wchars_buf_len];
ImTextStrFromUtf8(wchars, wchars_buf_len, utf8_chars, NULL);
for (int i = 0; i < wchars_buf_len && wchars[i] != 0; i++)
AddInputCharacter(wchars[i]);
}
//-----------------------------------------------------------------------------
// HELPERS
//-----------------------------------------------------------------------------
#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
// Play it nice with Windows users. Notepad in 2015 still doesn't display text data with Unix-style \n.
#ifdef _WIN32
#define IM_NEWLINE "\r\n"
#else
#define IM_NEWLINE "\n"
#endif
bool ImIsPointInTriangle(const ImVec2& p, const ImVec2& a, const ImVec2& b, const ImVec2& c)
{
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));
}
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, int 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, int count)
{
if (count < 1) return;
strncpy(dst, src, (size_t)count);
dst[count-1] = 0;
}
char* ImStrdup(const char *str)
{
size_t len = strlen(str) + 1;
void* buff = ImGui::MemAlloc(len);
return (char*)memcpy(buff, (const void*)str, len);
}
int ImStrlenW(const ImWchar* str)
{
int n = 0;
while (*str++) n++;
return n;
}
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;
}
int ImFormatString(char* buf, int buf_size, const char* fmt, ...)
{
va_list args;
va_start(args, fmt);
int w = vsnprintf(buf, buf_size, fmt, args);
va_end(args);
buf[buf_size-1] = 0;
return (w == -1) ? buf_size : w;
}
int ImFormatStringV(char* buf, int buf_size, const char* fmt, va_list args)
{
int w = vsnprintf(buf, buf_size, fmt, args);
buf[buf_size-1] = 0;
return (w == -1) ? buf_size : w;
}
// Pass data_size==0 for zero-terminated strings
// FIXME-OPT: Replace with e.g. FNV1a hash? CRC32 pretty much randomly access 1KB. Need to do proper measurements.
ImU32 ImHash(const void* data, int data_size, ImU32 seed)
{
static ImU32 crc32_lut[256] = { 0 };
if (!crc32_lut[1])
{
const ImU32 polynomial = 0xEDB88320;
for (ImU32 i = 0; i < 256; i++)
{
ImU32 crc = i;
for (ImU32 j = 0; j < 8; j++)
crc = (crc >> 1) ^ (ImU32(-int(crc & 1)) & polynomial);
crc32_lut[i] = crc;
}
}
seed = ~seed;
ImU32 crc = seed;
const unsigned char* current = (const unsigned char*)data;
if (data_size > 0)
{
// Known size
while (data_size--)
crc = (crc >> 8) ^ crc32_lut[(crc & 0xFF) ^ *current++];
}
else
{
// Zero-terminated string
while (unsigned char c = *current++)
{
// 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.
if (c == '#' && current[0] == '#' && current[1] == '#')
crc = seed;
crc = (crc >> 8) ^ crc32_lut[(crc & 0xFF) ^ c];
}
}
return ~crc;
}
//-----------------------------------------------------------------------------
// ImText* helpers
//-----------------------------------------------------------------------------
// 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;
}
}
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;
}
ImVec4 ImGui::ColorConvertU32ToFloat4(ImU32 in)
{
float s = 1.0f/255.0f;
return ImVec4((in & 0xFF) * s, ((in >> 8) & 0xFF) * s, ((in >> 16) & 0xFF) * s, (in >> 24) * s);
}
ImU32 ImGui::ColorConvertFloat4ToU32(const ImVec4& in)
{
ImU32 out;
out = ((ImU32)IM_F32_TO_INT8_SAT(in.x));
out |= ((ImU32)IM_F32_TO_INT8_SAT(in.y)) << 8;
out |= ((ImU32)IM_F32_TO_INT8_SAT(in.z)) << 16;
out |= ((ImU32)IM_F32_TO_INT8_SAT(in.w)) << 24;
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)
{
const float tmp = g; g = b; b = tmp;
K = -1.f;
}
if (r < g)
{
const float tmp = r; r = g; g = tmp;
K = -2.f / 6.f - K;
}
const float chroma = r - (g < b ? g : b);
out_h = fabsf(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 = fmodf(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;
}
}
// Load file content into memory
// Memory allocated with ImGui::MemAlloc(), must be freed by user using ImGui::MemFree()
void* ImLoadFileToMemory(const char* filename, const char* file_open_mode, int* out_file_size, int padding_bytes)
{
IM_ASSERT(filename && file_open_mode);
if (out_file_size)
*out_file_size = 0;
FILE* f;
if ((f = fopen(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;
}
int file_size = (int)file_size_signed;
void* file_data = ImGui::MemAlloc(file_size + padding_bytes);
if (file_data == NULL)
{
fclose(f);
return NULL;
}
if (fread(file_data, 1, (size_t)file_size, f) != (size_t)file_size)
{
fclose(f);
ImGui::MemFree(file_data);
return NULL;
}
if (padding_bytes > 0)
memset((void *)(((char*)file_data) + file_size), 0, padding_bytes);
fclose(f);
if (out_file_size)
*out_file_size = file_size;
return file_data;
}
//-----------------------------------------------------------------------------
// ImGuiStorage
//-----------------------------------------------------------------------------
// Helper: Key->value storage
void ImGuiStorage::Clear()
{
Data.clear();
}
// std::lower_bound but without the bullshit
static ImVector<ImGuiStorage::Pair>::iterator LowerBound(ImVector<ImGuiStorage::Pair>& data, ImGuiID key)
{
ImVector<ImGuiStorage::Pair>::iterator first = data.begin();
ImVector<ImGuiStorage::Pair>::iterator last = data.end();
int count = (int)(last - first);
while (count > 0)
{
int count2 = count / 2;
ImVector<ImGuiStorage::Pair>::iterator mid = first + count2;
if (mid->key < key)
{
first = ++mid;
count -= count2 + 1;
}
else
{
count = count2;
}
}
return first;
}
int ImGuiStorage::GetInt(ImGuiID key, int default_val) const
{
ImVector<Pair>::iterator it = LowerBound(const_cast<ImVector<ImGuiStorage::Pair>&>(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
{
ImVector<Pair>::iterator it = LowerBound(const_cast<ImVector<ImGuiStorage::Pair>&>(Data), key);
if (it == Data.end() || it->key != key)
return default_val;
return it->val_f;
}
void* ImGuiStorage::GetVoidPtr(ImGuiID key) const
{
ImVector<Pair>::iterator it = LowerBound(const_cast<ImVector<ImGuiStorage::Pair>&>(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)
{
ImVector<Pair>::iterator it = LowerBound(Data, key);
if (it == Data.end() || it->key != key)
it = Data.insert(it, Pair(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)
{
ImVector<Pair>::iterator it = LowerBound(Data, key);
if (it == Data.end() || it->key != key)
it = Data.insert(it, Pair(key, default_val));
return &it->val_f;
}
void** ImGuiStorage::GetVoidPtrRef(ImGuiID key, void* default_val)
{
ImVector<Pair>::iterator it = LowerBound(Data, key);
if (it == Data.end() || it->key != key)
it = Data.insert(it, Pair(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)
{
ImVector<Pair>::iterator it = LowerBound(Data, key);
if (it == Data.end() || it->key != key)
{
Data.insert(it, Pair(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)
{
ImVector<Pair>::iterator it = LowerBound(Data, key);
if (it == Data.end() || it->key != key)
{
Data.insert(it, Pair(key, val));
return;
}
it->val_f = val;
}
void ImGuiStorage::SetVoidPtr(ImGuiID key, void* val)
{
ImVector<Pair>::iterator it = LowerBound(Data, key);
if (it == Data.end() || it->key != key)
{
Data.insert(it, Pair(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;
}
//-----------------------------------------------------------------------------
// 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::PushItemWidth(width);
bool value_changed = ImGui::InputText(label, InputBuf, IM_ARRAYSIZE(InputBuf));
if (width != 0.0f)
ImGui::PopItemWidth();
if (value_changed)
Build();
return value_changed;
}
void ImGuiTextFilter::TextRange::split(char separator, ImVector<TextRange>& out)
{
out.resize(0);
const char* wb = b;
const char* we = wb;
while (we < e)
{
if (*we == separator)
{
out.push_back(TextRange(wb, we));
wb = we + 1;
}
we++;
}
if (wb != we)
out.push_back(TextRange(wb, we));
}
void ImGuiTextFilter::Build()
{
Filters.resize(0);
TextRange input_range(InputBuf, InputBuf+strlen(InputBuf));
input_range.split(',', Filters);
CountGrep = 0;
for (int i = 0; i != Filters.Size; i++)
{
Filters[i].trim_blanks();
if (Filters[i].empty())
continue;
if (Filters[i].front() != '-')
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 TextRange& f = Filters[i];
if (f.empty())
continue;
if (f.front() == '-')
{
// Subtract
if (ImStristr(text, text_end, f.begin()+1, f.end()) != NULL)
return false;
}
else
{
// Grep
if (ImStristr(text, text_end, f.begin(), f.end()) != NULL)
return true;
}
}
// Implicit * grep
if (CountGrep == 0)
return true;
return false;
}
//-----------------------------------------------------------------------------
// 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
#define va_copy(dest, src) (dest = src)
#endif
// Helper: Text buffer for logging/accumulating text
void ImGuiTextBuffer::appendv(const char* fmt, va_list args)
{
va_list args_copy;
va_copy(args_copy, args);
int len = vsnprintf(NULL, 0, fmt, args); // FIXME-OPT: could do a first pass write attempt, likely successful on first pass.
if (len <= 0)
return;
const int write_off = Buf.Size;
const int needed_sz = write_off + len;
if (write_off + len >= Buf.Capacity)
{
int double_capacity = Buf.Capacity * 2;
Buf.reserve(needed_sz > double_capacity ? needed_sz : double_capacity);
}
Buf.resize(needed_sz);
ImFormatStringV(&Buf[write_off] - 1, len+1, fmt, args_copy);
}
void ImGuiTextBuffer::append(const char* fmt, ...)
{
va_list args;
va_start(args, fmt);
appendv(fmt, args);
va_end(args);
}
//-----------------------------------------------------------------------------
// ImGuiSimpleColumns
//-----------------------------------------------------------------------------
ImGuiSimpleColumns::ImGuiSimpleColumns()
{
Count = 0;
Spacing = Width = NextWidth = 0.0f;
memset(Pos, 0, sizeof(Pos));
memset(NextWidths, 0, sizeof(NextWidths));
}
void ImGuiSimpleColumns::Update(int count, float spacing, bool clear)
{
IM_ASSERT(Count <= IM_ARRAYSIZE(Pos));
Count = count;
Width = NextWidth = 0.0f;
Spacing = spacing;
if (clear) memset(NextWidths, 0, sizeof(NextWidths));
for (int i = 0; i < Count; i++)
{
if (i > 0 && NextWidths[i] > 0.0f)
Width += Spacing;
Pos[i] = (float)(int)Width;
Width += NextWidths[i];
NextWidths[i] = 0.0f;
}
}
float ImGuiSimpleColumns::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 < 3; i++)
NextWidth += NextWidths[i] + ((i > 0 && NextWidths[i] > 0.0f) ? Spacing : 0.0f);
return ImMax(Width, NextWidth);
}
float ImGuiSimpleColumns::CalcExtraSpace(float avail_w)
{
return ImMax(0.0f, avail_w - Width);
}
//-----------------------------------------------------------------------------
// ImGuiListClipper
//-----------------------------------------------------------------------------
static void SetCursorPosYAndSetupDummyPrevLine(float pos_y, float line_height)
{
// Set cursor position and a few other things so that SetScrollHere() 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. Consider moving within SetCursorXXX functions?
ImGui::SetCursorPosY(pos_y);
ImGuiWindow* window = ImGui::GetCurrentWindow();
window->DC.CursorPosPrevLine.y = window->DC.CursorPos.y - line_height; // Setting those fields so that SetScrollHere() can properly function after the end of our clipper usage.
window->DC.PrevLineHeight = (line_height - GImGui->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 (window->DC.ColumnsCount > 1)
window->DC.ColumnsCellMinY = 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)
{
StartPosY = ImGui::GetCursorPosY();
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()
{
if (ItemsCount == 0 || ImGui::GetCurrentWindowRead()->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 = ImGui::GetCursorPosY();
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 = ImGui::GetCursorPosY() - 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;
}
//-----------------------------------------------------------------------------
// ImGuiWindow
//-----------------------------------------------------------------------------
ImGuiWindow::ImGuiWindow(const char* name)
{
Name = ImStrdup(name);
ID = ImHash(name, 0);
IDStack.push_back(ID);
MoveId = GetID("#MOVE");
Flags = 0;
IndexWithinParent = 0;
PosFloat = Pos = ImVec2(0.0f, 0.0f);
Size = SizeFull = ImVec2(0.0f, 0.0f);
SizeContents = SizeContentsExplicit = ImVec2(0.0f, 0.0f);
WindowPadding = ImVec2(0.0f, 0.0f);
Scroll = ImVec2(0.0f, 0.0f);
ScrollTarget = ImVec2(FLT_MAX, FLT_MAX);
ScrollTargetCenterRatio = ImVec2(0.5f, 0.5f);
ScrollbarX = ScrollbarY = false;
ScrollbarSizes = ImVec2(0.0f, 0.0f);
BorderSize = 0.0f;
Active = WasActive = false;
Accessed = false;
Collapsed = false;
SkipItems = false;
BeginCount = 0;
PopupId = 0;
AutoFitFramesX = AutoFitFramesY = -1;
AutoFitOnlyGrows = false;
AutoPosLastDirection = -1;
HiddenFrames = 0;
SetWindowPosAllowFlags = SetWindowSizeAllowFlags = SetWindowCollapsedAllowFlags = ImGuiSetCond_Always | ImGuiSetCond_Once | ImGuiSetCond_FirstUseEver | ImGuiSetCond_Appearing;
SetWindowPosCenterWanted = false;
LastFrameActive = -1;
ItemWidthDefault = 0.0f;
FontWindowScale = 1.0f;
DrawList = (ImDrawList*)ImGui::MemAlloc(sizeof(ImDrawList));
IM_PLACEMENT_NEW(DrawList) ImDrawList();
DrawList->_OwnerName = Name;
RootWindow = NULL;
RootNonPopupWindow = NULL;
ParentWindow = NULL;
FocusIdxAllCounter = FocusIdxTabCounter = -1;
FocusIdxAllRequestCurrent = FocusIdxTabRequestCurrent = INT_MAX;
FocusIdxAllRequestNext = FocusIdxTabRequestNext = INT_MAX;
}
ImGuiWindow::~ImGuiWindow()
{
DrawList->~ImDrawList();
ImGui::MemFree(DrawList);
DrawList = NULL;
ImGui::MemFree(Name);
Name = NULL;
}
ImGuiID ImGuiWindow::GetID(const char* str, const char* str_end)
{
ImGuiID seed = IDStack.back();
ImGuiID id = ImHash(str, str_end ? (int)(str_end - str) : 0, seed);
ImGui::KeepAliveID(id);
return id;
}
ImGuiID ImGuiWindow::GetID(const void* ptr)
{
ImGuiID seed = IDStack.back();
ImGuiID id = ImHash(&ptr, sizeof(void*), seed);
ImGui::KeepAliveID(id);
return id;
}
ImGuiID ImGuiWindow::GetIDNoKeepAlive(const char* str, const char* str_end)
{
ImGuiID seed = IDStack.back();
return ImHash(str, str_end ? (int)(str_end - str) : 0, seed);
}
//-----------------------------------------------------------------------------
// Internal API exposed in imgui_internal.h
//-----------------------------------------------------------------------------
static void SetCurrentWindow(ImGuiWindow* window)
{
ImGuiContext& g = *GImGui;
g.CurrentWindow = window;
if (window)
g.FontSize = window->CalcFontSize();
}
ImGuiWindow* ImGui::GetParentWindow()
{
ImGuiContext& g = *GImGui;
IM_ASSERT(g.CurrentWindowStack.Size >= 2);
return g.CurrentWindowStack[(unsigned int)g.CurrentWindowStack.Size - 2];
}
void ImGui::SetActiveID(ImGuiID id, ImGuiWindow* window = NULL)
{
ImGuiContext& g = *GImGui;
g.ActiveId = id;
g.ActiveIdAllowOverlap = false;
g.ActiveIdIsJustActivated = true;
g.ActiveIdWindow = window;
}
void ImGui::SetHoveredID(ImGuiID id)
{
ImGuiContext& g = *GImGui;
g.HoveredId = id;
g.HoveredIdAllowOverlap = false;
}
void ImGui::KeepAliveID(ImGuiID id)
{
ImGuiContext& g = *GImGui;
if (g.ActiveId == id)
g.ActiveIdIsAlive = true;
}
// Advance cursor given item size for layout.
void ImGui::ItemSize(const ImVec2& size, float text_offset_y)
{
ImGuiWindow* window = GetCurrentWindow();
if (window->SkipItems)
return;
// Always align ourselves on pixel boundaries
ImGuiContext& g = *GImGui;
const float line_height = ImMax(window->DC.CurrentLineHeight, size.y);
const float text_base_offset = ImMax(window->DC.CurrentLineTextBaseOffset, text_offset_y);
window->DC.CursorPosPrevLine = ImVec2(window->DC.CursorPos.x + size.x, window->DC.CursorPos.y);
window->DC.CursorPos = ImVec2((float)(int)(window->Pos.x + window->DC.IndentX + window->DC.ColumnsOffsetX), (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);
//window->DrawList->AddCircle(window->DC.CursorMaxPos, 3.0f, 0xFF0000FF, 4); // Debug
window->DC.PrevLineHeight = line_height;
window->DC.PrevLineTextBaseOffset = text_base_offset;
window->DC.CurrentLineHeight = window->DC.CurrentLineTextBaseOffset = 0.0f;
}
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
// declares 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, const ImGuiID* id)
{
ImGuiWindow* window = GetCurrentWindow();
window->DC.LastItemId = id ? *id : 0;
window->DC.LastItemRect = bb;
window->DC.LastItemHoveredAndUsable = window->DC.LastItemHoveredRect = false;
if (IsClippedEx(bb, id, false))
return false;
// This is a sensible default, but widgets are free to override it after calling ItemAdd()
ImGuiContext& g = *GImGui;
if (IsMouseHoveringRect(bb.Min, bb.Max))
{
// Matching the behavior of IsHovered() but allow if ActiveId==window->MoveID (we clicked on the window background)
// So that clicking on items with no active id such as Text() still returns true with IsItemHovered()
window->DC.LastItemHoveredRect = true;
if (g.HoveredRootWindow == window->RootWindow)
if (g.ActiveId == 0 || (id && g.ActiveId == *id) || g.ActiveIdAllowOverlap || (g.ActiveId == window->MoveId))
if (IsWindowContentHoverable(window))
window->DC.LastItemHoveredAndUsable = true;
}
return true;
}
bool ImGui::IsClippedEx(const ImRect& bb, const ImGuiID* id, bool clip_even_when_logged)
{
ImGuiContext& g = *GImGui;
ImGuiWindow* window = GetCurrentWindowRead();
if (!bb.Overlaps(window->ClipRect))
if (!id || *id != GImGui->ActiveId)
if (clip_even_when_logged || !g.LogEnabled)
return true;
return false;
}
// NB: This is an internal helper. The user-facing IsItemHovered() is using data emitted from ItemAdd(), with a slightly different logic.
bool ImGui::IsHovered(const ImRect& bb, ImGuiID id, bool flatten_childs)
{
ImGuiContext& g = *GImGui;
if (g.HoveredId == 0 || g.HoveredId == id || g.HoveredIdAllowOverlap)
{
ImGuiWindow* window = GetCurrentWindowRead();
if (g.HoveredWindow == window || (flatten_childs && g.HoveredRootWindow == window->RootWindow))
if ((g.ActiveId == 0 || g.ActiveId == id || g.ActiveIdAllowOverlap) && IsMouseHoveringRect(bb.Min, bb.Max))
if (IsWindowContentHoverable(g.HoveredRootWindow))
return true;
}
return false;
}
bool ImGui::FocusableItemRegister(ImGuiWindow* window, bool is_active, bool tab_stop)
{
ImGuiContext& g = *GImGui;
const bool allow_keyboard_focus = window->DC.AllowKeyboardFocus;
window->FocusIdxAllCounter++;
if (allow_keyboard_focus)
window->FocusIdxTabCounter++;
// Process keyboard input at this point: TAB, Shift-TAB switch focus
// We can always TAB out of a widget that doesn't allow tabbing in.
if (tab_stop && window->FocusIdxAllRequestNext == INT_MAX && window->FocusIdxTabRequestNext == INT_MAX && is_active && IsKeyPressedMap(ImGuiKey_Tab))
{
// Modulo on index will be applied at the end of frame once we've got the total counter of items.
window->FocusIdxTabRequestNext = window->FocusIdxTabCounter + (g.IO.KeyShift ? (allow_keyboard_focus ? -1 : 0) : +1);
}
if (window->FocusIdxAllCounter == window->FocusIdxAllRequestCurrent)
return true;
if (allow_keyboard_focus)
if (window->FocusIdxTabCounter == window->FocusIdxTabRequestCurrent)
return true;
return false;
}
void ImGui::FocusableItemUnregister(ImGuiWindow* window)
{
window->FocusIdxAllCounter--;
window->FocusIdxTabCounter--;
}
ImVec2 ImGui::CalcItemSize(ImVec2 size, float default_x, float default_y)
{
ImGuiContext& g = *GImGui;
ImVec2 content_max;
if (size.x < 0.0f || size.y < 0.0f)
content_max = g.CurrentWindow->Pos + GetContentRegionMax();
if (size.x <= 0.0f)
size.x = (size.x == 0.0f) ? default_x : ImMax(content_max.x - g.CurrentWindow->DC.CursorPos.x, 4.0f) + size.x;
if (size.y <= 0.0f)
size.y = (size.y == 0.0f) ? default_y : ImMax(content_max.y - g.CurrentWindow->DC.CursorPos.y, 4.0f) + size.y;
return size;
}
float ImGui::CalcWrapWidthForPos(const ImVec2& pos, float wrap_pos_x)
{
if (wrap_pos_x < 0.0f)
return 0.0f;
ImGuiWindow* window = GetCurrentWindowRead();
if (wrap_pos_x == 0.0f)
wrap_pos_x = GetContentRegionMax().x + window->Pos.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);
}
//-----------------------------------------------------------------------------
void* ImGui::MemAlloc(size_t sz)
{
GImGui->IO.MetricsAllocs++;
return GImGui->IO.MemAllocFn(sz);
}
void ImGui::MemFree(void* ptr)
{
if (ptr) GImGui->IO.MetricsAllocs--;
return GImGui->IO.MemFreeFn(ptr);
}
const char* ImGui::GetClipboardText()
{
return GImGui->IO.GetClipboardTextFn ? GImGui->IO.GetClipboardTextFn() : "";
}
void ImGui::SetClipboardText(const char* text)
{
if (GImGui->IO.SetClipboardTextFn)
GImGui->IO.SetClipboardTextFn(text);
}
const char* ImGui::GetVersion()
{
return IMGUI_VERSION;
}
// Internal state access - if you want to share 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)
{
GImGui = ctx;
}
ImGuiContext* ImGui::CreateContext(void* (*malloc_fn)(size_t), void (*free_fn)(void*))
{
if (!malloc_fn) malloc_fn = malloc;
ImGuiContext* ctx = (ImGuiContext*)malloc_fn(sizeof(ImGuiContext));
IM_PLACEMENT_NEW(ctx) ImGuiContext();
ctx->IO.MemAllocFn = malloc_fn;
ctx->IO.MemFreeFn = free_fn ? free_fn : free;
return ctx;
}
void ImGui::DestroyContext(ImGuiContext* ctx)
{
void (*free_fn)(void*) = ctx->IO.MemFreeFn;
ctx->~ImGuiContext();
free_fn(ctx);
if (GImGui == ctx)
GImGui = NULL;
}
ImGuiIO& ImGui::GetIO()
{
return GImGui->IO;
}
ImGuiStyle& ImGui::GetStyle()
{
return GImGui->Style;
}
// Same value as passed to your RenderDrawListsFn() function. valid after Render() and until the next call to NewFrame()
ImDrawData* ImGui::GetDrawData()
{
return GImGui->RenderDrawData.Valid ? &GImGui->RenderDrawData : NULL;
}
float ImGui::GetTime()
{
return GImGui->Time;
}
int ImGui::GetFrameCount()
{
return GImGui->FrameCount;
}
void ImGui::NewFrame()
{
ImGuiContext& g = *GImGui;
// Check user data
IM_ASSERT(g.IO.DeltaTime >= 0.0f); // Need a positive DeltaTime (zero is tolerated but will cause some timing issues)
IM_ASSERT(g.IO.DisplaySize.x >= 0.0f && g.IO.DisplaySize.y >= 0.0f);
IM_ASSERT(g.IO.Fonts->Fonts.Size > 0); // Font Atlas not created. Did you call io.Fonts->GetTexDataAsRGBA32 / GetTexDataAsAlpha8 ?
IM_ASSERT(g.IO.Fonts->Fonts[0]->IsLoaded()); // Font Atlas not created. Did you call io.Fonts->GetTexDataAsRGBA32 / GetTexDataAsAlpha8 ?
IM_ASSERT(g.Style.CurveTessellationTol > 0.0f); // Invalid style setting
if (!g.Initialized)
{
// Initialize on first frame
g.LogClipboard = (ImGuiTextBuffer*)ImGui::MemAlloc(sizeof(ImGuiTextBuffer));
IM_PLACEMENT_NEW(g.LogClipboard) ImGuiTextBuffer();
IM_ASSERT(g.Settings.empty());
LoadSettings();
g.Initialized = true;
}
SetCurrentFont(g.IO.Fonts->Fonts[0]);
g.Time += g.IO.DeltaTime;
g.FrameCount += 1;
g.Tooltip[0] = '\0';
g.OverlayDrawList.Clear();
g.OverlayDrawList.PushTextureID(g.IO.Fonts->TexID);
g.OverlayDrawList.PushClipRectFullScreen();
// Mark rendering data as invalid to prevent user who may have a handle on it to use it
g.RenderDrawData.Valid = false;
g.RenderDrawData.CmdLists = NULL;
g.RenderDrawData.CmdListsCount = g.RenderDrawData.TotalVtxCount = g.RenderDrawData.TotalIdxCount = 0;
// Update inputs state
if (g.IO.MousePos.x < 0 && g.IO.MousePos.y < 0)
g.IO.MousePos = ImVec2(-9999.0f, -9999.0f);
if ((g.IO.MousePos.x < 0 && g.IO.MousePos.y < 0) || (g.IO.MousePosPrev.x < 0 && g.IO.MousePosPrev.y < 0)) // if mouse just appeared or disappeared (negative coordinate) we cancel out movement in MouseDelta
g.IO.MouseDelta = ImVec2(0.0f, 0.0f);
else
g.IO.MouseDelta = g.IO.MousePos - g.IO.MousePosPrev;
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 (g.Time - g.IO.MouseClickedTime[i] < g.IO.MouseDoubleClickTime)
{
if (ImLengthSqr(g.IO.MousePos - g.IO.MouseClickedPos[i]) < 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.MouseDragMaxDistanceSqr[i] = 0.0f;
}
else if (g.IO.MouseDown[i])
{
g.IO.MouseDragMaxDistanceSqr[i] = ImMax(g.IO.MouseDragMaxDistanceSqr[i], ImLengthSqr(g.IO.MousePos - g.IO.MouseClickedPos[i]));
}
}
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;
// 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 = 1.0f / (g.FramerateSecPerFrameAccum / (float)IM_ARRAYSIZE(g.FramerateSecPerFrame));
// Clear reference to active widget if the widget isn't alive anymore
g.HoveredIdPreviousFrame = g.HoveredId;
g.HoveredId = 0;
g.HoveredIdAllowOverlap = false;
if (!g.ActiveIdIsAlive && g.ActiveIdPreviousFrame == g.ActiveId && g.ActiveId != 0)
SetActiveID(0);
g.ActiveIdPreviousFrame = g.ActiveId;
g.ActiveIdIsAlive = false;
g.ActiveIdIsJustActivated = false;
// Handle user moving window (at the beginning of the frame to avoid input lag or sheering). Only valid for root windows.
if (g.MovedWindowMoveId && g.MovedWindowMoveId == g.ActiveId)
{
KeepAliveID(g.MovedWindowMoveId);
IM_ASSERT(g.MovedWindow && g.MovedWindow->RootWindow);
IM_ASSERT(g.MovedWindow->RootWindow->MoveId == g.MovedWindowMoveId);
if (g.IO.MouseDown[0])
{
if (!(g.MovedWindow->Flags & ImGuiWindowFlags_NoMove))
{
g.MovedWindow->PosFloat += g.IO.MouseDelta;
if (!(g.MovedWindow->Flags & ImGuiWindowFlags_NoSavedSettings))
MarkSettingsDirty();
}
FocusWindow(g.MovedWindow);
}
else
{
SetActiveID(0);
g.MovedWindow = NULL;
g.MovedWindowMoveId = 0;
}
}
else
{
g.MovedWindow = NULL;
g.MovedWindowMoveId = 0;
}
// Delay saving settings so we don't spam disk too much
if (g.SettingsDirtyTimer > 0.0f)
{
g.SettingsDirtyTimer -= g.IO.DeltaTime;
if (g.SettingsDirtyTimer <= 0.0f)
SaveSettings();
}
// Find the window we are hovering. Child windows can extend beyond the limit of their parent so we need to derive HoveredRootWindow from HoveredWindow
g.HoveredWindow = g.MovedWindow ? g.MovedWindow : FindHoveredWindow(g.IO.MousePos, false);
if (g.HoveredWindow && (g.HoveredWindow->Flags & ImGuiWindowFlags_ChildWindow))
g.HoveredRootWindow = g.HoveredWindow->RootWindow;
else
g.HoveredRootWindow = g.MovedWindow ? g.MovedWindow->RootWindow : FindHoveredWindow(g.IO.MousePos, true);
if (ImGuiWindow* modal_window = GetFrontMostModalRootWindow())
{
g.ModalWindowDarkeningRatio = ImMin(g.ModalWindowDarkeningRatio + g.IO.DeltaTime * 6.0f, 1.0f);
ImGuiWindow* window = g.HoveredRootWindow;
while (window && window != modal_window)
window = window->ParentWindow;
if (!window)
g.HoveredRootWindow = g.HoveredWindow = NULL;
}
else
{
g.ModalWindowDarkeningRatio = 0.0f;
}
// Are we using inputs? Tell user so they can capture/discard the inputs away from the rest of their application.
// When clicking outside of a window we assume the click is owned by the application and won't request capture. We need to track click ownership.
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[mouse_earliest_button_down] > g.IO.MouseClickedTime[i])
mouse_earliest_button_down = i;
}
bool mouse_avail_to_imgui = (mouse_earliest_button_down == -1) || g.IO.MouseDownOwned[mouse_earliest_button_down];
if (g.CaptureMouseNextFrame != -1)
g.IO.WantCaptureMouse = (g.CaptureMouseNextFrame != 0);
else
g.IO.WantCaptureMouse = (mouse_avail_to_imgui && (g.HoveredWindow != NULL || mouse_any_down)) || (g.ActiveId != 0) || (!g.OpenPopupStack.empty());
g.IO.WantCaptureKeyboard = (g.CaptureKeyboardNextFrame != -1) ? (g.CaptureKeyboardNextFrame != 0) : (g.ActiveId != 0);
g.IO.WantTextInput = (g.ActiveId != 0 && g.InputTextState.Id == g.ActiveId);
g.MouseCursor = ImGuiMouseCursor_Arrow;
g.CaptureMouseNextFrame = g.CaptureKeyboardNextFrame = -1;
g.OsImePosRequest = ImVec2(1.0f, 1.0f); // OS Input Method Editor showing on top-left of our window by default
// If mouse was first clicked outside of ImGui bounds we also cancel out hovering.
if (!mouse_avail_to_imgui)
g.HoveredWindow = g.HoveredRootWindow = NULL;
// Scale & Scrolling
if (g.HoveredWindow && g.IO.MouseWheel != 0.0f && !g.HoveredWindow->Collapsed)
{
ImGuiWindow* window = g.HoveredWindow;
if (g.IO.KeyCtrl)
{
if (g.IO.FontAllowUserScaling)
{
// Zoom / Scale window
float new_font_scale = ImClamp(window->FontWindowScale + g.IO.MouseWheel * 0.10f, 0.50f, 2.50f);
float scale = new_font_scale / window->FontWindowScale;
window->FontWindowScale = new_font_scale;
const ImVec2 offset = window->Size * (1.0f - scale) * (g.IO.MousePos - window->Pos) / window->Size;
window->Pos += offset;
window->PosFloat += offset;
window->Size *= scale;
window->SizeFull *= scale;
}
}
else if (!(window->Flags & ImGuiWindowFlags_NoScrollWithMouse))
{
// Scroll
const int scroll_lines = (window->Flags & ImGuiWindowFlags_ComboBox) ? 3 : 5;
SetWindowScrollY(window, window->Scroll.y - g.IO.MouseWheel * window->CalcFontSize() * scroll_lines);
}
}
// Pressing TAB activate widget focus
// NB: Don't discard FocusedWindow if it isn't active, so that a window that go on/off programatically won't lose its keyboard focus.
if (g.ActiveId == 0 && g.FocusedWindow != NULL && g.FocusedWindow->Active && IsKeyPressedMap(ImGuiKey_Tab, false))
g.FocusedWindow->FocusIdxTabRequestNext = 0;
// Mark all windows as not visible
for (int i = 0; i != g.Windows.Size; i++)
{
ImGuiWindow* window = g.Windows[i];
window->WasActive = window->Active;
window->Active = false;
window->Accessed = false;
}
// Closing the focused window restore focus to the first active root window in descending z-order
if (g.FocusedWindow && !g.FocusedWindow->WasActive)
for (int i = g.Windows.Size-1; i >= 0; i--)
if (g.Windows[i]->WasActive && !(g.Windows[i]->Flags & ImGuiWindowFlags_ChildWindow))
{
FocusWindow(g.Windows[i]);
break;
}
// 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.CurrentPopupStack.resize(0);
CloseInactivePopups();
// Create implicit window - we will only render it if the user has added something to it.
ImGui::SetNextWindowSize(ImVec2(400,400), ImGuiSetCond_FirstUseEver);
ImGui::Begin("Debug");
}
// NB: behavior of ImGui after Shutdown() is not tested/guaranteed at the moment. This function is merely here to free heap allocations.
void ImGui::Shutdown()
{
ImGuiContext& g = *GImGui;
// 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)
if (g.IO.Fonts) // Testing for NULL to allow user to NULLify in case of running Shutdown() on multiple contexts. Bit hacky.
g.IO.Fonts->Clear();
// Cleanup of other data are conditional on actually having used ImGui.
if (!g.Initialized)
return;
SaveSettings();
for (int i = 0; i < g.Windows.Size; i++)
{
g.Windows[i]->~ImGuiWindow();
ImGui::MemFree(g.Windows[i]);
}
g.Windows.clear();
g.WindowsSortBuffer.clear();
g.CurrentWindowStack.clear();
g.FocusedWindow = NULL;
g.HoveredWindow = NULL;
g.HoveredRootWindow = NULL;
for (int i = 0; i < g.Settings.Size; i++)
ImGui::MemFree(g.Settings[i].Name);
g.Settings.clear();
g.ColorModifiers.clear();
g.StyleModifiers.clear();
g.FontStack.clear();
g.OpenPopupStack.clear();
g.CurrentPopupStack.clear();
for (int i = 0; i < IM_ARRAYSIZE(g.RenderDrawLists); i++)
g.RenderDrawLists[i].clear();
g.OverlayDrawList.ClearFreeMemory();
g.ColorEditModeStorage.Clear();
if (g.PrivateClipboard)
{
ImGui::MemFree(g.PrivateClipboard);
g.PrivateClipboard = NULL;
}
g.InputTextState.Text.clear();
g.InputTextState.InitialText.clear();
g.InputTextState.TempTextBuffer.clear();
if (g.LogFile && g.LogFile != stdout)
{
fclose(g.LogFile);
g.LogFile = NULL;
}
if (g.LogClipboard)
{
g.LogClipboard->~ImGuiTextBuffer();
ImGui::MemFree(g.LogClipboard);
}
g.Initialized = false;
}
static ImGuiIniData* FindWindowSettings(const char* name)
{
ImGuiContext& g = *GImGui;
ImGuiID id = ImHash(name, 0);
for (int i = 0; i != g.Settings.Size; i++)
{
ImGuiIniData* ini = &g.Settings[i];
if (ini->Id == id)
return ini;
}
return NULL;
}
static ImGuiIniData* AddWindowSettings(const char* name)
{
GImGui->Settings.resize(GImGui->Settings.Size + 1);
ImGuiIniData* ini = &GImGui->Settings.back();
ini->Name = ImStrdup(name);
ini->Id = ImHash(name, 0);
ini->Collapsed = false;
ini->Pos = ImVec2(FLT_MAX,FLT_MAX);
ini->Size = ImVec2(0,0);
return ini;
}
// Zero-tolerance, poor-man .ini parsing
// FIXME: Write something less rubbish
static void LoadSettings()
{
ImGuiContext& g = *GImGui;
const char* filename = g.IO.IniFilename;
if (!filename)
return;
int file_size;
char* file_data = (char*)ImLoadFileToMemory(filename, "rb", &file_size, 1);
if (!file_data)
return;
ImGuiIniData* settings = NULL;
const char* buf_end = file_data + file_size;
for (const char* line_start = file_data; line_start < buf_end; )
{
const char* line_end = line_start;
while (line_end < buf_end && *line_end != '\n' && *line_end != '\r')
line_end++;
if (line_start[0] == '[' && line_end > line_start && line_end[-1] == ']')
{
char name[64];
ImFormatString(name, IM_ARRAYSIZE(name), "%.*s", (int)(line_end-line_start-2), line_start+1);
settings = FindWindowSettings(name);
if (!settings)
settings = AddWindowSettings(name);
}
else if (settings)
{
float x, y;
int i;
if (sscanf(line_start, "Pos=%f,%f", &x, &y) == 2)
settings->Pos = ImVec2(x, y);
else if (sscanf(line_start, "Size=%f,%f", &x, &y) == 2)
settings->Size = ImMax(ImVec2(x, y), g.Style.WindowMinSize);
else if (sscanf(line_start, "Collapsed=%d", &i) == 1)
settings->Collapsed = (i != 0);
}
line_start = line_end+1;
}
ImGui::MemFree(file_data);
}
static void SaveSettings()
{
ImGuiContext& g = *GImGui;
const char* filename = g.IO.IniFilename;
if (!filename)
return;
// Gather data from windows that were active during this session
for (int i = 0; i != g.Windows.Size; i++)
{
ImGuiWindow* window = g.Windows[i];
if (window->Flags & ImGuiWindowFlags_NoSavedSettings)
continue;
ImGuiIniData* settings = FindWindowSettings(window->Name);
settings->Pos = window->Pos;
settings->Size = window->SizeFull;
settings->Collapsed = window->Collapsed;
}
// Write .ini file
// If a window wasn't opened in this session we preserve its settings
FILE* f = fopen(filename, "wt");
if (!f)
return;
for (int i = 0; i != g.Settings.Size; i++)
{
const ImGuiIniData* settings = &g.Settings[i];
if (settings->Pos.x == FLT_MAX)
continue;
const char* name = settings->Name;
if (const char* p = strstr(name, "###")) // Skip to the "###" marker if any. We don't skip past to match the behavior of GetID()
name = p;
fprintf(f, "[%s]\n", name);
fprintf(f, "Pos=%d,%d\n", (int)settings->Pos.x, (int)settings->Pos.y);
fprintf(f, "Size=%d,%d\n", (int)settings->Size.x, (int)settings->Size.y);
fprintf(f, "Collapsed=%d\n", settings->Collapsed);
fprintf(f, "\n");
}
fclose(f);
}
static void MarkSettingsDirty()
{
ImGuiContext& g = *GImGui;
if (g.SettingsDirtyTimer <= 0.0f)
g.SettingsDirtyTimer = g.IO.IniSavingRate;
}
// FIXME: Add a more explicit sort order in the window structure.
static int ChildWindowComparer(const void* lhs, const void* rhs)
{
const ImGuiWindow* a = *(const ImGuiWindow**)lhs;
const ImGuiWindow* b = *(const ImGuiWindow**)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;
if (int d = (a->Flags & ImGuiWindowFlags_ComboBox) - (b->Flags & ImGuiWindowFlags_ComboBox))
return d;
return (a->IndexWithinParent - b->IndexWithinParent);
}
static void AddWindowToSortedBuffer(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)
qsort(window->DC.ChildWindows.begin(), (size_t)count, sizeof(ImGuiWindow*), ChildWindowComparer);
for (int i = 0; i < count; i++)
{
ImGuiWindow* child = window->DC.ChildWindows[i];
if (child->Active)
AddWindowToSortedBuffer(out_sorted_windows, child);
}
}
}
static void AddDrawListToRenderList(ImVector<ImDrawList*>& out_render_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.
IM_ASSERT(draw_list->_VtxWritePtr == draw_list->VtxBuffer.Data + draw_list->VtxBuffer.Size);
IM_ASSERT(draw_list->_IdxWritePtr == draw_list->IdxBuffer.Data + draw_list->IdxBuffer.Size);
IM_ASSERT((int)draw_list->_VtxCurrentIdx == draw_list->VtxBuffer.Size);
// Check that draw_list doesn't use more vertices than indexable (default ImDrawIdx = 2 bytes = 64K vertices)
// If this assert triggers because you are drawing lots of stuff manually, A) workaround by calling BeginChild()/EndChild() to put your draw commands in multiple draw lists, B) #define ImDrawIdx to a 'unsigned int' in imconfig.h and render accordingly.
IM_ASSERT((int64_t)draw_list->_VtxCurrentIdx <= ((int64_t)1L << (sizeof(ImDrawIdx)*8))); // Too many vertices in same ImDrawList. See comment above.
out_render_list.push_back(draw_list);
GImGui->IO.MetricsRenderVertices += draw_list->VtxBuffer.Size;
GImGui->IO.MetricsRenderIndices += draw_list->IdxBuffer.Size;
}
static void AddWindowToRenderList(ImVector<ImDrawList*>& out_render_list, ImGuiWindow* window)
{
AddDrawListToRenderList(out_render_list, window->DrawList);
for (int i = 0; i < window->DC.ChildWindows.Size; i++)
{
ImGuiWindow* child = window->DC.ChildWindows[i];
if (!child->Active) // clipped children may have been marked not active
continue;
if ((child->Flags & ImGuiWindowFlags_Popup) && child->HiddenFrames > 0)
continue;
AddWindowToRenderList(out_render_list, child);
}
}
// 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); // Forgot to call ImGui::NewFrame()
IM_ASSERT(g.FrameCountEnded != g.FrameCount); // ImGui::EndFrame() called multiple times, or forgot to call ImGui::NewFrame() again
// Render tooltip
if (g.Tooltip[0])
{
ImGui::BeginTooltip();
ImGui::TextUnformatted(g.Tooltip);
ImGui::EndTooltip();
}
// Notify OS when our Input Method Editor cursor has moved (e.g. CJK inputs using Microsoft IME)
if (g.IO.ImeSetInputScreenPosFn && ImLengthSqr(g.OsImePosRequest - g.OsImePosSet) > 0.0001f)
{
g.IO.ImeSetInputScreenPosFn((int)g.OsImePosRequest.x, (int)g.OsImePosRequest.y);
g.OsImePosSet = g.OsImePosRequest;
}
// Hide implicit "Debug" window if it hasn't been used
IM_ASSERT(g.CurrentWindowStack.Size == 1); // Mismatched Begin()/End() calls
if (g.CurrentWindow && !g.CurrentWindow->Accessed)
g.CurrentWindow->Active = false;
ImGui::End();
// Click to focus window and start moving (after we're done with all our widgets)
if (g.ActiveId == 0 && g.HoveredId == 0 && g.IO.MouseClicked[0])
{
if (!(g.FocusedWindow && !g.FocusedWindow->WasActive && g.FocusedWindow->Active)) // Unless we just made a popup appear
{
if (g.HoveredRootWindow != NULL)
{
FocusWindow(g.HoveredWindow);
if (!(g.HoveredWindow->Flags & ImGuiWindowFlags_NoMove))
{
g.MovedWindow = g.HoveredWindow;
g.MovedWindowMoveId = g.HoveredRootWindow->MoveId;
SetActiveID(g.MovedWindowMoveId, g.HoveredRootWindow);
}
}
else if (g.FocusedWindow != NULL && GetFrontMostModalRootWindow() == NULL)
{
// Clicking on void disable focus
FocusWindow(NULL);
}
}
}
// 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;
AddWindowToSortedBuffer(g.WindowsSortBuffer, window);
}
IM_ASSERT(g.Windows.Size == g.WindowsSortBuffer.Size); // we done something wrong
g.Windows.swap(g.WindowsSortBuffer);
// Clear Input data for next frame
g.IO.MouseWheel = 0.0f;
memset(g.IO.InputCharacters, 0, sizeof(g.IO.InputCharacters));
g.FrameCountEnded = g.FrameCount;
}
void ImGui::Render()
{
ImGuiContext& g = *GImGui;
IM_ASSERT(g.Initialized); // Forgot to call ImGui::NewFrame()
if (g.FrameCountEnded != g.FrameCount)
ImGui::EndFrame();
g.FrameCountRendered = g.FrameCount;
// Skip render altogether if alpha is 0.0
// Note that vertex buffers have been created and are wasted, so it is best practice that you don't create windows in the first place, or consistently respond to Begin() returning false.
if (g.Style.Alpha > 0.0f)
{
// Gather windows to render
g.IO.MetricsRenderVertices = g.IO.MetricsRenderIndices = g.IO.MetricsActiveWindows = 0;
for (int i = 0; i < IM_ARRAYSIZE(g.RenderDrawLists); i++)
g.RenderDrawLists[i].resize(0);
for (int i = 0; i != g.Windows.Size; i++)
{
ImGuiWindow* window = g.Windows[i];
if (window->Active && window->HiddenFrames <= 0 && (window->Flags & (ImGuiWindowFlags_ChildWindow)) == 0)
{
// FIXME: Generalize this with a proper layering system so e.g. user can draw in specific layers, below text, ..
g.IO.MetricsActiveWindows++;
if (window->Flags & ImGuiWindowFlags_Popup)
AddWindowToRenderList(g.RenderDrawLists[1], window);
else if (window->Flags & ImGuiWindowFlags_Tooltip)
AddWindowToRenderList(g.RenderDrawLists[2], window);
else
AddWindowToRenderList(g.RenderDrawLists[0], window);
}
}
// Flatten layers
int n = g.RenderDrawLists[0].Size;
int flattened_size = n;
for (int i = 1; i < IM_ARRAYSIZE(g.RenderDrawLists); i++)
flattened_size += g.RenderDrawLists[i].Size;
g.RenderDrawLists[0].resize(flattened_size);
for (int i = 1; i < IM_ARRAYSIZE(g.RenderDrawLists); i++)
{
ImVector<ImDrawList*>& layer = g.RenderDrawLists[i];
if (layer.empty())
continue;
memcpy(&g.RenderDrawLists[0][n], &layer[0], layer.Size * sizeof(ImDrawList*));
n += layer.Size;
}
// Draw software mouse cursor if requested
if (g.IO.MouseDrawCursor)
{
const ImGuiMouseCursorData& cursor_data = g.MouseCursorData[g.MouseCursor];
const ImVec2 pos = g.IO.MousePos - cursor_data.HotOffset;
const ImVec2 size = cursor_data.Size;
const ImTextureID tex_id = g.IO.Fonts->TexID;
g.OverlayDrawList.PushTextureID(tex_id);
g.OverlayDrawList.AddImage(tex_id, pos+ImVec2(1,0), pos+ImVec2(1,0) + size, cursor_data.TexUvMin[1], cursor_data.TexUvMax[1], 0x30000000); // Shadow
g.OverlayDrawList.AddImage(tex_id, pos+ImVec2(2,0), pos+ImVec2(2,0) + size, cursor_data.TexUvMin[1], cursor_data.TexUvMax[1], 0x30000000); // Shadow
g.OverlayDrawList.AddImage(tex_id, pos, pos + size, cursor_data.TexUvMin[1], cursor_data.TexUvMax[1], 0xFF000000); // Black border
g.OverlayDrawList.AddImage(tex_id, pos, pos + size, cursor_data.TexUvMin[0], cursor_data.TexUvMax[0], 0xFFFFFFFF); // White fill
g.OverlayDrawList.PopTextureID();
}
if (!g.OverlayDrawList.VtxBuffer.empty())
AddDrawListToRenderList(g.RenderDrawLists[0], &g.OverlayDrawList);
// Setup draw data
g.RenderDrawData.Valid = true;
g.RenderDrawData.CmdLists = (g.RenderDrawLists[0].Size > 0) ? &g.RenderDrawLists[0][0] : NULL;
g.RenderDrawData.CmdListsCount = g.RenderDrawLists[0].Size;
g.RenderDrawData.TotalVtxCount = g.IO.MetricsRenderVertices;
g.RenderDrawData.TotalIdxCount = g.IO.MetricsRenderIndices;
// Render. If user hasn't set a callback then they may retrieve the draw data via GetDrawData()
if (g.RenderDrawData.CmdListsCount > 0 && g.IO.RenderDrawListsFn != NULL)
g.IO.RenderDrawListsFn(&g.RenderDrawData);
}
}
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;
}
// 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.LogClipboard->appendv(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
static void LogRenderedText(const ImVec2& ref_pos, const char* text, const char* text_end)
{
ImGuiContext& g = *GImGui;
ImGuiWindow* window = ImGui::GetCurrentWindowRead();
if (!text_end)
text_end = ImGui::FindRenderedTextEnd(text, text_end);
const bool log_new_line = ref_pos.y > window->DC.LogLinePosY+1;
window->DC.LogLinePosY = ref_pos.y;
const char* text_remaining = text;
if (g.LogStartDepth > window->DC.TreeDepth) // Re-adjust padding if we have popped out of our starting depth
g.LogStartDepth = window->DC.TreeDepth;
const int tree_depth = (window->DC.TreeDepth - g.LogStartDepth);
for (;;)
{
// Split the string. Each new line (after a '\n') is followed by spacing corresponding to the current depth of our log entry.
const char* line_end = text_remaining;
while (line_end < text_end)
if (*line_end == '\n')
break;
else
line_end++;
if (line_end >= text_end)
line_end = NULL;
const bool is_first_line = (text == text_remaining);
bool is_last_line = false;
if (line_end == NULL)
{
is_last_line = true;
line_end = text_end;
}
if (line_end != NULL && !(is_last_line && (line_end - text_remaining)==0))
{
const int char_count = (int)(line_end - text_remaining);
if (log_new_line || !is_first_line)
ImGui::LogText(IM_NEWLINE "%*s%.*s", tree_depth*4, "", char_count, text_remaining);
else
ImGui::LogText(" %.*s", char_count, text_remaining);
}
if (is_last_line)
break;
text_remaining = line_end + 1;
}
}
// 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 = GetCurrentWindow();
// 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;
}
const int text_len = (int)(text_display_end - text);
if (text_len > 0)
{
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 = GetCurrentWindow();
if (!text_end)
text_end = text + strlen(text); // FIXME-OPT
const int text_len = (int)(text_end - text);
if (text_len > 0)
{
window->DrawList->AddText(g.Font, g.FontSize, pos, GetColorU32(ImGuiCol_Text), text, text_end, wrap_width);
if (g.LogEnabled)
LogRenderedText(pos, text, text_end);
}
}
// Handle clipping on CPU immediately (vs typically let the GPU clip the triangles that are overlapping the clipping rectangle edges)
void ImGui::RenderTextClipped(const ImVec2& pos_min, const ImVec2& pos_max, const char* text, const char* text_end, const ImVec2* text_size_if_known, ImGuiAlign align, const ImVec2* clip_min, const ImVec2* clip_max)
{
// 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 = GetCurrentWindow();
// 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);
if (!clip_max) clip_max = &pos_max;
bool need_clipping = (pos.x + text_size.x >= clip_max->x) || (pos.y + text_size.y >= clip_max->y);
if (!clip_min) clip_min = &pos_min; else need_clipping |= (pos.x < clip_min->x) || (pos.y < clip_min->y);
// Align
if (align & ImGuiAlign_Center) pos.x = ImMax(pos.x, (pos.x + pos_max.x - text_size.x) * 0.5f);
else if (align & ImGuiAlign_Right) pos.x = ImMax(pos.x, pos_max.x - text_size.x);
if (align & ImGuiAlign_VCenter) pos.y = ImMax(pos.y, (pos.y + pos_max.y - text_size.y) * 0.5f);
// Render
if (need_clipping)
{
ImVec4 fine_clip_rect(clip_min->x, clip_min->y, clip_max->x, clip_max->y);
window->DrawList->AddText(g.Font, g.FontSize, pos, GetColorU32(ImGuiCol_Text), text, text_display_end, 0.0f, &fine_clip_rect);
}
else
{
window->DrawList->AddText(g.Font, g.FontSize, pos, GetColorU32(ImGuiCol_Text), text, text_display_end, 0.0f, NULL);
}
if (g.LogEnabled)
LogRenderedText(pos, text, text_display_end);
}
// 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)
{
ImGuiWindow* window = GetCurrentWindow();
window->DrawList->AddRectFilled(p_min, p_max, fill_col, rounding);
if (border && (window->Flags & ImGuiWindowFlags_ShowBorders))
{
window->DrawList->AddRect(p_min+ImVec2(1,1), p_max+ImVec2(1,1), GetColorU32(ImGuiCol_BorderShadow), rounding);
window->DrawList->AddRect(p_min, p_max, GetColorU32(ImGuiCol_Border), rounding);
}
}
// Render a triangle to denote expanded/collapsed state
void ImGui::RenderCollapseTriangle(ImVec2 p_min, bool is_open, float scale, bool shadow)
{
ImGuiContext& g = *GImGui;
ImGuiWindow* window = GetCurrentWindow();
const float h = g.FontSize * 1.00f;
const float r = h * 0.40f * scale;
ImVec2 center = p_min + ImVec2(h*0.50f, h*0.50f*scale);
ImVec2 a, b, c;
if (is_open)
{
center.y -= r*0.25f;
a = center + ImVec2(0,1)*r;
b = center + ImVec2(-0.866f,-0.5f)*r;
c = center + ImVec2(0.866f,-0.5f)*r;
}
else
{
a = center + ImVec2(1,0)*r;
b = center + ImVec2(-0.500f,0.866f)*r;
c = center + ImVec2(-0.500f,-0.866f)*r;
}
if (shadow && (window->Flags & ImGuiWindowFlags_ShowBorders) != 0)
window->DrawList->AddTriangleFilled(a+ImVec2(2,2), b+ImVec2(2,2), c+ImVec2(2,2), GetColorU32(ImGuiCol_BorderShadow));
window->DrawList->AddTriangleFilled(a, b, c, GetColorU32(ImGuiCol_Text));
}
void ImGui::RenderBullet(ImVec2 pos)
{
ImGuiWindow* window = GetCurrentWindow();
window->DrawList->AddCircleFilled(pos, GImGui->FontSize*0.20f, GetColorU32(ImGuiCol_Text), 8);
}
void ImGui::RenderCheckMark(ImVec2 pos, ImU32 col)
{
ImGuiContext& g = *GImGui;
ImGuiWindow* window = GetCurrentWindow();
ImVec2 a, b, c;
float start_x = (float)(int)(g.FontSize * 0.307f + 0.5f);
float rem_third = (float)(int)((g.FontSize - start_x) / 3.0f);
a.x = pos.x + 0.5f + start_x;
b.x = a.x + rem_third;
c.x = a.x + rem_third * 3.0f;
b.y = pos.y - 1.0f + (float)(int)(g.Font->Ascent * (g.FontSize / g.Font->FontSize) + 0.5f) + (float)(int)(g.Font->DisplayOffset.y);
a.y = b.y - rem_third;
c.y = b.y - rem_third * 2.0f;
window->DrawList->PathLineTo(a);
window->DrawList->PathLineTo(b);
window->DrawList->PathLineTo(c);
window->DrawList->PathStroke(col, false);
}
// 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);
// Cancel out character spacing for the last character of a line (it is baked into glyph->XAdvance field)
const float font_scale = font_size / font->FontSize;
const float character_spacing_x = 1.0f * font_scale;
if (text_size.x > 0.0f)
text_size.x -= character_spacing_x;
text_size.x = (float)(int)(text_size.x + 0.95f);
return text_size;
}
// 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 = GetCurrentWindowRead();
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;
}
const ImVec2 pos = window->DC.CursorPos;
int start = (int)((window->ClipRect.Min.y - pos.y) / items_height);
int end = (int)((window->ClipRect.Max.y - pos.y) / items_height);
start = ImClamp(start, 0, items_count);
end = ImClamp(end + 1, start, items_count);
*out_items_display_start = start;
*out_items_display_end = end;
}
// Find window given position, search front-to-back
// FIXME: Note that we have a lag here because WindowRectClipped is updated in Begin() so windows moved by user via 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 thankfully isn't affected.
static ImGuiWindow* FindHoveredWindow(ImVec2 pos, bool excluding_childs)
{
ImGuiContext& g = *GImGui;
for (int i = g.Windows.Size-1; i >= 0; i--)
{
ImGuiWindow* window = g.Windows[i];
if (!window->Active)
continue;
if (window->Flags & ImGuiWindowFlags_NoInputs)
continue;
if (excluding_childs && (window->Flags & ImGuiWindowFlags_ChildWindow) != 0)
continue;
// Using the clipped AABB so a child window will typically be clipped by its parent.
ImRect bb(window->WindowRectClipped.Min - g.Style.TouchExtraPadding, window->WindowRectClipped.Max + g.Style.TouchExtraPadding);
if (bb.Contains(pos))
return window;
}
return 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;
ImGuiWindow* window = GetCurrentWindowRead();
// Clip
ImRect rect_clipped(r_min, r_max);
if (clip)
rect_clipped.Clip(window->ClipRect);
// Expand for touch input
const ImRect rect_for_touch(rect_clipped.Min - g.Style.TouchExtraPadding, rect_clipped.Max + g.Style.TouchExtraPadding);
return rect_for_touch.Contains(g.IO.MousePos);
}
bool ImGui::IsMouseHoveringWindow()
{
ImGuiContext& g = *GImGui;
return g.HoveredWindow == g.CurrentWindow;
}
bool ImGui::IsMouseHoveringAnyWindow()
{
ImGuiContext& g = *GImGui;
return g.HoveredWindow != NULL;
}
bool ImGui::IsPosHoveringAnyWindow(const ImVec2& pos)
{
return FindHoveredWindow(pos, false) != NULL;
}
static bool IsKeyPressedMap(ImGuiKey key, bool repeat)
{
const int key_index = GImGui->IO.KeyMap[key];
return ImGui::IsKeyPressed(key_index, repeat);
}
int ImGui::GetKeyIndex(ImGuiKey key)
{
IM_ASSERT(key >= 0 && key < ImGuiKey_COUNT);
return GImGui->IO.KeyMap[key];
}
bool ImGui::IsKeyDown(int key_index)
{
if (key_index < 0) return false;
IM_ASSERT(key_index >= 0 && key_index < IM_ARRAYSIZE(GImGui->IO.KeysDown));
return GImGui->IO.KeysDown[key_index];
}
bool ImGui::IsKeyPressed(int key_index, bool repeat)
{
ImGuiContext& g = *GImGui;
if (key_index < 0) return false;
IM_ASSERT(key_index >= 0 && key_index < IM_ARRAYSIZE(g.IO.KeysDown));
const float t = g.IO.KeysDownDuration[key_index];
if (t == 0.0f)
return true;
if (repeat && t > g.IO.KeyRepeatDelay)
{
float delay = g.IO.KeyRepeatDelay, rate = g.IO.KeyRepeatRate;
if ((fmodf(t - delay, rate) > rate*0.5f) != (fmodf(t - delay - g.IO.DeltaTime, rate) > rate*0.5f))
return true;
}
return false;
}
bool ImGui::IsKeyReleased(int key_index)
{
ImGuiContext& g = *GImGui;
if (key_index < 0) return false;
IM_ASSERT(key_index >= 0 && key_index < IM_ARRAYSIZE(g.IO.KeysDown));
if (g.IO.KeysDownDurationPrev[key_index] >= 0.0f && !g.IO.KeysDown[key_index])
return true;
return false;
}
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::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)
{
float delay = g.IO.KeyRepeatDelay, rate = g.IO.KeyRepeatRate;
if ((fmodf(t - delay, rate) > rate*0.5f) != (fmodf(t - delay - g.IO.DeltaTime, rate) > rate*0.5f))
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];
}
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;
if (lock_threshold < 0.0f)
lock_threshold = g.IO.MouseDragThreshold;
return g.IO.MouseDragMaxDistanceSqr[button] >= lock_threshold * 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.CurrentPopupStack.Size > 0)
return g.OpenPopupStack[g.CurrentPopupStack.Size-1].MousePosOnOpen;
return g.IO.MousePos;
}
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])
if (g.IO.MouseDragMaxDistanceSqr[button] >= lock_threshold * lock_threshold)
return g.IO.MousePos - g.IO.MouseClickedPos[button]; // Assume we can only get active with left-mouse button (at the moment).
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->CaptureKeyboardNextFrame = capture ? 1 : 0;
}
void ImGui::CaptureMouseFromApp(bool capture)
{
GImGui->CaptureMouseNextFrame = capture ? 1 : 0;
}
bool ImGui::IsItemHovered()
{
ImGuiWindow* window = GetCurrentWindowRead();
return window->DC.LastItemHoveredAndUsable;
}
bool ImGui::IsItemHoveredRect()
{
ImGuiWindow* window = GetCurrentWindowRead();
return window->DC.LastItemHoveredRect;
}
bool ImGui::IsItemActive()
{
ImGuiContext& g = *GImGui;
if (g.ActiveId)
{
ImGuiWindow* window = GetCurrentWindowRead();
return g.ActiveId == window->DC.LastItemId;
}
return false;
}
bool ImGui::IsItemClicked(int mouse_button)
{
return IsMouseClicked(mouse_button) && IsItemHovered();
}
bool ImGui::IsAnyItemHovered()
{
return GImGui->HoveredId != 0 || GImGui->HoveredIdPreviousFrame != 0;
}
bool ImGui::IsAnyItemActive()
{
return GImGui->ActiveId != 0;
}
bool ImGui::IsItemVisible()
{
ImGuiWindow* window = GetCurrentWindowRead();
ImRect r(window->ClipRect);
return r.Overlaps(window->DC.LastItemRect);
}
// 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();
}
ImVec2 ImGui::CalcItemRectClosestPoint(const ImVec2& pos, bool on_edge, float outward)
{
ImGuiWindow* window = GetCurrentWindowRead();
ImRect rect = window->DC.LastItemRect;
rect.Expand(outward);
return rect.GetClosestPoint(pos, on_edge);
}
// Tooltip is stored and turned into a BeginTooltip()/EndTooltip() sequence at the end of the frame. Each call override previous value.
void ImGui::SetTooltipV(const char* fmt, va_list args)
{
ImGuiContext& g = *GImGui;
ImFormatStringV(g.Tooltip, IM_ARRAYSIZE(g.Tooltip), fmt, args);
}
void ImGui::SetTooltip(const char* fmt, ...)
{
va_list args;
va_start(args, fmt);
SetTooltipV(fmt, args);
va_end(args);
}
static ImRect GetVisibleRect()
{
ImGuiContext& g = *GImGui;
if (g.IO.DisplayVisibleMin.x != g.IO.DisplayVisibleMax.x && g.IO.DisplayVisibleMin.y != g.IO.DisplayVisibleMax.y)
return ImRect(g.IO.DisplayVisibleMin, g.IO.DisplayVisibleMax);
return ImRect(0.0f, 0.0f, g.IO.DisplaySize.x, g.IO.DisplaySize.y);
}
void ImGui::BeginTooltip()
{
ImGuiWindowFlags flags = ImGuiWindowFlags_Tooltip|ImGuiWindowFlags_NoTitleBar|ImGuiWindowFlags_NoMove|ImGuiWindowFlags_NoResize|ImGuiWindowFlags_NoSavedSettings|ImGuiWindowFlags_AlwaysAutoResize;
ImGui::Begin("##Tooltip", NULL, flags);
}
void ImGui::EndTooltip()
{
IM_ASSERT(GetCurrentWindowRead()->Flags & ImGuiWindowFlags_Tooltip); // Mismatched BeginTooltip()/EndTooltip() calls
ImGui::End();
}
static bool IsPopupOpen(ImGuiID id)
{
ImGuiContext& g = *GImGui;
const bool is_open = g.OpenPopupStack.Size > g.CurrentPopupStack.Size && g.OpenPopupStack[g.CurrentPopupStack.Size].PopupId == id;
return is_open;
}
// 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(const char* str_id, bool reopen_existing)
{
ImGuiContext& g = *GImGui;
ImGuiWindow* window = g.CurrentWindow;
ImGuiID id = window->GetID(str_id);
int current_stack_size = g.CurrentPopupStack.Size;
ImGuiPopupRef popup_ref = ImGuiPopupRef(id, window, window->GetID("##menus"), g.IO.MousePos); // Tagged as new ref because constructor sets Window to NULL (we are passing the ParentWindow info here)
if (g.OpenPopupStack.Size < current_stack_size + 1)
g.OpenPopupStack.push_back(popup_ref);
else if (reopen_existing || g.OpenPopupStack[current_stack_size].PopupId != id)
{
g.OpenPopupStack.resize(current_stack_size+1);
g.OpenPopupStack[current_stack_size] = popup_ref;
}
}
void ImGui::OpenPopup(const char* str_id)
{
ImGui::OpenPopupEx(str_id, false);
}
static void CloseInactivePopups()
{
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 n = 0;
if (g.FocusedWindow)
{
for (n = 0; n < g.OpenPopupStack.Size; n++)
{
ImGuiPopupRef& popup = g.OpenPopupStack[n];
if (!popup.Window)
continue;
IM_ASSERT((popup.Window->Flags & ImGuiWindowFlags_Popup) != 0);
if (popup.Window->Flags & ImGuiWindowFlags_ChildWindow)
continue;
bool has_focus = false;
for (int m = n; m < g.OpenPopupStack.Size && !has_focus; m++)
has_focus = (g.OpenPopupStack[m].Window && g.OpenPopupStack[m].Window->RootWindow == g.FocusedWindow->RootWindow);
if (!has_focus)
break;
}
}
if (n < g.OpenPopupStack.Size) // This test is not required but it allows to set a useful breakpoint on the line below
g.OpenPopupStack.resize(n);
}
static ImGuiWindow* GetFrontMostModalRootWindow()
{
ImGuiContext& g = *GImGui;
for (int n = g.OpenPopupStack.Size-1; n >= 0; n--)
if (ImGuiWindow* front_most_popup = g.OpenPopupStack.Data[n].Window)
if (front_most_popup->Flags & ImGuiWindowFlags_Modal)
return front_most_popup;
return NULL;
}
static void ClosePopupToLevel(int remaining)
{
ImGuiContext& g = *GImGui;
if (remaining > 0)
ImGui::FocusWindow(g.OpenPopupStack[remaining-1].Window);
else
ImGui::FocusWindow(g.OpenPopupStack[0].ParentWindow);
g.OpenPopupStack.resize(remaining);
}
static void ClosePopup(ImGuiID id)
{
if (!IsPopupOpen(id))
return;
ImGuiContext& g = *GImGui;
ClosePopupToLevel(g.OpenPopupStack.Size - 1);
}
// Close the popup we have begin-ed into.
void ImGui::CloseCurrentPopup()
{
ImGuiContext& g = *GImGui;
int popup_idx = g.CurrentPopupStack.Size - 1;
if (popup_idx < 0 || popup_idx > g.OpenPopupStack.Size || g.CurrentPopupStack[popup_idx].PopupId != g.OpenPopupStack[popup_idx].PopupId)
return;
while (popup_idx > 0 && g.OpenPopupStack[popup_idx].Window && (g.OpenPopupStack[popup_idx].Window->Flags & ImGuiWindowFlags_ChildMenu))
popup_idx--;
ClosePopupToLevel(popup_idx);
}
static inline void ClearSetNextWindowData()
{
ImGuiContext& g = *GImGui;
g.SetNextWindowPosCond = g.SetNextWindowSizeCond = g.SetNextWindowContentSizeCond = g.SetNextWindowCollapsedCond = 0;
g.SetNextWindowSizeConstraint = g.SetNextWindowFocus = false;
}
static bool BeginPopupEx(const char* str_id, ImGuiWindowFlags extra_flags)
{
ImGuiContext& g = *GImGui;
ImGuiWindow* window = g.CurrentWindow;
const ImGuiID id = window->GetID(str_id);
if (!IsPopupOpen(id))
{
ClearSetNextWindowData(); // We behave like Begin() and need to consume those values
return false;
}
ImGui::PushStyleVar(ImGuiStyleVar_WindowRounding, 0.0f);
ImGuiWindowFlags flags = extra_flags|ImGuiWindowFlags_Popup|ImGuiWindowFlags_NoTitleBar|ImGuiWindowFlags_NoMove|ImGuiWindowFlags_NoResize|ImGuiWindowFlags_NoSavedSettings|ImGuiWindowFlags_AlwaysAutoResize;
char name[32];
if (flags & ImGuiWindowFlags_ChildMenu)
ImFormatString(name, 20, "##menu_%d", g.CurrentPopupStack.Size); // Recycle windows based on depth
else
ImFormatString(name, 20, "##popup_%08x", id); // Not recycling, so we can close/open during the same frame
bool is_open = ImGui::Begin(name, NULL, flags);
if (!(window->Flags & ImGuiWindowFlags_ShowBorders))
g.CurrentWindow->Flags &= ~ImGuiWindowFlags_ShowBorders;
if (!is_open) // NB: is_open can be 'false' when the popup is completely clipped (e.g. zero size display)
ImGui::EndPopup();
return is_open;
}
bool ImGui::BeginPopup(const char* str_id)
{
if (GImGui->OpenPopupStack.Size <= GImGui->CurrentPopupStack.Size) // Early out for performance
{
ClearSetNextWindowData(); // We behave like Begin() and need to consume those values
return false;
}
return BeginPopupEx(str_id, ImGuiWindowFlags_ShowBorders);
}
bool ImGui::BeginPopupModal(const char* name, bool* p_open, ImGuiWindowFlags extra_flags)
{
ImGuiContext& g = *GImGui;
ImGuiWindow* window = g.CurrentWindow;
const ImGuiID id = window->GetID(name);
if (!IsPopupOpen(id))
{
ClearSetNextWindowData(); // We behave like Begin() and need to consume those values
return false;
}
ImGuiWindowFlags flags = extra_flags|ImGuiWindowFlags_Popup|ImGuiWindowFlags_Modal|ImGuiWindowFlags_NoCollapse|ImGuiWindowFlags_NoSavedSettings;
bool is_open = ImGui::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)
{
ImGui::EndPopup();
if (is_open)
ClosePopup(id);
return false;
}
return is_open;
}
void ImGui::EndPopup()
{
ImGuiWindow* window = GetCurrentWindow();
IM_ASSERT(window->Flags & ImGuiWindowFlags_Popup); // Mismatched BeginPopup()/EndPopup() calls
IM_ASSERT(GImGui->CurrentPopupStack.Size > 0);
ImGui::End();
if (!(window->Flags & ImGuiWindowFlags_Modal))
ImGui::PopStyleVar();
}
// This is a helper to handle the most simple case of associating one named popup to one given widget.
// 1. If you have many possible popups (for different "instances" of a same widget, or for wholly different widgets), you may be better off handling
// this yourself so you can store data relative to the widget that opened the popup instead of choosing different popup identifiers.
// 2. If you want right-clicking on the same item to reopen the popup at new location, use the same code replacing IsItemHovered() with IsItemHoveredRect()
// and passing true to the OpenPopupEx().
// Because: hovering an item in a window below the popup won't normally trigger is hovering behavior/coloring. The pattern of ignoring the fact that
// the item isn't interactable (because it is blocked by the active popup) may useful in some situation when e.g. large canvas as one item, content of menu
// driven by click position.
bool ImGui::BeginPopupContextItem(const char* str_id, int mouse_button)
{
if (IsItemHovered() && IsMouseClicked(mouse_button))
OpenPopupEx(str_id, false);
return BeginPopup(str_id);
}
bool ImGui::BeginPopupContextWindow(bool also_over_items, const char* str_id, int mouse_button)
{
if (!str_id) str_id = "window_context_menu";
if (IsMouseHoveringWindow() && IsMouseClicked(mouse_button))
if (also_over_items || !IsAnyItemHovered())
OpenPopupEx(str_id, true);
return BeginPopup(str_id);
}
bool ImGui::BeginPopupContextVoid(const char* str_id, int mouse_button)
{
if (!str_id) str_id = "void_context_menu";
if (!IsMouseHoveringAnyWindow() && IsMouseClicked(mouse_button))
OpenPopupEx(str_id, true);
return BeginPopup(str_id);
}
bool ImGui::BeginChild(const char* str_id, const ImVec2& size_arg, bool border, ImGuiWindowFlags extra_flags)
{
ImGuiWindow* window = GetCurrentWindow();
ImGuiWindowFlags flags = ImGuiWindowFlags_NoTitleBar|ImGuiWindowFlags_NoResize|ImGuiWindowFlags_NoSavedSettings|ImGuiWindowFlags_ChildWindow;
const ImVec2 content_avail = GetContentRegionAvail();
ImVec2 size = ImFloor(size_arg);
if (size.x <= 0.0f)
{
if (size.x == 0.0f)
flags |= ImGuiWindowFlags_ChildWindowAutoFitX;
size.x = ImMax(content_avail.x, 4.0f) - fabsf(size.x); // Arbitrary minimum zero-ish child size of 4.0f (0.0f causing too much issues)
}
if (size.y <= 0.0f)
{
if (size.y == 0.0f)
flags |= ImGuiWindowFlags_ChildWindowAutoFitY;
size.y = ImMax(content_avail.y, 4.0f) - fabsf(size.y);
}
if (border)
flags |= ImGuiWindowFlags_ShowBorders;
flags |= extra_flags;
char title[256];
ImFormatString(title, IM_ARRAYSIZE(title), "%s.%s", window->Name, str_id);
bool ret = ImGui::Begin(title, NULL, size, -1.0f, flags);
if (!(window->Flags & ImGuiWindowFlags_ShowBorders))
GetCurrentWindow()->Flags &= ~ImGuiWindowFlags_ShowBorders;
return ret;
}
bool ImGui::BeginChild(ImGuiID id, const ImVec2& size, bool border, ImGuiWindowFlags extra_flags)
{
char str_id[32];
ImFormatString(str_id, IM_ARRAYSIZE(str_id), "child_%08x", id);
bool ret = ImGui::BeginChild(str_id, size, border, extra_flags);
return ret;
}
void ImGui::EndChild()
{
ImGuiWindow* window = GetCurrentWindow();
IM_ASSERT(window->Flags & ImGuiWindowFlags_ChildWindow); // Mismatched BeginChild()/EndChild() callss
if ((window->Flags & ImGuiWindowFlags_ComboBox) || window->BeginCount > 1)
{
ImGui::End();
}
else
{
// When using auto-filling child window, we don't provide full width/height to ItemSize so that it doesn't feed back into automatic size-fitting.
ImVec2 sz = GetWindowSize();
if (window->Flags & ImGuiWindowFlags_ChildWindowAutoFitX) // 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->Flags & ImGuiWindowFlags_ChildWindowAutoFitY)
sz.y = ImMax(4.0f, sz.y);
ImGui::End();
window = GetCurrentWindow();
ImRect bb(window->DC.CursorPos, window->DC.CursorPos + sz);
ItemSize(sz);
ItemAdd(bb, NULL);
}
}
// 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;
ImGui::PushStyleColor(ImGuiCol_ChildWindowBg, style.Colors[ImGuiCol_FrameBg]);
ImGui::PushStyleVar(ImGuiStyleVar_ChildWindowRounding, style.FrameRounding);
ImGui::PushStyleVar(ImGuiStyleVar_WindowPadding, style.FramePadding);
return ImGui::BeginChild(id, size, (g.CurrentWindow->Flags & ImGuiWindowFlags_ShowBorders) ? true : false, ImGuiWindowFlags_NoMove | ImGuiWindowFlags_AlwaysUseWindowPadding | extra_flags);
}
void ImGui::EndChildFrame()
{
ImGui::EndChild();
ImGui::PopStyleVar(2);
ImGui::PopStyleColor();
}
// 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;
int* p_backup = &window->DC.StackSizesBackup[0];
{ int current = window->IDStack.Size; if (write) *p_backup = current; else IM_ASSERT(*p_backup == current && "PushID/PopID Mismatch!"); p_backup++; } // User forgot PopID()
{ int current = window->DC.GroupStack.Size; if (write) *p_backup = current; else IM_ASSERT(*p_backup == current && "BeginGroup/EndGroup Mismatch!"); p_backup++; } // User forgot EndGroup()
{ int current = g.CurrentPopupStack.Size; if (write) *p_backup = current; else IM_ASSERT(*p_backup == current && "BeginMenu/EndMenu or BeginPopup/EndPopup Mismatch"); p_backup++; }// User forgot EndPopup()/EndMenu()
{ int current = g.ColorModifiers.Size; if (write) *p_backup = current; else IM_ASSERT(*p_backup == current && "PushStyleColor/PopStyleColor Mismatch!"); p_backup++; } // User forgot PopStyleColor()
{ int current = g.StyleModifiers.Size; if (write) *p_backup = current; else IM_ASSERT(*p_backup == current && "PushStyleVar/PopStyleVar Mismatch!"); p_backup++; } // User forgot PopStyleVar()
{ int current = g.FontStack.Size; if (write) *p_backup = current; else IM_ASSERT(*p_backup == current && "PushFont/PopFont Mismatch!"); p_backup++; } // User forgot PopFont()
IM_ASSERT(p_backup == window->DC.StackSizesBackup + IM_ARRAYSIZE(window->DC.StackSizesBackup));
}
static ImVec2 FindBestPopupWindowPos(const ImVec2& base_pos, const ImVec2& size, int* last_dir, const ImRect& r_inner)
{
const ImGuiStyle& style = GImGui->Style;
// Clamp into visible area while not overlapping the cursor. Safety padding is optional if our popup size won't fit without it.
ImVec2 safe_padding = style.DisplaySafeAreaPadding;
ImRect r_outer(GetVisibleRect());
r_outer.Reduce(ImVec2((size.x - r_outer.GetWidth() > safe_padding.x*2) ? safe_padding.x : 0.0f, (size.y - r_outer.GetHeight() > safe_padding.y*2) ? safe_padding.y : 0.0f));
ImVec2 base_pos_clamped = ImClamp(base_pos, r_outer.Min, r_outer.Max - size);
for (int n = (*last_dir != -1) ? -1 : 0; n < 4; n++) // Last, Right, down, up, left. (Favor last used direction).
{
const int dir = (n == -1) ? *last_dir : n;
ImRect rect(dir == 0 ? r_inner.Max.x : r_outer.Min.x, dir == 1 ? r_inner.Max.y : r_outer.Min.y, dir == 3 ? r_inner.Min.x : r_outer.Max.x, dir == 2 ? r_inner.Min.y : r_outer.Max.y);
if (rect.GetWidth() < size.x || rect.GetHeight() < size.y)
continue;
*last_dir = dir;
return ImVec2(dir == 0 ? r_inner.Max.x : dir == 3 ? r_inner.Min.x - size.x : base_pos_clamped.x, dir == 1 ? r_inner.Max.y : dir == 2 ? r_inner.Min.y - size.y : base_pos_clamped.y);
}
// Fallback, try to keep within display
*last_dir = -1;
ImVec2 pos = base_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;
}
ImGuiWindow* ImGui::FindWindowByName(const char* name)
{
// FIXME-OPT: Store sorted hashes -> pointers so we can do a bissection in a contiguous block
ImGuiContext& g = *GImGui;
ImGuiID id = ImHash(name, 0);
for (int i = 0; i < g.Windows.Size; i++)
if (g.Windows[i]->ID == id)
return g.Windows[i];
return NULL;
}
static ImGuiWindow* CreateNewWindow(const char* name, ImVec2 size, ImGuiWindowFlags flags)
{
ImGuiContext& g = *GImGui;
// Create window the first time
ImGuiWindow* window = (ImGuiWindow*)ImGui::MemAlloc(sizeof(ImGuiWindow));
IM_PLACEMENT_NEW(window) ImGuiWindow(name);
window->Flags = flags;
if (flags & ImGuiWindowFlags_NoSavedSettings)
{
// User can disable loading and saving of settings. Tooltip and child windows also don't store settings.
window->Size = window->SizeFull = size;
}
else
{
// Retrieve settings from .ini file
// Use SetWindowPos() or SetNextWindowPos() with the appropriate condition flag to change the initial position of a window.
window->PosFloat = ImVec2(60, 60);
window->Pos = ImVec2((float)(int)window->PosFloat.x, (float)(int)window->PosFloat.y);
ImGuiIniData* settings = FindWindowSettings(name);
if (!settings)
{
settings = AddWindowSettings(name);
}
else
{
window->SetWindowPosAllowFlags &= ~ImGuiSetCond_FirstUseEver;
window->SetWindowSizeAllowFlags &= ~ImGuiSetCond_FirstUseEver;
window->SetWindowCollapsedAllowFlags &= ~ImGuiSetCond_FirstUseEver;
}
if (settings->Pos.x != FLT_MAX)
{
window->PosFloat = settings->Pos;
window->Pos = ImVec2((float)(int)window->PosFloat.x, (float)(int)window->PosFloat.y);
window->Collapsed = settings->Collapsed;
}
if (ImLengthSqr(settings->Size) > 0.00001f && !(flags & ImGuiWindowFlags_NoResize))
size = settings->Size;
window->Size = window->SizeFull = size;
}
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);
}
if (flags & ImGuiWindowFlags_NoBringToFrontOnFocus)
g.Windows.insert(g.Windows.begin(), window); // Quite slow but rare and only once
else
g.Windows.push_back(window);
return window;
}
static void ApplySizeFullWithConstraint(ImGuiWindow* window, ImVec2 new_size)
{
ImGuiContext& g = *GImGui;
if (g.SetNextWindowSizeConstraint)
{
// Using -1,-1 on either X/Y axis to preserve the current size.
ImRect cr = g.SetNextWindowSizeConstraintRect;
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.SetNextWindowSizeConstraintCallback)
{
ImGuiSizeConstraintCallbackData data;
data.UserData = g.SetNextWindowSizeConstraintCallbackUserData;
data.Pos = window->Pos;
data.CurrentSize = window->SizeFull;
data.DesiredSize = new_size;
g.SetNextWindowSizeConstraintCallback(&data);
new_size = data.DesiredSize;
}
}
if (!(window->Flags & (ImGuiWindowFlags_ChildWindow | ImGuiWindowFlags_AlwaysAutoResize)))
new_size = ImMax(new_size, g.Style.WindowMinSize);
window->SizeFull = new_size;
}
// Push a new 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.
// - 'size_on_first_use' for a regular window denote the initial size for first-time creation (no saved data) and isn't that useful. Use SetNextWindowSize() prior to calling Begin() for more flexible window manipulation.
// - 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.
// - Passing non-zero 'size' is roughly equivalent to calling SetNextWindowSize(size, ImGuiSetCond_FirstUseEver) prior to calling Begin().
bool ImGui::Begin(const char* name, bool* p_open, ImGuiWindowFlags flags)
{
return ImGui::Begin(name, p_open, ImVec2(0.f, 0.f), -1.0f, flags);
}
bool ImGui::Begin(const char* name, bool* p_open, const ImVec2& size_on_first_use, float bg_alpha, ImGuiWindowFlags flags)
{
ImGuiContext& g = *GImGui;
const ImGuiStyle& style = g.Style;
IM_ASSERT(name != NULL); // Window name required
IM_ASSERT(g.Initialized); // 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
if (flags & ImGuiWindowFlags_NoInputs)
flags |= ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoResize;
// Find or create
bool window_is_new = false;
ImGuiWindow* window = FindWindowByName(name);
if (!window)
{
window = CreateNewWindow(name, size_on_first_use, flags);
window_is_new = true;
}
const int current_frame = ImGui::GetFrameCount();
const bool first_begin_of_the_frame = (window->LastFrameActive != current_frame);
if (first_begin_of_the_frame)
window->Flags = (ImGuiWindowFlags)flags;
else
flags = window->Flags;
// Add to stack
ImGuiWindow* parent_window = !g.CurrentWindowStack.empty() ? g.CurrentWindowStack.back() : NULL;
g.CurrentWindowStack.push_back(window);
SetCurrentWindow(window);
CheckStacksSize(window, true);
IM_ASSERT(parent_window != NULL || !(flags & ImGuiWindowFlags_ChildWindow));
bool window_was_active = (window->LastFrameActive == current_frame - 1); // Not using !WasActive because the implicit "Debug" window would always toggle off->on
if (flags & ImGuiWindowFlags_Popup)
{
ImGuiPopupRef& popup_ref = g.OpenPopupStack[g.CurrentPopupStack.Size];
window_was_active &= (window->PopupId == popup_ref.PopupId);
window_was_active &= (window == popup_ref.Window);
popup_ref.Window = window;
g.CurrentPopupStack.push_back(popup_ref);
window->PopupId = popup_ref.PopupId;
}
const bool window_appearing_after_being_hidden = (window->HiddenFrames == 1);
// Process SetNextWindow***() calls
bool window_pos_set_by_api = false, window_size_set_by_api = false;
if (g.SetNextWindowPosCond)
{
const ImVec2 backup_cursor_pos = window->DC.CursorPos; // FIXME: not sure of the exact reason of this saving/restore anymore :( need to look into that.
if (!window_was_active || window_appearing_after_being_hidden) window->SetWindowPosAllowFlags |= ImGuiSetCond_Appearing;
window_pos_set_by_api = (window->SetWindowPosAllowFlags & g.SetNextWindowPosCond) != 0;
if (window_pos_set_by_api && ImLengthSqr(g.SetNextWindowPosVal - ImVec2(-FLT_MAX,-FLT_MAX)) < 0.001f)
{
window->SetWindowPosCenterWanted = true; // May be processed on the next frame if this is our first frame and we are measuring size
window->SetWindowPosAllowFlags &= ~(ImGuiSetCond_Once | ImGuiSetCond_FirstUseEver | ImGuiSetCond_Appearing);
}
else
{
SetWindowPos(window, g.SetNextWindowPosVal, g.SetNextWindowPosCond);
}
window->DC.CursorPos = backup_cursor_pos;
g.SetNextWindowPosCond = 0;
}
if (g.SetNextWindowSizeCond)
{
if (!window_was_active || window_appearing_after_being_hidden) window->SetWindowSizeAllowFlags |= ImGuiSetCond_Appearing;
window_size_set_by_api = (window->SetWindowSizeAllowFlags & g.SetNextWindowSizeCond) != 0;
SetWindowSize(window, g.SetNextWindowSizeVal, g.SetNextWindowSizeCond);
g.SetNextWindowSizeCond = 0;
}
if (g.SetNextWindowContentSizeCond)
{
window->SizeContentsExplicit = g.SetNextWindowContentSizeVal;
g.SetNextWindowContentSizeCond = 0;
}
else if (first_begin_of_the_frame)
{
window->SizeContentsExplicit = ImVec2(0.0f, 0.0f);
}
if (g.SetNextWindowCollapsedCond)
{
if (!window_was_active || window_appearing_after_being_hidden) window->SetWindowCollapsedAllowFlags |= ImGuiSetCond_Appearing;
SetWindowCollapsed(window, g.SetNextWindowCollapsedVal, g.SetNextWindowCollapsedCond);
g.SetNextWindowCollapsedCond = 0;
}
if (g.SetNextWindowFocus)
{
ImGui::SetWindowFocus();
g.SetNextWindowFocus = false;
}
// Update known root window (if we are a child window, otherwise window == window->RootWindow)
int root_idx, root_non_popup_idx;
for (root_idx = g.CurrentWindowStack.Size - 1; root_idx > 0; root_idx--)
if (!(g.CurrentWindowStack[root_idx]->Flags & ImGuiWindowFlags_ChildWindow))
break;
for (root_non_popup_idx = root_idx; root_non_popup_idx > 0; root_non_popup_idx--)
if (!(g.CurrentWindowStack[root_non_popup_idx]->Flags & (ImGuiWindowFlags_ChildWindow | ImGuiWindowFlags_Popup)))
break;
window->ParentWindow = parent_window;
window->RootWindow = g.CurrentWindowStack[root_idx];
window->RootNonPopupWindow = g.CurrentWindowStack[root_non_popup_idx]; // This is merely for displaying the TitleBgActive color.
// When reusing window again multiple times a frame, just append content (don't need to setup again)
if (first_begin_of_the_frame)
{
window->Active = true;
window->IndexWithinParent = 0;
window->BeginCount = 0;
window->ClipRect = ImVec4(-FLT_MAX,-FLT_MAX,+FLT_MAX,+FLT_MAX);
window->LastFrameActive = current_frame;
window->IDStack.resize(1);
// Clear draw list, setup texture, outer clipping rectangle
window->DrawList->Clear();
window->DrawList->PushTextureID(g.Font->ContainerAtlas->TexID);
ImRect fullscreen_rect(GetVisibleRect());
if ((flags & ImGuiWindowFlags_ChildWindow) && !(flags & (ImGuiWindowFlags_ComboBox|ImGuiWindowFlags_Popup)))
PushClipRect(parent_window->ClipRect.Min, parent_window->ClipRect.Max, true);
else
PushClipRect(fullscreen_rect.Min, fullscreen_rect.Max, true);
if (!window_was_active)
{
// Popup first latch mouse position, will position itself when it appears next frame
window->AutoPosLastDirection = -1;
if ((flags & ImGuiWindowFlags_Popup) != 0 && !window_pos_set_by_api)
window->PosFloat = g.IO.MousePos;
}
// 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))
{
ImRect title_bar_rect = window->TitleBarRect();
if (g.HoveredWindow == window && IsMouseHoveringRect(title_bar_rect.Min, title_bar_rect.Max) && g.IO.MouseDoubleClicked[0])
{
window->Collapsed = !window->Collapsed;
if (!(flags & ImGuiWindowFlags_NoSavedSettings))
MarkSettingsDirty();
FocusWindow(window);
}
}
else
{
window->Collapsed = false;
}
// SIZE
// Save contents size from last frame for auto-fitting (unless explicitly specified)
window->SizeContents.x = (float)(int)((window->SizeContentsExplicit.x != 0.0f) ? window->SizeContentsExplicit.x : ((window_is_new ? 0.0f : window->DC.CursorMaxPos.x - window->Pos.x) + window->Scroll.x));
window->SizeContents.y = (float)(int)((window->SizeContentsExplicit.y != 0.0f) ? window->SizeContentsExplicit.y : ((window_is_new ? 0.0f : window->DC.CursorMaxPos.y - window->Pos.y) + window->Scroll.y));
// Hide popup/tooltip window when first appearing while we measure size (because we recycle them)
if (window->HiddenFrames > 0)
window->HiddenFrames--;
if ((flags & (ImGuiWindowFlags_Popup | ImGuiWindowFlags_Tooltip)) != 0 && !window_was_active)
{
window->HiddenFrames = 1;
if (flags & ImGuiWindowFlags_AlwaysAutoResize)
{
if (!window_size_set_by_api)
window->Size = window->SizeFull = ImVec2(0.f, 0.f);
window->SizeContents = ImVec2(0.f, 0.f);
}
}
// Lock window padding so that altering the ShowBorders flag for children doesn't have side-effects.
window->WindowPadding = ((flags & ImGuiWindowFlags_ChildWindow) && !(flags & (ImGuiWindowFlags_AlwaysUseWindowPadding | ImGuiWindowFlags_ShowBorders | ImGuiWindowFlags_ComboBox | ImGuiWindowFlags_Popup))) ? ImVec2(0,0) : style.WindowPadding;
// Calculate auto-fit size
ImVec2 size_auto_fit;
if ((flags & ImGuiWindowFlags_Tooltip) != 0)
{
// Tooltip always resize. We keep the spacing symmetric on both axises for aesthetic purpose.
size_auto_fit = window->SizeContents + window->WindowPadding - ImVec2(0.0f, style.ItemSpacing.y);
}
else
{
size_auto_fit = ImClamp(window->SizeContents + window->WindowPadding, style.WindowMinSize, ImMax(style.WindowMinSize, g.IO.DisplaySize - g.Style.DisplaySafeAreaPadding));
// Handling case of auto fit window not fitting in screen on one axis, we are growing auto fit size on the other axis to compensate for expected scrollbar. FIXME: Might turn bigger than DisplaySize-WindowPadding.
if (size_auto_fit.x < window->SizeContents.x && !(flags & ImGuiWindowFlags_NoScrollbar) && (flags & ImGuiWindowFlags_HorizontalScrollbar))
size_auto_fit.y += style.ScrollbarSize;
if (size_auto_fit.y < window->SizeContents.y && !(flags & ImGuiWindowFlags_NoScrollbar))
size_auto_fit.x += style.ScrollbarSize;
size_auto_fit.y = ImMax(size_auto_fit.y - style.ItemSpacing.y, 0.0f);
}
// Handle automatic resize
if (window->Collapsed)
{
// We still process initial auto-fit on collapsed windows to get a window width,
// But otherwise we don't honor ImGuiWindowFlags_AlwaysAutoResize when collapsed.
if (window->AutoFitFramesX > 0)
window->SizeFull.x = window->AutoFitOnlyGrows ? ImMax(window->SizeFull.x, size_auto_fit.x) : size_auto_fit.x;
if (window->AutoFitFramesY > 0)
window->SizeFull.y = window->AutoFitOnlyGrows ? ImMax(window->SizeFull.y, size_auto_fit.y) : size_auto_fit.y;
}
else
{
if ((flags & ImGuiWindowFlags_AlwaysAutoResize) && !window_size_set_by_api)
{
window->SizeFull = size_auto_fit;
}
else if ((window->AutoFitFramesX > 0 || window->AutoFitFramesY > 0) && !window_size_set_by_api)
{
// Auto-fit only grows during the first few frames
if (window->AutoFitFramesX > 0)
window->SizeFull.x = window->AutoFitOnlyGrows ? ImMax(window->SizeFull.x, size_auto_fit.x) : size_auto_fit.x;
if (window->AutoFitFramesY > 0)
window->SizeFull.y = window->AutoFitOnlyGrows ? ImMax(window->SizeFull.y, size_auto_fit.y) : size_auto_fit.y;
if (!(flags & ImGuiWindowFlags_NoSavedSettings))
MarkSettingsDirty();
}
}
// Apply minimum/maximum window size constraints and final size
ApplySizeFullWithConstraint(window, window->SizeFull);
window->Size = window->Collapsed ? window->TitleBarRect().GetSize() : window->SizeFull;
// POSITION
// Position child window
if (flags & ImGuiWindowFlags_ChildWindow)
{
window->IndexWithinParent = parent_window->DC.ChildWindows.Size;
parent_window->DC.ChildWindows.push_back(window);
}
if ((flags & ImGuiWindowFlags_ChildWindow) && !(flags & ImGuiWindowFlags_Popup))
{
window->Pos = window->PosFloat = parent_window->DC.CursorPos;
window->Size = window->SizeFull = size_on_first_use; // NB: argument name 'size_on_first_use' misleading here, it's really just 'size' as provided by user passed via BeginChild()->Begin().
}
bool window_pos_center = false;
window_pos_center |= (window->SetWindowPosCenterWanted && window->HiddenFrames == 0);
window_pos_center |= ((flags & ImGuiWindowFlags_Modal) && !window_pos_set_by_api && window_appearing_after_being_hidden);
if (window_pos_center)
{
// Center (any sort of window)
SetWindowPos(ImMax(style.DisplaySafeAreaPadding, fullscreen_rect.GetCenter() - window->SizeFull * 0.5f));
}
else if (flags & ImGuiWindowFlags_ChildMenu)
{
IM_ASSERT(window_pos_set_by_api);
ImRect rect_to_avoid;
if (parent_window->DC.MenuBarAppending)
rect_to_avoid = ImRect(-FLT_MAX, parent_window->Pos.y + parent_window->TitleBarHeight(), FLT_MAX, parent_window->Pos.y + parent_window->TitleBarHeight() + parent_window->MenuBarHeight());
else
rect_to_avoid = ImRect(parent_window->Pos.x + style.ItemSpacing.x, -FLT_MAX, parent_window->Pos.x + parent_window->Size.x - style.ItemSpacing.x - parent_window->ScrollbarSizes.x, FLT_MAX); // We want some overlap to convey the relative depth of each popup (here hard-coded to 4)
window->PosFloat = FindBestPopupWindowPos(window->PosFloat, window->Size, &window->AutoPosLastDirection, rect_to_avoid);
}
else if ((flags & ImGuiWindowFlags_Popup) != 0 && !window_pos_set_by_api && window_appearing_after_being_hidden)
{
ImRect rect_to_avoid(window->PosFloat.x - 1, window->PosFloat.y - 1, window->PosFloat.x + 1, window->PosFloat.y + 1);
window->PosFloat = FindBestPopupWindowPos(window->PosFloat, window->Size, &window->AutoPosLastDirection, rect_to_avoid);
}
// Position tooltip (always follows mouse)
if ((flags & ImGuiWindowFlags_Tooltip) != 0 && !window_pos_set_by_api)
{
ImRect rect_to_avoid(g.IO.MousePos.x - 16, g.IO.MousePos.y - 8, g.IO.MousePos.x + 24, g.IO.MousePos.y + 24); // FIXME: Completely hard-coded. Perhaps center on cursor hit-point instead?
window->PosFloat = FindBestPopupWindowPos(g.IO.MousePos, window->Size, &window->AutoPosLastDirection, rect_to_avoid);
if (window->AutoPosLastDirection == -1)
window->PosFloat = g.IO.MousePos + 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.
}
// Clamp position so it stays visible
if (!(flags & ImGuiWindowFlags_ChildWindow) && !(flags & ImGuiWindowFlags_Tooltip))
{
if (!window_pos_set_by_api && window->AutoFitFramesX <= 0 && window->AutoFitFramesY <= 0 && 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 padding = ImMax(style.DisplayWindowPadding, style.DisplaySafeAreaPadding);
window->PosFloat = ImMax(window->PosFloat + window->Size, padding) - window->Size;
window->PosFloat = ImMin(window->PosFloat, g.IO.DisplaySize - padding);
}
}
window->Pos = ImVec2((float)(int)window->PosFloat.x, (float)(int)window->PosFloat.y);
// 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);
// Prepare for focus requests
window->FocusIdxAllRequestCurrent = (window->FocusIdxAllRequestNext == INT_MAX || window->FocusIdxAllCounter == -1) ? INT_MAX : (window->FocusIdxAllRequestNext + (window->FocusIdxAllCounter+1)) % (window->FocusIdxAllCounter+1);
window->FocusIdxTabRequestCurrent = (window->FocusIdxTabRequestNext == INT_MAX || window->FocusIdxTabCounter == -1) ? INT_MAX : (window->FocusIdxTabRequestNext + (window->FocusIdxTabCounter+1)) % (window->FocusIdxTabCounter+1);
window->FocusIdxAllCounter = window->FocusIdxTabCounter = -1;
window->FocusIdxAllRequestNext = window->FocusIdxTabRequestNext = INT_MAX;
// Apply scrolling
if (window->ScrollTarget.x < FLT_MAX)
{
window->Scroll.x = window->ScrollTarget.x;
window->ScrollTarget.x = FLT_MAX;
}
if (window->ScrollTarget.y < FLT_MAX)
{
float center_ratio = window->ScrollTargetCenterRatio.y;
window->Scroll.y = window->ScrollTarget.y - ((1.0f - center_ratio) * (window->TitleBarHeight() + window->MenuBarHeight())) - (center_ratio * window->SizeFull.y);
window->ScrollTarget.y = FLT_MAX;
}
window->Scroll = ImMax(window->Scroll, ImVec2(0.0f, 0.0f));
if (!window->Collapsed && !window->SkipItems)
window->Scroll = ImMin(window->Scroll, ImMax(ImVec2(0.0f, 0.0f), window->SizeContents - window->SizeFull + window->ScrollbarSizes));
// Modal window darkens what is behind them
if ((flags & ImGuiWindowFlags_Modal) != 0 && window == GetFrontMostModalRootWindow())
window->DrawList->AddRectFilled(fullscreen_rect.Min, fullscreen_rect.Max, GetColorU32(ImGuiCol_ModalWindowDarkening, g.ModalWindowDarkeningRatio));
// Draw window + handle manual resize
ImRect title_bar_rect = window->TitleBarRect();
const float window_rounding = (flags & ImGuiWindowFlags_ChildWindow) ? style.ChildWindowRounding : style.WindowRounding;
if (window->Collapsed)
{
// Draw title bar only
RenderFrame(title_bar_rect.GetTL(), title_bar_rect.GetBR(), GetColorU32(ImGuiCol_TitleBgCollapsed), true, window_rounding);
}
else
{
ImU32 resize_col = 0;
const float resize_corner_size = ImMax(g.FontSize * 1.35f, window_rounding + 1.0f + g.FontSize * 0.2f);
if (!(flags & ImGuiWindowFlags_AlwaysAutoResize) && window->AutoFitFramesX <= 0 && window->AutoFitFramesY <= 0 && !(flags & ImGuiWindowFlags_NoResize))
{
// Manual resize
const ImVec2 br = window->Rect().GetBR();
const ImRect resize_rect(br - ImVec2(resize_corner_size * 0.75f, resize_corner_size * 0.75f), br);
const ImGuiID resize_id = window->GetID("#RESIZE");
bool hovered, held;
ButtonBehavior(resize_rect, resize_id, &hovered, &held, ImGuiButtonFlags_FlattenChilds);
resize_col = GetColorU32(held ? ImGuiCol_ResizeGripActive : hovered ? ImGuiCol_ResizeGripHovered : ImGuiCol_ResizeGrip);
if (hovered || held)
g.MouseCursor = ImGuiMouseCursor_ResizeNWSE;
if (g.HoveredWindow == window && held && g.IO.MouseDoubleClicked[0])
{
// Manual auto-fit when double-clicking
ApplySizeFullWithConstraint(window, size_auto_fit);
if (!(flags & ImGuiWindowFlags_NoSavedSettings))
MarkSettingsDirty();
SetActiveID(0);
}
else if (held)
{
// We don't use an incremental MouseDelta but rather compute an absolute target size based on mouse position
ApplySizeFullWithConstraint(window, (g.IO.MousePos - g.ActiveIdClickOffset + resize_rect.GetSize()) - window->Pos);
if (!(flags & ImGuiWindowFlags_NoSavedSettings))
MarkSettingsDirty();
}
window->Size = window->SizeFull;
title_bar_rect = window->TitleBarRect();
}
// Scrollbars
window->ScrollbarY = (flags & ImGuiWindowFlags_AlwaysVerticalScrollbar) || ((window->SizeContents.y > window->Size.y + style.ItemSpacing.y) && !(flags & ImGuiWindowFlags_NoScrollbar));
window->ScrollbarX = (flags & ImGuiWindowFlags_AlwaysHorizontalScrollbar) || ((window->SizeContents.x > window->Size.x - (window->ScrollbarY ? style.ScrollbarSize : 0.0f) - window->WindowPadding.x) && !(flags & ImGuiWindowFlags_NoScrollbar) && (flags & ImGuiWindowFlags_HorizontalScrollbar));
window->ScrollbarSizes = ImVec2(window->ScrollbarY ? style.ScrollbarSize : 0.0f, window->ScrollbarX ? style.ScrollbarSize : 0.0f);
window->BorderSize = (flags & ImGuiWindowFlags_ShowBorders) ? 1.0f : 0.0f;
// Window background
// Default alpha
ImGuiCol bg_color_idx = ImGuiCol_WindowBg;
if ((flags & ImGuiWindowFlags_ComboBox) != 0)
bg_color_idx = ImGuiCol_ComboBg;
else if ((flags & ImGuiWindowFlags_Tooltip) != 0 || (flags & ImGuiWindowFlags_Popup) != 0)
bg_color_idx = ImGuiCol_PopupBg;
else if ((flags & ImGuiWindowFlags_ChildWindow) != 0)
bg_color_idx = ImGuiCol_ChildWindowBg;
ImVec4 bg_color = style.Colors[bg_color_idx];
if (bg_alpha >= 0.0f)
bg_color.w = bg_alpha;
bg_color.w *= style.Alpha;
if (bg_color.w > 0.0f)
window->DrawList->AddRectFilled(window->Pos+ImVec2(0,window->TitleBarHeight()), window->Pos+window->Size, ColorConvertFloat4ToU32(bg_color), window_rounding, (flags & ImGuiWindowFlags_NoTitleBar) ? 15 : 4|8);
// Title bar
if (!(flags & ImGuiWindowFlags_NoTitleBar))
window->DrawList->AddRectFilled(title_bar_rect.GetTL(), title_bar_rect.GetBR(), GetColorU32((g.FocusedWindow && window->RootNonPopupWindow == g.FocusedWindow->RootNonPopupWindow) ? ImGuiCol_TitleBgActive : ImGuiCol_TitleBg), window_rounding, 1|2);
// Menu bar
if (flags & ImGuiWindowFlags_MenuBar)
{
ImRect menu_bar_rect = window->MenuBarRect();
window->DrawList->AddRectFilled(menu_bar_rect.GetTL(), menu_bar_rect.GetBR(), GetColorU32(ImGuiCol_MenuBarBg), (flags & ImGuiWindowFlags_NoTitleBar) ? window_rounding : 0.0f, 1|2);
if (flags & ImGuiWindowFlags_ShowBorders)
window->DrawList->AddLine(menu_bar_rect.GetBL()-ImVec2(0,0), menu_bar_rect.GetBR()-ImVec2(0,0), GetColorU32(ImGuiCol_Border));
}
// Scrollbars
if (window->ScrollbarX)
Scrollbar(window, true);
if (window->ScrollbarY)
Scrollbar(window, false);
// Render resize grip
// (after the input handling so we don't have a frame of latency)
if (!(flags & ImGuiWindowFlags_NoResize))
{
const ImVec2 br = window->Rect().GetBR();
window->DrawList->PathLineTo(br + ImVec2(-resize_corner_size, -window->BorderSize));
window->DrawList->PathLineTo(br + ImVec2(-window->BorderSize, -resize_corner_size));
window->DrawList->PathArcToFast(ImVec2(br.x - window_rounding - window->BorderSize, br.y - window_rounding - window->BorderSize), window_rounding, 0, 3);
window->DrawList->PathFill(resize_col);
}
// Borders
if (flags & ImGuiWindowFlags_ShowBorders)
{
window->DrawList->AddRect(window->Pos+ImVec2(1,1), window->Pos+window->Size+ImVec2(1,1), GetColorU32(ImGuiCol_BorderShadow), window_rounding);
window->DrawList->AddRect(window->Pos, window->Pos+window->Size, GetColorU32(ImGuiCol_Border), window_rounding);
if (!(flags & ImGuiWindowFlags_NoTitleBar))
window->DrawList->AddLine(title_bar_rect.GetBL()+ImVec2(1,0), title_bar_rect.GetBR()-ImVec2(1,0), GetColorU32(ImGuiCol_Border));
}
}
// Update ContentsRegionMax. All the variable it depends on are set above in this function.
window->ContentsRegionRect.Min.x = -window->Scroll.x + window->WindowPadding.x;
window->ContentsRegionRect.Min.y = -window->Scroll.y + window->WindowPadding.y + window->TitleBarHeight() + window->MenuBarHeight();
window->ContentsRegionRect.Max.x = -window->Scroll.x - window->WindowPadding.x + (window->SizeContentsExplicit.x != 0.0f ? window->SizeContentsExplicit.x : (window->Size.x - window->ScrollbarSizes.x));
window->ContentsRegionRect.Max.y = -window->Scroll.y - window->WindowPadding.y + (window->SizeContentsExplicit.y != 0.0f ? window->SizeContentsExplicit.y : (window->Size.y - window->ScrollbarSizes.y));
// Setup drawing context
window->DC.IndentX = 0.0f + window->WindowPadding.x - window->Scroll.x;
window->DC.GroupOffsetX = 0.0f;
window->DC.ColumnsOffsetX = 0.0f;
window->DC.CursorStartPos = window->Pos + ImVec2(window->DC.IndentX + window->DC.ColumnsOffsetX, window->TitleBarHeight() + window->MenuBarHeight() + 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.CurrentLineHeight = window->DC.PrevLineHeight = 0.0f;
window->DC.CurrentLineTextBaseOffset = window->DC.PrevLineTextBaseOffset = 0.0f;
window->DC.MenuBarAppending = false;
window->DC.MenuBarOffsetX = ImMax(window->WindowPadding.x, style.ItemSpacing.x);
window->DC.LogLinePosY = window->DC.CursorPos.y - 9999.0f;
window->DC.ChildWindows.resize(0);
window->DC.LayoutType = ImGuiLayoutType_Vertical;
window->DC.ItemWidth = window->ItemWidthDefault;
window->DC.TextWrapPos = -1.0f; // disabled
window->DC.AllowKeyboardFocus = true;
window->DC.ButtonRepeat = false;
window->DC.ItemWidthStack.resize(0);
window->DC.TextWrapPosStack.resize(0);
window->DC.AllowKeyboardFocusStack.resize(0);
window->DC.ButtonRepeatStack.resize(0);
window->DC.ColorEditMode = ImGuiColorEditMode_UserSelect;
window->DC.ColumnsCurrent = 0;
window->DC.ColumnsCount = 1;
window->DC.ColumnsStartPosY = window->DC.CursorPos.y;
window->DC.ColumnsCellMinY = window->DC.ColumnsCellMaxY = window->DC.ColumnsStartPosY;
window->DC.TreeDepth = 0;
window->DC.StateStorage = &window->StateStorage;
window->DC.GroupStack.resize(0);
window->MenuColumns.Update(3, style.ItemSpacing.x, !window_was_active);
if (window->AutoFitFramesX > 0)
window->AutoFitFramesX--;
if (window->AutoFitFramesY > 0)
window->AutoFitFramesY--;
// New windows appears in front (we need to do that AFTER setting DC.CursorStartPos so our initial navigation reference rectangle can start around there)
if (!window_was_active && !(flags & ImGuiWindowFlags_NoFocusOnAppearing))
if (!(flags & (ImGuiWindowFlags_ChildWindow|ImGuiWindowFlags_Tooltip)) || (flags & ImGuiWindowFlags_Popup))
FocusWindow(window);
// Title bar
if (!(flags & ImGuiWindowFlags_NoTitleBar))
{
if (p_open != NULL)
{
const float pad = 2.0f;
const float rad = (window->TitleBarHeight() - pad*2.0f) * 0.5f;
if (CloseButton(window->GetID("#CLOSE"), window->Rect().GetTR() + ImVec2(-pad - rad, pad + rad), rad))
*p_open = false;
}
const ImVec2 text_size = CalcTextSize(name, NULL, true);
if (!(flags & ImGuiWindowFlags_NoCollapse))
RenderCollapseTriangle(window->Pos + style.FramePadding, !window->Collapsed, 1.0f, true);
ImVec2 text_min = window->Pos + style.FramePadding;
ImVec2 text_max = window->Pos + ImVec2(window->Size.x - style.FramePadding.x, style.FramePadding.y*2 + text_size.y);
ImVec2 clip_max = ImVec2(window->Pos.x + window->Size.x - (p_open ? title_bar_rect.GetHeight() - 3 : style.FramePadding.x), text_max.y); // Match the size of CloseWindowButton()
bool pad_left = (flags & ImGuiWindowFlags_NoCollapse) == 0;
bool pad_right = (p_open != NULL);
if (style.WindowTitleAlign & ImGuiAlign_Center) pad_right = pad_left;
if (pad_left) text_min.x += g.FontSize + style.ItemInnerSpacing.x;
if (pad_right) text_max.x -= g.FontSize + style.ItemInnerSpacing.x;
ImVec2 clip_min = ImVec2(text_min.x, window->Pos.y);
RenderTextClipped(text_min, text_max, name, NULL, &text_size, style.WindowTitleAlign, &clip_min, &clip_max);
}
// Save clipped aabb so we can access it in constant-time in FindHoveredWindow()
window->WindowRectClipped = window->Rect();
window->WindowRectClipped.Clip(window->ClipRect);
// 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))
ImGui::LogToClipboard();
*/
}
// Inner clipping rectangle
// We set this up after processing the resize grip so that our clip rectangle doesn't lag by a frame
// Note that if our window is collapsed we will end up with a null clipping rectangle which is the correct behavior.
const ImRect title_bar_rect = window->TitleBarRect();
const float border_size = window->BorderSize;
ImRect clip_rect; // Force round to ensure that e.g. (int)(max.x-min.x) in user's render code produce correct result.
clip_rect.Min.x = ImFloor(0.5f + title_bar_rect.Min.x + ImMax(border_size, ImFloor(window->WindowPadding.x*0.5f)));
clip_rect.Min.y = ImFloor(0.5f + title_bar_rect.Max.y + window->MenuBarHeight() + border_size);
clip_rect.Max.x = ImFloor(0.5f + window->Pos.x + window->Size.x - window->ScrollbarSizes.x - ImMax(border_size, ImFloor(window->WindowPadding.x*0.5f)));
clip_rect.Max.y = ImFloor(0.5f + window->Pos.y + window->Size.y - window->ScrollbarSizes.y - border_size);
PushClipRect(clip_rect.Min, clip_rect.Max, true);
// Clear 'accessed' flag last thing
if (first_begin_of_the_frame)
window->Accessed = false;
window->BeginCount++;
g.SetNextWindowSizeConstraint = false;
// 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 because they have no title bar).
if (flags & ImGuiWindowFlags_ChildWindow)
{
IM_ASSERT((flags & ImGuiWindowFlags_NoTitleBar) != 0);
window->Collapsed = parent_window && parent_window->Collapsed;
if (!(flags & ImGuiWindowFlags_AlwaysAutoResize) && window->AutoFitFramesX <= 0 && window->AutoFitFramesY <= 0)
window->Collapsed |= (window->WindowRectClipped.Min.x >= window->WindowRectClipped.Max.x || window->WindowRectClipped.Min.y >= window->WindowRectClipped.Max.y);
// We also hide the window from rendering because we've already added its border to the command list.
// (we could perform the check earlier in the function but it is simpler at this point)
if (window->Collapsed)
window->Active = false;
}
if (style.Alpha <= 0.0f)
window->Active = false;
// Return false if we don't intend to display anything to allow user to perform an early out optimization
window->SkipItems = (window->Collapsed || !window->Active) && window->AutoFitFramesX <= 0 && window->AutoFitFramesY <= 0;
return !window->SkipItems;
}
void ImGui::End()
{
ImGuiContext& g = *GImGui;
ImGuiWindow* window = g.CurrentWindow;
Columns(1, "#CloseColumns");
PopClipRect(); // inner window clip rectangle
// Stop logging
if (!(window->Flags & ImGuiWindowFlags_ChildWindow)) // FIXME: add more options for scope of logging
LogFinish();
// Pop
// NB: we don't clear 'window->RootWindow'. The pointer is allowed to live until the next call to Begin().
g.CurrentWindowStack.pop_back();
if (window->Flags & ImGuiWindowFlags_Popup)
g.CurrentPopupStack.pop_back();
CheckStacksSize(window, false);
SetCurrentWindow(g.CurrentWindowStack.empty() ? NULL : g.CurrentWindowStack.back());
}
// Vertical 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.
static void Scrollbar(ImGuiWindow* window, bool horizontal)
{
ImGuiContext& g = *GImGui;
const ImGuiStyle& style = g.Style;
const ImGuiID id = window->GetID(horizontal ? "#SCROLLX" : "#SCROLLY");
// Render background
bool other_scrollbar = (horizontal ? window->ScrollbarY : window->ScrollbarX);
float other_scrollbar_size_w = other_scrollbar ? style.ScrollbarSize : 0.0f;
const ImRect window_rect = window->Rect();
const float border_size = window->BorderSize;
ImRect bb = horizontal
? ImRect(window->Pos.x + border_size, window_rect.Max.y - style.ScrollbarSize, window_rect.Max.x - other_scrollbar_size_w - border_size, window_rect.Max.y - border_size)
: ImRect(window_rect.Max.x - style.ScrollbarSize, window->Pos.y + border_size, window_rect.Max.x - border_size, window_rect.Max.y - other_scrollbar_size_w - border_size);
if (!horizontal)
bb.Min.y += window->TitleBarHeight() + ((window->Flags & ImGuiWindowFlags_MenuBar) ? window->MenuBarHeight() : 0.0f);
float window_rounding = (window->Flags & ImGuiWindowFlags_ChildWindow) ? style.ChildWindowRounding : style.WindowRounding;
int window_rounding_corners;
if (horizontal)
window_rounding_corners = 8 | (other_scrollbar ? 0 : 4);
else
window_rounding_corners = (((window->Flags & ImGuiWindowFlags_NoTitleBar) && !(window->Flags & ImGuiWindowFlags_MenuBar)) ? 2 : 0) | (other_scrollbar ? 0 : 4);
window->DrawList->AddRectFilled(bb.Min, bb.Max, ImGui::GetColorU32(ImGuiCol_ScrollbarBg), window_rounding, window_rounding_corners);
bb.Reduce(ImVec2(ImClamp((float)(int)((bb.Max.x - bb.Min.x - 2.0f) * 0.5f), 0.0f, 3.0f), ImClamp((float)(int)((bb.Max.y - bb.Min.y - 2.0f) * 0.5f), 0.0f, 3.0f)));
// V denote the main axis of the scrollbar
float scrollbar_size_v = horizontal ? bb.GetWidth() : bb.GetHeight();
float scroll_v = horizontal ? window->Scroll.x : window->Scroll.y;
float win_size_avail_v = (horizontal ? window->Size.x : window->Size.y) - other_scrollbar_size_w;
float win_size_contents_v = horizontal ? window->SizeContents.x : window->SizeContents.y;
// The grabable box size 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.
const float grab_h_pixels = ImMin(ImMax(scrollbar_size_v * ImSaturate(win_size_avail_v / ImMax(win_size_contents_v, win_size_avail_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;
const bool previously_held = (g.ActiveId == id);
ImGui::ButtonBehavior(bb, id, &hovered, &held);
float scroll_max = ImMax(1.0f, win_size_contents_v - win_size_avail_v);
float scroll_ratio = ImSaturate(scroll_v / scroll_max);
float grab_v_norm = scroll_ratio * (scrollbar_size_v - grab_h_pixels) / scrollbar_size_v;
if (held && 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;
float* click_delta_to_grab_center_v = horizontal ? &g.ScrollbarClickDeltaToGrabCenter.x : &g.ScrollbarClickDeltaToGrabCenter.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);
ImGui::SetHoveredID(id);
bool seek_absolute = false;
if (!previously_held)
{
// On initial click calculate the distance between mouse and the center of the grab
if (clicked_v_norm >= grab_v_norm && clicked_v_norm <= grab_v_norm + grab_h_norm)
{
*click_delta_to_grab_center_v = clicked_v_norm - grab_v_norm - grab_h_norm*0.5f;
}
else
{
seek_absolute = true;
*click_delta_to_grab_center_v = 0.0f;
}
}
// Apply scroll
// It is ok to modify Scroll here because we are being called in Begin() after the calculation of SizeContents and before setting up our starting position
const float scroll_v_norm = ImSaturate((clicked_v_norm - *click_delta_to_grab_center_v - grab_h_norm*0.5f) / (1.0f - grab_h_norm));
scroll_v = (float)(int)(0.5f + scroll_v_norm * scroll_max);//(win_size_contents_v - win_size_v));
if (horizontal)
window->Scroll.x = scroll_v;
else
window->Scroll.y = scroll_v;
// Update values for rendering
scroll_ratio = ImSaturate(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)
*click_delta_to_grab_center_v = clicked_v_norm - grab_v_norm - grab_h_norm*0.5f;
}
// Render
const ImU32 grab_col = ImGui::GetColorU32(held ? ImGuiCol_ScrollbarGrabActive : hovered ? ImGuiCol_ScrollbarGrabHovered : ImGuiCol_ScrollbarGrab);
if (horizontal)
window->DrawList->AddRectFilled(ImVec2(ImLerp(bb.Min.x, bb.Max.x, grab_v_norm), bb.Min.y), ImVec2(ImLerp(bb.Min.x, bb.Max.x, grab_v_norm) + grab_h_pixels, bb.Max.y), grab_col, style.ScrollbarRounding);
else
window->DrawList->AddRectFilled(ImVec2(bb.Min.x, ImLerp(bb.Min.y, bb.Max.y, grab_v_norm)), ImVec2(bb.Max.x, ImLerp(bb.Min.y, bb.Max.y, grab_v_norm) + grab_h_pixels), grab_col, style.ScrollbarRounding);
}
// Moving window to front of display (which happens to be back of our sorted list)
void ImGui::FocusWindow(ImGuiWindow* window)
{
ImGuiContext& g = *GImGui;
// Always mark the window we passed as focused. This is used for keyboard interactions such as tabbing.
g.FocusedWindow = window;
// Passing NULL allow to disable keyboard focus
if (!window)
return;
// And move its 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)
SetActiveID(0);
// Bring to front
if ((window->Flags & ImGuiWindowFlags_NoBringToFrontOnFocus) || g.Windows.back() == window)
return;
for (int i = 0; i < g.Windows.Size; i++)
if (g.Windows[i] == window)
{
g.Windows.erase(g.Windows.begin() + i);
break;
}
g.Windows.push_back(window);
}
void ImGui::PushItemWidth(float item_width)
{
ImGuiWindow* window = GetCurrentWindow();
window->DC.ItemWidth = (item_width == 0.0f ? window->ItemWidthDefault : item_width);
window->DC.ItemWidthStack.push_back(window->DC.ItemWidth);
}
static void PushMultiItemsWidths(int components, float w_full)
{
ImGuiWindow* window = ImGui::GetCurrentWindow();
const ImGuiStyle& style = GImGui->Style;
if (w_full <= 0.0f)
w_full = ImGui::CalcItemWidth();
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();
}
void ImGui::PopItemWidth()
{
ImGuiWindow* window = GetCurrentWindow();
window->DC.ItemWidthStack.pop_back();
window->DC.ItemWidth = window->DC.ItemWidthStack.empty() ? window->ItemWidthDefault : window->DC.ItemWidthStack.back();
}
float ImGui::CalcItemWidth()
{
ImGuiWindow* window = GetCurrentWindowRead();
float w = window->DC.ItemWidth;
if (w < 0.0f)
{
// Align to a right-side limit. We include 1 frame padding in the calculation because this is how the width is always used (we add 2 frame padding to it), but we could move that responsibility to the widget as well.
float width_to_right_edge = GetContentRegionAvail().x;
w = ImMax(1.0f, width_to_right_edge + w);
}
w = (float)(int)w;
return w;
}
static void 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 = g.IO.FontGlobalScale * g.Font->FontSize * g.Font->Scale;
g.FontSize = g.CurrentWindow ? g.CurrentWindow->CalcFontSize() : 0.0f;
g.FontTexUvWhitePixel = g.Font->ContainerAtlas->TexUvWhitePixel;
}
void ImGui::PushFont(ImFont* font)
{
ImGuiContext& g = *GImGui;
if (!font)
font = g.IO.Fonts->Fonts[0];
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() ? g.IO.Fonts->Fonts[0] : g.FontStack.back());
}
void ImGui::PushAllowKeyboardFocus(bool allow_keyboard_focus)
{
ImGuiWindow* window = GetCurrentWindow();
window->DC.AllowKeyboardFocus = allow_keyboard_focus;
window->DC.AllowKeyboardFocusStack.push_back(allow_keyboard_focus);
}
void ImGui::PopAllowKeyboardFocus()
{
ImGuiWindow* window = GetCurrentWindow();
window->DC.AllowKeyboardFocusStack.pop_back();
window->DC.AllowKeyboardFocus = window->DC.AllowKeyboardFocusStack.empty() ? true : window->DC.AllowKeyboardFocusStack.back();
}
void ImGui::PushButtonRepeat(bool repeat)
{
ImGuiWindow* window = GetCurrentWindow();
window->DC.ButtonRepeat = repeat;
window->DC.ButtonRepeatStack.push_back(repeat);
}
void ImGui::PopButtonRepeat()
{
ImGuiWindow* window = GetCurrentWindow();
window->DC.ButtonRepeatStack.pop_back();
window->DC.ButtonRepeat = window->DC.ButtonRepeatStack.empty() ? false : window->DC.ButtonRepeatStack.back();
}
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();
}
void ImGui::PushStyleColor(ImGuiCol idx, const ImVec4& col)
{
ImGuiContext& g = *GImGui;
ImGuiColMod backup;
backup.Col = idx;
backup.PreviousValue = 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)
{
ImGuiColMod& backup = g.ColorModifiers.back();
g.Style.Colors[backup.Col] = backup.PreviousValue;
g.ColorModifiers.pop_back();
count--;
}
}
static float* GetStyleVarFloatAddr(ImGuiStyleVar idx)
{
ImGuiContext& g = *GImGui;
switch (idx)
{
case ImGuiStyleVar_Alpha: return &g.Style.Alpha;
case ImGuiStyleVar_WindowRounding: return &g.Style.WindowRounding;
case ImGuiStyleVar_ChildWindowRounding: return &g.Style.ChildWindowRounding;
case ImGuiStyleVar_FrameRounding: return &g.Style.FrameRounding;
case ImGuiStyleVar_IndentSpacing: return &g.Style.IndentSpacing;
case ImGuiStyleVar_GrabMinSize: return &g.Style.GrabMinSize;
}
return NULL;
}
static ImVec2* GetStyleVarVec2Addr(ImGuiStyleVar idx)
{
ImGuiContext& g = *GImGui;
switch (idx)
{
case ImGuiStyleVar_WindowPadding: return &g.Style.WindowPadding;
case ImGuiStyleVar_WindowMinSize: return &g.Style.WindowMinSize;
case ImGuiStyleVar_FramePadding: return &g.Style.FramePadding;
case ImGuiStyleVar_ItemSpacing: return &g.Style.ItemSpacing;
case ImGuiStyleVar_ItemInnerSpacing: return &g.Style.ItemInnerSpacing;
}
return NULL;
}
void ImGui::PushStyleVar(ImGuiStyleVar idx, float val)
{
ImGuiContext& g = *GImGui;
float* pvar = GetStyleVarFloatAddr(idx);
IM_ASSERT(pvar != NULL); // Called function with wrong-type? Variable is not a float.
ImGuiStyleMod backup;
backup.Var = idx;
backup.PreviousValue = ImVec2(*pvar, 0.0f);
g.StyleModifiers.push_back(backup);
*pvar = val;
}
void ImGui::PushStyleVar(ImGuiStyleVar idx, const ImVec2& val)
{
ImGuiContext& g = *GImGui;
ImVec2* pvar = GetStyleVarVec2Addr(idx);
IM_ASSERT(pvar != NULL); // Called function with wrong-type? Variable is not a ImVec2.
ImGuiStyleMod backup;
backup.Var = idx;
backup.PreviousValue = *pvar;
g.StyleModifiers.push_back(backup);
*pvar = val;
}
void ImGui::PopStyleVar(int count)
{
ImGuiContext& g = *GImGui;
while (count > 0)
{
ImGuiStyleMod& backup = g.StyleModifiers.back();
if (float* pvar_f = GetStyleVarFloatAddr(backup.Var))
*pvar_f = backup.PreviousValue.x;
else if (ImVec2* pvar_v = GetStyleVarVec2Addr(backup.Var))
*pvar_v = backup.PreviousValue;
g.StyleModifiers.pop_back();
count--;
}
}
const char* ImGui::GetStyleColName(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_ChildWindowBg: return "ChildWindowBg";
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_TitleBgCollapsed: return "TitleBgCollapsed";
case ImGuiCol_TitleBgActive: return "TitleBgActive";
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_ComboBg: return "ComboBg";
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_Column: return "Column";
case ImGuiCol_ColumnHovered: return "ColumnHovered";
case ImGuiCol_ColumnActive: return "ColumnActive";
case ImGuiCol_ResizeGrip: return "ResizeGrip";
case ImGuiCol_ResizeGripHovered: return "ResizeGripHovered";
case ImGuiCol_ResizeGripActive: return "ResizeGripActive";
case ImGuiCol_CloseButton: return "CloseButton";
case ImGuiCol_CloseButtonHovered: return "CloseButtonHovered";
case ImGuiCol_CloseButtonActive: return "CloseButtonActive";
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_ModalWindowDarkening: return "ModalWindowDarkening";
}
IM_ASSERT(0);
return "Unknown";
}
bool ImGui::IsWindowHovered()
{
ImGuiContext& g = *GImGui;
return g.HoveredWindow == g.CurrentWindow && IsWindowContentHoverable(g.HoveredRootWindow);
}
bool ImGui::IsWindowFocused()
{
ImGuiContext& g = *GImGui;
return g.FocusedWindow == g.CurrentWindow;
}
bool ImGui::IsRootWindowFocused()
{
ImGuiContext& g = *GImGui;
return g.FocusedWindow == g.CurrentWindow->RootWindow;
}
bool ImGui::IsRootWindowOrAnyChildFocused()
{
ImGuiContext& g = *GImGui;
return g.FocusedWindow && g.FocusedWindow->RootWindow == g.CurrentWindow->RootWindow;
}
bool ImGui::IsRootWindowOrAnyChildHovered()
{
ImGuiContext& g = *GImGui;
return g.HoveredRootWindow && (g.HoveredRootWindow == g.CurrentWindow->RootWindow) && IsWindowContentHoverable(g.HoveredRootWindow);
}
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;
}
static void SetWindowScrollY(ImGuiWindow* window, float new_scroll_y)
{
window->DC.CursorMaxPos.y += window->Scroll.y;
window->Scroll.y = new_scroll_y;
window->DC.CursorMaxPos.y -= window->Scroll.y;
}
static void SetWindowPos(ImGuiWindow* window, const ImVec2& pos, ImGuiSetCond cond)
{
// Test condition (NB: bit 0 is always true) and clear flags for next time
if (cond && (window->SetWindowPosAllowFlags & cond) == 0)
return;
window->SetWindowPosAllowFlags &= ~(ImGuiSetCond_Once | ImGuiSetCond_FirstUseEver | ImGuiSetCond_Appearing);
window->SetWindowPosCenterWanted = false;
// Set
const ImVec2 old_pos = window->Pos;
window->PosFloat = pos;
window->Pos = ImVec2((float)(int)window->PosFloat.x, (float)(int)window->PosFloat.y);
window->DC.CursorPos += (window->Pos - old_pos); // 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 += (window->Pos - old_pos); // And more importantly we need to adjust this so size calculation doesn't get affected.
}
void ImGui::SetWindowPos(const ImVec2& pos, ImGuiSetCond cond)
{
ImGuiWindow* window = GetCurrentWindow();
SetWindowPos(window, pos, cond);
}
void ImGui::SetWindowPos(const char* name, const ImVec2& pos, ImGuiSetCond cond)
{
ImGuiWindow* window = FindWindowByName(name);
if (window)
SetWindowPos(window, pos, cond);
}
ImVec2 ImGui::GetWindowSize()
{
ImGuiWindow* window = GetCurrentWindowRead();
return window->Size;
}
static void SetWindowSize(ImGuiWindow* window, const ImVec2& size, ImGuiSetCond cond)
{
// Test condition (NB: bit 0 is always true) and clear flags for next time
if (cond && (window->SetWindowSizeAllowFlags & cond) == 0)
return;
window->SetWindowSizeAllowFlags &= ~(ImGuiSetCond_Once | ImGuiSetCond_FirstUseEver | ImGuiSetCond_Appearing);
// Set
if (size.x > 0.0f)
{
window->AutoFitFramesX = 0;
window->SizeFull.x = size.x;
}
else
{
window->AutoFitFramesX = 2;
window->AutoFitOnlyGrows = false;
}
if (size.y > 0.0f)
{
window->AutoFitFramesY = 0;
window->SizeFull.y = size.y;
}
else
{
window->AutoFitFramesY = 2;
window->AutoFitOnlyGrows = false;
}
}
void ImGui::SetWindowSize(const ImVec2& size, ImGuiSetCond cond)
{
SetWindowSize(GImGui->CurrentWindow, size, cond);
}
void ImGui::SetWindowSize(const char* name, const ImVec2& size, ImGuiSetCond cond)
{
ImGuiWindow* window = FindWindowByName(name);
if (window)
SetWindowSize(window, size, cond);
}
static void SetWindowCollapsed(ImGuiWindow* window, bool collapsed, ImGuiSetCond cond)
{
// Test condition (NB: bit 0 is always true) and clear flags for next time
if (cond && (window->SetWindowCollapsedAllowFlags & cond) == 0)
return;
window->SetWindowCollapsedAllowFlags &= ~(ImGuiSetCond_Once | ImGuiSetCond_FirstUseEver | ImGuiSetCond_Appearing);
// Set
window->Collapsed = collapsed;
}
void ImGui::SetWindowCollapsed(bool collapsed, ImGuiSetCond cond)
{
SetWindowCollapsed(GImGui->CurrentWindow, collapsed, cond);
}
bool ImGui::IsWindowCollapsed()
{
return GImGui->CurrentWindow->Collapsed;
}
void ImGui::SetWindowCollapsed(const char* name, bool collapsed, ImGuiSetCond cond)
{
ImGuiWindow* window = FindWindowByName(name);
if (window)
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, ImGuiSetCond cond)
{
ImGuiContext& g = *GImGui;
g.SetNextWindowPosVal = pos;
g.SetNextWindowPosCond = cond ? cond : ImGuiSetCond_Always;
}
void ImGui::SetNextWindowPosCenter(ImGuiSetCond cond)
{
ImGuiContext& g = *GImGui;
g.SetNextWindowPosVal = ImVec2(-FLT_MAX, -FLT_MAX);
g.SetNextWindowPosCond = cond ? cond : ImGuiSetCond_Always;
}
void ImGui::SetNextWindowSize(const ImVec2& size, ImGuiSetCond cond)
{
ImGuiContext& g = *GImGui;
g.SetNextWindowSizeVal = size;
g.SetNextWindowSizeCond = cond ? cond : ImGuiSetCond_Always;
}
void ImGui::SetNextWindowSizeConstraints(const ImVec2& size_min, const ImVec2& size_max, ImGuiSizeConstraintCallback custom_callback, void* custom_callback_user_data)
{
ImGuiContext& g = *GImGui;
g.SetNextWindowSizeConstraint = true;
g.SetNextWindowSizeConstraintRect = ImRect(size_min, size_max);
g.SetNextWindowSizeConstraintCallback = custom_callback;
g.SetNextWindowSizeConstraintCallbackUserData = custom_callback_user_data;
}
void ImGui::SetNextWindowContentSize(const ImVec2& size)
{
ImGuiContext& g = *GImGui;
g.SetNextWindowContentSizeVal = size;
g.SetNextWindowContentSizeCond = ImGuiSetCond_Always;
}
void ImGui::SetNextWindowContentWidth(float width)
{
ImGuiContext& g = *GImGui;
g.SetNextWindowContentSizeVal = ImVec2(width, g.SetNextWindowContentSizeCond ? g.SetNextWindowContentSizeVal.y : 0.0f);
g.SetNextWindowContentSizeCond = ImGuiSetCond_Always;
}
void ImGui::SetNextWindowCollapsed(bool collapsed, ImGuiSetCond cond)
{
ImGuiContext& g = *GImGui;
g.SetNextWindowCollapsedVal = collapsed;
g.SetNextWindowCollapsedCond = cond ? cond : ImGuiSetCond_Always;
}
void ImGui::SetNextWindowFocus()
{
ImGuiContext& g = *GImGui;
g.SetNextWindowFocus = true;
}
// In window space (not screen space!)
ImVec2 ImGui::GetContentRegionMax()
{
ImGuiWindow* window = GetCurrentWindowRead();
ImVec2 mx = window->ContentsRegionRect.Max;
if (window->DC.ColumnsCount != 1)
mx.x = GetColumnOffset(window->DC.ColumnsCurrent + 1) - window->WindowPadding.x;
return mx;
}
ImVec2 ImGui::GetContentRegionAvail()
{
ImGuiWindow* window = GetCurrentWindowRead();
return GetContentRegionMax() - (window->DC.CursorPos - window->Pos);
}
float ImGui::GetContentRegionAvailWidth()
{
return GetContentRegionAvail().x;
}
// In window space (not screen space!)
ImVec2 ImGui::GetWindowContentRegionMin()
{
ImGuiWindow* window = GetCurrentWindowRead();
return window->ContentsRegionRect.Min;
}
ImVec2 ImGui::GetWindowContentRegionMax()
{
ImGuiWindow* window = GetCurrentWindowRead();
return window->ContentsRegionRect.Max;
}
float ImGui::GetWindowContentRegionWidth()
{
ImGuiWindow* window = GetCurrentWindowRead();
return window->ContentsRegionRect.Max.x - window->ContentsRegionRect.Min.x;
}
float ImGui::GetTextLineHeight()
{
ImGuiContext& g = *GImGui;
return g.FontSize;
}
float ImGui::GetTextLineHeightWithSpacing()
{
ImGuiContext& g = *GImGui;
return g.FontSize + g.Style.ItemSpacing.y;
}
float ImGui::GetItemsLineHeightWithSpacing()
{
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->FontTexUvWhitePixel;
}
void ImGui::SetWindowFontScale(float scale)
{
ImGuiContext& g = *GImGui;
ImGuiWindow* window = GetCurrentWindow();
window->FontWindowScale = scale;
g.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& screen_pos)
{
ImGuiWindow* window = GetCurrentWindow();
window->DC.CursorPos = screen_pos;
window->DC.CursorMaxPos = ImMax(window->DC.CursorMaxPos, window->DC.CursorPos);
}
float ImGui::GetScrollX()
{
return GImGui->CurrentWindow->Scroll.x;
}
float ImGui::GetScrollY()
{
return GImGui->CurrentWindow->Scroll.y;
}
float ImGui::GetScrollMaxX()
{
ImGuiWindow* window = GetCurrentWindowRead();
return window->SizeContents.x - window->SizeFull.x - window->ScrollbarSizes.x;
}
float ImGui::GetScrollMaxY()
{
ImGuiWindow* window = GetCurrentWindowRead();
return window->SizeContents.y - window->SizeFull.y - window->ScrollbarSizes.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->TitleBarHeight() + window->MenuBarHeight(); // title bar height canceled out when using ScrollTargetRelY
window->ScrollTargetCenterRatio.y = 0.0f;
}
void ImGui::SetScrollFromPosY(float pos_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
ImGuiWindow* window = GetCurrentWindow();
IM_ASSERT(center_y_ratio >= 0.0f && center_y_ratio <= 1.0f);
window->ScrollTarget.y = (float)(int)(pos_y + window->Scroll.y);
if (center_y_ratio <= 0.0f && window->ScrollTarget.y <= window->WindowPadding.y) // Minor hack to make "scroll to top" take account of WindowPadding, else it would scroll to (WindowPadding.y - ItemSpacing.y)
window->ScrollTarget.y = 0.0f;
window->ScrollTargetCenterRatio.y = center_y_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::SetScrollHere(float center_y_ratio)
{
ImGuiWindow* window = GetCurrentWindow();
float target_y = window->DC.CursorPosPrevLine.y + (window->DC.PrevLineHeight * center_y_ratio) + (GImGui->Style.ItemSpacing.y * (center_y_ratio - 0.5f) * 2.0f); // Precisely aim above, in the middle or below the last line.
SetScrollFromPosY(target_y - window->Pos.y, center_y_ratio);
}
void ImGui::SetKeyboardFocusHere(int offset)
{
ImGuiWindow* window = GetCurrentWindow();
window->FocusIdxAllRequestNext = window->FocusIdxAllCounter + 1 + offset;
window->FocusIdxTabRequestNext = INT_MAX;
}
void ImGui::SetStateStorage(ImGuiStorage* tree)
{
ImGuiWindow* window = GetCurrentWindow();
window->DC.StateStorage = tree ? tree : &window->StateStorage;
}
ImGuiStorage* ImGui::GetStateStorage()
{
ImGuiWindow* window = GetCurrentWindowRead();
return window->DC.StateStorage;
}
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);
TextUnformatted(g.TempBuffer, text_end);
}
void ImGui::Text(const char* fmt, ...)
{
va_list args;
va_start(args, fmt);
TextV(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::TextColored(const ImVec4& col, const char* fmt, ...)
{
va_list args;
va_start(args, fmt);
TextColoredV(col, 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::TextDisabled(const char* fmt, ...)
{
va_list args;
va_start(args, fmt);
TextDisabledV(fmt, args);
va_end(args);
}
void ImGui::TextWrappedV(const char* fmt, va_list args)
{
bool need_wrap = (GImGui->CurrentWindow->DC.TextWrapPos < 0.0f); // Keep existing wrap position is one ia already set
if (need_wrap) PushTextWrapPos(0.0f);
TextV(fmt, args);
if (need_wrap) PopTextWrapPos();
}
void ImGui::TextWrapped(const char* fmt, ...)
{
va_list args;
va_start(args, fmt);
TextWrappedV(fmt, args);
va_end(args);
}
void ImGui::TextUnformatted(const char* text, const char* text_end)
{
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 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.
const char* line = text;
const float line_height = GetTextLineHeight();
const ImVec2 text_pos = window->DC.CursorPos + ImVec2(0.0f, window->DC.CurrentLineTextBaseOffset);
const ImRect clip_rect = window->ClipRect;
ImVec2 text_size(0,0);
if (text_pos.y <= clip_rect.Max.y)
{
ImVec2 pos = text_pos;
// Lines to skip (can't skip when logging text)
if (!g.LogEnabled)
{
int lines_skippable = (int)((clip_rect.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 = strchr(line, '\n');
if (!line_end)
line_end = text_end;
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)
{
const char* line_end = strchr(line, '\n');
if (IsClippedEx(line_rect, NULL, false))
break;
const ImVec2 line_size = CalcTextSize(line, line_end, false);
text_size.x = ImMax(text_size.x, line_size.x);
RenderText(pos, line, line_end, false);
if (!line_end)
line_end = text_end;
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 = strchr(line, '\n');
if (!line_end)
line_end = text_end;
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(bb);
ItemAdd(bb, NULL);
}
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);
// Account of baseline offset
ImVec2 text_pos(window->DC.CursorPos.x, window->DC.CursorPos.y + window->DC.CurrentLineTextBaseOffset);
ImRect bb(text_pos, text_pos + text_size);
ItemSize(text_size);
if (!ItemAdd(bb, NULL))
return;
// Render (we don't hide text after ## in this end-user function)
RenderTextWrapped(bb.Min, text_begin, text_end, wrap_width);
}
}
void ImGui::AlignFirstTextHeightToWidgets()
{
ImGuiWindow* window = GetCurrentWindow();
if (window->SkipItems)
return;
// Declare a dummy item size to that upcoming items that are smaller will center-align on the newly expanded line height.
ImGuiContext& g = *GImGui;
ItemSize(ImVec2(0, g.FontSize + g.Style.FramePadding.y*2), g.Style.FramePadding.y);
SameLine(0, 0);
}
// 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, NULL))
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, ImGuiAlign_VCenter);
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::LabelText(const char* label, const char* fmt, ...)
{
va_list args;
va_start(args, fmt);
LabelTextV(label, fmt, args);
va_end(args);
}
static inline bool IsWindowContentHoverable(ImGuiWindow* window)
{
// An active popup disable hovering on other windows (apart from its own children)
ImGuiContext& g = *GImGui;
if (ImGuiWindow* focused_window = g.FocusedWindow)
if (ImGuiWindow* focused_root_window = focused_window->RootWindow)
if ((focused_root_window->Flags & ImGuiWindowFlags_Popup) != 0 && focused_root_window->WasActive && focused_root_window != window->RootWindow)
return false;
return 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) SetActiveID(0);
return false;
}
if ((flags & (ImGuiButtonFlags_PressedOnClickRelease | ImGuiButtonFlags_PressedOnClick | ImGuiButtonFlags_PressedOnRelease | ImGuiButtonFlags_PressedOnDoubleClick)) == 0)
flags |= ImGuiButtonFlags_PressedOnClickRelease;
bool pressed = false;
bool hovered = IsHovered(bb, id, (flags & ImGuiButtonFlags_FlattenChilds) != 0);
if (hovered)
{
SetHoveredID(id);
if (!(flags & ImGuiButtonFlags_NoKeyModifiers) || (!g.IO.KeyCtrl && !g.IO.KeyShift && !g.IO.KeyAlt))
{
// | CLICKING | HOLDING with ImGuiButtonFlags_Repeat
// PressedOnClickRelease | <on release>* | <on repeat> <on repeat> .. (NOT on release) <-- MOST COMMON! (*) only if both click/release were over bounds
// PressedOnClick | <on click> | <on click> <on repeat> <on repeat> ..
// PressedOnRelease | <on release> | <on repeat> <on repeat> .. (NOT on release)
// PressedOnDoubleClick | <on dclick> | <on dclick> <on repeat> <on repeat> ..
if ((flags & ImGuiButtonFlags_PressedOnClickRelease) && g.IO.MouseClicked[0])
{
SetActiveID(id, window); // Hold on ID
FocusWindow(window);
g.ActiveIdClickOffset = g.IO.MousePos - bb.Min;
}
if (((flags & ImGuiButtonFlags_PressedOnClick) && g.IO.MouseClicked[0]) || ((flags & ImGuiButtonFlags_PressedOnDoubleClick) && g.IO.MouseDoubleClicked[0]))
{
pressed = true;
SetActiveID(0);
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;
SetActiveID(0);
}
// '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;
}
}
bool held = false;
if (g.ActiveId == id)
{
if (g.IO.MouseDown[0])
{
held = true;
}
else
{
if (hovered && (flags & ImGuiButtonFlags_PressedOnClickRelease))
if (!((flags & ImGuiButtonFlags_Repeat) && g.IO.MouseDownDurationPrev[0] >= g.IO.KeyRepeatDelay)) // Repeat mode trumps <on release>
pressed = true;
SetActiveID(0);
}
}
// 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_AllowOverlapMode) && (g.HoveredIdPreviousFrame != id && g.HoveredIdPreviousFrame != 0))
hovered = pressed = held = false;
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.CurrentLineTextBaseOffset)
pos.y += window->DC.CurrentLineTextBaseOffset - 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(bb, style.FramePadding.y);
if (!ItemAdd(bb, &id))
return false;
if (window->DC.ButtonRepeat) flags |= ImGuiButtonFlags_Repeat;
bool hovered, held;
bool pressed = ButtonBehavior(bb, id, &hovered, &held, flags);
// Render
const ImU32 col = GetColorU32((hovered && held) ? ImGuiCol_ButtonActive : hovered ? ImGuiCol_ButtonHovered : ImGuiCol_Button);
RenderFrame(bb.Min, bb.Max, col, true, style.FrameRounding);
RenderTextClipped(bb.Min, bb.Max, label, NULL, &label_size, ImGuiAlign_Center | ImGuiAlign_VCenter);
// Automatically close popups
//if (pressed && !(flags & ImGuiButtonFlags_DontClosePopups) && (window->Flags & ImGuiWindowFlags_Popup))
// CloseCurrentPopup();
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;
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(bb);
if (!ItemAdd(bb, &id))
return false;
bool hovered, held;
bool pressed = ButtonBehavior(bb, id, &hovered, &held);
return pressed;
}
// Upper-right button to close a window.
bool ImGui::CloseButton(ImGuiID id, const ImVec2& pos, float radius)
{
ImGuiWindow* window = GetCurrentWindow();
const ImRect bb(pos - ImVec2(radius,radius), pos + ImVec2(radius,radius));
bool hovered, held;
bool pressed = ButtonBehavior(bb, id, &hovered, &held);
// Render
const ImU32 col = GetColorU32((held && hovered) ? ImGuiCol_CloseButtonActive : hovered ? ImGuiCol_CloseButtonHovered : ImGuiCol_CloseButton);
const ImVec2 center = bb.GetCenter();
window->DrawList->AddCircleFilled(center, ImMax(2.0f, radius), col, 12);
const float cross_extent = (radius * 0.7071f) - 1.0f;
if (hovered)
{
window->DrawList->AddLine(center + ImVec2(+cross_extent,+cross_extent), center + ImVec2(-cross_extent,-cross_extent), GetColorU32(ImGuiCol_Text));
window->DrawList->AddLine(center + ImVec2(+cross_extent,-cross_extent), center + ImVec2(-cross_extent,+cross_extent), GetColorU32(ImGuiCol_Text));
}
return pressed;
}
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, NULL))
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 *)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((hovered && held) ? ImGuiCol_ButtonActive : hovered ? ImGuiCol_ButtonHovered : ImGuiCol_Button);
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;
}
// Start logging ImGui output to TTY
void ImGui::LogToTTY(int max_depth)
{
ImGuiContext& g = *GImGui;
if (g.LogEnabled)
return;
ImGuiWindow* window = GetCurrentWindowRead();
g.LogEnabled = true;
g.LogFile = stdout;
g.LogStartDepth = window->DC.TreeDepth;
if (max_depth >= 0)
g.LogAutoExpandMaxDepth = max_depth;
}
// Start logging ImGui output to given file
void ImGui::LogToFile(int max_depth, const char* filename)
{
ImGuiContext& g = *GImGui;
if (g.LogEnabled)
return;
ImGuiWindow* window = GetCurrentWindowRead();
if (!filename)
{
filename = g.IO.LogFilename;
if (!filename)
return;
}
g.LogFile = fopen(filename, "ab");
if (!g.LogFile)
{
IM_ASSERT(g.LogFile != NULL); // Consider this an error
return;
}
g.LogEnabled = true;
g.LogStartDepth = window->DC.TreeDepth;
if (max_depth >= 0)
g.LogAutoExpandMaxDepth = max_depth;
}
// Start logging ImGui output to clipboard
void ImGui::LogToClipboard(int max_depth)
{
ImGuiContext& g = *GImGui;
if (g.LogEnabled)
return;
ImGuiWindow* window = GetCurrentWindowRead();
g.LogEnabled = true;
g.LogFile = NULL;
g.LogStartDepth = window->DC.TreeDepth;
if (max_depth >= 0)
g.LogAutoExpandMaxDepth = max_depth;
}
void ImGui::LogFinish()
{
ImGuiContext& g = *GImGui;
if (!g.LogEnabled)
return;
LogText(IM_NEWLINE);
g.LogEnabled = false;
if (g.LogFile != NULL)
{
if (g.LogFile == stdout)
fflush(g.LogFile);
else
fclose(g.LogFile);
g.LogFile = NULL;
}
if (g.LogClipboard->size() > 1)
{
if (g.IO.SetClipboardTextFn)
g.IO.SetClipboardTextFn(g.LogClipboard->begin());
g.LogClipboard->clear();
}
}
// Helper to display logging buttons
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();
PushItemWidth(80.0f);
PushAllowKeyboardFocus(false);
SliderInt("Depth", &g.LogAutoExpandMaxDepth, 0, 9, NULL);
PopAllowKeyboardFocus();
PopItemWidth();
PopID();
// Start logging at the end of the function so that the buttons don't appear in the log
if (log_to_tty)
LogToTTY(g.LogAutoExpandMaxDepth);
if (log_to_file)
LogToFile(g.LogAutoExpandMaxDepth, g.IO.LogFilename);
if (log_to_clipboard)
LogToClipboard(g.LogAutoExpandMaxDepth);
}
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 explicitely use SetNextTreeNode*** functions)
ImGuiContext& g = *GImGui;
ImGuiWindow* window = g.CurrentWindow;
ImGuiStorage* storage = window->DC.StateStorage;
bool is_open;
if (g.SetNextTreeNodeOpenCond != 0)
{
if (g.SetNextTreeNodeOpenCond & ImGuiSetCond_Always)
{
is_open = g.SetNextTreeNodeOpenVal;
storage->SetInt(id, is_open);
}
else
{
// We treat ImGuiSetCondition_Once and ImGuiSetCondition_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.SetNextTreeNodeOpenVal;
storage->SetInt(id, is_open);
}
else
{
is_open = stored_value != 0;
}
}
g.SetNextTreeNodeOpenCond = 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.LogAutoExpandMaxDepth)
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 ? 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(0.0f, window->DC.CurrentLineTextBaseOffset - padding.y); // Latch before ItemSize changes it
const float frame_height = ImMax(ImMin(window->DC.CurrentLineHeight, g.FontSize + style.FramePadding.y*2), label_size.y + padding.y*2);
ImRect bb = ImRect(window->DC.CursorPos, ImVec2(window->Pos.x + GetContentRegionMax().x, window->DC.CursorPos.y + frame_height));
if (display_frame)
{
// Framed header expand a little outside the default padding
bb.Min.x -= (float)(int)(window->WindowPadding.x*0.5f) - 1;
bb.Max.x += (float)(int)(window->WindowPadding.x*0.5f) - 1;
}
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 we want want the hit test to be done up to the right side of the content or not)
const ImRect interact_bb = display_frame ? bb : ImRect(bb.Min.x, bb.Min.y, bb.Min.x + text_width + style.ItemSpacing.x*2, bb.Max.y);
bool is_open = TreeNodeBehaviorIsOpen(id, flags);
if (!ItemAdd(interact_bb, &id))
{
if (is_open && !(flags & ImGuiTreeNodeFlags_NoTreePushOnOpen))
TreePushRawID(id);
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 | ((flags & ImGuiTreeNodeFlags_AllowOverlapMode) ? ImGuiButtonFlags_AllowOverlapMode : 0);
if (flags & ImGuiTreeNodeFlags_OpenOnDoubleClick)
button_flags |= ImGuiButtonFlags_PressedOnDoubleClick | ((flags & ImGuiTreeNodeFlags_OpenOnArrow) ? ImGuiButtonFlags_PressedOnClickRelease : 0);
bool hovered, held, pressed = ButtonBehavior(interact_bb, id, &hovered, &held, button_flags);
if (pressed && !(flags & ImGuiTreeNodeFlags_Leaf))
{
bool toggled = !(flags & (ImGuiTreeNodeFlags_OpenOnArrow | ImGuiTreeNodeFlags_OpenOnDoubleClick));
if (flags & ImGuiTreeNodeFlags_OpenOnArrow)
toggled |= IsMouseHoveringRect(interact_bb.Min, ImVec2(interact_bb.Min.x + text_offset_x, interact_bb.Max.y));
if (flags & ImGuiTreeNodeFlags_OpenOnDoubleClick)
toggled |= g.IO.MouseDoubleClicked[0];
if (toggled)
{
is_open = !is_open;
window->DC.StateStorage->SetInt(id, is_open);
}
}
if (flags & ImGuiTreeNodeFlags_AllowOverlapMode)
SetItemAllowOverlap();
// Render
const ImU32 col = GetColorU32((held && hovered) ? ImGuiCol_HeaderActive : hovered ? ImGuiCol_HeaderHovered : ImGuiCol_Header);
const ImVec2 text_pos = bb.Min + ImVec2(text_offset_x, padding.y + text_base_offset_y);
if (display_frame)
{
// Framed type
RenderFrame(bb.Min, bb.Max, col, true, style.FrameRounding);
RenderCollapseTriangle(bb.Min + padding + ImVec2(0.0f, text_base_offset_y), is_open, 1.0f, true);
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, bb.Max, label, label_end, &label_size);
LogRenderedText(text_pos, log_suffix+1, log_suffix+3);
}
else
{
RenderTextClipped(text_pos, bb.Max, label, label_end, &label_size);
}
}
else
{
// Unframed typed for tree nodes
if (hovered || (flags & ImGuiTreeNodeFlags_Selected))
RenderFrame(bb.Min, bb.Max, col, false);
if (flags & ImGuiTreeNodeFlags_Bullet)
RenderBullet(bb.Min + ImVec2(text_offset_x * 0.5f, g.FontSize*0.50f + text_base_offset_y));
else if (!(flags & ImGuiTreeNodeFlags_Leaf))
RenderCollapseTriangle(bb.Min + ImVec2(padding.x, g.FontSize*0.15f + text_base_offset_y), is_open, 0.70f, false);
if (g.LogEnabled)
LogRenderedText(text_pos, ">");
RenderText(text_pos, label, label_end, false);
}
if (is_open && !(flags & ImGuiTreeNodeFlags_NoTreePushOnOpen))
TreePushRawID(id);
return is_open;
}
// 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 | ImGuiTreeNodeFlags_NoTreePushOnOpen). 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 | ImGuiTreeNodeFlags_NoTreePushOnOpen, 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);
bool is_open = TreeNodeBehavior(id, flags | ImGuiTreeNodeFlags_CollapsingHeader | ImGuiTreeNodeFlags_NoTreePushOnOpen | (p_open ? ImGuiTreeNodeFlags_AllowOverlapMode : 0), 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.
ImGuiContext& g = *GImGui;
float button_sz = g.FontSize * 0.5f;
if (CloseButton(window->GetID((void*)(intptr_t)(id+1)), ImVec2(ImMin(window->DC.LastItemRect.Max.x, window->ClipRect.Max.x) - g.Style.FramePadding.x - button_sz, window->DC.LastItemRect.Min.y + g.Style.FramePadding.y + button_sz), button_sz))
*p_open = false;
}
return is_open;
}
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::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::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* 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::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);
}
void ImGui::TreeAdvanceToLabelPos()
{
ImGuiContext& g = *GImGui;
g.CurrentWindow->DC.CursorPos.x += GetTreeNodeToLabelSpacing();
}
// Horizontal distance preceeding label when using TreeNode() or Bullet()
float ImGui::GetTreeNodeToLabelSpacing()
{
ImGuiContext& g = *GImGui;
return g.FontSize + (g.Style.FramePadding.x * 2.0f);
}
void ImGui::SetNextTreeNodeOpen(bool is_open, ImGuiSetCond cond)
{
ImGuiContext& g = *GImGui;
g.SetNextTreeNodeOpenVal = is_open;
g.SetNextTreeNodeOpenCond = cond ? cond : ImGuiSetCond_Always;
}
void ImGui::PushID(const char* str_id)
{
ImGuiWindow* window = GetCurrentWindow();
window->IDStack.push_back(window->GetID(str_id));
}
void ImGui::PushID(const char* str_id_begin, const char* str_id_end)
{
ImGuiWindow* window = GetCurrentWindow();
window->IDStack.push_back(window->GetID(str_id_begin, str_id_end));
}
void ImGui::PushID(const void* ptr_id)
{
ImGuiWindow* window = GetCurrentWindow();
window->IDStack.push_back(window->GetID(ptr_id));
}
void ImGui::PushID(int int_id)
{
const void* ptr_id = (void*)(intptr_t)int_id;
ImGuiWindow* window = GetCurrentWindow();
window->IDStack.push_back(window->GetID(ptr_id));
}
void ImGui::PopID()
{
ImGuiWindow* window = GetCurrentWindow();
window->IDStack.pop_back();
}
ImGuiID ImGui::GetID(const char* str_id)
{
return GImGui->CurrentWindow->GetID(str_id);
}
ImGuiID ImGui::GetID(const char* str_id_begin, const char* str_id_end)
{
return GImGui->CurrentWindow->GetID(str_id_begin, str_id_end);
}
ImGuiID ImGui::GetID(const void* ptr_id)
{
return GImGui->CurrentWindow->GetID(ptr_id);
}
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.CurrentLineHeight, 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, NULL))
{
SameLine(0, style.FramePadding.x*2);
return;
}
// Render and stay on same line
RenderBullet(bb.Min + ImVec2(style.FramePadding.x + g.FontSize*0.5f, line_height*0.5f));
SameLine(0, style.FramePadding.x*2);
}
// 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, true);
const float text_base_offset_y = ImMax(0.0f, window->DC.CurrentLineTextBaseOffset); // Latch before ItemSize changes it
const float line_height = ImMax(ImMin(window->DC.CurrentLineHeight, 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, NULL))
return;
// Render
RenderBullet(bb.Min + ImVec2(style.FramePadding.x + g.FontSize*0.5f, line_height*0.5f));
RenderText(bb.Min+ImVec2(g.FontSize + style.FramePadding.x*2, text_base_offset_y), text_begin, text_end);
}
void ImGui::BulletText(const char* fmt, ...)
{
va_list args;
va_start(args, fmt);
BulletTextV(fmt, args);
va_end(args);
}
static inline void DataTypeFormatString(ImGuiDataType data_type, void* data_ptr, const char* display_format, char* buf, int buf_size)
{
if (data_type == ImGuiDataType_Int)
ImFormatString(buf, buf_size, display_format, *(int*)data_ptr);
else if (data_type == ImGuiDataType_Float)
ImFormatString(buf, buf_size, display_format, *(float*)data_ptr);
}
static inline void DataTypeFormatString(ImGuiDataType data_type, void* data_ptr, int decimal_precision, char* buf, int buf_size)
{
if (data_type == ImGuiDataType_Int)
{
if (decimal_precision < 0)
ImFormatString(buf, buf_size, "%d", *(int*)data_ptr);
else
ImFormatString(buf, buf_size, "%.*d", decimal_precision, *(int*)data_ptr);
}
else if (data_type == ImGuiDataType_Float)
{
if (decimal_precision < 0)
ImFormatString(buf, buf_size, "%f", *(float*)data_ptr); // Ideally we'd have a minimum decimal precision of 1 to visually denote that it is a float, while hiding non-significant digits?
else
ImFormatString(buf, buf_size, "%.*f", decimal_precision, *(float*)data_ptr);
}
}
static void DataTypeApplyOp(ImGuiDataType data_type, int op, void* value1, const void* value2)// Store into value1
{
if (data_type == ImGuiDataType_Int)
{
if (op == '+')
*(int*)value1 = *(int*)value1 + *(const int*)value2;
else if (op == '-')
*(int*)value1 = *(int*)value1 - *(const int*)value2;
}
else if (data_type == ImGuiDataType_Float)
{
if (op == '+')
*(float*)value1 = *(float*)value1 + *(const float*)value2;
else if (op == '-')
*(float*)value1 = *(float*)value1 - *(const float*)value2;
}
}
// User can input math operators (e.g. +100) to edit a numerical values.
static bool DataTypeApplyOpFromText(const char* buf, const char* initial_value_buf, ImGuiDataType data_type, void* data_ptr, const char* scalar_format)
{
while (ImCharIsSpace(*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 (ImCharIsSpace(*buf))
buf++;
}
else
{
op = 0;
}
if (!buf[0])
return false;
if (data_type == ImGuiDataType_Int)
{
if (!scalar_format)
scalar_format = "%d";
int* v = (int*)data_ptr;
const int old_v = *v;
int arg0 = *v;
if (op && sscanf(initial_value_buf, scalar_format, &arg0) < 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
float arg1 = 0.0f;
if (op == '+') { if (sscanf(buf, "%f", &arg1) == 1) *v = (int)(arg0 + arg1); } // Add (use "+-" to subtract)
else if (op == '*') { if (sscanf(buf, "%f", &arg1) == 1) *v = (int)(arg0 * arg1); } // Multiply
else if (op == '/') { if (sscanf(buf, "%f", &arg1) == 1 && arg1 != 0.0f) *v = (int)(arg0 / arg1); }// Divide
else { if (sscanf(buf, scalar_format, &arg0) == 1) *v = arg0; } // Assign constant
return (old_v != *v);
}
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
scalar_format = "%f";
float* v = (float*)data_ptr;
const float old_v = *v;
float arg0 = *v;
if (op && sscanf(initial_value_buf, scalar_format, &arg0) < 1)
return false;
float arg1 = 0.0f;
if (sscanf(buf, scalar_format, &arg1) < 1)
return false;
if (op == '+') { *v = arg0 + arg1; } // Add (use "+-" to subtract)
else if (op == '*') { *v = arg0 * arg1; } // Multiply
else if (op == '/') { if (arg1 != 0.0f) *v = arg0 / arg1; } // Divide
else { *v = arg1; } // Assign constant
return (old_v != *v);
}
return false;
}
// Create text input in place of a slider (when CTRL+Clicking on slider)
bool ImGui::InputScalarAsWidgetReplacement(const ImRect& aabb, const char* label, ImGuiDataType data_type, void* data_ptr, ImGuiID id, int decimal_precision)
{
ImGuiContext& g = *GImGui;
ImGuiWindow* window = GetCurrentWindow();
// Our replacement widget will override the focus ID (registered previously to allow for a TAB focus to happen)
SetActiveID(g.ScalarAsInputTextId, window);
SetHoveredID(0);
FocusableItemUnregister(window);
char buf[32];
DataTypeFormatString(data_type, data_ptr, decimal_precision, buf, IM_ARRAYSIZE(buf));
bool text_value_changed = InputTextEx(label, buf, IM_ARRAYSIZE(buf), aabb.GetSize(), ImGuiInputTextFlags_CharsDecimal | ImGuiInputTextFlags_AutoSelectAll);
if (g.ScalarAsInputTextId == 0)
{
// First frame
IM_ASSERT(g.ActiveId == id); // InputText ID expected to match the Slider ID (else we'd need to store them both, which is also possible)
g.ScalarAsInputTextId = g.ActiveId;
SetHoveredID(id);
}
else if (g.ActiveId != g.ScalarAsInputTextId)
{
// Release
g.ScalarAsInputTextId = 0;
}
if (text_value_changed)
return DataTypeApplyOpFromText(buf, GImGui->InputTextState.InitialText.begin(), data_type, data_ptr, NULL);
return false;
}
// Parse display precision back from the display format string
int ImGui::ParseFormatPrecision(const char* fmt, int default_precision)
{
int precision = default_precision;
while ((fmt = strchr(fmt, '%')) != NULL)
{
fmt++;
if (fmt[0] == '%') { fmt++; continue; } // Ignore "%%"
while (*fmt >= '0' && *fmt <= '9')
fmt++;
if (*fmt == '.')
{
precision = atoi(fmt + 1);
if (precision < 0 || precision > 10)
precision = default_precision;
}
break;
}
return precision;
}
float ImGui::RoundScalar(float value, int decimal_precision)
{
// Round past decimal precision
// So when our value is 1.99999 with a precision of 0.001 we'll end up rounding to 2.0
// FIXME: Investigate better rounding methods
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 };
float min_step = (decimal_precision >= 0 && decimal_precision < 10) ? min_steps[decimal_precision] : powf(10.0f, (float)-decimal_precision);
bool negative = value < 0.0f;
value = fabsf(value);
float remainder = fmodf(value, min_step);
if (remainder <= min_step*0.5f)
value -= remainder;
else
value += (min_step - remainder);
return negative ? -value : value;
}
bool ImGui::SliderBehavior(const ImRect& frame_bb, ImGuiID id, float* v, float v_min, float v_max, float power, int decimal_precision, ImGuiSliderFlags flags)
{
ImGuiContext& g = *GImGui;
ImGuiWindow* window = GetCurrentWindow();
const ImGuiStyle& style = g.Style;
// Draw frame
RenderFrame(frame_bb.Min, frame_bb.Max, GetColorU32(ImGuiCol_FrameBg), true, style.FrameRounding);
const bool is_non_linear = fabsf(power - 1.0f) > 0.0001f;
const bool is_horizontal = (flags & ImGuiSliderFlags_Vertical) == 0;
const float grab_padding = 2.0f;
const float slider_sz = is_horizontal ? (frame_bb.GetWidth() - grab_padding * 2.0f) : (frame_bb.GetHeight() - grab_padding * 2.0f);
float grab_sz;
if (decimal_precision > 0)
grab_sz = ImMin(style.GrabMinSize, slider_sz);
else
grab_sz = ImMin(ImMax(1.0f * (slider_sz / (v_max-v_min+1.0f)), style.GrabMinSize), slider_sz); // Integer sliders, if possible have the grab size represent 1 unit
const float slider_usable_sz = slider_sz - grab_sz;
const float slider_usable_pos_min = (is_horizontal ? frame_bb.Min.x : frame_bb.Min.y) + grab_padding + grab_sz*0.5f;
const float slider_usable_pos_max = (is_horizontal ? frame_bb.Max.x : frame_bb.Max.y) - grab_padding - grab_sz*0.5f;
// For logarithmic sliders that cross over sign boundary we want the exponential increase to be symmetric around 0.0f
float linear_zero_pos = 0.0f; // 0.0->1.0f
if (v_min * v_max < 0.0f)
{
// Different sign
const float linear_dist_min_to_0 = powf(fabsf(0.0f - v_min), 1.0f/power);
const float linear_dist_max_to_0 = powf(fabsf(v_max - 0.0f), 1.0f/power);
linear_zero_pos = 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 clicking on the slider
bool value_changed = false;
if (g.ActiveId == id)
{
if (g.IO.MouseDown[0])
{
const float mouse_abs_pos = is_horizontal ? g.IO.MousePos.x : g.IO.MousePos.y;
float normalized_pos = ImClamp((mouse_abs_pos - slider_usable_pos_min) / slider_usable_sz, 0.0f, 1.0f);
if (!is_horizontal)
normalized_pos = 1.0f - normalized_pos;
float new_value;
if (is_non_linear)
{
// Account for logarithmic scale on both sides of the zero
if (normalized_pos < linear_zero_pos)
{
// Negative: rescale to the negative range before powering
float a = 1.0f - (normalized_pos / linear_zero_pos);
a = powf(a, power);
new_value = ImLerp(ImMin(v_max,0.0f), v_min, a);
}
else
{
// Positive: rescale to the positive range before powering
float a;
if (fabsf(linear_zero_pos - 1.0f) > 1.e-6f)
a = (normalized_pos - linear_zero_pos) / (1.0f - linear_zero_pos);
else
a = normalized_pos;
a = powf(a, power);
new_value = ImLerp(ImMax(v_min,0.0f), v_max, a);
}
}
else
{
// Linear slider
new_value = ImLerp(v_min, v_max, normalized_pos);
}
// Round past decimal precision
new_value = RoundScalar(new_value, decimal_precision);
if (*v != new_value)
{
*v = new_value;
value_changed = true;
}
}
else
{
SetActiveID(0);
}
}
// Calculate slider grab positioning
float grab_t;
if (is_non_linear)
{
float v_clamped = ImClamp(*v, v_min, v_max);
if (v_clamped < 0.0f)
{
const float f = 1.0f - (v_clamped - v_min) / (ImMin(0.0f,v_max) - v_min);
grab_t = (1.0f - powf(f, 1.0f/power)) * linear_zero_pos;
}
else
{
const float f = (v_clamped - ImMax(0.0f,v_min)) / (v_max - ImMax(0.0f,v_min));
grab_t = linear_zero_pos + powf(f, 1.0f/power) * (1.0f - linear_zero_pos);
}
}
else
{
// Linear slider
grab_t = (ImClamp(*v, v_min, v_max) - v_min) / (v_max - v_min);
}
// Draw
if (!is_horizontal)
grab_t = 1.0f - grab_t;
const float grab_pos = ImLerp(slider_usable_pos_min, slider_usable_pos_max, grab_t);
ImRect grab_bb;
if (is_horizontal)
grab_bb = ImRect(ImVec2(grab_pos - grab_sz*0.5f, frame_bb.Min.y + grab_padding), ImVec2(grab_pos + grab_sz*0.5f, frame_bb.Max.y - grab_padding));
else
grab_bb = ImRect(ImVec2(frame_bb.Min.x + grab_padding, grab_pos - grab_sz*0.5f), ImVec2(frame_bb.Max.x - grab_padding, grab_pos + grab_sz*0.5f));
window->DrawList->AddRectFilled(grab_bb.Min, grab_bb.Max, GetColorU32(g.ActiveId == id ? ImGuiCol_SliderGrabActive : ImGuiCol_SliderGrab), style.GrabRounding);
return value_changed;
}
// Use power!=1.0 for logarithmic sliders.
// Adjust display_format to decorate the value with a prefix or a suffix.
// "%.3f" 1.234
// "%5.2f secs" 01.23 secs
// "Gold: %.0f" Gold: 1
bool ImGui::SliderFloat(const char* label, float* v, float v_min, float v_max, const char* display_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));
// NB- we don't call ItemSize() yet because we may turn into a text edit box below
if (!ItemAdd(total_bb, &id))
{
ItemSize(total_bb, style.FramePadding.y);
return false;
}
const bool hovered = IsHovered(frame_bb, id);
if (hovered)
SetHoveredID(id);
if (!display_format)
display_format = "%.3f";
int decimal_precision = ParseFormatPrecision(display_format, 3);
// Tabbing or CTRL-clicking on Slider turns it into an input box
bool start_text_input = false;
const bool tab_focus_requested = FocusableItemRegister(window, g.ActiveId == id);
if (tab_focus_requested || (hovered && g.IO.MouseClicked[0]))
{
SetActiveID(id, window);
FocusWindow(window);
if (tab_focus_requested || g.IO.KeyCtrl)
{
start_text_input = true;
g.ScalarAsInputTextId = 0;
}
}
if (start_text_input || (g.ActiveId == id && g.ScalarAsInputTextId == id))
return InputScalarAsWidgetReplacement(frame_bb, label, ImGuiDataType_Float, v, id, decimal_precision);
ItemSize(total_bb, style.FramePadding.y);
// Actual slider behavior + render grab
const bool value_changed = SliderBehavior(frame_bb, id, v, v_min, v_max, power, decimal_precision);
// 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 + ImFormatString(value_buf, IM_ARRAYSIZE(value_buf), display_format, *v);
RenderTextClipped(frame_bb.Min, frame_bb.Max, value_buf, value_buf_end, NULL, ImGuiAlign_Center|ImGuiAlign_VCenter);
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* display_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;
const bool hovered = IsHovered(frame_bb, id);
if (hovered)
SetHoveredID(id);
if (!display_format)
display_format = "%.3f";
int decimal_precision = ParseFormatPrecision(display_format, 3);
if (hovered && g.IO.MouseClicked[0])
{
SetActiveID(id, window);
FocusWindow(window);
}
// Actual slider behavior + render grab
bool value_changed = SliderBehavior(frame_bb, id, v, v_min, v_max, power, decimal_precision, ImGuiSliderFlags_Vertical);
// 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];
char* value_buf_end = value_buf + ImFormatString(value_buf, IM_ARRAYSIZE(value_buf), display_format, *v);
RenderTextClipped(ImVec2(frame_bb.Min.x, frame_bb.Min.y + style.FramePadding.y), frame_bb.Max, value_buf, value_buf_end, NULL, ImGuiAlign_Center);
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::SliderAngle(const char* label, float* v_rad, float v_degrees_min, float v_degrees_max)
{
float v_deg = (*v_rad) * 360.0f / (2*IM_PI);
bool value_changed = SliderFloat(label, &v_deg, v_degrees_min, v_degrees_max, "%.0f deg", 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* display_format)
{
if (!display_format)
display_format = "%.0f";
float v_f = (float)*v;
bool value_changed = SliderFloat(label, &v_f, (float)v_min, (float)v_max, display_format, 1.0f);
*v = (int)v_f;
return value_changed;
}
bool ImGui::VSliderInt(const char* label, const ImVec2& size, int* v, int v_min, int v_max, const char* display_format)
{
if (!display_format)
display_format = "%.0f";
float v_f = (float)*v;
bool value_changed = VSliderFloat(label, size, &v_f, (float)v_min, (float)v_max, display_format, 1.0f);
*v = (int)v_f;
return value_changed;
}
// Add multiple sliders on 1 line for compact edition of multiple components
bool ImGui::SliderFloatN(const char* label, float* v, int components, float v_min, float v_max, const char* display_format, float power)
{
ImGuiWindow* window = GetCurrentWindow();
if (window->SkipItems)
return false;
ImGuiContext& g = *GImGui;
bool value_changed = false;
BeginGroup();
PushID(label);
PushMultiItemsWidths(components);
for (int i = 0; i < components; i++)
{
PushID(i);
value_changed |= SliderFloat("##v", &v[i], v_min, v_max, display_format, power);
SameLine(0, g.Style.ItemInnerSpacing.x);
PopID();
PopItemWidth();
}
PopID();
TextUnformatted(label, FindRenderedTextEnd(label));
EndGroup();
return value_changed;
}
bool ImGui::SliderFloat2(const char* label, float v[2], float v_min, float v_max, const char* display_format, float power)
{
return SliderFloatN(label, v, 2, v_min, v_max, display_format, power);
}
bool ImGui::SliderFloat3(const char* label, float v[3], float v_min, float v_max, const char* display_format, float power)
{
return SliderFloatN(label, v, 3, v_min, v_max, display_format, power);
}
bool ImGui::SliderFloat4(const char* label, float v[4], float v_min, float v_max, const char* display_format, float power)
{
return SliderFloatN(label, v, 4, v_min, v_max, display_format, power);
}
bool ImGui::SliderIntN(const char* label, int* v, int components, int v_min, int v_max, const char* display_format)
{
ImGuiWindow* window = GetCurrentWindow();
if (window->SkipItems)
return false;
ImGuiContext& g = *GImGui;
bool value_changed = false;
BeginGroup();
PushID(label);
PushMultiItemsWidths(components);
for (int i = 0; i < components; i++)
{
PushID(i);
value_changed |= SliderInt("##v", &v[i], v_min, v_max, display_format);
SameLine(0, g.Style.ItemInnerSpacing.x);
PopID();
PopItemWidth();
}
PopID();
TextUnformatted(label, FindRenderedTextEnd(label));
EndGroup();
return value_changed;
}
bool ImGui::SliderInt2(const char* label, int v[2], int v_min, int v_max, const char* display_format)
{
return SliderIntN(label, v, 2, v_min, v_max, display_format);
}
bool ImGui::SliderInt3(const char* label, int v[3], int v_min, int v_max, const char* display_format)
{
return SliderIntN(label, v, 3, v_min, v_max, display_format);
}
bool ImGui::SliderInt4(const char* label, int v[4], int v_min, int v_max, const char* display_format)
{
return SliderIntN(label, v, 4, v_min, v_max, display_format);
}
bool ImGui::DragBehavior(const ImRect& frame_bb, ImGuiID id, float* v, float v_speed, float v_min, float v_max, int decimal_precision, float power)
{
ImGuiContext& g = *GImGui;
const ImGuiStyle& style = g.Style;
// Draw frame
const ImU32 frame_col = GetColorU32(g.ActiveId == id ? ImGuiCol_FrameBgActive : g.HoveredId == id ? ImGuiCol_FrameBgHovered : ImGuiCol_FrameBg);
RenderFrame(frame_bb.Min, frame_bb.Max, frame_col, true, style.FrameRounding);
bool value_changed = false;
// Process clicking on the drag
if (g.ActiveId == id)
{
if (g.IO.MouseDown[0])
{
if (g.ActiveIdIsJustActivated)
{
// Lock current value on click
g.DragCurrentValue = *v;
g.DragLastMouseDelta = ImVec2(0.f, 0.f);
}
float v_cur = g.DragCurrentValue;
const ImVec2 mouse_drag_delta = GetMouseDragDelta(0, 1.0f);
if (fabsf(mouse_drag_delta.x - g.DragLastMouseDelta.x) > 0.0f)
{
float speed = v_speed;
if (speed == 0.0f && (v_max - v_min) != 0.0f && (v_max - v_min) < FLT_MAX)
speed = (v_max - v_min) * g.DragSpeedDefaultRatio;
if (g.IO.KeyShift && g.DragSpeedScaleFast >= 0.0f)
speed = speed * g.DragSpeedScaleFast;
if (g.IO.KeyAlt && g.DragSpeedScaleSlow >= 0.0f)
speed = speed * g.DragSpeedScaleSlow;
float delta = (mouse_drag_delta.x - g.DragLastMouseDelta.x) * speed;
if (fabsf(power - 1.0f) > 0.001f)
{
// Logarithmic curve on both side of 0.0
float v0_abs = v_cur >= 0.0f ? v_cur : -v_cur;
float v0_sign = v_cur >= 0.0f ? 1.0f : -1.0f;
float v1 = powf(v0_abs, 1.0f / power) + (delta * v0_sign);
float v1_abs = v1 >= 0.0f ? v1 : -v1;
float v1_sign = v1 >= 0.0f ? 1.0f : -1.0f; // Crossed sign line
v_cur = powf(v1_abs, power) * v0_sign * v1_sign; // Reapply sign
}
else
{
v_cur += delta;
}
g.DragLastMouseDelta.x = mouse_drag_delta.x;
// Clamp
if (v_min < v_max)
v_cur = ImClamp(v_cur, v_min, v_max);
g.DragCurrentValue = v_cur;
}
// Round to user desired precision, then apply
v_cur = RoundScalar(v_cur, decimal_precision);
if (*v != v_cur)
{
*v = v_cur;
value_changed = true;
}
}
else
{
SetActiveID(0);
}
}
return value_changed;
}
bool ImGui::DragFloat(const char* label, float* v, float v_speed, float v_min, float v_max, const char* display_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 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.0f));
// NB- we don't call ItemSize() yet because we may turn into a text edit box below
if (!ItemAdd(total_bb, &id))
{
ItemSize(total_bb, style.FramePadding.y);
return false;
}
const bool hovered = IsHovered(frame_bb, id);
if (hovered)
SetHoveredID(id);
if (!display_format)
display_format = "%.3f";
int decimal_precision = ParseFormatPrecision(display_format, 3);
// Tabbing or CTRL-clicking on Drag turns it into an input box
bool start_text_input = false;
const bool tab_focus_requested = FocusableItemRegister(window, g.ActiveId == id);
if (tab_focus_requested || (hovered && (g.IO.MouseClicked[0] | g.IO.MouseDoubleClicked[0])))
{
SetActiveID(id, window);
FocusWindow(window);
if (tab_focus_requested || g.IO.KeyCtrl || g.IO.MouseDoubleClicked[0])
{
start_text_input = true;
g.ScalarAsInputTextId = 0;
}
}
if (start_text_input || (g.ActiveId == id && g.ScalarAsInputTextId == id))
return InputScalarAsWidgetReplacement(frame_bb, label, ImGuiDataType_Float, v, id, decimal_precision);
// Actual drag behavior
ItemSize(total_bb, style.FramePadding.y);
const bool value_changed = DragBehavior(frame_bb, id, v, v_speed, v_min, v_max, decimal_precision, power);
// 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 + ImFormatString(value_buf, IM_ARRAYSIZE(value_buf), display_format, *v);
RenderTextClipped(frame_bb.Min, frame_bb.Max, value_buf, value_buf_end, NULL, ImGuiAlign_Center|ImGuiAlign_VCenter);
if (label_size.x > 0.0f)
RenderText(ImVec2(frame_bb.Max.x + style.ItemInnerSpacing.x, inner_bb.Min.y), label);
return value_changed;
}
bool ImGui::DragFloatN(const char* label, float* v, int components, float v_speed, float v_min, float v_max, const char* display_format, float power)
{
ImGuiWindow* window = GetCurrentWindow();
if (window->SkipItems)
return false;
ImGuiContext& g = *GImGui;
bool value_changed = false;
BeginGroup();
PushID(label);
PushMultiItemsWidths(components);
for (int i = 0; i < components; i++)
{
PushID(i);
value_changed |= DragFloat("##v", &v[i], v_speed, v_min, v_max, display_format, power);
SameLine(0, g.Style.ItemInnerSpacing.x);
PopID();
PopItemWidth();
}
PopID();
TextUnformatted(label, FindRenderedTextEnd(label));
EndGroup();
return value_changed;
}
bool ImGui::DragFloat2(const char* label, float v[2], float v_speed, float v_min, float v_max, const char* display_format, float power)
{
return DragFloatN(label, v, 2, v_speed, v_min, v_max, display_format, power);
}
bool ImGui::DragFloat3(const char* label, float v[3], float v_speed, float v_min, float v_max, const char* display_format, float power)
{
return DragFloatN(label, v, 3, v_speed, v_min, v_max, display_format, power);
}
bool ImGui::DragFloat4(const char* label, float v[4], float v_speed, float v_min, float v_max, const char* display_format, float power)
{
return DragFloatN(label, v, 4, v_speed, v_min, v_max, display_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* display_format, const char* display_format_max, float power)
{
ImGuiWindow* window = GetCurrentWindow();
if (window->SkipItems)
return false;
ImGuiContext& g = *GImGui;
PushID(label);
BeginGroup();
PushMultiItemsWidths(2);
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), display_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, display_format_max ? display_format_max : display_format, power);
PopItemWidth();
SameLine(0, g.Style.ItemInnerSpacing.x);
TextUnformatted(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* display_format)
{
if (!display_format)
display_format = "%.0f";
float v_f = (float)*v;
bool value_changed = DragFloat(label, &v_f, v_speed, (float)v_min, (float)v_max, display_format);
*v = (int)v_f;
return value_changed;
}
bool ImGui::DragIntN(const char* label, int* v, int components, float v_speed, int v_min, int v_max, const char* display_format)
{
ImGuiWindow* window = GetCurrentWindow();
if (window->SkipItems)
return false;
ImGuiContext& g = *GImGui;
bool value_changed = false;
BeginGroup();
PushID(label);
PushMultiItemsWidths(components);
for (int i = 0; i < components; i++)
{
PushID(i);
value_changed |= DragInt("##v", &v[i], v_speed, v_min, v_max, display_format);
SameLine(0, g.Style.ItemInnerSpacing.x);
PopID();
PopItemWidth();
}
PopID();
TextUnformatted(label, FindRenderedTextEnd(label));
EndGroup();
return value_changed;
}
bool ImGui::DragInt2(const char* label, int v[2], float v_speed, int v_min, int v_max, const char* display_format)
{
return DragIntN(label, v, 2, v_speed, v_min, v_max, display_format);
}
bool ImGui::DragInt3(const char* label, int v[3], float v_speed, int v_min, int v_max, const char* display_format)
{
return DragIntN(label, v, 3, v_speed, v_min, v_max, display_format);
}
bool ImGui::DragInt4(const char* label, int v[4], float v_speed, int v_min, int v_max, const char* display_format)
{
return DragIntN(label, v, 4, v_speed, v_min, v_max, display_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* display_format, const char* display_format_max)
{
ImGuiWindow* window = GetCurrentWindow();
if (window->SkipItems)
return false;
ImGuiContext& g = *GImGui;
PushID(label);
BeginGroup();
PushMultiItemsWidths(2);
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), display_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, display_format_max ? display_format_max : display_format);
PopItemWidth();
SameLine(0, g.Style.ItemInnerSpacing.x);
TextUnformatted(label, FindRenderedTextEnd(label));
EndGroup();
PopID();
return value_changed;
}
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 graph_size)
{
ImGuiWindow* window = GetCurrentWindow();
if (window->SkipItems)
return;
ImGuiContext& g = *GImGui;
const ImGuiStyle& style = g.Style;
const ImVec2 label_size = CalcTextSize(label, NULL, true);
if (graph_size.x == 0.0f)
graph_size.x = CalcItemWidth();
if (graph_size.y == 0.0f)
graph_size.y = label_size.y + (style.FramePadding.y * 2);
const ImRect frame_bb(window->DC.CursorPos, window->DC.CursorPos + ImVec2(graph_size.x, graph_size.y));
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, NULL))
return;
// 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);
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);
int res_w = ImMin((int)graph_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 (IsHovered(inner_bb, 0))
{
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;
float v0 = values_getter(data, (0 + values_offset) % values_count);
float t0 = 0.0f;
ImVec2 tp0 = ImVec2( t0, 1.0f - ImSaturate((v0 - scale_min) / (scale_max - scale_min)) ); // Point in the normalized space of our target rectangle
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) / (scale_max - scale_min)) );
// 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, 1.0f));
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, ImGuiAlign_Center);
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 = *(float*)(void*)((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);
}
// 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;
ImRect bb(pos, pos + CalcItemSize(size_arg, CalcItemWidth(), g.FontSize + style.FramePadding.y*2.0f));
ItemSize(bb, style.FramePadding.y);
if (!ItemAdd(bb, NULL))
return;
// Render
fraction = ImSaturate(fraction);
RenderFrame(bb.Min, bb.Max, GetColorU32(ImGuiCol_FrameBg), true, style.FrameRounding);
bb.Reduce(ImVec2(window->BorderSize, window->BorderSize));
const ImVec2 fill_br = ImVec2(ImLerp(bb.Min.x, bb.Max.x, fraction), bb.Max.y);
RenderFrame(bb.Min, fill_br, GetColorU32(ImGuiCol_PlotHistogram), false, 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, ImGuiAlign_Left|ImGuiAlign_VCenter, &bb.Min, &bb.Max);
}
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 ImRect check_bb(window->DC.CursorPos, window->DC.CursorPos + ImVec2(label_size.y + style.FramePadding.y*2, label_size.y + style.FramePadding.y*2));
ItemSize(check_bb, style.FramePadding.y);
ImRect total_bb = check_bb;
if (label_size.x > 0)
SameLine(0, style.ItemInnerSpacing.x);
const ImRect text_bb(window->DC.CursorPos + ImVec2(0,style.FramePadding.y), window->DC.CursorPos + ImVec2(0,style.FramePadding.y) + label_size);
if (label_size.x > 0)
{
ItemSize(ImVec2(text_bb.GetWidth(), check_bb.GetHeight()), style.FramePadding.y);
total_bb = ImRect(ImMin(check_bb.Min, text_bb.Min), ImMax(check_bb.Max, text_bb.Max));
}
if (!ItemAdd(total_bb, &id))
return false;
bool hovered, held;
bool pressed = ButtonBehavior(total_bb, id, &hovered, &held);
if (pressed)
*v = !(*v);
RenderFrame(check_bb.Min, check_bb.Max, GetColorU32((held && hovered) ? ImGuiCol_FrameBgActive : hovered ? ImGuiCol_FrameBgHovered : ImGuiCol_FrameBg), true, style.FrameRounding);
if (*v)
{
const float check_sz = ImMin(check_bb.GetWidth(), check_bb.GetHeight());
const float pad = ImMax(1.0f, (float)(int)(check_sz / 6.0f));
window->DrawList->AddRectFilled(check_bb.Min+ImVec2(pad,pad), check_bb.Max-ImVec2(pad,pad), GetColorU32(ImGuiCol_CheckMark), style.FrameRounding);
}
if (g.LogEnabled)
LogRenderedText(text_bb.GetTL(), *v ? "[x]" : "[ ]");
if (label_size.x > 0.0f)
RenderText(text_bb.GetTL(), label);
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 ImRect check_bb(window->DC.CursorPos, window->DC.CursorPos + ImVec2(label_size.y + style.FramePadding.y*2-1, label_size.y + style.FramePadding.y*2-1));
ItemSize(check_bb, style.FramePadding.y);
ImRect total_bb = check_bb;
if (label_size.x > 0)
SameLine(0, style.ItemInnerSpacing.x);
const ImRect text_bb(window->DC.CursorPos + ImVec2(0, style.FramePadding.y), window->DC.CursorPos + ImVec2(0, style.FramePadding.y) + label_size);
if (label_size.x > 0)
{
ItemSize(ImVec2(text_bb.GetWidth(), check_bb.GetHeight()), style.FramePadding.y);
total_bb.Add(text_bb);
}
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 = check_bb.GetHeight() * 0.5f;
bool hovered, held;
bool pressed = ButtonBehavior(total_bb, id, &hovered, &held);
window->DrawList->AddCircleFilled(center, radius, GetColorU32((held && hovered) ? ImGuiCol_FrameBgActive : hovered ? ImGuiCol_FrameBgHovered : ImGuiCol_FrameBg), 16);
if (active)
{
const float check_sz = ImMin(check_bb.GetWidth(), check_bb.GetHeight());
const float pad = ImMax(1.0f, (float)(int)(check_sz / 6.0f));
window->DrawList->AddCircleFilled(center, radius-pad, GetColorU32(ImGuiCol_CheckMark), 16);
}
if (window->Flags & ImGuiWindowFlags_ShowBorders)
{
window->DrawList->AddCircle(center+ImVec2(1,1), radius, GetColorU32(ImGuiCol_BorderShadow), 16);
window->DrawList->AddCircle(center, radius, GetColorU32(ImGuiCol_Border), 16);
}
if (g.LogEnabled)
LogRenderedText(text_bb.GetTL(), active ? "(x)" : "( )");
if (label_size.x > 0.0f)
RenderText(text_bb.GetTL(), label);
return pressed;
}
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;
}
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)
{
ImFont* font = GImGui->Font;
const float line_height = GImGui->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((unsigned short)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 ImGuiStb
{
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->Text[idx]; }
static float STB_TEXTEDIT_GETWIDTH(STB_TEXTEDIT_STRING* obj, int line_start_idx, int char_idx) { ImWchar c = obj->Text[line_start_idx+char_idx]; if (c == '\n') return STB_TEXTEDIT_GETWIDTH_NEWLINE; return GImGui->Font->GetCharAdvance(c) * (GImGui->FontSize / GImGui->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->Text.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 ImCharIsSpace(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->Text[idx-1] ) && !is_separator( obj->Text[idx] ) ) : 1; }
static int STB_TEXTEDIT_MOVEWORDLEFT_IMPL(STB_TEXTEDIT_STRING* obj, int 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->Text[idx-1] ) && is_separator( obj->Text[idx] ) ) : 1; }
static int STB_TEXTEDIT_MOVEWORDRIGHT_IMPL(STB_TEXTEDIT_STRING* obj, int 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) { 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->Text.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
const ImWchar* src = obj->Text.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 int text_len = obj->CurLenW;
IM_ASSERT(pos <= text_len);
if (new_text_len + text_len + 1 > obj->Text.Size)
return false;
const int new_text_len_utf8 = ImTextCountUtf8BytesFromStr(new_text, new_text + new_text_len);
if (new_text_len_utf8 + obj->CurLenA + 1 > obj->BufSizeA)
return false;
ImWchar* text = obj->Text.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->Text[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 "stb_textedit.h"
}
void ImGuiTextEditState::OnKeyPressed(int key)
{
stb_textedit_key(this, &StbState, key);
CursorFollow = true;
CursorAnimReset();
}
// 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 ImGuiTextEditCallbackData::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 ImGuiTextEditCallbackData::InsertChars(int pos, const char* new_text, const char* new_text_end)
{
const int new_text_len = new_text_end ? (int)(new_text_end - new_text) : (int)strlen(new_text);
if (new_text_len + BufTextLen + 1 >= BufSize)
return;
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, ImGuiTextEditCallback callback, void* user_data)
{
unsigned int c = *p_char;
if (c < 128 && c != ' ' && !isprint((int)(c & 0xFF)))
{
bool pass = false;
pass |= (c == '\n' && (flags & ImGuiInputTextFlags_Multiline));
pass |= (c == '\t' && (flags & ImGuiInputTextFlags_AllowTabInput));
if (!pass)
return false;
}
if (c >= 0xE000 && c <= 0xF8FF) // Filter private Unicode range. I don't imagine anybody would want to input them. GLFW on OSX seems to send private characters for special keys like arrow keys.
return false;
if (flags & (ImGuiInputTextFlags_CharsDecimal | ImGuiInputTextFlags_CharsHexadecimal | ImGuiInputTextFlags_CharsUppercase | ImGuiInputTextFlags_CharsNoBlank))
{
if (flags & ImGuiInputTextFlags_CharsDecimal)
if (!(c >= '0' && c <= '9') && (c != '.') && (c != '-') && (c != '+') && (c != '*') && (c != '/'))
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 (ImCharIsSpace(c))
return false;
}
if (flags & ImGuiInputTextFlags_CallbackCharFilter)
{
ImGuiTextEditCallbackData callback_data;
memset(&callback_data, 0, sizeof(ImGuiTextEditCallbackData));
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
// NB: when active, hold on a privately held copy of the text (and apply back to 'buf'). So changing 'buf' while active has no effect.
// FIXME: Rather messy function partly because we are doing UTF8 > u16 > UTF8 conversions on the go to more easily handle stb_textedit calls. Ideally we should stay in UTF-8 all the time. See https://github.com/nothings/stb/issues/188
bool ImGui::InputTextEx(const char* label, char* buf, int buf_size, const ImVec2& size_arg, ImGuiInputTextFlags flags, ImGuiTextEditCallback callback, void* 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;
const ImGuiIO& io = g.IO;
const ImGuiStyle& style = g.Style;
const ImGuiID id = window->GetID(label);
const bool is_multiline = (flags & ImGuiInputTextFlags_Multiline) != 0;
const bool is_editable = (flags & ImGuiInputTextFlags_ReadOnly) == 0;
const bool is_password = (flags & ImGuiInputTextFlags_Password) != 0;
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)
{
BeginGroup();
if (!BeginChildFrame(id, frame_bb.GetSize()))
{
EndChildFrame();
EndGroup();
return false;
}
draw_window = GetCurrentWindow();
size.x -= draw_window->ScrollbarSizes.x;
}
else
{
ItemSize(total_bb, style.FramePadding.y);
if (!ItemAdd(total_bb, &id))
return false;
}
// Password pushes a temporary font with only a fallback glyph
if (is_password)
{
const ImFont::Glyph* 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->FallbackXAdvance = glyph->XAdvance;
IM_ASSERT(password_font->Glyphs.empty() && password_font->IndexXAdvance.empty() && password_font->IndexLookup.empty());
PushFont(password_font);
}
// NB: we are only allowed to access 'edit_state' if we are the active widget.
ImGuiTextEditState& edit_state = g.InputTextState;
const bool focus_requested = FocusableItemRegister(window, g.ActiveId == id, (flags & (ImGuiInputTextFlags_CallbackCompletion|ImGuiInputTextFlags_AllowTabInput)) == 0); // Using completion callback disable keyboard tabbing
const bool focus_requested_by_code = focus_requested && (window->FocusIdxAllCounter == window->FocusIdxAllRequestCurrent);
const bool focus_requested_by_tab = focus_requested && !focus_requested_by_code;
const bool hovered = IsHovered(frame_bb, id);
if (hovered)
{
SetHoveredID(id);
g.MouseCursor = ImGuiMouseCursor_TextInput;
}
const bool user_clicked = hovered && io.MouseClicked[0];
const bool user_scrolled = is_multiline && g.ActiveId == 0 && edit_state.Id == id && g.ActiveIdPreviousFrame == draw_window->GetIDNoKeepAlive("#SCROLLY");
bool select_all = (g.ActiveId != id) && (flags & ImGuiInputTextFlags_AutoSelectAll) != 0;
if (focus_requested || user_clicked || user_scrolled)
{
if (g.ActiveId != id)
{
// Start edition
// 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 prev_len_w = edit_state.CurLenW;
edit_state.Text.resize(buf_size+1); // wchar count <= UTF-8 count. we use +1 to make sure that .Data isn't NULL so it doesn't crash.
edit_state.InitialText.resize(buf_size+1); // UTF-8. we use +1 to make sure that .Data isn't NULL so it doesn't crash.
ImStrncpy(edit_state.InitialText.Data, buf, edit_state.InitialText.Size);
const char* buf_end = NULL;
edit_state.CurLenW = ImTextStrFromUtf8(edit_state.Text.Data, edit_state.Text.Size, buf, NULL, &buf_end);
edit_state.CurLenA = (int)(buf_end - buf); // We can't get the result from ImFormatString() above because it is not UTF-8 aware. Here we'll cut off malformed UTF-8.
edit_state.CursorAnimReset();
// Preserve cursor position and undo/redo stack if we come back to same widget
// FIXME: We should probably compare the whole buffer to be on the safety side. Comparing buf (utf8) and edit_state.Text (wchar).
const bool recycle_state = (edit_state.Id == id) && (prev_len_w == edit_state.CurLenW);
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.
edit_state.CursorClamp();
}
else
{
edit_state.Id = id;
edit_state.ScrollX = 0.0f;
stb_textedit_initialize_state(&edit_state.StbState, !is_multiline);
if (!is_multiline && focus_requested_by_code)
select_all = true;
}
if (flags & ImGuiInputTextFlags_AlwaysInsertMode)
edit_state.StbState.insert_mode = true;
if (!is_multiline && (focus_requested_by_tab || (user_clicked && io.KeyCtrl)))
select_all = true;
}
SetActiveID(id, window);
FocusWindow(window);
}
else if (io.MouseClicked[0])
{
// Release focus when we click outside
if (g.ActiveId == id)
SetActiveID(0);
}
bool value_changed = false;
bool enter_pressed = false;
if (g.ActiveId == id)
{
if (!is_editable && !g.ActiveIdIsJustActivated)
{
// When read-only we always use the live data passed to the function
edit_state.Text.resize(buf_size+1);
const char* buf_end = NULL;
edit_state.CurLenW = ImTextStrFromUtf8(edit_state.Text.Data, edit_state.Text.Size, buf, NULL, &buf_end);
edit_state.CurLenA = (int)(buf_end - buf);
edit_state.CursorClamp();
}
edit_state.BufSizeA = buf_size;
// 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];
// Edit in progress
const float mouse_x = (io.MousePos.x - frame_bb.Min.x - style.FramePadding.x) + edit_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 osx_double_click_selects_words = io.OSXBehaviors; // OS X style: Double click selects by word instead of selecting whole text
if (select_all || (hovered && !osx_double_click_selects_words && io.MouseDoubleClicked[0]))
{
edit_state.SelectAll();
edit_state.SelectedAllMouseLock = true;
}
else if (hovered && osx_double_click_selects_words && io.MouseDoubleClicked[0])
{
// Select a word only, OS X style (by simulating keystrokes)
edit_state.OnKeyPressed(STB_TEXTEDIT_K_WORDLEFT);
edit_state.OnKeyPressed(STB_TEXTEDIT_K_WORDRIGHT | STB_TEXTEDIT_K_SHIFT);
}
else if (io.MouseClicked[0] && !edit_state.SelectedAllMouseLock)
{
stb_textedit_click(&edit_state, &edit_state.StbState, mouse_x, mouse_y);
edit_state.CursorAnimReset();
}
else if (io.MouseDown[0] && !edit_state.SelectedAllMouseLock && (io.MouseDelta.x != 0.0f || io.MouseDelta.y != 0.0f))
{
stb_textedit_drag(&edit_state, &edit_state.StbState, mouse_x, mouse_y);
edit_state.CursorAnimReset();
edit_state.CursorFollow = true;
}
if (edit_state.SelectedAllMouseLock && !io.MouseDown[0])
edit_state.SelectedAllMouseLock = false;
if (io.InputCharacters[0])
{
// Process text input (before we check for Return because using some IME will effectively send a Return?)
// We ignore CTRL inputs, but need to allow CTRL+ALT as some keyboards (e.g. German) use AltGR - which is Alt+Ctrl - to input certain characters.
if (!(io.KeyCtrl && !io.KeyAlt) && is_editable)
{
for (int n = 0; n < IM_ARRAYSIZE(io.InputCharacters) && io.InputCharacters[n]; n++)
if (unsigned int c = (unsigned int)io.InputCharacters[n])
{
// Insert character if they pass filtering
if (!InputTextFilterCharacter(&c, flags, callback, user_data))
continue;
edit_state.OnKeyPressed((int)c);
}
}
// Consume characters
memset(g.IO.InputCharacters, 0, sizeof(g.IO.InputCharacters));
}
// Handle various key-presses
bool cancel_edit = false;
const int k_mask = (io.KeyShift ? STB_TEXTEDIT_K_SHIFT : 0);
const bool is_shortcut_key_only = (io.OSXBehaviors ? (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_wordmove_key_down = io.OSXBehaviors ? io.KeyAlt : io.KeyCtrl; // OS X style: Text editing cursor movement using Alt instead of Ctrl
const bool is_startend_key_down = io.OSXBehaviors && io.KeySuper && !io.KeyCtrl && !io.KeyAlt; // OS X style: Line/Text Start and End using Cmd+Arrows instead of Home/End
if (IsKeyPressedMap(ImGuiKey_LeftArrow)) { edit_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)) { edit_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) SetWindowScrollY(draw_window, ImMax(draw_window->Scroll.y - g.FontSize, 0.0f)); else edit_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) SetWindowScrollY(draw_window, ImMin(draw_window->Scroll.y + g.FontSize, GetScrollMaxY())); else edit_state.OnKeyPressed((is_startend_key_down ? STB_TEXTEDIT_K_TEXTEND : STB_TEXTEDIT_K_DOWN) | k_mask); }
else if (IsKeyPressedMap(ImGuiKey_Home)) { edit_state.OnKeyPressed(io.KeyCtrl ? STB_TEXTEDIT_K_TEXTSTART | k_mask : STB_TEXTEDIT_K_LINESTART | k_mask); }
else if (IsKeyPressedMap(ImGuiKey_End)) { edit_state.OnKeyPressed(io.KeyCtrl ? STB_TEXTEDIT_K_TEXTEND | k_mask : STB_TEXTEDIT_K_LINEEND | k_mask); }
else if (IsKeyPressedMap(ImGuiKey_Delete) && is_editable) { edit_state.OnKeyPressed(STB_TEXTEDIT_K_DELETE | k_mask); }
else if (IsKeyPressedMap(ImGuiKey_Backspace) && is_editable)
{
if (!edit_state.HasSelection())
{
if (is_wordmove_key_down) edit_state.OnKeyPressed(STB_TEXTEDIT_K_WORDLEFT|STB_TEXTEDIT_K_SHIFT);
else if (io.OSXBehaviors && io.KeySuper && !io.KeyAlt && !io.KeyCtrl) edit_state.OnKeyPressed(STB_TEXTEDIT_K_LINESTART|STB_TEXTEDIT_K_SHIFT);
}
edit_state.OnKeyPressed(STB_TEXTEDIT_K_BACKSPACE | k_mask);
}
else if (IsKeyPressedMap(ImGuiKey_Enter))
{
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))
{
SetActiveID(0);
enter_pressed = true;
}
else if (is_editable)
{
unsigned int c = '\n'; // Insert new line
if (InputTextFilterCharacter(&c, flags, callback, user_data))
edit_state.OnKeyPressed((int)c);
}
}
else if ((flags & ImGuiInputTextFlags_AllowTabInput) && IsKeyPressedMap(ImGuiKey_Tab) && !io.KeyCtrl && !io.KeyShift && !io.KeyAlt && is_editable)
{
unsigned int c = '\t'; // Insert TAB
if (InputTextFilterCharacter(&c, flags, callback, user_data))
edit_state.OnKeyPressed((int)c);
}
else if (IsKeyPressedMap(ImGuiKey_Escape)) { SetActiveID(0); cancel_edit = true; }
else if (is_shortcut_key_only && IsKeyPressedMap(ImGuiKey_Z) && is_editable) { edit_state.OnKeyPressed(STB_TEXTEDIT_K_UNDO); edit_state.ClearSelection(); }
else if (is_shortcut_key_only && IsKeyPressedMap(ImGuiKey_Y) && is_editable) { edit_state.OnKeyPressed(STB_TEXTEDIT_K_REDO); edit_state.ClearSelection(); }
else if (is_shortcut_key_only && IsKeyPressedMap(ImGuiKey_A)) { edit_state.SelectAll(); edit_state.CursorFollow = true; }
else if (is_shortcut_key_only && !is_password && ((IsKeyPressedMap(ImGuiKey_X) && is_editable) || IsKeyPressedMap(ImGuiKey_C)) && (!is_multiline || edit_state.HasSelection()))
{
// Cut, Copy
const bool cut = IsKeyPressedMap(ImGuiKey_X);
if (cut && !edit_state.HasSelection())
edit_state.SelectAll();
if (io.SetClipboardTextFn)
{
const int ib = edit_state.HasSelection() ? ImMin(edit_state.StbState.select_start, edit_state.StbState.select_end) : 0;
const int ie = edit_state.HasSelection() ? ImMax(edit_state.StbState.select_start, edit_state.StbState.select_end) : edit_state.CurLenW;
edit_state.TempTextBuffer.resize((ie-ib) * 4 + 1);
ImTextStrToUtf8(edit_state.TempTextBuffer.Data, edit_state.TempTextBuffer.Size, edit_state.Text.Data+ib, edit_state.Text.Data+ie);
io.SetClipboardTextFn(edit_state.TempTextBuffer.Data);
}
if (cut)
{
edit_state.CursorFollow = true;
stb_textedit_cut(&edit_state, &edit_state.StbState);
}
}
else if (is_shortcut_key_only && IsKeyPressedMap(ImGuiKey_V) && is_editable)
{
// Paste
if (const char* clipboard = io.GetClipboardTextFn ? io.GetClipboardTextFn() : NULL)
{
// Filter pasted buffer
const int clipboard_len = (int)strlen(clipboard);
ImWchar* clipboard_filtered = (ImWchar*)ImGui::MemAlloc((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, 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(&edit_state, &edit_state.StbState, clipboard_filtered, clipboard_filtered_len);
edit_state.CursorFollow = true;
}
ImGui::MemFree(clipboard_filtered);
}
}
if (cancel_edit)
{
// Restore initial value
if (is_editable)
{
ImStrncpy(buf, edit_state.InitialText.Data, buf_size);
value_changed = true;
}
}
else
{
// 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_editable)
{
edit_state.TempTextBuffer.resize(edit_state.Text.Size * 4);
ImTextStrToUtf8(edit_state.TempTextBuffer.Data, edit_state.TempTextBuffer.Size, edit_state.Text.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)
{
ImGuiTextEditCallbackData callback_data;
memset(&callback_data, 0, sizeof(ImGuiTextEditCallbackData));
callback_data.EventFlag = event_flag;
callback_data.Flags = flags;
callback_data.UserData = user_data;
callback_data.ReadOnly = !is_editable;
callback_data.EventKey = event_key;
callback_data.Buf = edit_state.TempTextBuffer.Data;
callback_data.BufTextLen = edit_state.CurLenA;
callback_data.BufSize = edit_state.BufSizeA;
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 = edit_state.Text.Data;
const int utf8_cursor_pos = callback_data.CursorPos = ImTextCountUtf8BytesFromStr(text, text + edit_state.StbState.cursor);
const int utf8_selection_start = callback_data.SelectionStart = ImTextCountUtf8BytesFromStr(text, text + edit_state.StbState.select_start);
const int utf8_selection_end = callback_data.SelectionEnd = ImTextCountUtf8BytesFromStr(text, text + edit_state.StbState.select_end);
// Call user code
callback(&callback_data);
// Read back what user may have modified
IM_ASSERT(callback_data.Buf == edit_state.TempTextBuffer.Data); // Invalid to modify those fields
IM_ASSERT(callback_data.BufSize == edit_state.BufSizeA);
IM_ASSERT(callback_data.Flags == flags);
if (callback_data.CursorPos != utf8_cursor_pos) edit_state.StbState.cursor = ImTextCountCharsFromUtf8(callback_data.Buf, callback_data.Buf + callback_data.CursorPos);
if (callback_data.SelectionStart != utf8_selection_start) edit_state.StbState.select_start = ImTextCountCharsFromUtf8(callback_data.Buf, callback_data.Buf + callback_data.SelectionStart);
if (callback_data.SelectionEnd != utf8_selection_end) edit_state.StbState.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!
edit_state.CurLenW = ImTextStrFromUtf8(edit_state.Text.Data, edit_state.Text.Size, callback_data.Buf, NULL);
edit_state.CurLenA = callback_data.BufTextLen; // Assume correct length and valid UTF-8 from user, saves us an extra strlen()
edit_state.CursorAnimReset();
}
}
}
// Copy back to user buffer
if (is_editable && strcmp(edit_state.TempTextBuffer.Data, buf) != 0)
{
ImStrncpy(buf, edit_state.TempTextBuffer.Data, buf_size);
value_changed = true;
}
}
}
// Render
// Select which buffer we are going to display. When ImGuiInputTextFlags_NoLiveEdit is set 'buf' might still be the old value. We set buf to NULL to prevent accidental usage from now on.
const char* buf_display = (g.ActiveId == id && is_editable) ? edit_state.TempTextBuffer.Data : buf; buf = NULL;
if (!is_multiline)
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 render_pos = is_multiline ? draw_window->DC.CursorPos : frame_bb.Min + style.FramePadding;
ImVec2 text_size(0.f, 0.f);
const bool is_currently_scrolling = (edit_state.Id == id && is_multiline && g.ActiveId == draw_window->GetIDNoKeepAlive("#SCROLLY"));
if (g.ActiveId == id || is_currently_scrolling)
{
edit_state.CursorAnim += io.DeltaTime;
// 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 = edit_state.Text.Data;
ImVec2 cursor_offset, select_start_offset;
{
// Count lines + find lines numbers straddling 'cursor' and 'select_start' position.
const ImWchar* searches_input_ptr[2];
searches_input_ptr[0] = text_begin + edit_state.StbState.cursor;
searches_input_ptr[1] = NULL;
int searches_remaining = 1;
int searches_result_line_number[2] = { -1, -999 };
if (edit_state.StbState.select_start != edit_state.StbState.select_end)
{
searches_input_ptr[1] = text_begin + ImMin(edit_state.StbState.select_start, edit_state.StbState.select_end);
searches_result_line_number[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 != 0; s++)
if (*s == '\n')
{
line_count++;
if (searches_result_line_number[0] == -1 && s >= searches_input_ptr[0]) { searches_result_line_number[0] = line_count; if (--searches_remaining <= 0) break; }
if (searches_result_line_number[1] == -1 && s >= searches_input_ptr[1]) { searches_result_line_number[1] = line_count; if (--searches_remaining <= 0) break; }
}
line_count++;
if (searches_result_line_number[0] == -1) searches_result_line_number[0] = line_count;
if (searches_result_line_number[1] == -1) searches_result_line_number[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_number[0] * g.FontSize;
if (searches_result_line_number[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_number[1] * g.FontSize;
}
// Calculate text height
if (is_multiline)
text_size = ImVec2(size.x, line_count * g.FontSize);
}
// Scroll
if (edit_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 < edit_state.ScrollX)
edit_state.ScrollX = (float)(int)ImMax(0.0f, cursor_offset.x - scroll_increment_x);
else if (cursor_offset.x - size.x >= edit_state.ScrollX)
edit_state.ScrollX = (float)(int)(cursor_offset.x - size.x + scroll_increment_x);
}
else
{
edit_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_window->DC.CursorPos.y += (draw_window->Scroll.y - scroll_y); // To avoid a frame of lag
draw_window->Scroll.y = scroll_y;
render_pos.y = draw_window->DC.CursorPos.y;
}
}
edit_state.CursorFollow = false;
const ImVec2 render_scroll = ImVec2(edit_state.ScrollX, 0.0f);
// Draw selection
if (edit_state.StbState.select_start != edit_state.StbState.select_end)
{
const ImWchar* text_selected_begin = text_begin + ImMin(edit_state.StbState.select_start, edit_state.StbState.select_end);
const ImWchar* text_selected_end = text_begin + ImMax(edit_state.StbState.select_start, edit_state.StbState.select_end);
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;
ImU32 bg_color = GetColorU32(ImGuiCol_TextSelectedBg);
ImVec2 rect_pos = render_pos + select_start_offset - render_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)
{
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((unsigned short)' ') * 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.Clip(clip_rect);
if (rect.Overlaps(clip_rect))
draw_window->DrawList->AddRectFilled(rect.Min, rect.Max, bg_color);
}
rect_pos.x = render_pos.x - render_scroll.x;
rect_pos.y += g.FontSize;
}
}
draw_window->DrawList->AddText(g.Font, g.FontSize, render_pos - render_scroll, GetColorU32(ImGuiCol_Text), buf_display, buf_display + edit_state.CurLenA, 0.0f, is_multiline ? NULL : &clip_rect);
// Draw blinking cursor
bool cursor_is_visible = (g.InputTextState.CursorAnim <= 0.0f) || fmodf(g.InputTextState.CursorAnim, 1.20f) <= 0.80f;
ImVec2 cursor_screen_pos = render_pos + cursor_offset - render_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_editable)
g.OsImePosRequest = ImVec2(cursor_screen_pos.x - 1, cursor_screen_pos.y - g.FontSize);
}
else
{
// Render text only
const char* buf_end = NULL;
if (is_multiline)
text_size = ImVec2(size.x, InputTextCalcTextLenAndLineCount(buf_display, &buf_end) * g.FontSize); // We don't need width
draw_window->DrawList->AddText(g.Font, g.FontSize, render_pos, GetColorU32(ImGuiCol_Text), buf_display, buf_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 (g.ActiveId == id || is_currently_scrolling) // Set LastItemId which was lost by EndChild/EndGroup, so user can use IsItemActive()
window->DC.LastItemId = g.ActiveId;
}
if (is_password)
PopFont();
// Log as text
if (g.LogEnabled && !is_password)
LogRenderedText(render_pos, buf_display, NULL);
if (label_size.x > 0)
RenderText(ImVec2(frame_bb.Max.x + style.ItemInnerSpacing.x, frame_bb.Min.y + style.FramePadding.y), label);
if ((flags & ImGuiInputTextFlags_EnterReturnsTrue) != 0)
return enter_pressed;
else
return value_changed;
}
bool ImGui::InputText(const char* label, char* buf, size_t buf_size, ImGuiInputTextFlags flags, ImGuiTextEditCallback callback, void* user_data)
{
IM_ASSERT(!(flags & ImGuiInputTextFlags_Multiline)); // call InputTextMultiline()
return InputTextEx(label, 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, ImGuiTextEditCallback callback, void* user_data)
{
return InputTextEx(label, buf, (int)buf_size, size, flags | ImGuiInputTextFlags_Multiline, callback, user_data);
}
// NB: scalar_format here must be a simple "%xx" format string with no prefix/suffix (unlike the Drag/Slider functions "display_format" argument)
bool ImGui::InputScalarEx(const char* label, ImGuiDataType data_type, void* data_ptr, void* step_ptr, void* step_fast_ptr, const char* scalar_format, ImGuiInputTextFlags extra_flags)
{
ImGuiWindow* window = GetCurrentWindow();
if (window->SkipItems)
return false;
ImGuiContext& g = *GImGui;
const ImGuiStyle& style = g.Style;
const ImVec2 label_size = CalcTextSize(label, NULL, true);
BeginGroup();
PushID(label);
const ImVec2 button_sz = ImVec2(g.FontSize, g.FontSize) + style.FramePadding*2.0f;
if (step_ptr)
PushItemWidth(ImMax(1.0f, CalcItemWidth() - (button_sz.x + style.ItemInnerSpacing.x)*2));
char buf[64];
DataTypeFormatString(data_type, data_ptr, scalar_format, buf, IM_ARRAYSIZE(buf));
bool value_changed = false;
if (!(extra_flags & ImGuiInputTextFlags_CharsHexadecimal))
extra_flags |= ImGuiInputTextFlags_CharsDecimal;
extra_flags |= ImGuiInputTextFlags_AutoSelectAll;
if (InputText("", buf, IM_ARRAYSIZE(buf), extra_flags))
value_changed = DataTypeApplyOpFromText(buf, GImGui->InputTextState.InitialText.begin(), data_type, data_ptr, scalar_format);
// Step buttons
if (step_ptr)
{
PopItemWidth();
SameLine(0, style.ItemInnerSpacing.x);
if (ButtonEx("-", button_sz, ImGuiButtonFlags_Repeat | ImGuiButtonFlags_DontClosePopups))
{
DataTypeApplyOp(data_type, '-', data_ptr, g.IO.KeyCtrl && step_fast_ptr ? step_fast_ptr : step_ptr);
value_changed = true;
}
SameLine(0, style.ItemInnerSpacing.x);
if (ButtonEx("+", button_sz, ImGuiButtonFlags_Repeat | ImGuiButtonFlags_DontClosePopups))
{
DataTypeApplyOp(data_type, '+', data_ptr, g.IO.KeyCtrl && step_fast_ptr ? step_fast_ptr : step_ptr);
value_changed = true;
}
}
PopID();
if (label_size.x > 0)
{
SameLine(0, style.ItemInnerSpacing.x);
RenderText(ImVec2(window->DC.CursorPos.x, window->DC.CursorPos.y + style.FramePadding.y), label);
ItemSize(label_size, style.FramePadding.y);
}
EndGroup();
return value_changed;
}
bool ImGui::InputFloat(const char* label, float* v, float step, float step_fast, int decimal_precision, ImGuiInputTextFlags extra_flags)
{
char display_format[16];
if (decimal_precision < 0)
strcpy(display_format, "%f"); // Ideally we'd have a minimum decimal precision of 1 to visually denote that this is a float, while hiding non-significant digits? %f doesn't have a minimum of 1
else
ImFormatString(display_format, 16, "%%.%df", decimal_precision);
return InputScalarEx(label, ImGuiDataType_Float, (void*)v, (void*)(step>0.0f ? &step : NULL), (void*)(step_fast>0.0f ? &step_fast : NULL), display_format, extra_flags);
}
bool ImGui::InputInt(const char* label, int* v, int step, int step_fast, ImGuiInputTextFlags extra_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* scalar_format = (extra_flags & ImGuiInputTextFlags_CharsHexadecimal) ? "%08X" : "%d";
return InputScalarEx(label, ImGuiDataType_Int, (void*)v, (void*)(step>0.0f ? &step : NULL), (void*)(step_fast>0.0f ? &step_fast : NULL), scalar_format, extra_flags);
}
bool ImGui::InputFloatN(const char* label, float* v, int components, int decimal_precision, ImGuiInputTextFlags extra_flags)
{
ImGuiWindow* window = GetCurrentWindow();
if (window->SkipItems)
return false;
ImGuiContext& g = *GImGui;
bool value_changed = false;
BeginGroup();
PushID(label);
PushMultiItemsWidths(components);
for (int i = 0; i < components; i++)
{
PushID(i);
value_changed |= InputFloat("##v", &v[i], 0, 0, decimal_precision, extra_flags);
SameLine(0, g.Style.ItemInnerSpacing.x);
PopID();
PopItemWidth();
}
PopID();
window->DC.CurrentLineTextBaseOffset = ImMax(window->DC.CurrentLineTextBaseOffset, g.Style.FramePadding.y);
TextUnformatted(label, FindRenderedTextEnd(label));
EndGroup();
return value_changed;
}
bool ImGui::InputFloat2(const char* label, float v[2], int decimal_precision, ImGuiInputTextFlags extra_flags)
{
return InputFloatN(label, v, 2, decimal_precision, extra_flags);
}
bool ImGui::InputFloat3(const char* label, float v[3], int decimal_precision, ImGuiInputTextFlags extra_flags)
{
return InputFloatN(label, v, 3, decimal_precision, extra_flags);
}
bool ImGui::InputFloat4(const char* label, float v[4], int decimal_precision, ImGuiInputTextFlags extra_flags)
{
return InputFloatN(label, v, 4, decimal_precision, extra_flags);
}
bool ImGui::InputIntN(const char* label, int* v, int components, ImGuiInputTextFlags extra_flags)
{
ImGuiWindow* window = GetCurrentWindow();
if (window->SkipItems)
return false;
ImGuiContext& g = *GImGui;
bool value_changed = false;
BeginGroup();
PushID(label);
PushMultiItemsWidths(components);
for (int i = 0; i < components; i++)
{
PushID(i);
value_changed |= InputInt("##v", &v[i], 0, 0, extra_flags);
SameLine(0, g.Style.ItemInnerSpacing.x);
PopID();
PopItemWidth();
}
PopID();
window->DC.CurrentLineTextBaseOffset = ImMax(window->DC.CurrentLineTextBaseOffset, g.Style.FramePadding.y);
TextUnformatted(label, FindRenderedTextEnd(label));
EndGroup();
return value_changed;
}
bool ImGui::InputInt2(const char* label, int v[2], ImGuiInputTextFlags extra_flags)
{
return InputIntN(label, v, 2, extra_flags);
}
bool ImGui::InputInt3(const char* label, int v[3], ImGuiInputTextFlags extra_flags)
{
return InputIntN(label, v, 3, extra_flags);
}
bool ImGui::InputInt4(const char* label, int v[4], ImGuiInputTextFlags extra_flags)
{
return InputIntN(label, v, 4, extra_flags);
}
static bool Items_ArrayGetter(void* data, int idx, const char** out_text)
{
const char** items = (const char**)data;
if (out_text)
*out_text = items[idx];
return true;
}
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;
}
// Combo box helper allowing to pass an array of strings.
bool ImGui::Combo(const char* label, int* current_item, const char** 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.
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;
}
// Combo box function.
bool ImGui::Combo(const char* label, int* current_item, bool (*items_getter)(void*, int, const char**), void* data, int items_count, int height_in_items)
{
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))
return false;
const float arrow_size = (g.FontSize + style.FramePadding.x * 2.0f);
const bool hovered = IsHovered(frame_bb, id);
bool popup_open = IsPopupOpen(id);
bool popup_opened_now = false;
const ImRect value_bb(frame_bb.Min, frame_bb.Max - ImVec2(arrow_size, 0.0f));
RenderFrame(frame_bb.Min, frame_bb.Max, GetColorU32(ImGuiCol_FrameBg), true, style.FrameRounding);
RenderFrame(ImVec2(frame_bb.Max.x-arrow_size, frame_bb.Min.y), frame_bb.Max, GetColorU32(popup_open || hovered ? ImGuiCol_ButtonHovered : ImGuiCol_Button), true, style.FrameRounding); // FIXME-ROUNDING
RenderCollapseTriangle(ImVec2(frame_bb.Max.x-arrow_size, frame_bb.Min.y) + style.FramePadding, true);
if (*current_item >= 0 && *current_item < items_count)
{
const char* item_text;
if (items_getter(data, *current_item, &item_text))
RenderTextClipped(frame_bb.Min + style.FramePadding, value_bb.Max, item_text, NULL, NULL);
}
if (label_size.x > 0)
RenderText(ImVec2(frame_bb.Max.x + style.ItemInnerSpacing.x, frame_bb.Min.y + style.FramePadding.y), label);
if (hovered)
{
SetHoveredID(id);
if (g.IO.MouseClicked[0])
{
SetActiveID(0);
if (IsPopupOpen(id))
{
ClosePopup(id);
}
else
{
FocusWindow(window);
OpenPopup(label);
popup_open = popup_opened_now = true;
}
}
}
bool value_changed = false;
if (IsPopupOpen(id))
{
// Size default to hold ~7 items
if (height_in_items < 0)
height_in_items = 7;
float popup_height = (label_size.y + style.ItemSpacing.y) * ImMin(items_count, height_in_items) + (style.FramePadding.y * 3);
float popup_y1 = frame_bb.Max.y;
float popup_y2 = ImClamp(popup_y1 + popup_height, popup_y1, g.IO.DisplaySize.y - style.DisplaySafeAreaPadding.y);
if ((popup_y2 - popup_y1) < ImMin(popup_height, frame_bb.Min.y - style.DisplaySafeAreaPadding.y))
{
// Position our combo ABOVE because there's more space to fit! (FIXME: Handle in Begin() or use a shared helper. We have similar code in Begin() for popup placement)
popup_y1 = ImClamp(frame_bb.Min.y - popup_height, style.DisplaySafeAreaPadding.y, frame_bb.Min.y);
popup_y2 = frame_bb.Min.y;
}
ImRect popup_rect(ImVec2(frame_bb.Min.x, popup_y1), ImVec2(frame_bb.Max.x, popup_y2));
SetNextWindowPos(popup_rect.Min);
SetNextWindowSize(popup_rect.GetSize());
PushStyleVar(ImGuiStyleVar_WindowPadding, style.FramePadding);
const ImGuiWindowFlags flags = ImGuiWindowFlags_ComboBox | ((window->Flags & ImGuiWindowFlags_ShowBorders) ? ImGuiWindowFlags_ShowBorders : 0);
if (BeginPopupEx(label, flags))
{
// Display items
Spacing();
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))
{
SetActiveID(0);
value_changed = true;
*current_item = i;
}
if (item_selected && popup_opened_now)
SetScrollHere();
PopID();
}
EndPopup();
}
PopStyleVar();
}
return value_changed;
}
// Tip: pass an empty 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.
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.ColumnsCount > 1)
PopClipRect();
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.CurrentLineTextBaseOffset;
ImRect bb(pos, pos + size);
ItemSize(bb);
// 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 - window->DC.CursorPos.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_with_spacing(pos, pos + size_draw);
if (size_arg.x == 0.0f || (flags & ImGuiSelectableFlags_DrawFillAvailWidth))
bb_with_spacing.Max.x += window_padding.x;
// Selectables are tightly packed together, we extend the box to cover spacing between selectable.
float spacing_L = (float)(int)(style.ItemSpacing.x * 0.5f);
float spacing_U = (float)(int)(style.ItemSpacing.y * 0.5f);
float spacing_R = style.ItemSpacing.x - spacing_L;
float spacing_D = style.ItemSpacing.y - spacing_U;
bb_with_spacing.Min.x -= spacing_L;
bb_with_spacing.Min.y -= spacing_U;
bb_with_spacing.Max.x += spacing_R;
bb_with_spacing.Max.y += spacing_D;
if (!ItemAdd(bb_with_spacing, &id))
{
if ((flags & ImGuiSelectableFlags_SpanAllColumns) && window->DC.ColumnsCount > 1)
PushColumnClipRect();
return false;
}
ImGuiButtonFlags button_flags = 0;
if (flags & ImGuiSelectableFlags_Menu) button_flags |= ImGuiButtonFlags_PressedOnClick;
if (flags & ImGuiSelectableFlags_MenuItem) button_flags |= ImGuiButtonFlags_PressedOnClick|ImGuiButtonFlags_PressedOnRelease;
if (flags & ImGuiSelectableFlags_Disabled) button_flags |= ImGuiButtonFlags_Disabled;
if (flags & ImGuiSelectableFlags_AllowDoubleClick) button_flags |= ImGuiButtonFlags_PressedOnClickRelease | ImGuiButtonFlags_PressedOnDoubleClick;
bool hovered, held;
bool pressed = ButtonBehavior(bb_with_spacing, id, &hovered, &held, button_flags);
if (flags & ImGuiSelectableFlags_Disabled)
selected = false;
// Render
if (hovered || selected)
{
const ImU32 col = GetColorU32((held && hovered) ? ImGuiCol_HeaderActive : hovered ? ImGuiCol_HeaderHovered : ImGuiCol_Header);
RenderFrame(bb_with_spacing.Min, bb_with_spacing.Max, col, false, 0.0f);
}
if ((flags & ImGuiSelectableFlags_SpanAllColumns) && window->DC.ColumnsCount > 1)
{
PushColumnClipRect();
bb_with_spacing.Max.x -= (GetContentRegionMax().x - max_x);
}
if (flags & ImGuiSelectableFlags_Disabled) PushStyleColor(ImGuiCol_Text, g.Style.Colors[ImGuiCol_TextDisabled]);
RenderTextClipped(bb.Min, bb_with_spacing.Max, label, NULL, &label_size);
if (flags & ImGuiSelectableFlags_Disabled) PopStyleColor();
// Automatically close popups
if (pressed && !(flags & ImGuiSelectableFlags_DontClosePopups) && (window->Flags & ImGuiWindowFlags_Popup))
CloseCurrentPopup();
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;
}
// 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 empty label "##empty"
bool ImGui::ListBoxHeader(const char* label, const ImVec2& size_arg)
{
ImGuiWindow* window = GetCurrentWindow();
if (window->SkipItems)
return false;
const ImGuiStyle& style = GetStyle();
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;
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;
}
bool ImGui::ListBoxHeader(const char* label, int items_count, int height_in_items)
{
// Size default to hold ~7 items. Fractional number of items helps seeing that we can scroll down/up without looking at scrollbar.
// However we don't add +0.40f 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);
float height_in_items_f = height_in_items < items_count ? (height_in_items + 0.40f) : (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 + GetStyle().ItemSpacing.y;
return ListBoxHeader(label, size);
}
void ImGui::ListBoxFooter()
{
ImGuiWindow* parent_window = GetParentWindow();
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** 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.
bool value_changed = false;
ImGuiListClipper clipper(items_count, GetTextLineHeightWithSpacing());
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;
}
PopID();
}
ListBoxFooter();
return value_changed;
}
bool ImGui::MenuItem(const char* label, const char* shortcut, bool selected, bool enabled)
{
ImGuiWindow* window = GetCurrentWindow();
if (window->SkipItems)
return false;
ImGuiContext& g = *GImGui;
ImVec2 pos = window->DC.CursorPos;
ImVec2 label_size = CalcTextSize(label, NULL, true);
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);
bool pressed = Selectable(label, false, ImGuiSelectableFlags_MenuItem | ImGuiSelectableFlags_DrawFillAvailWidth | (enabled ? 0 : ImGuiSelectableFlags_Disabled), 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.20f, 0.0f), GetColorU32(enabled ? ImGuiCol_Text : ImGuiCol_TextDisabled));
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;
}
bool ImGui::BeginMainMenuBar()
{
ImGuiContext& g = *GImGui;
SetNextWindowPos(ImVec2(0.0f, 0.0f));
SetNextWindowSize(ImVec2(g.IO.DisplaySize.x, g.FontBaseSize + g.Style.FramePadding.y * 2.0f));
PushStyleVar(ImGuiStyleVar_WindowRounding, 0.0f);
PushStyleVar(ImGuiStyleVar_WindowMinSize, ImVec2(0,0));
if (!Begin("##MainMenuBar", NULL, ImGuiWindowFlags_NoTitleBar|ImGuiWindowFlags_NoResize|ImGuiWindowFlags_NoMove|ImGuiWindowFlags_NoScrollbar|ImGuiWindowFlags_NoSavedSettings|ImGuiWindowFlags_MenuBar)
|| !BeginMenuBar())
{
End();
PopStyleVar(2);
return false;
}
g.CurrentWindow->DC.MenuBarOffsetX += g.Style.DisplaySafeAreaPadding.x;
return true;
}
void ImGui::EndMainMenuBar()
{
EndMenuBar();
End();
PopStyleVar(2);
}
bool ImGui::BeginMenuBar()
{
ImGuiWindow* window = GetCurrentWindow();
if (window->SkipItems)
return false;
if (!(window->Flags & ImGuiWindowFlags_MenuBar))
return false;
IM_ASSERT(!window->DC.MenuBarAppending);
BeginGroup(); // Save position
PushID("##menubar");
ImRect rect = window->MenuBarRect();
PushClipRect(ImVec2(ImFloor(rect.Min.x+0.5f), ImFloor(rect.Min.y + window->BorderSize + 0.5f)), ImVec2(ImFloor(rect.Max.x+0.5f), ImFloor(rect.Max.y+0.5f)), false);
window->DC.CursorPos = ImVec2(rect.Min.x + window->DC.MenuBarOffsetX, rect.Min.y);// + g.Style.FramePadding.y);
window->DC.LayoutType = ImGuiLayoutType_Horizontal;
window->DC.MenuBarAppending = true;
AlignFirstTextHeightToWidgets();
return true;
}
void ImGui::EndMenuBar()
{
ImGuiWindow* window = GetCurrentWindow();
if (window->SkipItems)
return;
IM_ASSERT(window->Flags & ImGuiWindowFlags_MenuBar);
IM_ASSERT(window->DC.MenuBarAppending);
PopClipRect();
PopID();
window->DC.MenuBarOffsetX = window->DC.CursorPos.x - window->MenuBarRect().Min.x;
window->DC.GroupStack.back().AdvanceCursor = false;
EndGroup();
window->DC.LayoutType = ImGuiLayoutType_Vertical;
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);
ImGuiWindow* backed_focused_window = g.FocusedWindow;
bool pressed;
bool menu_is_open = IsPopupOpen(id);
bool menuset_is_open = !(window->Flags & ImGuiWindowFlags_Popup) && (g.OpenPopupStack.Size > g.CurrentPopupStack.Size && g.OpenPopupStack[g.CurrentPopupStack.Size].ParentMenuSet == window->GetID("##menus"));
if (menuset_is_open)
g.FocusedWindow = window;
ImVec2 popup_pos, pos = window->DC.CursorPos;
if (window->DC.LayoutType == ImGuiLayoutType_Horizontal)
{
popup_pos = ImVec2(pos.x - window->WindowPadding.x, pos.y - style.FramePadding.y + window->MenuBarHeight());
window->DC.CursorPos.x += (float)(int)(style.ItemSpacing.x * 0.5f);
PushStyleVar(ImGuiStyleVar_ItemSpacing, style.ItemSpacing * 2.0f);
float w = label_size.x;
pressed = Selectable(label, menu_is_open, ImGuiSelectableFlags_Menu | ImGuiSelectableFlags_DontClosePopups | (!enabled ? ImGuiSelectableFlags_Disabled : 0), ImVec2(w, 0.0f));
PopStyleVar();
SameLine();
window->DC.CursorPos.x += (float)(int)(style.ItemSpacing.x * 0.5f);
}
else
{
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_Menu | ImGuiSelectableFlags_DontClosePopups | ImGuiSelectableFlags_DrawFillAvailWidth | (!enabled ? ImGuiSelectableFlags_Disabled : 0), ImVec2(w, 0.0f));
if (!enabled) PushStyleColor(ImGuiCol_Text, g.Style.Colors[ImGuiCol_TextDisabled]);
RenderCollapseTriangle(pos + ImVec2(window->MenuColumns.Pos[2] + extra_w + g.FontSize * 0.20f, 0.0f), false);
if (!enabled) PopStyleColor();
}
bool hovered = enabled && IsHovered(window->DC.LastItemRect, id);
if (menuset_is_open)
g.FocusedWindow = backed_focused_window;
bool want_open = false, want_close = false;
if (window->Flags & (ImGuiWindowFlags_Popup|ImGuiWindowFlags_ChildMenu))
{
// Implement http://bjk5.com/post/44698559168/breaking-down-amazons-mega-dropdown to avoid using timers, so menus feels more reactive.
bool moving_within_opened_triangle = false;
if (g.HoveredWindow == window && g.OpenPopupStack.Size > g.CurrentPopupStack.Size && g.OpenPopupStack[g.CurrentPopupStack.Size].ParentWindow == window)
{
if (ImGuiWindow* next_window = g.OpenPopupStack[g.CurrentPopupStack.Size].Window)
{
ImRect next_window_rect = next_window->Rect();
ImVec2 ta = g.IO.MousePos - g.IO.MouseDelta;
ImVec2 tb = (window->Pos.x < next_window->Pos.x) ? next_window_rect.GetTL() : next_window_rect.GetTR();
ImVec2 tc = (window->Pos.x < next_window->Pos.x) ? next_window_rect.GetBL() : next_window_rect.GetBR();
float extra = ImClamp(fabsf(ta.x - tb.x) * 0.30f, 5.0f, 30.0f); // add a bit of extra slack.
ta.x += (window->Pos.x < next_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_within_opened_triangle = ImIsPointInTriangle(g.IO.MousePos, ta, tb, tc);
//window->DrawList->PushClipRectFullScreen(); window->DrawList->AddTriangleFilled(ta, tb, tc, moving_within_opened_triangle ? 0x80008000 : 0x80000080); window->DrawList->PopClipRect(); // Debug
}
}
want_close = (menu_is_open && !hovered && g.HoveredWindow == window && g.HoveredIdPreviousFrame != 0 && g.HoveredIdPreviousFrame != id && !moving_within_opened_triangle);
want_open = (!menu_is_open && hovered && !moving_within_opened_triangle) || (!menu_is_open && hovered && pressed);
}
else if (menu_is_open && pressed && menuset_is_open) // menu-bar: click open menu to close
{
want_close = true;
want_open = menu_is_open = false;
}
else if (pressed || (hovered && menuset_is_open && !menu_is_open)) // menu-bar: first click to open, then hover to open others
want_open = true;
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(GImGui->CurrentPopupStack.Size);
if (!menu_is_open && want_open && g.OpenPopupStack.Size > g.CurrentPopupStack.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)
{
SetNextWindowPos(popup_pos, ImGuiSetCond_Always);
ImGuiWindowFlags flags = ImGuiWindowFlags_ShowBorders | ((window->Flags & (ImGuiWindowFlags_Popup|ImGuiWindowFlags_ChildMenu)) ? ImGuiWindowFlags_ChildMenu|ImGuiWindowFlags_ChildWindow : ImGuiWindowFlags_ChildMenu);
menu_is_open = BeginPopupEx(label, 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()
{
EndPopup();
}
// 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.
bool ImGui::ColorButton(const ImVec4& col, bool small_height, bool outline_border)
{
ImGuiWindow* window = GetCurrentWindow();
if (window->SkipItems)
return false;
ImGuiContext& g = *GImGui;
const ImGuiStyle& style = g.Style;
const ImGuiID id = window->GetID("#colorbutton");
const float square_size = g.FontSize;
const ImRect bb(window->DC.CursorPos, window->DC.CursorPos + ImVec2(square_size + style.FramePadding.y*2, square_size + (small_height ? 0 : style.FramePadding.y*2)));
ItemSize(bb, small_height ? 0.0f : style.FramePadding.y);
if (!ItemAdd(bb, &id))
return false;
bool hovered, held;
bool pressed = ButtonBehavior(bb, id, &hovered, &held);
RenderFrame(bb.Min, bb.Max, GetColorU32(col), outline_border, style.FrameRounding);
if (hovered)
SetTooltip("Color:\n(%.2f,%.2f,%.2f,%.2f)\n#%02X%02X%02X%02X", col.x, col.y, col.z, col.w, IM_F32_TO_INT8_SAT(col.x), IM_F32_TO_INT8_SAT(col.y), IM_F32_TO_INT8_SAT(col.z), IM_F32_TO_INT8_SAT(col.z));
return pressed;
}
bool ImGui::ColorEdit3(const char* label, float col[3])
{
float col4[4];
col4[0] = col[0];
col4[1] = col[1];
col4[2] = col[2];
col4[3] = 1.0f;
const bool value_changed = ColorEdit4(label, col4, false);
col[0] = col4[0];
col[1] = col4[1];
col[2] = col4[2];
return value_changed;
}
// Edit colors components (each component in 0.0f..1.0f range
// Use CTRL-Click to input value and TAB to go to next item.
bool ImGui::ColorEdit4(const char* label, float col[4], bool alpha)
{
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_full = CalcItemWidth();
const float square_sz = (g.FontSize + style.FramePadding.y * 2.0f);
ImGuiColorEditMode edit_mode = window->DC.ColorEditMode;
if (edit_mode == ImGuiColorEditMode_UserSelect || edit_mode == ImGuiColorEditMode_UserSelectShowButton)
edit_mode = g.ColorEditModeStorage.GetInt(id, 0) % 3;
float f[4] = { col[0], col[1], col[2], col[3] };
if (edit_mode == ImGuiColorEditMode_HSV)
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]) };
int components = alpha ? 4 : 3;
bool value_changed = false;
BeginGroup();
PushID(label);
const bool hsv = (edit_mode == 1);
switch (edit_mode)
{
case ImGuiColorEditMode_RGB:
case ImGuiColorEditMode_HSV:
{
// RGB/HSV 0..255 Sliders
const float w_items_all = w_full - (square_sz + style.ItemInnerSpacing.x);
const float w_item_one = ImMax(1.0f, (float)(int)((w_items_all - (style.ItemInnerSpacing.x) * (components-1)) / (float)components));
const float w_item_last = ImMax(1.0f, (float)(int)(w_items_all - (w_item_one + style.ItemInnerSpacing.x) * (components-1)));
const bool hide_prefix = (w_item_one <= CalcTextSize("M:999").x);
const char* ids[4] = { "##X", "##Y", "##Z", "##W" };
const char* fmt_table[3][4] =
{
{ "%3.0f", "%3.0f", "%3.0f", "%3.0f" },
{ "R:%3.0f", "G:%3.0f", "B:%3.0f", "A:%3.0f" },
{ "H:%3.0f", "S:%3.0f", "V:%3.0f", "A:%3.0f" }
};
const char** fmt = hide_prefix ? fmt_table[0] : hsv ? fmt_table[2] : fmt_table[1];
PushItemWidth(w_item_one);
for (int n = 0; n < components; n++)
{
if (n > 0)
SameLine(0, style.ItemInnerSpacing.x);
if (n + 1 == components)
PushItemWidth(w_item_last);
value_changed |= DragInt(ids[n], &i[n], 1.0f, 0, 255, fmt[n]);
}
PopItemWidth();
PopItemWidth();
}
break;
case ImGuiColorEditMode_HEX:
{
// RGB Hexadecimal Input
const float w_slider_all = w_full - square_sz;
char buf[64];
if (alpha)
ImFormatString(buf, IM_ARRAYSIZE(buf), "#%02X%02X%02X%02X", i[0], i[1], i[2], i[3]);
else
ImFormatString(buf, IM_ARRAYSIZE(buf), "#%02X%02X%02X", i[0], i[1], i[2]);
PushItemWidth(w_slider_all - style.ItemInnerSpacing.x);
if (InputText("##Text", buf, IM_ARRAYSIZE(buf), ImGuiInputTextFlags_CharsHexadecimal | ImGuiInputTextFlags_CharsUppercase))
{
value_changed |= true;
char* p = buf;
while (*p == '#' || ImCharIsSpace(*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]);
}
PopItemWidth();
}
break;
}
SameLine(0, style.ItemInnerSpacing.x);
const ImVec4 col_display(col[0], col[1], col[2], 1.0f);
if (ColorButton(col_display))
g.ColorEditModeStorage.SetInt(id, (edit_mode + 1) % 3); // Don't set local copy of 'edit_mode' right away!
// Recreate our own tooltip over's ColorButton() one because we want to display correct alpha here
if (IsItemHovered())
SetTooltip("Color:\n(%.2f,%.2f,%.2f,%.2f)\n#%02X%02X%02X%02X", col[0], col[1], col[2], col[3], IM_F32_TO_INT8_SAT(col[0]), IM_F32_TO_INT8_SAT(col[1]), IM_F32_TO_INT8_SAT(col[2]), IM_F32_TO_INT8_SAT(col[3]));
if (window->DC.ColorEditMode == ImGuiColorEditMode_UserSelectShowButton)
{
SameLine(0, style.ItemInnerSpacing.x);
const char* button_titles[3] = { "RGB", "HSV", "HEX" };
if (ButtonEx(button_titles[edit_mode], ImVec2(0,0), ImGuiButtonFlags_DontClosePopups))
g.ColorEditModeStorage.SetInt(id, (edit_mode + 1) % 3); // Don't set local copy of 'edit_mode' right away!
}
const char* label_display_end = FindRenderedTextEnd(label);
if (label != label_display_end)
{
SameLine(0, (window->DC.ColorEditMode == ImGuiColorEditMode_UserSelectShowButton) ? -1.0f : style.ItemInnerSpacing.x);
TextUnformatted(label, label_display_end);
}
// Convert back
for (int n = 0; n < 4; n++)
f[n] = i[n] / 255.0f;
if (edit_mode == 1)
ColorConvertHSVtoRGB(f[0], f[1], f[2], f[0], f[1], f[2]);
if (value_changed)
{
col[0] = f[0];
col[1] = f[1];
col[2] = f[2];
if (alpha)
col[3] = f[3];
}
PopID();
EndGroup();
return value_changed;
}
void ImGui::ColorEditMode(ImGuiColorEditMode mode)
{
ImGuiWindow* window = GetCurrentWindow();
window->DC.ColorEditMode = mode;
}
// Horizontal separating line.
void ImGui::Separator()
{
ImGuiWindow* window = GetCurrentWindow();
if (window->SkipItems)
return;
if (window->DC.ColumnsCount > 1)
PopClipRect();
float x1 = window->Pos.x;
float x2 = window->Pos.x + window->Size.x;
if (!window->DC.GroupStack.empty())
x1 += window->DC.IndentX;
const ImRect bb(ImVec2(x1, window->DC.CursorPos.y), ImVec2(x2, window->DC.CursorPos.y));
ItemSize(ImVec2(0.0f, 0.0f)); // NB: we don't provide our width so that it doesn't get feed back into AutoFit // FIXME: Height should be 1.0f not 0.0f ?
if (!ItemAdd(bb, NULL))
{
if (window->DC.ColumnsCount > 1)
PushColumnClipRect();
return;
}
window->DrawList->AddLine(bb.Min, bb.Max, GetColorU32(ImGuiCol_Border));
ImGuiContext& g = *GImGui;
if (g.LogEnabled)
LogText(IM_NEWLINE "--------------------------------");
if (window->DC.ColumnsCount > 1)
{
PushColumnClipRect();
window->DC.ColumnsCellMinY = window->DC.CursorPos.y;
}
}
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(bb);
ItemAdd(bb, NULL);
}
bool ImGui::IsRectVisible(const ImVec2& size)
{
ImGuiWindow* window = GetCurrentWindowRead();
return window->ClipRect.Overlaps(ImRect(window->DC.CursorPos, window->DC.CursorPos + size));
}
// 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()
{
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.BackupIndentX = window->DC.IndentX;
group_data.BackupCurrentLineHeight = window->DC.CurrentLineHeight;
group_data.BackupCurrentLineTextBaseOffset = window->DC.CurrentLineTextBaseOffset;
group_data.BackupLogLinePosY = window->DC.LogLinePosY;
group_data.AdvanceCursor = true;
window->DC.GroupOffsetX = window->DC.CursorPos.x - window->Pos.x - window->DC.ColumnsOffsetX;
window->DC.IndentX = window->DC.GroupOffsetX;
window->DC.CursorMaxPos = window->DC.CursorPos;
window->DC.CurrentLineHeight = 0.0f;
window->DC.LogLinePosY = window->DC.CursorPos.y - 9999.0f;
}
void ImGui::EndGroup()
{
ImGuiWindow* window = GetCurrentWindow();
ImGuiStyle& style = GetStyle();
IM_ASSERT(!window->DC.GroupStack.empty()); // Mismatched BeginGroup()/EndGroup() calls
ImGuiGroupData& group_data = window->DC.GroupStack.back();
ImRect group_bb(group_data.BackupCursorPos, window->DC.CursorMaxPos);
group_bb.Max.y -= style.ItemSpacing.y; // Cancel out last vertical spacing because we are adding one ourselves.
group_bb.Max = ImMax(group_bb.Min, group_bb.Max);
window->DC.CursorPos = group_data.BackupCursorPos;
window->DC.CursorMaxPos = ImMax(group_data.BackupCursorMaxPos, window->DC.CursorMaxPos);
window->DC.CurrentLineHeight = group_data.BackupCurrentLineHeight;
window->DC.CurrentLineTextBaseOffset = group_data.BackupCurrentLineTextBaseOffset;
window->DC.IndentX = group_data.BackupIndentX;
window->DC.GroupOffsetX = window->DC.IndentX;
window->DC.LogLinePosY = window->DC.CursorPos.y - 9999.0f;
if (group_data.AdvanceCursor)
{
window->DC.CurrentLineTextBaseOffset = ImMax(window->DC.PrevLineTextBaseOffset, group_data.BackupCurrentLineTextBaseOffset); // 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(), group_data.BackupCurrentLineTextBaseOffset);
ItemAdd(group_bb, NULL);
}
window->DC.GroupStack.pop_back();
//window->DrawList->AddRect(group_bb.Min, group_bb.Max, 0xFFFF00FF); // Debug
}
// Gets back to previous line and continue with horizontal layout
// pos_x == 0 : follow right after previous item
// pos_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 pos_x, float spacing_w)
{
ImGuiWindow* window = GetCurrentWindow();
if (window->SkipItems)
return;
ImGuiContext& g = *GImGui;
if (pos_x != 0.0f)
{
if (spacing_w < 0.0f) spacing_w = 0.0f;
window->DC.CursorPos.x = window->Pos.x - window->Scroll.x + pos_x + spacing_w + window->DC.GroupOffsetX + window->DC.ColumnsOffsetX;
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.CurrentLineHeight = window->DC.PrevLineHeight;
window->DC.CurrentLineTextBaseOffset = window->DC.PrevLineTextBaseOffset;
}
void ImGui::NewLine()
{
ImGuiWindow* window = GetCurrentWindow();
if (window->SkipItems)
return;
if (window->DC.CurrentLineHeight > 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, GImGui->FontSize));
}
void ImGui::NextColumn()
{
ImGuiWindow* window = GetCurrentWindow();
if (window->SkipItems || window->DC.ColumnsCount <= 1)
return;
ImGuiContext& g = *GImGui;
PopItemWidth();
PopClipRect();
window->DC.ColumnsCellMaxY = ImMax(window->DC.ColumnsCellMaxY, window->DC.CursorPos.y);
if (++window->DC.ColumnsCurrent < window->DC.ColumnsCount)
{
// Columns 1+ cancel out IndentX
window->DC.ColumnsOffsetX = GetColumnOffset(window->DC.ColumnsCurrent) - window->DC.IndentX + g.Style.ItemSpacing.x;
window->DrawList->ChannelsSetCurrent(window->DC.ColumnsCurrent);
}
else
{
window->DC.ColumnsCurrent = 0;
window->DC.ColumnsOffsetX = 0.0f;
window->DC.ColumnsCellMinY = window->DC.ColumnsCellMaxY;
window->DrawList->ChannelsSetCurrent(0);
}
window->DC.CursorPos.x = (float)(int)(window->Pos.x + window->DC.IndentX + window->DC.ColumnsOffsetX);
window->DC.CursorPos.y = window->DC.ColumnsCellMinY;
window->DC.CurrentLineHeight = 0.0f;
window->DC.CurrentLineTextBaseOffset = 0.0f;
PushColumnClipRect();
PushItemWidth(GetColumnWidth() * 0.65f); // FIXME: Move on columns setup
}
int ImGui::GetColumnIndex()
{
ImGuiWindow* window = GetCurrentWindowRead();
return window->DC.ColumnsCurrent;
}
int ImGui::GetColumnsCount()
{
ImGuiWindow* window = GetCurrentWindowRead();
return window->DC.ColumnsCount;
}
static float GetDraggedColumnOffset(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 = ImGui::GetCurrentWindowRead();
IM_ASSERT(column_index > 0); // We cannot drag column 0. If you get this assert you may have a conflict between the ID of your columns and another widgets.
IM_ASSERT(g.ActiveId == window->DC.ColumnsSetId + ImGuiID(column_index));
float x = g.IO.MousePos.x - g.ActiveIdClickOffset.x - window->Pos.x;
x = ImClamp(x, ImGui::GetColumnOffset(column_index-1)+g.Style.ColumnsMinSpacing, ImGui::GetColumnOffset(column_index+1)-g.Style.ColumnsMinSpacing);
return (float)(int)x;
}
float ImGui::GetColumnOffset(int column_index)
{
ImGuiContext& g = *GImGui;
ImGuiWindow* window = GetCurrentWindowRead();
if (column_index < 0)
column_index = window->DC.ColumnsCurrent;
if (g.ActiveId)
{
const ImGuiID column_id = window->DC.ColumnsSetId + ImGuiID(column_index);
if (g.ActiveId == column_id)
return GetDraggedColumnOffset(column_index);
}
IM_ASSERT(column_index < window->DC.ColumnsData.Size);
const float t = window->DC.ColumnsData[column_index].OffsetNorm;
const float x_offset = window->DC.ColumnsMinX + t * (window->DC.ColumnsMaxX - window->DC.ColumnsMinX);
return (float)(int)x_offset;
}
void ImGui::SetColumnOffset(int column_index, float offset)
{
ImGuiWindow* window = GetCurrentWindow();
if (column_index < 0)
column_index = window->DC.ColumnsCurrent;
IM_ASSERT(column_index < window->DC.ColumnsData.Size);
const float t = (offset - window->DC.ColumnsMinX) / (window->DC.ColumnsMaxX - window->DC.ColumnsMinX);
window->DC.ColumnsData[column_index].OffsetNorm = t;
const ImGuiID column_id = window->DC.ColumnsSetId + ImGuiID(column_index);
window->DC.StateStorage->SetFloat(column_id, t);
}
float ImGui::GetColumnWidth(int column_index)
{
ImGuiWindow* window = GetCurrentWindowRead();
if (column_index < 0)
column_index = window->DC.ColumnsCurrent;
float w = GetColumnOffset(column_index+1) - GetColumnOffset(column_index);
return w;
}
static void PushColumnClipRect(int column_index)
{
ImGuiWindow* window = ImGui::GetCurrentWindow();
if (column_index < 0)
column_index = window->DC.ColumnsCurrent;
float x1 = ImFloor(0.5f + window->Pos.x + ImGui::GetColumnOffset(column_index) - 1.0f);
float x2 = ImFloor(0.5f + window->Pos.x + ImGui::GetColumnOffset(column_index+1) - 1.0f);
ImGui::PushClipRect(ImVec2(x1,-FLT_MAX), ImVec2(x2,+FLT_MAX), true);
}
void ImGui::Columns(int columns_count, const char* id, bool border)
{
ImGuiContext& g = *GImGui;
ImGuiWindow* window = GetCurrentWindow();
IM_ASSERT(columns_count >= 1);
if (window->DC.ColumnsCount != 1)
{
if (window->DC.ColumnsCurrent != 0)
ItemSize(ImVec2(0,0)); // Advance to column 0
PopItemWidth();
PopClipRect();
window->DrawList->ChannelsMerge();
window->DC.ColumnsCellMaxY = ImMax(window->DC.ColumnsCellMaxY, window->DC.CursorPos.y);
window->DC.CursorPos.y = window->DC.ColumnsCellMaxY;
}
// Draw columns borders and handle resize at the time of "closing" a columns set
if (window->DC.ColumnsCount != columns_count && window->DC.ColumnsCount != 1 && window->DC.ColumnsShowBorders && !window->SkipItems)
{
const float y1 = window->DC.ColumnsStartPosY;
const float y2 = window->DC.CursorPos.y;
for (int i = 1; i < window->DC.ColumnsCount; i++)
{
float x = window->Pos.x + GetColumnOffset(i);
const ImGuiID column_id = window->DC.ColumnsSetId + ImGuiID(i);
const ImRect column_rect(ImVec2(x-4,y1),ImVec2(x+4,y2));
if (IsClippedEx(column_rect, &column_id, false))
continue;
bool hovered, held;
ButtonBehavior(column_rect, column_id, &hovered, &held);
if (hovered || held)
g.MouseCursor = ImGuiMouseCursor_ResizeEW;
// Draw before resize so our items positioning are in sync with the line being drawn
const ImU32 col = GetColorU32(held ? ImGuiCol_ColumnActive : hovered ? ImGuiCol_ColumnHovered : ImGuiCol_Column);
const float xi = (float)(int)x;
window->DrawList->AddLine(ImVec2(xi, y1+1.0f), ImVec2(xi, y2), col);
if (held)
{
if (g.ActiveIdIsJustActivated)
g.ActiveIdClickOffset.x -= 4; // Store from center of column line (we used a 8 wide rect for columns clicking)
x = GetDraggedColumnOffset(i);
SetColumnOffset(i, x);
}
}
}
// 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 + (id ? 0 : columns_count));
window->DC.ColumnsSetId = window->GetID(id ? id : "columns");
PopID();
// Set state for first column
window->DC.ColumnsCurrent = 0;
window->DC.ColumnsCount = columns_count;
window->DC.ColumnsShowBorders = border;
const float content_region_width = (window->SizeContentsExplicit.x != 0.0f) ? window->SizeContentsExplicit.x : window->Size.x;
window->DC.ColumnsMinX = window->DC.IndentX; // Lock our horizontal range
window->DC.ColumnsMaxX = content_region_width - window->Scroll.x - ((window->Flags & ImGuiWindowFlags_NoScrollbar) ? 0 : g.Style.ScrollbarSize);// - window->WindowPadding().x;
window->DC.ColumnsStartPosY = window->DC.CursorPos.y;
window->DC.ColumnsCellMinY = window->DC.ColumnsCellMaxY = window->DC.CursorPos.y;
window->DC.ColumnsOffsetX = 0.0f;
window->DC.CursorPos.x = (float)(int)(window->Pos.x + window->DC.IndentX + window->DC.ColumnsOffsetX);
if (window->DC.ColumnsCount != 1)
{
// Cache column offsets
window->DC.ColumnsData.resize(columns_count + 1);
for (int column_index = 0; column_index < columns_count + 1; column_index++)
{
const ImGuiID column_id = window->DC.ColumnsSetId + ImGuiID(column_index);
KeepAliveID(column_id);
const float default_t = column_index / (float)window->DC.ColumnsCount;
const float t = window->DC.StateStorage->GetFloat(column_id, default_t); // Cheaply store our floating point value inside the integer (could store an union into the map?)
window->DC.ColumnsData[column_index].OffsetNorm = t;
}
window->DrawList->ChannelsSplit(window->DC.ColumnsCount);
PushColumnClipRect();
PushItemWidth(GetColumnWidth() * 0.65f);
}
else
{
window->DC.ColumnsData.resize(0);
}
}
void ImGui::Indent(float indent_w)
{
ImGuiContext& g = *GImGui;
ImGuiWindow* window = GetCurrentWindow();
window->DC.IndentX += (indent_w > 0.0f) ? indent_w : g.Style.IndentSpacing;
window->DC.CursorPos.x = window->Pos.x + window->DC.IndentX + window->DC.ColumnsOffsetX;
}
void ImGui::Unindent(float indent_w)
{
ImGuiContext& g = *GImGui;
ImGuiWindow* window = GetCurrentWindow();
window->DC.IndentX -= (indent_w > 0.0f) ? indent_w : g.Style.IndentSpacing;
window->DC.CursorPos.x = window->Pos.x + window->DC.IndentX + window->DC.ColumnsOffsetX;
}
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::TreePushRawID(ImGuiID id)
{
ImGuiWindow* window = GetCurrentWindow();
Indent();
window->DC.TreeDepth++;
window->IDStack.push_back(id);
}
void ImGui::TreePop()
{
ImGuiWindow* window = GetCurrentWindow();
Unindent();
window->DC.TreeDepth--;
PopID();
}
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);
}
}
// FIXME: May want to remove those helpers?
void ImGui::ValueColor(const char* prefix, const ImVec4& v)
{
Text("%s: (%.2f,%.2f,%.2f,%.2f)", prefix, v.x, v.y, v.z, v.w);
SameLine();
ColorButton(v, true);
}
void ImGui::ValueColor(const char* prefix, ImU32 v)
{
Text("%s: %08X", prefix, v);
SameLine();
ImVec4 col;
col.x = (float)((v >> 0) & 0xFF) / 255.0f;
col.y = (float)((v >> 8) & 0xFF) / 255.0f;
col.z = (float)((v >> 16) & 0xFF) / 255.0f;
col.w = (float)((v >> 24) & 0xFF) / 255.0f;
ColorButton(col, true);
}
//-----------------------------------------------------------------------------
// PLATFORM DEPENDANT HELPERS
//-----------------------------------------------------------------------------
#if defined(_WIN32) && !defined(_WINDOWS_) && (!defined(IMGUI_DISABLE_WIN32_DEFAULT_CLIPBOARD_FUNCS) || !defined(IMGUI_DISABLE_WIN32_DEFAULT_IME_FUNCS))
#undef WIN32_LEAN_AND_MEAN
#define WIN32_LEAN_AND_MEAN
#include <windows.h>
#endif
// Win32 API clipboard implementation
#if defined(_WIN32) && !defined(IMGUI_DISABLE_WIN32_DEFAULT_CLIPBOARD_FUNCS)
#ifdef _MSC_VER
#pragma comment(lib, "user32")
#endif
static const char* GetClipboardTextFn_DefaultImpl()
{
static ImVector<char> buf_local;
buf_local.clear();
if (!OpenClipboard(NULL))
return NULL;
HANDLE wbuf_handle = GetClipboardData(CF_UNICODETEXT);
if (wbuf_handle == NULL)
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(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)
return;
ImWchar* wbuf_global = (ImWchar*)GlobalLock(wbuf_handle);
ImTextStrFromUtf8(wbuf_global, wbuf_length, text, NULL);
GlobalUnlock(wbuf_handle);
EmptyClipboard();
SetClipboardData(CF_UNICODETEXT, wbuf_handle);
CloseClipboard();
}
#else
// Local ImGui-only clipboard implementation, if user hasn't defined better clipboard handlers
static const char* GetClipboardTextFn_DefaultImpl()
{
return GImGui->PrivateClipboard;
}
// Local ImGui-only clipboard implementation, if user hasn't defined better clipboard handlers
static void SetClipboardTextFn_DefaultImpl(const char* text)
{
ImGuiContext& g = *GImGui;
if (g.PrivateClipboard)
{
ImGui::MemFree(g.PrivateClipboard);
g.PrivateClipboard = NULL;
}
const char* text_end = text + strlen(text);
g.PrivateClipboard = (char*)ImGui::MemAlloc((size_t)(text_end - text) + 1);
memcpy(g.PrivateClipboard, 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_DEFAULT_IME_FUNCS)
#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
if (HWND hwnd = (HWND)GImGui->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);
}
}
#else
static void ImeSetInputScreenPosFn_DefaultImpl(int, int) {}
#endif
//-----------------------------------------------------------------------------
// HELP
//-----------------------------------------------------------------------------
void ImGui::ShowMetricsWindow(bool* p_open)
{
if (ImGui::Begin("ImGui Metrics", p_open))
{
ImGui::Text("ImGui %s", ImGui::GetVersion());
ImGui::Text("Application average %.3f ms/frame (%.1f FPS)", 1000.0f / ImGui::GetIO().Framerate, ImGui::GetIO().Framerate);
ImGui::Text("%d vertices, %d indices (%d triangles)", ImGui::GetIO().MetricsRenderVertices, ImGui::GetIO().MetricsRenderIndices, ImGui::GetIO().MetricsRenderIndices / 3);
ImGui::Text("%d allocations", ImGui::GetIO().MetricsAllocs);
static bool show_clip_rects = true;
ImGui::Checkbox("Show clipping rectangles when hovering a ImDrawCmd", &show_clip_rects);
ImGui::Separator();
struct Funcs
{
static void NodeDrawList(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(ImColor(255,100,100), "CURRENTLY APPENDING"); // Can't display stats for active draw list! (we don't have the data double-buffered)
if (node_open) ImGui::TreePop();
return;
}
if (!node_open)
return;
ImDrawList* overlay_draw_list = &GImGui->OverlayDrawList; // Render additional visuals into the top-most draw list
overlay_draw_list->PushClipRectFullScreen();
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)
{
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;
bool pcmd_node_open = ImGui::TreeNode((void*)(pcmd - draw_list->CmdBuffer.begin()), "Draw %-4d %s vtx, tex = %p, clip_rect = (%.0f,%.0f)..(%.0f,%.0f)", pcmd->ElemCount, draw_list->IdxBuffer.Size > 0 ? "indexed" : "non-indexed", pcmd->TextureId, pcmd->ClipRect.x, pcmd->ClipRect.y, pcmd->ClipRect.z, pcmd->ClipRect.w);
if (show_clip_rects && 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(); overlay_draw_list->AddRect(clip_rect.Min, clip_rect.Max, IM_COL32(255,255,0,255));
vtxs_rect.Floor(); overlay_draw_list->AddRect(vtxs_rect.Min, vtxs_rect.Max, IM_COL32(255,0,255,255));
}
if (!pcmd_node_open)
continue;
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, vtx_i = elem_offset + clipper.DisplayStart*3; prim < clipper.DisplayEnd; prim++)
{
char buf[300], *buf_p = buf;
ImVec2 triangles_pos[3];
for (int n = 0; n < 3; n++, vtx_i++)
{
ImDrawVert& v = draw_list->VtxBuffer[idx_buffer ? idx_buffer[vtx_i] : vtx_i];
triangles_pos[n] = v.pos;
buf_p += sprintf(buf_p, "%s %04d { pos = (%8.2f,%8.2f), uv = (%.6f,%.6f), col = %08X }\n", (n == 0) ? "vtx" : " ", vtx_i, v.pos.x, v.pos.y, v.uv.x, v.uv.y, v.col);
}
ImGui::Selectable(buf, false);
if (ImGui::IsItemHovered())
overlay_draw_list->AddPolyline(triangles_pos, 3, IM_COL32(255,255,0,255), true, 1.0f, false); // Add triangle without AA, more readable for large-thin triangle
}
ImGui::TreePop();
}
overlay_draw_list->PopClipRect();
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 (!ImGui::TreeNode(window, "%s '%s', %d @ 0x%p", label, window->Name, window->Active || window->WasActive, window))
return;
NodeDrawList(window->DrawList, "DrawList");
ImGui::BulletText("Size: (%.1f,%.1f), SizeContents (%.1f,%.1f)", window->Size.x, window->Size.y, window->SizeContents.x, window->SizeContents.y);
ImGui::BulletText("Scroll: (%.2f,%.2f)", window->Scroll.x, window->Scroll.y);
if (window->RootWindow != window) NodeWindow(window->RootWindow, "RootWindow");
if (window->DC.ChildWindows.Size > 0) NodeWindows(window->DC.ChildWindows, "ChildWindows");
ImGui::BulletText("Storage: %d bytes", window->StateStorage.Data.Size * (int)sizeof(ImGuiStorage::Pair));
ImGui::TreePop();
}
};
ImGuiContext& g = *GImGui; // Access private state
Funcs::NodeWindows(g.Windows, "Windows");
if (ImGui::TreeNode("DrawList", "Active DrawLists (%d)", g.RenderDrawLists[0].Size))
{
for (int i = 0; i < g.RenderDrawLists[0].Size; i++)
Funcs::NodeDrawList(g.RenderDrawLists[0][i], "DrawList");
ImGui::TreePop();
}
if (ImGui::TreeNode("Popups", "Open Popups Stack (%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("Basic state"))
{
ImGui::Text("FocusedWindow: '%s'", g.FocusedWindow ? g.FocusedWindow->Name : "NULL");
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", g.HoveredId, g.HoveredIdPreviousFrame); // 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", g.ActiveId, g.ActiveIdPreviousFrame);
ImGui::TreePop();
}
}
ImGui::End();
}
//-----------------------------------------------------------------------------
// 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
//-----------------------------------------------------------------------------
| [
"[email protected]"
] | |
75fb41f0fa52815c8726e5549d28dde586e29e18 | 42c64672a2a640646a2b66197da2e5134486a1bc | /80/pr5/pr5Doc.h | 47ab2d0ff1ee6bd8f5b8fbea4ef7086f12ef809a | [] | no_license | 15831944/C_plus_plus | 898de0abd44898060460c9adcabade9f4849fece | 50a3d1e72718c6d577a49180ce29e8c81108cdfd | refs/heads/master | 2022-10-01T15:30:13.837718 | 2020-06-08T20:08:09 | 2020-06-08T20:08:09 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,464 | h | // pr5Doc.h : interface of the CPr5Doc class
//
/////////////////////////////////////////////////////////////////////////////
#if !defined(AFX_PR5DOC_H__0B5293BE_C950_11D3_A3DB_000001260696__INCLUDED_)
#define AFX_PR5DOC_H__0B5293BE_C950_11D3_A3DB_000001260696__INCLUDED_
#if _MSC_VER > 1000
#pragma once
#endif // _MSC_VER > 1000
class CPr5Doc : public CDocument
{
protected: // create from serialization only
CPr5Doc();
DECLARE_DYNCREATE(CPr5Doc)
// Attributes
public:
// Operations
public:
// Overrides
// ClassWizard generated virtual function overrides
//{{AFX_VIRTUAL(CPr5Doc)
public:
virtual BOOL OnNewDocument();
virtual void Serialize(CArchive& ar);
//}}AFX_VIRTUAL
// Implementation
public:
CString stringData;
virtual ~CPr5Doc();
#ifdef _DEBUG
virtual void AssertValid() const;
virtual void Dump(CDumpContext& dc) const;
#endif
protected:
// Generated message map functions
protected:
//{{AFX_MSG(CPr5Doc)
// NOTE - the ClassWizard will add and remove member functions here.
// DO NOT EDIT what you see in these blocks of generated code !
//}}AFX_MSG
DECLARE_MESSAGE_MAP()
};
/////////////////////////////////////////////////////////////////////////////
//{{AFX_INSERT_LOCATION}}
// Microsoft Visual C++ will insert additional declarations immediately before the previous line.
#endif // !defined(AFX_PR5DOC_H__0B5293BE_C950_11D3_A3DB_000001260696__INCLUDED_)
| [
"[email protected]"
] | |
80cd27a4e94ca8636e112c5ad8769a8e945e85ff | 55d1010bab89d723390e26e7113e1da30e745e66 | /main.cpp | fd99863e7a4cea2372cc1d3c5374225fc00fec28 | [] | no_license | tomasblazek/IMS | ec0deafd16534ec72c922690fe70a171d0d60ffc | b538c403dd01bbb8adbd54030c63291541b49b42 | refs/heads/master | 2021-08-23T16:31:02.345668 | 2017-12-05T16:43:54 | 2017-12-05T16:43:54 | 112,334,498 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 8,561 | cpp | #include <iostream>
#include <simlib.h>
#include <getopt.h>
//Macros
#define seconds(x) (x)
#define minutes(x) (seconds((x)*60))
#define hours(x) (minutes((x)*60))
#define days(x) (hours((x)*24))
using namespace std;
//Default values of simulation
#define COUNT_OF_STARTS 68
//Season 1425/per day | Outseason 351/per day
#define GENERATE_PEOPLE 98
#define CAPACITY 40
#define RUNTIME days(1) // 182days
//Globals
double generatePeople = GENERATE_PEOPLE;
double countOfStarts = COUNT_OF_STARTS;
Histogram Time_of_Passager1("Čas pasažéra(Podhoří-Podbaba) stráveného na cestě",0, minutes(1), 25);
Histogram Time_of_Passager2("Čas pasažéra(Podbaba-Podhoří) stráveného na cestě",0, minutes(1), 25);
Queue queue1("Fronta v Podhoří");
Queue queue2("Fronta v Podbabě");
Queue queueLoaded("Pasažeři nastoupení v lodi");
//Stores Boat_place, Pier
Store Boat_place("Boat_place capacity", CAPACITY);
Facility Pier1("Molo-Podhori");
Facility Pier2("Molo-Podbaba");
bool Boat_time;
//Processes Boat_place, Passager1, Time
class DayTime : public Process{
void Behavior() {
Seize(Pier1);
Seize(Pier2);
Boat_time = false;
double timeBefore;
double waitingTime1 = 0;
double waitingTime2 = 0;
double uniform = 0;
Priority = 1;
while(true){
Boat_time = true;
for(int i = 0; i < countOfStarts; i++){
Release(Pier1);
if(!queueLoaded.Empty()){
(queueLoaded.GetFirst())->Activate();
}else{
if(!queue1.Empty()){
queue1.GetFirst()->Activate();
}
}
Wait(hours(17/countOfStarts)-waitingTime1-waitingTime2-uniform);
timeBefore = Time;
Seize(Pier1);
waitingTime1 = Time - timeBefore;
uniform = Uniform(minutes(1),minutes(2));
Wait(uniform);
Release(Pier2);
if(!queueLoaded.Empty()){
(queueLoaded.GetFirst())->Activate();
}else{
if(!queue2.Empty()){
queue2.GetFirst()->Activate();
}
}
Wait(minutes(4)-waitingTime1-uniform);
timeBefore = Time;
Seize(Pier2);
waitingTime2 = Time - timeBefore;
uniform = Uniform(minutes(1),minutes(2));
Wait(uniform);
waitingTime2 = minutes(4)+waitingTime2;
waitingTime1 = 0;
}
Release(Pier1);
Boat_time = false;
if(!queueLoaded.Empty()){
(queueLoaded.GetFirst())->Activate();
}
//When work day is gone ...People leaves queue
while(!queue1.Empty()){
queue1.GetFirst()->Activate();
}
while(!queue2.Empty()){
queue2.GetFirst()->Activate();
}
Wait(hours(7)-waitingTime2-uniform); //problem s nevystupovaním
Seize(Pier1);
waitingTime2 = 0;
waitingTime1 = 0;
uniform = 0;
}
}
};
class Passager1 : public Process{
void Behavior() {
double startOfPassager = Time;
if(!queue1.Empty()){
queue1.Insert(this);
Passivate();
}
repeatBoard:
if(Boat_time) {
if (!Boat_place.Full() && !Pier1.Busy()) {
Seize(Pier1);
} else {
queue1.Insert(this);
Passivate();
goto repeatBoard;
}
double uniform = Uniform(seconds(1), seconds(3));//1-3s
Wait(uniform);
Enter(Boat_place);
Release(Pier1);
if (!queue1.Empty()) {
(queue1.GetFirst())->Activate();
}
queueLoaded.Insert(this);
Passivate();
Seize(Pier2);
uniform = Uniform(seconds(1), seconds(3));//1-3s
Wait(uniform);
Leave(Boat_place);
Release(Pier2);
if (!queueLoaded.Empty()) {
(queueLoaded.GetFirst())->Activate();
} else {
if (!queue2.Empty() && Boat_time) {
queue2.GetFirst()->Activate();
}
}
}
Time_of_Passager1(Time - startOfPassager);
}
};
class Passager2 : public Process{
void Behavior() {
double startOfPassager = Time;
if(!queue2.Empty()){
queue2.Insert(this);
Passivate();
}
repeatBoard:
if(Boat_time){
if (!Boat_place.Full() && !Pier2.Busy()) {
Seize(Pier2);
} else {
queue2.Insert(this);
Passivate();
goto repeatBoard;
}
double uniform = Uniform(seconds(1), seconds(3)); //1-3s
Wait(uniform);
Enter(Boat_place);
Release(Pier2);
if (!queue2.Empty()) {
(queue2.GetFirst())->Activate();
}
queueLoaded.Insert(this);
Passivate();
Seize(Pier1);
uniform = Uniform(seconds(1), seconds(3));//1-3s
Wait(uniform);
Leave(Boat_place);
Release(Pier1);
if (!queueLoaded.Empty()) {
(queueLoaded.GetFirst())->Activate();
} else {
if (!queue1.Empty() && Boat_time) {
queue1.GetFirst()->Activate();
}
}
}
Time_of_Passager2(Time - startOfPassager);
}
};
class GeneratorOfPassager1 : public Event {
void Behavior(){
if(Boat_time)
(new Passager1)->Activate();
Activate(Time + Exponential(generatePeople));
}
};
class GeneratorOfPassager2 : public Event {
void Behavior(){
if(Boat_time)
(new Passager2)->Activate();
Activate(Time + Exponential(generatePeople));
}
};
void printHelp(){
printf("Simulační model - Přívoz Podbaba-Podhoří\n");
printf("Použití: ./ims [-r doba_běhu] [-c kapacita] [-s počet_jízd] [-p střední_hodnota] [-f výstupní_soubor] [-h]\n");
printf("-h Otevře tuto nápovědu a nic jiného\n");
printf("-r Doba běhu simulace v sekundách\n");
printf("-c Kapacita lodi\n");
printf("-s Počet jízd za jeden pracovní den\n");
printf("-p Generování pasažérů v celém systému (pro obě mola dohromady) a zadává se střední hodnota exponenciálního rozdělení\n");
printf("-f Jméno výstupního souboru (výchozí hodnota 'output.out')\n");
exit(EXIT_SUCCESS);
}
int main(int argc, char *argv[]) {
unsigned long capacity = CAPACITY;
unsigned long runtime = RUNTIME;
//global variable
generatePeople = GENERATE_PEOPLE;
countOfStarts = COUNT_OF_STARTS;
string outputFile = "output.out";
//TODO parse aguments
int c;
while ((c = getopt (argc, argv, "ht:c:s:p:f:")) != -1 ) {
switch (c) {
case 'h':
printHelp();
break;
case 't':
runtime = days(strtoul(optarg, NULL, 0));
break;
case 'c':
capacity = strtoul(optarg, NULL, 0);
break;
case 's':
countOfStarts = strtoul(optarg, NULL, 0);
break;
case 'p':
generatePeople = strtoul(optarg, NULL, 0);
break;
case 'f':
outputFile = optarg;
break;
case '?':
fprintf(stderr,"Unknown argument: %s of %c\n", optarg, c);
exit(EXIT_FAILURE);
default:
break;
}
}
Boat_place.SetCapacity(capacity);
//SET PARAMETERS
SetOutput(outputFile.c_str());
//INITIALIZATION OF SIMULATION
Init(0, runtime);
//GENERATORS
(new DayTime)->Activate();
(new GeneratorOfPassager1)->Activate();
(new GeneratorOfPassager2)->Activate();
//START SIMULATION
Run();
//OUTPUTS
queue1.Output();
queue2.Output();
queueLoaded.Output();
Boat_place.Output();
Time_of_Passager1.Output();
Time_of_Passager2.Output();
return 0;
} | [
"[email protected]"
] | |
f5ab31f17f1b2433edf1c8ed181b4f4829923bea | 8ae71678631a89179c22bbee617e021f2b5c13b5 | /cpp/a058.cpp | 103a90da4b78533da2c4987e7177be03dcdf09fc | [] | no_license | hectortu/exercise | b32ecae19a8589889137f519c1878bcc6ec537f9 | 320eb52ed2ebd782af26d4e573bed6e83c58ba0f | refs/heads/master | 2022-01-21T17:07:21.932060 | 2021-10-18T03:19:59 | 2021-10-18T03:19:59 | 74,837,469 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 360 | cpp | #include <cstdio>
using namespace std;
int main(){
int t,a,b,i,sum,test,count;
while(scanf("%d",&t)!=EOF){
count=0;
while(t--){
scanf("%d%d",&a,&b);
sum=0;
i=0;
test=0;
while(test<=b){
if(test>=a)
sum+=test;
++i;
test=i*i;
}
count++;
printf("Case %d: %d\n",count,sum);
}
}
return 0;
}
| [
"[email protected]"
] | |
e6217cd81a3e1f4b2bac0031a9b69aa4437f65b0 | 9e83e357538639cfe29356901640072fce261cad | /_DirectX/DirectX12FirstTest/DirectX12FirstTest/DirectX12FirstTestMain.h | d0d84fc201c44afce0e387c7500e4d74729bdd3f | [] | no_license | ConnerTenn/Legacy_CPP | 615fa4ca4b5a5824e27c8a213e559e0678f7b690 | fd150a8f81d2606622dfa9ac199f20009962f5da | refs/heads/master | 2021-05-09T21:46:23.880623 | 2018-05-01T20:29:33 | 2018-05-01T20:29:33 | 118,735,762 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 699 | h | #pragma once
#include "Common\StepTimer.h"
#include "Common\DeviceResources.h"
#include "Content\Sample3DSceneRenderer.h"
// Renders Direct3D content on the screen.
namespace DirectX12FirstTest
{
class DirectX12FirstTestMain
{
public:
DirectX12FirstTestMain();
void CreateRenderers(const std::shared_ptr<DX::DeviceResources>& deviceResources);
void Update();
bool Render();
void OnWindowSizeChanged();
void OnSuspending();
void OnResuming();
void OnDeviceRemoved();
private:
// TODO: Replace with your own content renderers.
std::unique_ptr<Sample3DSceneRenderer> m_sceneRenderer;
// Rendering loop timer.
DX::StepTimer m_timer;
};
} | [
"[email protected]"
] | |
fd036e4b359d604a0a1d784779d3382eee670086 | ce7876095646b3da23811753cd1850f7dde2d673 | /highland2/highlandUtils/v2r19/src/ND280GeomId.hxx | cee3e2c871cb01a1a88fb8fd851a14d50dd72847 | [] | no_license | Balthazar6969/T2K | 63d7bd6dc2ef9eb1d8e33311d220bf8eb8b61828 | 14709b0dbe1f9b22992efecf30c50d9b8f8bba5c | refs/heads/master | 2020-09-09T18:19:24.346765 | 2019-11-19T07:01:44 | 2019-11-19T07:01:44 | 221,523,255 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 18,325 | hxx | #ifndef ND280GeomId_hxx_seen
#define ND280GeomId_hxx_seen
//#include "TGeometryId.hxx"
/*
This file is an exact copy of the file in oaEvent except:
- The commented include
- a TGeometryId typdef below to avoid inclusing TGeometryId.hxx
*/
namespace ND {
// The exposed type for the geometry id.
typedef int TGeometryId;
/// Define the geometry identifiers for elements in the ND280 geometry.
namespace GeomId {
/// Return the geometry id indication None.
TGeometryId Empty();
/// Get the sub-system type.
int GetSubSystem(TGeometryId id);
/// Define the P0D specific geometry identifiers.
namespace P0D {
/// Define a geometry identifier to the entire P0D detector.
TGeometryId Detector();
/// Check if the id is for the P0D.
bool IsP0D(TGeometryId id);
/// The geometry identifiers for the P0D super-P0Dules. The
/// super-P0Dules are number 0 to 3 from the upstream end of the
/// P0D.
/// * 0 -- Upstream ECal
/// * 1 -- Upstream Water Target
/// * 2 -- Central Water Target
/// * 3 -- Central ECal.
TGeometryId SuperP0Dule(int sP0Dule);
/// If this is a super-P0Dule id, return the super-P0Dule number,
/// otherwise return -1.
int GetSuperP0Dule(TGeometryId id);
/// The geometry identifiers for the P0D scintillator modules.
/// The P0Dules are number 0 to 39 from the upstream end of the
/// P0D.
TGeometryId P0Dule(int p0dule);
/// If this is a P0Dule id, return the P0Dule number, otherwise
/// return -1.
int GetP0Dule(TGeometryId id);
/// The geometry identifiers for the P0D water targets. The
/// targets are numbered from 0 to 24 from the upstream end of the
/// P0D.
TGeometryId Target(int target);
/// If this is a water target, return it's number, otherwise
/// return -1.
int GetTarget(TGeometryId id);
/// The geometry identifiers for the P0D lead radiators. The lead
/// radiators are numbered from 0 to 13 from the upstream end of
/// the P0D.
TGeometryId ECalRadiator(int radiator);
/// If this is an ECal radiator, return it's number, otherwise
/// return -1.
int GetECalRadiator(TGeometryId id);
/// The geometry identifiers for the P0D brass radiators. The
/// brass radiators are numbered from 0 to 24 from the upstream
/// end of the P0D.
TGeometryId TargetRadiator(int radiator);
/// If this is a target radiator, return it's number, otherwise
/// return -1.
int GetTargetRadiator(TGeometryId id);
/// The geometry identifiers for p0d scintillators. The P0Dules
/// are numbered from 0 to 39 with 0 as the most upstream. The
/// layer is 0 (X), or 1 (Y), and the bar is from 0 to 125 (X) or
/// 133 (Y). Bar 0 has the most negative coordinate.
TGeometryId Bar(int p0dule, int layer, int bar);
/// Get the P0Dule number for an id. If the provided geometry is
/// not for a P0D bar, then this returns -1. The P0Dule numbering
/// runs from 0 to 39.
int GetBarP0Dule(TGeometryId id);
/// Get the P0D Bar Layer number from an id. If the provided
/// geometry id is not for a P0D bar, then this returns -1. The
/// P0Dule layers are numbered 0 (x) and 1 (y).
int GetBarLayer(TGeometryId id);
/// Get the P0D Bar Number from an id. If the provided geometry
/// id is not for a P0D bar, then this returns -1. The Bars are
/// numbered between 0 and 126 (or 134). Bar Number zero hs the
/// tip of the triangle facing upstream. You can use
/// \code
/// bool pointsDownstream = (GetBarNumber(id)%2);
/// \endcode
/// to determine which way a bar is facing.
int GetBarNumber(TGeometryId id);
};
/// Define the TPC specific identifiers.
namespace TPC {
/// Check to see if the id is for a TPC.
bool IsTPC(TGeometryId id);
/// The geometry identifier for the TPC modules. This count
/// starts from zero and runs from upstream to downstream.
TGeometryId Module(int mod);
/// Get the TPC module number (0 to 2). This returns -1 if the id
/// is invalid.
int GetModule(TGeometryId id);
/// The geometry identifier for TPC1.
TGeometryId TPC1();
/// The geometry identifier for TPC2.
TGeometryId TPC2();
/// The geometry identifier for TPC3.
TGeometryId TPC3();
/// @{ Check to see if the id is for a TPCn.
bool IsTPC1(TGeometryId id);
bool IsTPC2(TGeometryId id);
bool IsTPC3(TGeometryId id);
/// @}
/// The geometry identifier for the micromegas. The TPCs are
/// numbered 0 to 2 from upstream to downstream. The half is 0
/// for -x, and 1 for +x. The micromegas run from 0 to 15;
TGeometryId MicroMega(int tpc, int half, int mm);
/// @{ Get the micromega TPC, half, or number. This returns -1 if
/// the id is invalid.
int GetMicroMegaTPC(TGeometryId id);
int GetMicroMegaHalf(TGeometryId id);
int GetMicroMegaNumber(TGeometryId id);
/// @}
/// Check if a TGeometryId is a MicroMega
bool IsMicroMega(TGeometryId id);
/// The geometry identifier for the micromega pads. The TPCs are
/// numbered 0 to 2 from upstream to downstream. The half is 0
/// for -x, and 1 for +x. The micromegas run from 0 to 15; The
/// pad runs from 0 to 1727.
TGeometryId Pad(int tpc, int half, int mm, int pad);
/// @{ Get the pad TPC, half, micro-mega or number. This returns
/// -1 if the id is invalid.
int GetPadTPC(TGeometryId id);
int GetPadHalf(TGeometryId id);
int GetPadMicroMega(TGeometryId id);
int GetPadNumber(TGeometryId id);
/// @}
/// Check if a TGeometryId is a PAD
bool IsPad(TGeometryId id);
};
/// Define the FGD specific geometry identifiers.
namespace FGD {
/// Check if this is an FGD id.
bool IsFGD(TGeometryId id);
/// The geometry identifier for the FGD modules. This count
/// starts from zero and runs from upstream to downstream. 0 is
/// the upstream FGD (FGD1). 1 is the downstream FGD (FGD2 -- The
/// water target FGD).
TGeometryId FGD(int mod);
/// Get the FGD number. This returns -1 if the id is invalid.
int GetFGD(TGeometryId id);
/// The geometry identifier for FGD1.
TGeometryId FGD1();
/// The geometry identifier for FGD2. FGD2 has the water targets.
TGeometryId FGD2();
/// @{ Check if the id is for FGDn. This returns -1 if the id is
/// invalid.
bool IsFGD1(TGeometryId id);
bool IsFGD2(TGeometryId id);
/// @}
/// The geometry identifier for the targets.
TGeometryId Target(int i);
/// Get the FGD target number. This returns -1 if the id is
/// invalid.
int GetTarget(TGeometryId id);
/// A layer within the FGD. The fgd is either 0 or 1. The module
/// is the glued plane of X and Y scintillator bars. The layer is
/// 0 (x) or 1 (y).
TGeometryId Layer(int fgd, int module, int layer);
/// {@ Get the number of the fgd, module or layer from a geometry
/// id for a layer. This returns -1 if the id is invalid.
int GetLayerFGD(TGeometryId id);
int GetLayerModule(TGeometryId id);
int GetLayerNumber(TGeometryId id);
/// @}
/// The geometry identifiers for FGD scintillators. The FGD
/// indicates which FGD the bar is in (0: FGD1, 1: FGD2). The
/// module gives the glued plane of X and Y bars in the FGD. The
/// layer (x or y) indicates which orientation the bars have (0: X,
/// 1: Y). The bar is the number of bar in the layer.
TGeometryId Bar(int fgd, int module, int layer, int bar);
/// {@ Get the number of the fgd, module, layer, or bar for a
/// geometry id for a bar. This returns -1 if the id is invalid.
int GetBarFGD(TGeometryId id);
int GetBarModule(TGeometryId id);
int GetBarLayer(TGeometryId id);
int GetBarNumber(TGeometryId id);
/// @}
};
/// Define the geometry identifiers for a generic (uk) ecal.
namespace ECal {
/// The geometry identifier for the tracker ecal modules. The
/// ecal must be either ND::GeomId::Def::kDSECal,
/// ND::GeomId::Def::kPECal, or ND::GeomId::Def::kTECal. The clam
/// is 0 for south (-x) or 1 for north (+x). The module is 0 for
/// bottom, 1 for side, and 2 for top.
TGeometryId Module(int ecal, int clam, int module);
/// The geometry identifier for barrel ECal container modules
/// The ecal must be ND::GeomId::Def::kTECal
/// Clams and modules are in in Module()
TGeometryId Container(int ecal, int clam, int module);
/// The layer within the ecal.
TGeometryId Layer(int ecal, int clam, int module, int layer);
/// The geometry identifier for the radiators
TGeometryId Radiator(int ecal, int clam, int module, int radiator);
/// The geometry identifiers for the scintillators.
TGeometryId Bar(int ecal, int clam,
int module, int layer, int bar);
/// @{ Access the information for an ECal Module.
int GetModuleECal(TGeometryId id);
int GetModuleClam(TGeometryId id);
int GetModuleNumber(TGeometryId id);
/// @}
/// @{ Get the layer number. This returns -1 if the id is
/// invalid.
int GetLayerECal(TGeometryId id);
int GetLayerClam(TGeometryId id);
int GetLayerModule(TGeometryId id);
int GetLayerNumber(TGeometryId id);
/// @}
/// @{ Get the radiator number. This returns -1 if the id is
/// invalid.
int GetRadiatorECal(TGeometryId id);
int GetRadiatorClam(TGeometryId id);
int GetRadiatorModule(TGeometryId id);
int GetRadiatorNumber(TGeometryId id);
/// @}
/// @{ Get the layer or bar number. This returns -1 if the id is
/// invalid.
int GetBarECal(TGeometryId id);
int GetBarClam(TGeometryId id);
int GetBarModule(TGeometryId id);
int GetBarLayer(TGeometryId id);
int GetBarNumber(TGeometryId id);
/// @}
};
/// Define the DSECal specific geometry identifiers.
namespace DSECal {
/// Check if the id corresponds to the DSECal.
bool IsDSECal(TGeometryId id);
/// The geometry identifier for the downstream ecal detector.
TGeometryId Detector();
/// The layer within the ecal.
TGeometryId Layer(int layer);
/// Get the DSECal layer number. This returns -1 if the id is
/// invalid.
int GetLayer(TGeometryId id);
/// The geometry identifiers for DSECal scintillators.
TGeometryId Bar(int layer, int bar);
/// @{ Get the layer or bar number. This returns -1 if the id is
/// invalid.
int GetBarLayer(TGeometryId id);
int GetBarNumber(TGeometryId id);
/// @}
/// The geometry identifier for the radiators
TGeometryId Radiator(int radiator);
/// Get the DSECal radiator number. This returns -1 if the id is
/// invalid.
int GetRadiator(TGeometryId id);
};
/// Define the TECal specific geometry identifiers.
namespace TECal {
/// Check if the id corresponds to the TECal.
bool IsTECal(TGeometryId id);
/// The geometry identifier for the tracker ecal modules
TGeometryId Module(int clam, int module);
/// The layer within the ecal.
TGeometryId Layer(int clam, int module, int layer);
/// The geometry identifier for the radiators
TGeometryId Radiator(int clam, int module, int radiator);
/// The geometry identifiers for the scintillators.
TGeometryId Bar(int clam, int module, int layer, int bar);
/// @{ Access the information for an ECal Module.
int GetModuleClam(TGeometryId id);
int GetModuleNumber(TGeometryId id);
/// @}
/// @{ Get the layer number. This returns -1 if the id is
/// invalid.
int GetLayerClam(TGeometryId id);
int GetLayerModule(TGeometryId id);
int GetLayerNumber(TGeometryId id);
/// @}
/// @{ Get the radiator number. This returns -1 if the id is
/// invalid.
int GetRadiatorClam(TGeometryId id);
int GetRadiatorModule(TGeometryId id);
int GetRadiatorNumber(TGeometryId id);
/// @}
/// @{ Get the layer or bar number. This returns -1 if the id is
/// invalid.
int GetBarClam(TGeometryId id);
int GetBarModule(TGeometryId id);
int GetBarLayer(TGeometryId id);
int GetBarNumber(TGeometryId id);
/// @}
};
/// Define the PECal specific geometry identifiers.
namespace PECal {
/// Check if the id corresponds to the PECal.
bool IsPECal(TGeometryId id);
/// The geometry identifier for the tracker ecal modules
TGeometryId Module(int clam, int module);
/// The layer within the ecal.
TGeometryId Layer(int clam, int module, int layer);
/// The geometry identifiers for the scintillators.
TGeometryId Bar(int clam, int module, int layer, int bar);
/// The geometry identifier for the radiators
TGeometryId Radiator(int clam, int module, int radiator);
/// @{ Access the information for an ECal Module.
int GetModuleClam(TGeometryId id);
int GetModuleNumber(TGeometryId id);
/// @}
/// @{ Get the layer number. This returns -1 if the id is
/// invalid.
int GetLayerClam(TGeometryId id);
int GetLayerModule(TGeometryId id);
int GetLayerNumber(TGeometryId id);
/// @}
/// @{ Get the radiator number. This returns -1 if the id is
/// invalid.
int GetRadiatorClam(TGeometryId id);
int GetRadiatorModule(TGeometryId id);
int GetRadiatorNumber(TGeometryId id);
/// @}
/// @{ Get the layer or bar number. This returns -1 if the id is
/// invalid.
int GetBarClam(TGeometryId id);
int GetBarModule(TGeometryId id);
int GetBarLayer(TGeometryId id);
int GetBarNumber(TGeometryId id);
/// @}
};
/// Define the SMRD specific geometry identifiers.
namespace SMRD {
/// Test if this id is for the SMRD.
bool IsSMRD(TGeometryId id);
/// The geometry identifier for a SMRD module.
TGeometryId Module(int clam, int yoke, int layer, int slot);
/// The geometry identifer for a SMRD bar.
TGeometryId Bar(int clam, int yoke, int layer, int slot, int bar);
/// @{ Access the information for a Module. This returns -1 if
/// the id is invalid.
int GetModuleClam(TGeometryId id);
int GetModuleYoke(TGeometryId id);
int GetModuleLayer(TGeometryId id);
int GetModuleSlot(TGeometryId id);
/// @}
/// @{ Get the bar information. This returns -1 if the id is
/// invalid.
int GetBarClam(TGeometryId id);
int GetBarYoke(TGeometryId id);
int GetBarLayer(TGeometryId id);
int GetBarSlot(TGeometryId id);
int GetBarNumber(TGeometryId id);
/// @}
};
/// Define the INGRID specific geometry identifiers.
namespace INGRID {
/// The geometry of a generical scintillator. The object type is
/// either kIngridModule = 0, or kIngridVeto = 1.
TGeometryId Scintillator(int objType, int obj, int trk,
int proj, int scinti);
/// The geometry of a module scintillator.
TGeometryId ModScintillator(int mod, int trk,
int proj, int scinti);
/// The geometry of a vertical veto scintillator.
TGeometryId VertVetoScintillator(int veto, int scinti);
/// The geometry of an horizontal veto scintillator.
TGeometryId HorzVetoScintillator(int veto, int scinti);
};
};
};
#endif
| [
"[email protected]"
] | |
7825b20725613efe45e904775434aafca6f9866b | 0f902011c5742f632b3cdf7c865f48587cb55dc4 | /AdvancedGraphics/lightwidget.h | 66184856e0d6b86f41a8853b381c2de701786c13 | [
"MIT"
] | permissive | Trodek/Advanced-Graphics-Subject | 5a872a87ebc6b439aa2f16260f2ec9daf1e8165f | 5e89fa33a3bc5c4e0910cfae907a22f879be035a | refs/heads/master | 2020-04-24T15:13:13.642562 | 2019-06-12T21:26:40 | 2019-06-12T21:26:40 | 172,057,204 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 567 | h | #ifndef LIGHTWIDGET_H
#define LIGHTWIDGET_H
#include <QWidget>
namespace Ui {
class LightWidget;
}
class LightWidget : public QWidget
{
Q_OBJECT
public:
explicit LightWidget(QWidget *parent = nullptr);
~LightWidget();
private slots:
void on_comboBox_currentIndexChanged(int index);
void on_Red_valueChanged(int arg1);
void on_Green_valueChanged(int arg1);
void on_Blue_valueChanged(int arg1);
void on_doubleSpinBox_valueChanged(double arg1);
private:
Ui::LightWidget *ui;
void UpdateUI();
};
#endif // LIGHTWIDGET_H
| [
"[email protected]"
] | |
af4136d4acca2f6e354ed04e6ba5e836403e9cae | 9a0655e047423d5ec9a0a87b8a58d5e952e06ab8 | /folly/experimental/channels/ConsumeChannel-inl.h | e9951ae7c2fa4062b65deccb2c2e77dd721f4deb | [
"MIT",
"Apache-2.0"
] | permissive | willruggiano/folly | fae0ac567db3d12806d14cf6d986b05e5571d9d6 | 8e44e1e4698579af888e316a0052f52c415b9997 | refs/heads/main | 2023-08-26T01:41:50.147773 | 2021-11-11T18:12:09 | 2021-11-11T19:28:18 | 427,095,000 | 0 | 0 | Apache-2.0 | 2021-11-11T17:58:48 | 2021-11-11T17:58:47 | null | UTF-8 | C++ | false | false | 9,965 | h | /*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* 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.
*/
#pragma once
#include <folly/Executor.h>
#include <folly/Format.h>
#include <folly/IntrusiveList.h>
#include <folly/ScopeGuard.h>
#include <folly/experimental/channels/Channel.h>
#include <folly/experimental/channels/ChannelCallbackHandle.h>
#include <folly/experimental/channels/detail/Utility.h>
#include <folly/experimental/coro/Task.h>
namespace folly {
namespace channels {
namespace detail {
template <typename TValue, typename OnNextFunc>
class ChannelCallbackProcessorImpl : public ChannelCallbackProcessor {
public:
ChannelCallbackProcessorImpl(
ChannelBridgePtr<TValue> receiver,
folly::Executor::KeepAlive<> executor,
OnNextFunc onNext)
: receiver_(std::move(receiver)),
executor_(std::move(executor)),
onNext_(std::move(onNext)),
cancelSource_(folly::CancellationSource::invalid()) {}
void start(std::optional<detail::ReceiverQueue<TValue>> buffer) {
runCoroutineWithCancellation(processAllAvailableValues(std::move(buffer)))
.scheduleOn(executor_)
.start();
}
protected:
virtual void onFinishedConsumption() {}
private:
/**
* Called when the handle is destroyed.
*/
void onHandleDestroyed() override {
executor_->add([=]() { processHandleDestroyed(); });
}
/**
* Called when the channel we are listening to has an update.
*/
void consume(ChannelBridgeBase*) override {
runCoroutineWithCancellation(processAllAvailableValues())
.scheduleOn(executor_)
.start();
}
/**
* Called after we cancelled the input channel (which happens after the handle
* is destroyed).
*/
void canceled(ChannelBridgeBase*) override {
runCoroutineWithCancellation(
processReceiverCancelled(true /* fromHandleDestruction */))
.scheduleOn(executor_)
.start();
}
/**
* Processes all available values from the input receiver (starting from the
* provided buffer, if present).
*
* If a value was received indicating that the input channel has been closed,
* we will process cancellation for the input receiver.
*/
folly::coro::Task<void> processAllAvailableValues(
std::optional<ReceiverQueue<TValue>> buffer = std::nullopt) {
bool closed = buffer.has_value()
? !co_await processValues(std::move(buffer.value()))
: false;
while (!closed) {
if (receiver_->receiverWait(this)) {
// There are no more values available right now, but more values may
// come in the future. We will stop processing for now, until we
// re-start processing when the consume() callback is fired.
break;
}
auto values = receiver_->receiverGetValues();
CHECK(!values.empty());
closed = !co_await processValues(std::move(values));
}
if (closed) {
// The input receiver was closed.
receiver_->receiverCancel();
co_await processReceiverCancelled(false /* fromHandleDestruction */);
}
}
/**
* Processes values from the channel. Returns false if the channel has been
* closed, so the caller can stop processing values from it.
*/
folly::coro::Task<bool> processValues(ReceiverQueue<TValue> values) {
auto cancelToken = co_await folly::coro::co_current_cancellation_token;
while (!values.empty()) {
if (cancelToken.isCancellationRequested()) {
co_return true;
}
auto result = std::move(values.front());
values.pop();
bool closed = !result.hasValue();
if (!co_await callCallback(std::move(result))) {
closed = true;
}
if (closed) {
co_return false;
}
co_await folly::coro::co_reschedule_on_current_executor;
}
co_return true;
}
/**
* Process cancellation of the input receiver.
*
* @param fromHandleDestruction: Whether the cancellation was prompted by the
* handle being destroyed. If true, we will call the user's callback with
* a folly::OperationCancelled exception. This will be false if the
* cancellation was prompted by the closure of the channel.
*/
folly::coro::Task<void> processReceiverCancelled(bool fromHandleDestruction) {
CHECK_EQ(getReceiverState(), ChannelState::CancellationTriggered);
receiver_ = nullptr;
if (fromHandleDestruction) {
co_await callCallback(folly::Try<TValue>(
folly::make_exception_wrapper<folly::OperationCancelled>()));
}
maybeDelete();
}
/**
* Processes the destruction of the handle.
*/
void processHandleDestroyed() {
CHECK(!handleDestroyed_);
handleDestroyed_ = true;
cancelSource_.requestCancellation();
if (getReceiverState() == ChannelState::Active) {
receiver_->receiverCancel();
}
maybeDelete();
}
/**
* Deletes this object if we have already processed cancellation for the
* receiver and the handle.
*/
void maybeDelete() {
if (getReceiverState() == ChannelState::CancellationProcessed &&
handleDestroyed_) {
delete this;
}
}
/**
* Calls the user's callback with the given result.
*/
folly::coro::Task<bool> callCallback(folly::Try<TValue> result) {
auto retVal = co_await folly::coro::co_awaitTry(onNext_(std::move(result)));
if (retVal.template hasException<folly::OperationCancelled>()) {
co_return false;
} else if (retVal.hasException()) {
LOG(FATAL) << folly::sformat(
"Encountered exception from callback when consuming channel of "
"type {}: {}",
typeid(TValue).name(),
retVal.exception().what());
}
co_return retVal.value();
}
/**
* Runs the given coroutine while listening for cancellation triggered by the
* handle's destruction.
*/
folly::coro::Task<void> runCoroutineWithCancellation(
folly::coro::Task<void> task) {
cancelSource_ = folly::CancellationSource();
if (handleDestroyed_) {
// The handle was already destroyed before we even started the coroutine.
// Request cancellation so that the user's callback knows to stop quickly.
cancelSource_.requestCancellation();
}
auto token = cancelSource_.getToken();
auto retVal = co_await folly::coro::co_awaitTry(
folly::coro::co_withCancellation(token, std::move(task)));
CHECK(!retVal.hasException()) << fmt::format(
"Unexpected exception when running coroutine: {}",
retVal.exception().what());
if (!token.isCancellationRequested()) {
cancelSource_ = folly::CancellationSource::invalid();
}
}
ChannelState getReceiverState() {
return detail::getReceiverState(receiver_.get());
}
ChannelBridgePtr<TValue> receiver_;
folly::Executor::KeepAlive<> executor_;
OnNextFunc onNext_;
folly::CancellationSource cancelSource_;
bool handleDestroyed_{false};
};
} // namespace detail
namespace detail {
template <typename TValue, typename OnNextFunc>
class ChannelCallbackProcessorImplWithList
: public ChannelCallbackProcessorImpl<TValue, OnNextFunc> {
public:
ChannelCallbackProcessorImplWithList(
ChannelBridgePtr<TValue> receiver,
folly::Executor::KeepAlive<> executor,
OnNextFunc onNext,
ChannelCallbackHandleList& holders)
: ChannelCallbackProcessorImpl<TValue, OnNextFunc>(
std::move(receiver), std::move(executor), std::move(onNext)),
holder_(ChannelCallbackHandle(this)) {
holders.add(holder_);
}
private:
void onFinishedConsumption() override {
// In this subclass, we will remove ourselves from the list of handles
// when consumption is complete (triggering cancellation).
std::ignore = std::move(holder_);
}
ChannelCallbackHandleHolder holder_;
};
} // namespace detail
template <
typename TReceiver,
typename OnNextFunc,
typename TValue,
std::enable_if_t<
std::is_constructible_v<
folly::Function<folly::coro::Task<bool>(folly::Try<TValue>)>,
OnNextFunc>,
int>>
ChannelCallbackHandle consumeChannelWithCallback(
TReceiver receiver,
folly::Executor::KeepAlive<> executor,
OnNextFunc onNext) {
detail::ChannelCallbackProcessorImpl<TValue, OnNextFunc>* processor = nullptr;
auto [unbufferedReceiver, buffer] =
detail::receiverUnbuffer(std::move(receiver));
processor = new detail::ChannelCallbackProcessorImpl<TValue, OnNextFunc>(
std::move(unbufferedReceiver), std::move(executor), std::move(onNext));
processor->start(std::move(buffer));
return ChannelCallbackHandle(processor);
}
template <
typename TReceiver,
typename OnNextFunc,
typename TValue,
std::enable_if_t<
std::is_constructible_v<
folly::Function<folly::coro::Task<bool>(folly::Try<TValue>)>,
OnNextFunc>,
int>>
void consumeChannelWithCallback(
TReceiver receiver,
folly::Executor::KeepAlive<> executor,
OnNextFunc onNext,
ChannelCallbackHandleList& callbackHandles) {
auto [unbufferedReceiver, buffer] =
detail::receiverUnbuffer(std::move(receiver));
auto* processor =
new detail::ChannelCallbackProcessorImplWithList<TValue, OnNextFunc>(
std::move(unbufferedReceiver),
std::move(executor),
std::move(onNext),
callbackHandles);
processor->start(std::move(buffer));
}
} // namespace channels
} // namespace folly
| [
"[email protected]"
] | |
e6383f35585a4f7aed38289e7004e4dfb62f4d67 | 6d660d843ce4b56a3bad62dcdb84d289a87de2bb | /sys/net/transport/conn_listen.cpp | 9c173e2519092fd1553a56eb0dbb8dd72c13df07 | [] | no_license | charlesg3/faux | eb0a19ec0475d6f30a41cfc4b7fc93dd730c34ce | 762f292e246a18b9ec765761bebc3c5606ce4ae3 | refs/heads/master | 2021-01-23T03:27:26.419917 | 2015-03-13T13:47:54 | 2015-03-13T13:47:54 | 32,158,202 | 5 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 5,698 | cpp | //#include <rpc/rpc.h>
#include <assert.h>
#include "transport_private.hpp"
#include "transport_server.hpp"
#include "conn_private.hpp"
#include "conn_listen.hpp"
#include "conn_socket.hpp"
#include "transport_callbacks.h"
#include <utilities/tsc.h>
#include <utilities/console_colors.h>
#include <config/config.h>
#include "../common/include/hash.h"
//#include <threading/sched.h>
#ifdef CONFIG_PROF_NETSTACK
extern uint64_t g_tcp_sends;
extern uint64_t g_tcp_bytes_sent;
extern uint64_t g_tcp_cycles_spent;
extern uint64_t g_tcp_fails;
extern uint64_t g_link_send_cycles;
extern uint64_t g_connects;
extern uint64_t g_accepts;
#endif
namespace fos { namespace net { namespace transport {
template <class T, class T2> T* make_offset(T *a, T2 *b)
{
return (T*)((uint8_t *)a - (uint8_t *)b);
}
struct WaitThreadArgs
{
flow_t flow_id;
Transport *transport;
};
void acceptorWaitThread(void *p)
{
WaitThreadArgs *args = (WaitThreadArgs *)p;
#if 0
dispatchSleep(TRANSPORT_TIMEOUT);
FlowSocket *out_flow;
bool is_claimed = args->transport->isClaimed(args->flow_id, &out_flow);
if (out_flow && is_claimed)
{
// Success - we are done
NET_DEBUG(CONSOLE_COLOR_CYAN "TransportServer: " CONSOLE_COLOR_NORMAL
" new connection " CONSOLE_COLOR_YELLOW "[%x]" CONSOLE_COLOR_NORMAL " claimed." CONSOLE_COLOR_NORMAL,
args->flow_id);
}
else if(out_flow) // flow not claimed
{
PS("flow not claimed in time. throwing hands in air.");
assert(false);
}
else // out_flow must be gone because app closed it -- assume it was claimed --cg3
{
//out flow gone, assuming app closed.
}
#endif
free(p);
}
// **** Server callbacks and message handlers
// Called by lwip when a new connection is accepted.
err_t acceptCallback(Transport * transport, PendingFlowSocket *pending_flow, struct tcp_pcb * pcb, err_t err)
{
USE_PROF_NETSTACK(g_accepts++);
tcp_finished(pcb, ::connectionFinished);
NET_DEBUG(CONSOLE_COLOR_BLUE "ConnectionManager: " CONSOLE_COLOR_NORMAL
CONSOLE_COLOR_RED " << acceptCallback - Start"
CONSOLE_COLOR_NORMAL " remote port: "
CONSOLE_COLOR_RED "[%d]"
CONSOLE_COLOR_NORMAL " local port: "
CONSOLE_COLOR_RED "[%d]"
CONSOLE_COLOR_NORMAL, pcb->remote_port, pcb->local_port);
// FIXME: I don't think this is necessary anymore; letting it be here
// for now until we verify that this is the case (HK)
// We *possibly* don't handle chain's of pbufs, so make sure this is one chunk
assert(pcb->tcp_input_args->inseg.p->next == NULL);
flow_t flow_id = transport->m_flows.compute(pcb);
assert(pending_flow->m_flow_id == flow_id);
assert(pending_flow->m_remote_ip == ip_to_in(pcb->remote_ip));
if(pending_flow->m_acceptor_valid && pending_flow->m_acceptor_addr == 0)
{
transport->echoAccept(pcb);
return ERR_OK;
}
FlowSocket *flow = new FlowSocket();
flow->m_remote_ip = pending_flow->m_remote_ip;
flow->m_remote_port = pending_flow->m_remote_port;
flow->m_client = {NULL, NULL};
flow->setConnectionId(flow_id);
// Finish setting up connection
tcp_recv(pcb, ::connectionRecv);
tcp_sent(pcb, ::connectionSent);
tcp_err(pcb, ::connectionError);
tcp_finished(pcb, ::connectionFinished);
tcp_arg(pcb, flow);
transport->m_flows.add(pcb);
// Hand over connection to acceptor if acceptor exists
if(pending_flow->m_acceptor_valid)
{
// This is ugly, since we use dispatchOpen() to open a unique
// listen channel (dispatch makes sure it is unique) to the
// application, but then use vanilla channel_send() to send the
// conneciton notification on it; this channel is subsequently used
// by the application to claim the connection (via a
// dispatchRequest)
flow->m_client_addr = pending_flow->m_acceptor_addr;
Channel *chan;
std::map<Address, Channel *>::iterator it = transport->m_conn_handoff_chans.find(flow->m_client_addr);
if(it == transport->m_conn_handoff_chans.end())
{
// Open asynchronous (non-dispatch) connection handoff channel
chan = endpoint_connect(transport->getEndpoint(), flow->m_client_addr);
transport->m_conn_handoff_chans.insert(
std::make_pair<Address, Channel *>(flow->m_client_addr, chan));
// The synchronuos (dispatch) channel is opened by the client
// via dispatchOpen()
}
else
{
chan = it->second;
}
// Notify acceptor of connection
conn::ConnectionAcceptedEventApp *app_data =
(conn::ConnectionAcceptedEventApp *) channel_allocate(chan, sizeof(*app_data));
app_data->addr = ip_to_in(pcb->remote_ip);
app_data->port = flow->m_remote_port;
app_data->flow_id = flow_id;
channel_send(chan, app_data, sizeof(*app_data));
// FIXME: Don't handle timeout right now
// transport->handleTimeout(flow_id, pending_flow->m_acceptor_rbox);
}
// Free memory
delete pending_flow;
return ERR_OK;
}
}}}
| [
"[email protected]"
] | |
947b7998b7d2065fd57d96d4e75c4126ebcdfa68 | 3f78a9da3eecc6d8e401f1cce37e054a252930bc | /[Client]MH/HelpDicManager.cpp | a4ce23c0f8bc141ce10f04caff3e28d5f1710c27 | [] | no_license | apik1997/Mosiang-Online-Titan-DarkStroy-Azuga-Source-Code | 9055aa319c5371afd1ebd504044160234ddbb418 | 74d6441754efb6da87855ee4916994adb7f838d5 | refs/heads/master | 2020-06-14T07:46:03.383719 | 2019-04-09T00:07:28 | 2019-04-09T00:07:28 | 194,951,315 | 0 | 0 | null | 2019-07-03T00:14:59 | 2019-07-03T00:14:59 | null | UHC | C++ | false | false | 2,901 | cpp | #include "stdafx.h"
#include "HelpDicManager.h"
#include "cPage.h"
#include "cDialogueList.h"
#include "cHyperTextList.h"
GLOBALTON(cHelpDicManager)
cHelpDicManager::cHelpDicManager()
{
}
cHelpDicManager::~cHelpDicManager()
{
DeleteAllPageInfo();
SAFE_DELETE( m_pDialogue );
SAFE_DELETE( m_pHyperText );
}
void cHelpDicManager::Init()
{
nTest = 0;
LoadHelpDicInfo();
m_pDialogue = new cDialogueList;
#ifdef _FILE_BIN_
m_pDialogue->LoadDialogueListFile( HELP_DIALOGUE_PATH, "rb" );
#else
m_pDialogue->LoadDialogueListFile( HELP_DIALOGUE_PATH );
#endif
m_pHyperText = new cHyperTextList;
#ifdef _FILE_BIN_
m_pHyperText->LoadHyperTextFormFile( HELP_HYPERTEXT_PATH, "rb");
#else
m_pHyperText->LoadHyperTextFormFile( HELP_HYPERTEXT_PATH );
#endif
}
void cHelpDicManager::AddPage( cPage* pPage )
{
m_HelpDicList.AddTail( pPage );
}
void cHelpDicManager::LoadHelpDicInfo()
{
CMHFile fp;
#ifdef _FILE_BIN_
if(!fp.Init(HELP_SCRIPT_PATH, "rb"))
return;
#else
if(!fp.Init(HELP_SCRIPT_PATH, "rt"))
return;
#endif
char buff[256]={0,};
while(1)
{
fp.GetString(buff);
if( fp.IsEOF() )
break;
if(buff[0] == '@')
{
fp.GetLineX(buff, 256);
continue;
}
CMD_ST(buff)
CMD_CS("$HELPDIC")
if((fp.GetString())[0] == '{')
LoadPageInfo(NULL, &fp);
else
__asm int 3;
CMD_EN
}
}
void cHelpDicManager::LoadPageInfo(cPage* pPage, CMHFile* fp)
{
char buff[256]={0,};
DWORD dwPageId;
int nDialogueCount = 0;
int nHyperLinkCount = 0;
DWORD dwDialogueId;
HYPERLINK sHyper;
while(1)
{
fp->GetString(buff);
if(buff[0] == '}'|| fp->IsEOF())
break;
if(buff[0] == '@')
{
fp->GetLineX(buff, 256);
continue;
}
CMD_ST(buff)
CMD_CS("$PAGE")
if((fp->GetString())[0] == '{')
{
cPage* pNewPage = new cPage; // 새로운 페이지의 등록
AddPage( pNewPage );
LoadPageInfo(pNewPage, fp);
}
CMD_CS("#PAGEINFO")
dwPageId = fp->GetDword();
nDialogueCount = fp->GetInt();
nHyperLinkCount = fp->GetInt();
pPage->Init( dwPageId );
CMD_CS("#DIALOGUE")
for(int i =0; i<nDialogueCount;++i)
{
dwDialogueId = fp->GetDword();
pPage->AddDialogue( dwDialogueId );
}
CMD_CS("#HYPERLINK")
sHyper.wLinkId = fp->GetWord();
sHyper.wLinkType = fp->GetWord()+1;
if( sHyper.wLinkType == emLink_Page )
sHyper.dwData = fp->GetDword();
pPage->AddHyperLink( &sHyper );
nTest++;
CMD_EN
}
}
void cHelpDicManager::DeleteAllPageInfo()
{
PTRLISTSEARCHSTART(m_HelpDicList,cPage*,pPage)
delete pPage;
PTRLISTSEARCHEND
m_HelpDicList.RemoveAll();
}
cPage* cHelpDicManager::GetMainPage()
{
if( m_HelpDicList.IsEmpty() ) return NULL;
return (cPage*)m_HelpDicList.GetHead();
}
cPage* cHelpDicManager::GetPage( DWORD dwPageId )
{
PTRLISTSEARCHSTART(m_HelpDicList, cPage*, pPage)
if( pPage->GetPageId() == dwPageId )
return pPage;
PTRLISTSEARCHEND
return NULL;
}
| [
"[email protected]"
] | |
de85d24077244ed0388fa845bcd0a1d58f3bf9ba | 27cba2b754748e2b75a8a6df18ca8efa9b65a496 | /KeyboardAgeOfEmpireSpam/KeyboardAgeOfEmpireSpam.ino | 19901b1c1de5d582a8197275ac29bb991037eeae | [] | no_license | Rosaroterpanther/Digispark-Keyboard-Programs | 074c8e3384ccd5376fd935ee961f5a901f531db1 | 9731667be6feff38b8f43821a425382154377dc4 | refs/heads/master | 2021-05-14T01:31:02.269674 | 2018-01-07T17:39:29 | 2018-01-07T17:39:29 | 116,570,873 | 0 | 0 | null | 2018-01-07T17:39:30 | 2018-01-07T14:13:12 | Arduino | UTF-8 | C++ | false | false | 1,100 | ino | #include "DigiKeyboard.h"
// Spam Age of Empires 2 Taunts
// Little Digistump Programm
// @author = Rosaroterpanther
long randNumber;
boolean started = false;
void setup() {
// don't need to set anything up to use DigiKeyboard
Serial.begin(9600);
randomSeed(analogRead(0));
}
void loop() {
// this is generally not necessary but with some older systems it seems to
// prevent missing the first character after a delay:
DigiKeyboard.sendKeyStroke(0);
if(!started){
DigiKeyboard.delay(2000);
DigiKeyboard.print("Age of Empire 2 Spammer");
DigiKeyboard.delay(50);
DigiKeyboard.sendKeyStroke(KEY_ENTER);
DigiKeyboard.print("Start in 2 Seconds");
DigiKeyboard.delay(50);
DigiKeyboard.sendKeyStroke(KEY_ENTER);
DigiKeyboard.delay(2000);
started = true;
}
// Generate a random number from 1 to 42
randNumber = random(1, 43);
// Print a random taunt
// Age of Empire 2 taunts overview
// http://ageofempires.wikia.com/wiki/Taunts
DigiKeyboard.print(randNumber);
DigiKeyboard.delay(10);
DigiKeyboard.sendKeyStroke(KEY_ENTER);
}
| [
"[email protected]"
] | |
629ceab312d649d3d4aac48422b0c7dd1be40c11 | e7e497b20442a4220296dea1550091a457df5a38 | /main_project/ad/trunk/engine_b/src/MatchHandlers.h | 3b193c64f213f03a71688d4e1146f78bc56078b2 | [] | no_license | gunner14/old_rr_code | cf17a2dedf8dfcdcf441d49139adaadc770c0eea | bb047dc88fa7243ded61d840af0f8bad22d68dee | refs/heads/master | 2021-01-17T18:23:28.154228 | 2013-12-02T23:45:33 | 2013-12-02T23:45:33 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,543 | h | #ifndef AD_MACHER_HANDLERS_H_
#define AD_MACHER_HANDLERS_H_
#include <IceUtil/Shared.h>
#include <boost/algorithm/string/regex.hpp>
#include "AdEngine.h"
#include "AdStruct.h"
#include "AdConfig.h"
#include "../../util/src/AdCommonUtil.h"
#include "OnlyFirstHandler.h"
namespace xce {
namespace ad {
using namespace MyUtil;
using namespace std;
using namespace boost;
enum REMAIN_STATE {
NORMAL, DEFAULT, ENGINE_U
};
struct MatchHandlerParamter {
MatchHandlerParamter(const UserProfile& userProfile,
const string& append_para):
userProfile_(userProfile),
rotate_index_(0),
remain_state_(NORMAL) {
vector < string > para_strs;
boost::algorithm::split_regex(para_strs, append_para, regex("\\^C"));
if (para_strs.size() >= 3) {
referer_ = para_strs[0];
next_load_time_ = para_strs[1];
refresh_idx_ = para_strs[2];
} else if (para_strs.size() >= 1) {
referer_ = para_strs[0];
}
first_ = FirstFlag::instance().First(userProfile_.id());
};
unsigned int PickCount() const { // 返回还需要选取的广告数
if (EngineConfig::instance().IsForBrand()) {
return adzone_->brand_count() - zone_selected_groups_.size();
} else {
return adzone_->bp_count() - zone_selected_groups_.size();
}
}
UserProfile userProfile_;
string referer_;
string next_load_time_;
string refresh_idx_;
AdZonePtr adzone_;
int rotate_index_;
bool first_;
vector<string> pv_log_seq_;
vector<string> default_log72_;
vector<string> cpm_pv_log_seq_;
vector<string> cpm_default_log72_;
REMAIN_STATE remain_state_;
set<SelectedAdGroupPtr> total_selected_groups_;
set<SelectedAdGroupPtr> zone_selected_groups_;
};
class AdMatchHandler : public IceUtil::Shared {
public:
virtual bool handle(MatchHandlerParamter& para, AdResultMap& result) = 0;
};
class RotationHandler : public AdMatchHandler {
public:
virtual bool handle(MatchHandlerParamter& para, AdResultMap& result);
};
class DefaultHandler : public AdMatchHandler {
public:
virtual bool handle(MatchHandlerParamter& para, AdResultMap& result);
};
class LogHandler : public AdMatchHandler {
public:
virtual bool handle(MatchHandlerParamter& para, AdResultMap& result);
};
class OnlyFirstHandler : public AdMatchHandler {
public:
OnlyFirstHandler() {
FirstFlag::instance().First(0);
}
virtual bool handle(MatchHandlerParamter& para, AdResultMap& result);
};
}
}
#endif // AD_MACHER_HANDLERS_H_
| [
"[email protected]"
] | |
c3f62ff65f295e2fae7b99c179102d64ea5c42c2 | a5edb9bc455f8e1e4cb7e20842ab0eeb8f602049 | /include/lwiot/kernel/uniquelock.h | b280f495787b343bd60ad06a1928d5236fc7230f | [
"Apache-2.0"
] | permissive | lwIoT/lwiot-core | 32d148b4527c9ca9f4b9716bd89ae10d4a99030e | 07d2a3ba962aef508911e453268427b006c57701 | refs/heads/master | 2020-03-13T06:47:44.493308 | 2019-08-30T15:15:21 | 2019-08-30T15:15:21 | 131,012,032 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 998 | h | /*
* UniqueLock definition & implementation.
*
* @author Michel Megens
* @email [email protected]
*/
#pragma once
#include <lwiot/sharedpointer.h>
#include <lwiot/kernel/lock.h>
#include <lwiot/stl/referencewrapper.h>
namespace lwiot
{
template <typename T>
class UniqueLock {
public:
typedef T LockType;
explicit UniqueLock(LockType & lock) : _lock(lock), _locked(false)
{
this->lock();
}
explicit UniqueLock(SharedPointer<LockType >& ptr) : UniqueLock(ptr.get())
{
}
explicit UniqueLock(LockType* lock) : UniqueLock(*lock)
{
}
~UniqueLock()
{
if(this->_locked) {
this->unlock();
}
}
LockType & operator=(const LockType & lock) = delete;
void lock() const
{
this->_lock->lock();
this->_locked = true;
}
void unlock() const
{
this->_locked = false;
this->_lock->unlock();
}
private:
stl::ReferenceWrapper<LockType> _lock;
mutable bool _locked;
};
}
| [
"[email protected]"
] | |
fcf1df065197e0b80b613b1b0f8315123c2e7050 | 1002b7018a7c43904a4efc12699cf841a31f3165 | /SP1Framework/atax.h | 5d96b34f0cb1a34ad8190ab7652389f18cf97ac4 | [] | no_license | SquishableRTWW/Studio-Project-1 | bc17c5e8268523082b927c21862086399e93ea7c | 3a075d842ba17313db7699e3f91083b2b831b611 | refs/heads/master | 2023-07-16T10:09:21.343715 | 2021-08-26T16:17:06 | 2021-08-26T16:17:06 | 396,240,496 | 1 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 191 | h | #pragma once
#include "monster.h"
class atax : public monster
{
private:
string element;
moveList moves;
public:
atax(void); //Default constructor.
void setMove(int i);
~atax(void);
};
| [
"[email protected]"
] | |
5f83a301801135ae266866628d6225a0e9a12c0f | 3f3095dbf94522e37fe897381d9c76ceb67c8e4f | /Current/UI_NameTags.hpp | 2de9ed7ca0d7111f6029bb908a96933c7024d62e | [] | no_license | DRG-Modding/Header-Dumps | 763c7195b9fb24a108d7d933193838d736f9f494 | 84932dc1491811e9872b1de4f92759616f9fa565 | refs/heads/main | 2023-06-25T11:11:10.298500 | 2023-06-20T13:52:18 | 2023-06-20T13:52:18 | 399,652,576 | 8 | 7 | null | null | null | null | UTF-8 | C++ | false | false | 456 | hpp | #ifndef UE4SS_SDK_UI_NameTags_HPP
#define UE4SS_SDK_UI_NameTags_HPP
class UUI_NameTags_C : public UUserWidget
{
FPointerToUberGraphFrame UberGraphFrame;
class UImage* Image_Icon;
class USizeBox* SizeBox_Image;
float Height;
void SetData(class AFSDPlayerState* Player);
void PreConstruct(bool IsDesignTime);
void OnPlayerNameChanged_Event_0(FString NewName);
void ExecuteUbergraph_UI_NameTags(int32 EntryPoint);
};
#endif
| [
"[email protected]"
] | |
d16198f3d2f42d19808a1143d61e1826950450e5 | b2d279b5dd7a3f2c3a0351a04fc5209de1fc13ca | /BFS + DFS.cpp | 80eaada802ad6f28bfdc46d516d520e1ed672e5d | [] | no_license | haroonfayyaz17/Graph-Algorithms | 6301279e5f1284fe39a42e09a2940cfd1c4128a5 | 555a129936c0d2d6ff38f85a52742c9237f34dbe | refs/heads/main | 2023-02-26T16:01:13.059755 | 2021-02-02T12:35:39 | 2021-02-02T12:35:39 | 335,282,963 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,473 | cpp | #include <iostream>
#include <string>
#include <queue>
#include <stack>
using namespace std;
class Graph
{
struct Vertex
{
string data;
bool isVisited = false;
};
struct Edge
{
string edge;
int weight;
};
Vertex vertices[9];
Edge edges[200];
int vCount, eCount;
public:
Graph() :vCount(9), eCount(0){
for (int i = 0; i < 9; i++)
{
vertices[i].data = 48 + i;
}
}
int getVertexPos(string str)
{
for (int i = 0; i < vCount; i++)
if (vertices[i].data == str)
return i;
}
void changeStatus()
{
for (int i = 0; i < vCount; i++)
vertices[i].isVisited = false;
}
void BFS(int matrix[][9], string start)
{
queue<string>q;
q.push(start);
while (!q.empty())
{
start = q.front();
q.pop();
int vertex = getVertexPos(start);
vertices[vertex].isVisited = true;
for (int i = 0; i < vCount; i++)
{
if (matrix[vertex][i] != 0)
if (vertices[i].isVisited == false)
{
q.push(vertices[i].data);
vertices[i].isVisited = true;
}
}
cout << start << " ";
}
changeStatus();
cout << endl;
}
void DFS(int matrix[][9], string start)
{
stack<string>stack;
stack.push(start);
int vertex = getVertexPos(start);
vertices[vertex].isVisited = true;
cout << start << " ";
while (!stack.empty())
{
start = stack.top();
int vertex = getVertexPos(start);
bool done = false;
for (int i = 0; i < vCount&&!done; i++)
{
if (matrix[vertex][i] != 0)
if (vertices[i].isVisited == false)
{
stack.push(vertices[i].data);
vertices[i].isVisited = true;
done = true;
cout << vertices[i].data << " ";
}
}
if (!done)
stack.pop();
}
changeStatus();
cout << endl;
}
void display(int matrix[][9])
{
cout << " ";
for (int i = 0; i < vCount; i++)
cout << vertices[i].data << " ";
cout << endl << endl;
for (int i = 0; i < vCount; i++)
{
cout << vertices[i].data << " ";
for (int j = 0; j < vCount; j++)
{
cout << matrix[i][j] << " ";
}
cout << endl << endl;
}
}
};
int main()
{
Graph graph;
int matrix[9][9] = { { 0, 1, 0, 0, 0, 0, 1, 1, 0 }, { 0, 0, 0, 0, 1, 0, 1, 0, 0 }, { 1, 1, 0, 0, 0, 0, 0, 0, 1 }, { 0, 0, 0, 0, 1, 1, 0, 0, 0 }, { 0, 0, 0, 0, 0, 0, 0, 0, 0 }, { 0, 0, 0, 0, 1, 0, 0, 0, 0 }, { 0, 0, 0, 1, 1, 0, 0, 0, 0 }, { 0, 0, 0, 1, 0, 0, 1, 0, 0 }, { 1, 0, 0, 0, 0, 0, 0, 1, 0 } };
graph.display(matrix);
graph.BFS(matrix, "2");
graph.DFS(matrix, "2");
system("pause>0");
} | [
"[email protected]"
] | |
94a4e6d174ccd586fdb3f4c0a4b03c58a86a5e15 | 757374a2b6a1b16d9f4327a28017b4f213b7e32e | /parser.cpp | 9be1855817a5702b24dec5b8ca5e7980e959ada7 | [] | no_license | yenting-chen/SAT-Solver | 1a4f93772ae1a8eea1a30bbd8a2c43efe68d40a2 | 17ba7c62cff5a07c5a020b2a51e177769d0afc6b | refs/heads/main | 2023-01-10T06:59:45.610637 | 2020-11-13T14:08:50 | 2020-11-13T14:08:50 | 312,200,100 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,032 | cpp | /*********************************************************************
================
CNF Parsing code
================
**********************************************************************/
#include "parser.h"
#include <iostream>
using std::ifstream;
//#include <zlib.h>
#include <cstdlib>
#include <cstdio>
//=====================================================================
// DIMACS Parser:
#define CHUNK_LIMIT 1048576
class StreamBuffer {
//gzFile in;
FILE *in;
char buf[CHUNK_LIMIT];
int pos;
int size;
void assureLookahead() {
if (pos >= size) {
pos = 0;
//size = gzread(in, buf, sizeof(buf)); } }
size = fread(buf, 1, sizeof(buf), in); } }
public:
//StreamBuffer(gzFile i) : in(i), pos(0), size(0) {
StreamBuffer(FILE *i) : in(i), pos(0), size(0) {
assureLookahead(); }
int operator * () { return (pos >= size) ? EOF : buf[pos]; }
void operator ++ () { pos++; assureLookahead(); }
};
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
void skipWhitespace(StreamBuffer &in) {
while ((*in >= 9 && *in <= 13) || *in == 32)
++in;
}
void skipLine(StreamBuffer &in) {
while (true) {
if (*in == EOF) return;
if (*in == '\n') { ++in; return; }
++in;
}
}
int parseInt(StreamBuffer &in) {
int val = 0;
bool neg = false;
skipWhitespace(in);
if (*in == '-') neg = true, ++in;
else if (*in == '+') ++in;
if (*in < '0' || *in > '9')
fprintf(stderr, "PARSE ERROR! Unexpected char: %c\n", *in), exit(3);
while (*in >= '0' && *in <= '9') {
val = val*10 + (*in - '0');
++in;
}
return neg ? -val : val;
}
void readClause(StreamBuffer &in, vector<vector<int> > &clauses) {
int parsed_lit;
vector<int> newClause;
while (true) {
parsed_lit = parseInt(in);
if (parsed_lit == 0) break;
newClause.push_back(parsed_lit);
}
clauses.push_back(newClause);
}
void parse_DIMACS_main(StreamBuffer &in, vector<vector<int> > &clauses) {
while (true) {
skipWhitespace(in);
if (*in == EOF) break;
else if (*in == 'c' || *in == 'p') skipLine(in);
else readClause(in, clauses);
}
}
//void parse_DIMACS(gzFile input_stream, vector<vector<int> > &clauses)
void parse_DIMACS(FILE *input_stream, vector<vector<int> > &clauses)
{
StreamBuffer in(input_stream);
parse_DIMACS_main(in, clauses);
}
void parse_DIMACS_CNF(vector<vector<int> > &clauses,
int &maxVarIndex,
const char *DIMACS_cnf_file) {
unsigned int i, j;
int candidate;
//gzFile in = gzopen(DIMACS_cnf_file, "rb");
FILE *in = fopen(DIMACS_cnf_file, "r");
if (in == NULL) {
fprintf(stderr, "ERROR! Could not open file: %s\n",
DIMACS_cnf_file);
exit(1);
}
parse_DIMACS(in, clauses);
//gzclose(in);
fclose(in);
maxVarIndex = 0;
for (i = 0; i < clauses.size(); ++i)
for (j = 0; j < clauses[i].size(); ++j) {
candidate = abs(clauses[i][j]);
if (candidate > maxVarIndex) maxVarIndex = candidate;
}
}
| [
"[email protected]"
] | |
027188cc15a7306c95844c5ce7f743812d130f20 | 716150dacdd51c2ed559d3fe7259076bd3d1aa19 | /test/circle_circle_intersection_test.cpp | 63020fd6de0a992f65e087fa8c35bee0cf738d26 | [] | no_license | Eadral/SE_Individual_Project | 964bf95828e9cef36c47caf2319e8a62b6df9ad0 | 7c5e0d8360a1afbbe18207226723390aba88af39 | refs/heads/master | 2021-02-17T15:31:42.417850 | 2020-03-10T05:47:43 | 2020-03-10T05:47:43 | 245,107,623 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,165 | cpp | #include "pch.h"
#include "CppUnitTest.h"
#include <sstream>
using namespace Microsoft::VisualStudio::CppUnitTestFramework;
using namespace std;
namespace UnitTest
{
TEST_CLASS(CircleCircleIntersectionTest)
{
public:
TEST_METHOD(TwoCross)
{
stringstream sin;
stringstream sout;
Solver solver(sin, sout);
solver.CircleCircleIntersect(
Circle(1, 0, 1),
Circle(0, 0, 1)
);
Assert::AreEqual(solver.GetAns(), 2);
}
TEST_METHOD(ExternallyTangent)
{
stringstream sin;
stringstream sout;
Solver solver(sin, sout);
solver.CircleCircleIntersect(
Circle(2, 0, 1),
Circle(0, 0, 1)
);
Assert::AreEqual(solver.GetAns(), 1);
}
TEST_METHOD(InternallTangent)
{
stringstream sin;
stringstream sout;
Solver solver(sin, sout);
solver.CircleCircleIntersect(
Circle(1, 0, 1),
Circle(0, 0, 2)
);
Assert::AreEqual(solver.GetAns(), 1);
}
TEST_METHOD(NoCross)
{
stringstream sin;
stringstream sout;
Solver solver(sin, sout);
solver.CircleCircleIntersect(
Circle(5, 0, 1),
Circle(0, 0, 2)
);
Assert::AreEqual(solver.GetAns(), 0);
}
};
}
| [
"[email protected]"
] | |
117b60f87bb79b61d6832e7540b30ee44b1134e6 | a06a9ae73af6690fabb1f7ec99298018dd549bb7 | /_Library/_Include/boost/fusion/container/set/detail/cpp03/preprocessed/as_set10.hpp | 3820fa484b34c8ff8c5b3d14318e9c376ab4cc45 | [
"BSL-1.0"
] | permissive | longstl/mus12 | f76de65cca55e675392eac162dcc961531980f9f | 9e1be111f505ac23695f7675fb9cefbd6fa876e9 | refs/heads/master | 2021-05-18T08:20:40.821655 | 2020-03-29T17:38:13 | 2020-03-29T17:38:13 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 14,411 | hpp | ////////////////////////////////////////////////////////////////////////////////
// as_set10.hpp
/*=============================================================================
Copyright (c) 2001-2011 Joel de Guzman
Distributed under the Boost Software License, Version 1.0. (See accompanying
file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
This is an auto-generated file. Do not edit!
==============================================================================*/
namespace boost { namespace fusion { namespace detail
{
BOOST_FUSION_BARRIER_BEGIN
template <>
struct as_set<1>
{
template <typename I0>
struct apply
{
typedef typename fusion::result_of::next<I0>::type I1;
typedef typename fusion::result_of::value_of<I0>::type T0;
typedef set<T0> type;
};
template <typename Iterator>
BOOST_CXX14_CONSTEXPR BOOST_FUSION_GPU_ENABLED
static typename apply<Iterator>::type
call(Iterator const& i0)
{
typedef apply<Iterator> gen;
typedef typename gen::type result;
return result(*i0);
}
};
template <>
struct as_set<2>
{
template <typename I0>
struct apply
{
typedef typename fusion::result_of::next<I0>::type I1; typedef typename fusion::result_of::next<I1>::type I2;
typedef typename fusion::result_of::value_of<I0>::type T0; typedef typename fusion::result_of::value_of<I1>::type T1;
typedef set<T0 , T1> type;
};
template <typename Iterator>
BOOST_CXX14_CONSTEXPR BOOST_FUSION_GPU_ENABLED
static typename apply<Iterator>::type
call(Iterator const& i0)
{
typedef apply<Iterator> gen;
typedef typename gen::type result;
typename gen::I1 i1 = fusion::next(i0);
return result(*i0 , *i1);
}
};
template <>
struct as_set<3>
{
template <typename I0>
struct apply
{
typedef typename fusion::result_of::next<I0>::type I1; typedef typename fusion::result_of::next<I1>::type I2; typedef typename fusion::result_of::next<I2>::type I3;
typedef typename fusion::result_of::value_of<I0>::type T0; typedef typename fusion::result_of::value_of<I1>::type T1; typedef typename fusion::result_of::value_of<I2>::type T2;
typedef set<T0 , T1 , T2> type;
};
template <typename Iterator>
BOOST_CXX14_CONSTEXPR BOOST_FUSION_GPU_ENABLED
static typename apply<Iterator>::type
call(Iterator const& i0)
{
typedef apply<Iterator> gen;
typedef typename gen::type result;
typename gen::I1 i1 = fusion::next(i0); typename gen::I2 i2 = fusion::next(i1);
return result(*i0 , *i1 , *i2);
}
};
template <>
struct as_set<4>
{
template <typename I0>
struct apply
{
typedef typename fusion::result_of::next<I0>::type I1; typedef typename fusion::result_of::next<I1>::type I2; typedef typename fusion::result_of::next<I2>::type I3; typedef typename fusion::result_of::next<I3>::type I4;
typedef typename fusion::result_of::value_of<I0>::type T0; typedef typename fusion::result_of::value_of<I1>::type T1; typedef typename fusion::result_of::value_of<I2>::type T2; typedef typename fusion::result_of::value_of<I3>::type T3;
typedef set<T0 , T1 , T2 , T3> type;
};
template <typename Iterator>
BOOST_CXX14_CONSTEXPR BOOST_FUSION_GPU_ENABLED
static typename apply<Iterator>::type
call(Iterator const& i0)
{
typedef apply<Iterator> gen;
typedef typename gen::type result;
typename gen::I1 i1 = fusion::next(i0); typename gen::I2 i2 = fusion::next(i1); typename gen::I3 i3 = fusion::next(i2);
return result(*i0 , *i1 , *i2 , *i3);
}
};
template <>
struct as_set<5>
{
template <typename I0>
struct apply
{
typedef typename fusion::result_of::next<I0>::type I1; typedef typename fusion::result_of::next<I1>::type I2; typedef typename fusion::result_of::next<I2>::type I3; typedef typename fusion::result_of::next<I3>::type I4; typedef typename fusion::result_of::next<I4>::type I5;
typedef typename fusion::result_of::value_of<I0>::type T0; typedef typename fusion::result_of::value_of<I1>::type T1; typedef typename fusion::result_of::value_of<I2>::type T2; typedef typename fusion::result_of::value_of<I3>::type T3; typedef typename fusion::result_of::value_of<I4>::type T4;
typedef set<T0 , T1 , T2 , T3 , T4> type;
};
template <typename Iterator>
BOOST_CXX14_CONSTEXPR BOOST_FUSION_GPU_ENABLED
static typename apply<Iterator>::type
call(Iterator const& i0)
{
typedef apply<Iterator> gen;
typedef typename gen::type result;
typename gen::I1 i1 = fusion::next(i0); typename gen::I2 i2 = fusion::next(i1); typename gen::I3 i3 = fusion::next(i2); typename gen::I4 i4 = fusion::next(i3);
return result(*i0 , *i1 , *i2 , *i3 , *i4);
}
};
template <>
struct as_set<6>
{
template <typename I0>
struct apply
{
typedef typename fusion::result_of::next<I0>::type I1; typedef typename fusion::result_of::next<I1>::type I2; typedef typename fusion::result_of::next<I2>::type I3; typedef typename fusion::result_of::next<I3>::type I4; typedef typename fusion::result_of::next<I4>::type I5; typedef typename fusion::result_of::next<I5>::type I6;
typedef typename fusion::result_of::value_of<I0>::type T0; typedef typename fusion::result_of::value_of<I1>::type T1; typedef typename fusion::result_of::value_of<I2>::type T2; typedef typename fusion::result_of::value_of<I3>::type T3; typedef typename fusion::result_of::value_of<I4>::type T4; typedef typename fusion::result_of::value_of<I5>::type T5;
typedef set<T0 , T1 , T2 , T3 , T4 , T5> type;
};
template <typename Iterator>
BOOST_CXX14_CONSTEXPR BOOST_FUSION_GPU_ENABLED
static typename apply<Iterator>::type
call(Iterator const& i0)
{
typedef apply<Iterator> gen;
typedef typename gen::type result;
typename gen::I1 i1 = fusion::next(i0); typename gen::I2 i2 = fusion::next(i1); typename gen::I3 i3 = fusion::next(i2); typename gen::I4 i4 = fusion::next(i3); typename gen::I5 i5 = fusion::next(i4);
return result(*i0 , *i1 , *i2 , *i3 , *i4 , *i5);
}
};
template <>
struct as_set<7>
{
template <typename I0>
struct apply
{
typedef typename fusion::result_of::next<I0>::type I1; typedef typename fusion::result_of::next<I1>::type I2; typedef typename fusion::result_of::next<I2>::type I3; typedef typename fusion::result_of::next<I3>::type I4; typedef typename fusion::result_of::next<I4>::type I5; typedef typename fusion::result_of::next<I5>::type I6; typedef typename fusion::result_of::next<I6>::type I7;
typedef typename fusion::result_of::value_of<I0>::type T0; typedef typename fusion::result_of::value_of<I1>::type T1; typedef typename fusion::result_of::value_of<I2>::type T2; typedef typename fusion::result_of::value_of<I3>::type T3; typedef typename fusion::result_of::value_of<I4>::type T4; typedef typename fusion::result_of::value_of<I5>::type T5; typedef typename fusion::result_of::value_of<I6>::type T6;
typedef set<T0 , T1 , T2 , T3 , T4 , T5 , T6> type;
};
template <typename Iterator>
BOOST_CXX14_CONSTEXPR BOOST_FUSION_GPU_ENABLED
static typename apply<Iterator>::type
call(Iterator const& i0)
{
typedef apply<Iterator> gen;
typedef typename gen::type result;
typename gen::I1 i1 = fusion::next(i0); typename gen::I2 i2 = fusion::next(i1); typename gen::I3 i3 = fusion::next(i2); typename gen::I4 i4 = fusion::next(i3); typename gen::I5 i5 = fusion::next(i4); typename gen::I6 i6 = fusion::next(i5);
return result(*i0 , *i1 , *i2 , *i3 , *i4 , *i5 , *i6);
}
};
template <>
struct as_set<8>
{
template <typename I0>
struct apply
{
typedef typename fusion::result_of::next<I0>::type I1; typedef typename fusion::result_of::next<I1>::type I2; typedef typename fusion::result_of::next<I2>::type I3; typedef typename fusion::result_of::next<I3>::type I4; typedef typename fusion::result_of::next<I4>::type I5; typedef typename fusion::result_of::next<I5>::type I6; typedef typename fusion::result_of::next<I6>::type I7; typedef typename fusion::result_of::next<I7>::type I8;
typedef typename fusion::result_of::value_of<I0>::type T0; typedef typename fusion::result_of::value_of<I1>::type T1; typedef typename fusion::result_of::value_of<I2>::type T2; typedef typename fusion::result_of::value_of<I3>::type T3; typedef typename fusion::result_of::value_of<I4>::type T4; typedef typename fusion::result_of::value_of<I5>::type T5; typedef typename fusion::result_of::value_of<I6>::type T6; typedef typename fusion::result_of::value_of<I7>::type T7;
typedef set<T0 , T1 , T2 , T3 , T4 , T5 , T6 , T7> type;
};
template <typename Iterator>
BOOST_CXX14_CONSTEXPR BOOST_FUSION_GPU_ENABLED
static typename apply<Iterator>::type
call(Iterator const& i0)
{
typedef apply<Iterator> gen;
typedef typename gen::type result;
typename gen::I1 i1 = fusion::next(i0); typename gen::I2 i2 = fusion::next(i1); typename gen::I3 i3 = fusion::next(i2); typename gen::I4 i4 = fusion::next(i3); typename gen::I5 i5 = fusion::next(i4); typename gen::I6 i6 = fusion::next(i5); typename gen::I7 i7 = fusion::next(i6);
return result(*i0 , *i1 , *i2 , *i3 , *i4 , *i5 , *i6 , *i7);
}
};
template <>
struct as_set<9>
{
template <typename I0>
struct apply
{
typedef typename fusion::result_of::next<I0>::type I1; typedef typename fusion::result_of::next<I1>::type I2; typedef typename fusion::result_of::next<I2>::type I3; typedef typename fusion::result_of::next<I3>::type I4; typedef typename fusion::result_of::next<I4>::type I5; typedef typename fusion::result_of::next<I5>::type I6; typedef typename fusion::result_of::next<I6>::type I7; typedef typename fusion::result_of::next<I7>::type I8; typedef typename fusion::result_of::next<I8>::type I9;
typedef typename fusion::result_of::value_of<I0>::type T0; typedef typename fusion::result_of::value_of<I1>::type T1; typedef typename fusion::result_of::value_of<I2>::type T2; typedef typename fusion::result_of::value_of<I3>::type T3; typedef typename fusion::result_of::value_of<I4>::type T4; typedef typename fusion::result_of::value_of<I5>::type T5; typedef typename fusion::result_of::value_of<I6>::type T6; typedef typename fusion::result_of::value_of<I7>::type T7; typedef typename fusion::result_of::value_of<I8>::type T8;
typedef set<T0 , T1 , T2 , T3 , T4 , T5 , T6 , T7 , T8> type;
};
template <typename Iterator>
BOOST_CXX14_CONSTEXPR BOOST_FUSION_GPU_ENABLED
static typename apply<Iterator>::type
call(Iterator const& i0)
{
typedef apply<Iterator> gen;
typedef typename gen::type result;
typename gen::I1 i1 = fusion::next(i0); typename gen::I2 i2 = fusion::next(i1); typename gen::I3 i3 = fusion::next(i2); typename gen::I4 i4 = fusion::next(i3); typename gen::I5 i5 = fusion::next(i4); typename gen::I6 i6 = fusion::next(i5); typename gen::I7 i7 = fusion::next(i6); typename gen::I8 i8 = fusion::next(i7);
return result(*i0 , *i1 , *i2 , *i3 , *i4 , *i5 , *i6 , *i7 , *i8);
}
};
template <>
struct as_set<10>
{
template <typename I0>
struct apply
{
typedef typename fusion::result_of::next<I0>::type I1; typedef typename fusion::result_of::next<I1>::type I2; typedef typename fusion::result_of::next<I2>::type I3; typedef typename fusion::result_of::next<I3>::type I4; typedef typename fusion::result_of::next<I4>::type I5; typedef typename fusion::result_of::next<I5>::type I6; typedef typename fusion::result_of::next<I6>::type I7; typedef typename fusion::result_of::next<I7>::type I8; typedef typename fusion::result_of::next<I8>::type I9; typedef typename fusion::result_of::next<I9>::type I10;
typedef typename fusion::result_of::value_of<I0>::type T0; typedef typename fusion::result_of::value_of<I1>::type T1; typedef typename fusion::result_of::value_of<I2>::type T2; typedef typename fusion::result_of::value_of<I3>::type T3; typedef typename fusion::result_of::value_of<I4>::type T4; typedef typename fusion::result_of::value_of<I5>::type T5; typedef typename fusion::result_of::value_of<I6>::type T6; typedef typename fusion::result_of::value_of<I7>::type T7; typedef typename fusion::result_of::value_of<I8>::type T8; typedef typename fusion::result_of::value_of<I9>::type T9;
typedef set<T0 , T1 , T2 , T3 , T4 , T5 , T6 , T7 , T8 , T9> type;
};
template <typename Iterator>
BOOST_CXX14_CONSTEXPR BOOST_FUSION_GPU_ENABLED
static typename apply<Iterator>::type
call(Iterator const& i0)
{
typedef apply<Iterator> gen;
typedef typename gen::type result;
typename gen::I1 i1 = fusion::next(i0); typename gen::I2 i2 = fusion::next(i1); typename gen::I3 i3 = fusion::next(i2); typename gen::I4 i4 = fusion::next(i3); typename gen::I5 i5 = fusion::next(i4); typename gen::I6 i6 = fusion::next(i5); typename gen::I7 i7 = fusion::next(i6); typename gen::I8 i8 = fusion::next(i7); typename gen::I9 i9 = fusion::next(i8);
return result(*i0 , *i1 , *i2 , *i3 , *i4 , *i5 , *i6 , *i7 , *i8 , *i9);
}
};
BOOST_FUSION_BARRIER_END
}}}
/////////////////////////////////////////////////
// vnDev.Games - Trong.LIVE - DAO VAN TRONG //
////////////////////////////////////////////////////////////////////////////////
| [
"[email protected]"
] | |
5d8ba46ed184b61cb7019480a508ef87991ba8c3 | 1cc5d45273d008e97497dad9ec004505cc68c765 | /cheatsheet/MyNote/study_note/cpp/day13/limit.cpp | e57edadd9f744db815871fbc25ba3680cf39f84f | [] | no_license | wangfuli217/ld_note | 6efb802989c3ea8acf031a10ccf8a8a27c679142 | ad65bc3b711ec00844da7493fc55e5445d58639f | refs/heads/main | 2023-08-26T19:26:45.861748 | 2023-03-25T08:13:19 | 2023-03-25T08:13:19 | 375,861,686 | 5 | 6 | null | null | null | null | UTF-8 | C++ | false | false | 203 | cpp | #include<iostream>
using namespace std;
template<int x> void foo(void)
{
cout<<x<<endl;
}
template<double x> void foo1(void)
{
cout<<x<<endl;
}
int main(void)
{
foo<3>();
foo1<3.13>();
return 0;
}
| [
"[email protected]"
] | |
dbaaa17f96e1d0f44b86f9511141d712c12bc0b1 | 5065511786597a358d39f332557a17ae10ea04d8 | /OpenFile.h | b49b9763415f87f4e69dd256da08441aadec9fdf | [] | no_license | mpartel/editor | 98cd56cbdf2cc0bb36ea1a20570113e413caa0e1 | 61ff6a07f9e84ac85193c9127e60688b32998cf4 | refs/heads/master | 2021-01-22T07:02:45.736159 | 2012-10-06T11:50:58 | 2012-10-06T11:50:58 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,341 | h | #ifndef OPENFILE_H
#define OPENFILE_H
#include <QObject>
#include <QTextDocument>
class OpenFile : public QObject
{
Q_OBJECT
Q_PROPERTY(QTextDocument* document READ document)
Q_PROPERTY(QString title READ title)
Q_PROPERTY(QString path READ path WRITE setPath)
public:
explicit OpenFile(QString path = QString::null, QObject* parent = 0);
QString path() const { return m_path; } // May be a null string
QString title() const;
QTextDocument* document() const { return m_doc; }
void setPath(QString path) { m_path = path; }
bool isNewUnsavedFile() const { return m_path.isNull(); }
void registerReference(QObject* obj);
bool hasReferences() const { return m_refcount > 0; }
signals:
void noMoreReferences(OpenFile* file);
void documentModifiedStatusChanged(OpenFile* file, bool newStatus);
void documentSaved(OpenFile* file);
void documentLoaded(OpenFile* file);
void readError(OpenFile* file, QString msg);
void writeError(OpenFile* file, QString msg);
public slots:
bool save();
bool revertToSavedState();
private slots:
void emitDocumentModifiedStatusChanged(bool newStatus);
void decrementRefcount();
private:
QString m_path;
QTextDocument* m_doc;
int m_refcount;
QString m_lastError;
};
#endif // OPENFILE_H
| [
"[email protected]"
] | |
be9c63601c0de54309064c80492d82fdc16e53da | a3348cfff05ff3392dd04fe6e0bf2b7c7c1c2151 | /wav_header.hpp | 868498ca54dd2d5f29508c3b52a5cc92ec1ecb92 | [] | no_license | asdredmitry/Wav | 0cb173a0adb81691f05442b5ef206d275660dfdc | 1b29921fb21a18c359c7158915cf51e7def138b9 | refs/heads/master | 2020-06-09T06:59:27.711050 | 2019-06-26T19:30:11 | 2019-06-26T19:30:11 | 193,395,691 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 397 | hpp | typedef struct
{
char chunkId[4];
unsigned int chunkSize;
char format[4];
char subchunk1Id[4];
unsigned int subchunk1Size;
unsigned short audioFormat;
unsigned short numChannels;
unsigned int sampleRate;
unsigned int byteRate;
unsigned short blockAlign;
unsigned short bitsPerSample;
char subchunk2Id[4];
unsigned int subchunk2Size;
}WAVHEADER; | [
"[email protected]"
] | |
0dc38886522364c1cdc056921b71d876d00c9d58 | f969f027e98c3d5106c423e57ea4fc7d2903a8fb | /跳跃游戏II.cpp | 270aa076e12354ac1cb1825c52d8658e850b3ffc | [] | no_license | BenQuickDeNN/LeetCodeSolutions | eb2e1e3d2f13621f4d603e26f28a0fce2af75f1b | 4165aca74114e9841a312b27ccc4a807a9fd65e5 | refs/heads/master | 2023-09-04T12:02:24.846562 | 2021-11-13T03:44:11 | 2021-11-13T03:44:11 | 255,344,497 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 633 | cpp | #include <vector>
#include <algorithm>
using namespace std;
class Solution {
public:
int jump(vector<int>& nums) {
/* 使用前向贪心算法 */
int maxRight = 0; // 当前下标可达最远距离
int end = 0; // 当前可达边界
const int n = nums.size();
int step = 0;
for (int i = 0; i < n - 1; i++)
if (maxRight >= i)
{
maxRight = max(maxRight, i + nums[i]);
if (i == end)
{
end = maxRight;
++step;
}
}
return step;
}
}; | [
"[email protected]"
] | |
64efe250539ee758348bc446c64732b3b890ea3d | 059844b682215e7e35182d40b6df988c77f4a7de | /src/AN/AN_avx2_32_64_s_inv.cpp | a49798e3936e5d8586aa49148a4205a61c203f67 | [
"Apache-2.0"
] | permissive | brics-db/coding_benchmark | 8da83baee9e8b1a8bb183bc1359dcb6a547552f0 | f4bab7b57fcb57d98d94a4efc3b8adad2bad6767 | refs/heads/master | 2018-12-17T07:46:44.680427 | 2018-09-14T10:43:41 | 2018-09-14T10:49:24 | 75,196,831 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,334 | cpp | // Copyright (c) 2018 Till Kolditz
//
// 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.
/*
* AN_avx2_32_64_s_inv.cpp
*
* Created on: 22.03.2018
* Author: Till Kolditz - [email protected]
*/
#ifdef __AVX2__
#include <AN/AN_simd.hpp>
namespace coding_benchmark {
template
struct AN_avx2_32_64_s_inv<1>;
template
struct AN_avx2_32_64_s_inv<2>;
template
struct AN_avx2_32_64_s_inv<4>;
template
struct AN_avx2_32_64_s_inv<8>;
template
struct AN_avx2_32_64_s_inv<16>;
template
struct AN_avx2_32_64_s_inv<32>;
template
struct AN_avx2_32_64_s_inv<64>;
template
struct AN_avx2_32_64_s_inv<128>;
template
struct AN_avx2_32_64_s_inv<256>;
template
struct AN_avx2_32_64_s_inv<512>;
template
struct AN_avx2_32_64_s_inv<1024>;
}
#endif
| [
"[email protected]"
] | |
fc103057a24fbfc4f8770d4520d21839475ba134 | 211fcb30d2c0068d88074c646258b31e008fd32b | /AtCoder/arc/arc025/2.cpp | 67350866dae0e7922482fd3ef31e756081e5cfda | [] | no_license | makecir/competitive-programming | 2f9ae58284b37fab9aed872653518089951ff7fd | be6c7eff4baf07dd19b50eb756ec0d5dc5ec3ebf | refs/heads/master | 2021-06-11T08:10:17.375410 | 2021-04-13T11:59:17 | 2021-04-13T11:59:17 | 155,111,372 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,725 | cpp | #include <bits/stdc++.h>
#include <atcoder/all>
using namespace std;
using namespace atcoder;
using ll=long long;
using ull=unsigned long long;
using ld=long double;
using vb=vector<bool>;
using vvb=vector<vb>;
using vd=vector<double>;
using vvd=vector<vd>;
using vi=vector<int>;
using vvi=vector<vi>;
using vl=vector<ll>;
using vvl=vector<vl>;
using pii=pair<int,int>;
using pll=pair<ll,ll>;
using vpll=vector<pll>;
using tll=tuple<ll,ll>;
using tlll=tuple<ll,ll,ll>;
using vs=vector<string>;
#define all(a) a.begin(),a.end()
#define rall(a) a.rbegin(),a.rend()
#define rep(i,n) range(i,0,n)
#define rrep(i,n) for(ll i=(n)-1;i>=0;i--)
#define range(i,a,n) for(ll i=(a);i<(n);i++)
#define sz(x) (int)(x).size()
#define LINF ((ll)1ll<<60)
#define INF ((int)1<<30)
#define EPS (1e-9)
#define MOD (1000000007ll)
//#define MOD (998244353ll)
#define fcout(a) cout<<setprecision(a)<<fixed
#define fs first
#define sc second
#define PI 3.1415926535897932384
int dx[]={1,0,-1,0,1,-1,-1,1},dy[]={0,1,0,-1,1,1,-1,-1};
template<class T>bool chmax(T&a,T b){if(a<b){a=b; return true;}return false;}
template<class T>bool chmin(T&a,T b){if(a>b){a=b; return true;}return false;}
template<class S>S acm(vector<S>&a){return accumulate(all(a),S());}
template<class S>S max(vector<S>&a){return *max_element(all(a));}
template<class S>S min(vector<S>&a){return *min_element(all(a));}
void YN(bool b){cout<<(b?"YES":"NO")<<"\n";}
void Yn(bool b){cout<<(b?"Yes":"No")<<"\n";}
void yn(bool b){cout<<(b?"yes":"no")<<"\n";}
int sgn(const double&r){return (r>EPS)-(r<-EPS);} // a>0 : sgn(a)>0
int sgn(const double&a,const double&b){return sgn(a-b);} // b<=c : sgn(b,c)<=0
int popcnt(int x){return __builtin_popcount(x);}
int popcnt(ll x){return __builtin_popcountll(x);}
ll max(int a,ll b){return max((ll)a,b);} ll max(ll a,int b){return max(a,(ll)b);}
template<class T>void puta(T&&t){cout<<t<<"\n";}
template<class H,class...T>void puta(H&&h,T&&...t){cout<<h<<' ';puta(t...);}
template<class S,class T>ostream&operator<<(ostream&os,pair<S,T>p){os<<"["<<p.first<<", "<<p.second<<"]";return os;}
template<class S>auto&operator<<(ostream&os,vector<S>t){bool a=1; for(auto s:t){os<<(a?"":" ")<<s;a=0;} return os;}
int main(){
cin.tie(0);
ios::sync_with_stdio(false);
ll h,w,ans=0;
cin>>h>>w;
vvl vv(h,vl(w)),sum(h+1,vl(w+1));
rep(i,h)rep(j,w){
cin>>vv[i][j];
if((i+j)%2==1)vv[i][j]*=-1;
}
rep(i,h)rep(j,w){
sum[i+1][j+1]=sum[i+1][j]+vv[i][j];
}
rep(i,h)rep(j,w+1){
sum[i+1][j]+=sum[i][j];
}
rep(i,h)rep(j,w)rep(k,i+1)rep(l,j+1){
ll scr=sum[i+1][j+1]-sum[k][j+1]-sum[i+1][l]+sum[k][l];
if(scr==0)chmax(ans,(i-k+1)*(j-l+1));
}
puta(ans);
}
| [
"[email protected]"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.