blob_id
stringlengths 40
40
| directory_id
stringlengths 40
40
| path
stringlengths 4
201
| content_id
stringlengths 40
40
| detected_licenses
sequencelengths 0
85
| license_type
stringclasses 2
values | repo_name
stringlengths 7
100
| snapshot_id
stringlengths 40
40
| revision_id
stringlengths 40
40
| branch_name
stringclasses 260
values | visit_date
timestamp[us] | revision_date
timestamp[us] | committer_date
timestamp[us] | github_id
int64 11.4k
681M
⌀ | star_events_count
int64 0
209k
| fork_events_count
int64 0
110k
| gha_license_id
stringclasses 17
values | gha_event_created_at
timestamp[us] | gha_created_at
timestamp[us] | gha_language
stringclasses 80
values | src_encoding
stringclasses 28
values | language
stringclasses 1
value | is_vendor
bool 1
class | is_generated
bool 2
classes | length_bytes
int64 8
9.86M
| extension
stringclasses 52
values | content
stringlengths 8
9.86M
| authors
sequencelengths 1
1
| author
stringlengths 0
119
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
b9776e82e9b6ad23756076a20f92d7c410d502f4 | eaaf681680e36b249fc898aef5debba4ca5ec442 | /codeforces/749/A.cpp | cc44b80cfe15c439f5d9f41276f71549139921ad | [] | no_license | anshbargoti/ProblemSolving | a832cfc28820bd7dd76899d3d6859bae4f3e995e | 28da9995dc8ebba1db560d598b2422bd9873671f | refs/heads/master | 2023-05-06T12:19:42.448925 | 2021-05-16T08:10:00 | 2021-05-25T01:46:01 | 323,315,306 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 788 | cpp | #include<bits/stdc++.h>
using namespace std;
#define int long long
// const int MOD = 1000000007;
int powerf(int x, int n)
{
int res = 1;
for (int i = 1; i <= n; i++)
res *= x;
return res;
}
void striker()
{
int n;
cin >> n;
int x = n / 2;
cout << x << "\n";
for (int i = 1; i < x; i++)
cout << 2 << " ";
if (n % 2 == 0)
cout << 2;
else
cout << 3;
}
int32_t main(){
ios_base::sync_with_stdio(false);
cin.tie(nullptr);
#ifndef ONLINE_JUDGE
freopen("input.txt", "r", stdin);
freopen("output.txt", "w", stdout);
#endif
int t = 1;
// cin >> t;
for (int i = 0; i < t; i++)
{
//cout<<"#Case: "<<i+1<<endl;
striker();
cout << endl;
}
return 0;
} | [
"[email protected]"
] | |
563960da9f17866134129ff6cd2695ac693d4314 | 43a2fbc77f5cea2487c05c7679a30e15db9a3a50 | /Cpp/Internal (Offsets Only)/SDK/CS_HitBySnakePoison_classes.h | a2b656a1e407c52cc47d42377bda250ecc40a8f9 | [] | no_license | zH4x/SoT-Insider-SDK | 57e2e05ede34ca1fd90fc5904cf7a79f0259085c | 6bff738a1b701c34656546e333b7e59c98c63ad7 | refs/heads/main | 2023-06-09T23:10:32.929216 | 2021-07-07T01:34:27 | 2021-07-07T01:34:27 | 383,638,719 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 748 | h | #pragma once
// Name: SoT-Insider, Version: 1.102.2382.0
/*!!DEFINE!!*/
/*!!HELPER_DEF!!*/
/*!!HELPER_INC!!*/
#ifdef _MSC_VER
#pragma pack(push, 0x01)
#endif
namespace CG
{
//---------------------------------------------------------------------------
// Classes
//---------------------------------------------------------------------------
// BlueprintGeneratedClass CS_HitBySnakePoison.CS_HitBySnakePoison_C
// 0x0000 (FullSize[0x0140] - InheritedSize[0x0140])
class UCS_HitBySnakePoison_C : public UCameraShake
{
public:
static UClass* StaticClass()
{
static auto ptr = UObject::FindClass("BlueprintGeneratedClass CS_HitBySnakePoison.CS_HitBySnakePoison_C");
return ptr;
}
};
}
#ifdef _MSC_VER
#pragma pack(pop)
#endif
| [
"[email protected]"
] | |
ec63e0b6d284fef0832c616d50e3643228fc7fa5 | 5ac4199d968f301e01ef741fe7d1d162c4f82921 | /Samples/Mathematics/BSplineCurveReduction/BSplineCurveReductionWindow3.h | 445942de99af91cd8223d1aa062da91be2f1bfb4 | [
"LicenseRef-scancode-unknown-license-reference",
"BSL-1.0"
] | permissive | kabukunz/GeometricTools | 9eada1b0d8b1447398e8739c9684e5ed14d4cf96 | bbc55cdef89a877f06310fdb6c6248205eae704b | refs/heads/master | 2020-11-25T11:54:23.772441 | 2019-12-17T16:11:32 | 2019-12-17T16:11:32 | 228,645,271 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 668 | h | // David Eberly, Geometric Tools, Redmond WA 98052
// Copyright (c) 1998-2019
// Distributed under the Boost Software License, Version 1.0.
// https://www.boost.org/LICENSE_1_0.txt
// https://www.geometrictools.com/License/Boost/LICENSE_1_0.txt
// Version: 4.0.2019.08.13
#pragma once
#include <Applications/Window3.h>
using namespace gte;
class BSplineCurveReductionWindow3 : public Window3
{
public:
BSplineCurveReductionWindow3(Parameters& parameters);
virtual void OnIdle() override;
private:
bool SetEnvironment();
void CreateScene();
std::shared_ptr<Visual> mOriginal;
std::shared_ptr<Visual> mReduced;
};
| [
"[email protected]"
] | |
4f8ef0dc1582455936755fdcc6e741e410f8d75f | eb7f2f5953dfd0d066ed6727df3a554b705ce8cc | /sw/src/extern/ptam/src/SmallBlurryImage.cc | 3105339d2d6a73038032a6c2777b43f42bae0163 | [] | no_license | zangel/uquad | 3de785a04ad9bd6e5a146caf1eefa186ba58efd4 | 7a314f1a2f2a0db549251c48aba991c5cce4d585 | refs/heads/master | 2021-01-21T12:58:12.805486 | 2016-06-02T22:21:35 | 2016-06-02T22:21:35 | 51,906,573 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 8,586 | cc | // Copyright 2008 Isis Innovation Limited
#include "SmallBlurryImage.h"
#include <cvd/utility.h>
#include <cvd/convolution.h>
#include <cvd/vision.h>
#include <TooN/se2.h>
#include <TooN/Cholesky.h>
#include <TooN/wls.h>
using namespace CVD;
using namespace std;
ImageRef SmallBlurryImage::mirSize(-1,-1);
SmallBlurryImage::SmallBlurryImage(KeyFrame &kf, double dBlur)
{
mbMadeJacs = false;
MakeFromKF(kf, dBlur);
}
SmallBlurryImage::SmallBlurryImage()
{
mbMadeJacs = false;
}
// Make a SmallBlurryImage from a KeyFrame This fills in the mimSmall
// image (Which is just a small un-blurred version of the KF) and
// mimTemplate (which is a floating-point, zero-mean blurred version
// of the above)
void SmallBlurryImage::MakeFromKF(KeyFrame &kf, double dBlur)
{
if(mirSize[0] == -1)
mirSize = kf.aLevels[3].im.size() / 2;
mbMadeJacs = false;
mimSmall.resize(mirSize);
mimTemplate.resize(mirSize);
mbMadeJacs = false;
halfSample(kf.aLevels[3].im, mimSmall);
ImageRef ir;
unsigned int nSum = 0;
do
nSum += mimSmall[ir];
while(ir.next(mirSize));
float fMean = ((float) nSum) / mirSize.area();
ir.home();
do
mimTemplate[ir] = mimSmall[ir] - fMean;
while(ir.next(mirSize));
convolveGaussian(mimTemplate, dBlur);
}
// Make the jacobians (actually, no more than a gradient image)
// of the blurred template
void SmallBlurryImage::MakeJacs()
{
mimImageJacs.resize(mirSize);
// Fill in the gradient image
ImageRef ir;
do
{
Vector<2> &v2Grad = mimImageJacs[ir];
if(mimTemplate.in_image_with_border(ir,1))
{
v2Grad[0] = mimTemplate[ir + ImageRef(1,0)] - mimTemplate[ir - ImageRef(1,0)];
v2Grad[1] = mimTemplate[ir + ImageRef(0,1)] - mimTemplate[ir - ImageRef(0,1)];
// N.b. missing 0.5 factor in above, this will be added later.
}
else
v2Grad = Zeros;
}
while(ir.next(mirSize));
mbMadeJacs = true;
};
// Calculate the zero-mean SSD between one image and the next.
// Since both are zero mean already, just calculate the SSD...
double SmallBlurryImage::ZMSSD(SmallBlurryImage &other)
{
double dSSD = 0.0;
ImageRef ir;
do
{
double dDiff = mimTemplate[ir] - other.mimTemplate[ir];
dSSD += dDiff * dDiff;
}
while(ir.next(mirSize));
return dSSD;
}
// Find an SE2 which best aligns an SBI to a target
// Do this by ESM-tracking a la Benhimane & Malis
pair<SE2<>,double> SmallBlurryImage::IteratePosRelToTarget(SmallBlurryImage &other, int nIterations)
{
SE2<> se2CtoC;
SE2<> se2WfromC;
ImageRef irCenter = mirSize / 2;
se2WfromC.get_translation() = vec(irCenter);
pair<SE2<>, double> result_pair;
if(!other.mbMadeJacs)
{
cerr << "You spanner, you didn't make the jacs for the target." << endl;
assert(other.mbMadeJacs);
};
double dMeanOffset = 0.0;
Vector<4> v4Accum;
Vector<10> v10Triangle;
Image<float> imWarped(mirSize);
double dFinalScore = 0.0;
for(int it = 0; it<nIterations; it++)
{
dFinalScore = 0.0;
v4Accum = Zeros;
v10Triangle = Zeros; // Holds the bottom-left triangle of JTJ
Vector<4> v4Jac;
v4Jac[3] = 1.0;
SE2<> se2XForm = se2WfromC * se2CtoC * se2WfromC.inverse();
// Make the warped current image template:
Vector<2> v2Zero = Zeros;
CVD::transform(mimTemplate, imWarped, se2XForm.get_rotation().get_matrix(), se2XForm.get_translation(), v2Zero, -9e20f);
// Now compare images, calc differences, and current image jacobian:
ImageRef ir;
do
{
if(!imWarped.in_image_with_border(ir,1))
continue;
float l,r,u,d,here;
l = imWarped[ir - ImageRef(1,0)];
r = imWarped[ir + ImageRef(1,0)];
u = imWarped[ir - ImageRef(0,1)];
d = imWarped[ir + ImageRef(0,1)];
here = imWarped[ir];
if(l + r + u + d + here < -9999.9) // This means it's out of the image; c.f. the -9e20f param to transform.
continue;
Vector<2> v2CurrentGrad;
v2CurrentGrad[0] = r - l; // Missing 0.5 factor
v2CurrentGrad[1] = d - u;
Vector<2> v2SumGrad = 0.25 * (v2CurrentGrad + other.mimImageJacs[ir]);
// Why 0.25? This is from missing 0.5 factors: One for
// the fact we average two gradients, the other from
// each gradient missing a 0.5 factor.
v4Jac[0] = v2SumGrad[0];
v4Jac[1] = v2SumGrad[1];
v4Jac[2] = -(ir.y - irCenter.y) * v2SumGrad[0] + (ir.x - irCenter.x) * v2SumGrad[1];
// v4Jac[3] = 1.0;
double dDiff = imWarped[ir] - other.mimTemplate[ir] + dMeanOffset;
dFinalScore += dDiff * dDiff;
v4Accum += dDiff * v4Jac;
// Speedy fill of the LL triangle of JTJ:
double *p = &v10Triangle[0];
*p++ += v4Jac[0] * v4Jac[0];
*p++ += v4Jac[1] * v4Jac[0];
*p++ += v4Jac[1] * v4Jac[1];
*p++ += v4Jac[2] * v4Jac[0];
*p++ += v4Jac[2] * v4Jac[1];
*p++ += v4Jac[2] * v4Jac[2];
*p++ += v4Jac[0];
*p++ += v4Jac[1];
*p++ += v4Jac[2];
*p++ += 1.0;
}
while(ir.next(mirSize));
Vector<4> v4Update;
// Solve for JTJ-1JTv;
{
Matrix<4> m4;
int v=0;
for(int j=0; j<4; j++)
for(int i=0; i<=j; i++)
m4[j][i] = m4[i][j] = v10Triangle[v++];
Cholesky<4> chol(m4);
v4Update = chol.backsub(v4Accum);
}
SE2<> se2Update;
se2Update.get_translation() = -v4Update.slice<0,2>();
se2Update.get_rotation() = SO2<>::exp(-v4Update[2]);
se2CtoC = se2CtoC * se2Update;
dMeanOffset -= v4Update[3];
}
result_pair.first = se2CtoC;
result_pair.second = dFinalScore;
return result_pair;
}
// What is the 3D camera rotation (zero trans) SE3<> which causes an
// input image SO2 rotation?
SE3<> SmallBlurryImage::SE3fromSE2(SE2<> se2, ATANCamera camera)
{
// Do this by projecting two points, and then iterating the SE3<> (SO3
// actually) until convergence. It might seem stupid doing this so
// precisely when the whole SE2-finding is one big hack, but hey.
camera.SetImageSize(mirSize);
Vector<2> av2Turned[2]; // Our two warped points in pixels
av2Turned[0] = vec(mirSize / 2) + se2 * vec(ImageRef(5,0));
av2Turned[1] = vec(mirSize / 2) + se2 * vec(ImageRef(-5,0));
Vector<3> av3OrigPoints[2]; // 3D versions of these points.
av3OrigPoints[0] = unproject(camera.UnProject(vec(mirSize / 2) + vec(ImageRef(5,0))));
av3OrigPoints[1] = unproject(camera.UnProject(vec(mirSize / 2) + vec(ImageRef(-5,0))));
SO3<> so3;
for(int it = 0; it<3; it++)
{
WLS<3> wls; // lazy; no need for the 'W'
wls.add_prior(10.0);
for(int i=0; i<2; i++)
{
// Project into the image to find error
Vector<3> v3Cam = so3 * av3OrigPoints[i];
Vector<2> v2Implane = project(v3Cam);
Vector<2> v2Pixels = camera.Project(v2Implane);
Vector<2> v2Error = av2Turned[i] - v2Pixels;
Matrix<2> m2CamDerivs = camera.GetProjectionDerivs();
Matrix<2,3> m23Jacobian;
double dOneOverCameraZ = 1.0 / v3Cam[2];
for(int m=0; m<3; m++)
{
const Vector<3> v3Motion = SO3<>::generator_field(m, v3Cam);
Vector<2> v2CamFrameMotion;
v2CamFrameMotion[0] = (v3Motion[0] - v3Cam[0] * v3Motion[2] * dOneOverCameraZ) * dOneOverCameraZ;
v2CamFrameMotion[1] = (v3Motion[1] - v3Cam[1] * v3Motion[2] * dOneOverCameraZ) * dOneOverCameraZ;
m23Jacobian.T()[m] = m2CamDerivs * v2CamFrameMotion;
};
wls.add_mJ(v2Error[0], m23Jacobian[0], 1.0);
wls.add_mJ(v2Error[1], m23Jacobian[1], 1.0);
};
wls.compute();
Vector<3> v3Res = wls.get_mu();
so3 = SO3<>::exp(v3Res) * so3;
};
SE3<> se3Result;
se3Result.get_rotation() = so3;
return se3Result;
}
| [
"[email protected]"
] | |
b9acf1dd703310265140cda46d898bca3f442fc1 | 9b0eaf00a1dd59db9183360e4a032fdc67918fdc | /user.h | 99443b2acb683c97f094799d5cd73b5ff9e4d951 | [] | no_license | Costecc/TexasHoldem | addbb85e3f135ada96fe55118077e44bd3d04f31 | d54a49ed127b550e94fcccfa6ec53ca330dc44f9 | refs/heads/master | 2020-03-12T11:19:18.372622 | 2018-06-04T18:52:22 | 2018-06-04T18:52:22 | 130,593,872 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,490 | h | #ifndef USER_H
#define USER_H
#include <string>
#include <iostream>
#include "player.h"
using namespace std;
/**
* @brief Klasa User obsluguje zachowania gracza oraz odpowiada za interakcje z nim.
* Dziedziczy po klasie Player
*/
class User : public Player
{
string nick;
public:
/**
* @brief Konstruktor klasy User, inicjalizujacy nick gracza
*/
User();
/**
* @brief Destruktor klasy User
*/
~User();
/**
* @brief Metoda wyswietlajaca biezacy stan konta obu graczy
* @param userStack : Stan konta gracza realnego
* @param botStack : Stan konta bota
*/
void displayStacks(int userStack, int botStack);
/**
* @brief Metoda wyswietlajaca biezaca faze gry
* @param phase : Faza gry, np. flop czy turn
*/
void showPhase(int phase);
/**
* @brief Metoda pokazujaca dane karty
* @param kind : Rodzaj karty np. walet
* @param colour : Kolor karty np. pik
*/
void showCards(int kind, int colour);
/**
* @brief Komunikat wyswietlajacy zwyciezce gry
* @param winner : Zmienna informujaca o zwyciezcy
*/
string showWinner(int winner);
/**
* @brief Komunikat odnosnie mozliwosci zakladu gracza
* @param mBet : Minimalny zaklad jaki moze zagrac gracz
* @param money : Maksymalny zaklad gracza
*/
void playerDecisionOption(int mBet, int money);
/**
* @brief Komunikat wyswietlajacy decyzje bota
* @param decision : Decyzja bota, np przebicie lub pas
* @param botBet : Suma zakladu bota
*/
void botDecision(int decision, int botBet);
/**
* @brief Komunikat wyswietlajacy decyzje gracza
* @param decision : Decyzja gracza, np przebicie lub pas
*/
void playerDecision(int decision);
/**
* @brief Podjecie decyzji przez gracza
* @param minBet : Minimalny mozliwy zaklad gracza
* @param maxBet : Maksymalny mozliwy zaklad gracza
*/
int makeBet(int minBet, int maxBet);
/**
* @brief Komunikat o rozpoczeniu nastepnego rozdania
* @param round : Numer biezacego rozdania
*/
void nextRound(int round);
/**
* @brief Wyswietlenie biezacej puli
* @param pot : Biezaca pula
*/
void showPot(int pot);
/**
* @brief Komunikat pytajacy o wczytanie gry z pliku
*/
bool readGameMessage();
/**
* @brief Krotka instrukcja na temat gry
*/
void instructionMessage();
};
#endif // USER_H
| [
"="
] | = |
16bc86898a3938f80043a10d0d18dc026705b5c4 | e75cc18f64db23b9c1d304c39fb74ed083d9feee | /assignment-5/Tetromino.h | d9c97f184fdbfb55dba404e2ae4149aa63feeeb5 | [] | no_license | ChrisProgramming2018/cpp-course | 0b790e29ca239639dac70fa163d8af186ba7f7c7 | 398c0da3e49e67440ab663bb61d45eaf2dd56d2a | refs/heads/master | 2020-04-06T12:20:27.792277 | 2018-12-22T14:42:30 | 2018-12-22T14:42:30 | 157,451,729 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,351 | h | // Copyright 2018
// Computer Science
// Author: Christian Leininger [email protected]
#ifndef ASSIGNMENT_5_TETROMINO_H_
#define ASSIGNMENT_5_TETROMINO_H_
#include <gtest/gtest.h>
// Class for a single Tetromino.
class Tetromino {
public:
// Reset Tetromino to given kind in starting position at the top.
void reset(int kindOfTetromino);
// Move Tetromino according to last key. If reverse == true, do the opposite.
void move(int key, bool reverse);
// FRIEND_TEST(TetrisTest, move);
// Rotate Tetromino by n times 90 degrees clockwise.
void rotate(int n);
// FRIEND_TEST(TetrisTest, rotate);
// Show Tetromino at current position. If showOrDelete == true, draw in
// inverse video, otherwise draw spaces to delete it. If bottomReached, draw
// in red.
void show(bool showOrDelete, bool bottomReached);
private:
friend class Structure;
// Stretch of a pixel;
static const int _sx = 5;
static const int _sy = 3;
// Absolute position of the Tetromino.
int _tx;
int _ty;
// Relative positions of the four parts of the Tetromino.
int _txr[4];
int _tyr[4];
FRIEND_TEST(TetrisTest, move);
FRIEND_TEST(TetrisTest, rotate);
FRIEND_TEST(TetrisTest, reset);
FRIEND_TEST(StructureTest, addTetromino);
FRIEND_TEST(StructureTest, checkCollision);
};
#endif // ASSIGNMENT_5_TETROMINO_H_
| [
"[email protected]"
] | |
5eb3fffd63878b2f5a6c4705fccaea54cbe9aa24 | 72852e07bb30adbee608275d6048b2121a5b9d82 | /algorithms/problem_0678/other1.cpp | 38d439f99f1684b771b9b351846e7812f5a2149f | [] | no_license | drlongle/leetcode | e172ae29ea63911ccc3afb815f6dbff041609939 | 8e61ddf06fb3a4fb4a4e3d8466f3367ee1f27e13 | refs/heads/master | 2023-01-08T16:26:12.370098 | 2023-01-03T09:08:24 | 2023-01-03T09:08:24 | 81,335,609 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 618 | cpp | class Solution {
public:
bool checkValidString(string s) {
stack<int> open,ast;
for(int i=0;i<s.length();i++)
{
if(s[i] == ')')
{
if(!open.empty()) open.pop();
else if(!ast.empty()) ast.pop();
else return false;
}
else if(s[i] == '(') open.push(i);
else ast.push(i);
}
while(!open.empty() && !ast.empty())
{
if(open.top() > ast.top()) return false;
open.pop();
ast.pop();
}
return open.empty();
}
};
| [
"[email protected]"
] | |
fef67dfc1d769ec287cef253bf9d8207a6eabcec | 2a7e77565c33e6b5d92ce6702b4a5fd96f80d7d0 | /fuzzedpackages/Buddle/src/BentIdentity.h | adfe2631cd1477f58d6987d3fc7c6c9847319753 | [] | no_license | akhikolla/testpackages | 62ccaeed866e2194652b65e7360987b3b20df7e7 | 01259c3543febc89955ea5b79f3a08d3afe57e95 | refs/heads/master | 2023-02-18T03:50:28.288006 | 2021-01-18T13:23:32 | 2021-01-18T13:23:32 | 329,981,898 | 7 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 894 | h |
#ifndef xxBENTIDENTITY_H
#define xxBENTIDENTITY_H
class BentIdentity{
private:
int p;
int n;
arma::mat Out;
arma::mat dOut;
public:
BentIdentity(){
n=0;
p=0;
}
BentIdentity(int xp, int xn) // Constructor
: Out(xp, xn), dOut(xp, xn) { // Default matrix member variable initialization
n = xn;
p = xp;
}
arma::mat Get_Out();
arma::mat Get_dOut();
void forward(arma::mat xX);
void backward(arma::mat xX, arma::mat xdOut);
};
arma::mat BentIdentity::Get_Out(){
return Out;
}
arma::mat BentIdentity::Get_dOut(){
return dOut;
}
void BentIdentity::forward(arma::mat X){
arma::mat XX = X%X+1;
Out = ( X + ( sqrt(XX) -1 )/2 ) ;
}
void BentIdentity::backward(arma::mat xX, arma::mat xdOut){
arma::mat XX = xX%xX+1;
dOut = xdOut% (1+ 0.5*xX /sqrt(1+xX%xX) ) ;
}
#endif
| [
"[email protected]"
] | |
287f1eda8528d3d1f28e991e15737a2b94f10029 | 5a34f38e1d0b6a925bb602383705f0e45b449dff | /interviews/incsa.cpp | 4b09539894710903a7ff0b7886b8b683813357f6 | [] | no_license | samuraiexx/competitiveProgramming | 15fcbcf75114c80d112473e5ce9d69b9f33d5280 | 1862e381d0d7aecc0082f2416950cd18b26858d4 | refs/heads/master | 2021-06-10T20:53:39.039074 | 2019-03-25T01:02:21 | 2019-03-25T01:02:21 | 106,463,296 | 0 | 1 | null | 2019-10-20T21:18:08 | 2017-10-10T19:43:09 | C++ | UTF-8 | C++ | false | false | 412 | cpp | #include<bits/stdc++.h>
using namespace std;
int cntInc(vector<int> &A) {
int n = A.size();
long long ans = 0;
const int mod = 1e9 + 7;
for(int i = 0; i < n;){
int j;
for(j = i + 1; j < n and A[i - 1] < A[i]; j++)
ans += (j - i)*(j - i - 1)/2 + (j - i);
i = j;
cout << ans << endl;
}
return ans%mod;
}
int main(){
vector<int> v = {4, 5, 1, 2};
cout << cntInc(v) << endl;
}
| [
"[email protected]"
] | |
5b1770e1e775cc3b6339c474afe795c8028c718e | fce6eb121e925632e111596ae976e5636516b2bf | /utils/src/io/reader.cpp | 7c32ef6f218c0cb480f53e7293c368e1ab8da738 | [] | no_license | MatrixPlayer/forlfs | f99de6f31ac1bee7caeec48324f9f25eb1a41d33 | 9ed9b7b857ce61e8e4d2d0adbe3a4bab07c1304f | refs/heads/master | 2021-04-15T07:34:56.832962 | 2017-02-08T05:38:38 | 2017-02-08T05:38:38 | 126,415,271 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 817 | cpp | /*============================================================================
* File Name : reader.cpp
* Author : [email protected]
* Version : 1.0.0.0
* Copyright : Copyright 2016 DeepGlint Inc.
* Created on : 04/15/2016
* Description :
* ==========================================================================*/
#include <fstream>
#include "reader.h"
using namespace std;
using namespace dg;
namespace dg{
Reader::Reader()
{
}
Reader::~Reader()
{
}
vector<uchar> Reader::Read(const char *filename)
{
streampos file_size;
ifstream file(filename, ios::binary);
file.seekg(0, ios::end);
file_size = file.tellg();
file.seekg(0, ios::beg);
std::vector<uchar> file_data(file_size);
file.read((char *)&file_data[0], file_size);
return file_data;
}
} | [
"[email protected]"
] | |
4a33c9e6af3919362dad3f8994b546b82f34a32f | ae3996db7afd26c852a14a5ba472a6aafea96d9f | /Source/BansheeVulkanRenderAPI/Include/BsVulkanQueue.h | f0c0706d1bbab98bd534dcf43a2fffb43cc2b9ee | [] | no_license | kevinfyc/BansheeEngine | 0ce45fad0a34dbbbc3a06369b47bcabc98694653 | e51517f40ec49068174d22d49968f73c10a094c2 | refs/heads/master | 2021-01-11T09:13:56.819177 | 2017-02-08T15:45:27 | 2017-02-08T15:45:27 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,761 | h | //********************************** Banshee Engine (www.banshee3d.com) **************************************************//
//**************** Copyright (c) 2016 Marko Pintera ([email protected]). All rights reserved. **********************//
#pragma once
#include "BsVulkanPrerequisites.h"
namespace bs { namespace ct
{
/** @addtogroup Vulkan
* @{
*/
/** Wrapper for the Vulkan device queue. */
class VulkanQueue
{
public:
VulkanQueue(VulkanDevice& device, VkQueue queue, GpuQueueType type, UINT32 index);
/** Returns the internal handle to the Vulkan queue object. */
VkQueue getHandle() const { return mQueue; }
/** Returns the device that owns the queue. */
VulkanDevice& getDevice() const { return mDevice; }
/** Returns the type of the queue. */
GpuQueueType getType() const { return mType; }
/** Returns the unique index of the queue, for its type. */
UINT32 getIndex() const { return mIndex; }
/**
* Checks if anything is currently executing on this queue.
*
* @note This status is only updated after a VulkanCommandBufferManager::refreshStates() call.
*/
bool isExecuting() const;
/** Submits the provided command buffer on the queue. */
void submit(VulkanCmdBuffer* cmdBuffer, VulkanSemaphore** waitSemaphores, UINT32 semaphoresCount);
/**
* Stores information about a submit internally, but doesn't actually execute it. The intended use is to queue
* multiple submits and execute them all at once using submitQueued(), ensuring better performance than queuing them
* all individually.
*/
void queueSubmit(VulkanCmdBuffer* cmdBuffer, VulkanSemaphore** waitSemaphores, UINT32 semaphoresCount);
/** Submits all previously queued commands buffers, as recorded by queueSubmit(). */
void submitQueued();
/**
* Presents the back buffer of the provided swap chain.
*
* @param[in] swapChain Swap chain whose back buffer to present.
* @param[in] waitSemaphores Optional semaphores to wait on before presenting the queue.
* @param[in] semaphoresCount Number of semaphores in the @p semaphores array.
*/
void present(VulkanSwapChain* swapChain, VulkanSemaphore** waitSemaphores, UINT32 semaphoresCount);
/** Blocks the calling thread until all operations on the queue finish. */
void waitIdle() const;
/**
* Checks if any of the active command buffers finished executing on the queue and updates their states
* accordingly.
*
* @param[in] queueEmpty Set to true if the caller guarantees the queue will be empty (e.g. on shutdown). This
* allows the system to free all needed resources.
*/
void refreshStates(bool queueEmpty = false);
/** Returns the last command buffer that was submitted on this queue. */
VulkanCmdBuffer* getLastCommandBuffer() const { return mLastCommandBuffer; }
protected:
/**
* Generates a submit-info structure that can be used for submitting the command buffer to the queue, but doesn't
* perform the actual submit.
*/
void getSubmitInfo(VkCommandBuffer* cmdBuffer, VkSemaphore* signalSemaphores, UINT32 numSignalSemaphores,
VkSemaphore* waitSemaphores, UINT32 numWaitSemaphores, VkSubmitInfo& submitInfo);
/**
* Prepares a list of semaphores that can be provided to submit or present calls. *
*
* @param[in] inSemaphores External wait semaphores that need to be waited on.
* @param[out] outSemaphores All semaphores (external ones, and possibly additional ones), as Vulkan handles.
* @param[in, out] semaphoresCount Number of semaphores in @p inSemaphores when calling. When method returns this
* will contain number of semaphores in @p outSemaphores.
*/
void prepareSemaphores(VulkanSemaphore** inSemaphores, VkSemaphore* outSemaphores, UINT32& semaphoresCount);
/** Information about a single submitted command buffer. */
struct SubmitInfo
{
SubmitInfo(VulkanCmdBuffer* cmdBuffer, UINT32 submitIdx, UINT32 numSemaphores, UINT32 numCommandBuffers)
: cmdBuffer(cmdBuffer), submitIdx(submitIdx), numSemaphores(numSemaphores)
, numCommandBuffers(numCommandBuffers)
{ }
VulkanCmdBuffer* cmdBuffer;
UINT32 submitIdx;
UINT32 numSemaphores;
UINT32 numCommandBuffers;
};
VulkanDevice& mDevice;
VkQueue mQueue;
GpuQueueType mType;
UINT32 mIndex;
VkPipelineStageFlags mSubmitDstWaitMask[BS_MAX_UNIQUE_QUEUES];
Vector<SubmitInfo> mQueuedBuffers;
Vector<VulkanSemaphore*> mQueuedSemaphores;
List<SubmitInfo> mActiveSubmissions;
Queue<VulkanCmdBuffer*> mActiveBuffers;
Queue<VulkanSemaphore*> mActiveSemaphores;
VulkanCmdBuffer* mLastCommandBuffer;
bool mLastCBSemaphoreUsed;
UINT32 mNextSubmitIdx;
Vector<VkSemaphore> mSemaphoresTemp;
};
/** @} */
}} | [
"[email protected]"
] | |
b3dc87b8eed02e52196faa7e0b53b4958d349a19 | 7a5184494d95dced060b05ce7ab442636bd02734 | /OrionUO/Wisp/WispMappedFile.cpp | e774b5df24409107fc36807f1192497219a2c260 | [
"MIT"
] | permissive | Feramor/OrionUO | eeb76b25b468f2912e2e58917458e34f3ed17d51 | 0d58b611eec0e558d608437475ff2a7a5d3735d0 | refs/heads/master | 2019-07-16T13:00:59.644292 | 2017-12-23T08:31:51 | 2017-12-23T08:31:51 | 115,181,383 | 1 | 0 | null | 2017-12-23T08:13:04 | 2017-12-23T08:13:04 | null | UTF-8 | C++ | false | false | 2,926 | cpp | // This is an open source non-commercial project. Dear PVS-Studio, please check it.
// PVS-Studio Static Code Analyzer for C, C++ and C#: http://www.viva64.com
//----------------------------------------------------------------------------------
#include "stdafx.h"
namespace WISP_FILE
{
//----------------------------------------------------------------------------------
string g_WispMappedFileError = "";
//----------------------------------------------------------------------------------
CMappedFile::CMappedFile()
: WISP_DATASTREAM::CDataReader()
{
}
//----------------------------------------------------------------------------------
CMappedFile::~CMappedFile()
{
Unload();
}
//----------------------------------------------------------------------------------
bool CMappedFile::Load()
{
WISPFUN_DEBUG("c7_f1");
bool result = false;
m_Size = GetFileSize(m_File, NULL);
if (m_Size > 0)
{
m_Map = CreateFileMapping(m_File, NULL, 2, 0, NULL, NULL);
if (m_Map != NULL)
{
m_Start = (puchar)MapViewOfFile(m_Map, FILE_MAP_READ, 0, 0, m_Size);
result = (m_Start != NULL);
if (!result)
{
CloseHandle(m_Map);
CloseHandle(m_File);
m_Map = NULL;
m_File = INVALID_HANDLE_VALUE;
}
else
SetData(m_Start, m_Size);
}
else
{
CloseHandle(m_File);
m_File = INVALID_HANDLE_VALUE;
}
}
else
{
CloseHandle(m_File);
m_File = INVALID_HANDLE_VALUE;
}
return result;
}
//----------------------------------------------------------------------------------
bool CMappedFile::Load(const string &path)
{
WISPFUN_DEBUG("c7_f2");
bool result = false;
if (PathFileExistsA(path.c_str()))
{
Unload();
m_File = CreateFileA(path.c_str(), GENERIC_READ, 1, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
if (m_File != INVALID_HANDLE_VALUE)
result = Load();
}
if (!result)
g_WispMappedFileError = path;
return result;
}
//----------------------------------------------------------------------------------
bool CMappedFile::Load(const wstring &path)
{
WISPFUN_DEBUG("c7_f3");
bool result = false;
if (PathFileExistsW(path.c_str()))
{
Unload();
m_File = CreateFileW(path.c_str(), GENERIC_READ, 1, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
if (m_File != INVALID_HANDLE_VALUE)
result = Load();
}
if (!result)
g_WispMappedFileError = ToString(path);
return result;
}
//----------------------------------------------------------------------------------
void CMappedFile::Unload()
{
WISPFUN_DEBUG("c7_f4");
if (m_Start != NULL)
UnmapViewOfFile(m_Start);
if (m_Map != NULL)
{
CloseHandle(m_Map);
m_Map = 0;
}
if (m_File != INVALID_HANDLE_VALUE)
{
CloseHandle(m_File);
m_File = INVALID_HANDLE_VALUE;
}
SetData(NULL, 0);
}
//----------------------------------------------------------------------------------
}; //namespace
//----------------------------------------------------------------------------------
| [
"[email protected]"
] | |
c70b5f30f46b275ef638db5df3841c52a7694100 | da4d8e4510012a849349fc9c943d43dbf55b18ff | /OPTRE_Hud/z_HUD_Marine/AmmoCounters/GLASS_HUD_AmmoCount_PistolODST.hpp | b3184c6367c9b0f32b17a64b9db5685a72c12029 | [] | no_license | thedog88/OPTRE_DEV | fd02f59dded7958cf2b8f19c90ef818f695fa139 | 6ba99bbe1b76191abd0414cc017304435ceb2bde | refs/heads/master | 2021-01-09T20:59:10.634187 | 2017-06-06T23:43:46 | 2017-06-06T23:43:46 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,722 | hpp | class OPTRE_GLASS_HUD_AmmoCount_PistolODST
{
//onLoad = "";
idd = 8000;
duration = 99999;
class controls {
class RscPicture_1200: OPTRE_HUD_RscPicture
{
idc = 1200;
text = "\OPTRE_Hud\data\Bullets\ODST_Pistol.paa";
onLoad = "_array = (profileNamespace getVariable [""OPTRE_GLASS_HUDColourPictNEW"",[1,0.5,0,.95]]); (_this select 0) ctrlSetTextColor [ (_array select 0), (_array select 1), (_array select 2), ((_array select 3) / 3)];";
x = 0.881562 * safezoneW + safezoneX;
y = 0.093 * safezoneH + safezoneY;
w = 0.0670312 * safezoneW;
h = 0.011 * safezoneH;
};
class RscPicture_123: OPTRE_HUD_RscProgress
{
idc = 1200;
//text = "OPTRE_Hud\Data\Hud_ODST_1\hud_healthBar.paa";
texture = "\OPTRE_Hud\data\Bullets\ODST_Pistol.paa";
x = 0.881562 * safezoneW + safezoneX;
y = 0.093 * safezoneH + safezoneY;
w = 0.0670312 * safezoneW;
h = 0.011 * safezoneH;
colorText[] = {1,1,1,1};
onLoad = "uinamespace setvariable ['OPTRE_HUD_AmmoCountCurrent_1',(_this select 0)]; (_this select 0) ctrlSetTextColor (profileNamespace getVariable [""OPTRE_GLASS_HUDColourPictNEW"",[1,0.5,0,.8]]);";
colorBar[] = {1,1,1,1};
};
};
};
/*
////////////////////////////////////////////////////////
// GUI EDITOR OUTPUT START (by big_wilk, v1.063, #Xiqehe)
////////////////////////////////////////////////////////
class RscPicture_1200: RscPicture
{
idc = 1200;
text = "\OPTRE_Hud\data\Bullets\ODST_Pistol.paa";
x = 0.881562 * safezoneW + safezoneX;
y = 0.093 * safezoneH + safezoneY;
w = 0.0670312 * safezoneW;
h = 0.011 * safezoneH;
};
////////////////////////////////////////////////////////
// GUI EDITOR OUTPUT END
////////////////////////////////////////////////////////
| [
"[email protected]"
] | |
b1bb131796d9cff7b6595965fddc3a40296516e8 | 4da1dc67f0ca2d0db91e54fd430761a8c900ae92 | /PraticeCPP/PraticeCPP/exam.cpp | 3d20ec84f4385b2b65e5047caed09c33021e5979 | [] | no_license | yoyao/ItCast | d4c25bfb6bc590a0ec84f437a0a3fd7d744758d6 | 77dd1ba29e75d46539b88dfbd9143b0776848db6 | refs/heads/master | 2021-01-23T06:16:13.391901 | 2019-06-14T01:59:19 | 2019-06-14T01:59:19 | 86,350,298 | 0 | 0 | null | null | null | null | GB18030 | C++ | false | false | 5,046 | cpp |
#define _CRT_SECURE_NO_WARNINGS
#include<iostream>
#include<string>
#include<algorithm>
#include<vector>
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<stdarg.h>
using namespace std;
class Single
{
public:
static Single* GetInstance()
{
return Instance;
}
private:
Single(const Single& s)
{
}
Single()
{
}
static Single* Instance;
};
Single* Single::Instance=new Single;
/*
1. 传入一个字符串,
1求出该字符串中字符的个数<重复字符不计入个数>
2出现频次最高的字符
若有多个相同的字符备选,返回其中最早出现的字符
函数原型:
(1)int getCountOfString(const char *str);
int getCountOfString1(const char *str,int *count);
char getMostCharFromString(const char *str);
char getMostCharFromString1(const char *str,char * chr);
*/
void StrSort(char* str)
{
if (str == NULL)
{
return;
}
size_t len = strlen(str);
for (size_t i = 0; i < len; ++i)
{
int index = i;
for (size_t j = i + 1; j < len; ++j)
{
if (str[index] > str[j])
{
index = j;
}
}
char tmp = str[i];
str[i] = str[index];
str[index] = tmp;
}
}
// 计算字符个数
int CalcuCharCount(char* str)
{
if (str == NULL)
{
return 0;
}
size_t len = strlen(str);
char* p_assist = (char*)calloc(len + 1, sizeof(char));
memcpy(p_assist, str, len + 1);
StrSort(p_assist);
int count = 0;
char pre = '\0';
for (size_t j = 0; j < len; ++j)
{
if (pre != p_assist[j] && (p_assist[j]<'0'||p_assist[j]>'9'))
{
++count;
pre = p_assist[j];
}
}
if (p_assist != NULL)
{
free(p_assist);
}
return count;
}
//最多的字符
char GetMostCharFromString(const char *str)
{
if (str == NULL)
{
return 0;
}
size_t len = strlen(str);
if (len == 1)
{
return *str;
}
char* p_assist = (char*)calloc(len + 1, sizeof(char));
memcpy(p_assist, str, len + 1);
StrSort(p_assist);
char ret ;
int ccount = 0;
char pre = '\0';
for (size_t i = 0; i < len; ++i)
{
int t_cout = 0;
for (size_t j = i + 1; j < len && (p_assist[i] == p_assist[j]); ++j)
{
++t_cout;
}
if (t_cout>ccount)
{
ccount = t_cout;
ret = p_assist[i];
}
}
if (p_assist != NULL)
{
free(p_assist);
}
return ret;
}
// 计算字符个数
int CalcuCharCountW(wchar_t* str)
{
if (str == NULL)
{
return 0;
}
size_t len = wcslen(str);
char* p_assist = (char*)calloc(len + 1, sizeof(char));
memcpy(p_assist, str, len + 1);
StrSort(p_assist);
int count = 0;
char pre = '\0';
for (size_t j = 0; j < len; ++j)
{
if (pre != p_assist[j] && (p_assist[j]<'0' || p_assist[j]>'9'))
{
++count;
pre = p_assist[j];
}
}
if (p_assist != NULL)
{
free(p_assist);
}
return count;
}
//最多的字符
wchar_t GetMostCharFromStringW(const char *str)
{
if (str == NULL)
{
return 0;
}
size_t len = strlen(str);
if (len == 1)
{
return *str;
}
char* p_assist = (char*)calloc(len + 1, sizeof(char));
memcpy(p_assist, str, len + 1);
StrSort(p_assist);
char ret;
int ccount = 0;
char pre = '\0';
for (size_t i = 0; i < len; ++i)
{
int t_cout = 0;
for (size_t j = i + 1; j < len && (p_assist[i] == p_assist[j]); ++j)
{
++t_cout;
}
if (t_cout>ccount)
{
ccount = t_cout;
ret = p_assist[i];
}
}
if (p_assist != NULL)
{
free(p_assist);
}
return ret;
}
void VariablePram(int a, ...)
{
va_list li;
va_start(li,a);
for (int i = 0; i < a; ++i)
{
printf("%d ", va_arg(li, int));
}
printf("\n");
}
typedef struct _tag_Student {
char name[24];
int age;
} Student;
typedef struct _listNode {
Student *stu;
struct _listNode *next;
}ListNode;
int GetStudentInfo(char *studentInfo, Student *stu)
{
if (studentInfo == NULL || *studentInfo == '\n' || *studentInfo == '\0')
{
return -1;
}
if (strcmp(studentInfo, "\r\n") == 0)
{
return -1;
}
char* p_info = studentInfo;
p_info = strchr(studentInfo, '=');
++p_info;//跳过=
while (p_info != NULL&&*p_info == ' ')
{
++p_info;
}
char* p_back = strchr(p_info, ' ');
strncpy(stu->name, p_info, strlen(p_info) - strlen(p_back));
p_info = strchr(p_info, '=');
++p_info;//跳过=
while (p_info != NULL&&*p_info == ' ')
{
++p_info;
}
p_back = strchr(p_info, ' ');
if (p_back != NULL)
{
*p_back = 0;
}
stu->age = atoi(p_info);
return 1;
}
void TestStudent()
{
FILE* file = fopen("./student.txt","rb");
if (file == NULL)
{
return;
}
char buf[1024] = { 0 };
while (!feof(file))
{
fgets(buf, 1024, file);
if (buf != NULL)
{
Student* stu = (Student*)calloc(1, sizeof(Student));
GetStudentInfo(buf, stu);
ListNode node;
}
memset(buf, 0, 1024);
}
}
int main_exam(int argc, char* argv[])
{
char buf[64] = { "fhddddadrfffaetw" };
char han[] = { "aaabbbccc" };
char han1[] = { "aaabbbccc" };
int count = CalcuCharCount(buf);
char ret = GetMostCharFromString(buf);
cout << count << endl;
cout << han << endl;
cout << wcslen((wchar_t*)han1) << " " << strlen(han) << endl;
VariablePram(5,1,2,3,4,5);
system("pause");
return EXIT_SUCCESS;
}
| [
"[email protected]"
] | |
d4dccad8ed04548d283bccf08bb6adf74cd19610 | 6ce3c81a5662c638a0461316855e279f03f40abd | /sp2/sp2/sp2.cpp | 7e61bfe61ec9c637b0d6db73dd124252e7394ac2 | [] | no_license | Qunney/lr2 | a5c97f33d0d2be6d6e629c14a6ff8bcbd9375d66 | b15bf5f0d20bd3a1b28c07bec8202b4c51f3a8fb | refs/heads/main | 2023-04-02T16:09:21.019497 | 2021-04-09T22:24:24 | 2021-04-09T22:24:24 | 356,411,573 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 366 | cpp | #include <iostream>
using namespace std;
#define size 9
int main()
{
int array[size] = { 5, -2, 7, 4, -5, -6, 7, -8, 10 };
for (int i = 0; i < size; i++)
{
if (array[i] > 0)
array[i] = array[i] & 0b01110111;
else array[i] = array[i] >> 2;
cout << array[i] << " " ;
}
return 0;
}
| [
"[email protected]"
] | |
0f8e517567c0185840453b0da9943005125b6e9d | 0eff74b05b60098333ad66cf801bdd93becc9ea4 | /second/download/collectd/gumtree/collectd_repos_function_213_collectd-5.0.1.cpp | 2c220528f67b647a027ab04a962b424d5e031071 | [] | 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 | 3,972 | cpp | static int putval (lcc_connection_t *c, int argc, char **argv)
{
lcc_value_list_t vl = LCC_VALUE_LIST_INIT;
/* 64 ought to be enough for anybody ;-) */
value_t values[64];
int values_types[64];
size_t values_len = 0;
int status;
int i;
assert (strcasecmp (argv[0], "putval") == 0);
if (argc < 3) {
fprintf (stderr, "ERROR: putval: Missing identifier "
"and/or value list.\n");
return (-1);
}
vl.values = values;
vl.values_types = values_types;
status = parse_identifier (c, argv[1], &vl.identifier);
if (status != 0)
return (status);
for (i = 2; i < argc; ++i) {
char *tmp;
tmp = strchr (argv[i], (int)'=');
if (tmp != NULL) { /* option */
char *key = argv[i];
char *value = tmp;
*value = '\0';
++value;
if (strcasecmp (key, "interval") == 0) {
char *endptr;
vl.interval = strtol (value, &endptr, 0);
if (endptr == value) {
fprintf (stderr, "ERROR: Failed to parse interval as number: %s.\n",
value);
return (-1);
}
else if ((endptr != NULL) && (*endptr != '\0')) {
fprintf (stderr, "WARNING: Ignoring trailing garbage after "
"interval: %s.\n", endptr);
}
}
else {
fprintf (stderr, "ERROR: putval: Unknown option `%s'.\n", key);
return (-1);
}
}
else { /* value list */
char *value;
tmp = strchr (argv[i], (int)':');
if (tmp == NULL) {
fprintf (stderr, "ERROR: putval: Invalid value list: %s.\n",
argv[i]);
return (-1);
}
*tmp = '\0';
++tmp;
if (strcasecmp (argv[i], "N") == 0) {
vl.time = 0;
}
else {
char *endptr;
vl.time = strtol (argv[i], &endptr, 0);
if (endptr == argv[i]) {
fprintf (stderr, "ERROR: Failed to parse time as number: %s.\n",
argv[i]);
return (-1);
}
else if ((endptr != NULL) && (*endptr != '\0')) {
fprintf (stderr, "ERROR: Garbage after time: %s.\n", endptr);
return (-1);
}
}
values_len = 0;
value = tmp;
while (value != 0) {
char *dot, *endptr;
tmp = strchr (argv[i], (int)':');
if (tmp != NULL) {
*tmp = '\0';
++tmp;
}
/* This is a bit of a hack, but parsing types.db just does not make
* much sense imho -- the server might have different types defined
* anyway. Also, lcc uses the type information for formatting the
* number only, so the real meaning does not matter. -tokkee */
dot = strchr (value, (int)'.');
endptr = NULL;
if (strcasecmp (value, "U") == 0) {
values[values_len].gauge = NAN;
values_types[values_len] = LCC_TYPE_GAUGE;
}
else if (dot) { /* floating point value */
values[values_len].gauge = strtod (value, &endptr);
values_types[values_len] = LCC_TYPE_GAUGE;
}
else { /* integer */
values[values_len].counter = strtol (value, &endptr, 0);
values_types[values_len] = LCC_TYPE_COUNTER;
}
++values_len;
if (endptr == value) {
fprintf (stderr, "ERROR: Failed to parse value as number: %s.\n",
argv[i]);
return (-1);
}
else if ((endptr != NULL) && (*endptr != '\0')) {
fprintf (stderr, "ERROR: Garbage after value: %s.\n", endptr);
return (-1);
}
value = tmp;
}
assert (values_len >= 1);
vl.values_len = values_len;
status = lcc_putval (c, &vl);
if (status != 0) {
fprintf (stderr, "ERROR: %s\n", lcc_strerror (c));
return (-1);
}
}
}
if (values_len == 0) {
fprintf (stderr, "ERROR: putval: Missing value list(s).\n");
return (-1);
}
return (0);
} | [
"[email protected]"
] | |
c08cb155cd740cd9a75f3d9e5b706f889167ec91 | c0fb79ca802dbe964c39446cb914b61ca5072956 | /Source/S05_TestingGrounds/Player/FirstPersonCharacter.cpp | d39ebbf139477a39cfa742cce368c1aa4835fce4 | [] | no_license | andrewmontoyaiv/05_TestingGrounds | 23b3bdf819a44ae603c2643f7c2b288ba82b1aaa | 6de9b3c84dc94eea926abd3c088effd6436330a3 | refs/heads/master | 2021-06-24T21:12:43.815536 | 2017-08-01T06:22:31 | 2017-08-01T06:22:31 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 7,634 | cpp | // Copyright 1998-2017 Epic Games, Inc. All Rights Reserved.
#include "S05_TestingGrounds.h"
#include "FirstPersonCharacter.h"
#include "GameFramework/InputSettings.h"
#include "Kismet/HeadMountedDisplayFunctionLibrary.h"
#include "../Weapons/Gun.h"
#include "MotionControllerComponent.h"
DEFINE_LOG_CATEGORY_STATIC(LogFPChar, Warning, All);
//////////////////////////////////////////////////////////////////////////
// AFirstPersonCharacter
AFirstPersonCharacter::AFirstPersonCharacter()
{
// Set size for collision capsule
GetCapsuleComponent()->InitCapsuleSize(55.f, 96.0f);
// set our turn rates for input
BaseTurnRate = 45.f;
BaseLookUpRate = 45.f;
// Create a CameraComponent
FirstPersonCameraComponent = CreateDefaultSubobject<UCameraComponent>(TEXT("FirstPersonCamera"));
FirstPersonCameraComponent->SetupAttachment(GetCapsuleComponent());
FirstPersonCameraComponent->RelativeLocation = FVector(-39.56f, 1.75f, 64.f); // Position the camera
FirstPersonCameraComponent->bUsePawnControlRotation = true;
// Create a mesh component that will be used when being viewed from a '1st person' view (when controlling this pawn)
Mesh1P = CreateDefaultSubobject<USkeletalMeshComponent>(TEXT("CharacterMesh1P"));
Mesh1P->SetOnlyOwnerSee(true);
Mesh1P->SetupAttachment(FirstPersonCameraComponent);
Mesh1P->bCastDynamicShadow = false;
Mesh1P->CastShadow = false;
Mesh1P->RelativeRotation = FRotator(1.9f, -19.19f, 5.2f);
Mesh1P->RelativeLocation = FVector(-0.5f, -4.4f, -155.7f);
// Create VR Controllers.
R_MotionController = CreateDefaultSubobject<UMotionControllerComponent>(TEXT("R_MotionController"));
R_MotionController->Hand = EControllerHand::Right;
R_MotionController->SetupAttachment(RootComponent);
L_MotionController = CreateDefaultSubobject<UMotionControllerComponent>(TEXT("L_MotionController"));
L_MotionController->SetupAttachment(RootComponent);
}
void AFirstPersonCharacter::BeginPlay()
{
// Call the base class
Super::BeginPlay();
if (GunBlueprint == NULL) {
UE_LOG(LogTemp, Warning, TEXT("Gun Blueprint Missing"));
return;
}
//Attach gun mesh component to Skeleton, doing it here because the skeleton is not yet created in the constructor
auto Gun = GetWorld()->SpawnActor<AGun>(
GunBlueprint
);
Gun->AttachToComponent(Mesh1P, FAttachmentTransformRules(EAttachmentRule::SnapToTarget, true), TEXT("GripPoint"));
// setting animation for gun - generally this should be made as a setter/getter if this will be used alot
Gun->AnimInstanceFP = Mesh1P->GetAnimInstance();
// Show or hide the two versions of the gun based on whether or not we're using motion controllers.
if (bUsingMotionControllers)
{
Mesh1P->SetHiddenInGame(true, true);
}
else
{
Mesh1P->SetHiddenInGame(false, true);
}
//InputComponent->BindTouch(EInputEvent::IE_Pressed, this, &AFirstPersonCharacter::TouchStarted);
if (EnableTouchscreenMovement(InputComponent) == false)
{
InputComponent->BindAction("Fire", IE_Pressed, Gun, &AGun::OnFire);
}
}
//////////////////////////////////////////////////////////////////////////
// Input
void AFirstPersonCharacter::SetupPlayerInputComponent(class UInputComponent* PlayerInputComponent)
{
// set up gameplay key bindings
check(PlayerInputComponent);
PlayerInputComponent->BindAction("Jump", IE_Pressed, this, &ACharacter::Jump);
PlayerInputComponent->BindAction("Jump", IE_Released, this, &ACharacter::StopJumping);
PlayerInputComponent->BindAction("ResetVR", IE_Pressed, this, &AFirstPersonCharacter::OnResetVR);
PlayerInputComponent->BindAxis("MoveForward", this, &AFirstPersonCharacter::MoveForward);
PlayerInputComponent->BindAxis("MoveRight", this, &AFirstPersonCharacter::MoveRight);
// We have 2 versions of the rotation bindings to handle different kinds of devices differently
// "turn" handles devices that provide an absolute delta, such as a mouse.
// "turnrate" is for devices that we choose to treat as a rate of change, such as an analog joystick
PlayerInputComponent->BindAxis("Turn", this, &APawn::AddControllerYawInput);
PlayerInputComponent->BindAxis("TurnRate", this, &AFirstPersonCharacter::TurnAtRate);
PlayerInputComponent->BindAxis("LookUp", this, &APawn::AddControllerPitchInput);
PlayerInputComponent->BindAxis("LookUpRate", this, &AFirstPersonCharacter::LookUpAtRate);
}
void AFirstPersonCharacter::OnResetVR()
{
UHeadMountedDisplayFunctionLibrary::ResetOrientationAndPosition();
}
void AFirstPersonCharacter::BeginTouch(const ETouchIndex::Type FingerIndex, const FVector Location)
{
if (TouchItem.bIsPressed == true)
{
return;
}
TouchItem.bIsPressed = true;
TouchItem.FingerIndex = FingerIndex;
TouchItem.Location = Location;
TouchItem.bMoved = false;
}
void AFirstPersonCharacter::EndTouch(const ETouchIndex::Type FingerIndex, const FVector Location)
{
if (TouchItem.bIsPressed == false)
{
return;
}
if ((FingerIndex == TouchItem.FingerIndex) && (TouchItem.bMoved == false))
{
// OnFire();
}
TouchItem.bIsPressed = false;
}
//Commenting this section out to be consistent with FPS BP template.
//This allows the user to turn without using the right virtual joystick
//void AFirstPersonCharacter::TouchUpdate(const ETouchIndex::Type FingerIndex, const FVector Location)
//{
// if ((TouchItem.bIsPressed == true) && (TouchItem.FingerIndex == FingerIndex))
// {
// if (TouchItem.bIsPressed)
// {
// if (GetWorld() != nullptr)
// {
// UGameViewportClient* ViewportClient = GetWorld()->GetGameViewport();
// if (ViewportClient != nullptr)
// {
// FVector MoveDelta = Location - TouchItem.Location;
// FVector2D ScreenSize;
// ViewportClient->GetViewportSize(ScreenSize);
// FVector2D ScaledDelta = FVector2D(MoveDelta.X, MoveDelta.Y) / ScreenSize;
// if (FMath::Abs(ScaledDelta.X) >= 4.0 / ScreenSize.X)
// {
// TouchItem.bMoved = true;
// float Value = ScaledDelta.X * BaseTurnRate;
// AddControllerYawInput(Value);
// }
// if (FMath::Abs(ScaledDelta.Y) >= 4.0 / ScreenSize.Y)
// {
// TouchItem.bMoved = true;
// float Value = ScaledDelta.Y * BaseTurnRate;
// AddControllerPitchInput(Value);
// }
// TouchItem.Location = Location;
// }
// TouchItem.Location = Location;
// }
// }
// }
//}
void AFirstPersonCharacter::MoveForward(float Value)
{
if (Value != 0.0f)
{
// add movement in that direction
AddMovementInput(GetActorForwardVector(), Value);
}
}
void AFirstPersonCharacter::MoveRight(float Value)
{
if (Value != 0.0f)
{
// add movement in that direction
AddMovementInput(GetActorRightVector(), Value);
}
}
void AFirstPersonCharacter::TurnAtRate(float Rate)
{
// calculate delta for this frame from the rate information
AddControllerYawInput(Rate * BaseTurnRate * GetWorld()->GetDeltaSeconds());
}
void AFirstPersonCharacter::LookUpAtRate(float Rate)
{
// calculate delta for this frame from the rate information
AddControllerPitchInput(Rate * BaseLookUpRate * GetWorld()->GetDeltaSeconds());
}
bool AFirstPersonCharacter::EnableTouchscreenMovement(class UInputComponent* PlayerInputComponent)
{
bool bResult = false;
if (FPlatformMisc::GetUseVirtualJoysticks() || GetDefault<UInputSettings>()->bUseMouseForTouch)
{
bResult = true;
PlayerInputComponent->BindTouch(EInputEvent::IE_Pressed, this, &AFirstPersonCharacter::BeginTouch);
PlayerInputComponent->BindTouch(EInputEvent::IE_Released, this, &AFirstPersonCharacter::EndTouch);
//Commenting this out to be more consistent with FPS BP template.
//PlayerInputComponent->BindTouch(EInputEvent::IE_Repeat, this, &AFirstPersonCharacter::TouchUpdate);
}
return bResult;
}
| [
"[email protected]"
] | |
49cf02a64c826cbbed61f62faa9c42ae8ed1c48b | 30bdd8ab897e056f0fb2f9937dcf2f608c1fd06a | /contest/1542587051.cpp | 3a7d10a4f88ceff11e0ba3c357907a3201c4ea6d | [] | no_license | thegamer1907/Code_Analysis | 0a2bb97a9fb5faf01d983c223d9715eb419b7519 | 48079e399321b585efc8a2c6a84c25e2e7a22a61 | refs/heads/master | 2020-05-27T01:20:55.921937 | 2019-11-20T11:15:11 | 2019-11-20T11:15:11 | 188,403,594 | 2 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 488 | cpp | #include<iostream>
#include<cstdio>
#include<cstring>
#define V 43200
using namespace std;
int n,h,m,s,t1,t2;
bool mp[V],f;
int main()
{
scanf("%d%d%d%d%d",&h,&m,&s,&t1,&t2);
h=(h*3600+m*60+s)%V,m=(m*720+s*12)%V,s=(s*720)%V;
t1=t1*3600%V,t2=t2*3600%V;
mp[h]=mp[m]=mp[s]=1;
for(int i=t1;i!=t2;i=(i+1)%V)
if(mp[i]){f=1;break;}
if(!f){puts("YES");return 0;}
for(int i=t1;i!=t2;i=(i+V-1)%V)
if(mp[i]){f=0;break;}
puts(f?"YES":"NO");
}
| [
"[email protected]"
] | |
37a534c42128773212ce9ab5d2ddb3a91949d569 | 632fd7915a9e0c38ee467458da5dc919e05934a6 | /CDB2OSG/src/CDB2OSG/TileBuilders/ProgressiveTileBuilder.h | 7365890ee822a423aeff8200b752655f2c94f6db | [] | no_license | adem99307/CDB2OSG | 00d7d4a5efcfeca43efe0c1a4c9ec21167c0d213 | 9da5ad3cfa4069d224afd7373812a2af472529d9 | refs/heads/master | 2023-03-16T11:48:04.453272 | 2017-03-05T14:11:51 | 2017-03-05T14:11:51 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,565 | h | /* Copyright (C) 2014-2016 Leandro Linardos, Buenos Aires, Argentina
*
* This file is part of CDB2OSG.
*
* CDB2OSG is open source and may be redistributed and/or modified under
* the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or
* (at your option) any later version. The full license is in LICENSE file
* included with this distribution, and on the openscenegraph.org website.
*
* This software 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. See the
* OpenSceneGraph Public License for more details.
*/
#ifndef CDB2OSG_PROGRESSIVETILEBUILDER_H
#define CDB2OSG_PROGRESSIVETILEBUILDER_H
#include <CDB2OSG/TileBuilders/LODPolicy.h>
#include <CDB2OSG/TileBuilder.h>
#include <CDB/LodTileQuery.h>
#include "NextTiles.h"
namespace CDB2OSG {
class ProgressiveTileBuilder : public TileBuilder {
public:
void setLodPolicy(LODPolicy *lodPolicy);
void setNextTiles(NextTiles *nextTiles);
void enableElevationSubsampling(bool enable);
virtual osg::Node *build();
virtual void setupMoreDetailedChildForRange(double min, double max, CDB::LodTile::List lodTilesToLoad) = 0;
virtual osg::LOD *getLodNode() = 0;
protected:
osg::ref_ptr<LODPolicy> lodPolicy;
osg::ref_ptr<NextTiles> nextTiles;
bool subsamplingEnabled;
};
};
#endif
| [
"[email protected]"
] | |
75bd76f570becdcbbc27f2049e6adf47b79341aa | 8bab14489780e1262d87b6cd7fdec01f6e9c3f48 | /Recursion/Merge Two Sorted Arrays.cpp | f0d3437022716e77ad0c86b6c1c691f8d50e5639 | [] | no_license | Leanbow1708/Competetive-Programming | 0e9e5eb18446311816895b3c4369ec6712a4f0af | 810aeae3d365c1ed745f8609c08b621798b88a5b | refs/heads/master | 2023-03-10T21:58:12.077658 | 2021-02-16T05:59:49 | 2021-02-16T05:59:49 | 299,811,002 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 762 | cpp | #include<iostream>
using namespace std;
void merge_fun(int* a,int* b,int n,int m){
int t[m+n];
int N = m+n;
int l = 0;
int r = 0;
int i =0;
while(l < n || r < m)
{
if(l == n)
{
t[i] = b[r];
r++;
i++;
}
else if(r == m){
t[i] = a[l];
l++;
i++;
}
else if(a[l] <= b[r])
{
t[i] = a[l];
l++;
i++;
}
else{
t[i] = b[r];
r++;
i++;
}
}
for(int i = 0;i < N;i++)
{
cout<<t[i]<<" ";
}
}
int main(){
int a[3] = {1,2,3};
int b[3] = {2,5,6};
merge_fun(a,b,3,3);
}
| [
"[email protected]"
] | |
98a44d910fb4bcdeb71324e339533e66061c6073 | 0e0346431e4ab47c53df586888b1c8cf33f2b5cc | /LampuLaluLintas/Waktu.h | 225674c8a8a3f0a9ef97a9650769eae326fb9547 | [] | no_license | yafithekid/lampu-lalu-lintas | 569f4aadb0ce935ee5c76756b07eb16de27e776e | ef0f088d20c32e45937c213f3957a039ba511b63 | refs/heads/master | 2021-01-19T06:53:07.311657 | 2014-03-16T03:05:06 | 2014-03-16T03:05:06 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 286 | h | #pragma once
class Waktu
{
public:
Waktu();
~Waktu();
void SetWaktu(int Waktu);
int GetWaktu();
static float GetCurrentTime();
static void Begin();
void BeginNS();
void ResetNS(int time);
private:
int waktu;
static sf::Clock Elapsed;
sf::Clock ElapsedNS;
}; | [
"[email protected]"
] | |
6e550ef2cd78e0a3046cb928c8c5bdcff1ba87a1 | 05d0608385955b6d5782f91fc976aee430aadfe1 | /notes/day1/code/04-for-with-skipped-initialiser.cpp | 27dce69a9eaa9a08ed89bfedce7d789dbad3724a | [
"BSD-3-Clause",
"FreeBSD-DOC",
"BSD-2-Clause"
] | permissive | ajbennieston/cpp | 68a578c9aaa3162f6b0a374019086425bbb3031a | e43687b4289c2e07c0c9c87b4c0003abf4e2a054 | refs/heads/master | 2020-06-03T11:08:22.709114 | 2016-01-18T00:27:36 | 2016-01-18T00:27:36 | 6,890,513 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 386 | cpp | /*
* C++ Notes Accompanying Code
* Compile: Y
* Run: Y
* Compile Should Succeed: Y
* Run Should Succeed: Y
* Input: 5
*/
#include <iostream>
int main() {
// NOTES: BEGIN INCLUSION
int i{0};
std::cout << "Enter starting point: ";
std::cin >> i;
for (/* use existing value of i */; i < 10; ++i) {
std::cout << i << "\n";
}
// NOTES: END INCLUSION
return 0;
}
| [
"[email protected]"
] | |
add5340d43573d6f106e1f3ac6fbffc3bea2f7f1 | 34a3fa29d9270398372c04e002332ddedb3c498a | /div2/561/A.cpp | 45e6512120bdfc13da7a4dbd01cb01dd55ec83c6 | [] | no_license | tatsumack/codeforces | 643accf23bc772d136708a1170ac2200a9348efc | b99c1ff04c8756121a059f130655885705018eca | refs/heads/master | 2021-07-10T05:55:56.329203 | 2020-07-23T10:50:08 | 2020-07-23T10:50:08 | 143,435,557 | 0 | 0 | null | 2019-10-12T03:10:19 | 2018-08-03T14:12:22 | C++ | UTF-8 | C++ | false | false | 1,990 | cpp |
#include <limits.h>
#include <algorithm>
#include <bitset>
#include <cctype>
#include <cmath>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <ctime>
#include <deque>
#include <functional>
#include <iomanip>
#include <iostream>
#include <list>
#include <map>
#include <numeric>
#include <set>
#include <sstream>
#include <stack>
#include <string>
#include <utility>
#include <vector>
#include <queue>
#include <unordered_map>
#include <unordered_set>
#define int long long
#define REP(i, n) for (int i = 0, i##_len = (n); i < i##_len; ++i)
#define REPS(i, n) for (int i = 1, i##_len = (n); i <= i##_len; ++i)
#define FOR(i, a, b) for (int i = (a), i##_len = (b); i <= i##_len; ++i)
#define REV(i, a, b) for (int i = (a); i >= (b); --i)
#define CLR(a, b) memset((a), (b), sizeof(a))
#define DUMP(x) cout << #x << " = " << (x) << endl;
#define INF 1001001001001001001ll
#define fcout cout << fixed << setprecision(10)
using namespace std;
template<typename T>
vector<T> make_v(size_t a) { return vector<T>(a); }
template<typename T, typename... Ts>
auto make_v(size_t a, Ts... ts) {
return vector<decltype(make_v<T>(ts...))>(a, make_v<T>(ts...));
}
template<typename T, typename V>
typename enable_if<is_class<T>::value == 0>::type
fill_v(T& t, const V& v) { t = v; }
template<typename T, typename V>
typename enable_if<is_class<T>::value != 0>::type
fill_v(T& t, const V& v) {
for (auto& e:t) fill_v(e, v);
}
typedef pair<int, int> P;
signed main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
cout.tie(nullptr);
int n;
cin >> n;
map<char, int> cnt;
REP(i, n) {
string s;
cin >> s;
cnt[s[0]]++;
}
int res = 0;
for (auto& kv: cnt) {
int n = kv.second;
int t = kv.second / 2;
if (t > 1) {
res += t * (t - 1) / 2;
}
n -= t;
if (n > 1) {
res += n * (n - 1) / 2;
}
}
cout << res << endl;
return 0;
}
| [
"[email protected]"
] | |
d151b2c0d853115e6d9c8e0ec33fa9a84a1f80c7 | ffebe32ba2decbf89a56cbf15c672557dc306db9 | /firstProject1415/Products/Electronic/Electronic.h | 4f3e646f13932f697da404a15969d44832f3be79 | [] | no_license | JuliaZvizlo/firstProject1415 | 2a0f387802b9415ed43b51ce38c51ba03445b3ca | 1b2a4b681b54676c8bc37bedaf280f5ed60a27a3 | refs/heads/master | 2020-12-28T12:13:12.385857 | 2015-04-06T15:27:44 | 2015-04-06T15:27:44 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 948 | h | # pragma once
# include "../Product.h"
class Electronic : public Product
{
protected:
string category;
double weight;
string model;
public:
Electronic(): category("No category"), weight(0.0), model("No model") { }
friend istream& operator>>(istream& stream, Electronic& obj)
{
getline(stream, obj.category);
stream >> obj.weight;
stream.get();
getline(stream, obj.model);
return stream;
}
friend ostream& operator<<(ostream& stream, const Electronic& obj)
{
stream << obj.category << ' ' << obj.weight << ' '<< obj.model << endl;
return stream;
}
string getCategory() const { return category; }
void setCategory(const string& c) { category = c; }
double getWeight() const { return weight; }
void setWeight(double w) { this->weight = w; }
string getModel() const { return model; }
void setModel(string m) { model = m; }
~Electronic(){}
}; | [
"[email protected]"
] | |
372b6ad94dd297aa6cf8edbdc08c0abc5894a07a | 182dd1d01d61a85536ac2f748696362a30f0f1de | /Codeforces/Competetion/matPalin.cpp | 03198df229b25bded845fbc289916589c411d08d | [
"MIT"
] | permissive | SanchitTaliyan/Codes | 069cc75352abccff9e788b11f351d9d37e3019d9 | 259c31c01ea7756755b93f5cac9f412b66e0d492 | refs/heads/master | 2023-01-06T12:20:33.410341 | 2023-01-05T15:35:50 | 2023-01-05T15:35:50 | 218,686,299 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,938 | cpp | #include <iostream>
#include <vector>
#include<math.h>
#include <cmath>
#include <queue>
using namespace std;
long long countOperations(vector< vector<long long> > &mat, int r, int c) {
int ur, dr;
ur = 0;
dr = r-1;
long long numOp = 0;
while(ur <= dr) {
for(int i = 0; i < (c + 1)/2; i++) {
if(ur != dr){
long long avg;
if(i == c - i - 1) {
avg = (mat[ur][i] + mat[dr][i]) / 2;
numOp += abs(mat[ur][i] - avg) + abs(mat[dr][i] - avg);
mat[ur][i] = avg;
mat[dr][i] = avg;
}else {
avg = (mat[ur][i] + mat[ur][c - i - 1] + mat[dr][i] + mat[dr][c - i - 1]) / 4;
numOp += abs(mat[ur][i] - avg) + abs(mat[ur][c - i - 1] - avg) + abs(mat[dr][i] - avg) + abs(mat[dr][c - i - 1] - avg);
mat[ur][i] = avg;
mat[ur][c- i -1] = avg;
mat[dr][i] = avg;
mat[dr][c - i - 1] = avg;
}
}
else if(ur == dr) {
if(i != c - 1 - i){
long long avg = (mat[ur][i] + mat[ur][c - i - 1]) / 2;
numOp += abs(mat[ur][i] - avg) + abs(mat[ur][c - i - 1] - avg);
mat[ur][i] = avg;
mat[ur][c- i -1] = avg;
}
}
}
ur++;
dr--;
}
return numOp;
}
int main() {
int t;
cin >> t;
for(int i = 0; i < t; i++) {
int r, c;
cin >> r >> c;
vector< vector<long long> > mat(r, vector<long long>(c));
for(int j = 0; j < r; j++) {
for(int k = 0; k < c; k++) {
cin >> mat[j][k];
}
}
long long ans = countOperations(mat, r, c);
cout << ans << "\n";
}
} | [
"[email protected]"
] | |
2c3ff8d8e9761e28fd6a2f3c201ee833645cc533 | 4611624808ccc2681272cc0847f01e54389490a7 | /build/Android/Debug/app/src/main/include/Fuse.Controls.ClientPanel.h | d92e68d5e4118235f9397637114bada92a5ca3fd | [] | no_license | kvitberg/TestCase | 62d6c88e5cab7ac46fd70c29a6e2e695d838f261 | 75c6e7fdf680189e6d6a447c157a07e10218796a | refs/heads/master | 2020-12-02T18:01:51.624735 | 2017-07-06T18:55:24 | 2017-07-06T18:55:24 | 96,462,146 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,353 | h | // This file was generated based on '../../../Library/Application Support/Fusetools/Packages/Fuse.Controls.Panels/1.0.5/$.uno'.
// WARNING: Changes might be lost if you edit this file directly.
#pragma once
#include <Fuse.Animations.IResize.h>
#include <Fuse.Binding.h>
#include <Fuse.Controls.DockPanel.h>
#include <Fuse.Drawing.ISurfaceDrawable.h>
#include <Fuse.IActualPlacement.h>
#include <Fuse.INotifyUnrooted.h>
#include <Fuse.IProperties.h>
#include <Fuse.Node.h>
#include <Fuse.Scripting.IScriptObject.h>
#include <Fuse.Triggers.Actions.IHide.h>
#include <Fuse.Triggers.Actions.IShow.h>
#include <Fuse.Triggers.Actions-ea70af1f.h>
#include <Uno.Collections.ICollection-1.h>
#include <Uno.Collections.IEnumerable-1.h>
#include <Uno.Collections.IList-1.h>
#include <Uno.UX.IPropertyListener.h>
namespace g{namespace Fuse{namespace Controls{struct ClientPanel;}}}
namespace g{
namespace Fuse{
namespace Controls{
// public partial sealed class ClientPanel :33
// {
::g::Fuse::Controls::Panel_type* ClientPanel_typeof();
void ClientPanel__ctor_8_fn(ClientPanel* __this);
void ClientPanel__InitializeUX_fn(ClientPanel* __this);
void ClientPanel__New5_fn(ClientPanel** __retval);
struct ClientPanel : ::g::Fuse::Controls::DockPanel
{
void ctor_8();
void InitializeUX();
static ClientPanel* New5();
};
// }
}}} // ::g::Fuse::Controls
| [
"[email protected]"
] | |
df332816f612253259bec3a2f416ae834ff98b7b | d703c051d7e696b22231fe1756c31608fc521f83 | /Source/LonelyDark/Humanoid.cpp | 54ae7d62399fc7f97155b71337fe0ec7dd938c1a | [] | no_license | theopathy/LonelyDark | 49b04525334ee22ab1f41752e59c32a682e1e806 | cac8a3e689ef333eb76784583c1828b3af51e994 | refs/heads/master | 2023-03-08T13:30:43.271967 | 2021-02-12T04:02:47 | 2021-02-12T04:02:47 | 315,323,721 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 939 | cpp | // Fill out your copyright notice in the Description page of Project Settings.
#include "Humanoid.h"
// Sets default values for this component's properties
UHumanoid::UHumanoid()
{
// Set this component to be initialized when the game starts, and to be ticked every frame. You can turn these features
// off to improve performance if you don't need them.
PrimaryComponentTick.bCanEverTick = true;
// ...
}
// Called when the game starts
void UHumanoid::BeginPlay()
{
Super::BeginPlay();
// ...
}
float UHumanoid::getResistance()
{
return 1 - (Armor / 5);
}
float UHumanoid::GetHarm(int32 Damage)
{
Damage *= getResistance();
return Damage;
}
void UHumanoid::Harm(int32 Damage)
{
Health -= Damage;
}
// Called every frame
void UHumanoid::TickComponent(float DeltaTime, ELevelTick TickType, FActorComponentTickFunction* ThisTickFunction)
{
Super::TickComponent(DeltaTime, TickType, ThisTickFunction);
// ...
}
| [
"[email protected]"
] | |
53186d09da0e08b6b3014bb52447474fb1323670 | ed7e1851605dc417f471b24bceaa4efe3ebd577e | /Export/mac64/cpp/release/obj/src/lime/_backend/native/_NativeApplication/SensorEventInfo.cpp | 31349dd1a9cdc7070b8744a698dfc96cb082cf06 | [] | no_license | matthewswallace/StableUITest | 60d88c31540b07b68fc5867cb42901676012cf31 | 8ad46db8245bb8a9bc38b3525dfcdfe90c78b845 | refs/heads/master | 2021-01-12T14:41:07.354460 | 2016-10-26T23:13:43 | 2016-10-26T23:13:43 | 72,050,029 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | true | 6,692 | cpp | // Generated by Haxe 3.3.0
#include <hxcpp.h>
#ifndef INCLUDED_lime__backend_native__NativeApplication_SensorEventInfo
#include <lime/_backend/native/_NativeApplication/SensorEventInfo.h>
#endif
namespace lime{
namespace _backend{
namespace native{
namespace _NativeApplication{
void SensorEventInfo_obj::__construct( ::Dynamic type,hx::Null< Int > __o_id,hx::Null< Float > __o_x,hx::Null< Float > __o_y,hx::Null< Float > __o_z){
Int id = __o_id.Default(0);
Float x = __o_x.Default(0);
Float y = __o_y.Default(0);
Float z = __o_z.Default(0);
HX_STACK_FRAME("lime._backend.native._NativeApplication.SensorEventInfo","new",0x51c6b8a3,"lime._backend.native._NativeApplication.SensorEventInfo.new","lime/_backend/native/NativeApplication.hx",938,0xb13849fd)
HX_STACK_THIS(this)
HX_STACK_ARG(type,"type")
HX_STACK_ARG(id,"id")
HX_STACK_ARG(x,"x")
HX_STACK_ARG(y,"y")
HX_STACK_ARG(z,"z")
HXLINE( 940) this->type = type;
HXLINE( 941) this->id = id;
HXLINE( 942) this->x = x;
HXLINE( 943) this->y = y;
HXLINE( 944) this->z = z;
}
Dynamic SensorEventInfo_obj::__CreateEmpty() { return new SensorEventInfo_obj; }
hx::ObjectPtr< SensorEventInfo_obj > SensorEventInfo_obj::__new( ::Dynamic type,hx::Null< Int > __o_id,hx::Null< Float > __o_x,hx::Null< Float > __o_y,hx::Null< Float > __o_z)
{
hx::ObjectPtr< SensorEventInfo_obj > _hx_result = new SensorEventInfo_obj();
_hx_result->__construct(type,__o_id,__o_x,__o_y,__o_z);
return _hx_result;
}
Dynamic SensorEventInfo_obj::__Create(hx::DynamicArray inArgs)
{
hx::ObjectPtr< SensorEventInfo_obj > _hx_result = new SensorEventInfo_obj();
_hx_result->__construct(inArgs[0],inArgs[1],inArgs[2],inArgs[3],inArgs[4]);
return _hx_result;
}
::lime::_backend::native::_NativeApplication::SensorEventInfo SensorEventInfo_obj::clone(){
HX_STACK_FRAME("lime._backend.native._NativeApplication.SensorEventInfo","clone",0x0a92d260,"lime._backend.native._NativeApplication.SensorEventInfo.clone","lime/_backend/native/NativeApplication.hx",951,0xb13849fd)
HX_STACK_THIS(this)
HXLINE( 951) return ::lime::_backend::native::_NativeApplication::SensorEventInfo_obj::__new(this->type,this->id,this->x,this->y,this->z);
}
HX_DEFINE_DYNAMIC_FUNC0(SensorEventInfo_obj,clone,return )
SensorEventInfo_obj::SensorEventInfo_obj()
{
}
hx::Val SensorEventInfo_obj::__Field(const ::String &inName,hx::PropertyAccess inCallProp)
{
switch(inName.length) {
case 1:
if (HX_FIELD_EQ(inName,"x") ) { return hx::Val( x); }
if (HX_FIELD_EQ(inName,"y") ) { return hx::Val( y); }
if (HX_FIELD_EQ(inName,"z") ) { return hx::Val( z); }
break;
case 2:
if (HX_FIELD_EQ(inName,"id") ) { return hx::Val( id); }
break;
case 4:
if (HX_FIELD_EQ(inName,"type") ) { return hx::Val( type); }
break;
case 5:
if (HX_FIELD_EQ(inName,"clone") ) { return hx::Val( clone_dyn()); }
}
return super::__Field(inName,inCallProp);
}
hx::Val SensorEventInfo_obj::__SetField(const ::String &inName,const hx::Val &inValue,hx::PropertyAccess inCallProp)
{
switch(inName.length) {
case 1:
if (HX_FIELD_EQ(inName,"x") ) { x=inValue.Cast< Float >(); return inValue; }
if (HX_FIELD_EQ(inName,"y") ) { y=inValue.Cast< Float >(); return inValue; }
if (HX_FIELD_EQ(inName,"z") ) { z=inValue.Cast< Float >(); return inValue; }
break;
case 2:
if (HX_FIELD_EQ(inName,"id") ) { id=inValue.Cast< Int >(); return inValue; }
break;
case 4:
if (HX_FIELD_EQ(inName,"type") ) { type=inValue.Cast< Int >(); return inValue; }
}
return super::__SetField(inName,inValue,inCallProp);
}
void SensorEventInfo_obj::__GetFields(Array< ::String> &outFields)
{
outFields->push(HX_HCSTRING("id","\xdb","\x5b","\x00","\x00"));
outFields->push(HX_HCSTRING("x","\x78","\x00","\x00","\x00"));
outFields->push(HX_HCSTRING("y","\x79","\x00","\x00","\x00"));
outFields->push(HX_HCSTRING("z","\x7a","\x00","\x00","\x00"));
outFields->push(HX_HCSTRING("type","\xba","\xf2","\x08","\x4d"));
super::__GetFields(outFields);
};
#if HXCPP_SCRIPTABLE
static hx::StorageInfo SensorEventInfo_obj_sMemberStorageInfo[] = {
{hx::fsInt,(int)offsetof(SensorEventInfo_obj,id),HX_HCSTRING("id","\xdb","\x5b","\x00","\x00")},
{hx::fsFloat,(int)offsetof(SensorEventInfo_obj,x),HX_HCSTRING("x","\x78","\x00","\x00","\x00")},
{hx::fsFloat,(int)offsetof(SensorEventInfo_obj,y),HX_HCSTRING("y","\x79","\x00","\x00","\x00")},
{hx::fsFloat,(int)offsetof(SensorEventInfo_obj,z),HX_HCSTRING("z","\x7a","\x00","\x00","\x00")},
{hx::fsInt,(int)offsetof(SensorEventInfo_obj,type),HX_HCSTRING("type","\xba","\xf2","\x08","\x4d")},
{ hx::fsUnknown, 0, null()}
};
static hx::StaticInfo *SensorEventInfo_obj_sStaticStorageInfo = 0;
#endif
static ::String SensorEventInfo_obj_sMemberFields[] = {
HX_HCSTRING("id","\xdb","\x5b","\x00","\x00"),
HX_HCSTRING("x","\x78","\x00","\x00","\x00"),
HX_HCSTRING("y","\x79","\x00","\x00","\x00"),
HX_HCSTRING("z","\x7a","\x00","\x00","\x00"),
HX_HCSTRING("type","\xba","\xf2","\x08","\x4d"),
HX_HCSTRING("clone","\x5d","\x13","\x63","\x48"),
::String(null()) };
static void SensorEventInfo_obj_sMarkStatics(HX_MARK_PARAMS) {
HX_MARK_MEMBER_NAME(SensorEventInfo_obj::__mClass,"__mClass");
};
#ifdef HXCPP_VISIT_ALLOCS
static void SensorEventInfo_obj_sVisitStatics(HX_VISIT_PARAMS) {
HX_VISIT_MEMBER_NAME(SensorEventInfo_obj::__mClass,"__mClass");
};
#endif
hx::Class SensorEventInfo_obj::__mClass;
void SensorEventInfo_obj::__register()
{
hx::Static(__mClass) = new hx::Class_obj();
__mClass->mName = HX_HCSTRING("lime._backend.native._NativeApplication.SensorEventInfo","\x31","\x2b","\xf7","\xf9");
__mClass->mSuper = &super::__SGetClass();
__mClass->mConstructEmpty = &__CreateEmpty;
__mClass->mConstructArgs = &__Create;
__mClass->mGetStaticField = &hx::Class_obj::GetNoStaticField;
__mClass->mSetStaticField = &hx::Class_obj::SetNoStaticField;
__mClass->mMarkFunc = SensorEventInfo_obj_sMarkStatics;
__mClass->mStatics = hx::Class_obj::dupFunctions(0 /* sStaticFields */);
__mClass->mMembers = hx::Class_obj::dupFunctions(SensorEventInfo_obj_sMemberFields);
__mClass->mCanCast = hx::TCanCast< SensorEventInfo_obj >;
#ifdef HXCPP_VISIT_ALLOCS
__mClass->mVisitFunc = SensorEventInfo_obj_sVisitStatics;
#endif
#ifdef HXCPP_SCRIPTABLE
__mClass->mMemberStorageInfo = SensorEventInfo_obj_sMemberStorageInfo;
#endif
#ifdef HXCPP_SCRIPTABLE
__mClass->mStaticStorageInfo = SensorEventInfo_obj_sStaticStorageInfo;
#endif
hx::_hx_RegisterClass(__mClass->mName, __mClass);
}
} // end namespace lime
} // end namespace _backend
} // end namespace native
} // end namespace _NativeApplication
| [
"[email protected]"
] | |
81e45c51ffa4274a9e4c113b38433ec664f2dbbb | c6f8134410addbbbd94963e9ec5e7e03af0134a1 | /DungeonOfMadness/src/Executable/Executable.cpp | ca24b73237a233b40108cf2b5ad8bdaf5051b46b | [] | no_license | RunningFlip/DungeonOfMadness | 37d53efea6e65ff796b4b086fb7ce607b3bf5ec6 | aa7a97a0b9c13426d319c2e1b6cc121fe85e3e7e | refs/heads/master | 2022-12-13T20:54:25.527860 | 2020-09-08T17:16:46 | 2020-09-08T17:16:46 | 293,872,238 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,051 | cpp | #include "Executable.h"
#include <iostream>
Executable::Executable(const std::string _keyword, const std::string _description, const StateContainer _stateContainer)
: keyword(_keyword), extension(""), description(_description), stateContainer(_stateContainer)
{
}
Executable::Executable(const std::string _keyword, const std::string _extension, const std::string _description, const StateContainer _stateContainer)
: keyword(_keyword), extension("<" + _extension + ">"), description(_description), stateContainer(_stateContainer)
{
}
void Executable::PrintDeniedState() const
{
std::cout << "Command not valid right now." << std::endl;
}
std::string Executable::GetKeyword() { return keyword; }
std::string Executable::GetExtension() { return extension; }
std::string Executable::GetDescription() { return description; }
void Executable::Execute(const StateMachine& _stateMachine, const std::string _extension)
{
if (_stateMachine.StateIsValid(stateContainer))
{
OnExecute(_stateMachine, _extension);
}
else
{
PrintDeniedState();
}
} | [
"[email protected]"
] | |
03ed73644a7ac1f72a806829ae13f93173802654 | da4c0054515972e5f9b9daadfd6b8eb868652348 | /async_client/basicservice.h | 86404e4745d6c2650de1060e0f33fb93f279ea2a | [] | no_license | SiteView/QtRPC2 | 17ba0ddadbe8df1e50c4412bfc15ba94fd3f33ea | 7f4acb24c65c6433f6faa4865817842c09a66c62 | refs/heads/master | 2021-01-19T20:14:59.183052 | 2013-01-11T08:48:39 | 2013-01-11T08:48:39 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,959 | h | /***************************************************************************
* Copyright (c) 2010, Resara LLC
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of Resara LLC nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL RESARA LLC BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
***************************************************************************/
#ifndef BASICSERVICE_H
#define BASICSERVICE_H
#include <ClientProxy>
using namespace QtRpc;
//Client service inherit from ClientProxy
//Inheriting from another client service is also allowed
class BasicService : public ClientProxy
{
Q_OBJECT
//This macro declares a couple of operators for converting
//ReturnValues to services.
QTRPC_CLIENTPROXY(BasicService)
public:
explicit BasicService(QObject *parent = 0);
//Functions to be called over the network are signals with
//a return value of ReturnValue. Running or calling this signal
//Will call the remote services function, and return the result.
//
//Note that signals have been redeclared public, so you can call them
//from outside the class...
signals:
ReturnValue addNumbers(int a, int b);
ReturnValue returnError();
ReturnValue pause();
//Adding a QObject *, const char * to the end of a function signals
//QtRpc to make an asynchronous call, and to call the provided slot when
//the function returns.
ReturnValue pause(QObject *object, const char *slot);
ReturnValue pauseAsync(QObject *obj, const char *slot);
};
#endif // BASICSERVICE_H
| [
"[email protected]"
] | |
e9ce76073595482f58d2d1fc7ed9f881b7823b99 | 7f19b825f620086a6854aafde00ebeffab699a82 | /acctabc.h | e87b8f7140c466c2ec4e53e5677896a52bb11f26 | [] | no_license | GLnwu/Cpp_Learning_Code | 348b36617f6195be31884be3cf1a4577e08a95bc | 3aa95cf518378cabbe9f1bd939cfeda197de77dc | refs/heads/master | 2020-05-22T05:41:29.670355 | 2017-09-26T13:59:32 | 2017-09-26T13:59:32 | 53,390,987 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,058 | h | /*************************************************************************
> File Name: acctabc.h
> Copyright @2017 <gaoli>
> Mail: [email protected]
> Created Time: Sat 15 Jul 2017 09:04:08 PM CST
************************************************************************/
// acctabc.h -- bank account classes
#ifndef ACCTABC_H_
#define ACCTABC_H_
#include <iostream>
#include <string>
// Abstract Base Class
class AcctABC {
private:
std::string fullName;
long acctNum;
double balance;
protected:
struct Formatting {
std::ios_base::fmtflags flag;
std::streamsize pr;
};
// 查询私有数据成员,但不改变其值,因此可以放在保护成员中。
const std::string & FullName() const {return fullName;}
long AcctNum() const {return acctNum;}
Formatting SetFormat() const;
void Restore(Formatting & f) const; // 如不改变该引用的值,则应尽量使用常量引用
public:
AcctABC(const std::string & s = "Nullbody", long an = -1,
double bal = 0.0);
void Deposit(double amt);
virtual void Withdraw(double amt) = 0; // pure virtual function
double Balance() const {return balance;}
virtual void ViewAcct() const = 0; // pure virtual function
virtual ~AcctABC() {}
};
// Brass Account Class
class Brass : public AcctABC {
public:
Brass(const std::string & s = "Nullbody", long an = -1,
double bal = 0.0) : AcctABC(s, an, bal) {}
virtual void Withdraw(double amt);
virtual void ViewAcct() const;
virtual ~Brass() {}
};
// Brass Plus Account Class
class BrassPlus : public AcctABC {
private:
double maxLoan;
double rate;
double owesBank;
public:
BrassPlus(const std::string & s = "Nullbody", long an = -1,
double bal = 0.0, double ml = 500, double r = 0.10);
BrassPlus(const Brass & ba, double ml = 500, double r = 0.1);
virtual void ViewAcct() const;
virtual void Withdraw(double amt);
void ReserMax(double m) {maxLoan = m;}
void ResetRate(double r) {rate = r;}
void ResetOwes(){owesBank = 0;}
};
#endif // ACCTABC_H_
| [
"[email protected]"
] | |
72171aa84be9059b41004dca56b6f052cbdace03 | bd1fea86d862456a2ec9f56d57f8948456d55ee6 | /000/088/539/CWE195_Signed_to_Unsigned_Conversion_Error__rand_memmove_82_bad.cpp | eaf6f872db1f84bf8f1da5cc94881327b4f821f9 | [] | no_license | CU-0xff/juliet-cpp | d62b8485104d8a9160f29213368324c946f38274 | d8586a217bc94cbcfeeec5d39b12d02e9c6045a2 | refs/heads/master | 2021-03-07T15:44:19.446957 | 2020-03-10T12:45:40 | 2020-03-10T12:45:40 | 246,275,244 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 1,371 | cpp | /* TEMPLATE GENERATED TESTCASE FILE
Filename: CWE195_Signed_to_Unsigned_Conversion_Error__rand_memmove_82_bad.cpp
Label Definition File: CWE195_Signed_to_Unsigned_Conversion_Error.label.xml
Template File: sources-sink-82_bad.tmpl.cpp
*/
/*
* @description
* CWE: 195 Signed to Unsigned Conversion Error
* BadSource: rand Set data to result of rand(), which may be zero
* GoodSource: Positive integer
* Sinks: memmove
* BadSink : Copy strings using memmove() with the length of data
* Flow Variant: 82 Data flow: data passed in a parameter to an virtual method called via a pointer
*
* */
#ifndef OMITBAD
#include "std_testcase.h"
#include "CWE195_Signed_to_Unsigned_Conversion_Error__rand_memmove_82.h"
namespace CWE195_Signed_to_Unsigned_Conversion_Error__rand_memmove_82
{
void CWE195_Signed_to_Unsigned_Conversion_Error__rand_memmove_82_bad::action(int data)
{
{
char source[100];
char dest[100] = "";
memset(source, 'A', 100-1);
source[100-1] = '\0';
if (data < 100)
{
/* POTENTIAL FLAW: data is interpreted as an unsigned int - if its value is negative,
* the sign conversion could result in a very large number */
memmove(dest, source, data);
dest[data] = '\0'; /* NULL terminate */
}
printLine(dest);
}
}
}
#endif /* OMITBAD */
| [
"[email protected]"
] | |
4685481c86a12594a11ed386c944ba71ba34a27b | b0dd7779c225971e71ae12c1093dc75ed9889921 | /libs/scope_exit/test/world_checkpoint.cpp | ef938daff9e0f77c04a2d3aa46184864f59eaa03 | [
"LicenseRef-scancode-warranty-disclaimer",
"BSL-1.0"
] | permissive | blackberry/Boost | 6e653cd91a7806855a162347a5aeebd2a8c055a2 | fc90c3fde129c62565c023f091eddc4a7ed9902b | refs/heads/1_48_0-gnu | 2021-01-15T14:31:33.706351 | 2013-06-25T16:02:41 | 2013-06-25T16:02:41 | 2,599,411 | 244 | 154 | BSL-1.0 | 2018-10-13T18:35:09 | 2011-10-18T14:25:18 | C++ | UTF-8 | C++ | false | false | 2,934 | cpp |
// Copyright (C) 2006-2009, 2012 Alexander Nasonov
// Copyright (C) 2012 Lorenzo Caminiti
// Distributed under the Boost Software License, Version 1.0
// (see accompanying file LICENSE_1_0.txt or a copy at
// http://www.boost.org/LICENSE_1_0.txt)
// Home at http://www.boost.org/libs/scope_exit
#include <boost/config.hpp>
#ifdef BOOST_NO_VARIADIC_MACROS
# error "variadic macros required"
#else
#include <boost/scope_exit.hpp>
#include <boost/foreach.hpp>
#include <boost/typeof/typeof.hpp>
#include <boost/typeof/std/vector.hpp>
#include BOOST_TYPEOF_INCREMENT_REGISTRATION_GROUP()
#include <boost/detail/lightweight_test.hpp>
#include <vector>
#include <iostream>
#include <sstream>
struct person {
typedef unsigned int id_t;
typedef unsigned int evolution_t;
id_t id;
evolution_t evolution;
person(void) : id(0), evolution(0) {}
friend std::ostream& operator<<(std::ostream& o, person const& p) {
return o << "person(" << p.id << ", " << p.evolution << ")";
}
};
BOOST_TYPEOF_REGISTER_TYPE(person)
struct world {
world(void) : next_id_(1) {}
void add_person(person const& a_person);
friend std::ostream& operator<<(std::ostream& o, world const& w) {
o << "world(" << w.next_id_ << ", {";
BOOST_FOREACH(person const& p, w.persons_) {
o << " " << p << ", ";
}
return o << "})";
}
private:
person::id_t next_id_;
std::vector<person> persons_;
};
BOOST_TYPEOF_REGISTER_TYPE(world)
//[world_checkpoint
void world::add_person(person const& a_person) {
persons_.push_back(a_person);
// This block must be no-throw.
person& p = persons_.back();
person::evolution_t checkpoint = p.evolution;
BOOST_SCOPE_EXIT(checkpoint, &p, &persons_) {
if(checkpoint == p.evolution) persons_.pop_back();
} BOOST_SCOPE_EXIT_END
// ...
checkpoint = ++p.evolution;
// Assign new identifier to the person.
person::id_t const prev_id = p.id;
p.id = next_id_++;
BOOST_SCOPE_EXIT(checkpoint, &p, &next_id_, prev_id) {
if(checkpoint == p.evolution) {
next_id_ = p.id;
p.id = prev_id;
}
} BOOST_SCOPE_EXIT_END
// ...
checkpoint = ++p.evolution;
}
//]
int main(void) {
person adam, eva;
std::ostringstream oss;
oss << adam;
std::cout << oss.str() << std::endl;
BOOST_TEST(oss.str() == "person(0, 0)");
oss.str("");
oss << eva;
std::cout << oss.str() << std::endl;
BOOST_TEST(oss.str() == "person(0, 0)");
world w;
w.add_person(adam);
w.add_person(eva);
oss.str("");
oss << w;
std::cout << oss.str() << std::endl;
BOOST_TEST(oss.str() == "world(3, { person(1, 2), person(2, 2), })");
return boost::report_errors();
}
#endif // variadic macros
| [
"[email protected]"
] | |
d6f90039cdf624220f365b87a0cbdb7c96230150 | 51635684d03e47ebad12b8872ff469b83f36aa52 | /external/gcc-12.1.0/gcc/config/loongarch/loongarch-opts.cc | eb9c2a52f9efafe4d55937228ef4456fd1ccccc2 | [
"LGPL-2.1-only",
"GPL-3.0-only",
"GCC-exception-3.1",
"GPL-2.0-only",
"LGPL-3.0-only",
"LGPL-2.0-or-later",
"FSFAP",
"Zlib",
"LicenseRef-scancode-public-domain"
] | permissive | zhmu/ananas | 8fb48ddfe3582f85ff39184fc7a3c58725fe731a | 30850c1639f03bccbfb2f2b03361792cc8fae52e | refs/heads/master | 2022-06-25T10:44:46.256604 | 2022-06-12T17:04:40 | 2022-06-12T17:04:40 | 30,108,381 | 59 | 8 | Zlib | 2021-09-26T17:30:30 | 2015-01-31T09:44:33 | C | UTF-8 | C++ | false | false | 15,779 | cc | /* Subroutines for loongarch-specific option handling.
Copyright (C) 2021-2022 Free Software Foundation, Inc.
Contributed by Loongson Ltd.
This file is part of GCC.
GCC 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 3, or (at your option)
any later version.
GCC 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. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with GCC; see the file COPYING3. If not see
<http://www.gnu.org/licenses/>. */
#define IN_TARGET_CODE 1
#include "config.h"
#include "system.h"
#include "coretypes.h"
#include "tm.h"
#include "obstack.h"
#include "diagnostic-core.h"
#include "loongarch-cpu.h"
#include "loongarch-opts.h"
#include "loongarch-str.h"
struct loongarch_target la_target;
/* ABI-related configuration. */
#define ABI_COUNT (sizeof(abi_priority_list)/sizeof(struct loongarch_abi))
static const struct loongarch_abi
abi_priority_list[] = {
{ABI_BASE_LP64D, ABI_EXT_BASE},
{ABI_BASE_LP64F, ABI_EXT_BASE},
{ABI_BASE_LP64S, ABI_EXT_BASE},
};
/* Initialize enabled_abi_types from TM_MULTILIB_LIST. */
#ifdef LA_DISABLE_MULTILIB
#define MULTILIB_LIST_LEN 1
#else
#define MULTILIB_LIST_LEN (sizeof (tm_multilib_list) / sizeof (int) / 2)
static const int tm_multilib_list[] = { TM_MULTILIB_LIST };
#endif
static int enabled_abi_types[N_ABI_BASE_TYPES][N_ABI_EXT_TYPES] = { 0 };
#define isa_required(ABI) (abi_minimal_isa[(ABI).base][(ABI).ext])
extern "C" const struct loongarch_isa
abi_minimal_isa[N_ABI_BASE_TYPES][N_ABI_EXT_TYPES];
static inline int
is_multilib_enabled (struct loongarch_abi abi)
{
return enabled_abi_types[abi.base][abi.ext];
}
static void
init_enabled_abi_types ()
{
#ifdef LA_DISABLE_MULTILIB
enabled_abi_types[DEFAULT_ABI_BASE][DEFAULT_ABI_EXT] = 1;
#else
int abi_base, abi_ext;
for (unsigned int i = 0; i < MULTILIB_LIST_LEN; i++)
{
abi_base = tm_multilib_list[i << 1];
abi_ext = tm_multilib_list[(i << 1) + 1];
enabled_abi_types[abi_base][abi_ext] = 1;
}
#endif
}
/* Switch masks. */
#undef M
#define M(NAME) OPTION_MASK_##NAME
const int loongarch_switch_mask[N_SWITCH_TYPES] = {
/* SW_SOFT_FLOAT */ M(FORCE_SOFTF),
/* SW_SINGLE_FLOAT */ M(FORCE_F32),
/* SW_DOUBLE_FLOAT */ M(FORCE_F64),
};
#undef M
/* String processing. */
static struct obstack msg_obstack;
#define APPEND_STRING(STR) obstack_grow (&msg_obstack, STR, strlen(STR));
#define APPEND1(CH) obstack_1grow(&msg_obstack, CH);
static const char* abi_str (struct loongarch_abi abi);
static const char* isa_str (const struct loongarch_isa *isa, char separator);
static const char* arch_str (const struct loongarch_target *target);
static const char* multilib_enabled_abi_list ();
/* Misc */
static struct loongarch_abi isa_default_abi (const struct loongarch_isa *isa);
static int isa_base_compat_p (const struct loongarch_isa *set1,
const struct loongarch_isa *set2);
static int isa_fpu_compat_p (const struct loongarch_isa *set1,
const struct loongarch_isa *set2);
static int abi_compat_p (const struct loongarch_isa *isa,
struct loongarch_abi abi);
static int abi_default_cpu_arch (struct loongarch_abi abi);
/* Checking configure-time defaults. */
#ifndef DEFAULT_ABI_BASE
#error missing definition of DEFAULT_ABI_BASE in ${tm_defines}.
#endif
#ifndef DEFAULT_ABI_EXT
#error missing definition of DEFAULT_ABI_EXT in ${tm_defines}.
#endif
#ifndef DEFAULT_CPU_ARCH
#error missing definition of DEFAULT_CPU_ARCH in ${tm_defines}.
#endif
#ifndef DEFAULT_ISA_EXT_FPU
#error missing definition of DEFAULT_ISA_EXT_FPU in ${tm_defines}.
#endif
/* Handle combinations of -m machine option values
(see loongarch.opt and loongarch-opts.h). */
void
loongarch_config_target (struct loongarch_target *target,
HOST_WIDE_INT opt_switches,
int opt_arch, int opt_tune, int opt_fpu,
int opt_abi_base, int opt_abi_ext,
int opt_cmodel, int follow_multilib_list)
{
struct loongarch_target t;
if (!target)
return;
/* Initialization */
init_enabled_abi_types ();
obstack_init (&msg_obstack);
struct {
int arch, tune, fpu, abi_base, abi_ext, cmodel;
} constrained = {
M_OPT_ABSENT(opt_arch) ? 0 : 1,
M_OPT_ABSENT(opt_tune) ? 0 : 1,
M_OPT_ABSENT(opt_fpu) ? 0 : 1,
M_OPT_ABSENT(opt_abi_base) ? 0 : 1,
M_OPT_ABSENT(opt_abi_ext) ? 0 : 1,
M_OPT_ABSENT(opt_cmodel) ? 0 : 1,
};
#define on(NAME) ((loongarch_switch_mask[(SW_##NAME)] & opt_switches) \
&& (on_switch = (SW_##NAME), 1))
int on_switch;
/* 1. Target ABI */
t.abi.base = constrained.abi_base ? opt_abi_base : DEFAULT_ABI_BASE;
t.abi.ext = constrained.abi_ext ? opt_abi_ext : DEFAULT_ABI_EXT;
/* Extra switch handling. */
if (on (SOFT_FLOAT) || on (SINGLE_FLOAT) || on (DOUBLE_FLOAT))
{
switch (on_switch)
{
case SW_SOFT_FLOAT:
opt_fpu = ISA_EXT_NOFPU;
break;
case SW_SINGLE_FLOAT:
opt_fpu = ISA_EXT_FPU32;
break;
case SW_DOUBLE_FLOAT:
opt_fpu = ISA_EXT_FPU64;
break;
default:
gcc_unreachable();
}
constrained.fpu = 1;
/* The target ISA is not ready yet, but (isa_required (t.abi)
+ forced fpu) is enough for computing the forced base ABI. */
struct loongarch_isa default_isa = isa_required (t.abi);
struct loongarch_isa force_isa = default_isa;
struct loongarch_abi force_abi = t.abi;
force_isa.fpu = opt_fpu;
force_abi.base = isa_default_abi (&force_isa).base;
if (constrained.abi_base && (t.abi.base != force_abi.base))
inform (UNKNOWN_LOCATION,
"%<-m%s%> overrides %<-m%s=%s%>, adjusting ABI to %qs",
loongarch_switch_strings[on_switch],
OPTSTR_ABI_BASE, loongarch_abi_base_strings[t.abi.base],
abi_str (force_abi));
t.abi.base = force_abi.base;
}
#ifdef LA_DISABLE_MULTILIB
if (follow_multilib_list)
if (t.abi.base != DEFAULT_ABI_BASE || t.abi.ext != DEFAULT_ABI_EXT)
{
static const struct loongarch_abi default_abi
= {DEFAULT_ABI_BASE, DEFAULT_ABI_EXT};
warning (0, "ABI changed (%qs to %qs) while multilib is disabled",
abi_str (default_abi), abi_str (t.abi));
}
#endif
/* 2. Target CPU */
t.cpu_arch = constrained.arch ? opt_arch : DEFAULT_CPU_ARCH;
t.cpu_tune = constrained.tune ? opt_tune
: (constrained.arch ? DEFAULT_CPU_ARCH : DEFAULT_CPU_TUNE);
#ifdef __loongarch__
/* For native compilers, gather local CPU information
and fill the "CPU_NATIVE" index of arrays defined in
loongarch-cpu.c. */
t.cpu_native = fill_native_cpu_config (t.cpu_arch == CPU_NATIVE,
t.cpu_tune == CPU_NATIVE);
#else
if (t.cpu_arch == CPU_NATIVE)
fatal_error (UNKNOWN_LOCATION,
"%qs does not work on a cross compiler",
"-m" OPTSTR_ARCH "=" STR_CPU_NATIVE);
else if (t.cpu_tune == CPU_NATIVE)
fatal_error (UNKNOWN_LOCATION,
"%qs does not work on a cross compiler",
"-m" OPTSTR_TUNE "=" STR_CPU_NATIVE);
#endif
/* 3. Target ISA */
config_target_isa:
/* Get default ISA from "-march" or its default value. */
t.isa = loongarch_cpu_default_isa[LARCH_ACTUAL_ARCH];
/* Apply incremental changes. */
/* "-march=native" overrides the default FPU type. */
t.isa.fpu = constrained.fpu ? opt_fpu :
((t.cpu_arch == CPU_NATIVE && constrained.arch) ?
t.isa.fpu : DEFAULT_ISA_EXT_FPU);
/* 4. ABI-ISA compatibility */
/* Note:
- There IS a unique default -march value for each ABI type
(config.gcc: triplet -> abi -> default arch).
- If the base ABI is incompatible with the default arch,
try using the default -march it implies (and mark it
as "constrained" this time), then re-apply step 3. */
struct loongarch_abi abi_tmp;
const struct loongarch_isa* isa_min;
abi_tmp = t.abi;
isa_min = &isa_required (abi_tmp);
if (isa_base_compat_p (&t.isa, isa_min)); /* OK. */
else if (!constrained.arch)
{
/* Base architecture can only be implied by -march,
so we adjust that first if it is not constrained. */
int fallback_arch = abi_default_cpu_arch (t.abi);
if (t.cpu_arch == CPU_NATIVE)
warning (0, "your native CPU architecture (%qs) "
"does not support %qs ABI, falling back to %<-m%s=%s%>",
arch_str (&t), abi_str (t.abi), OPTSTR_ARCH,
loongarch_cpu_strings[fallback_arch]);
else
warning (0, "default CPU architecture (%qs) "
"does not support %qs ABI, falling back to %<-m%s=%s%>",
arch_str (&t), abi_str (t.abi), OPTSTR_ARCH,
loongarch_cpu_strings[fallback_arch]);
t.cpu_arch = fallback_arch;
constrained.arch = 1;
goto config_target_isa;
}
else if (!constrained.abi_base)
{
/* If -march is given while -mabi is not,
try selecting another base ABI type. */
abi_tmp.base = isa_default_abi (&t.isa).base;
}
else
goto fatal;
if (isa_fpu_compat_p (&t.isa, isa_min)); /* OK. */
else if (!constrained.fpu)
t.isa.fpu = isa_min->fpu;
else if (!constrained.abi_base)
/* If -march is compatible with the default ABI
while -mfpu is not. */
abi_tmp.base = isa_default_abi (&t.isa).base;
else
goto fatal;
if (0)
fatal:
fatal_error (UNKNOWN_LOCATION,
"unable to implement ABI %qs with instruction set %qs",
abi_str (t.abi), isa_str (&t.isa, '/'));
/* Using the fallback ABI. */
if (abi_tmp.base != t.abi.base || abi_tmp.ext != t.abi.ext)
{
/* This flag is only set in the GCC driver. */
if (follow_multilib_list)
{
/* Continue falling back until we find a feasible ABI type
enabled by TM_MULTILIB_LIST. */
if (!is_multilib_enabled (abi_tmp))
{
for (unsigned int i = 0; i < ABI_COUNT; i++)
{
if (is_multilib_enabled (abi_priority_list[i])
&& abi_compat_p (&t.isa, abi_priority_list[i]))
{
abi_tmp = abi_priority_list[i];
warning (0, "ABI %qs cannot be implemented due to "
"limited instruction set %qs, "
"falling back to %qs", abi_str (t.abi),
isa_str (&t.isa, '/'), abi_str (abi_tmp));
goto fallback;
}
}
/* Otherwise, keep using abi_tmp with a warning. */
#ifdef LA_DISABLE_MULTILIB
warning (0, "instruction set %qs cannot implement "
"default ABI %qs, falling back to %qs",
isa_str (&t.isa, '/'), abi_str (t.abi),
abi_str (abi_tmp));
#else
warning (0, "no multilib-enabled ABI (%qs) can be implemented "
"with instruction set %qs, falling back to %qs",
multilib_enabled_abi_list (),
isa_str (&t.isa, '/'), abi_str (abi_tmp));
#endif
}
}
fallback:
t.abi = abi_tmp;
}
else if (follow_multilib_list)
{
if (!is_multilib_enabled (t.abi))
{
inform (UNKNOWN_LOCATION,
"ABI %qs is not enabled at configure-time, "
"the linker might report an error", abi_str (t.abi));
inform (UNKNOWN_LOCATION, "ABI with startfiles: %s",
multilib_enabled_abi_list ());
}
}
/* 5. Target code model */
t.cmodel = constrained.cmodel ? opt_cmodel : CMODEL_NORMAL;
/* Cleanup and return. */
obstack_free (&msg_obstack, NULL);
*target = t;
}
/* Returns the default ABI for the given instruction set. */
static inline struct loongarch_abi
isa_default_abi (const struct loongarch_isa *isa)
{
struct loongarch_abi abi;
switch (isa->fpu)
{
case ISA_EXT_FPU64:
if (isa->base == ISA_BASE_LA64V100)
abi.base = ABI_BASE_LP64D;
break;
case ISA_EXT_FPU32:
if (isa->base == ISA_BASE_LA64V100)
abi.base = ABI_BASE_LP64F;
break;
case ISA_EXT_NOFPU:
if (isa->base == ISA_BASE_LA64V100)
abi.base = ABI_BASE_LP64S;
break;
default:
gcc_unreachable ();
}
abi.ext = ABI_EXT_BASE;
return abi;
}
/* Check if set2 is a subset of set1. */
static inline int
isa_base_compat_p (const struct loongarch_isa *set1,
const struct loongarch_isa *set2)
{
switch (set2->base)
{
case ISA_BASE_LA64V100:
return (set1->base == ISA_BASE_LA64V100);
default:
gcc_unreachable ();
}
}
static inline int
isa_fpu_compat_p (const struct loongarch_isa *set1,
const struct loongarch_isa *set2)
{
switch (set2->fpu)
{
case ISA_EXT_FPU64:
return set1->fpu == ISA_EXT_FPU64;
case ISA_EXT_FPU32:
return set1->fpu == ISA_EXT_FPU32 || set1->fpu == ISA_EXT_FPU64;
case ISA_EXT_NOFPU:
return 1;
default:
gcc_unreachable ();
}
}
static inline int
abi_compat_p (const struct loongarch_isa *isa, struct loongarch_abi abi)
{
int compatible = 1;
const struct loongarch_isa *isa2 = &isa_required (abi);
/* Append conditionals for new ISA components below. */
compatible = compatible && isa_base_compat_p (isa, isa2);
compatible = compatible && isa_fpu_compat_p (isa, isa2);
return compatible;
}
/* The behavior of this function should be consistent
with config.gcc. */
static inline int
abi_default_cpu_arch (struct loongarch_abi abi)
{
switch (abi.base)
{
case ABI_BASE_LP64D:
case ABI_BASE_LP64F:
case ABI_BASE_LP64S:
if (abi.ext == ABI_EXT_BASE)
return CPU_LOONGARCH64;
}
gcc_unreachable ();
}
static const char*
abi_str (struct loongarch_abi abi)
{
/* "/base" can be omitted. */
if (abi.ext == ABI_EXT_BASE)
return (const char*)
obstack_copy0 (&msg_obstack, loongarch_abi_base_strings[abi.base],
strlen (loongarch_abi_base_strings[abi.base]));
else
{
APPEND_STRING (loongarch_abi_base_strings[abi.base])
APPEND1 ('/')
APPEND_STRING (loongarch_abi_ext_strings[abi.ext])
APPEND1 ('\0')
return XOBFINISH (&msg_obstack, const char *);
}
}
static const char*
isa_str (const struct loongarch_isa *isa, char separator)
{
APPEND_STRING (loongarch_isa_base_strings[isa->base])
APPEND1 (separator)
if (isa->fpu == ISA_EXT_NOFPU)
{
APPEND_STRING ("no" OPTSTR_ISA_EXT_FPU)
}
else
{
APPEND_STRING (OPTSTR_ISA_EXT_FPU)
APPEND_STRING (loongarch_isa_ext_strings[isa->fpu])
}
APPEND1 ('\0')
/* Add more here. */
return XOBFINISH (&msg_obstack, const char *);
}
static const char*
arch_str (const struct loongarch_target *target)
{
if (target->cpu_arch == CPU_NATIVE)
{
if (target->cpu_native == CPU_NATIVE)
{
/* Describe a native CPU with unknown PRID. */
const char* isa_string = isa_str (&target->isa, ',');
APPEND_STRING ("PRID: 0x")
APPEND_STRING (get_native_prid_str ())
APPEND_STRING (", ISA features: ")
APPEND_STRING (isa_string)
APPEND1 ('\0')
}
else
APPEND_STRING (loongarch_cpu_strings[target->cpu_native]);
}
else
APPEND_STRING (loongarch_cpu_strings[target->cpu_arch]);
APPEND1 ('\0')
return XOBFINISH (&msg_obstack, const char *);
}
static const char*
multilib_enabled_abi_list ()
{
int enabled_abi_idx[MULTILIB_LIST_LEN] = { 0 };
const char* enabled_abi_str[MULTILIB_LIST_LEN] = { NULL };
unsigned int j = 0;
for (unsigned int i = 0; i < ABI_COUNT && j < MULTILIB_LIST_LEN; i++)
{
if (enabled_abi_types[abi_priority_list[i].base]
[abi_priority_list[i].ext])
{
enabled_abi_idx[j++] = i;
}
}
for (unsigned int k = 0; k < j; k++)
{
enabled_abi_str[k] = abi_str (abi_priority_list[enabled_abi_idx[k]]);
}
for (unsigned int k = 0; k < j - 1; k++)
{
APPEND_STRING (enabled_abi_str[k])
APPEND1 (',')
APPEND1 (' ')
}
APPEND_STRING (enabled_abi_str[j - 1])
APPEND1 ('\0')
return XOBFINISH (&msg_obstack, const char *);
}
| [
"[email protected]"
] | |
e67098a340828d10f9db657a62ec168559933d3f | a62c90044ddbe6facf263c2e7ecb3bc1d4c393b0 | /x5mgcBase/NetWork/CEventVideoInitConnection/CEventVideoInitConnectionRequest.h | e79f75ba9e2f35b81bbd3354f0a7f53680c6f62f | [] | no_license | shuyabin/x5mgc | 794a1874da915f7a11e7f6cf1b8af3ab2e9ab232 | 6b36bc06ed9fd3416368bfa1163f64877a2e4199 | refs/heads/master | 2023-01-27T19:44:34.538871 | 2020-12-11T06:43:53 | 2020-12-11T06:43:53 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 580 | h | #pragma once
#include "..//Utils.h"
#include "..//CEventQueryVideoAccountInfo/UserIdentity.h"
class CEventVideoInitConnectionRequest : public ProtoBufSerializable
{
public:
CEventVideoInitConnectionRequest();
~CEventVideoInitConnectionRequest();
virtual void * operator[](string name);
public:
UserIdentity uid;
int account = 0;
int channel = 0;
int zoneid = 0;
int roomID = 0;
int64_t trans_id = 0;
int client_device_type = 1;
int appid = 0;
std::string skey;
std::string mobile_version;
std::string m_open_id;
int logic_version = 0;
std::string android_md5;
};
| [
"[email protected]"
] | |
ab225860223cfd0454484001740a7a2e0114c36c | 33dbc182ce363645d767e22e21fc8f08390144d2 | /src/FlareStar/IAmmo.h | 57244e5d44ef2f4df8f429e20fa0d69a0bb0690d | [] | no_license | beorc/flare_star | 52275a8d791b46223c6be4069a86726656e11017 | e80ea7c882472a46650fcdebed07f383c3978c51 | refs/heads/master | 2021-03-12T23:46:49.572632 | 2018-05-13T17:13:33 | 2018-05-13T17:14:51 | 9,377,029 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 592 | h | #pragma once
#include <Ogre.h>
#include "Weapon.h"
class IAAObject;
class TiXmlElement;
class IAmmo
{
public:
virtual void Init(Ogre::Vector3 pos, Ogre::Quaternion direction) = 0;
virtual void Hit(IAAObject *obj) = 0;
virtual bool Parse(TiXmlElement* xml) = 0;
virtual void ApplyWeapon(const Weapon::WeaponDescription &descr) = 0;
virtual int GetLID() const = 0;
virtual void SetLID(int lid) = 0;
virtual void Destroy() = 0;
virtual void SetAmmoGroup(int) = 0;
virtual int GetVelocity() const = 0;
virtual bool IsMe(IAAObject *object) const = 0;
};
| [
"[email protected]"
] | |
b33645055e2103ed3bf75dacc6ac721060476f09 | c6753213698ae900fa6d632a25619ccf160764ac | /test_codes/2test.cpp | 3f44316e979c688a9e5d2874130f242c1fba0bfe | [] | no_license | aapage/test_projects | 503dc22e1ac6b7818a3a7b90a9d4c2fbac1a938e | 7f57cfb8eca05d7c3f79b17f888ef9091927528a | refs/heads/master | 2021-01-24T18:13:04.634800 | 2018-03-02T19:07:34 | 2018-03-02T19:07:34 | 123,236,553 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 474 | cpp |
#include <iostream>
using namespace std;
class middy
{
public:
string hair;
string mood;
int location;
int speak(string topic)
{
if (mood == 'happy') {cout << "I love you" << endl;}
else if (mood == 'sad') {cout << "I hate you" << endl;}
}
};
int main()
{
#int matrix1[3][3] = {{1,2,3},{4,5,6},{7,8,9}};
#matrix1[0][0]=3;
#cout << matrix1[0][0] << endl;
middy midHat;
midHat.mood = "happy";
midHat.speak("topic");
return (0);
}
| [
"[email protected]"
] | |
449a23674ba7fa399d6a538c6a8bfdf7655194e2 | 9e06ab10f02237e348c0133690e55065fe69cbfa | /src/cyberpc.cpp | f328de942a3e9cfb564682e49ba7d3a4935ba5bc | [] | no_license | rozenHadas/Cybersecurity | e1bc418e0e2f79ad78431f0006b056ffc8c00176 | 05ed7f4f36dcb3bc6291f8045da9a9ac60d589c4 | refs/heads/master | 2021-09-27T01:13:49.550629 | 2018-11-05T06:51:59 | 2018-11-05T06:51:59 | 156,172,826 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,376 | cpp |
#include "../include/cyberpc.h"
#include <vector>
#include <iostream>
#include<iterator>
using namespace std;
std::vector<std::string> cyber_pc_connections_;
CyberPC::CyberPC(std::string cyber_pc_os,std::string cyber_pc_name): cyber_pc_os_(cyber_pc_os), cyber_pc_name_(cyber_pc_name),cyber_pc_connections_(),cyber_pc_time_to_infect_(-1){}
const std:: string CyberPC::getName() {
return cyber_pc_name_;
}
void CyberPC :: setCyberPCTime(int Time){
cyber_pc_time_to_infect_ = Time;
}
void CyberPC::AddConnection(std::string second_pc){
cyber_pc_connections_.push_back(second_pc);
std::cout << "\t" << cyber_pc_name_ << " now connected to " << second_pc << std::endl;
};
void CyberPC::Infect(CyberWorm & worm){
if(cyber_pc_os_.compare(worm.getOS())==0 ){
if(cyber_worm_!=0)
delete cyber_worm_;
cyber_worm_ = new CyberWorm(worm);
cout<< " "<<cyber_pc_name_ <<" infected by "<< cyber_worm_->getName()<<endl;
int time = cyber_worm_->getTime();
setCyberPCTime (time);
}
else{
cout << " Worm "<< worm.getName()<< " is incompatible with "<< getName() << endl;
}
};
void CyberPC::Disinfect(){
cout<< " Worm "<< cyber_worm_->getName()<<" successfully removed from "<< cyber_pc_name_<< endl;
delete(cyber_worm_);
cyber_worm_= NULL;
cyber_pc_time_to_infect_=-1;
};
std:: string CyberPC:: getConnection(int i) {
return cyber_pc_connections_[i];
}
int CyberPC:: getpcTimeToInfect(){
return cyber_pc_time_to_infect_;
}
bool CyberPC::HaveWorm(){
bool ans;
if (cyber_worm_ != NULL){
ans= true;
}
else{
ans= false;
}
return ans;
}
void CyberPC :: Run(const CyberDNS & server){
if (getpcTimeToInfect()> 0){ //if she's sleeping
cout << " "<<getName() << " : "<< "Worm "<< cyber_worm_->getName()<< " is dormant"<< endl;
this->cyber_pc_time_to_infect_ = this->cyber_pc_time_to_infect_ -1;
}
else if ( cyber_pc_time_to_infect_ == 0){ //else infect computers
cout << " "<<cyber_pc_name_ << " infecting..."<< endl;
std::vector<std::string>::iterator it;
for (it = this->cyber_pc_connections_.begin(); it != this->cyber_pc_connections_.end(); it++){
CyberPC & temp = server.GetCyberPC(*it);
temp.Infect(*cyber_worm_);
}
}
}
CyberPC::~CyberPC(){
if(cyber_worm_!=0)
delete cyber_worm_;
}
| [
"[email protected]"
] | |
884778abc082e5f13d614e40ea86af48328048b5 | 3282ccae547452b96c4409e6b5a447f34b8fdf64 | /SimModel_Python_API/simmodel_swig/SimModel_Dll_lib/framework/SimMaterialLayer_EquivGlazingLayer.hxx | d6da7ed510da9cf3ec3e505d79bbc5964c548a5b | [
"MIT"
] | permissive | EnEff-BIM/EnEffBIM-Framework | c8bde8178bb9ed7d5e3e5cdf6d469a009bcb52de | 6328d39b498dc4065a60b5cc9370b8c2a9a1cddf | refs/heads/master | 2021-01-18T00:16:06.546875 | 2017-04-18T08:03:40 | 2017-04-18T08:03:40 | 28,960,534 | 3 | 0 | null | 2017-04-18T08:03:40 | 2015-01-08T10:19:18 | C++ | UTF-8 | C++ | false | false | 12,404 | hxx | // Copyright (c) 2005-2014 Code Synthesis Tools CC
//
// This program was generated by CodeSynthesis XSD, an XML Schema to
// C++ data binding compiler.
//
// This program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License version 2 as
// published by the Free Software Foundation.
//
// 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. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program; if not, write to the Free Software
// Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
//
// In addition, as a special exception, Code Synthesis Tools CC gives
// permission to link this program with the Xerces-C++ library (or with
// modified versions of Xerces-C++ that use the same license as Xerces-C++),
// and distribute linked combinations including the two. You must obey
// the GNU General Public License version 2 in all respects for all of
// the code used other than Xerces-C++. If you modify this copy of the
// program, you may extend this exception to your version of the program,
// but you are not obligated to do so. If you do not wish to do so, delete
// this exception statement from your version.
//
// Furthermore, Code Synthesis Tools CC makes a special exception for
// the Free/Libre and Open Source Software (FLOSS) which is described
// in the accompanying FLOSSE file.
//
#ifndef SIM_MATERIAL_LAYER_EQUIV_GLAZING_LAYER_HXX
#define SIM_MATERIAL_LAYER_EQUIV_GLAZING_LAYER_HXX
#ifndef XSD_USE_CHAR
#define XSD_USE_CHAR
#endif
#ifndef XSD_CXX_TREE_USE_CHAR
#define XSD_CXX_TREE_USE_CHAR
#endif
// Begin prologue.
//
//
// End prologue.
#include <xsd/cxx/config.hxx>
#if (XSD_INT_VERSION != 4000000L)
#error XSD runtime version mismatch
#endif
#include <xsd/cxx/pre.hxx>
#include <xsd/cxx/xml/char-utf8.hxx>
#include <xsd/cxx/tree/exceptions.hxx>
#include <xsd/cxx/tree/elements.hxx>
#include <xsd/cxx/tree/types.hxx>
#include <xsd/cxx/xml/error-handler.hxx>
#include <xsd/cxx/xml/dom/auto-ptr.hxx>
#include <xsd/cxx/tree/parsing.hxx>
#include <xsd/cxx/tree/parsing/byte.hxx>
#include <xsd/cxx/tree/parsing/unsigned-byte.hxx>
#include <xsd/cxx/tree/parsing/short.hxx>
#include <xsd/cxx/tree/parsing/unsigned-short.hxx>
#include <xsd/cxx/tree/parsing/int.hxx>
#include <xsd/cxx/tree/parsing/unsigned-int.hxx>
#include <xsd/cxx/tree/parsing/long.hxx>
#include <xsd/cxx/tree/parsing/unsigned-long.hxx>
#include <xsd/cxx/tree/parsing/boolean.hxx>
#include <xsd/cxx/tree/parsing/float.hxx>
#include <xsd/cxx/tree/parsing/double.hxx>
#include <xsd/cxx/tree/parsing/decimal.hxx>
namespace xml_schema
{
// anyType and anySimpleType.
//
typedef ::xsd::cxx::tree::type type;
typedef ::xsd::cxx::tree::simple_type< char, type > simple_type;
typedef ::xsd::cxx::tree::type container;
// 8-bit
//
typedef signed char byte;
typedef unsigned char unsigned_byte;
// 16-bit
//
typedef short short_;
typedef unsigned short unsigned_short;
// 32-bit
//
typedef int int_;
typedef unsigned int unsigned_int;
// 64-bit
//
typedef long long long_;
typedef unsigned long long unsigned_long;
// Supposed to be arbitrary-length integral types.
//
typedef long long integer;
typedef long long non_positive_integer;
typedef unsigned long long non_negative_integer;
typedef unsigned long long positive_integer;
typedef long long negative_integer;
// Boolean.
//
typedef bool boolean;
// Floating-point types.
//
typedef float float_;
typedef double double_;
typedef double decimal;
// String types.
//
typedef ::xsd::cxx::tree::string< char, simple_type > string;
typedef ::xsd::cxx::tree::normalized_string< char, string > normalized_string;
typedef ::xsd::cxx::tree::token< char, normalized_string > token;
typedef ::xsd::cxx::tree::name< char, token > name;
typedef ::xsd::cxx::tree::nmtoken< char, token > nmtoken;
typedef ::xsd::cxx::tree::nmtokens< char, simple_type, nmtoken > nmtokens;
typedef ::xsd::cxx::tree::ncname< char, name > ncname;
typedef ::xsd::cxx::tree::language< char, token > language;
// ID/IDREF.
//
typedef ::xsd::cxx::tree::id< char, ncname > id;
typedef ::xsd::cxx::tree::idref< char, ncname, type > idref;
typedef ::xsd::cxx::tree::idrefs< char, simple_type, idref > idrefs;
// URI.
//
typedef ::xsd::cxx::tree::uri< char, simple_type > uri;
// Qualified name.
//
typedef ::xsd::cxx::tree::qname< char, simple_type, uri, ncname > qname;
// Binary.
//
typedef ::xsd::cxx::tree::buffer< char > buffer;
typedef ::xsd::cxx::tree::base64_binary< char, simple_type > base64_binary;
typedef ::xsd::cxx::tree::hex_binary< char, simple_type > hex_binary;
// Date/time.
//
typedef ::xsd::cxx::tree::time_zone time_zone;
typedef ::xsd::cxx::tree::date< char, simple_type > date;
typedef ::xsd::cxx::tree::date_time< char, simple_type > date_time;
typedef ::xsd::cxx::tree::duration< char, simple_type > duration;
typedef ::xsd::cxx::tree::gday< char, simple_type > gday;
typedef ::xsd::cxx::tree::gmonth< char, simple_type > gmonth;
typedef ::xsd::cxx::tree::gmonth_day< char, simple_type > gmonth_day;
typedef ::xsd::cxx::tree::gyear< char, simple_type > gyear;
typedef ::xsd::cxx::tree::gyear_month< char, simple_type > gyear_month;
typedef ::xsd::cxx::tree::time< char, simple_type > time;
// Entity.
//
typedef ::xsd::cxx::tree::entity< char, ncname > entity;
typedef ::xsd::cxx::tree::entities< char, simple_type, entity > entities;
typedef ::xsd::cxx::tree::content_order content_order;
// Flags and properties.
//
typedef ::xsd::cxx::tree::flags flags;
typedef ::xsd::cxx::tree::properties< char > properties;
// Parsing/serialization diagnostics.
//
typedef ::xsd::cxx::tree::severity severity;
typedef ::xsd::cxx::tree::error< char > error;
typedef ::xsd::cxx::tree::diagnostics< char > diagnostics;
// Exceptions.
//
typedef ::xsd::cxx::tree::exception< char > exception;
typedef ::xsd::cxx::tree::bounds< char > bounds;
typedef ::xsd::cxx::tree::duplicate_id< char > duplicate_id;
typedef ::xsd::cxx::tree::parsing< char > parsing;
typedef ::xsd::cxx::tree::expected_element< char > expected_element;
typedef ::xsd::cxx::tree::unexpected_element< char > unexpected_element;
typedef ::xsd::cxx::tree::expected_attribute< char > expected_attribute;
typedef ::xsd::cxx::tree::unexpected_enumerator< char > unexpected_enumerator;
typedef ::xsd::cxx::tree::expected_text_content< char > expected_text_content;
typedef ::xsd::cxx::tree::no_prefix_mapping< char > no_prefix_mapping;
typedef ::xsd::cxx::tree::no_type_info< char > no_type_info;
typedef ::xsd::cxx::tree::not_derived< char > not_derived;
// Error handler callback interface.
//
typedef ::xsd::cxx::xml::error_handler< char > error_handler;
// DOM interaction.
//
namespace dom
{
// Automatic pointer for DOMDocument.
//
using ::xsd::cxx::xml::dom::auto_ptr;
#ifndef XSD_CXX_TREE_TREE_NODE_KEY__XML_SCHEMA
#define XSD_CXX_TREE_TREE_NODE_KEY__XML_SCHEMA
// DOM user data key for back pointers to tree nodes.
//
const XMLCh* const tree_node_key = ::xsd::cxx::tree::user_data_keys::node;
#endif
}
}
// Forward declarations.
//
namespace schema
{
namespace simxml
{
namespace ResourcesGeneral
{
class SimMaterialLayer_EquivGlazingLayer;
}
}
}
#include <memory> // ::std::auto_ptr
#include <limits> // std::numeric_limits
#include <algorithm> // std::binary_search
#include <xsd/cxx/xml/char-utf8.hxx>
#include <xsd/cxx/tree/exceptions.hxx>
#include <xsd/cxx/tree/elements.hxx>
#include <xsd/cxx/tree/containers.hxx>
#include <xsd/cxx/tree/list.hxx>
#include <xsd/cxx/xml/dom/parsing-header.hxx>
#include "simmateriallayer.hxx"
namespace schema
{
namespace simxml
{
namespace ResourcesGeneral
{
class SimMaterialLayer_EquivGlazingLayer: public ::schema::simxml::ResourcesGeneral::SimMaterialLayer
{
public:
// SimMatLayer_MaterialLayerName
//
typedef ::xml_schema::string SimMatLayer_MaterialLayerName_type;
typedef ::xsd::cxx::tree::optional< SimMatLayer_MaterialLayerName_type > SimMatLayer_MaterialLayerName_optional;
typedef ::xsd::cxx::tree::traits< SimMatLayer_MaterialLayerName_type, char > SimMatLayer_MaterialLayerName_traits;
const SimMatLayer_MaterialLayerName_optional&
SimMatLayer_MaterialLayerName () const;
SimMatLayer_MaterialLayerName_optional&
SimMatLayer_MaterialLayerName ();
void
SimMatLayer_MaterialLayerName (const SimMatLayer_MaterialLayerName_type& x);
void
SimMatLayer_MaterialLayerName (const SimMatLayer_MaterialLayerName_optional& x);
void
SimMatLayer_MaterialLayerName (::std::auto_ptr< SimMatLayer_MaterialLayerName_type > p);
// SimMatLayer_MaterialName
//
typedef ::xml_schema::idref SimMatLayer_MaterialName_type;
typedef ::xsd::cxx::tree::optional< SimMatLayer_MaterialName_type > SimMatLayer_MaterialName_optional;
typedef ::xsd::cxx::tree::traits< SimMatLayer_MaterialName_type, char > SimMatLayer_MaterialName_traits;
const SimMatLayer_MaterialName_optional&
SimMatLayer_MaterialName () const;
SimMatLayer_MaterialName_optional&
SimMatLayer_MaterialName ();
void
SimMatLayer_MaterialName (const SimMatLayer_MaterialName_type& x);
void
SimMatLayer_MaterialName (const SimMatLayer_MaterialName_optional& x);
void
SimMatLayer_MaterialName (::std::auto_ptr< SimMatLayer_MaterialName_type > p);
// SimMatLayer_LayerThickness
//
typedef ::xml_schema::double_ SimMatLayer_LayerThickness_type;
typedef ::xsd::cxx::tree::optional< SimMatLayer_LayerThickness_type > SimMatLayer_LayerThickness_optional;
typedef ::xsd::cxx::tree::traits< SimMatLayer_LayerThickness_type, char, ::xsd::cxx::tree::schema_type::double_ > SimMatLayer_LayerThickness_traits;
const SimMatLayer_LayerThickness_optional&
SimMatLayer_LayerThickness () const;
SimMatLayer_LayerThickness_optional&
SimMatLayer_LayerThickness ();
void
SimMatLayer_LayerThickness (const SimMatLayer_LayerThickness_type& x);
void
SimMatLayer_LayerThickness (const SimMatLayer_LayerThickness_optional& x);
// Constructors.
//
SimMaterialLayer_EquivGlazingLayer ();
SimMaterialLayer_EquivGlazingLayer (const RefId_type&);
SimMaterialLayer_EquivGlazingLayer (const ::xercesc::DOMElement& e,
::xml_schema::flags f = 0,
::xml_schema::container* c = 0);
SimMaterialLayer_EquivGlazingLayer (const SimMaterialLayer_EquivGlazingLayer& x,
::xml_schema::flags f = 0,
::xml_schema::container* c = 0);
virtual SimMaterialLayer_EquivGlazingLayer*
_clone (::xml_schema::flags f = 0,
::xml_schema::container* c = 0) const;
SimMaterialLayer_EquivGlazingLayer&
operator= (const SimMaterialLayer_EquivGlazingLayer& x);
virtual
~SimMaterialLayer_EquivGlazingLayer ();
// Implementation.
//
protected:
void
parse (::xsd::cxx::xml::dom::parser< char >&,
::xml_schema::flags);
protected:
SimMatLayer_MaterialLayerName_optional SimMatLayer_MaterialLayerName_;
SimMatLayer_MaterialName_optional SimMatLayer_MaterialName_;
SimMatLayer_LayerThickness_optional SimMatLayer_LayerThickness_;
};
}
}
}
#include <iosfwd>
#include <xercesc/sax/InputSource.hpp>
#include <xercesc/dom/DOMDocument.hpp>
#include <xercesc/dom/DOMErrorHandler.hpp>
namespace schema
{
namespace simxml
{
namespace ResourcesGeneral
{
}
}
}
#include <xsd/cxx/post.hxx>
// Begin epilogue.
//
//
// End epilogue.
#endif // SIM_MATERIAL_LAYER_EQUIV_GLAZING_LAYER_HXX
| [
"[email protected]"
] | |
5c1895ec2cf75f3edd05170e6b0f1436c3e0b81a | cb8c337a790b62905ad3b30f7891a4dff0ae7b6d | /st-ericsson/hardware/libcamera/include/b2r2/STECamB2R2Utils.h | 29185c8b90f8199a2a384ed0d18343313bdb3425 | [] | no_license | CustomROMs/android_vendor | 67a2a096bfaa805d47e7d72b0c7a0d7e4830fa31 | 295e660547846f90ac7ebe42a952e613dbe1b2c3 | refs/heads/master | 2020-04-27T15:01:52.612258 | 2019-03-11T13:26:23 | 2019-03-12T11:23:02 | 174,429,381 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,718 | h | #ifndef __STECAMB2R2UTILS_H__
#define __STECAMB2R2UTILS_H__
#include <IFM_Types.h>
#include <mmhwbuffer.h>
#include <mmhwbuffer_ext.h>
#include <mmhwbuffer_c_wrapper.h>
extern "C" {
#include <blt_api.h>
}
/* Utility Class to use B2R2 for CRROP, RESIZE and ROTATION */
/* HWConversion class doesnot have crop functionality */
class B2R2Utills {
public:
struct TImageData {
TImageData(): mWidth(0), mHeight(0), mBufSize(0),
mLogAddr(NULL), mPhyAddr(NULL),
mColorFmt(OMX_COLOR_FormatUnused) {
};
size_t mWidth;
size_t mHeight;
size_t mBufSize;
void* mLogAddr;
void* mPhyAddr;
OMX_COLOR_FORMATTYPE mColorFmt;
};
struct TRect {
TRect(): mX(0), mY(0),
mWidth(0), mHeight(0) {
};
int mX;
int mY;
size_t mWidth;
size_t mHeight;
};
public:
static unsigned int align16bit(unsigned int aValue);
static int crop_resize(TImageData* aSrcImage, TImageData* aIntImage, TImageData* aDstImage, TRect* aCropRect, int aPass, bool aInPlace=false);
static int crop(TImageData* aSrcImage, TImageData* aDstImage, TRect* aCropRect);
static int resize(TImageData* aSrcImage, TImageData* aDstImage);
static int crop_resize(TImageData* aSrcImage, TImageData* aDstImage, TRect* aCropRect);
private:
static int process(TImageData* aSrcImage, TImageData* aDstImage, TRect* aCropRect, int aRotation);
static blt_fmt blt_fmt_from_omx_color_format(OMX_COLOR_FORMATTYPE aOmxColorFmt);
};
#endif | [
"[email protected]"
] | |
c001d0bfc7e6b4a34edcb7987abe36431a19e96b | 84d86bf32f3849b5c5e1a9965e78c639fde49cd8 | /Assignment 3/Assignment 3/creature.cpp | 2893b72f09b4e96954042cb2b7061b0d3b6f9454 | [] | no_license | LouisT123/CSS342-Cont-d | cb9f11af99f3404455ea882deb8478cb0e11de69 | 0e8d5bf091b33bd79e71044d78988abdd22da678 | refs/heads/master | 2023-04-03T02:34:38.323542 | 2021-04-02T00:25:55 | 2021-04-02T00:25:55 | 332,897,238 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,609 | cpp | //creature.cpp
//impelementations of functions declared in timespan.h
//Louis Taing
#include "creature.h"
//Purpose: output creature coordinates
//Preconditions: takes timespan object
//Postconditions: outputs string in correct time format
std::ostream& operator<<(std::ostream& Out, const Creature& Creature) {
Out << "C(" << Creature.Row << ", " << Creature.Col << ")";
return Out;
}
//Purpose: constructor
//Preconditions: takes in Row and Col
//Postconditions: outputs Creature object
Creature::Creature(int Row, int Col) : Row(Row), Col(Col) {
initialPath = "";
}
//Purpose: check to see if creature is at exit
//Preconditions: takes in Maze
//Postconditions: outputs true or false depending on if at exit or not respectively
bool Creature::atExit(const Maze& Maze) const {
return (Row == Maze.getExitRow() && (Col == Maze.getExitColumn()));
}
//Purpose: creature "movement" through maze at runtime as well as printing solution path
//Preconditions: takes in Maze
//Postconditions: outputs solution path
string Creature::solve(Maze& Maze) {
string Path;
Maze.markAsPath(Row, Col);
if (!atExit(Maze)) {
Path = goNorth(Maze);
}
if (!atExit(Maze)) {
Path = goWest(Maze);
}
if (!atExit(Maze)) {
Path = goEast(Maze);
}
if (!atExit(Maze)) {
Path = goSouth(Maze);
}
return Path;
}
//Purpose: recursive function, creature goes north
//Preconditions: takes in Maze
//Postconditions: outputs path visited and path of solution
string Creature::goNorth(Maze& Maze) {
string Output;
if (Maze.isClear(Row - 1, Col)) {
Row = Row - 1;
Maze.markAsPath(Row, Col);
if (atExit(Maze)) {
Output = "N";
}
else {
Output = "N" + goNorth(Maze) ;
if (!atExit(Maze)) {
Output = "N" + goWest(Maze);
if (!atExit(Maze)) {
Output = "N" + goEast(Maze);
if (!atExit(Maze)) {
Maze.markAsVisited(Row, Col);
Row=Row + 1;
}
}
}
}
}
return Output;
}
//Purpose: recursive function, creature goes south
//Preconditions: takes in Maze
//Postconditions: outputs path visited and path of solution
string Creature::goSouth(Maze& Maze) {
string output;
if (Maze.isClear(Row + 1, Col)) {
Row=Row + 1;
Maze.markAsPath(Row, Col);
if (atExit(Maze)) {
output = "S";
}
else {
output = "S" + goWest(Maze);
if (!atExit(Maze)) {
output = "S" + goEast(Maze);
if (!atExit(Maze)) {
output = "S" + goSouth(Maze);
if (!atExit(Maze)) {
Maze.markAsVisited(Row, Col);
Row=Row - 1;
}
}
}
}
}
return output;
}
//Purpose: recursive function, creature goes east
//Preconditions: takes in Maze
//Postconditions: outputs path visited and path of solution
string Creature::goEast(Maze& Maze) {
string output;
if (Maze.isClear(Row, Col + 1)) {
Col = Col + 1;
Maze.markAsPath(Row, Col);
if (atExit(Maze)) {
output = "E";
}
else {
output = "E" + goNorth(Maze);
if (!atExit(Maze)) {
output = "E" + goEast(Maze);
if (!atExit(Maze)) {
output = "E" + goSouth(Maze);
if (!atExit(Maze)) {
Maze.markAsVisited(Row, Col);
Col=Col - 1;
}
}
}
}
}
return output;
}
//Purpose: recursive function, creature goes west
//Preconditions: takes in Maze
//Postconditions: outputs path visited and path of solution
string Creature::goWest(Maze& Maze) {
string output;
if (Maze.isClear(Row, Col-1)) {
Col = Col - 1;
Maze.markAsPath(Row, Col);
if (atExit(Maze)) {
output = "W";
}
else {
output = "W" + goNorth(Maze);
if (!atExit(Maze)) {
output = "W" + goWest(Maze);
if (!atExit(Maze)) {
output = "W" + goSouth(Maze);
if (!atExit(Maze)) {
Maze.markAsVisited(Row, Col);
Col=Col + 1;
}
}
}
}
}
return output;
}
| [
"[email protected]"
] | |
531ee1f2bf054a2085cb3eb8a4b7825597df99a3 | 9ca5b44b494b7e8e19a700e89734bb478df5ca5f | /BinarySearchTreeIterator.cpp | 4933521acedf639a81c5001e2b081ed3cf3b62ae | [
"BSD-3-Clause"
] | permissive | hgfeaon/leetcode | ce549f0dc8c3a7fa367f10a189f09dd6f8dbf7c6 | 1e2a562bd8341fc57a02ecff042379989f3361ea | refs/heads/master | 2021-01-25T08:59:56.033771 | 2015-03-10T06:35:51 | 2015-03-10T06:35:51 | 17,615,493 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,287 | cpp | #include <iostream>
#include <cstdlib>
#include <stack>
using namespace std;
struct TreeNode {
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
class BSTIterator {
private:
TreeNode* current;
stack<TreeNode*> nodeStack;
public:
BSTIterator(TreeNode *root) {
current = root;
}
/** @return whether we have a next smallest number */
bool hasNext() {
if (nodeStack.empty() && current == NULL) {
return false;
} else {
return true;
}
}
/** @return the next smallest number */
int next() {
while (current != NULL) {
nodeStack.push(current);
current = current->left;
}
// node current must be null,
// the last one pushed in the stack must be the smallest one
TreeNode* last = nodeStack.top();
nodeStack.pop();
// next we will start from its right sub-tree to find the smallest one
current = last->right;
return last->val;
}
};
/**
* Your BSTIterator will be called like this:
* BSTIterator i = BSTIterator(root);
* while (i.hasNext()) cout << i.next();
*/
int main() {
system("pause");
return 0;
}
| [
"[email protected]"
] | |
58b6fff77896cae3d2d0ab3257a6f5647b4543e2 | c1dbd6dde2b018f003bcbc8c9cbd0785734a4110 | /src/SimpleRootClass.cpp | 8e1524029ab65d82594b64e8be97fa22dbc9cf74 | [] | no_license | jdfrankland/autorootlib | bd2db04c36e9a70d86a9786bb7957d6e1b41eefb | da32c15220a840ab68f078c6d467b2337c119952 | refs/heads/master | 2016-09-10T00:24:30.954771 | 2013-05-24T12:12:46 | 2013-05-24T12:12:46 | 29,357,832 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,505 | cpp | //Created by KVClassFactory on Thu May 16 19:32:00 2013
//Author: John Frankland,,,
#include "SimpleRootClass.h"
ClassImp(SimpleRootClass)
////////////////////////////////////////////////////////////////////////////////
// BEGIN_HTML <!--
/* -->
<h2>SimpleRootClass</h2>
<h4>A simple class based on ROOT</h4>
<!-- */
// --> END_HTML
////////////////////////////////////////////////////////////////////////////////
SimpleRootClass::SimpleRootClass()
{
// Default constructor
Info("SimpleRootClass", "I am created");
}
//________________________________________________________________
SimpleRootClass::SimpleRootClass(const SimpleRootClass& obj) : TObject()
{
// Copy constructor
// This ctor is used to make a copy of an existing object (for example
// when a method returns an object), and it is always a good idea to
// implement it.
// If your class allocates memory in its constructor(s) then it is ESSENTIAL :-)
obj.Copy(*this);
}
SimpleRootClass::~SimpleRootClass()
{
// Destructor
}
//________________________________________________________________
void SimpleRootClass::Copy(TObject& obj) const
{
// This method copies the current state of 'this' object into 'obj'
// You should add here any member variables, for example:
// (supposing a member variable SimpleRootClass::fToto)
// CastedObj.fToto = fToto;
// or
// CastedObj.SetToto( GetToto() );
TObject::Copy(obj);
//SimpleRootClass& CastedObj = (SimpleRootClass&)obj;
}
| [
"[email protected]"
] | |
fecc2826d481bbad760d085fcbabe5499b06dbf3 | 09de839a79f88b4cfb131b78b9dfe622bfadfa6c | /Triangles/ChildView.h | 978256c14133d2646060fbcd32acbfbe5dd693eb | [] | no_license | HanshiZ/CSE335Final | 39fc5c06debe184a4a3093eecb2caeb7e92a2c60 | 008a571f67430e4a672d701fe7246036773577a8 | refs/heads/main | 2023-01-13T05:42:16.191338 | 2020-11-14T03:01:23 | 2020-11-14T03:01:23 | 312,733,705 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,778 | h | #pragma once
#include <memory>
#include <string>
#include <random>
class CTriangleMesh;
// CChildView window
/**
* Main view window.
*/
class CChildView : public CWnd
{
// Construction
public:
CChildView();
// Attributes
public:
// Operations
public:
// Overrides
protected:
virtual BOOL PreCreateWindow(CREATESTRUCT& cs);
// Implementation
public:
virtual ~CChildView();
// Generated message map functions
protected:
afx_msg void OnPaint();
DECLARE_MESSAGE_MAP()
public:
afx_msg BOOL OnEraseBkgnd(CDC* pDC);
private:
/// The mesh we are currently displaying
std::shared_ptr<CTriangleMesh> mMesh;
void SafeInvalidate();
/// True if window has not yet been drawn
bool mNotDrawnYet = true;
/// True if we fill with random colors
bool mRandomColors = false;
/// The type of filling
enum class FillType {Lines, Filled };
/// Current filling type
FillType mFillType = FillType::Lines;
void MeshFile(const std::wstring& name);
void NoMeshFile();
void SetMesh();
/// The currently loaded mesh OBJ file
std::wstring mMeshFile;
/// Random number generator
std::mt19937 mRandom;
public:
afx_msg void OnExamplesEmpty();
afx_msg void OnExamples1triangle();
afx_msg void OnExamples1filledtriangle();
afx_msg void OnExamplesBox();
afx_msg void OnExamples3triangles();
/// \cond
afx_msg void OnMeshesM();
afx_msg void OnMeshesMsu();
afx_msg void OnMeshesLines();
afx_msg void OnUpdateMeshesLines(CCmdUI* pCmdUI);
afx_msg void OnMeshesFilled();
afx_msg void OnMeshesRandomcolors();
afx_msg void OnUpdateMeshesRandomcolors(CCmdUI* pCmdUI);
afx_msg void OnUpdateMeshesFilled(CCmdUI* pCmdUI);
afx_msg void OnMeshesMichigan();
/// \endcond
};
| [
"[email protected]"
] | |
d87f55e75bca0055715ffa84f0eb4d0ce71169a8 | bd1f589153a5202e1f34f8a3fd6a654922cbce2a | /MyWrapper/OpenGLMain.h | 04ed088b29a83393d01bf0bea180cdef7d2415d7 | [] | no_license | lalitadithya/DatabaseQueryPlanVisualization | 96d87deeca022642a31bc3030cc9b07a4c2950fe | d7b4c18c33c2cd7c0f73156093f399cdeefd393a | refs/heads/master | 2022-04-16T14:26:03.864286 | 2020-04-12T10:31:05 | 2020-04-12T10:31:05 | 88,893,096 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 140 | h | #pragma once
#include "SqlQueryPlanNode.h"
#include <vector>
using namespace std;
void displayQueryPlan(SqlQueryPlanNode *root, int size); | [
"[email protected]"
] | |
1b8b688afb0897810cb6f235ae42083d325b5ffc | bb7c26963a6ee931c33e08d25c282053db3d1e45 | /Game/src/Controller.cpp | 0eee470d08124d590495431857b0c688b83f0af4 | [] | no_license | EKISUKE/GitHubTest | bf85afea50f41ccbd1df6f7cba09de7528932a63 | 961ad6edebcb0ef289b602482b6b8f90ce63b8fa | refs/heads/master | 2021-01-21T10:12:55.452091 | 2015-07-18T10:40:27 | 2015-07-18T10:40:27 | 39,287,618 | 0 | 0 | null | 2015-07-18T14:26:36 | 2015-07-18T05:18:16 | Logos | SHIFT_JIS | C++ | false | false | 9,114 | cpp | //-----------------------------------------------------------------------------
//!
//! @file Controller.cpp
//! @brief コントローラー
//! @author YukiIshigaki
//!
//-----------------------------------------------------------------------------
#include "Library.h"
//-----------------------------------------------------------------------------
//! コンストラクタ
//-----------------------------------------------------------------------------
Controller::Controller(s32 playerNum)
{
_controllerNum = playerNum -1;
int Index = 0;
for( s32 i=0; i<16; i++ ){
// 配列番号用の変数
if( i == 10 || i == 11 ){
continue;
}
XInputPadState[Index] = 0x001 << i;
// 次の番号へ
Index++;
}
// 今押しているキーと前のフレームでのキー初期化
for( s32 i=0; i<14; i++ ){
prevPadState[i] = false;
nowPadState[i] = false;
}
}
//-----------------------------------------------------------------------------
//! 更新
//-----------------------------------------------------------------------------
void Controller::Update()
{
}
//-----------------------------------------------------------------------------
//! 接続確認
//-----------------------------------------------------------------------------
bool Controller::IsConnected()
{
XINPUT_STATE state; // コントローラ情報取得用
// 初期化
ZeroMemory( &state, sizeof(XINPUT_STATE) );
// 状態取得
DWORD Result = XInputGetState(_controllerNum, &state);
if(Result == ERROR_SUCCESS){
return true; // 接続されています。
}else{
return false; // 接続されていません。
}
}
//-----------------------------------------------------------------------------
//! 入力チェック
//-----------------------------------------------------------------------------
bool Controller::GetPadState(PAD_STATE p_state)
{
XINPUT_STATE state; // コントローラ情報取得用
ZeroMemory( &state, sizeof(XINPUT_STATE) ); // 初期化
DWORD dwResult; // 関数結果判定用
// 情報取得
dwResult = XInputGetState(_controllerNum,&state);
if(dwResult == ERROR_SUCCESS){ // 情報がとれたら
CheckMode(p_state); // アナログモードかデジタルかチェック
// モードによって入力チェック切替
switch(mode){
case ANALOG: // アナログ
if(GetAnalogState(state,p_state)){return true;}
break;
case DIGITAL: // デジタル
if(GetDigitalState(state,p_state)){return true;}
break;
}
}
return false;
}
//-----------------------------------------------------------------------------
//! 今押されたかチェック
//-----------------------------------------------------------------------------
bool Controller::GetPushState(PAD_STATE p_state)
{
// つながっていなかったら処理しない
if( !IsConnected() ) return false;
// 前のフレームのキーを入れる
prevPadState[p_state] = nowPadState[p_state];
// 現在の状態のを取得
nowPadState[p_state] = GetPadState(p_state);
// 前回のそのボタンの状態が押されてなければ
if((prevPadState[p_state] ^ nowPadState[p_state]) & nowPadState[p_state] )
{
return true;
}
return false;
}
//-----------------------------------------------------------------------------
//! デジタルの入力チェック
//-----------------------------------------------------------------------------
bool Controller::GetDigitalState(XINPUT_STATE state, PAD_STATE p_state)
{
To_XInput(p_state); // XINPUTに変換
// 入力チェック
if(state.Gamepad.wButtons & p_state){return true;}
return false;
}
//-----------------------------------------------------------------------------
//! アナログの入力チェック
//-----------------------------------------------------------------------------
bool Controller::GetAnalogState(XINPUT_STATE state, PAD_STATE p_state)
{
// トリガーの入力無視範囲設定
int TRIGGER_DEADZONE = XINPUT_GAMEPAD_TRIGGER_THRESHOLD;
// スティックの入力無視判定設定
int L_STICK_THUMB_DEAD = XINPUT_GAMEPAD_LEFT_THUMB_DEADZONE;
int R_STICK_THUMB_DEAD = XINPUT_GAMEPAD_RIGHT_THUMB_DEADZONE;
// 入力の状態によって入力チェック切替
switch(p_state){
// トリガー
case PAD_LT:
if(state.Gamepad.bLeftTrigger > TRIGGER_DEADZONE){return true;}
break;
case PAD_RT:
if(state.Gamepad.bRightTrigger > TRIGGER_DEADZONE){return true;}
break;
// 左スティック
case PAD_LEFT_U_STICK:
if(state.Gamepad.sThumbLY > L_STICK_THUMB_DEAD ){return true;}
break;
case PAD_LEFT_D_STICK:
if(state.Gamepad.sThumbLY < -L_STICK_THUMB_DEAD ){return true;}
break;
case PAD_LEFT_R_STICK:
if(state.Gamepad.sThumbLX > L_STICK_THUMB_DEAD ){return true;}
break;
case PAD_LEFT_L_STICK:
if(state.Gamepad.sThumbLX < -L_STICK_THUMB_DEAD ){return true;}
break;
// 右スティック
case PAD_RIGHT_U_STICK:
if(state.Gamepad.sThumbRY > R_STICK_THUMB_DEAD ){return true;}
break;
case PAD_RIGHT_D_STICK:
if(state.Gamepad.sThumbRY < -R_STICK_THUMB_DEAD ){return true;}
break;
case PAD_RIGHT_R_STICK:
if(state.Gamepad.sThumbRX > R_STICK_THUMB_DEAD ){return true;}
break;
case PAD_RIGHT_L_STICK:
if(state.Gamepad.sThumbRX < -R_STICK_THUMB_DEAD ){return true;}
break;
}
return false;
}
//-----------------------------------------------------------------------------
//! アナログ値を取得
//! @param [in] Thumb true:左スティック false:右スティック
//! @param [in] KnockSize 押し加減 0.0f〜1.0f
//-----------------------------------------------------------------------------
Vector3 Controller::getStickState(bool Thumb, f32& KnockSize)
{
// つながっていなかったら処理しない
if( !IsConnected() ) return Vector3( 0.0f, 0.0f, 0.0f );
// スティックの入力無視判定設定
int L_STICK_THUMB_DEAD = XINPUT_GAMEPAD_LEFT_THUMB_DEADZONE;
int R_STICK_THUMB_DEAD = XINPUT_GAMEPAD_RIGHT_THUMB_DEADZONE;
/*int L_STICK_THUMB_DEAD = 32768;
int R_STICK_THUMB_DEAD = 32768;*/
Vector3 dir(0.0f, 0.0f, 0.0f);
XINPUT_STATE state;
ZeroMemory( &state, sizeof(XINPUT_STATE) ); // 初期化
DWORD dwResult; // 関数結果判定用
dwResult = XInputGetState(_controllerNum,&state);
if(dwResult == ERROR_SUCCESS){ // 情報がとれたら
// trueなら左
if( Thumb ){
Vector3 StickL(0.0f,0.0f,0.0f);
StickL._x = state.Gamepad.sThumbLX;
StickL._z = state.Gamepad.sThumbLY;
int LX = abs(StickL._x);
int LY = abs(StickL._z);
if( LX >= L_STICK_THUMB_DEAD || LY >= L_STICK_THUMB_DEAD){
dir = StickL;
}
}
else
// falseなら右
{
Vector3 StickR(0.0f,0.0f,0.0f);
StickR._x = state.Gamepad.sThumbRX;
StickR._z = state.Gamepad.sThumbRY;
int RX = abs(StickR._x);
int RY = abs(StickR._z);
if( RX >= R_STICK_THUMB_DEAD || RY >= R_STICK_THUMB_DEAD){
dir = StickR;
}
}
}
// 押し加減の計算
KnockSize = LinearInterpolation(0.0f, 1.0f, dir.length(), 32767.0f);
return dir;
}
//-----------------------------------------------------------------------------
//! XINPUTに変換
//-----------------------------------------------------------------------------
void Controller::To_XInput(PAD_STATE &p_state)
{
if( p_state >= 10 ){
p_state = (PAD_STATE)(p_state + 2);
}
p_state = (PAD_STATE)(0x001 << p_state);
}
//-----------------------------------------------------------------------------
//! 入力モードチェック
//-----------------------------------------------------------------------------
void Controller::CheckMode(PAD_STATE p_state)
{
int stateNum = p_state;
int LastDigitalNum = PAD_Y;
if( stateNum > LastDigitalNum ){
mode = ANALOG;
}else{
mode = DIGITAL;
}
}
//-----------------------------------------------------------------------------
//! 振動開始
//! @param [in] L_vib 左振動値(0.0f ~ 1.0f)
//! @param [in] R_vib 右振動値(0.0f ~ 1.0f)
//-----------------------------------------------------------------------------
void Controller::EnableVibration( f32 L_vib, f32 R_vib )
{
// 振動値を0.0~1.0fから 0 ~ 65535に変換
L_vib = 65535 * L_vib;
R_vib = 65535 * R_vib;
// 振動用の構造体
XINPUT_VIBRATION vibration;
// 初期化
ZeroMemory( &vibration, sizeof(XINPUT_VIBRATION) );
// 振動値代入
vibration.wLeftMotorSpeed = L_vib;
vibration.wRightMotorSpeed = R_vib;
// 結果転送
XInputSetState( _controllerNum, &vibration);
}
//-----------------------------------------------------------------------------
//! 振動停止
//-----------------------------------------------------------------------------
void Controller::DisableVibration()
{
// 振動用の構造体
XINPUT_VIBRATION vibration;
// 初期化
ZeroMemory( &vibration, sizeof(XINPUT_VIBRATION) );
// 振動値代入
vibration.wLeftMotorSpeed = 0;
vibration.wRightMotorSpeed = 0;
// 結果転送
XInputSetState( _controllerNum, &vibration);
}
//=============================================================================
// END OF FILE
//============================================================================= | [
"[email protected]"
] | |
6855ebb799653fc85cd69ae666332c3c138a1b04 | f7746f466bb9e52ea5e5b704d0cd8bddab489f49 | /242/hw3/qtree.cpp | 20f833c1f966c302e5695119839944e2ec096433 | [] | no_license | canerdogar/Homeworks | cc6e233cf41758bb1ffb17497de797f81cea0cf4 | ccfbcf3842297e94392e83ee0920992701593a52 | refs/heads/master | 2020-03-14T08:57:10.861469 | 2018-04-29T23:36:36 | 2018-04-29T23:36:36 | 131,536,001 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 7,265 | cpp | #include "qtree.h"
QTree::QTree(int input)
{
topLeft.setx(0);
topLeft.sety(0);
bottomRight.setx(input-1);
bottomRight.sety(input-1);
birinci=NULL;
ikinci=NULL;
ucuncu=NULL;
dorduncu=NULL;
rec=NULL;
level=0;
}
QTree::QTree(const QTree& rhs)
{
*this=rhs;
}
QTree::~QTree()
{
//cout<<"terminated"<<endl;
delete birinci;
delete ikinci;
delete ucuncu;
delete dorduncu;
}
void QTree::insert(const Rectangle& rhs)
{
Rectangle tree(this->topLeft,this->bottomRight);
if(rec==NULL && birinci==NULL && tree.intersects(rhs)){
//cout<<"bombos"<<endl;
rec=&rhs;
}else if(rec!=NULL && birinci==NULL && tree.intersects(rhs)){
//cout<<"cocuguyoksadecedikdortgen"<<endl;
const Rectangle* temp=rec;
rec=NULL;
int length=(bottomRight.getx()-topLeft.getx()+1)/2;
birinci=new QTree(length);
ikinci=new QTree(length);
ucuncu=new QTree(length);
dorduncu=new QTree(length);
//kareleri ayarla
birinci->topLeft.setx(this->topLeft.getx());//birinciyi oturtma
birinci->topLeft.sety(this->topLeft.gety());
birinci->bottomRight.setx(this->topLeft.getx()+length-1);
birinci->bottomRight.sety(this->topLeft.gety()+length-1);
birinci->level=level+1;
ikinci->topLeft.setx(birinci->topLeft.getx()+length);//ikinciyi oturtma
ikinci->topLeft.sety(birinci->topLeft.gety());
ikinci->bottomRight.setx(birinci->bottomRight.getx()+length);
ikinci->bottomRight.sety(birinci->bottomRight.gety());
ikinci->level=level+1;
ucuncu->topLeft.setx(ikinci->topLeft.getx());//ucuncuyu oturtma
ucuncu->topLeft.sety(ikinci->topLeft.gety()+length);
ucuncu->bottomRight.setx(ikinci->bottomRight.getx());
ucuncu->bottomRight.sety(ikinci->bottomRight.gety()+length);
ucuncu->level=level+1;
dorduncu->topLeft.setx(birinci->topLeft.getx());//dorduncuyu oturtma
dorduncu->topLeft.sety(birinci->topLeft.gety()+length);
dorduncu->bottomRight.setx(birinci->bottomRight.getx());
dorduncu->bottomRight.sety(birinci->bottomRight.gety()+length);
dorduncu->level=level+1;
//tempi koy
if(Rectangle(birinci->topLeft,birinci->bottomRight).intersects(*temp)){
//cout<<"birincitreeyedikdörtgenkoydum"<<endl;
birinci->rec=temp;
}
if(Rectangle(ikinci->topLeft,ikinci->bottomRight).intersects(*temp)){
ikinci->rec=temp;
//cout<<"ikincitreeyedikdörtgenkoydum"<<endl;
}
if(Rectangle(ucuncu->topLeft,ucuncu->bottomRight).intersects(*temp)){
//cout<<"ucuncutreeyedikdörtgenkoydum"<<endl;
ucuncu->rec=temp;
}
if(Rectangle(dorduncu->topLeft,dorduncu->bottomRight).intersects(*temp)){
dorduncu->rec=temp;
//cout<<"dorduncutreeyedikdörtgenkoydum"<<endl;
}
//rhsyi koy
if(Rectangle(birinci->topLeft,birinci->bottomRight).intersects(rhs)){
//cout<<"int1egirdim"<<endl;
birinci->insert(rhs);
}
if(Rectangle(ikinci->topLeft,ikinci->bottomRight).intersects(rhs)){
//cout<<"int2yegirdim"<<endl;
ikinci->insert(rhs);
}
if(Rectangle(ucuncu->topLeft,ucuncu->bottomRight).intersects(rhs)){
//cout<<"int3egirdim"<<endl;
ucuncu->insert(rhs);
}
if(Rectangle(dorduncu->topLeft,dorduncu->bottomRight).intersects(rhs)){
//cout<<"int4egirdim"<<endl;
dorduncu->insert(rhs);
}
}else if(rec==NULL && birinci!=NULL && tree.intersects(rhs)){
//cout<<"cocuguvardikdortgeniyok"<<endl;
Rectangle tree1(birinci->topLeft,birinci->bottomRight);
Rectangle tree2(ikinci->topLeft,ikinci->bottomRight);
Rectangle tree3(ucuncu->topLeft,ucuncu->bottomRight);
Rectangle tree4(dorduncu->topLeft,dorduncu->bottomRight);
if(Rectangle(birinci->topLeft,birinci->bottomRight).intersects(rhs))birinci->insert(rhs);
if(Rectangle(ikinci->topLeft,ikinci->bottomRight).intersects(rhs))ikinci->insert(rhs);
if(Rectangle(ucuncu->topLeft,ucuncu->bottomRight).intersects(rhs))ucuncu->insert(rhs);
if(Rectangle(dorduncu->topLeft,dorduncu->bottomRight).intersects(rhs))dorduncu->insert(rhs);
}
}
const Rectangle* QTree::operator[](const Coordinate& rhs) const
{
if(birinci==NULL && rec==NULL){
return NULL;
}
else if(birinci==NULL && rec!=NULL){
if(rec->contains(rhs)){
//cout<<rec->getTopLeft().getx()<<' '<<rec->getTopLeft().gety()<<endl;
return rec;
}
else{
return NULL;
}
}
else{
Rectangle can1(birinci->topLeft,birinci->bottomRight);
Rectangle can2(ikinci->topLeft,ikinci->bottomRight);
Rectangle can3(ucuncu->topLeft,ucuncu->bottomRight);
Rectangle can4(dorduncu->topLeft,dorduncu->bottomRight);
if(can1.contains(rhs)){
//cout<<"kasar";
return (*birinci)[rhs];
}else if(can2.contains(rhs)){
return (*ikinci)[rhs];
}else if(can3.contains(rhs)){
return (*ucuncu)[rhs];
}else if(can4.contains(rhs)){
return (*dorduncu)[rhs];
}else{
return NULL;
}
}
}
ostream& operator<<(ostream& out, const QTree& rhs)
{
if(rhs.rec!=NULL && rhs.birinci==NULL){
out<<'('<<rhs.topLeft.getx()<<','<<rhs.topLeft.gety()<<')'<<' ';
out<<'['<<rhs.bottomRight.getx()-rhs.topLeft.getx()+1<<']'<<' ';
out<<"***"<<' ';
out<<'('<<(rhs.rec)->getTopLeft().getx()<<','<<(rhs.rec)->getTopLeft().gety()<<')'<<' ';
out<<'['<<(rhs.rec)->getBottomRight().getx()-(rhs.rec)->getTopLeft().getx()+1<<',';
out<<(rhs.rec)->getBottomRight().gety()-(rhs.rec)->getTopLeft().gety()+1<<']'<<' ';
out<<"***"<<endl;
}else if(rhs.rec==NULL && rhs.birinci==NULL){
out<<'('<<rhs.topLeft.getx()<<','<<rhs.topLeft.gety()<<')'<<' ';
out<<'['<<rhs.bottomRight.getx()-rhs.topLeft.getx()+1<<']'<<' ';
out<<"..."<<endl;
}else if(rhs.rec==NULL && rhs.birinci!=NULL){
out<<'('<<rhs.topLeft.getx()<<','<<rhs.topLeft.gety()<<')'<<' ';
out<<'['<<rhs.bottomRight.getx()-rhs.topLeft.getx()+1<<']'<<' ';
out<<"..."<<endl;
for(int i=rhs.birinci->level;i>0;i--)out<<" ";
out<<*(rhs.birinci);
for(int i=rhs.ikinci->level;i>0;i--)out<<" ";
out<<*(rhs.ikinci);
for(int i=rhs.ucuncu->level;i>0;i--)out<<" ";
out<<*(rhs.ucuncu);
for(int i=rhs.dorduncu->level;i>0;i--)out<<" ";
out<<*(rhs.dorduncu);
}
return out;
}
QTree& QTree::operator=(const QTree& rhs)
{
if(this!=&rhs){
delete birinci;
delete ikinci;
delete ucuncu;
delete dorduncu;
if(rhs.birinci==NULL && rhs.rec==NULL)
{
this->topLeft.setx(rhs.topLeft.getx());
this->topLeft.sety(rhs.topLeft.gety());
this->bottomRight.setx(rhs.bottomRight.getx());
this->bottomRight.sety(rhs.bottomRight.gety());
birinci=ikinci=ucuncu=dorduncu=NULL;
rec=NULL;
level=rhs.level;
}else if(rhs.birinci==NULL && rhs.rec!=NULL){
topLeft.setx(rhs.topLeft.getx());
topLeft.sety(rhs.topLeft.gety());
bottomRight.setx(rhs.bottomRight.getx());
bottomRight.sety(rhs.bottomRight.gety());
birinci=ikinci=ucuncu=dorduncu=NULL;
rec=NULL;//yeni ekledin
insert(*(rhs.rec));
level=rhs.level;
}else{
topLeft.setx(rhs.topLeft.getx());
topLeft.sety(rhs.topLeft.gety());
bottomRight.setx(rhs.bottomRight.getx());
bottomRight.sety(rhs.bottomRight.gety());
level=rhs.level;
rec=NULL;
int length=(rhs.bottomRight.getx()-rhs.topLeft.getx()+1)/2;
birinci=new QTree(length);
*birinci=*(rhs.birinci);
ikinci=new QTree(length);
*ikinci=*(rhs.ikinci);
ucuncu=new QTree(length);
*ucuncu=*(rhs.ucuncu);
dorduncu=new QTree(length);
*dorduncu=*(rhs.dorduncu);
}
}
else
return *this;
}
| [
"[email protected]"
] | |
0c9925c75a5e01adcd048f827c9ab43ce2876899 | 67e5b93fe4c883c6fe4fe9a20dc3e6164f9ac169 | /Source.cpp | aa0b2b81990fe354832913aed203144eeab91254 | [] | no_license | RostyslavPanasiyuk/Deposito1 | c2e70cc024fadb0312b0a2b1cd516ca45380e618 | fccd8f92f3287bcd22326dac1ce209ec3c593896 | refs/heads/main | 2023-04-09T12:09:00.739600 | 2021-04-21T17:17:46 | 2021-04-21T17:17:46 | 360,251,446 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,088 | cpp | #include <iostream>
#include<string>
#include<string.h>
#include "Sensor.h"
#include"MagneticSensor.h"
#include "Motion_sensor.h"
#include "Smoke_sensor.h"
#include "Electronic_security_system.h"
using namespace std;
int main()
{
Electronic_security_system* ESS = new Electronic_security_system();
MagneticSensor* s1 = new MagneticSensor("MagneticSensor entrace_door");
MagneticSensor* s2 = new MagneticSensor("MagneticSensor window_bathroom");
MagneticSensor* s3 = new MagneticSensor("MagneticSensor window_kitchen");
MagneticSensor* s4 = new MagneticSensor("MagneticSensor window_bedroom1");
MagneticSensor* s5 = new MagneticSensor("MagneticSensor window_bedroom2");
MagneticSensor* s6 = new MagneticSensor("MagneticSensor window1_bedroom3");
MagneticSensor* s7 = new MagneticSensor("MagneticSensor window2_bedroom3");
MagneticSensor* s8 = new MagneticSensor("MagneticSensor window1_livingroom");
MagneticSensor* s9 = new MagneticSensor("MagneticSensor window2_livingroom");
s1->GenerateValue();
s1->GetName();
s1->GetValue();
Motion_sensor* Ms1 = new Motion_sensor("Motion_sensor holl");
Motion_sensor* Ms2 = new Motion_sensor("Motion_sensor bathroom");
Motion_sensor* Ms3 = new Motion_sensor("Motion_sensor kitchen");
Motion_sensor* Ms4 = new Motion_sensor("Motion_sensor bedroom1");
Motion_sensor* Ms5 = new Motion_sensor("Motion_sensor bedroom2");
Motion_sensor* Ms6 = new Motion_sensor("Motion_sensor bedroom3");
Motion_sensor* Ms7 = new Motion_sensor("Motion_sensor livingroom");
Ms1->GenerateValue();
Ms1->GetName();
Ms1->GetValue();
Smoke_sensor* SS1 = new Smoke_sensor("Smoke_sensor holl");
Smoke_sensor* SS2 = new Smoke_sensor("Smoke_sensor bathroom");
Smoke_sensor* SS3 = new Smoke_sensor("Smoke_sensor kitchen");
Smoke_sensor* SS4 = new Smoke_sensor("Smoke_sensor bedroom1");
Smoke_sensor* SS5 = new Smoke_sensor("Smoke_sensor bedroom2");
Smoke_sensor* SS6 = new Smoke_sensor("Smoke_sensor bedroom3");
Smoke_sensor* SS7 = new Smoke_sensor("Smoke_sensor livingroom");
SS1->GenerateValue();
SS1->GetName();
SS1->GetValue();
return 0;
} | [
"[email protected]"
] | |
79fbefcfa3d7bd298f2131afc93baec597a7b932 | 9240ceb15f7b5abb1e4e4644f59d209b83d70066 | /sp/src/public/stringregistry.cpp | beaf3767e14a303e0df3f7d690d7ddcccedc317d | [
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | Margen67/blamod | 13e5cd9f7f94d1612eb3f44a2803bf2f02a3dcbe | d59b5f968264121d013a81ae1ba1f51432030170 | refs/heads/master | 2023-04-16T12:05:12.130933 | 2019-02-20T10:23:04 | 2019-02-20T10:23:04 | 264,556,156 | 2 | 0 | NOASSERTION | 2020-05-17T00:47:56 | 2020-05-17T00:47:55 | null | UTF-8 | C++ | false | false | 4,545 | cpp | //========= Copyright Valve Corporation, All rights reserved. ============//
//
// Purpose: A registry of strings and associated ints
//
// $Workfile: $
// $Date: $
//
//-----------------------------------------------------------------------------
// $Log: $
//
// $NoKeywords: $
//=============================================================================//
#include <stdio.h>
#include <string.h>
#include "stringregistry.h"
#include "utldict.h"
// memdbgon must be the last include file in a .cpp file!!!
#include "tier0/memdbgon.h"
#if !defined(_STATIC_LINKED) || defined(CLIENT_DLL)
//-----------------------------------------------------------------------------
// Purpose: This class wraps the containers that do the actual work
//-----------------------------------------------------------------------------
struct StringTable_t : public CUtlDict<int, unsigned short>
{
};
//-----------------------------------------------------------------------------
// Purpose: Add null terminated string to the string registry
// Input :
// Output :
//-----------------------------------------------------------------------------
unsigned short CStringRegistry::AddString(const char *stringText, int stringID)
{
return m_pStringList->Insert( stringText, stringID );
}
//-----------------------------------------------------------------------------
// Purpose: Given string text get the string ID
// Input : Text of string to find
// Output : Return string id or -1 if no such string exists
//-----------------------------------------------------------------------------
int CStringRegistry::GetStringID( const char *stringText )
{
unsigned short index = m_pStringList->Find( stringText );
if ( m_pStringList->IsValidIndex( index ) )
{
return (*m_pStringList)[index];
}
return -1;
}
//-----------------------------------------------------------------------------
// Purpose: Given a string ID return the string text
// Input : ID of string to find
// Output : Return string text of NULL of no such ID exists
//-----------------------------------------------------------------------------
char const *CStringRegistry::GetStringText( int stringID )
{
for( unsigned short index = m_pStringList->First() ; index != m_pStringList->InvalidIndex(); index = m_pStringList->Next( index ) )
{
if ( (*m_pStringList)[index] == stringID )
{
return m_pStringList->GetElementName( index );
}
}
return NULL;
}
//-----------------------------------------------------------------------------
// Purpose: Given a key return the string text
//-----------------------------------------------------------------------------
char const *CStringRegistry::GetStringForKey( unsigned short key )
{
if ( !m_pStringList->IsValidIndex( key ) )
return NULL;
return m_pStringList->GetElementName( key );
}
//-----------------------------------------------------------------------------
// Purpose: Given a key return the string text
//-----------------------------------------------------------------------------
int CStringRegistry::GetIDForKey( unsigned short key )
{
if ( !m_pStringList->IsValidIndex( key ) )
return 0;
return (*m_pStringList)[key];
}
//-----------------------------------------------------------------------------
// Purpose: Clear all strings from the string registry
//-----------------------------------------------------------------------------
void CStringRegistry::ClearStrings(void)
{
m_pStringList->RemoveAll();
}
//-----------------------------------------------------------------------------
// Purpose: Destructor - delete the list of strings and maps
// Input :
// Output :
//-----------------------------------------------------------------------------
CStringRegistry::~CStringRegistry(void)
{
delete m_pStringList;
}
//-----------------------------------------------------------------------------
// Purpose: Constructor
// Input :
// Output :
//-----------------------------------------------------------------------------
CStringRegistry::CStringRegistry(void)
{
m_pStringList = new StringTable_t;
}
unsigned short CStringRegistry::First() const
{
return m_pStringList->First();
}
unsigned short CStringRegistry::Next( unsigned short key ) const
{
return m_pStringList->Next( key );
}
unsigned short CStringRegistry::InvalidIndex() const
{
return m_pStringList->InvalidIndex();
}
#endif // _STATIC_LINKED && CLIENT_DLL
| [
"[email protected]"
] | |
a126e89bd34f31d40c351264365891b2b1eb5f7f | 9694e35e70331ee2e417b9796b13dde80134a25f | /Empty.h | aa8ba002b04d43760df39a3b80fc75e8c0787ca3 | [
"MIT"
] | permissive | BishWhite/Projekt-c-szachy | 9dc90fca372d186ee81d00ec8519e59228dae015 | 5e1d01f3bfdf6fd2e2417b661f5b54f86fc3315f | refs/heads/main | 2023-06-12T23:17:18.935341 | 2021-06-30T10:43:11 | 2021-06-30T10:43:11 | 381,157,507 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 356 | h |
#ifndef ULTIMATETERMINALCHESS_EMPTY_H
#define ULTIMATETERMINALCHESS_EMPTY_H
#include <iostream>
#include <vector>
#include "Field.h"
class Empty : public Field {
int x=0; int y=0;
int x0=0;int y0=0;
public:
bool color;
string name = "E";
Empty( int x, int y, int x0, int y0, bool color);
};
#endif //ULTIMATETERMINALCHESS_EMPTY_H
| [
"[email protected]"
] | |
8e2db2f73ad11f456921734388c8a9297fa7dc4e | 4b27033174f3f27e2efc107b80af4cab349f2b9b | /lib-display/include/ssd1306.h | 10fc54d810d687c9611546c15d3ff86f35a1f25f | [] | no_license | Adco28k/rpidmx512 | aeed26049217f29172615ed5ceeccae8ab21b531 | fe9278265603807b453237ed294a4cc8709ed039 | refs/heads/master | 2022-07-19T22:18:32.157884 | 2020-05-28T19:07:40 | 2020-05-28T19:07:40 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,711 | h | /**
* @file ssd1306.h
*
*/
/* Copyright (C) 2017-2020 by Arjan van Vught mailto:[email protected]
*
* 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.
*/
#ifndef SSD1306_H_
#define SSD1306_H_
#include <stdint.h>
#include "displayset.h"
#define OLED_I2C_SLAVE_ADDRESS_DEFAULT 0x3C
enum TOledPanel {
OLED_PANEL_128x64_8ROWS, ///< Default
OLED_PANEL_128x64_4ROWS,
OLED_PANEL_128x32_4ROWS
};
class Ssd1306: public DisplaySet {
public:
Ssd1306 (void);
Ssd1306 (TOledPanel);
Ssd1306 (uint8_t, TOledPanel);
~Ssd1306 (void);
bool Start(void);
void Cls(void);
void ClearLine(uint8_t);
void PutChar(int);
void PutString(const char *);
void TextLine(uint8_t, const char *, uint8_t);
void Text(const char *, uint8_t);
void SetCursorPos(uint8_t, uint8_t);
void SetSleep(bool bSleep) override;
bool IsSH1106(void) {
return m_bHaveSH1106;
}
#if defined(ENABLE_CURSOR_MODE)
void SetCursor(CursorMode);
#endif
static Ssd1306* Get(void) {
return s_pThis;
}
private:
void Setup(void);
void CheckSH1106(void);
void InitMembers(void);
void SendCommand(uint8_t);
void SendData(const uint8_t *, uint32_t);
#if defined(ENABLE_CURSOR_MODE)
void SetCursorOn(void);
void SetCursorOff(void);
void SetCursorBlinkOn(void);
#endif
#ifndef NDEBUG
void DumpShadowRam(void);
#endif
private:
uint8_t m_nSlaveAddress;
TOledPanel m_OledPanel;
uint32_t m_nPages;
#if defined(ENABLE_CURSOR_MODE)
CursorMode m_tCursorMode = CursorMode::OFF;
#endif
alignas(uintptr_t) char *m_pShadowRam;
uint16_t m_nShadowRamIndex;
uint8_t m_nCursorOnChar;
uint8_t m_nCursorOnCol;
uint8_t m_nCursorOnRow;
bool m_bHaveSH1106;
static Ssd1306 *s_pThis;
};
#endif /* SSD1306_H_ */
| [
"[email protected]"
] | |
f1e160aeda45a420ece0b85f6220ba8e3097fdcb | b9c1098de9e26cedad92f6071b060dfeb790fbae | /3rdparty/openmpt/include/ancient/src/NUKEDecompressor.cpp | 5f154585345baea823e76b1644ef4a0e910ffff7 | [
"BSD-2-Clause",
"BSD-3-Clause",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | vitamin-caig/zxtune | 2a6f38a941f3ba2548a0eb8310eb5c61bb934dbe | 9940f3f0b0b3b19e94a01cebf803d1a14ba028a1 | refs/heads/master | 2023-08-31T01:03:45.603265 | 2023-08-27T11:50:45 | 2023-08-27T11:51:26 | 13,986,319 | 138 | 13 | null | 2021-09-13T13:58:32 | 2013-10-30T12:51:01 | C++ | UTF-8 | C++ | false | false | 3,577 | cpp | /* Copyright (C) Teemu Suutari */
#include <cstring>
#include "NUKEDecompressor.hpp"
#include "DLTADecode.hpp"
#include "InputStream.hpp"
#include "OutputStream.hpp"
#include "common/Common.hpp"
namespace ancient::internal
{
bool NUKEDecompressor::detectHeaderXPK(uint32_t hdr) noexcept
{
return hdr==FourCC("NUKE") || hdr==FourCC("DUKE");
}
std::unique_ptr<XPKDecompressor> NUKEDecompressor::create(uint32_t hdr,uint32_t recursionLevel,const Buffer &packedData,std::unique_ptr<XPKDecompressor::State> &state,bool verify)
{
return std::make_unique<NUKEDecompressor>(hdr,recursionLevel,packedData,state,verify);
}
NUKEDecompressor::NUKEDecompressor(uint32_t hdr,uint32_t recursionLevel,const Buffer &packedData,std::unique_ptr<XPKDecompressor::State> &state,bool verify) :
XPKDecompressor(recursionLevel),
_packedData(packedData)
{
if (!detectHeaderXPK(hdr)) throw Decompressor::InvalidFormatError();
if (hdr==FourCC("DUKE")) _isDUKE=true;
}
NUKEDecompressor::~NUKEDecompressor()
{
// nothing needed
}
const std::string &NUKEDecompressor::getSubName() const noexcept
{
static std::string nameN="XPK-NUKE: LZ77-compressor";
static std::string nameD="XPK-DUKE: LZ77-compressor with delta encoding";
return (_isDUKE)?nameD:nameN;
}
void NUKEDecompressor::decompressImpl(Buffer &rawData,const Buffer &previousData,bool verify)
{
// there are 2 streams, reverse stream for bytes and
// normal stream for bits, the bit stream is divided
// into single bit, 2 bit, 4 bit and random accumulator
ForwardInputStream forwardInputStream(_packedData,0,_packedData.size());
BackwardInputStream backwardInputStream(_packedData,0,_packedData.size());
forwardInputStream.link(backwardInputStream);
backwardInputStream.link(forwardInputStream);
MSBBitReader<ForwardInputStream> bit1Reader(forwardInputStream);
MSBBitReader<ForwardInputStream> bit2Reader(forwardInputStream);
LSBBitReader<ForwardInputStream> bit4Reader(forwardInputStream);
MSBBitReader<ForwardInputStream> bitXReader(forwardInputStream);
auto readBit=[&]()->uint32_t
{
return bit1Reader.readBitsBE16(1);
};
auto read2Bits=[&]()->uint32_t
{
return bit2Reader.readBitsBE16(2);
};
auto read4Bits=[&]()->uint32_t
{
return bit4Reader.readBitsBE32(4);
};
auto readBits=[&](uint32_t count)->uint32_t
{
return bitXReader.readBitsBE16(count);
};
auto readByte=[&]()->uint8_t
{
return backwardInputStream.readByte();
};
ForwardOutputStream outputStream(rawData,0,rawData.size());
for (;;)
{
if (!readBit())
{
uint32_t count=0;
if (readBit())
{
count=1;
} else {
uint32_t tmp;
do {
tmp=read2Bits();
if (tmp) count+=5-tmp;
else count+=3;
} while (!tmp);
}
for (uint32_t i=0;i<count;i++) outputStream.writeByte(readByte());
}
if (outputStream.eof()) break;
uint32_t distanceIndex=read4Bits();
static const uint8_t distanceBits[16]={
4,6,8,9,
4,7,9,11,13,14,
5,7,9,11,13,14};
static const uint32_t distanceAdditions[16]={
0,0x10,0x50,0x150,
0,0x10,0x90,0x290,0xa90,0x2a90,
0,0x20,0xa0,0x2a0,0xaa0,0x2aa0};
uint32_t distance=readBits(distanceBits[distanceIndex])+distanceAdditions[distanceIndex];
uint32_t count=(distanceIndex<4)?2:(distanceIndex<10)?3:0;
if (!count)
{
count=read2Bits();
if (!count)
{
count=3+3;
uint32_t tmp;
do {
tmp=read4Bits();
if (tmp) count+=16-tmp;
else count+=15;
} while (!tmp);
} else count=3+4-count;
}
outputStream.copy(distance,count);
}
if (_isDUKE)
DLTADecode::decode(rawData,rawData,0,rawData.size());
}
}
| [
"[email protected]"
] | |
6917d553e2188a165461ecc6259f1482bc362cad | 5a5613ab04d4f9849653decd0371d8e27d6970bf | /Micromegas/Simone/Tesi/Isto_costa.cxx | 95ed97811918c3826999f9f62a03c07dc8d971f1 | [] | no_license | MMPavia/Micromegas | 529ec648bb1001b8cc3fc0b624f9199f8bd8e11b | 83bab7bc6d8e298bd6fcb6570167819cfd28cf8b | refs/heads/master | 2020-06-10T21:26:28.199898 | 2019-07-24T13:35:10 | 2019-07-24T13:35:10 | 75,877,331 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,773 | cxx | #include <stdio.h>
#include <string>
#include <vector>
#define inpath "/Users/simonesottocornola/Documents/Uni/MicroMegas/Misure_qaqc/Tesi/"
#define outpath "/Users/simonesottocornola/Documents/Uni/MicroMegas/Misure_qaqc/Tesi/output"
void Isto_costa (TString scan){
// style option
gStyle->SetPalette(1);
gStyle->SetOptStat(111111);
gStyle->SetPaintTextFormat(".3f");
// file containing the data
ostringstream file1;
file1 << inpath << scan ;
// create all the histograms
TH1F *frame1 = new TH1F("Punto1","punto1", 20, 25.88, 26.01 );
cout << "histos created " << endl;
//variables for reading the file
Float_t x;
Int_t nmis;
// reading the file
ifstream in(file1.str().c_str());
if (!in || in.bad() )
{
cout << "file non letto" << endl;
return; // sanity check
}
cout << "starting reading file " << endl;
// looping on the file lines
while (1) {
in >> nmis;
if ( !in.good() || in.eof()) break; // another sanity check
cout <<"nmis " << nmis << endl;
in >> x;
cout <<"x" << " " << x<< endl;
frame1->Fill(x);
} // end while
cout << "file completed "<< endl;
// close the input file
in.close();
// create a root file for the histograms;
ostringstream rootfile;
rootfile << outpath <<"myout_"<<scan <<".root";
TFile myroot(rootfile.str().c_str(), "RECREATE");
cout << "Root output file: " << endl << rootfile.str() << endl;
ostringstream Smedia1;
Smedia1 << outpath <<"myout_" << scan << "_Isto_costa.png";
// create a canvas for each plot and drawing with different options
TCanvas *c0 = new TCanvas();
frame1->SetLineColor(kRed);
frame1->Draw();
frame1->Write();
c0->Print(Smedia1.str().c_str());
//myroot.Close();
return;
}
| [
"[email protected]"
] | |
7eb347a1d2336795fdf1522e0616ee2e6bbccbd3 | 69784e105ddc2aca3699b6b07dbcb1834d7c242c | /Classes/Native/mscorlib_System_Collections_Generic_Dictionary_2_K3442153334.h | 2443f5a0943dbc3aebfea822544cf46b58a69b8d | [] | no_license | ryanmcgrail95/CRHC-iOS | 7e72139100b2140143deb424d21fdc69b2959ed1 | 1b00260e6c59f552d9a8b94e42fcae5e657a6c46 | refs/heads/master | 2021-06-12T11:21:33.461817 | 2017-03-04T01:08:34 | 2017-03-04T01:08:34 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,340 | h | #pragma once
#include "il2cpp-config.h"
#ifndef _MSC_VER
# include <alloca.h>
#else
# include <malloc.h>
#endif
#include <stdint.h>
// System.Collections.Generic.Dictionary`2<UnityEngine.UI.Graphic,System.Int32>
struct Dictionary_2_t958655563;
#include "mscorlib_System_Object2689449295.h"
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// System.Collections.Generic.Dictionary`2/KeyCollection<UnityEngine.UI.Graphic,System.Int32>
struct KeyCollection_t3442153334 : public Il2CppObject
{
public:
// System.Collections.Generic.Dictionary`2<TKey,TValue> System.Collections.Generic.Dictionary`2/KeyCollection::dictionary
Dictionary_2_t958655563 * ___dictionary_0;
public:
inline static int32_t get_offset_of_dictionary_0() { return static_cast<int32_t>(offsetof(KeyCollection_t3442153334, ___dictionary_0)); }
inline Dictionary_2_t958655563 * get_dictionary_0() const { return ___dictionary_0; }
inline Dictionary_2_t958655563 ** get_address_of_dictionary_0() { return &___dictionary_0; }
inline void set_dictionary_0(Dictionary_2_t958655563 * value)
{
___dictionary_0 = value;
Il2CppCodeGenWriteBarrier(&___dictionary_0, value);
}
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
| [
"[email protected]"
] | |
3032824fb805bf33efa40685b8475534d4d161c7 | 211b528bcafd591781c8ce24dc474f3024ac5da9 | /include/NTL/ZZ.h | 8b6a70e648f952d9d59e9ffacb6f1db550448744 | [] | no_license | DanielDenshikov/cryptoSystem | 471a97fb03ff22c5790e5484f78c3915b5b81ed6 | d06d3408cf0781508986680df519c40351d92758 | refs/heads/master | 2020-08-26T14:55:45.110583 | 2019-10-23T20:47:38 | 2019-10-23T20:47:38 | 217,046,747 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 38,410 | h |
#ifndef NTL_ZZ__H
#define NTL_ZZ__H
/********************************************************
LIP INTERFACE
The class ZZ implements signed, arbitrary length integers.
**********************************************************/
#include <NTL/lip.h>
#include <NTL/tools.h>
#include <NTL/vector.h>
#include <NTL/SmartPtr.h>
#include <NTL/sp_arith.h>
NTL_OPEN_NNS
class ZZ_p; // forward declaration
class ZZX;
class ZZ {
public:
typedef ZZ_p residue_type;
typedef ZZX poly_type;
class Deleter {
public:
static void apply(_ntl_gbigint p) { _ntl_gfree(p); }
};
WrappedPtr<_ntl_gbigint_body, Deleter> rep;
// This is currently public for "emergency" situations
// May be private in future versions.
ZZ() { }
explicit ZZ(long a) { *this = a; }
ZZ(INIT_SIZE_TYPE, long k)
// initial value is 0, but space is pre-allocated so that numbers
// x with x.size() <= k can be stored without re-allocation.
// Call with ZZ(INIT_SIZE, k).
// The purpose for the INIT_SIZE argument is to prevent automatic
// type conversion from long to ZZ, which would be tempting, but wrong.
{
_ntl_gsetlength(&rep, k);
}
ZZ(const ZZ& a)
// initial value is a.
{
_ntl_gcopy(a.rep, &rep);
}
ZZ(INIT_VAL_TYPE, long a) { _ntl_gintoz(a, &rep); }
ZZ(INIT_VAL_TYPE, int a) { _ntl_gintoz(a, &rep); }
ZZ(INIT_VAL_TYPE, unsigned long a) { _ntl_guintoz(a, &rep); }
ZZ(INIT_VAL_TYPE, unsigned int a) { _ntl_guintoz((unsigned long) a, &rep); }
inline ZZ(INIT_VAL_TYPE, const char *);
inline ZZ(INIT_VAL_TYPE, float);
inline ZZ(INIT_VAL_TYPE, double);
ZZ& operator=(const ZZ& a) { _ntl_gcopy(a.rep, &rep); return *this; }
ZZ& operator=(long a) { _ntl_gintoz(a, &rep); return *this; }
void kill()
// force the space held by this ZZ to be released.
// The value then becomes 0.
{ rep.kill(); }
void swap(ZZ& x)
{ _ntl_gswap(&rep, &x.rep); }
void SetSize(long k)
// pre-allocates space for k-digit numbers (base 2^NTL_ZZ_NBITS);
// does not change the value.
{ _ntl_gsetlength(&rep, k); }
long size() const
// returns the number of (NTL_ZZ_NBIT-bit) digits of |a|; the size of 0 is 0.
{ return _ntl_gsize(rep); }
long null() const
// test of rep is null
{ return !rep; }
long MaxAlloc() const
// returns max allocation request, possibly rounded up a bit...
{ return _ntl_gmaxalloc(rep); }
long SinglePrecision() const
{ return _ntl_gsptest(rep); }
// tests if less than NTL_SP_BOUND in absolute value
long WideSinglePrecision() const
{ return _ntl_gwsptest(rep); }
// tests if less than NTL_WSP_BOUND in absolute value
static const ZZ& zero();
ZZ(ZZ& x, INIT_TRANS_TYPE) { rep.swap(x.rep); }
// used to cheaply hand off memory management of return value,
// without copying, assuming compiler implements the
// "return value optimization". This is probably obsolete by
// now, as modern compilers can and should optimize
// the copy constructor in the situations where this is used.
// This should only be used for simple, local variables
// that are not be subject to special memory management.
// mainly for internal consumption by ZZWatcher
void KillBig() { if (MaxAlloc() > NTL_RELEASE_THRESH) kill(); }
long validate() { return _ntl_gvalidate(rep); }
};
class ZZWatcher {
public:
ZZ& watched;
explicit
ZZWatcher(ZZ& _watched) : watched(_watched) {}
~ZZWatcher() { watched.KillBig(); }
};
#define NTL_ZZRegister(x) NTL_TLS_LOCAL(ZZ, x); ZZWatcher _WATCHER__ ## x(x)
const ZZ& ZZ_expo(long e);
inline void clear(ZZ& x)
// x = 0
{ _ntl_gzero(&x.rep); }
inline void set(ZZ& x)
// x = 1
{ _ntl_gone(&x.rep); }
inline void swap(ZZ& x, ZZ& y)
// swap the values of x and y (swaps pointers only)
{ x.swap(y); }
inline double log(const ZZ& a)
{ return _ntl_glog(a.rep); }
/**********************************************************
Conversion routines.
***********************************************************/
inline void conv(ZZ& x, const ZZ& a) { x = a; }
inline ZZ to_ZZ(const ZZ& a) { return a; }
inline void conv(ZZ& x, long a) { _ntl_gintoz(a, &x.rep); }
inline ZZ to_ZZ(long a) { return ZZ(INIT_VAL, a); }
inline void conv(ZZ& x, int a) { _ntl_gintoz(long(a), &x.rep); }
inline ZZ to_ZZ(int a) { return ZZ(INIT_VAL, a); }
inline void conv(ZZ& x, unsigned long a) { _ntl_guintoz(a, &x.rep); }
inline ZZ to_ZZ(unsigned long a) { return ZZ(INIT_VAL, a); }
inline void conv(ZZ& x, unsigned int a) { _ntl_guintoz((unsigned long)(a), &x.rep); }
inline ZZ to_ZZ(unsigned int a) { return ZZ(INIT_VAL, a); }
void conv(ZZ& x, const char *s);
inline ZZ::ZZ(INIT_VAL_TYPE, const char *s) { conv(*this, s); }
inline ZZ to_ZZ(const char *s) { return ZZ(INIT_VAL, s); }
inline void conv(ZZ& x, double a) { _ntl_gdoubtoz(a, &x.rep); }
inline ZZ::ZZ(INIT_VAL_TYPE, double a) { conv(*this, a); }
inline ZZ to_ZZ(double a) { return ZZ(INIT_VAL, a); }
inline void conv(ZZ& x, float a) { _ntl_gdoubtoz(double(a), &x.rep); }
inline ZZ::ZZ(INIT_VAL_TYPE, float a) { conv(*this, a); }
inline ZZ to_ZZ(float a) { return ZZ(INIT_VAL, a); }
inline void conv(long& x, const ZZ& a) { x = _ntl_gtoint(a.rep); }
inline long to_long(const ZZ& a) { return _ntl_gtoint(a.rep); }
inline void conv(int& x, const ZZ& a)
{ unsigned int res = (unsigned int) _ntl_gtouint(a.rep);
x = NTL_UINT_TO_INT(res); }
inline int to_int(const ZZ& a)
{ unsigned int res = (unsigned int) _ntl_gtouint(a.rep);
return NTL_UINT_TO_INT(res); }
inline void conv(unsigned long& x, const ZZ& a) { x = _ntl_gtouint(a.rep); }
inline unsigned long to_ulong(const ZZ& a) { return _ntl_gtouint(a.rep); }
inline void conv(unsigned int& x, const ZZ& a)
{ x = (unsigned int)(_ntl_gtouint(a.rep)); }
inline unsigned int to_uint(const ZZ& a)
{ return (unsigned int)(_ntl_gtouint(a.rep)); }
inline void conv(double& x, const ZZ& a) { x = _ntl_gdoub(a.rep); }
inline double to_double(const ZZ& a) { return _ntl_gdoub(a.rep); }
inline void conv(float& x, const ZZ& a) { x = float(_ntl_gdoub(a.rep)); }
inline float to_float(const ZZ& a) { return float(_ntl_gdoub(a.rep)); }
inline void ZZFromBytes(ZZ& x, const unsigned char *p, long n)
{ _ntl_gfrombytes(&x.rep, p, n); }
inline ZZ ZZFromBytes(const unsigned char *p, long n)
{ ZZ x; ZZFromBytes(x, p, n); NTL_OPT_RETURN(ZZ, x); }
inline void BytesFromZZ(unsigned char *p, const ZZ& a, long n)
{ _ntl_gbytesfromz(p, a.rep, n); }
// ****** comparisons
inline long sign(const ZZ& a)
// returns the sign of a (-1, 0, or 1).
{ return _ntl_gsign(a.rep); }
inline long compare(const ZZ& a, const ZZ& b)
// returns the sign of a-b (-1, 0, or 1).
{
return _ntl_gcompare(a.rep, b.rep);
}
inline long IsZero(const ZZ& a)
// zero test
{ return _ntl_giszero(a.rep); }
inline long IsOne(const ZZ& a)
{ return _ntl_gisone(a.rep); }
// test for 1
/* the usual comparison operators */
inline long operator==(const ZZ& a, const ZZ& b)
{ return _ntl_gcompare(a.rep, b.rep) == 0; }
inline long operator!=(const ZZ& a, const ZZ& b)
{ return _ntl_gcompare(a.rep, b.rep) != 0; }
inline long operator<(const ZZ& a, const ZZ& b)
{ return _ntl_gcompare(a.rep, b.rep) < 0; }
inline long operator>(const ZZ& a, const ZZ& b)
{ return _ntl_gcompare(a.rep, b.rep) > 0; }
inline long operator<=(const ZZ& a, const ZZ& b)
{ return _ntl_gcompare(a.rep, b.rep) <= 0; }
inline long operator>=(const ZZ& a, const ZZ& b)
{ return _ntl_gcompare(a.rep, b.rep) >= 0; }
/* single-precision versions of the above */
inline long compare(const ZZ& a, long b) { return _ntl_gscompare(a.rep, b); }
inline long compare(long a, const ZZ& b) { return -_ntl_gscompare(b.rep, a); }
inline long operator==(const ZZ& a, long b) { return _ntl_gscompare(a.rep, b) == 0; }
inline long operator!=(const ZZ& a, long b) { return _ntl_gscompare(a.rep, b) != 0; }
inline long operator<(const ZZ& a, long b) { return _ntl_gscompare(a.rep, b) < 0; }
inline long operator>(const ZZ& a, long b) { return _ntl_gscompare(a.rep, b) > 0; }
inline long operator<=(const ZZ& a, long b) { return _ntl_gscompare(a.rep, b) <= 0; }
inline long operator>=(const ZZ& a, long b) { return _ntl_gscompare(a.rep, b) >= 0; }
inline long operator==(long a, const ZZ& b) { return b == a; }
inline long operator!=(long a, const ZZ& b) { return b != a; }
inline long operator<(long a, const ZZ& b) { return b > a; }
inline long operator>(long a, const ZZ& b) { return b < a; }
inline long operator<=(long a, const ZZ& b) { return b >= a; }
inline long operator>=(long a, const ZZ& b) { return b <= a; }
/**************************************************
Addition
**************************************************/
inline void add(ZZ& x, const ZZ& a, const ZZ& b)
// x = a + b
{ _ntl_gadd(a.rep, b.rep, &x.rep); }
inline void sub(ZZ& x, const ZZ& a, const ZZ& b)
// x = a - b
{ _ntl_gsub(a.rep, b.rep, &x.rep); }
inline void SubPos(ZZ& x, const ZZ& a, const ZZ& b)
// x = a - b; assumes a >= b >= 0.
{ _ntl_gsubpos(a.rep, b.rep, &x.rep); }
inline void negate(ZZ& x, const ZZ& a)
// x = -a
{ _ntl_gcopy(a.rep, &x.rep); _ntl_gnegate(&x.rep); }
inline void abs(ZZ& x, const ZZ& a)
// x = |a|
{ _ntl_gcopy(a.rep, &x.rep); _ntl_gabs(&x.rep); }
/* single-precision versions of the above */
inline void add(ZZ& x, const ZZ& a, long b)
{ _ntl_gsadd(a.rep, b, &x.rep); }
inline void add(ZZ& x, long a, const ZZ& b) { add(x, b, a); }
void sub(ZZ& x, const ZZ& a, long b);
void sub(ZZ& x, long a, const ZZ& b);
/* operator/function notation */
inline ZZ operator+(const ZZ& a, const ZZ& b)
{ ZZ x; add(x, a, b); NTL_OPT_RETURN(ZZ, x); }
inline ZZ operator+(const ZZ& a, long b)
{ ZZ x; add(x, a, b); NTL_OPT_RETURN(ZZ, x); }
inline ZZ operator+(long a, const ZZ& b)
{ ZZ x; add(x, a, b); NTL_OPT_RETURN(ZZ, x); }
inline ZZ operator-(const ZZ& a, const ZZ& b)
{ ZZ x; sub(x, a, b); NTL_OPT_RETURN(ZZ, x); }
inline ZZ operator-(const ZZ& a, long b)
{ ZZ x; sub(x, a, b); NTL_OPT_RETURN(ZZ, x); }
inline ZZ operator-(long a, const ZZ& b)
{ ZZ x; sub(x, a, b); NTL_OPT_RETURN(ZZ, x); }
inline ZZ operator-(const ZZ& a)
{ ZZ x; negate(x, a); NTL_OPT_RETURN(ZZ, x); }
inline ZZ abs(const ZZ& a)
{ ZZ x; abs(x, a); NTL_OPT_RETURN(ZZ, x); }
/* op= notation */
inline ZZ& operator+=(ZZ& x, const ZZ& a)
{ add(x, x, a); return x; }
inline ZZ& operator+=(ZZ& x, long a)
{ add(x, x, a); return x; }
inline ZZ& operator-=(ZZ& x, const ZZ& a)
{ sub(x, x, a); return x; }
inline ZZ& operator-=(ZZ& x, long a)
{ sub(x, x, a); return x; }
/* inc/dec */
inline ZZ& operator++(ZZ& x) { add(x, x, 1); return x; }
inline void operator++(ZZ& x, int) { add(x, x, 1); }
inline ZZ& operator--(ZZ& x) { add(x, x, -1); return x; }
inline void operator--(ZZ& x, int) { add(x, x, -1); }
/*******************************************************
Multiplication.
********************************************************/
inline void mul(ZZ& x, const ZZ& a, const ZZ& b)
// x = a * b
{ _ntl_gmul(a.rep, b.rep, &x.rep); }
inline void sqr(ZZ& x, const ZZ& a)
// x = a*a
{ _ntl_gsq(a.rep, &x.rep); }
inline ZZ sqr(const ZZ& a)
{ ZZ x; sqr(x, a); NTL_OPT_RETURN(ZZ, x); }
/* single-precision versions */
inline void mul(ZZ& x, const ZZ& a, long b)
{ _ntl_gsmul(a.rep, b, &x.rep); }
inline void mul(ZZ& x, long a, const ZZ& b)
{ mul(x, b, a); }
/* operator notation */
inline ZZ operator*(const ZZ& a, const ZZ& b)
{ ZZ x; mul(x, a, b); NTL_OPT_RETURN(ZZ, x); }
inline ZZ operator*(const ZZ& a, long b)
{ ZZ x; mul(x, a, b); NTL_OPT_RETURN(ZZ, x); }
inline ZZ operator*(long a, const ZZ& b)
{ ZZ x; mul(x, a, b); NTL_OPT_RETURN(ZZ, x); }
/* op= notation */
inline ZZ& operator*=(ZZ& x, const ZZ& a)
{ mul(x, x, a); return x; }
inline ZZ& operator*=(ZZ& x, long a)
{ mul(x, x, a); return x; }
// x += a*b
inline void
MulAddTo(ZZ& x, const ZZ& a, long b)
{
_ntl_gsaddmul(a.rep, b, &x.rep);
}
inline void
MulAddTo(ZZ& x, const ZZ& a, const ZZ& b)
{
_ntl_gaddmul(a.rep, b.rep, &x.rep);
}
// x -= a*b
inline void
MulSubFrom(ZZ& x, const ZZ& a, long b)
{
_ntl_gssubmul(a.rep, b, &x.rep);
}
inline void
MulSubFrom(ZZ& x, const ZZ& a, const ZZ& b)
{
_ntl_gsubmul(a.rep, b.rep, &x.rep);
}
// Special routines for implementing CRT in ZZ_pX arithmetic
// These are verbose, but fairly boilerplate
class ZZ_CRTStructAdapter;
class ZZ_RemStructAdapter;
class ZZ_TmpVecAdapter {
public:
UniquePtr<_ntl_tmp_vec> rep;
inline void fetch(const ZZ_CRTStructAdapter&);
inline void fetch(ZZ_CRTStructAdapter&);
inline void fetch(const ZZ_RemStructAdapter&);
};
class ZZ_CRTStructAdapter {
public:
UniquePtr<_ntl_crt_struct> rep;
void init(long n, const ZZ& p, long (*primes)(long))
{
rep.reset(_ntl_crt_struct_build(n, p.rep, primes));
}
void insert(long i, const ZZ& m)
{
rep->insert(i, m.rep);
}
void eval(ZZ& t, const long *a, ZZ_TmpVecAdapter& tmp_vec) const
{
rep->eval(&t.rep, a, tmp_vec.rep.get());
}
bool special() const
{
return rep->special();
}
};
class ZZ_RemStructAdapter {
public:
UniquePtr<_ntl_rem_struct> rep;
void init(long n, const ZZ& p, long (*primes)(long))
{
rep.reset(_ntl_rem_struct_build(n, p.rep, primes));
}
void eval(long *x, const ZZ& a, ZZ_TmpVecAdapter& tmp_vec) const
{
rep->eval(x, a.rep, tmp_vec.rep.get());
}
};
inline void ZZ_TmpVecAdapter::fetch(const ZZ_CRTStructAdapter& crt_struct)
{
rep.reset(crt_struct.rep->fetch());
}
inline void ZZ_TmpVecAdapter::fetch(ZZ_CRTStructAdapter& crt_struct)
{
rep.reset(crt_struct.rep->extract()); // EXTRACT!!
}
inline void ZZ_TmpVecAdapter::fetch(const ZZ_RemStructAdapter& rem_struct)
{
rep.reset(rem_struct.rep->fetch());
}
// montgomery
class ZZ_ReduceStructAdapter {
public:
UniquePtr<_ntl_reduce_struct> rep;
void init(const ZZ& p, const ZZ& excess)
{
rep.reset(_ntl_reduce_struct_build(p.rep, excess.rep));
}
void eval(ZZ& x, ZZ& a) const
{
rep->eval(&x.rep, &a.rep);
}
void adjust(ZZ& x) const
{
rep->adjust(&x.rep);
}
};
/*******************************************************
Division
*******************************************************/
inline void DivRem(ZZ& q, ZZ& r, const ZZ& a, const ZZ& b)
// q = [a/b], r = a - b*q
// |r| < |b|, and if r != 0, sign(r) = sign(b)
{ _ntl_gdiv(a.rep, b.rep, &q.rep, &r.rep); }
inline void div(ZZ& q, const ZZ& a, const ZZ& b)
// q = a/b
{ _ntl_gdiv(a.rep, b.rep, &q.rep, 0); }
inline void rem(ZZ& r, const ZZ& a, const ZZ& b)
// r = a%b
{ _ntl_gmod(a.rep, b.rep, &r.rep); }
inline void QuickRem(ZZ& r, const ZZ& b)
// r = r%b
// assumes b > 0 and r >=0
// division is performed in place and may cause r to be re-allocated.
{ _ntl_gquickmod(&r.rep, b.rep); }
long divide(ZZ& q, const ZZ& a, const ZZ& b);
// if b | a, sets q = a/b and returns 1; otherwise returns 0.
long divide(const ZZ& a, const ZZ& b);
// if b | a, returns 1; otherwise returns 0.
/* non-standard single-precision versions */
inline long DivRem(ZZ& q, const ZZ& a, long b)
{ return _ntl_gsdiv(a.rep, b, &q.rep); }
inline long rem(const ZZ& a, long b)
{ return _ntl_gsmod(a.rep, b); }
/* single precision versions */
inline void div(ZZ& q, const ZZ& a, long b)
{ (void) _ntl_gsdiv(a.rep, b, &q.rep); }
long divide(ZZ& q, const ZZ& a, long b);
// if b | a, sets q = a/b and returns 1; otherwise returns 0.
long divide(const ZZ& a, long b);
// if b | a, returns 1; otherwise returns 0.
inline ZZ operator/(const ZZ& a, const ZZ& b)
{ ZZ x; div(x, a, b); NTL_OPT_RETURN(ZZ, x); }
inline ZZ operator/(const ZZ& a, long b)
{ ZZ x; div(x, a, b); NTL_OPT_RETURN(ZZ, x); }
inline ZZ operator%(const ZZ& a, const ZZ& b)
{ ZZ x; rem(x, a, b); NTL_OPT_RETURN(ZZ, x); }
inline long operator%(const ZZ& a, long b)
{ return rem(a, b); }
inline ZZ& operator/=(ZZ& x, const ZZ& b)
{ div(x, x, b); return x; }
inline ZZ& operator/=(ZZ& x, long b)
{ div(x, x, b); return x; }
inline ZZ& operator%=(ZZ& x, const ZZ& b)
{ rem(x, x, b); return x; }
// preconditioned single-precision variant
// not documented for now...
struct sp_ZZ_reduce_struct_policy {
static
void deleter(_ntl_general_rem_one_struct *pinfo)
{
_ntl_general_rem_one_struct_delete(pinfo);
}
};
struct sp_ZZ_reduce_struct {
long p;
UniquePtr<_ntl_general_rem_one_struct,sp_ZZ_reduce_struct_policy> pinfo;
sp_ZZ_reduce_struct() : p(0) { }
void build(long _p)
{
pinfo.reset(_ntl_general_rem_one_struct_build(_p));
p = _p;
}
long rem(const ZZ& a) const
{
return _ntl_general_rem_one_struct_apply(a.rep, p, pinfo.get());
}
};
// special-purpose routines for accumulating CRT-like summations
// Not documented for now.
// Allocates sz+2 limbs and zeros them all out.
// x is not normalized.
inline
void QuickAccumBegin(ZZ& x, long sz)
{
_ntl_quick_accum_begin(&x.rep, sz);
}
// x += y*b.
// Assumes y >= 0 and that 0 <= b < NTL_SP_BOUND.
// Must only be called less than NTL_NSP_BOUND times.
// x remains unnormalized.
inline
void QuickAccumMulAdd(ZZ& x, const ZZ& y, long b)
{
_ntl_quick_accum_muladd(x.rep, y.rep, b);
}
// renormalizes x.
inline
void QuickAccumEnd(ZZ& x)
{
_ntl_quick_accum_end(x.rep);
}
/**********************************************************
GCD's
***********************************************************/
inline void GCD(ZZ& d, const ZZ& a, const ZZ& b)
// d = gcd(a, b)
{ _ntl_ggcd(a.rep, b.rep, &d.rep); }
inline ZZ GCD(const ZZ& a, const ZZ& b)
{ ZZ x; GCD(x, a, b); NTL_OPT_RETURN(ZZ, x); }
inline void GCD_alt(ZZ& d, const ZZ& a, const ZZ& b)
// d = gcd(a, b)
{ _ntl_ggcd_alt(a.rep, b.rep, &d.rep); }
inline void XGCD(ZZ& d, ZZ& s, ZZ& t, const ZZ& a, const ZZ& b)
// d = gcd(a, b) = a*s + b*t;
{ _ntl_gexteucl(a.rep, &s.rep, b.rep, &t.rep, &d.rep); }
// single-precision versions
long GCD(long a, long b);
void XGCD(long& d, long& s, long& t, long a, long b);
/************************************************************
Bit Operations
*************************************************************/
inline void LeftShift(ZZ& x, const ZZ& a, long k)
// x = (a << k), k < 0 => RightShift
{ _ntl_glshift(a.rep, k, &x.rep); }
inline ZZ LeftShift(const ZZ& a, long k)
{ ZZ x; LeftShift(x, a, k); NTL_OPT_RETURN(ZZ, x); }
inline void RightShift(ZZ& x, const ZZ& a, long k)
// x = (a >> k), k < 0 => LeftShift
{ _ntl_grshift(a.rep, k, &x.rep); }
inline ZZ RightShift(const ZZ& a, long k)
{ ZZ x; RightShift(x, a, k); NTL_OPT_RETURN(ZZ, x); }
#ifndef NTL_TRANSITION
inline ZZ operator>>(const ZZ& a, long n)
{ ZZ x; RightShift(x, a, n); NTL_OPT_RETURN(ZZ, x); }
inline ZZ operator<<(const ZZ& a, long n)
{ ZZ x; LeftShift(x, a, n); NTL_OPT_RETURN(ZZ, x); }
inline ZZ& operator<<=(ZZ& x, long n)
{ LeftShift(x, x, n); return x; }
inline ZZ& operator>>=(ZZ& x, long n)
{ RightShift(x, x, n); return x; }
#endif
inline long MakeOdd(ZZ& x)
// removes factors of 2 from x, returns the number of 2's removed
// returns 0 if x == 0
{ return _ntl_gmakeodd(&x.rep); }
inline long NumTwos(const ZZ& x)
// returns max e such that 2^e divides x if x != 0, and returns 0 if x == 0.
{ return _ntl_gnumtwos(x.rep); }
inline long IsOdd(const ZZ& a)
// returns 1 if a is odd, otherwise 0
{ return _ntl_godd(a.rep); }
inline long NumBits(const ZZ& a)
// returns the number of bits in |a|; NumBits(0) = 0
{ return _ntl_g2log(a.rep); }
inline long bit(const ZZ& a, long k)
// returns bit k of a, 0 being the low-order bit
{ return _ntl_gbit(a.rep, k); }
#ifndef NTL_GMP_LIP
// only defined for the "classic" long integer package, for backward
// compatability.
inline long digit(const ZZ& a, long k)
{ return _ntl_gdigit(a.rep, k); }
#endif
// returns k-th digit of |a|, 0 being the low-order digit.
inline void trunc(ZZ& x, const ZZ& a, long k)
// puts k low order bits of |a| into x
{ _ntl_glowbits(a.rep, k, &x.rep); }
inline ZZ trunc_ZZ(const ZZ& a, long k)
{ ZZ x; trunc(x, a, k); NTL_OPT_RETURN(ZZ, x); }
inline long trunc_long(const ZZ& a, long k)
// returns k low order bits of |a|
{ return _ntl_gslowbits(a.rep, k); }
inline long SetBit(ZZ& x, long p)
// returns original value of p-th bit of |a|, and replaces
// p-th bit of a by 1 if it was zero;
// error if p < 0
{ return _ntl_gsetbit(&x.rep, p); }
inline long SwitchBit(ZZ& x, long p)
// returns original value of p-th bit of |a|, and switches
// the value of p-th bit of a;
// p starts counting at 0;
// error if p < 0
{ return _ntl_gswitchbit(&x.rep, p); }
inline long weight(long a)
// returns Hamming weight of |a|
{ return _ntl_gweights(a); }
inline long weight(const ZZ& a)
// returns Hamming weight of |a|
{ return _ntl_gweight(a.rep); }
inline void bit_and(ZZ& x, const ZZ& a, const ZZ& b)
// x = |a| AND |b|
{ _ntl_gand(a.rep, b.rep, &x.rep); }
void bit_and(ZZ& x, const ZZ& a, long b);
inline void bit_and(ZZ& x, long a, const ZZ& b)
{ bit_and(x, b, a); }
inline void bit_or(ZZ& x, const ZZ& a, const ZZ& b)
// x = |a| OR |b|
{ _ntl_gor(a.rep, b.rep, &x.rep); }
void bit_or(ZZ& x, const ZZ& a, long b);
inline void bit_or(ZZ& x, long a, const ZZ& b)
{ bit_or(x, b, a); }
inline void bit_xor(ZZ& x, const ZZ& a, const ZZ& b)
// x = |a| XOR |b|
{ _ntl_gxor(a.rep, b.rep, &x.rep); }
void bit_xor(ZZ& x, const ZZ& a, long b);
inline void bit_xor(ZZ& x, long a, const ZZ& b)
{ bit_xor(x, b, a); }
inline ZZ operator&(const ZZ& a, const ZZ& b)
{ ZZ x; bit_and(x, a, b); NTL_OPT_RETURN(ZZ, x); }
inline ZZ operator&(const ZZ& a, long b)
{ ZZ x; bit_and(x, a, b); NTL_OPT_RETURN(ZZ, x); }
inline ZZ operator&(long a, const ZZ& b)
{ ZZ x; bit_and(x, a, b); NTL_OPT_RETURN(ZZ, x); }
inline ZZ operator|(const ZZ& a, const ZZ& b)
{ ZZ x; bit_or(x, a, b); NTL_OPT_RETURN(ZZ, x); }
inline ZZ operator|(const ZZ& a, long b)
{ ZZ x; bit_or(x, a, b); NTL_OPT_RETURN(ZZ, x); }
inline ZZ operator|(long a, const ZZ& b)
{ ZZ x; bit_or(x, a, b); NTL_OPT_RETURN(ZZ, x); }
inline ZZ operator^(const ZZ& a, const ZZ& b)
{ ZZ x; bit_xor(x, a, b); NTL_OPT_RETURN(ZZ, x); }
inline ZZ operator^(const ZZ& a, long b)
{ ZZ x; bit_xor(x, a, b); NTL_OPT_RETURN(ZZ, x); }
inline ZZ operator^(long a, const ZZ& b)
{ ZZ x; bit_xor(x, a, b); NTL_OPT_RETURN(ZZ, x); }
inline ZZ& operator&=(ZZ& x, const ZZ& b)
{ bit_and(x, x, b); return x; }
inline ZZ& operator&=(ZZ& x, long b)
{ bit_and(x, x, b); return x; }
inline ZZ& operator|=(ZZ& x, const ZZ& b)
{ bit_or(x, x, b); return x; }
inline ZZ& operator|=(ZZ& x, long b)
{ bit_or(x, x, b); return x; }
inline ZZ& operator^=(ZZ& x, const ZZ& b)
{ bit_xor(x, x, b); return x; }
inline ZZ& operator^=(ZZ& x, long b)
{ bit_xor(x, x, b); return x; }
long NumBits(long a);
long bit(long a, long k);
long NextPowerOfTwo(long m);
// returns least nonnegative k such that 2^k >= m
inline
long NumBytes(const ZZ& a)
{ return (NumBits(a)+7)/8; }
inline
long NumBytes(long a)
{ return (NumBits(a)+7)/8; }
/***********************************************************
Some specialized routines
************************************************************/
inline long ZZ_BlockConstructAlloc(ZZ& x, long d, long n)
{ return _ntl_gblock_construct_alloc(&x.rep, d, n); }
inline void ZZ_BlockConstructSet(ZZ& x, ZZ& y, long i)
{ _ntl_gblock_construct_set(x.rep, &y.rep, i); }
inline long ZZ_BlockDestroy(ZZ& x)
{ return _ntl_gblock_destroy(x.rep); }
inline long ZZ_storage(long d)
{ return _ntl_gblock_storage(d); }
inline long ZZ_RoundCorrection(const ZZ& a, long k, long residual)
{ return _ntl_ground_correction(a.rep, k, residual); }
/***********************************************************
Psuedo-random Numbers
************************************************************/
// ================ NEW PRG STUFF =================
// Low-level key-derivation
void DeriveKey(unsigned char *key, long klen,
const unsigned char *data, long dlen);
// Low-level chacha stuff
#define NTL_PRG_KEYLEN (32)
class RandomStream {
private:
_ntl_uint32 state[16];
unsigned char buf[64];
long pos;
void do_get(unsigned char *res, long n);
public:
explicit
RandomStream(const unsigned char *key);
// No default constructor
// default copy and assignment
void get(unsigned char *res, long n)
{
// optimize short reads
if (n >= 0 && n <= 64-pos) {
long i;
for (i = 0; i < n; i++) {
res[i] = buf[pos+i];
}
pos += n;
}
else {
do_get(res, n);
}
}
};
RandomStream& GetCurrentRandomStream();
// get reference to the current random by stream --
// if SetSeed has not been called, it is called with
// a default value (which should be unique to each
// process/thread
void SetSeed(const ZZ& s);
void SetSeed(const unsigned char *data, long dlen);
void SetSeed(const RandomStream& s);
// initialize random number generator
// in the first two version, a PRG key is derived from
// the data using DeriveKey.
// RAII for saving/restoring current state of PRG
class RandomStreamPush {
private:
RandomStream saved;
RandomStreamPush(const RandomStreamPush&); // disable
void operator=(const RandomStreamPush&); // disable
public:
RandomStreamPush() : saved(GetCurrentRandomStream()) { }
~RandomStreamPush() { SetSeed(saved); }
};
void RandomBnd(ZZ& x, const ZZ& n);
// x = "random number" in the range 0..n-1, or 0 if n <= 0
inline ZZ RandomBnd(const ZZ& n)
{ ZZ x; RandomBnd(x, n); NTL_OPT_RETURN(ZZ, x); }
void RandomLen(ZZ& x, long NumBits);
// x = "random number" with precisely NumBits bits.
inline ZZ RandomLen_ZZ(long NumBits)
{ ZZ x; RandomLen(x, NumBits); NTL_OPT_RETURN(ZZ, x); }
void RandomBits(ZZ& x, long NumBits);
// x = "random number", 0 <= x < 2^NumBits
inline ZZ RandomBits_ZZ(long NumBits)
{ ZZ x; RandomBits(x, NumBits); NTL_OPT_RETURN(ZZ, x); }
// single-precision version of the above
long RandomBnd(long n);
inline void RandomBnd(long& x, long n) { x = RandomBnd(n); }
long RandomLen_long(long l);
inline void RandomLen(long& x, long l) { x = RandomLen_long(l); }
long RandomBits_long(long l);
inline void RandomBits(long& x, long l) { x = RandomBits_long(l); }
// specialty routines
unsigned long RandomWord();
unsigned long RandomBits_ulong(long l);
// helper class to make generating small random numbers faster
// FIXME: add documentation?
struct RandomBndGenerator {
long p;
long nb;
unsigned long mask;
RandomStream *str;
RandomBndGenerator() : p(0) { }
explicit
RandomBndGenerator(long _p) : p(0) { build(_p); }
void build(long _p)
{
if (_p <= 1) LogicError("RandomBndGenerator::init: bad args");
if (!p) {
str = &GetCurrentRandomStream();
}
p = _p;
long l = NumBits(p-1);
nb = (l+7)/8;
mask = (1UL << l)-1UL;
}
long next()
{
unsigned char buf[NTL_BITS_PER_LONG/8];
long tmp;
do {
str->get(buf, nb);
unsigned long word = 0;
for (long i = nb-1; i >= 0; i--) word = (word << 8) | buf[i];
tmp = long(word & mask);
} while (tmp >= p);
return tmp;
}
};
inline void VectorRandomBnd(long k, long* x, long n)
{
if (k <= 0) return;
if (n <= 1) {
for (long i = 0; i < k; i++) x[i] = 0;
}
else {
RandomBndGenerator gen(n);
for (long i = 0; i < k; i++) x[i] = gen.next();
}
}
/**********************************************************
Incremental Chinese Remaindering
***********************************************************/
long CRT(ZZ& a, ZZ& p, const ZZ& A, const ZZ& P);
long CRT(ZZ& a, ZZ& p, long A, long P);
// 0 <= A < P, (p, P) = 1;
// computes b such that b = a mod p, b = A mod p,
// and -p*P/2 < b <= p*P/2;
// sets a = b, p = p*P, and returns 1 if a's value
// has changed, otherwise 0
inline long CRTInRange(const ZZ& gg, const ZZ& aa)
{ return _ntl_gcrtinrange(gg.rep, aa.rep); }
// an auxilliary routine used by newer CRT routines to maintain
// backward compatability.
// test if a > 0 and -a/2 < g <= a/2
// this is "hand crafted" so as not too waste too much time
// in the CRT routines.
/**********************************************************
Rational Reconstruction
***********************************************************/
inline
long ReconstructRational(ZZ& a, ZZ& b, const ZZ& u, const ZZ& m,
const ZZ& a_bound, const ZZ& b_bound)
{
return _ntl_gxxratrecon(u.rep, m.rep, a_bound.rep, b_bound.rep, &a.rep, &b.rep);
}
/************************************************************
Primality Testing
*************************************************************/
void GenPrime(ZZ& n, long l, long err = 80);
inline ZZ GenPrime_ZZ(long l, long err = 80)
{ ZZ x; GenPrime(x, l, err); NTL_OPT_RETURN(ZZ, x); }
long GenPrime_long(long l, long err = 80);
// This generates a random prime n of length l so that the
// probability of erroneously returning a composite is bounded by 2^(-err).
void GenGermainPrime(ZZ& n, long l, long err = 80);
inline ZZ GenGermainPrime_ZZ(long l, long err = 80)
{ ZZ x; GenGermainPrime(x, l, err); NTL_OPT_RETURN(ZZ, x); }
long GenGermainPrime_long(long l, long err = 80);
// This generates a random prime n of length l so that the
long ProbPrime(const ZZ& n, long NumTrials = 10);
// tests if n is prime; performs a little trial division,
// followed by a single-precision MillerWitness test, followed by
// up to NumTrials general MillerWitness tests.
long MillerWitness(const ZZ& n, const ZZ& w);
// Tests if w is a witness to primality a la Miller.
// Assumption: n is odd and positive, 0 <= w < n.
void RandomPrime(ZZ& n, long l, long NumTrials=10);
// n = random l-bit prime
inline ZZ RandomPrime_ZZ(long l, long NumTrials=10)
{ ZZ x; RandomPrime(x, l, NumTrials); NTL_OPT_RETURN(ZZ, x); }
void NextPrime(ZZ& n, const ZZ& m, long NumTrials=10);
// n = smallest prime >= m.
inline ZZ NextPrime(const ZZ& m, long NumTrials=10)
{ ZZ x; NextPrime(x, m, NumTrials); NTL_OPT_RETURN(ZZ, x); }
// single-precision versions
long ProbPrime(long n, long NumTrials = 10);
long RandomPrime_long(long l, long NumTrials=10);
long NextPrime(long l, long NumTrials=10);
/************************************************************
Exponentiation
*************************************************************/
inline void power(ZZ& x, const ZZ& a, long e)
{ _ntl_gexp(a.rep, e, &x.rep); }
inline ZZ power(const ZZ& a, long e)
{ ZZ x; power(x, a, e); NTL_OPT_RETURN(ZZ, x); }
inline void power(ZZ& x, long a, long e)
{ _ntl_gexps(a, e, &x.rep); }
inline ZZ power_ZZ(long a, long e)
{ ZZ x; power(x, a, e); NTL_OPT_RETURN(ZZ, x); }
long power_long(long a, long e);
void power2(ZZ& x, long e);
inline ZZ power2_ZZ(long e)
{ ZZ x; power2(x, e); NTL_OPT_RETURN(ZZ, x); }
/*************************************************************
Square Roots
**************************************************************/
inline void SqrRoot(ZZ& x, const ZZ& a)
// x = [a^{1/2}], a >= 0
{
_ntl_gsqrt(a.rep, &x.rep);
}
inline ZZ SqrRoot(const ZZ& a)
{ ZZ x; SqrRoot(x, a); NTL_OPT_RETURN(ZZ, x); }
inline long SqrRoot(long a) { return _ntl_gsqrts(a); }
// single-precision version
/***************************************************************
Modular Arithmetic
***************************************************************/
// The following routines perform arithmetic mod n, n positive.
// All args (other than exponents) are assumed to be in the range 0..n-1.
inline void AddMod(ZZ& x, const ZZ& a, const ZZ& b, const ZZ& n)
// x = (a+b)%n
{ _ntl_gaddmod(a.rep, b.rep, n.rep, &x.rep); }
inline ZZ AddMod(const ZZ& a, const ZZ& b, const ZZ& n)
{ ZZ x; AddMod(x, a, b, n); NTL_OPT_RETURN(ZZ, x); }
inline void SubMod(ZZ& x, const ZZ& a, const ZZ& b, const ZZ& n)
// x = (a-b)%n
{ _ntl_gsubmod(a.rep, b.rep, n.rep, &x.rep); }
inline ZZ SubMod(const ZZ& a, const ZZ& b, const ZZ& n)
{ ZZ x; SubMod(x, a, b, n); NTL_OPT_RETURN(ZZ, x); }
inline void NegateMod(ZZ& x, const ZZ& a, const ZZ& n)
// x = -a % n
{ _ntl_gsubmod(0, a.rep, n.rep, &x.rep); }
inline ZZ NegateMod(const ZZ& a, const ZZ& n)
{ ZZ x; NegateMod(x, a, n); NTL_OPT_RETURN(ZZ, x); }
void AddMod(ZZ& x, const ZZ& a, long b, const ZZ& n);
inline ZZ AddMod(const ZZ& a, long b, const ZZ& n)
{ ZZ x; AddMod(x, a, b, n); NTL_OPT_RETURN(ZZ, x); }
inline void AddMod(ZZ& x, long a, const ZZ& b, const ZZ& n)
{ AddMod(x, b, a, n); }
inline ZZ AddMod(long a, const ZZ& b, const ZZ& n)
{ ZZ x; AddMod(x, a, b, n); NTL_OPT_RETURN(ZZ, x); }
void SubMod(ZZ& x, const ZZ& a, long b, const ZZ& n);
inline ZZ SubMod(const ZZ& a, long b, const ZZ& n)
{ ZZ x; SubMod(x, a, b, n); NTL_OPT_RETURN(ZZ, x); }
void SubMod(ZZ& x, long a, const ZZ& b, const ZZ& n);
inline ZZ SubMod(long a, const ZZ& b, const ZZ& n)
{ ZZ x; SubMod(x, a, b, n); NTL_OPT_RETURN(ZZ, x); }
inline void MulMod(ZZ& x, const ZZ& a, const ZZ& b, const ZZ& n)
// x = (a*b)%n
{ _ntl_gmulmod(a.rep, b.rep, n.rep, &x.rep); }
inline ZZ MulMod(const ZZ& a, const ZZ& b, const ZZ& n)
{ ZZ x; MulMod(x, a, b, n); NTL_OPT_RETURN(ZZ, x); }
inline void MulMod(ZZ& x, const ZZ& a, long b, const ZZ& n)
// x = (a*b)%n
{ _ntl_gsmulmod(a.rep, b, n.rep, &x.rep); }
inline ZZ MulMod(const ZZ& a, long b, const ZZ& n)
{ ZZ x; MulMod(x, a, b, n); NTL_OPT_RETURN(ZZ, x); }
inline void MulMod(ZZ& x, long a, const ZZ& b, const ZZ& n)
{ MulMod(x, b, a, n); }
inline ZZ MulMod(long a, const ZZ& b, const ZZ& n)
{ ZZ x; MulMod(x, a, b, n); NTL_OPT_RETURN(ZZ, x); }
inline void SqrMod(ZZ& x, const ZZ& a, const ZZ& n)
// x = a^2 % n
{ _ntl_gsqmod(a.rep, n.rep, &x.rep); }
inline ZZ SqrMod(const ZZ& a, const ZZ& n)
{ ZZ x; SqrMod(x, a, n); NTL_OPT_RETURN(ZZ, x); }
void InvMod(ZZ& x, const ZZ& a, const ZZ& n);
// defined in ZZ.c in terms of InvModStatus
inline ZZ InvMod(const ZZ& a, const ZZ& n)
{ ZZ x; InvMod(x, a, n); NTL_OPT_RETURN(ZZ, x); }
inline long InvModStatus(ZZ& x, const ZZ& a, const ZZ& n)
// if gcd(a,n) = 1, then ReturnValue = 0, x = a^{-1} mod n
// otherwise, ReturnValue = 1, x = gcd(a, n)
{ return _ntl_ginv(a.rep, n.rep, &x.rep); }
void PowerMod(ZZ& x, const ZZ& a, const ZZ& e, const ZZ& n);
// defined in ZZ.c in terms of LowLevelPowerMod
inline void LowLevelPowerMod(ZZ& x, const ZZ& a, const ZZ& e, const ZZ& n)
{ _ntl_gpowermod(a.rep, e.rep, n.rep, &x.rep); }
inline ZZ PowerMod(const ZZ& a, const ZZ& e, const ZZ& n)
{ ZZ x; PowerMod(x, a, e, n); NTL_OPT_RETURN(ZZ, x); }
inline void PowerMod(ZZ& x, const ZZ& a, long e, const ZZ& n)
{ PowerMod(x, a, ZZ_expo(e), n); }
inline ZZ PowerMod(const ZZ& a, long e, const ZZ& n)
{ ZZ x; PowerMod(x, a, e, n); NTL_OPT_RETURN(ZZ, x); }
/*************************************************************
Jacobi symbol and modular squre roots
**************************************************************/
long Jacobi(const ZZ& a, const ZZ& n);
// compute Jacobi symbol of a and n;
// assumes 0 <= a < n, n odd
void SqrRootMod(ZZ& x, const ZZ& a, const ZZ& n);
// computes square root of a mod n;
// assumes n is an odd prime, and that a is a square mod n
inline ZZ SqrRootMod(const ZZ& a, const ZZ& n)
{ ZZ x; SqrRootMod(x, a, n); NTL_OPT_RETURN(ZZ, x); }
/*************************************************************
Small Prime Generation
*************************************************************/
// primes are generated in sequence, starting at 2,
// and up until (2*NTL_PRIME_BND+1)^2, which is less than NTL_SP_BOUND.
#if (NTL_SP_NBITS > 30)
#define NTL_PRIME_BND ((1L << 14) - 1)
#else
#define NTL_PRIME_BND ((1L << (NTL_SP_NBITS/2-1)) - 1)
#endif
class PrimeSeq {
const char *movesieve;
Vec<char> movesieve_mem;
long pindex;
long pshift;
long exhausted;
public:
PrimeSeq();
long next();
// returns next prime in the sequence.
// returns 0 if list of small primes is exhausted.
void reset(long b);
// resets generator so that the next prime in the sequence
// is the smallest prime >= b.
private:
PrimeSeq(const PrimeSeq&); // disabled
void operator=(const PrimeSeq&); // disabled
// auxilliary routines
void start();
void shift(long);
};
/**************************************************************
Input/Output
***************************************************************/
NTL_SNS istream& operator>>(NTL_SNS istream& s, ZZ& x);
NTL_SNS ostream& operator<<(NTL_SNS ostream& s, const ZZ& a);
// Some additional SP arithmetic routines, not defined in sp_arith.h
long InvMod(long a, long n);
// computes a^{-1} mod n. Error is raised if undefined.
long InvModStatus(long& x, long a, long n);
// if gcd(a,n) = 1, then ReturnValue = 0, x = a^{-1} mod n
// otherwise, ReturnValue = 1, x = gcd(a, n)
long PowerMod(long a, long e, long n);
// computes a^e mod n, e >= 0
// Error handling
#ifdef NTL_EXCEPTIONS
class InvModErrorObject : public ArithmeticErrorObject {
private:
SmartPtr<ZZ> a_ptr;
SmartPtr<ZZ> n_ptr;
public:
InvModErrorObject(const char *s, const ZZ& a, const ZZ& n)
: ArithmeticErrorObject(s) , a_ptr(MakeSmart<ZZ>(a)),
n_ptr(MakeSmart<ZZ>(n)) { }
const ZZ& get_a() const { return *a_ptr; }
const ZZ& get_n() const { return *n_ptr; }
};
#else
// We need this alt definition to keep pre-C++11
// compilers happy (NTL_EXCEPTIONS should only be used
// with C++11 compilers).
class InvModErrorObject : public ArithmeticErrorObject {
public:
InvModErrorObject(const char *s, const ZZ& a, const ZZ& n)
: ArithmeticErrorObject(s) { }
const ZZ& get_a() const { return ZZ::zero(); }
const ZZ& get_n() const { return ZZ::zero(); }
};
#endif
void InvModError(const char *s, const ZZ& a, const ZZ& n);
NTL_CLOSE_NNS
#endif
| [
"[email protected]"
] | |
8874cc7d6e7d75976c19cd4c71f133cfeeafe299 | f94c62d00d733284189006d65d8e57bdd89ac961 | /sample_projects/GBM_OV_immune_stroma_double_immune/custom_modules/GBM_OV_immune_stroma_double_immune.cpp | 1009dd12d4cb05f6d0f39dbd9e51c1b44be2fdca | [] | no_license | adriannejnner/InvitroGBMCellProliferation | 62fd39840834d617c74842a13fb2241c7c72c4a8 | ff23ff71dbfb2ef5bd8ca89e0d3795b7a8722dff | refs/heads/main | 2023-07-16T21:05:35.937708 | 2021-08-11T02:08:33 | 2021-08-11T02:08:33 | 393,213,607 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 72,277 | cpp | /*
###############################################################################
# If you use PhysiCell in your project, please cite PhysiCell and the version #
# number, such as below: #
# #
# We implemented and solved the model using PhysiCell (Version x.y.z) [1]. #
# #
# [1] A Ghaffarizadeh, R Heiland, SH Friedman, SM Mumenthaler, and P Macklin, #
# PhysiCell: an Open Source Physics-Based Cell Simulator for Multicellu- #
# lar Systems, PLoS Comput. Biol. 14(2): e1005991, 2018 #
# DOI: 10.1371/journal.pcbi.1005991 #
# #
# See VERSION.txt or call get_PhysiCell_version() to get the current version #
# x.y.z. Call display_citations() to get detailed information on all cite-#
# able software used in your PhysiCell application. #
# #
# Because PhysiCell extensively uses BioFVM, we suggest you also cite BioFVM #
# as below: #
# #
# We implemented and solved the model using PhysiCell (Version x.y.z) [1], #
# with BioFVM [2] to solve the transport equations. #
# #
# [1] A Ghaffarizadeh, R Heiland, SH Friedman, SM Mumenthaler, and P Macklin, #
# PhysiCell: an Open Source Physics-Based Cell Simulator for Multicellu- #
# lar Systems, PLoS Comput. Biol. 14(2): e1005991, 2018 #
# DOI: 10.1371/journal.pcbi.1005991 #
# #
# [2] A Ghaffarizadeh, SH Friedman, and P Macklin, BioFVM: an efficient para- #
# llelized diffusive transport solver for 3-D biological simulations, #
# Bioinformatics 32(8): 1256-8, 2016. DOI: 10.1093/bioinformatics/btv730 #
# #
###############################################################################
# #
# BSD 3-Clause License (see https://opensource.org/licenses/BSD-3-Clause) #
# #
# Copyright (c) 2015-2018, Paul Macklin and the PhysiCell Project #
# All rights reserved. #
# #
# Redistribution and use in source and binary forms, with or without #
# modification, are permitted provided that the following conditions are met: #
# #
# 1. Redistributions of source code must retain the above copyright notice, #
# this list of conditions and the following disclaimer. #
# #
# 2. Redistributions in binary form must reproduce the above copyright #
# notice, this list of conditions and the following disclaimer in the #
# documentation and/or other materials provided with the distribution. #
# #
# 3. Neither the name of the copyright holder nor the names of its #
# contributors may be used to endorse or promote products derived from this #
# software without specific prior written permission. #
# #
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" #
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE #
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE #
# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE #
# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR #
# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF #
# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS #
# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN #
# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) #
# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE #
# POSSIBILITY OF SUCH DAMAGE. #
# #
###############################################################################
*/
#include "./GBM_OV_immune_stroma_double_immune.h"
#include "../modules/PhysiCell_settings.h"
#include <cmath>
#include <iostream>
#include <random>
Cell_Definition TH_cell;
Cell_Definition CTL_cell;
Cell_Definition cancer_cell;
Cell_Definition stroma_cell;
void create_TH_cells( void )
{
TH_cell = cell_defaults;
TH_cell.name = "TH cell";
TH_cell.type = 1;
// proliferation
TH_cell.functions.cycle_model = Ki67_basic;
TH_cell.phenotype.cycle.sync_to_cycle_model( Ki67_basic);
int cycle_start_index = Ki67_basic.find_phase_index( PhysiCell_constants::Ki67_negative );
int cycle_end_index = Ki67_basic.find_phase_index( PhysiCell_constants::Ki67_positive );
TH_cell.phenotype.cycle.data.transition_rate(cycle_start_index,cycle_end_index) = parameters.doubles("TH_prolif_rate");
TH_cell.phenotype.cycle.data.transition_rate(cycle_end_index,cycle_start_index) = parameters.doubles("TH_quiescent_transistion_rate");
// cell actions
TH_cell.phenotype.secretion.uptake_rates[1] = 0.0;
TH_cell.phenotype.secretion.secretion_rates[1] = 0.0;
TH_cell.phenotype.motility.migration_speed = parameters.ints("TH_migration_speed");//4
// cell morphology
TH_cell.phenotype.geometry.radius = 3.6;
TH_cell.phenotype.volume.total = 185.66;
TH_cell.phenotype.volume.fluid_fraction = 0.75;
TH_cell.phenotype.volume.fluid = TH_cell.phenotype.volume.fluid_fraction*TH_cell.phenotype.volume.total;
TH_cell.phenotype.volume.solid = TH_cell.phenotype.volume.total-TH_cell.phenotype.volume.fluid;
TH_cell.phenotype.volume.nuclear = 95.21;
TH_cell.phenotype.volume.nuclear_solid = 23.8;
TH_cell.phenotype.volume.nuclear_fluid = TH_cell.phenotype.volume.nuclear - TH_cell.phenotype.volume.nuclear_solid;
TH_cell.phenotype.volume.cytoplasmic = TH_cell.phenotype.volume.total - TH_cell.phenotype.volume.nuclear;
TH_cell.phenotype.volume.cytoplasmic_fluid = TH_cell.phenotype.volume.fluid_fraction*TH_cell.phenotype.volume.cytoplasmic;
TH_cell.phenotype.volume.cytoplasmic_solid = TH_cell.phenotype.volume.cytoplasmic-TH_cell.phenotype.volume.cytoplasmic_fluid;
TH_cell.phenotype.volume.cytoplasmic_to_nuclear_ratio = 1.05;
TH_cell.phenotype.volume.target_solid_cytoplasmic = TH_cell.phenotype.volume.cytoplasmic_solid;
TH_cell.phenotype.volume.target_solid_nuclear = TH_cell.phenotype.volume.nuclear_solid;
TH_cell.phenotype.volume.target_fluid_fraction = TH_cell.phenotype.volume.fluid_fraction;
TH_cell.phenotype.volume.target_cytoplasmic_to_nuclear_ratio = TH_cell.phenotype.volume.cytoplasmic_to_nuclear_ratio;
// update function
TH_cell.functions.update_phenotype = TH_functions;
return;
}
void create_CTL_cells( void )
{
CTL_cell = cell_defaults;
CTL_cell.name = "CTL cell";
CTL_cell.type = 3;
// proliferation
CTL_cell.functions.cycle_model = Ki67_basic;
CTL_cell.phenotype.cycle.sync_to_cycle_model( Ki67_basic);
int cycle_start_index = Ki67_basic.find_phase_index( PhysiCell_constants::Ki67_negative );
int cycle_end_index = Ki67_basic.find_phase_index( PhysiCell_constants::Ki67_positive);
CTL_cell.phenotype.cycle.data.transition_rate(cycle_start_index,cycle_end_index) = parameters.doubles("CTL_prolif_rate");//7.2206*1e-5;
CTL_cell.phenotype.cycle.data.transition_rate(cycle_end_index,cycle_start_index) = parameters.doubles("CTL_quiescent_transistion_rate");//0.00143;
// cell actions
CTL_cell.phenotype.secretion.uptake_rates[1] = 0.0;
CTL_cell.phenotype.secretion.secretion_rates[1] = 0.0;
CTL_cell.phenotype.motility.migration_speed = parameters.ints("CTL_migration_speed");
//cell morphology
CTL_cell.phenotype.geometry.radius = 3.6;
CTL_cell.phenotype.volume.total = 185.66;
CTL_cell.phenotype.volume.fluid_fraction = 0.75;
CTL_cell.phenotype.volume.fluid = CTL_cell.phenotype.volume.fluid_fraction*CTL_cell.phenotype.volume.total;
CTL_cell.phenotype.volume.solid = CTL_cell.phenotype.volume.total-CTL_cell.phenotype.volume.fluid;
CTL_cell.phenotype.volume.nuclear = 96.23;
CTL_cell.phenotype.volume.nuclear_solid = 24.06;
CTL_cell.phenotype.volume.nuclear_fluid = CTL_cell.phenotype.volume.nuclear - CTL_cell.phenotype.volume.nuclear_solid;
CTL_cell.phenotype.volume.cytoplasmic = CTL_cell.phenotype.volume.total - CTL_cell.phenotype.volume.nuclear;
CTL_cell.phenotype.volume.cytoplasmic_fluid = CTL_cell.phenotype.volume.fluid_fraction*CTL_cell.phenotype.volume.cytoplasmic;
CTL_cell.phenotype.volume.cytoplasmic_solid = CTL_cell.phenotype.volume.cytoplasmic-CTL_cell.phenotype.volume.cytoplasmic_fluid;
CTL_cell.phenotype.volume.cytoplasmic_to_nuclear_ratio = 1.03;
CTL_cell.phenotype.volume.target_solid_cytoplasmic = CTL_cell.phenotype.volume.cytoplasmic_solid;
CTL_cell.phenotype.volume.target_solid_nuclear = CTL_cell.phenotype.volume.nuclear_solid;
CTL_cell.phenotype.volume.target_fluid_fraction = CTL_cell.phenotype.volume.fluid_fraction;
CTL_cell.phenotype.volume.target_cytoplasmic_to_nuclear_ratio = CTL_cell.phenotype.volume.cytoplasmic_to_nuclear_ratio;
// cell update phenotype
CTL_cell.functions.update_phenotype = CTL_functions;
return;
}void create_stroma_cells( void )
{
stroma_cell = cell_defaults;
stroma_cell.name = "stroma cell";
stroma_cell.type = 4;
// turn off proliferation
int cycle_start_index = live.find_phase_index( PhysiCell_constants::live );
int cycle_end_index = live.find_phase_index( PhysiCell_constants::live);
stroma_cell.phenotype.cycle.data.transition_rate(cycle_start_index,cycle_end_index) = 0;
// cell actions
static int virus_index = microenvironment.find_density_index( "virus");
stroma_cell.phenotype.secretion.uptake_rates[virus_index] = parameters.doubles("stroma_virus_uptake_rate")*0.5;
stroma_cell.phenotype.secretion.secretion_rates[1] = 0.0;
stroma_cell.phenotype.motility.migration_speed = 0;
stroma_cell.phenotype.motility.is_motile = false;
stroma_cell.phenotype.molecular.fraction_released_at_death[virus_index] = 0;//1;
// cell morphology
stroma_cell.phenotype.geometry.radius = parameters.doubles("stroma_radius");//7.5;
stroma_cell.phenotype.volume.total = 1767;
stroma_cell.phenotype.volume.fluid_fraction = 0.75;
stroma_cell.phenotype.volume.fluid = stroma_cell.phenotype.volume.fluid_fraction*stroma_cell.phenotype.volume.total;
stroma_cell.phenotype.volume.solid = stroma_cell.phenotype.volume.total-stroma_cell.phenotype.volume.fluid;
stroma_cell.phenotype.volume.nuclear = 500;
stroma_cell.phenotype.volume.nuclear_solid = 125;
stroma_cell.phenotype.volume.nuclear_fluid = stroma_cell.phenotype.volume.nuclear - stroma_cell.phenotype.volume.nuclear_solid;
stroma_cell.phenotype.volume.cytoplasmic = stroma_cell.phenotype.volume.total - stroma_cell.phenotype.volume.nuclear;
stroma_cell.phenotype.volume.cytoplasmic_fluid = stroma_cell.phenotype.volume.fluid_fraction*stroma_cell.phenotype.volume.cytoplasmic;
stroma_cell.phenotype.volume.cytoplasmic_solid = stroma_cell.phenotype.volume.cytoplasmic-stroma_cell.phenotype.volume.cytoplasmic_fluid;
stroma_cell.phenotype.volume.cytoplasmic_to_nuclear_ratio = 2.53;
stroma_cell.phenotype.volume.target_solid_cytoplasmic = stroma_cell.phenotype.volume.cytoplasmic_solid;
stroma_cell.phenotype.volume.target_solid_nuclear = stroma_cell.phenotype.volume.nuclear_solid;
stroma_cell.phenotype.volume.target_fluid_fraction = stroma_cell.phenotype.volume.fluid_fraction;
stroma_cell.phenotype.volume.target_cytoplasmic_to_nuclear_ratio = stroma_cell.phenotype.volume.cytoplasmic_to_nuclear_ratio;
// update phenotype
stroma_cell.functions.update_phenotype = stroma_function;
return;
}
void create_cancer_cells( void )
{
cancer_cell = cell_defaults;
// cell actions
static int virus_index = microenvironment.find_density_index( "virus");
cancer_cell.phenotype.secretion.uptake_rates[virus_index] = 0.0;
cancer_cell.phenotype.secretion.secretion_rates[virus_index] = 0.0;
cancer_cell.phenotype.motility.migration_speed = 0.0;
// cell morphology
cancer_cell.phenotype.geometry.radius = 10.75;
cancer_cell.phenotype.volume.total = 4/3*3.1416*(cancer_cell.phenotype.geometry.radius)*(cancer_cell.phenotype.geometry.radius)*(cancer_cell.phenotype.geometry.radius);//5203.7;
cancer_cell.phenotype.volume.fluid_fraction = 0.75;
cancer_cell.phenotype.volume.fluid = cancer_cell.phenotype.volume.fluid_fraction*cancer_cell.phenotype.volume.total;
cancer_cell.phenotype.volume.solid = cancer_cell.phenotype.volume.total-cancer_cell.phenotype.volume.fluid;
cancer_cell.phenotype.volume.nuclear = 740;
cancer_cell.phenotype.volume.nuclear_solid = 185;
cancer_cell.phenotype.volume.nuclear_fluid = cancer_cell.phenotype.volume.nuclear - cancer_cell.phenotype.volume.nuclear_solid;
cancer_cell.phenotype.volume.cytoplasmic = cancer_cell.phenotype.volume.total - cancer_cell.phenotype.volume.nuclear;
cancer_cell.phenotype.volume.cytoplasmic_fluid = cancer_cell.phenotype.volume.fluid_fraction*cancer_cell.phenotype.volume.cytoplasmic;
cancer_cell.phenotype.volume.cytoplasmic_solid = cancer_cell.phenotype.volume.cytoplasmic-cancer_cell.phenotype.volume.cytoplasmic_fluid;
cancer_cell.phenotype.volume.cytoplasmic_to_nuclear_ratio = cancer_cell.phenotype.volume.cytoplasmic/cancer_cell.phenotype.volume.nuclear;//6.0321;
cancer_cell.phenotype.volume.target_solid_cytoplasmic = cancer_cell.phenotype.volume.cytoplasmic_solid;
cancer_cell.phenotype.volume.target_solid_nuclear = cancer_cell.phenotype.volume.nuclear_solid;
cancer_cell.phenotype.volume.target_fluid_fraction = cancer_cell.phenotype.volume.fluid_fraction;
cancer_cell.phenotype.volume.target_cytoplasmic_to_nuclear_ratio = cancer_cell.phenotype.volume.cytoplasmic_to_nuclear_ratio;
cancer_cell.phenotype.volume.calcified_fraction = 0;
cancer_cell.phenotype.volume.calcification_rate = 0;
cancer_cell.phenotype.mechanics.cell_cell_repulsion_strength = 0.35*cancer_cell.phenotype.mechanics.cell_cell_repulsion_strength;
//update phenoypt
cancer_cell.functions.update_phenotype = cancer_cell_proliferation_infection_movement;
cancer_cell.name = "cancer cell";
cancer_cell.type = 2;
return;
}
void create_cell_types( void )
{
// housekeeping
SeedRandom( parameters.ints( "random_seed" ) );
initialize_default_cell_definition();
cell_defaults.phenotype.secretion.sync_to_microenvironment( µenvironment );
cell_defaults.phenotype.molecular.sync_to_microenvironment( µenvironment );
//cell_defaults.phenotype.sync_to_functions( cell_defaults.functions );
// Make sure we're ready for 2D
cell_defaults.functions.set_orientation = up_orientation;
cell_defaults.phenotype.geometry.polarity = 1.0;
cell_defaults.phenotype.motility.restrict_to_2D = true;
//setting cycle model to live
cell_defaults.phenotype.cycle.sync_to_cycle_model( live );
int cycle_start_index = live.find_phase_index( PhysiCell_constants::live );
int cycle_end_index = live.find_phase_index( PhysiCell_constants::live );
cell_defaults.phenotype.cycle.data.transition_rate( cycle_start_index , cycle_end_index ) = 0;//0.00073549;//0.0000064812*(1-9740/512720);
// turn off death
int apoptosis_index = cell_defaults.phenotype.death.find_death_model_index( PhysiCell_constants::apoptosis_death_model );
cell_defaults.phenotype.death.rates[apoptosis_index] = 0.0;
// reduce cell velocity
cell_defaults.phenotype.motility.migration_speed = 0.0;//0.05;
// add variables to track virus infection start time, length of time and amount of virus
cell_defaults.custom_data.add_variable( "intracellular_virus_amount", "dimensionless", 0.0 ); // amount of intracellular virus
cell_defaults.custom_data.add_variable( "persistence_time", "dimensionless", 0.0 ); // how long cells will persist in move or stop phenotype
cell_defaults.custom_data.add_variable( "cell_motility_type", "dimensionless", 0.0 );
cell_defaults.custom_data.add_variable( "rep_rate", "dimensionless", 0.0 );
cell_defaults.custom_data.add_variable( "attachment lifetime" , "min" , 0 ); // how long it can stay attached
cell_defaults.custom_data.add_variable( "special_virus_uptakerate" ,"min",0); // creating a distribution for the uptake rates
cell_defaults.custom_data.add_variable( "special_virus_replication_rate","min",0.0);
Parameter<double> paramD;
paramD = parameters.doubles[ "elastic_coefficient" ];
cell_defaults.custom_data.add_variable( "elastic coefficient" , paramD.units, paramD.value );
// turn off secretion from these cells (oxygen and virus)
cell_defaults.phenotype.secretion.secretion_rates[0] = 0;
cell_defaults.phenotype.secretion.uptake_rates[0] = 0;
cell_defaults.phenotype.secretion.saturation_densities[0] = 10;
static int virus_index = microenvironment.find_density_index( "virus");
cell_defaults.phenotype.secretion.secretion_rates[virus_index] = 0;
cell_defaults.phenotype.secretion.uptake_rates[virus_index] = 0.0;
cell_defaults.phenotype.secretion.saturation_densities[virus_index] = parameters.doubles("virus_saturation_density");//;//10;
cell_defaults.phenotype.molecular.fraction_released_at_death[virus_index] = 1;//1;
cell_defaults.phenotype.molecular.fraction_released_at_death[0] = 1;//1;
cell_defaults.phenotype.molecular.fraction_released_at_death[2] = 1;//1;
cell_defaults.phenotype.molecular.fraction_released_at_death[3] = 1;//1;
static int wall_index = microenvironment.find_density_index( "wall");
cell_defaults.phenotype.secretion.secretion_rates[wall_index] = 0;
cell_defaults.phenotype.secretion.uptake_rates[wall_index] = 0;
cell_defaults.phenotype.secretion.saturation_densities[wall_index] = 10;
static int chemokine_index = microenvironment.find_density_index( "chemokine");
cell_defaults.phenotype.secretion.secretion_rates[chemokine_index] = 0;
cell_defaults.phenotype.secretion.uptake_rates[chemokine_index] = 0;
cell_defaults.phenotype.secretion.saturation_densities[chemokine_index] = parameters.ints("chemokine_saturation_density");//5;
// update cell and phenotype based on virus dynamics only
cell_defaults.functions.update_phenotype = cancer_cell_proliferation_infection_movement;
cell_defaults.phenotype.motility.is_motile = true;
cell_defaults.name = "holder cell";
cell_defaults.type = 0;
//create cell types
create_cancer_cells();
create_CTL_cells();
create_TH_cells();
create_stroma_cells();
return;
}
void setup_microenvironment( void )
{
// set domain parameters
// make sure not override and go back to 2D
if( default_microenvironment_options.simulate_2D == false )
{
std::cout << "Warning: overriding XML config option and setting to 2D!" << std::endl;
default_microenvironment_options.simulate_2D = true;
}
initialize_microenvironment();
static int virus_index = microenvironment.find_density_index( "virus");
static int oxygen_index = microenvironment.find_density_index( "oxygen");
static int wall_index = microenvironment.find_density_index( "wall");
static int chemokine_index = microenvironment.find_density_index( "chemokine");
for( int n = 0 ; n < microenvironment.mesh.voxels.size(); n++ )
{
std::vector<double> ECMdense = microenvironment.mesh.voxels[n].center;
//assign random ECM density to microenvironment voxel
if( ECMdense[0]*ECMdense[0]+ECMdense[1]*ECMdense[1]>(parameters.doubles("tumour_radius")+10)*(parameters.doubles("tumour_radius")+10))//1280*1280)//420*420)//
{
microenvironment(n)[oxygen_index] = 0;
microenvironment(n)[virus_index] = 0;
microenvironment(n)[wall_index] = 1;
microenvironment(n)[chemokine_index] = 0;
}
else if(ECMdense[0]*ECMdense[0]+ECMdense[1]*ECMdense[1]>(parameters.doubles("tumour_radius")-10)*(parameters.doubles("tumour_radius")-10))//420*420)//1260*1260)//1260*1260)400*400)//
{
microenvironment(n)[oxygen_index] = 0;
microenvironment(n)[virus_index] = parameters.doubles("initial_virus_density");
microenvironment(n)[wall_index] = 3.5;
microenvironment(n)[chemokine_index] = 0;
}
else if( ECMdense[0]*ECMdense[0]+ECMdense[1]*ECMdense[1]>250*250 )
{
microenvironment(n)[oxygen_index] = 0;
microenvironment(n)[virus_index] = 0;
microenvironment(n)[wall_index] = 5;
microenvironment(n)[chemokine_index] = 0;
}
else
{
microenvironment(n)[oxygen_index] = 0;
microenvironment(n)[virus_index] = 0;
microenvironment(n)[wall_index] = 10;
microenvironment(n)[chemokine_index] = 0;
}
}
return;
}
void setup_tissue_circle_immune( void )
{
double Radius = parameters.doubles("tumour_radius");
Cell* pCell = NULL;
double x = 0.0;
double y = 0.0;
// setting up distributions for movement and persistance of cells
std::vector<double> go_times_cumul(8);
go_times_cumul[0] = 0.01;
go_times_cumul[1] = 0.962;
go_times_cumul[2] = 0.9735;
go_times_cumul[3] = 0.9835;
go_times_cumul[4] = 0.9935;
go_times_cumul[5] = 0.9955;
go_times_cumul[6] = 0.9975;
go_times_cumul[7] = 1;
std::vector<double> persistence_times_vec(8);
persistence_times_vec[0] = 0;
persistence_times_vec[1] = 30;
persistence_times_vec[2] = 60;
persistence_times_vec[3] = 90;
persistence_times_vec[4] = 120;
persistence_times_vec[5] = 150;
persistence_times_vec[6] = 180;
persistence_times_vec[7] = 240;
std::vector<double> speed_cumul(12);
speed_cumul[0] = 0.0014;
speed_cumul[1] = 0.0317;
speed_cumul[2] = 0.2441;
speed_cumul[3] = 0.5137;
speed_cumul[4] = 0.7598;
speed_cumul[5] = 0.8822;
speed_cumul[6] = 0.9453;
speed_cumul[7] = 0.9787;
speed_cumul[8] = 0.9882;
speed_cumul[9] = 0.9937;
speed_cumul[10] = 0.9963;
speed_cumul[11] = 1;
std::vector<double> speed_vec(12);
speed_vec[0] = 0.0833;
speed_vec[1] = 0.1667;
speed_vec[2] = 0.25;
speed_vec[3] = 0.333;
speed_vec[4] = 0.4167;
speed_vec[5] = 0.5;
speed_vec[6] = 0.5833;
speed_vec[7] = 0.667;
speed_vec[8] = 0.75;
speed_vec[9] = 0.833;
speed_vec[10] = 0.9167;
speed_vec[11] = 1;
immune_cell_placement();
double GBM_NO = parameters.ints("initial_GBM_cells");
double stroma_NO = parameters.ints("initial_stroma_cells");
std::default_random_engine generator;
/*
std::default_random_engine generator;
double nu_mean1 = parameters.doubles("GBM_virus_uptake_rate")*10;
double nu_variance1 = 0.0001;
double shape1 = nu_mean1*nu_mean1/nu_variance1;
double scale1 = nu_variance1/nu_mean1;
std::gamma_distribution<double> distribution1(shape1,scale1);
double nu_mean2 = parameters.doubles("stroma_virus_uptake_rate")*10;
double nu_variance2 = 0.0001;
double shape2 = nu_mean2*nu_mean2/nu_variance2;
double scale2 = nu_variance2/nu_mean2;
std::gamma_distribution<double> distribution2(shape2,scale2);
*/
double nu_mean = 10;
double nu_variance = 0.0001;
double shape = nu_mean*nu_mean/nu_variance;
double scale = nu_variance/nu_mean;
std::gamma_distribution<double> distribution(shape,scale);
//GBM cells
for( int i=0; i<GBM_NO; i++ )
{
double R = sqrt(UniformRandom())*Radius;
double alp = UniformRandom()*2*3.141;
x = R*cos(alp);
y = R*sin(alp);
pCell = create_cell( cancer_cell );
pCell->assign_position( x , y , 0.0 );
static int virus_signal_index = microenvironment.find_density_index( "virus");
int persistence_time_index = pCell->custom_data.find_variable_index( "persistence_time" );
int cell_motility_type_index = pCell->custom_data.find_variable_index( "cell_motility_type" );
int virus_uptake_rate_index = pCell->custom_data.find_variable_index( "special_virus_uptakerate");
int virus_replication_rate_index = pCell->custom_data.find_variable_index( "special_virus_replication_rate");
pCell->custom_data.variables[virus_uptake_rate_index].value = parameters.doubles("GBM_virus_uptake_rate")*distribution(generator);//distribution1(generator);
pCell->custom_data.variables[virus_replication_rate_index].value = parameters.doubles("virus_replication_rate");//distribution(generator);
double p = UniformRandom();
if(p<=0.5)// GO
{
pCell->custom_data.variables[cell_motility_type_index].value = 1;
double speed_var = UniformRandom();
for( int k=0; k<12; )
{
if( speed_var> speed_cumul[k] )
{k++;}
else
{
pCell->phenotype.motility.migration_speed = speed_vec[k];
k = 12;
}
}
}
else
{pCell->custom_data.variables[cell_motility_type_index].value = 2;} // STOP
double go_stop_var = UniformRandom();
for( int j=0; j<8; )
{
if( go_stop_var> go_times_cumul[j] )
{j++;}
else
{
pCell->custom_data.variables[persistence_time_index].value = persistence_times_vec[j];
j = 8;
}
}
}
for( int l=0; l<stroma_NO; l++ )
{
double R = sqrt(UniformRandom())*Radius;
double alp = UniformRandom()*2*3.141;
x = R*cos(alp);
y = R*sin(alp);
pCell = create_cell( stroma_cell );
pCell->assign_position( x , y , 0.0 );
static int virus_signal_index = microenvironment.find_density_index("virus");
//pCell->phenotype.secretion.uptake_rates[virus_signal_index] = NormalRandom( 0.2, 0.3);
//if( pCell->phenotype.secretion.uptake_rates[virus_signal_index] < 0)
//{pCell->phenotype.secretion.uptake_rates[virus_signal_index] = 0;}
pCell->phenotype.secretion.uptake_rates[virus_signal_index] = parameters.doubles("stroma_virus_uptake_rate")*distribution(generator);//distribution2(generator);
int virus_uptake_rate_index = pCell->custom_data.find_variable_index( "special_virus_uptakerate");
pCell->custom_data.variables[virus_uptake_rate_index].value = pCell->phenotype.secretion.uptake_rates[virus_signal_index];
}
return;
}
void cancer_cell_proliferation_infection_movement( Cell* pCell, Phenotype& phenotype, double dt )
{
double R = 21.5/2;
double SA = 4*3.1416*R*R;
double s = parameters.doubles("maximum_cell_density");
double pressure = 6*(1-1/(2*R)*s)*(1-1/(2*R)*s);
double pressure_scale = 0.027288820670331;
double max_pressure = pressure/pressure_scale;
//tumour cell proliferation
if(pCell->type ==2)
{
int cycle_start_index = live.find_phase_index( PhysiCell_constants::live );
int cycle_end_index = live.find_phase_index( PhysiCell_constants::live );
pCell->phenotype.cycle.data.transition_rate( cycle_start_index , cycle_end_index ) = parameters.doubles("GBM_cell_proliferation_rate");
if( pCell->state.simple_pressure*pCell->state.simple_pressure>max_pressure) // if cell under too much pressure -> no proliferation
{pCell->phenotype.cycle.data.transition_rate( cycle_start_index , cycle_end_index ) = 0;}
}
cell_movement( pCell, phenotype, dt);
infection_dynamics( pCell, phenotype, dt );
return;
}
void cell_movement( Cell* pCell, Phenotype& phenotype, double dt )
{
//cell movement
static int wall_index = microenvironment.find_density_index( "wall" );
double wall_amount = pCell->nearest_density_vector()[wall_index];
static int persistence_time_index = pCell->custom_data.find_variable_index( "persistence_time" );
static int cell_motility_type_index = pCell->custom_data.find_variable_index( "cell_motility_type" );
double persistence_time = pCell->custom_data.variables[persistence_time_index].value;
double cell_motility_type = pCell->custom_data.variables[cell_motility_type_index].value; // 1 = go, 2 = stop
std::vector<double> go_times_cumul(8);
go_times_cumul[0] = 0.01;
go_times_cumul[1] = 0.962;
go_times_cumul[2] = 0.9735;
go_times_cumul[3] = 0.9835;
go_times_cumul[4] = 0.9935;
go_times_cumul[5] = 0.9955;
go_times_cumul[6] = 0.9975;
go_times_cumul[7] = 1;
std::vector<double> persistence_times_vec(8);
persistence_times_vec[0] = 0;
persistence_times_vec[1] = 30;
persistence_times_vec[2] = 60;
persistence_times_vec[3] = 90;
persistence_times_vec[4] = 120;
persistence_times_vec[5] = 150;
persistence_times_vec[6] = 180;
persistence_times_vec[7] = 240;
std::vector<double> speed_cumul(12);
speed_cumul[0] = 0.0014;
speed_cumul[1] = 0.0317;
speed_cumul[2] = 0.2441;
speed_cumul[3] = 0.5137;
speed_cumul[4] = 0.7598;
speed_cumul[5] = 0.8822;
speed_cumul[6] = 0.9453;
speed_cumul[7] = 0.9787;
speed_cumul[8] = 0.9882;
speed_cumul[9] = 0.9937;
speed_cumul[10] = 0.9963;
speed_cumul[11] = 1;
std::vector<double> speed_vec(12);
speed_vec[0] = 0.0833;
speed_vec[1] = 0.1667;
speed_vec[2] = 0.25;
speed_vec[3] = 0.333;
speed_vec[4] = 0.4167;
speed_vec[5] = 0.5;
speed_vec[6] = 0.5833;
speed_vec[7] = 0.667;
speed_vec[8] = 0.75;
speed_vec[9] = 0.833;
speed_vec[10] = 0.9167;
speed_vec[11] = 1;
if( wall_amount<2 & pCell->type == 2 )
{
pCell->phenotype.motility.migration_speed = 0;
}
else if(pCell->type != 2)
{
pCell->phenotype.motility.migration_speed = 4;
}
else
{
if( persistence_time <= PhysiCell_globals.current_time ) // if the cell's persistence time is up
{
// assign new type (stop = 2, or go = 1)
double new_type_rand = UniformRandom();
if(new_type_rand<=0.5)// GO
{
pCell->custom_data.variables[cell_motility_type_index].value = 1; // assign go type
double speed_var = UniformRandom();
for( int k=0; k<12; )
{
if( speed_var> speed_cumul[k] )
{k++;}
else
{
pCell->phenotype.motility.migration_speed = speed_vec[k]; // assign migration speed
k = 12;
}
}
}
else
{pCell->custom_data.variables[cell_motility_type_index].value = 2;
pCell->phenotype.motility.migration_speed = 0;} // assign STOP type
// assign persistence time - needs to be a real time!
double go_stop_var = UniformRandom();
for( int j=0; j<8; )
{
if( go_stop_var> go_times_cumul[j] )
{j++;}
else
{
pCell->custom_data.variables[persistence_time_index].value = persistence_times_vec[j]+PhysiCell_globals.current_time; // assign persist time
j = 8;
}
}
}
}
return;
}
void infection_dynamics( Cell* pCell, Phenotype& phenotype, double dt )
{
//cell infection
static int virus_signal_index = microenvironment.find_density_index( "virus");
static int apoptosis_model_index = pCell->phenotype.death.find_death_model_index( "apoptosis" );
static double intracellular_virus_index = pCell->custom_data.find_variable_index( "intracellular_virus_amount" );
double n = pCell->phenotype.molecular.internalized_total_substrates[virus_signal_index];//custom_data.variables[intracellular_virus_index].value;
double p = pCell->nearest_density_vector()[virus_signal_index];
// double u = parameters.doubles("GBM_virus_uptake_rate");//0.0020276;//uptake rate
int index_specal_uptake = pCell->custom_data.find_variable_index( "special_virus_uptakerate" );
double u = pCell->custom_data.variables[index_specal_uptake].value;
double Vvoxel = microenvironment.mesh.voxels[1].volume;//volume of voxel
double nstar = parameters.doubles("infection_threshold");//10;//infection threshol
//double nu = parameters.doubles("virus_replication_rate");//10*0.4886;//repliation rate
double alp = parameters.doubles("virus_burst_number");//1000;//virus burst number
int virus_replication_rate_index = pCell->custom_data.find_variable_index( "special_virus_replication_rate");
double nu = pCell->custom_data.variables[virus_replication_rate_index].value;
pCell->custom_data.variables[intracellular_virus_index].value = pCell->phenotype.molecular.internalized_total_substrates[virus_signal_index];
double pmax = parameters.doubles("pmax");//0.0125;
if( pCell->phenotype.death.dead == false )// cell not dead
{
if(p<pmax)
{pCell->phenotype.secretion.uptake_rates[virus_signal_index] = u*p/(n/Vvoxel+nstar/Vvoxel);}
else
{pCell->phenotype.secretion.uptake_rates[virus_signal_index] = u*pmax*pmax/(n/Vvoxel+nstar/Vvoxel)/p;}
if( n > 1 && n <= alp) // update amount inside due to replication
{
pCell->phenotype.molecular.internalized_total_substrates[virus_signal_index] = n+dt*(nu*n);
pCell->custom_data.variables[intracellular_virus_index].value = pCell->phenotype.molecular.internalized_total_substrates[virus_signal_index];
}
else if( n > alp-1)
{
pCell->custom_data.variables[intracellular_virus_index].value = pCell->phenotype.molecular.internalized_total_substrates[virus_signal_index];
pCell->phenotype.molecular.fraction_released_at_death[virus_signal_index] = 1;
pCell->phenotype.secretion.uptake_rates[virus_signal_index] = 0;
pCell->start_death( apoptosis_model_index );
}
else if( pCell->phenotype.molecular.internalized_total_substrates[virus_signal_index]<0 )
{std::cout<<"NEGATIVE INTRACELLULAR VIRUS"<<std::endl;}
}
if( pCell->phenotype.death.dead == true && pCell->phenotype.molecular.fraction_released_at_death[virus_signal_index]>0)
{
virus_induced_lysis(pCell, phenotype, dt );
}
return;
}
void virus_induced_lysis( Cell* pCell, Phenotype& phenotype, double dt )
{
static int virus_signal_index = microenvironment.find_density_index( "virus");
double pstar = pCell->phenotype.secretion.saturation_densities[virus_signal_index];
double delta_V = parameters.doubles("viral_decay_from_burst_cell");//0.1466;
double Vvoxel = microenvironment.mesh.voxels[1].volume;//volume of voxel
double p = pCell->nearest_density_vector()[virus_signal_index];
double n = pCell->phenotype.molecular.internalized_total_substrates[virus_signal_index];
if( pCell->phenotype.molecular.internalized_total_substrates[virus_signal_index]> 1 )
{
double amount_to_add = (n-n*exp(-delta_V*dt))/Vvoxel;
if( amount_to_add > pstar-p )
{
pCell->nearest_density_vector()[virus_signal_index] += (pstar-p)*dt;
pCell->phenotype.molecular.internalized_total_substrates[virus_signal_index] -= (pstar-p)*Vvoxel*dt;
}
else
{
pCell->nearest_density_vector()[virus_signal_index] += (amount_to_add)*dt;
pCell->phenotype.molecular.internalized_total_substrates[virus_signal_index] = n*exp(-delta_V*dt);
}
//std::cout<<amount_to_add<<" old p: "<<p<<" new p: "<<pCell->nearest_density_vector()[virus_signal_index]<<" old n: "<<n<<" new n: "<<pCell->phenotype.molecular.internalized_total_substrates[virus_signal_index]<<std::endl;
}
return;
}
void stroma_function( Cell* pCell, Phenotype& phenotype, double dt )
{
static int virus_signal_index = microenvironment.find_density_index("virus");
static double intracellular_virus_index = pCell->custom_data.find_variable_index( "intracellular_virus_amount" );
pCell->custom_data.variables[intracellular_virus_index].value = pCell->phenotype.molecular.internalized_total_substrates[virus_signal_index];
if(pCell->phenotype.molecular.internalized_total_substrates[virus_signal_index]>1e5)
{
pCell->phenotype.molecular.internalized_total_substrates[virus_signal_index] = 0;
pCell->custom_data.variables[intracellular_virus_index].value = 0;
//stroma_cell.phenotype.secretion.uptake_rates[virus_signal_index] = 0;
}
else
{
pCell->custom_data.variables[intracellular_virus_index].value = pCell->phenotype.molecular.internalized_total_substrates[virus_signal_index];
}
//std::cout<<pCell->phenotype.secretion.uptake_rates[virus_signal_index]<<" "<<pCell->custom_data.variables[intracellular_virus_index].value<<std::endl;
return;
}
void TH_functions( Cell* pCell, Phenotype& phenotype, double dt )
{
static int wall_index = microenvironment.find_density_index( "wall" );
double wall_amount = pCell->nearest_density_vector()[wall_index];
std::vector<double> ae_ini(3);
if( wall_amount<2 )// Make TH cells that have left the diameter of the tumour make cell turn around
{
pCell->phenotype.motility.migration_speed = 4;
ae_ini = -1*pCell->position;
pCell->phenotype.motility.migration_bias = 1;
normalize( &( ae_ini ) );
pCell->phenotype.motility.migration_bias_direction = ae_ini;
}
else
{
pCell->phenotype.motility.migration_speed = 4;
pCell->phenotype.motility.migration_bias = 0;
}
// TH secretion of cytokines
std::vector<Cell*> nearby = pCell->cells_in_my_container();
static int virus_signal_index = microenvironment.find_density_index( "virus");
static int chemokine_index = microenvironment.find_density_index( "chemokine");
int cycle_start_index = Ki67_basic.find_phase_index( PhysiCell_constants::Ki67_negative );
int cycle_end_index = Ki67_basic.find_phase_index( PhysiCell_constants::Ki67_positive );
Cell* pC = NULL;
bool stop = false;
int i=0;
double nstar = parameters.doubles("infection_threshold");
while( !stop && i < nearby.size() )
{
pC = nearby[i];
if( pC->phenotype.molecular.internalized_total_substrates[virus_signal_index] > nstar &&
pC->phenotype.death.dead == false &&
pC != pCell && pC->type != 4)
{ stop = true; }
i++;
if( stop == false )
{ pC = NULL; }
}
if( pC )
{
//std::cout << "infected cell found by TH" << std::endl;
pCell->phenotype.secretion.secretion_rates[chemokine_index] = parameters.doubles("chemokine_secretion_rate");//0.0417;//0.1;
pCell->phenotype.cycle.data.transition_rate(cycle_start_index,cycle_end_index) = parameters.doubles("TH_prolif_rate")*parameters.doubles("TH_prolif_increase_due_to_stimulus");
pCell->phenotype.motility.migration_speed = 0.1;
}
else
{
pCell->phenotype.secretion.secretion_rates[chemokine_index] = 0;//0.1;
pCell->phenotype.cycle.data.transition_rate(cycle_start_index,cycle_end_index) = parameters.doubles("TH_prolif_rate");
//pCell->phenotype.motility.is_motile = true;
}
// TH increased proliferation ?
return;
}
void CTL_functions( Cell* pCell, Phenotype& phenotype, double dt )
{
int cycle_start_index = Ki67_basic.find_phase_index( PhysiCell_constants::Ki67_negative );
int cycle_end_index = Ki67_basic.find_phase_index( PhysiCell_constants::Ki67_positive );
if( pCell->type != 3 )
{std::cout<<"wrong cell type"<<std::endl;}
if( phenotype.death.dead == true )
{
// the cell death functions don't automatically turn off custom functions,
// since those are part of mechanics.
// Let's just fully disable now.
pCell->functions.update_phenotype = NULL;
return;
}
static int attach_lifetime_i = pCell->custom_data.find_variable_index( "attachment lifetime" );
// is CTL docked to infected cell - increase prolif - time for docking
if( pCell->state.neighbors.size() > 0 )
{
extra_elastic_attachment_mechanics( pCell, phenotype, dt );
// attempt to kill my attached cell
bool dettach_me = false;
if( immune_cell_attempt_apoptosis( pCell, pCell->state.neighbors[0], dt ) )
{
immune_cell_trigger_apoptosis( pCell, pCell->state.neighbors[0] );
dettach_me = true;
}
// if I dettach, resume motile behavior
if( dettach_me )
{
dettach_cells( pCell, pCell->state.neighbors[0] );
phenotype.motility.is_motile = true;
CTL_movement( pCell, phenotype, dt);
pCell->phenotype.cycle.data.transition_rate(cycle_start_index,cycle_end_index) = parameters.doubles("CTL_prolif_rate")*parameters.doubles("CTL_prolif_increase_due_to_stimulus");
//std::cout<<"detached and should be proliferating"<<std::endl;
}
return;
}
//has CTL encounted a new infected cell - start docking clock
// if this returns non-NULL, we're now attached to a cell
if( immune_cell_check_neighbors_for_attachment( pCell , dt) )
{
// set motility off
phenotype.motility.is_motile = false;
return;
}
// is there a gradient for the CTL to follow - start random walk in the direction of the chemattractant
phenotype.motility.is_motile = true;
CTL_movement( pCell, phenotype, dt);
return;
}
void extra_elastic_attachment_mechanics( Cell* pCell, Phenotype& phenotype, double dt )
{
for( int i=0; i < pCell->state.neighbors.size() ; i++ )
{
add_elastic_velocity( pCell, pCell->state.neighbors[i], pCell->custom_data["elastic coefficient"] );
}
return;
}
void add_elastic_velocity( Cell* pActingOn, Cell* pAttachedTo , double elastic_constant )
{
std::vector<double> displacement = pAttachedTo->position - pActingOn->position;
axpy( &(pActingOn->velocity) , elastic_constant , displacement );
return;
}
Cell* immune_cell_check_neighbors_for_attachment( Cell* pAttacker , double dt )
{
std::vector<Cell*> nearby = pAttacker->cells_in_my_container();
int i = 0;
while( i < nearby.size() )
{
// don't try to kill yourself
if( nearby[i] != pAttacker )
{
if( immune_cell_attempt_attachment( pAttacker, nearby[i] , dt ) )
{ return nearby[i]; }
}
i++;
}
return NULL;
}
bool immune_cell_attempt_attachment( Cell* pAttacker, Cell* pTarget , double dt )
{
static double max_attachment_distance = parameters.doubles("max_attachment_distance"); // 18.0;
static int virus_signal_index = microenvironment.find_density_index( "virus");
double internal_virus = pTarget->phenotype.molecular.internalized_total_substrates[virus_signal_index];//custom_data.variables[intracellular_virus_index].value;
static int attach_lifetime_i = pAttacker->custom_data.find_variable_index( "attachment lifetime" );
double kill_time = parameters.doubles("time_to_kill_cell"); // how long the cell needs to attach for the infected cell to be killed
double nstar = parameters.doubles("infection_threshold"); // how long the cell needs to attach for the infected cell to be killed
// XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX CHANGED SO THAT CTLS KILL ANY CELL
//if( internal_virus > nstar && pTarget->phenotype.death.dead == false && pTarget->type!=4)
if( pTarget->phenotype.death.dead == false && pTarget->type!=4)
{
std::vector<double> displacement = pTarget->position - pAttacker->position;
double distance_scale = norm( displacement );
if( distance_scale > max_attachment_distance )
{ return false; }
attach_cells( pAttacker, pTarget );
pAttacker->custom_data[attach_lifetime_i] = PhysiCell_globals.current_time + kill_time;
return true;
}
return false;
}
void attach_cells( Cell* pCell_1, Cell* pCell_2 )
{
#pragma omp critical
{
bool already_attached = false;
for( int i=0 ; i < pCell_1->state.neighbors.size() ; i++ )
{
if( pCell_1->state.neighbors[i] == pCell_2 )
{ already_attached = true; }
}
if( already_attached == false )
{ pCell_1->state.neighbors.push_back( pCell_2 ); }
already_attached = false;
for( int i=0 ; i < pCell_2->state.neighbors.size() ; i++ )
{
if( pCell_2->state.neighbors[i] == pCell_1 )
{ already_attached = true; }
}
if( already_attached == false )
{ pCell_2->state.neighbors.push_back( pCell_1 ); }
}
return;
}
void dettach_cells( Cell* pCell_1 , Cell* pCell_2 )
{
#pragma omp critical
{
bool found = false;
int i = 0;
while( !found && i < pCell_1->state.neighbors.size() )
{
// if cell 2 is in cell 1's list, remove it
if( pCell_1->state.neighbors[i] == pCell_2 )
{
int n = pCell_1->state.neighbors.size();
// copy last entry to current position
pCell_1->state.neighbors[i] = pCell_1->state.neighbors[n-1];
// shrink by one
pCell_1->state.neighbors.pop_back();
found = true;
}
i++;
}
found = false;
i = 0;
while( !found && i < pCell_2->state.neighbors.size() )
{
// if cell 1 is in cell 2's list, remove it
if( pCell_2->state.neighbors[i] == pCell_1 )
{
int n = pCell_2->state.neighbors.size();
// copy last entry to current position
pCell_2->state.neighbors[i] = pCell_2->state.neighbors[n-1];
// shrink by one
pCell_2->state.neighbors.pop_back();
found = true;
}
i++;
}
}
return;
}
void CTL_movement( Cell* pCell, Phenotype& phenotype, double dt )
{
static int wall_index = microenvironment.find_density_index( "wall" );
double wall_amount = pCell->nearest_density_vector()[wall_index];
static int chemokine_index = microenvironment.find_density_index( "chemokine" );
double chemokine_amount = pCell->nearest_density_vector()[chemokine_index];
int cycle_start_index = Ki67_basic.find_phase_index( PhysiCell_constants::Ki67_negative );
int cycle_end_index = Ki67_basic.find_phase_index( PhysiCell_constants::Ki67_positive );
std::vector<double> ae_ini(3);
// TH movement
if( wall_amount<2 )
{
pCell->phenotype.motility.migration_speed = 1;
pCell->phenotype.motility.migration_bias = 1;
pCell->phenotype.motility.migration_bias_direction = pCell->nearest_gradient(wall_index);
ae_ini = -1*pCell->position;
pCell->phenotype.motility.migration_bias = 1;
//std::cout<<pCell->nearest_gradient(wall_index)<<" "<<pCell->position<<" "<<ae_ini<<" "<<wall_amount<<std::endl;
normalize( &( ae_ini ) );
pCell->phenotype.motility.migration_bias_direction = ae_ini;
return;
}
else if(chemokine_amount>1e-8)// sample chemotaxis gradient and random walk in that direction
{
pCell->phenotype.motility.migration_speed = parameters.doubles("CTL_min_speed")+(parameters.doubles("CTL_max_speed")-parameters.doubles("CTL_min_speed"))*(chemokine_amount/(parameters.doubles("Chemokine_EC50")+chemokine_amount));
pCell->phenotype.motility.migration_bias = parameters.doubles("CTL_chemokine_migration_bias");//0.85;
pCell->phenotype.motility.migration_bias_direction = pCell->nearest_gradient(chemokine_index);
pCell->phenotype.cycle.data.transition_rate(cycle_start_index,cycle_end_index) = parameters.doubles("CTL_prolif_rate");
return;
}
else if(chemokine_amount>1e-3)
{
pCell->phenotype.cycle.data.transition_rate(cycle_start_index,cycle_end_index) = parameters.doubles("CTL_prolif_rate")*parameters.doubles("CTL_prolif_increase_due_to_stimulus");//7.9026*1e-5*1e1;
pCell->phenotype.motility.migration_speed = parameters.doubles("CTL_min_speed")+(parameters.doubles("CTL_max_speed")-parameters.doubles("CTL_min_speed"))*(chemokine_amount/(parameters.doubles("Chemokine_EC50")+chemokine_amount));
pCell->phenotype.motility.migration_bias = parameters.doubles("CTL_chemokine_migration_bias");//0.85;
pCell->phenotype.motility.migration_bias_direction = pCell->nearest_gradient(chemokine_index);
}
else
{
pCell->phenotype.motility.migration_bias = 0;
pCell->phenotype.motility.migration_speed = 4;
pCell->phenotype.cycle.data.transition_rate(cycle_start_index,cycle_end_index) = 7.9026*1e-5;
return;
}
}
bool immune_cell_attempt_apoptosis( Cell* pAttacker, Cell* pTarget, double dt )
{
static int apoptosis_model_index = pTarget->phenotype.death.find_death_model_index( "apoptosis" );
static int attach_lifetime_i = pAttacker->custom_data.find_variable_index( "attachment lifetime" );
// CTL kills cell if it has been attached for enough time
if( pAttacker->custom_data[attach_lifetime_i] < PhysiCell_globals.current_time )
{
//std::cout << "cell killed" << std::endl;
return true;
}
return false;
}
bool immune_cell_trigger_apoptosis( Cell* pAttacker, Cell* pTarget )
{
static int apoptosis_model_index = pTarget->phenotype.death.find_death_model_index( "apoptosis" );
static int virus_index = microenvironment.find_density_index( "virus" );
// if the Target cell is already dead, don't bother!
if( pTarget->phenotype.death.dead == true )
{ return false; }
pTarget->start_death( apoptosis_model_index );
pTarget->phenotype.molecular.fraction_released_at_death[virus_index] = 0;//1;
return true;
}
std::vector<std::string> colouring_by_intracellular_virus_amount( Cell* pCell )
{
std::vector< std::string > output( 4, "darkgrey" );
static int v_index = microenvironment.find_density_index( "virus");
static int infection_density_capacity = parameters.doubles("infection_density_capacity");
static double intracellular_virus_index = pCell->custom_data.find_variable_index( "intracellular_virus_amount" );
double p_min = 1;
double p_max = parameters.doubles("virus_burst_number");
double n_I = pCell->phenotype.molecular.internalized_total_substrates[v_index];
if(n_I>7000 && pCell->type ==2)
{std::cout<<" above 6600: "<<n_I<<std::endl;}
if(pCell->type==1 && pCell->phenotype.death.dead==false)
{
int oncoprotein = (int) round( (1.0/(p_max-p_min)) * (pCell->phenotype.molecular.internalized_total_substrates[v_index]-p_min) * 255.0 );
char szTempString [128]; // ceates a character array that can store 128
sprintf( szTempString , "rgb(%u,%u,%u)", oncoprotein, oncoprotein, 255-oncoprotein ); // puts oncoprotein, oncoprotein and 255-oncoprotein in place of u u u
if(pCell-> phenotype.cycle.data.current_phase_index==0)
{
output[0] = "orange";
output[1] = "orange";
output[2] = "coral";
output[3] = "coral";
return output;
}
else if(pCell-> phenotype.cycle.data.current_phase_index==1)
{
output[0] = "darkred";
output[1] = "darkred";
output[2] = "firebrick";
output[3] = "firebrick";
}
//}
}
if( pCell->type == 3)
{
if(pCell-> phenotype.cycle.data.current_phase_index==0)
{
output[0] = "aquamarine";
output[1] = "lightsteelblue";
output[2] = "lightskyblue";
output[3] = "aquamarine";
}
else if(pCell-> phenotype.cycle.data.current_phase_index==1)
{
output[0] = "darkslateblue";
output[1] = "darkblue";
output[2] = "darkblue";
output[3] = "aquamarine";
}
}
if( pCell->type == 2 && pCell->phenotype.death.dead==false)
{
if( n_I>1)//n_I > 1 )
{
double p_min = 1;
//double p_max = 6600;//V_0;
int oncoprotein1 = (int) round((210-139)*(1.0/(p_max-p_min)) * (n_I-1));
int oncoprotein2 = (int) round((180-69)*(1.0/(p_max-p_min)) * (n_I-1));
int oncoprotein3 = (int) round((140-19)*(1.0/(p_max-p_min)) * (n_I-1));
char szTempString [128]; // ceates a character array that can store 128
sprintf( szTempString , "rgb(%u,%u,%u)", 210-oncoprotein1, 180-oncoprotein2, 140-oncoprotein3); // puts oncoprotein, oncoprotein and 255-oncoprotein in place of u u u
output[0].assign( szTempString );
output[1]="brown";
output[2].assign( szTempString );
output[3]="brown";
return output;
}
else
{
output[0] = "rgb(104, 55, 99)";//"orchid";//"rgb(255,230,230)";
output[1] = "rgb(104, 55, 99)";
output[2] = "rgb(85, 50, 70)";//"plum";//"rgb(255,230,230)";
output[3] = "rgb(85, 50, 70)";
return output;
}
}
if( pCell->phenotype.death.dead == true )
{
output[0] = "rgb(255, 255, 224)";
output[1] = "rgb(255, 255, 224)";
output[2] = "rgb(255, 228, 181)";
output[3] = "rgb(255, 228, 181)";
return output;
}
if( pCell->type == 4)
{
output[0] = "rgb(234, 172, 199)";//"rgb(255,230,230)";
output[1] = "rgb(234, 172, 199)";
output[2] = "rgb(243, 186, 211)";//"rgb(255,230,230)";
output[3] = "rgb(243, 186, 211)";
}
return output;
}
void immune_cell_placement(void)
{
///////////////////////////////////////////////////////////////////////////////////////////////
//UNPROLIFERATIVE TH CELLS
//
double x = -886.1874 ;
double y = -377.9556;
Cell* pCell = NULL;
pCell = create_cell( TH_cell );
pCell->assign_position( x , y , 0.0 );
pCell-> phenotype.cycle.data.current_phase_index = 0;
x = -92.9598;
y = -408.5643;
pCell = create_cell( TH_cell );
pCell->assign_position( x , y , 0.0 );
pCell-> phenotype.cycle.data.current_phase_index = 0;
x = 715.7926;
y = 108.4208;
pCell = create_cell( TH_cell );
pCell->assign_position( x , y , 0.0 );
pCell-> phenotype.cycle.data.current_phase_index = 0;
x = 305.4827;
y = -100.0779;
pCell = create_cell( TH_cell );
pCell->assign_position( x , y , 0.0 );
pCell-> phenotype.cycle.data.current_phase_index = 0;
x = 914.8197;
y = 334.7098;
pCell = create_cell( TH_cell );
pCell->assign_position( x , y , 0.0 );
pCell-> phenotype.cycle.data.current_phase_index = 0;
x = 818.4357;
y = 102.3158;
pCell = create_cell( TH_cell );
pCell->assign_position( x , y , 0.0 );
pCell-> phenotype.cycle.data.current_phase_index = 0;
x = -657.9876;
y = 552.5539;
pCell = create_cell( TH_cell );
pCell->assign_position( x , y , 0.0 );
pCell-> phenotype.cycle.data.current_phase_index = 0;
x = 396.205;
y = 790.0036;
pCell = create_cell( TH_cell );
pCell->assign_position( x , y , 0.0 );
pCell-> phenotype.cycle.data.current_phase_index = 0;
x = -197.4969;
y = -709.7589;
pCell = create_cell( TH_cell );
pCell->assign_position( x , y , 0.0 );
pCell-> phenotype.cycle.data.current_phase_index = 0;
x = -591.2807;
y = -732.2582;
pCell = create_cell( TH_cell );
pCell->assign_position( x , y , 0.0 );
pCell-> phenotype.cycle.data.current_phase_index = 0;
x = 49.2169;
y = -452.7280;
pCell = create_cell( TH_cell );
pCell->assign_position( x , y , 0.0 );
pCell-> phenotype.cycle.data.current_phase_index = 0;
x = -26.8695;
y = 465.632;
pCell = create_cell( TH_cell );
pCell->assign_position( x , y , 0.0 );
pCell-> phenotype.cycle.data.current_phase_index = 0;
x = -289.5373;
y = 513.8335 ;
pCell = create_cell( TH_cell );
pCell->assign_position( x , y , 0.0 );
pCell-> phenotype.cycle.data.current_phase_index = 0;
x = -315.2772;
y = -772.8922;
pCell = create_cell( TH_cell );
pCell->assign_position( x , y , 0.0 );
pCell-> phenotype.cycle.data.current_phase_index = 0;
x = -120.1230;
y = -608.1192;
pCell = create_cell( TH_cell );
pCell->assign_position( x , y , 0.0 );
pCell-> phenotype.cycle.data.current_phase_index = 0;
x = -312.1967;
y = 974.7604;
pCell = create_cell( TH_cell );
pCell->assign_position( x , y , 0.0 );
pCell-> phenotype.cycle.data.current_phase_index = 0;
x = 924.1434;
y = 206.5514;
pCell = create_cell( TH_cell );
pCell->assign_position( x , y , 0.0 );
pCell-> phenotype.cycle.data.current_phase_index = 0;
x = -329.2369;
y = 386.8689;
pCell = create_cell( TH_cell );
pCell->assign_position( x , y , 0.0 );
pCell-> phenotype.cycle.data.current_phase_index = 0;
x = 434.6186;
y = 366.5498;
pCell = create_cell( TH_cell );
pCell->assign_position( x , y , 0.0 );
pCell-> phenotype.cycle.data.current_phase_index = 0;
x = -109.1024;
y = -992.4774;
pCell = create_cell( TH_cell );
pCell->assign_position( x , y , 0.0 );
pCell-> phenotype.cycle.data.current_phase_index = 0;
x = 588.8850;
y = 88.1708;
pCell = create_cell( TH_cell );
pCell->assign_position( x , y , 0.0 );
pCell-> phenotype.cycle.data.current_phase_index = 0;
x = 293.6073;
y = -769.3062;
pCell = create_cell( TH_cell );
pCell->assign_position( x , y , 0.0 );
pCell-> phenotype.cycle.data.current_phase_index = 0;
x = -758.5694;
y = 469.0668;
pCell = create_cell( TH_cell );
pCell->assign_position( x , y , 0.0 );
pCell-> phenotype.cycle.data.current_phase_index = 0;
x = 711.9720;
y = 522.8015;
pCell = create_cell( TH_cell );
pCell->assign_position( x , y , 0.0 );
pCell-> phenotype.cycle.data.current_phase_index = 0;
x = -202.5984;
y = 317.7974;
pCell = create_cell( TH_cell );
pCell->assign_position( x , y , 0.0 );
pCell-> phenotype.cycle.data.current_phase_index = 0;
x = -550.3849;
y = 31.0353;
pCell = create_cell( TH_cell );
pCell->assign_position( x , y , 0.0 );
pCell-> phenotype.cycle.data.current_phase_index = 0;
x = 641.0909;
y = -685.7513;
pCell = create_cell( TH_cell );
pCell->assign_position( x , y , 0.0 );
pCell-> phenotype.cycle.data.current_phase_index = 0;
x = 208.1485;
y = -182.9283;
pCell = create_cell( TH_cell );
pCell->assign_position( x , y , 0.0 );
pCell-> phenotype.cycle.data.current_phase_index = 0;
x = -773.5824;
y = 598.8495;
pCell = create_cell( TH_cell );
pCell->assign_position( x , y , 0.0 );
pCell-> phenotype.cycle.data.current_phase_index = 0;
x = 589.6732;
y = -64.6089;
pCell = create_cell( TH_cell );
pCell->assign_position( x , y , 0.0 );
pCell-> phenotype.cycle.data.current_phase_index = 0;
x = -631.5368;
y = -88.5340;
pCell = create_cell( TH_cell );
pCell->assign_position( x , y , 0.0 );
pCell-> phenotype.cycle.data.current_phase_index = 0;
x = 358.2984;
y = -894.3028;
pCell = create_cell( TH_cell );
pCell->assign_position( x , y , 0.0 );
pCell-> phenotype.cycle.data.current_phase_index = 0;
x = -65.4904;
y = -508.6133;
pCell = create_cell( TH_cell );
pCell->assign_position( x , y , 0.0 );
pCell-> phenotype.cycle.data.current_phase_index = 0;
x = 422.3507;
y = -808.1449;
pCell = create_cell( TH_cell );
pCell->assign_position( x , y , 0.0 );
pCell-> phenotype.cycle.data.current_phase_index = 0;
x = 69.0509;
y = -696.4078;
pCell = create_cell( TH_cell );
pCell->assign_position( x , y , 0.0 );
pCell-> phenotype.cycle.data.current_phase_index = 0;
x = 188.2291;
y = -34.1874;
pCell = create_cell( TH_cell );
pCell->assign_position( x , y , 0.0 );
pCell-> phenotype.cycle.data.current_phase_index = 0;
x = -890.0763;
y = 425.9101;
pCell = create_cell( TH_cell );
pCell->assign_position( x , y , 0.0 );
pCell-> phenotype.cycle.data.current_phase_index = 0;
x = 749.9007;
y = -614.8952;
pCell = create_cell( TH_cell );
pCell->assign_position( x , y , 0.0 );
pCell-> phenotype.cycle.data.current_phase_index = 0;
x = -69.6065;
y = -283.4312;
pCell = create_cell( TH_cell );
pCell->assign_position( x , y , 0.0 );
pCell-> phenotype.cycle.data.current_phase_index = 0;
x = 375.0652;
y = 20.8637;
pCell = create_cell( TH_cell );
pCell->assign_position( x , y , 0.0 );
pCell-> phenotype.cycle.data.current_phase_index = 0;
x = 14.8366;
y = -587.9312;
pCell = create_cell( TH_cell );
pCell->assign_position( x , y , 0.0 );
pCell-> phenotype.cycle.data.current_phase_index = 0;
x = -338.3966;
y = -646.7752;
pCell = create_cell( TH_cell );
pCell->assign_position( x , y , 0.0 );
pCell-> phenotype.cycle.data.current_phase_index = 0;
x = -617.0420;
y = -438.5693;
pCell = create_cell( TH_cell );
pCell->assign_position( x , y , 0.0 );
pCell-> phenotype.cycle.data.current_phase_index = 0;
x = -808.1436;
y = -480.9575;
pCell = create_cell( TH_cell );
pCell->assign_position( x , y , 0.0 );
pCell-> phenotype.cycle.data.current_phase_index = 0;
x = -11.5636;
y = -922.3531;
pCell = create_cell( TH_cell );
pCell->assign_position( x , y , 0.0 );
pCell-> phenotype.cycle.data.current_phase_index = 0;
x = -239.5675;
y = -578.7236;
pCell = create_cell( TH_cell );
pCell->assign_position( x , y , 0.0 );
pCell-> phenotype.cycle.data.current_phase_index = 0;
x = -521.0613;
y = 768.1352;
pCell = create_cell( TH_cell );
pCell->assign_position( x , y , 0.0 );
pCell-> phenotype.cycle.data.current_phase_index = 0;
x = 107.7491;
y = 797.8105;
pCell = create_cell( TH_cell );
pCell->assign_position( x , y , 0.0 );
pCell-> phenotype.cycle.data.current_phase_index = 0;
x = -447.2199;
y = -727.9198;
pCell = create_cell( TH_cell );
pCell->assign_position( x , y , 0.0 );
pCell-> phenotype.cycle.data.current_phase_index = 0;
x = 105.9531;
y = 441.1681;
pCell = create_cell( TH_cell );
pCell->assign_position( x , y , 0.0 );
pCell-> phenotype.cycle.data.current_phase_index = 0;
x = 644.2658;
y = -538.5330;
pCell = create_cell( TH_cell );
pCell->assign_position( x , y , 0.0 );
pCell-> phenotype.cycle.data.current_phase_index = 0;
x = 908.9122;
y = 26.160;
pCell = create_cell( TH_cell );
pCell->assign_position( x , y , 0.0 );
pCell-> phenotype.cycle.data.current_phase_index = 0;
x = 701.5531;
y = -4.7266;
pCell = create_cell( TH_cell );
pCell->assign_position( x , y , 0.0 );
pCell-> phenotype.cycle.data.current_phase_index = 0;
x = 509.1125;
y = 700.8723;
pCell = create_cell( TH_cell );
pCell->assign_position( x , y , 0.0 );
pCell-> phenotype.cycle.data.current_phase_index = 0;
x = 22.525;
y = 700.6533;
pCell = create_cell( TH_cell );
pCell->assign_position( x , y , 0.0 );
pCell-> phenotype.cycle.data.current_phase_index = 0;
x = 840.2498;
y = 552.8631;
pCell = create_cell( TH_cell );
pCell->assign_position( x , y , 0.0 );
pCell-> phenotype.cycle.data.current_phase_index = 0;
x = 285.0359;
y = -535.5775;
pCell = create_cell( TH_cell );
pCell->assign_position( x , y , 0.0 );
pCell-> phenotype.cycle.data.current_phase_index = 0;
x =-758.6877;
y = -605.8141;
pCell = create_cell( TH_cell );
pCell->assign_position( x , y , 0.0 );
pCell-> phenotype.cycle.data.current_phase_index = 0;
x =285.0359;
y = -535.5775;
pCell = create_cell( TH_cell );
pCell->assign_position( x , y , 0.0 );
pCell-> phenotype.cycle.data.current_phase_index = 0;
x =-758.6877;
y =-605.8141;
pCell = create_cell( TH_cell );
pCell->assign_position( x , y , 0.0 );
pCell-> phenotype.cycle.data.current_phase_index = 0;
x =826.7548;
y =-303.953;
pCell = create_cell( TH_cell );
pCell->assign_position( x , y , 0.0 );
pCell-> phenotype.cycle.data.current_phase_index = 0;
x =142.712;
y =668.9715;
pCell = create_cell( TH_cell );
pCell->assign_position( x , y , 0.0 );
pCell-> phenotype.cycle.data.current_phase_index = 0;
x =-566.4609;
y =651.0637;
pCell = create_cell( TH_cell );
pCell->assign_position( x , y , 0.0 );
pCell-> phenotype.cycle.data.current_phase_index = 0;
x =-136.700;
y = 828.8107;
pCell = create_cell( TH_cell );
pCell->assign_position( x , y , 0.0 );
pCell-> phenotype.cycle.data.current_phase_index = 0;
x =-310.4904;
y =249.8461;
pCell = create_cell( TH_cell );
pCell->assign_position( x , y , 0.0 );
pCell-> phenotype.cycle.data.current_phase_index = 0;
x =249.6918;
y =605.5657;
pCell = create_cell( TH_cell );
pCell->assign_position( x , y , 0.0 );
pCell-> phenotype.cycle.data.current_phase_index = 0;
x =1.0007e+03;
y = 112.6398;
pCell = create_cell( TH_cell );
pCell->assign_position( x , y , 0.0 );
pCell-> phenotype.cycle.data.current_phase_index = 0;
x = 223.6434;
y = -885.2210;
pCell = create_cell( TH_cell );
pCell->assign_position( x , y , 0.0 );
pCell-> phenotype.cycle.data.current_phase_index = 0;
x = 49.8545;
y = 571.3492;
pCell = create_cell( TH_cell );
pCell->assign_position( x , y , 0.0 );
pCell-> phenotype.cycle.data.current_phase_index = 0;
x = -100.4299;
y = 233.0141;
pCell = create_cell( TH_cell );
pCell->assign_position( x , y , 0.0 );
pCell-> phenotype.cycle.data.current_phase_index = 0;
x = 109.5735;
y = -954.7865;
pCell = create_cell( TH_cell );
pCell->assign_position( x , y , 0.0 );
pCell-> phenotype.cycle.data.current_phase_index = 0;
pCell->phenotype.cycle.data.current_phase_index = 0;
x = -622.7696;
y = 428.8238;
pCell = create_cell( TH_cell );
pCell->assign_position( x , y , 0.0 );
pCell-> phenotype.cycle.data.current_phase_index = 0;
x = -950.7404;
y = 289.7073;
pCell = create_cell( TH_cell );
pCell->assign_position( x , y , 0.0 );
pCell-> phenotype.cycle.data.current_phase_index = 0;
x = -746.3485;
y = -354.7596;
pCell = create_cell( TH_cell );
pCell->assign_position( x , y , 0.0 );
pCell-> phenotype.cycle.data.current_phase_index = 0;
x = -58.8064;
y = -710.556;
pCell = create_cell( TH_cell );
pCell->assign_position( x , y , 0.0 );
pCell-> phenotype.cycle.data.current_phase_index = 0;
///////////////////////////////////////////////////////////////////////////////////////////////
//PROLIFERATIVE TH CELLS
x = 18.3263;
y = 202.6912;
pCell = create_cell( TH_cell );
pCell->assign_position( x , y , 0.0 );
pCell-> phenotype.cycle.data.current_phase_index = 1;
x = 85.522;
y = 928.9369;
pCell = create_cell( TH_cell );
pCell->assign_position( x , y , 0.0 );
pCell-> phenotype.cycle.data.current_phase_index = 1;
x = 294.9299;
y = 408.8944;
pCell = create_cell( TH_cell );
pCell->assign_position( x , y , 0.0 );
pCell-> phenotype.cycle.data.current_phase_index = 1;
x = 490.6082;
y = -357.8950;
pCell = create_cell( TH_cell );
pCell->assign_position( x , y , 0.0 );
pCell-> phenotype.cycle.data.current_phase_index = 1;
///////////////////////////////////////////////////////////////////////////////////////////////
//UNPROLIFERATIVE CTL CELLS
x = -229.7546;
y = -99.6055;
pCell = create_cell( CTL_cell );
pCell->assign_position( x , y , 0.0 );
pCell-> phenotype.cycle.data.current_phase_index = 0;
x = 357.8347;
y = 634.1085;
pCell = create_cell( CTL_cell );
pCell->assign_position( x , y , 0.0 );
pCell-> phenotype.cycle.data.current_phase_index = 0;
x = 563.1912;
y = -209.8626;
pCell = create_cell( CTL_cell );
pCell->assign_position( x , y , 0.0 );
pCell-> phenotype.cycle.data.current_phase_index = 0;
x = -465.3017;
y = -404.2420;
pCell = create_cell( CTL_cell );
pCell->assign_position( x , y , 0.0 );
pCell-> phenotype.cycle.data.current_phase_index = 0;
x = -739.3612;
y = -195.8691;
pCell = create_cell( CTL_cell );
pCell->assign_position( x , y , 0.0 );
pCell-> phenotype.cycle.data.current_phase_index = 0;
x = -310.6741;
y = 91.5128;
pCell = create_cell( CTL_cell );
pCell->assign_position( x , y , 0.0 );
pCell-> phenotype.cycle.data.current_phase_index = 0;
x =-836.8711;
y = 5.789;
pCell = create_cell( CTL_cell );
pCell->assign_position( x , y , 0.0 );
pCell-> phenotype.cycle.data.current_phase_index = 0;
x =170.3629;
y =296.8521;
pCell = create_cell( CTL_cell );
pCell->assign_position( x , y , 0.0 );
pCell-> phenotype.cycle.data.current_phase_index = 0;
x =502.7784;
y =-503.5691;
pCell = create_cell( CTL_cell );
pCell->assign_position( x , y , 0.0 );
pCell-> phenotype.cycle.data.current_phase_index = 0;
x =717.2875;
y =-384.5512;
pCell = create_cell( CTL_cell );
pCell->assign_position( x , y , 0.0 );
pCell-> phenotype.cycle.data.current_phase_index = 0;
x =-293.0794;
y =-299.6722;
pCell = create_cell( CTL_cell );
pCell->assign_position( x , y , 0.0 );
pCell-> phenotype.cycle.data.current_phase_index = 0;
x =660.4160;
y =663.8240;
pCell = create_cell( CTL_cell );
pCell->assign_position( x , y , 0.0 );
pCell-> phenotype.cycle.data.current_phase_index = 0;
x =-619.8710;
y =-589.8832;
pCell = create_cell( CTL_cell );
pCell->assign_position( x , y , 0.0 );
pCell-> phenotype.cycle.data.current_phase_index = 0;
x =426.8735;
y =928.6956;
pCell = create_cell( CTL_cell );
pCell->assign_position( x , y , 0.0 );
pCell-> phenotype.cycle.data.current_phase_index = 0;
x =-167.0797;
y =687.6530;
pCell = create_cell( CTL_cell );
pCell->assign_position( x , y , 0.0 );
pCell-> phenotype.cycle.data.current_phase_index = 0;
x =-1.0237e3;
y =137.0964;
pCell = create_cell( CTL_cell );
pCell->assign_position( x , y , 0.0 );
pCell-> phenotype.cycle.data.current_phase_index = 0;
x =502.0188;
y =229.9418;
pCell = create_cell( CTL_cell );
pCell->assign_position( x , y , 0.0 );
pCell-> phenotype.cycle.data.current_phase_index = 0;
x =329.8713;
y =168.4815;
pCell = create_cell( CTL_cell );
pCell->assign_position( x , y , 0.0 );
pCell-> phenotype.cycle.data.current_phase_index = 0;
x =-263.1634;
y =-450.6436;
pCell = create_cell( CTL_cell );
pCell->assign_position( x , y , 0.0 );
pCell-> phenotype.cycle.data.current_phase_index = 0;
x =144.7437;
y =101.6446;
pCell = create_cell( CTL_cell );
pCell->assign_position( x , y , 0.0 );
pCell-> phenotype.cycle.data.current_phase_index = 0;
x =395.2043;
y =-576.2011;
pCell = create_cell( CTL_cell );
pCell->assign_position( x , y , 0.0 );
pCell-> phenotype.cycle.data.current_phase_index = 0;
x =-430.9143;
y =850.4354;
pCell = create_cell( CTL_cell );
pCell->assign_position( x , y , 0.0 );
pCell-> phenotype.cycle.data.current_phase_index = 0;
x =76.5861;
y =-245.4335;
pCell = create_cell( CTL_cell );
pCell->assign_position( x , y , 0.0 );
pCell-> phenotype.cycle.data.current_phase_index = 0;
x =-456.6180;
y =-557.6040;
pCell = create_cell( CTL_cell );
pCell->assign_position( x , y , 0.0 );
pCell-> phenotype.cycle.data.current_phase_index = 0;
x =-55.1681;
y =-23.9806;
pCell = create_cell( CTL_cell );
pCell->assign_position( x , y , 0.0 );
pCell-> phenotype.cycle.data.current_phase_index = 0;
x =806.7518;
y = 242.4464;
pCell = create_cell( CTL_cell );
pCell->assign_position( x , y , 0.0 );
pCell-> phenotype.cycle.data.current_phase_index = 0;
x =-644.9479;
y =796.8378;
pCell = create_cell( CTL_cell );
pCell->assign_position( x , y , 0.0 );
pCell-> phenotype.cycle.data.current_phase_index = 0;
x =-157.3983;
y =509.2217;
pCell = create_cell( CTL_cell );
pCell->assign_position( x , y , 0.0 );
pCell-> phenotype.cycle.data.current_phase_index = 0;
x =662.5205;
y =290.8544;
pCell = create_cell( CTL_cell );
pCell->assign_position( x , y , 0.0 );
pCell-> phenotype.cycle.data.current_phase_index = 0;
x =583.3736;
y =843.4895;
pCell = create_cell( CTL_cell );
pCell->assign_position( x , y , 0.0 );
pCell-> phenotype.cycle.data.current_phase_index = 0;
x =-107.6750;
y = -839.4925;
pCell = create_cell( CTL_cell );
pCell->assign_position( x , y , 0.0 );
pCell-> phenotype.cycle.data.current_phase_index = 0;
x =-423.3672;
y =579.6212;
pCell = create_cell( CTL_cell );
pCell->assign_position( x , y , 0.0 );
pCell-> phenotype.cycle.data.current_phase_index = 0;
x =-432.9000;
y =-70.883;
pCell = create_cell( CTL_cell );
pCell->assign_position( x , y , 0.0 );
pCell-> phenotype.cycle.data.current_phase_index = 0;
x =-530.5991;
y =224.9672;
pCell = create_cell( CTL_cell );
pCell->assign_position( x , y , 0.0 );
pCell-> phenotype.cycle.data.current_phase_index = 0;
x =675.3453;
y =394.918;
pCell = create_cell( CTL_cell );
pCell->assign_position( x , y , 0.0 );
pCell-> phenotype.cycle.data.current_phase_index = 0;
x =-321.6393;
y =731.7346;
pCell = create_cell( CTL_cell );
pCell->assign_position( x , y , 0.0 );
pCell-> phenotype.cycle.data.current_phase_index = 0;
x =503.9698;
y =498.1822;
pCell = create_cell( CTL_cell );
pCell->assign_position( x , y , 0.0 );
pCell-> phenotype.cycle.data.current_phase_index = 0;
x =-749.3654;
y =210.6520;
pCell = create_cell( CTL_cell );
pCell->assign_position( x , y , 0.0 );
pCell-> phenotype.cycle.data.current_phase_index = 0;
x = 194.5936;
y =-670.9127;
pCell = create_cell( CTL_cell );
pCell->assign_position( x , y , 0.0 );
pCell-> phenotype.cycle.data.current_phase_index = 0;
x = 499.6782;
y =-731.5829 ;
pCell = create_cell( CTL_cell );
pCell->assign_position( x , y , 0.0 );
pCell-> phenotype.cycle.data.current_phase_index = 0;
x =337.0153;
y =-298.361;
pCell = create_cell( CTL_cell );
pCell->assign_position( x , y , 0.0 );
pCell-> phenotype.cycle.data.current_phase_index = 0;
x =-479.2653;
y =412.2822;
pCell = create_cell( CTL_cell );
pCell->assign_position( x , y , 0.0 );
pCell-> phenotype.cycle.data.current_phase_index = 0;
x =-479.2653;
y =412.2822;
pCell = create_cell( CTL_cell );
pCell->assign_position( x , y , 0.0 );
pCell-> phenotype.cycle.data.current_phase_index = 0;
///////////////////////////////////////////////////////////////////////////////////////////////
// PROLIFERATIVE CTL cell
x = -340.8754;
y = -928.9261;
pCell = create_cell( CTL_cell );
pCell->assign_position( x , y , 0.0 );
pCell-> phenotype.cycle.data.current_phase_index = 1;
x = 244.3090;
y = -461.5348;
pCell = create_cell( CTL_cell );
pCell->assign_position( x , y , 0.0 );
pCell-> phenotype.cycle.data.current_phase_index = 1;
//*/
return;
}
| [
"[email protected]"
] | |
22ae7f79e84bb57fafce98bf168dd8f7bdcc72f0 | 0d2d3f5722091fc83842b20991864b5b78c85d5e | /FuckLeetCode/candy.cpp | 938381f64e923ac348df0fd4442fc446d99dd22a | [] | no_license | 0x0all/FuckInterview | 010d586915054a3d82203705d094c1e1c5803de6 | d83cc1dc1583bd32678494feb524e35b70357d91 | refs/heads/master | 2020-12-25T00:50:43.585098 | 2014-03-03T01:32:45 | 2014-03-03T01:32:45 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,372 | cpp | /*
* There are N children standing in a line. Each child is assigned a rating value.
*
* You are giving candies to these children subjected to the following requirements:
*
* Each child must have at least one candy.
* Children with a higher rating get more candies than their neighbors.
* What is the minimum candies you must give?
*/
#include <vector>
#include <assert.h>
int Candy(std::vector<int> &ratings) {
int sum = 0;
std::vector<int> candies(ratings.size(), 1);
// Check the ascending sequence
for (int i = 1; i < ratings.size(); i++)
if (ratings[i] > ratings[i - 1])
candies[i] = candies[i - 1] + 1;
// Check the descending sequence
for (int i = ratings.size() - 2; i >= 0; i--)
if (ratings[i] > ratings[i + 1])
candies[i] = std::max(candies[i + 1] + 1, candies[i]);
for (int i = 0; i < candies.size(); i++)
sum += candies[i];
return sum;
}
int main() {
int a[] = {58,21,72,77,48,9,38,71,68,77,82,47,25,94,89,54,26,54,54,99,64,71,76,63,81,82,60,64,29,51,87,87,72,12,16,20,21,54,43,41,83,77,41,61,72,82,15,50,36,69,49,53,92,77,16,73,12,28,37,41,79,25,80,3,37,48,23,10,55,19,51,38,96,92,99,68,75,14,18,63,35,19,68,28,49,36,53,61,64,91,2,43,68,34,46,57,82,22,67,89};
std::vector<int> vec(a, a + sizeof(a) / sizeof(int));
assert(Candy(vec) == 208);
return 0;
}
| [
"[email protected]"
] | |
879ca60af9ac1e36cf3220d5b3bdfa40b462f064 | efe9b015f3e45e8df7a457d39292a6a31afb23ec | /llvm/lib/Target/CSKY/CSKYMCInstLower.cpp | c42a56bfb04eaf3c596ce0b6da34f496bbc839d4 | [
"NCSA",
"LLVM-exception",
"Apache-2.0"
] | permissive | open-dotnet/llvm-project | 3c8cd67ed2501630f46e2ff574d6a8a4e977e92c | b72b56016a6b586a22a49f145c924c03e4239b1d | refs/heads/main | 2023-09-05T18:23:30.802715 | 2021-11-22T02:14:30 | 2021-11-22T02:16:02 | 430,545,862 | 1 | 0 | null | 2021-11-22T03:09:22 | 2021-11-22T03:09:22 | null | UTF-8 | C++ | false | false | 3,633 | cpp | //===-- CSKYMCInstLower.cpp - Convert CSKY MachineInstr to an MCInst --------=//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
//
// This file contains code to lower CSKY MachineInstrs to their corresponding
// MCInst records.
//
//===----------------------------------------------------------------------===//
#include "CSKYMCInstLower.h"
#include "MCTargetDesc/CSKYBaseInfo.h"
#include "MCTargetDesc/CSKYMCExpr.h"
#include "llvm/CodeGen/AsmPrinter.h"
#include "llvm/MC/MCExpr.h"
#define DEBUG_TYPE "csky-mcinst-lower"
using namespace llvm;
CSKYMCInstLower::CSKYMCInstLower(MCContext &Ctx, AsmPrinter &Printer)
: Ctx(Ctx), Printer(Printer) {}
void CSKYMCInstLower::Lower(const MachineInstr *MI, MCInst &OutMI) const {
OutMI.setOpcode(MI->getOpcode());
for (const MachineOperand &MO : MI->operands()) {
MCOperand MCOp;
if (lowerOperand(MO, MCOp))
OutMI.addOperand(MCOp);
}
}
MCOperand CSKYMCInstLower::lowerSymbolOperand(const MachineOperand &MO,
MCSymbol *Sym) const {
CSKYMCExpr::VariantKind Kind;
MCContext &Ctx = Printer.OutContext;
switch (MO.getTargetFlags()) {
default:
llvm_unreachable("Unknown target flag.");
case CSKYII::MO_None:
Kind = CSKYMCExpr::VK_CSKY_None;
break;
case CSKYII::MO_GOT32:
Kind = CSKYMCExpr::VK_CSKY_GOT;
break;
case CSKYII::MO_GOTOFF:
Kind = CSKYMCExpr::VK_CSKY_GOTOFF;
break;
case CSKYII::MO_ADDR32:
Kind = CSKYMCExpr::VK_CSKY_ADDR;
break;
case CSKYII::MO_PLT32:
Kind = CSKYMCExpr::VK_CSKY_PLT;
break;
case CSKYII::MO_ADDR_HI16:
Kind = CSKYMCExpr::VK_CSKY_ADDR_HI16;
break;
case CSKYII::MO_ADDR_LO16:
Kind = CSKYMCExpr::VK_CSKY_ADDR_LO16;
break;
}
const MCExpr *ME =
MCSymbolRefExpr::create(Sym, MCSymbolRefExpr::VK_None, Ctx);
if (Kind != CSKYMCExpr::VK_CSKY_None)
ME = CSKYMCExpr::create(ME, Kind, Ctx);
return MCOperand::createExpr(ME);
}
bool CSKYMCInstLower::lowerOperand(const MachineOperand &MO,
MCOperand &MCOp) const {
switch (MO.getType()) {
default:
llvm_unreachable("unknown operand type");
case MachineOperand::MO_RegisterMask:
break;
case MachineOperand::MO_Immediate:
MCOp = MCOperand::createImm(MO.getImm());
break;
case MachineOperand::MO_Register:
if (MO.isImplicit())
return false;
MCOp = MCOperand::createReg(MO.getReg());
break;
case MachineOperand::MO_MachineBasicBlock:
MCOp = MCOperand::createExpr(
MCSymbolRefExpr::create(MO.getMBB()->getSymbol(), Ctx));
break;
case MachineOperand::MO_GlobalAddress:
MCOp = lowerSymbolOperand(MO, Printer.getSymbol(MO.getGlobal()));
break;
case MachineOperand::MO_BlockAddress:
MCOp = lowerSymbolOperand(
MO, Printer.GetBlockAddressSymbol(MO.getBlockAddress()));
break;
case MachineOperand::MO_ExternalSymbol:
MCOp = lowerSymbolOperand(
MO, Printer.GetExternalSymbolSymbol(MO.getSymbolName()));
break;
case MachineOperand::MO_ConstantPoolIndex:
MCOp = lowerSymbolOperand(MO, Printer.GetCPISymbol(MO.getIndex()));
break;
case MachineOperand::MO_JumpTableIndex:
MCOp = lowerSymbolOperand(MO, Printer.GetJTISymbol(MO.getIndex()));
break;
case MachineOperand::MO_MCSymbol:
MCOp = lowerSymbolOperand(MO, MO.getMCSymbol());
break;
}
return true;
} | [
"[email protected]"
] | |
a205e5f0675676b2c8f0ef74a43a5dd54d6a6a67 | 6fb361e086e445c16150397453bfbb086082a8f8 | /Graphics/DirectX11/Buffers/D3D11IndexBuffer.cpp | ccdabecae79b7c3be8bd863c7ca6f0d2271bcb2a | [] | no_license | blockspacer/EightEngine | d16d5df253697379e14309644a459f115ef449c1 | 61f7f1535063fae06200291fe0e772c454388341 | refs/heads/master | 2021-04-13T15:28:50.818682 | 2016-09-01T20:17:54 | 2016-09-01T20:17:58 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,220 | cpp | #include "stdafx.h"
#include "D3D11IndexBuffer.h"
#include "EightEngine\Graphics\ApiWrapper\RenderingDevice.h"
#include "EightEngine\Graphics\ApiWrapper\RenderingDeviceContext.h"
bool D3D11IndexBuffer::CreateApiSpecific(const BYTE *pIndices, UINT indexCount,
UINT indexStride, const std::shared_ptr<RenderingDevice> &pRenderingDevice)
{
Microsoft::WRL::ComPtr<ID3D11Device> &pDevice3D = pRenderingDevice->GetDevice3D();
// Translate engine description to directX
CD3D11_BUFFER_DESC bufferDesc(indexCount * indexStride, D3D11_BIND_INDEX_BUFFER,
static_cast<D3D11_USAGE>(m_UsageFlag), m_CpuAccessFlag);
HRESULT hr;
// If you want to create empty index buffer and fill it with data later
if (!pIndices)
{
hr = pDevice3D->CreateBuffer(&bufferDesc, nullptr, &m_pIndexBuffer);
}
else {
D3D11_SUBRESOURCE_DATA subresourceData;
subresourceData.pSysMem = pIndices;
subresourceData.SysMemPitch = 0;
subresourceData.SysMemSlicePitch = 0;
hr = pDevice3D->CreateBuffer(&bufferDesc, &subresourceData, &m_pIndexBuffer);
}
if (FAILED(hr))
{
EIGHT_ERROR("Creating index buffer failed!");
return false;
}
m_Format = indexStride == sizeof(UINT) ? DXGI_FORMAT_R32_UINT : DXGI_FORMAT_R16_UINT;
m_Stride = indexStride;
return true;
}
bool D3D11IndexBuffer::UpdateIndicesApiSpecific(const BYTE *pNewIndices, UINT indexCount,
const std::shared_ptr<RenderingDeviceContext> &pRenderingDeviceContext)
{
// First map data(this mean that allocate new buffer, because discard parameter is used)
D3D11_MAPPED_SUBRESOURCE mappedData;
HRESULT hr = pRenderingDeviceContext->GetContext3D()->Map(m_pIndexBuffer, 0,
D3D11_MAP_WRITE_DISCARD, 0, &mappedData);
if (FAILED(hr))
{
return false;
}
// Then copy data
memcpy(mappedData.pData, pNewIndices, indexCount * m_Stride);
// And unmap buffer(this mean transfer data back to gpu)
pRenderingDeviceContext->GetContext3D()->Unmap(m_pIndexBuffer, 0);
return true;
}
void D3D11IndexBuffer::BindApiSpecific(
const std::shared_ptr<RenderingDeviceContext> &pRenderingDeviceContext)
{
// Future work binding multiple buffers at the same time -> batching
pRenderingDeviceContext->GetContext3D()->IASetIndexBuffer(
m_pIndexBuffer, m_Format, m_Offset);
} | [
"[email protected]"
] | |
ba89828c0b55c7b0cd8fae7cd477dca35fb044e7 | 290952d106627de07fc2c9581665e7c560ab18bd | /ACM ICPC 2016 Dhaka Regional Preliminary Mock Contest/C. Stick to Triangle checking.cpp | c0eeb822b98cbc7ac36339924852e6d3a1dc5487 | [] | no_license | MdAbuNafeeIbnaZahid/Competitive-Programming | 8669db792d3d604ee09429378da52d238b0e5b13 | 5b8f4f0c08c62ac410fdf153b3c4bd19775411b1 | refs/heads/master | 2021-01-20T07:57:04.742595 | 2018-09-25T15:29:32 | 2018-09-25T15:29:32 | 83,894,136 | 4 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,505 | cpp | #include <bits/stdc++.h>
using namespace std;
long long T, N;
long long X, Y, Z;
long long a,b, c, d, e, f, ans, low, high, ans2;
int main()
{
//freopen("input.txt", "r", stdin);
//cin >> T;
for (a = 10000; a <= 10000; a++)
{
//cout << "a = " << a << endl;
ans = 0;
N = a;
//cin >> N;
//cout << "N = " << N << endl;
//high = (N+1)/2;
for (b = 1; b <= N; b++)
{
//cout << "b = " << b << endl;
//low = b;
//high = ((N-b)/2.0);
low = max(N-b-(N/2), b);
high = N-b-low;
//cout << "low = " << low << endl;
//cout << "high = " << high << endl;
if ( high < low )
{
break;
}
ans += ( (high-low+2)/2 );
//cout << "ans = " << ans << endl;
}
//cout << ans << endl;
//if (a < T) cout << endl;
ans2 = 0;
for (X = 1; X <= N; X++)
{
for (Y = X; Y <= N; Y++)
{
for (Z = Y; Z <= N; Z++)
{
if ( X+Y+Z == N && Z <= X+Y )
{
ans2++;
}
}
}
}
//cout << "ans = " << ans << ", ans2 = " << ans2 << endl;
if (ans != ans2)
{
cout << "a = " <<a << endl;
cout << "ans != ans2" << endl;
}
}
return 0;
}
| [
"[email protected]"
] | |
329e9a0a8e0a5640d11c704efe1b6ab3f5614ae5 | 1c91b63316701109bb1f7f2dea716ce8db8ced3a | /src/Player.cpp | 02ea0d5e1a638b47c43a802f380ddc64f7f63fd6 | [
"Apache-2.0"
] | permissive | CesarVaz/Projeto-1.2018 | e75d550f66c4324f9b93eeb04615cf672df14eea | 1a08b503ccac732e8d0c04903b13a7ee8ea7487d | refs/heads/master | 2022-12-20T23:26:02.400281 | 2020-09-27T21:17:07 | 2020-09-27T21:17:07 | 133,577,540 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,561 | cpp | #include "Player.h"
static const float sCD = 0.25f;
static const float jCD = 1.0f;
//ctor dtor
Player::Player(sf::Texture* texture, sf::Vector2u imageCount, float switchTime, sf::Texture* projTexture, float speed):
Animation(texture, imageCount, switchTime), projectile(projTexture)
{
this->speed = speed;
row = 0;
faceRight = true;
setBodyPosition(0.0f, -192.0f);
hitTheFloor = false;
jumpHeight = 180.0f;
shootCD = sCD;
jumpCD = jCD;
body.setSize(sf::Vector2f(100.0f, 150.0f));
body.setOrigin(body.getSize()/2.0f);
body.setTexture(texture);
damage = 0;
dead = false;
}
//sets
void Player::setSpeed(float _speed)
{
speed = _speed;
}
void Player::setBodyPosition(float x, float y)
{
body.setPosition(x, y);
}
//gets
sf::RectangleShape Player::getBody()
{
return body;
}
sf::Vector2f Player::GetPosition()
{
return body.getPosition();
}
bool Player::getFaceRight()
{
return faceRight;
}
bool Player::getDead()
{
return dead;
}
//interacoes com o ambiente
//do personagem
void Player::CheckCollision_Player(sf::RectangleShape platformBody)
{
if((body.getGlobalBounds().left + body.getGlobalBounds().width) < platformBounds.left || body.getGlobalBounds().left > (platformBounds.left + platformBounds.width))
hitTheFloor = false;
if(body.getGlobalBounds().intersects(platformBody.getGlobalBounds()))
{
platformBounds = platformBody.getGlobalBounds();
if(body.getPosition().y > platformBody.getPosition().y + platformBody.getSize().y / 2)
{
body.move(0.0, 1.0);
}
else
if(body.getPosition().y < platformBody.getPosition().y - platformBody.getSize().y / 2)
{
body.move(0.0, - 1.0);
hitTheFloor = true;
}
else
if(body.getPosition().x < platformBody.getPosition().x - platformBody.getSize().x / 2)
{
body.move(- 1.0, 0.0);
}
else
if(body.getPosition().x > platformBody.getPosition().x + platformBody.getSize().x / 2)
{
body.move(1.0, 0.0);
}
}
}
//do tiro
void Player::CheckCollision_ProjectileVector(sf::RectangleShape target)
{
for(i = 0; i < vectProj.size(); i++)
{
vectProj[i].CheckCollision(target);
if(vectProj[i].collision == true)
{
vectProj.erase (vectProj.begin()+i);
vectProj.shrink_to_fit();
}
}
}
void Player::CheckCollision_ProjectileVector_Damage(sf::RectangleShape target, int &damage)
{
for(i = 0; i < vectProj.size(); i++)
{
vectProj[i].CheckCollision_Damage(target, damage);
if(vectProj[i].collision == true)
{
vectProj.erase (vectProj.begin()+i);
vectProj.shrink_to_fit();
}
}
}
//INPUTS
void Player::move(string direction)
{
if(dead == false)
{
if(direction == "left")
{
velocity.x -= speed;
}
if(direction == "right")
{
velocity.x += speed;
}
}
}
void Player::jump()
{
if(dead == false)
{
if (jumpCD >= jCD && hitTheFloor == true)
{
velocity.y = -sqrtf(2.0f * 981.0f * jumpHeight);
jumpCD = 0.0f;
hitTheFloor = false;
}
}
}
void Player::shoot()
{
if(dead == false)
{
if (shootCD >= sCD)
{
shootCD = 0.0f;
vectProj.push_back(projectile);
vectProj[vectProj.size() - 1].addVelocity(velocity);
vectProj[vectProj.size() - 1].setFaceRight(getFaceRight());
vectProj[vectProj.size() - 1].setBodyPosition(body.getPosition(), getFaceRight());
}
}
}
//Atualizacao e grafico personagem
void Player::Update_Player(float deltaTime)
{
shootCD += deltaTime;
jumpCD += deltaTime;
//gravidade
velocity.y += 981.0f * deltaTime;
if (hitTheFloor == true)
velocity.y = 0.0f;
if (velocity.y > 3000.0f)
dead = true;
if(damage >= 200 && dead == false)
{
if(faceRight == true)
body.rotate(270);
else
body.rotate(90);
hitTheFloor = false;
row = 3;
dead = true;
}
if(dead == false)
{
if(velocity.x == 0.0f)
row = 1;
else
row = 2;
}
if(velocity.x > 0.0f)
faceRight = true;
if(velocity.x < 0.0f)
faceRight = false;
for(i = 0; i < vectProj.size(); i++)
{
vectProj[i].totalTime += deltaTime;
if(vectProj[i].totalTime >= vectProj[i].duration)
{
vectProj.erase (vectProj.begin()+i);
vectProj.shrink_to_fit();
}
}
Update(row, deltaTime, faceRight);
body.setTextureRect(uvRect);
body.move(velocity * deltaTime);
velocity.x = 0.0f;
}
void Player::Draw_Player(sf::RenderWindow& window)
{
window.draw(body);
}
//Atualizacao e grafico tiro
void Player::Update_Projectile(float deltaTime)
{
for(i = 0; i < vectProj.size(); i++)
{
vectProj[i].Update_Projectile(deltaTime);
}
}
void Player::Draw_Projectile(sf::RenderWindow& window)
{
for(i = 0; i < vectProj.size(); i++)
{
vectProj[i].Draw(window);
}
}
| [
"[email protected]"
] | |
e7c94042914803f78664fe36a18cca2021fa5a94 | e798f3cd0d6cc6ad191702bbb387afdb0ae9eab0 | /Classes/Messages/ConfirmMessage.hpp | b09e000efbf975ebb078139a252cf8e25ae3ad21 | [] | no_license | Morgan87/FlameDragonX | 9dbd359c939df08a1f7c7a8a769d9408bf50ca10 | 15ed056572c52df76cfea8990cc1e5f81331c8fc | refs/heads/master | 2021-05-07T04:08:19.692309 | 2016-11-29T22:41:46 | 2016-11-29T22:41:46 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 464 | hpp | //
// ConfirmMessage.hpp
// FlameDragonX
//
// Created by SuiYi on 9/13/16.
//
//
#ifndef ConfirmMessage_hpp
#define ConfirmMessage_hpp
#include "cocos2d.h"
#include "ConversationMessage.hpp"
class ConfirmMessage : public ConversationMessage
{
private:
public:
ConfirmMessage(std::string content);
ConfirmMessage(Creature * creature, std::string content);
void handleClick(Vec2 location) override;
};
#endif /* ConfirmMessage_hpp */
| [
"[email protected]"
] | |
e312a356d8cdd6c9177265ac4fe524a3a111a730 | 75546df4b6aeb0f2332ab9341923ad572d37046b | /imgui/imgui.cpp | 7a0954a16e461be24f7ce3ce3cefb4c5cc75ae3f | [] | no_license | maximebl/transforms | d86f81f073a2ba713e4bb89b12a0a664dac18695 | 2c2dac6eb18d737bc5b2dfbc8ddcee1b0acbad47 | refs/heads/master | 2021-05-17T02:10:44.200003 | 2020-12-17T06:09:29 | 2020-12-17T06:09:29 | 250,570,319 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 503,822 | cpp | // dear imgui, v1.76 WIP
// (main code and documentation)
// Help:
// - Read FAQ at http://dearimgui.org/faq
// - Newcomers, read 'Programmer guide' below for notes on how to setup Dear ImGui in your codebase.
// - Call and read ImGui::ShowDemoWindow() in imgui_demo.cpp for demo code. All applications in examples/ are doing that.
// Resources:
// - FAQ http://dearimgui.org/faq
// - Homepage & latest https://github.com/ocornut/imgui
// - Releases & changelog https://github.com/ocornut/imgui/releases
// - Gallery https://github.com/ocornut/imgui/issues/2847 (please post your screenshots/video there!)
// - Glossary https://github.com/ocornut/imgui/wiki/Glossary
// - Wiki https://github.com/ocornut/imgui/wiki
// - Issues & support https://github.com/ocornut/imgui/issues
// Developed by Omar Cornut and every direct or indirect contributors to the GitHub.
// See LICENSE.txt for copyright and licensing details (standard MIT License).
// This library is free but I need your support to sustain development and maintenance.
// Businesses: you can support continued development via invoiced technical support, maintenance and sponsoring contracts. Please reach out to "contact AT dearimgui.org".
// Individuals: you can support continued development via donations. See docs/README or web page.
// It is recommended that you don't modify imgui.cpp! It will become difficult for you to update the library.
// Note that 'ImGui::' being a namespace, you can add functions into the namespace from your own source files, without
// modifying imgui.h or imgui.cpp. You may include imgui_internal.h to access internal data structures, but it doesn't
// come with any guarantee of forward compatibility. Discussing your changes on the GitHub Issue Tracker may lead you
// to a better solution or official support for them.
/*
Index of this file:
DOCUMENTATION
- MISSION STATEMENT
- END-USER GUIDE
- PROGRAMMER GUIDE
- READ FIRST
- HOW TO UPDATE TO A NEWER VERSION OF DEAR IMGUI
- GETTING STARTED WITH INTEGRATING DEAR IMGUI IN YOUR CODE/ENGINE
- HOW A SIMPLE APPLICATION MAY LOOK LIKE (2 variations)
- HOW A SIMPLE RENDERING FUNCTION MAY LOOK LIKE
- USING GAMEPAD/KEYBOARD NAVIGATION CONTROLS
- API BREAKING CHANGES (read me when you update!)
- FREQUENTLY ASKED QUESTIONS (FAQ)
- Read all answers online: https://www.dearimgui.org/faq, or in docs/FAQ.md (with a Markdown viewer)
CODE
(search for "[SECTION]" in the code to find them)
// [SECTION] INCLUDES
// [SECTION] FORWARD DECLARATIONS
// [SECTION] CONTEXT AND MEMORY ALLOCATORS
// [SECTION] USER FACING STRUCTURES (ImGuiStyle, ImGuiIO)
// [SECTION] MISC HELPERS/UTILITIES (Geometry functions)
// [SECTION] MISC HELPERS/UTILITIES (String, Format, Hash functions)
// [SECTION] MISC HELPERS/UTILITIES (File functions)
// [SECTION] MISC HELPERS/UTILITIES (ImText* functions)
// [SECTION] MISC HELPERS/UTILITIES (Color functions)
// [SECTION] ImGuiStorage
// [SECTION] ImGuiTextFilter
// [SECTION] ImGuiTextBuffer
// [SECTION] ImGuiListClipper
// [SECTION] STYLING
// [SECTION] RENDER HELPERS
// [SECTION] MAIN CODE (most of the code! lots of stuff, needs tidying up!)
// [SECTION] ERROR CHECKING
// [SECTION] LAYOUT
// [SECTION] SCROLLING
// [SECTION] TOOLTIPS
// [SECTION] POPUPS
// [SECTION] KEYBOARD/GAMEPAD NAVIGATION
// [SECTION] DRAG AND DROP
// [SECTION] LOGGING/CAPTURING
// [SECTION] SETTINGS
// [SECTION] PLATFORM DEPENDENT HELPERS
// [SECTION] METRICS/DEBUG WINDOW
*/
//-----------------------------------------------------------------------------
// DOCUMENTATION
//-----------------------------------------------------------------------------
/*
MISSION STATEMENT
=================
- Easy to use to create code-driven and data-driven tools.
- Easy to use to create ad hoc short-lived tools and long-lived, more elaborate tools.
- Easy to hack and improve.
- Minimize screen real-estate usage.
- Minimize setup and maintenance.
- Minimize state storage on user side.
- Portable, minimize dependencies, run on target (consoles, phones, etc.).
- Efficient runtime and memory consumption (NB- we do allocate when "growing" content e.g. creating a window,.
opening a tree node for the first time, etc. but a typical frame should not allocate anything).
Designed for developers and content-creators, not the typical end-user! Some of the weaknesses includes:
- Doesn't look fancy, doesn't animate.
- Limited layout features, intricate layouts are typically crafted in code.
END-USER GUIDE
==============
- Double-click on title bar to collapse window.
- Click upper right corner to close a window, available when 'bool* p_open' is passed to ImGui::Begin().
- Click and drag on lower right corner to resize window (double-click to auto fit window to its contents).
- Click and drag on any empty space to move window.
- TAB/SHIFT+TAB to cycle through keyboard editable fields.
- CTRL+Click on a slider or drag box to input value as text.
- Use mouse wheel to scroll.
- Text editor:
- Hold SHIFT or use mouse to select text.
- CTRL+Left/Right to word jump.
- CTRL+Shift+Left/Right to select words.
- CTRL+A our Double-Click to select all.
- CTRL+X,CTRL+C,CTRL+V to use OS clipboard/
- CTRL+Z,CTRL+Y to undo/redo.
- ESCAPE to revert text to its original value.
- You can apply arithmetic operators +,*,/ on numerical values. Use +- to subtract (because - would set a negative value!)
- Controls are automatically adjusted for OSX to match standard OSX text editing operations.
- General Keyboard controls: enable with ImGuiConfigFlags_NavEnableKeyboard.
- General Gamepad controls: enable with ImGuiConfigFlags_NavEnableGamepad. See suggested mappings in imgui.h ImGuiNavInput_ + download PNG/PSD at http://goo.gl/9LgVZW
PROGRAMMER GUIDE
================
READ FIRST
----------
- Remember to read the FAQ (https://www.dearimgui.org/faq)
- Your code creates the UI, if your code doesn't run the UI is gone! The UI can be highly dynamic, there are no construction
or destruction steps, less superfluous data retention on your side, less state duplication, less state synchronization, less bugs.
- Call and read ImGui::ShowDemoWindow() for demo code demonstrating most features.
- The library is designed to be built from sources. Avoid pre-compiled binaries and packaged versions. See imconfig.h to configure your build.
- Dear ImGui is an implementation of the IMGUI paradigm (immediate-mode graphical user interface, a term coined by Casey Muratori).
You can learn about IMGUI principles at http://www.johno.se/book/imgui.html, http://mollyrocket.com/861 & more links docs/README.md.
- Dear ImGui is a "single pass" rasterizing implementation of the IMGUI paradigm, aimed at ease of use and high-performances.
For every application frame your UI code will be called only once. This is in contrast to e.g. Unity's own implementation of an IMGUI,
where the UI code is called multiple times ("multiple passes") from a single entry point. There are pros and cons to both approaches.
- Our origin are on the top-left. In axis aligned bounding boxes, Min = top-left, Max = bottom-right.
- This codebase is also optimized to yield decent performances with typical "Debug" builds settings.
- Please make sure you have asserts enabled (IM_ASSERT redirects to assert() by default, but can be redirected).
If you get an assert, read the messages and comments around the assert.
- C++: this is a very C-ish codebase: we don't rely on C++11, we don't include any C++ headers, and ImGui:: is a namespace.
- C++: ImVec2/ImVec4 do not expose math operators by default, because it is expected that you use your own math types.
See FAQ "How can I use my own math types instead of ImVec2/ImVec4?" for details about setting up imconfig.h for that.
However, imgui_internal.h can optionally export math operators for ImVec2/ImVec4, which we use in this codebase.
- C++: pay attention that ImVector<> manipulates plain-old-data and does not honor construction/destruction (avoid using it in your code!).
HOW TO UPDATE TO A NEWER VERSION OF DEAR IMGUI
----------------------------------------------
- Overwrite all the sources files except for imconfig.h (if you have made modification to your copy of imconfig.h)
- Or maintain your own branch where you have imconfig.h modified.
- Read the "API BREAKING CHANGES" section (below). This is where we list occasional API breaking changes.
If a function/type has been renamed / or marked obsolete, try to fix the name in your code before it is permanently removed
from the public API. If you have a problem with a missing function/symbols, search for its name in the code, there will
likely be a comment about it. Please report any issue to the GitHub page!
- Try to keep your copy of dear imgui reasonably up to date.
GETTING STARTED WITH INTEGRATING DEAR IMGUI IN YOUR CODE/ENGINE
---------------------------------------------------------------
- Run and study the examples and demo in imgui_demo.cpp to get acquainted with the library.
- In the majority of cases you should be able to use unmodified back-ends files available in the examples/ folder.
- Add the Dear ImGui source files to your projects or using your preferred build system.
It is recommended you build and statically link the .cpp files as part of your project and NOT as shared library (DLL).
- You can later customize the imconfig.h file to tweak some compile-time behavior, such as integrating Dear ImGui types with your own maths types.
- When using Dear ImGui, your programming IDE is your friend: follow the declaration of variables, functions and types to find comments about them.
- Dear ImGui never touches or knows about your GPU state. The only function that knows about GPU is the draw function that you provide.
Effectively it means you can create widgets at any time in your code, regardless of considerations of being in "update" vs "render"
phases of your own application. All rendering information are stored into command-lists that you will retrieve after calling ImGui::Render().
- Refer to the bindings and demo applications in the examples/ folder for instruction on how to setup your code.
- If you are running over a standard OS with a common graphics API, you should be able to use unmodified imgui_impl_*** files from the examples/ folder.
HOW A SIMPLE APPLICATION MAY LOOK LIKE
--------------------------------------
EXHIBIT 1: USING THE EXAMPLE BINDINGS (imgui_impl_XXX.cpp files from the examples/ folder).
// Application init: create a dear imgui context, setup some options, load fonts
ImGui::CreateContext();
ImGuiIO& io = ImGui::GetIO();
// TODO: Set optional io.ConfigFlags values, e.g. 'io.ConfigFlags |= ImGuiConfigFlags_NavEnableKeyboard' to enable keyboard controls.
// TODO: Fill optional fields of the io structure later.
// TODO: Load TTF/OTF fonts if you don't want to use the default font.
// Initialize helper Platform and Renderer bindings (here we are using imgui_impl_win32.cpp and imgui_impl_dx11.cpp)
ImGui_ImplWin32_Init(hwnd);
ImGui_ImplDX11_Init(g_pd3dDevice, g_pd3dDeviceContext);
// Application main loop
while (true)
{
// Feed inputs to dear imgui, start new frame
ImGui_ImplDX11_NewFrame();
ImGui_ImplWin32_NewFrame();
ImGui::NewFrame();
// Any application code here
ImGui::Text("Hello, world!");
// Render dear imgui into screen
ImGui::Render();
ImGui_ImplDX11_RenderDrawData(ImGui::GetDrawData());
g_pSwapChain->Present(1, 0);
}
// Shutdown
ImGui_ImplDX11_Shutdown();
ImGui_ImplWin32_Shutdown();
ImGui::DestroyContext();
EXHIBIT 2: IMPLEMENTING CUSTOM BINDING / CUSTOM ENGINE
// Application init: create a dear imgui context, setup some options, load fonts
ImGui::CreateContext();
ImGuiIO& io = ImGui::GetIO();
// TODO: Set optional io.ConfigFlags values, e.g. 'io.ConfigFlags |= ImGuiConfigFlags_NavEnableKeyboard' to enable keyboard controls.
// TODO: Fill optional fields of the io structure later.
// TODO: Load TTF/OTF fonts if you don't want to use the default font.
// Build and load the texture atlas into a texture
// (In the examples/ app this is usually done within the ImGui_ImplXXX_Init() function from one of the demo Renderer)
int width, height;
unsigned char* pixels = NULL;
io.Fonts->GetTexDataAsRGBA32(&pixels, &width, &height);
// At this point you've got the texture data and you need to upload that your your graphic system:
// After we have created the texture, store its pointer/identifier (_in whichever format your engine uses_) in 'io.Fonts->TexID'.
// This will be passed back to your via the renderer. Basically ImTextureID == void*. Read FAQ for details about ImTextureID.
MyTexture* texture = MyEngine::CreateTextureFromMemoryPixels(pixels, width, height, TEXTURE_TYPE_RGBA32)
io.Fonts->TexID = (void*)texture;
// Application main loop
while (true)
{
// Setup low-level inputs, e.g. on Win32: calling GetKeyboardState(), or write to those fields from your Windows message handlers, etc.
// (In the examples/ app this is usually done within the ImGui_ImplXXX_NewFrame() function from one of the demo Platform bindings)
io.DeltaTime = 1.0f/60.0f; // set the time elapsed since the previous frame (in seconds)
io.DisplaySize.x = 1920.0f; // set the current display width
io.DisplaySize.y = 1280.0f; // set the current display height here
io.MousePos = my_mouse_pos; // set the mouse position
io.MouseDown[0] = my_mouse_buttons[0]; // set the mouse button states
io.MouseDown[1] = my_mouse_buttons[1];
// Call NewFrame(), after this point you can use ImGui::* functions anytime
// (So you want to try calling NewFrame() as early as you can in your mainloop to be able to use Dear ImGui everywhere)
ImGui::NewFrame();
// Most of your application code here
ImGui::Text("Hello, world!");
MyGameUpdate(); // may use any Dear ImGui functions, e.g. ImGui::Begin("My window"); ImGui::Text("Hello, world!"); ImGui::End();
MyGameRender(); // may use any Dear ImGui functions as well!
// Render dear imgui, swap buffers
// (You want to try calling EndFrame/Render as late as you can, to be able to use Dear ImGui in your own game rendering code)
ImGui::EndFrame();
ImGui::Render();
ImDrawData* draw_data = ImGui::GetDrawData();
MyImGuiRenderFunction(draw_data);
SwapBuffers();
}
// Shutdown
ImGui::DestroyContext();
HOW A SIMPLE RENDERING FUNCTION MAY LOOK LIKE
---------------------------------------------
void void MyImGuiRenderFunction(ImDrawData* draw_data)
{
// TODO: Setup render state: alpha-blending enabled, no face culling, no depth testing, scissor enabled
// TODO: Setup viewport covering draw_data->DisplayPos to draw_data->DisplayPos + draw_data->DisplaySize
// TODO: Setup orthographic projection matrix cover draw_data->DisplayPos to draw_data->DisplayPos + draw_data->DisplaySize
// TODO: Setup shader: vertex { float2 pos, float2 uv, u32 color }, fragment shader sample color from 1 texture, multiply by vertex color.
for (int n = 0; n < draw_data->CmdListsCount; n++)
{
const ImDrawList* cmd_list = draw_data->CmdLists[n];
const ImDrawVert* vtx_buffer = cmd_list->VtxBuffer.Data; // vertex buffer generated by Dear ImGui
const ImDrawIdx* idx_buffer = cmd_list->IdxBuffer.Data; // index buffer generated by Dear ImGui
for (int cmd_i = 0; cmd_i < cmd_list->CmdBuffer.Size; cmd_i++)
{
const ImDrawCmd* pcmd = &cmd_list->CmdBuffer[cmd_i];
if (pcmd->UserCallback)
{
pcmd->UserCallback(cmd_list, pcmd);
}
else
{
// The texture for the draw call is specified by pcmd->TextureId.
// The vast majority of draw calls will use the Dear ImGui texture atlas, which value you have set yourself during initialization.
MyEngineBindTexture((MyTexture*)pcmd->TextureId);
// We are using scissoring to clip some objects. All low-level graphics API should supports it.
// - If your engine doesn't support scissoring yet, you may ignore this at first. You will get some small glitches
// (some elements visible outside their bounds) but you can fix that once everything else works!
// - Clipping coordinates are provided in imgui coordinates space (from draw_data->DisplayPos to draw_data->DisplayPos + draw_data->DisplaySize)
// In a single viewport application, draw_data->DisplayPos will always be (0,0) and draw_data->DisplaySize will always be == io.DisplaySize.
// However, in the interest of supporting multi-viewport applications in the future (see 'viewport' branch on github),
// always subtract draw_data->DisplayPos from clipping bounds to convert them to your viewport space.
// - Note that pcmd->ClipRect contains Min+Max bounds. Some graphics API may use Min+Max, other may use Min+Size (size being Max-Min)
ImVec2 pos = draw_data->DisplayPos;
MyEngineScissor((int)(pcmd->ClipRect.x - pos.x), (int)(pcmd->ClipRect.y - pos.y), (int)(pcmd->ClipRect.z - pos.x), (int)(pcmd->ClipRect.w - pos.y));
// Render 'pcmd->ElemCount/3' indexed triangles.
// By default the indices ImDrawIdx are 16-bit, you can change them to 32-bit in imconfig.h if your engine doesn't support 16-bit indices.
MyEngineDrawIndexedTriangles(pcmd->ElemCount, sizeof(ImDrawIdx) == 2 ? GL_UNSIGNED_SHORT : GL_UNSIGNED_INT, idx_buffer, vtx_buffer);
}
idx_buffer += pcmd->ElemCount;
}
}
}
- The examples/ folders contains many actual implementation of the pseudo-codes above.
- When calling NewFrame(), the 'io.WantCaptureMouse', 'io.WantCaptureKeyboard' and 'io.WantTextInput' flags are updated.
They tell you if Dear ImGui intends to use your inputs. When a flag is set you want to hide the corresponding inputs from the
rest of your application. In every cases you need to pass on the inputs to Dear ImGui.
- Refer to the FAQ for more information. Amusingly, it is called a FAQ because people frequently run into the same issues!
USING GAMEPAD/KEYBOARD NAVIGATION CONTROLS
------------------------------------------
- The gamepad/keyboard navigation is fairly functional and keeps being improved.
- Gamepad support is particularly useful to use Dear ImGui on a console system (e.g. PS4, Switch, XB1) without a mouse!
- You can ask questions and report issues at https://github.com/ocornut/imgui/issues/787
- The initial focus was to support game controllers, but keyboard is becoming increasingly and decently usable.
- Keyboard:
- Set io.ConfigFlags |= ImGuiConfigFlags_NavEnableKeyboard to enable.
NewFrame() will automatically fill io.NavInputs[] based on your io.KeysDown[] + io.KeyMap[] arrays.
- When keyboard navigation is active (io.NavActive + ImGuiConfigFlags_NavEnableKeyboard), the io.WantCaptureKeyboard flag
will be set. For more advanced uses, you may want to read from:
- io.NavActive: true when a window is focused and it doesn't have the ImGuiWindowFlags_NoNavInputs flag set.
- io.NavVisible: true when the navigation cursor is visible (and usually goes false when mouse is used).
- or query focus information with e.g. IsWindowFocused(ImGuiFocusedFlags_AnyWindow), IsItemFocused() etc. functions.
Please reach out if you think the game vs navigation input sharing could be improved.
- Gamepad:
- Set io.ConfigFlags |= ImGuiConfigFlags_NavEnableGamepad to enable.
- Backend: Set io.BackendFlags |= ImGuiBackendFlags_HasGamepad + fill the io.NavInputs[] fields before calling NewFrame().
Note that io.NavInputs[] is cleared by EndFrame().
- See 'enum ImGuiNavInput_' in imgui.h for a description of inputs. For each entry of io.NavInputs[], set the following values:
0.0f= not held. 1.0f= fully held. Pass intermediate 0.0f..1.0f values for analog triggers/sticks.
- We uses a simple >0.0f test for activation testing, and won't attempt to test for a dead-zone.
Your code will probably need to transform your raw inputs (such as e.g. remapping your 0.2..0.9 raw input range to 0.0..1.0 imgui range, etc.).
- You can download PNG/PSD files depicting the gamepad controls for common controllers at: http://goo.gl/9LgVZW.
- If you need to share inputs between your game and the imgui parts, the easiest approach is to go all-or-nothing, with a buttons combo
to toggle the target. Please reach out if you think the game vs navigation input sharing could be improved.
- Mouse:
- PS4 users: Consider emulating a mouse cursor with DualShock4 touch pad or a spare analog stick as a mouse-emulation fallback.
- Consoles/Tablet/Phone users: Consider using a Synergy 1.x server (on your PC) + uSynergy.c (on your console/tablet/phone app) to share your PC mouse/keyboard.
- On a TV/console system where readability may be lower or mouse inputs may be awkward, you may want to set the ImGuiConfigFlags_NavEnableSetMousePos flag.
Enabling ImGuiConfigFlags_NavEnableSetMousePos + ImGuiBackendFlags_HasSetMousePos instructs dear imgui to move your mouse cursor along with navigation movements.
When enabled, the NewFrame() function may alter 'io.MousePos' and set 'io.WantSetMousePos' to notify you that it wants the mouse cursor to be moved.
When that happens your back-end NEEDS to move the OS or underlying mouse cursor on the next frame. Some of the binding in examples/ do that.
(If you set the NavEnableSetMousePos flag but don't honor 'io.WantSetMousePos' properly, imgui will misbehave as it will see your mouse as moving back and forth!)
(In a setup when you may not have easy control over the mouse cursor, e.g. uSynergy.c doesn't expose moving remote mouse cursor, you may want
to set a boolean to ignore your other external mouse positions until the external source is moved again.)
API BREAKING CHANGES
====================
Occasionally introducing changes that are breaking the API. We try to make the breakage minor and easy to fix.
Below is a change-log of API breaking changes only. If you are using one of the functions listed, expect to have to fix some code.
When you are not sure about a old symbol or function name, try using the Search/Find function of your IDE to look for comments or references in all imgui files.
You can read releases logs https://github.com/ocornut/imgui/releases for more details.
- 2020/01/22 (1.75) - ImDrawList::AddCircle()/AddCircleFilled() functions don't accept negative radius any more.
- 2019/12/17 (1.75) - made Columns() limited to 64 columns by asserting above that limit. While the current code technically supports it, future code may not so we're putting the restriction ahead.
- 2019/12/13 (1.75) - [imgui_internal.h] changed ImRect() default constructor initializes all fields to 0.0f instead of (FLT_MAX,FLT_MAX,-FLT_MAX,-FLT_MAX). If you used ImRect::Add() to create bounding boxes by adding multiple points into it, you may need to fix your initial value.
- 2019/12/08 (1.75) - removed redirecting functions/enums that were marked obsolete in 1.53 (December 2017):
- ShowTestWindow() -> use ShowDemoWindow()
- IsRootWindowFocused() -> use IsWindowFocused(ImGuiFocusedFlags_RootWindow)
- IsRootWindowOrAnyChildFocused() -> use IsWindowFocused(ImGuiFocusedFlags_RootAndChildWindows)
- SetNextWindowContentWidth(w) -> use SetNextWindowContentSize(ImVec2(w, 0.0f)
- GetItemsLineHeightWithSpacing() -> use GetFrameHeightWithSpacing()
- ImGuiCol_ChildWindowBg -> use ImGuiCol_ChildBg
- ImGuiStyleVar_ChildWindowRounding -> use ImGuiStyleVar_ChildRounding
- ImGuiTreeNodeFlags_AllowOverlapMode -> use ImGuiTreeNodeFlags_AllowItemOverlap
- IMGUI_DISABLE_TEST_WINDOWS -> use IMGUI_DISABLE_DEMO_WINDOWS
- 2019/12/08 (1.75) - obsoleted calling ImDrawList::PrimReserve() with a negative count (which was the vaguely documented and rarely if ever used). Instead we added an explicit PrimUnreserve() API.
- 2019/12/06 (1.75) - removed implicit default parameter to IsMouseDragging(int button = 0) to be consistent with other mouse functions (none of the other functions have it).
- 2019/11/21 (1.74) - ImFontAtlas::AddCustomRectRegular() now requires an ID larger than 0x110000 (instead of 0x10000) to conform with supporting Unicode planes 1-16 in a future update. ID below 0x110000 will now assert.
- 2019/11/19 (1.74) - renamed IMGUI_DISABLE_FORMAT_STRING_FUNCTIONS to IMGUI_DISABLE_DEFAULT_FORMAT_FUNCTIONS for consistency.
- 2019/11/19 (1.74) - renamed IMGUI_DISABLE_MATH_FUNCTIONS to IMGUI_DISABLE_DEFAULT_MATH_FUNCTIONS for consistency.
- 2019/10/22 (1.74) - removed redirecting functions/enums that were marked obsolete in 1.52 (October 2017):
- Begin() [old 5 args version] -> use Begin() [3 args], use SetNextWindowSize() SetNextWindowBgAlpha() if needed
- IsRootWindowOrAnyChildHovered() -> use IsWindowHovered(ImGuiHoveredFlags_RootAndChildWindows)
- AlignFirstTextHeightToWidgets() -> use AlignTextToFramePadding()
- SetNextWindowPosCenter() -> use SetNextWindowPos() with a pivot of (0.5f, 0.5f)
- ImFont::Glyph -> use ImFontGlyph
- 2019/10/14 (1.74) - inputs: Fixed a miscalculation in the keyboard/mouse "typematic" repeat delay/rate calculation, used by keys and e.g. repeating mouse buttons as well as the GetKeyPressedAmount() function.
if you were using a non-default value for io.KeyRepeatRate (previous default was 0.250), you can add +io.KeyRepeatDelay to it to compensate for the fix.
The function was triggering on: 0.0 and (delay+rate*N) where (N>=1). Fixed formula responds to (N>=0). Effectively it made io.KeyRepeatRate behave like it was set to (io.KeyRepeatRate + io.KeyRepeatDelay).
If you never altered io.KeyRepeatRate nor used GetKeyPressedAmount() this won't affect you.
- 2019/07/15 (1.72) - removed TreeAdvanceToLabelPos() which is rarely used and only does SetCursorPosX(GetCursorPosX() + GetTreeNodeToLabelSpacing()). Kept redirection function (will obsolete).
- 2019/07/12 (1.72) - renamed ImFontAtlas::CustomRect to ImFontAtlasCustomRect. Kept redirection typedef (will obsolete).
- 2019/06/14 (1.72) - removed redirecting functions/enums names that were marked obsolete in 1.51 (June 2017): ImGuiCol_Column*, ImGuiSetCond_*, IsItemHoveredRect(), IsPosHoveringAnyWindow(), IsMouseHoveringAnyWindow(), IsMouseHoveringWindow(), IMGUI_ONCE_UPON_A_FRAME. Grep this log for details and new names, or see how they were implemented until 1.71.
- 2019/06/07 (1.71) - rendering of child window outer decorations (bg color, border, scrollbars) is now performed as part of the parent window. If you have
overlapping child windows in a same parent, and relied on their relative z-order to be mapped to their submission order, this will affect your rendering.
This optimization is disabled if the parent window has no visual output, because it appears to be the most common situation leading to the creation of overlapping child windows.
Please reach out if you are affected.
- 2019/05/13 (1.71) - renamed SetNextTreeNodeOpen() to SetNextItemOpen(). Kept inline redirection function (will obsolete).
- 2019/05/11 (1.71) - changed io.AddInputCharacter(unsigned short c) signature to io.AddInputCharacter(unsigned int c).
- 2019/04/29 (1.70) - improved ImDrawList thick strokes (>1.0f) preserving correct thickness up to 90 degrees angles (e.g. rectangles). If you have custom rendering using thick lines, they will appear thicker now.
- 2019/04/29 (1.70) - removed GetContentRegionAvailWidth(), use GetContentRegionAvail().x instead. Kept inline redirection function (will obsolete).
- 2019/03/04 (1.69) - renamed GetOverlayDrawList() to GetForegroundDrawList(). Kept redirection function (will obsolete).
- 2019/02/26 (1.69) - renamed ImGuiColorEditFlags_RGB/ImGuiColorEditFlags_HSV/ImGuiColorEditFlags_HEX to ImGuiColorEditFlags_DisplayRGB/ImGuiColorEditFlags_DisplayHSV/ImGuiColorEditFlags_DisplayHex. Kept redirection enums (will obsolete).
- 2019/02/14 (1.68) - made it illegal/assert when io.DisplayTime == 0.0f (with an exception for the first frame). If for some reason your time step calculation gives you a zero value, replace it with a dummy small value!
- 2019/02/01 (1.68) - removed io.DisplayVisibleMin/DisplayVisibleMax (which were marked obsolete and removed from viewport/docking branch already).
- 2019/01/06 (1.67) - renamed io.InputCharacters[], marked internal as was always intended. Please don't access directly, and use AddInputCharacter() instead!
- 2019/01/06 (1.67) - renamed ImFontAtlas::GlyphRangesBuilder to ImFontGlyphRangesBuilder. Kept redirection typedef (will obsolete).
- 2018/12/20 (1.67) - made it illegal to call Begin("") with an empty string. This somehow half-worked before but had various undesirable side-effects.
- 2018/12/10 (1.67) - renamed io.ConfigResizeWindowsFromEdges to io.ConfigWindowsResizeFromEdges as we are doing a large pass on configuration flags.
- 2018/10/12 (1.66) - renamed misc/stl/imgui_stl.* to misc/cpp/imgui_stdlib.* in prevision for other C++ helper files.
- 2018/09/28 (1.66) - renamed SetScrollHere() to SetScrollHereY(). Kept redirection function (will obsolete).
- 2018/09/06 (1.65) - renamed stb_truetype.h to imstb_truetype.h, stb_textedit.h to imstb_textedit.h, and stb_rect_pack.h to imstb_rectpack.h.
If you were conveniently using the imgui copy of those STB headers in your project you will have to update your include paths.
- 2018/09/05 (1.65) - renamed io.OptCursorBlink/io.ConfigCursorBlink to io.ConfigInputTextCursorBlink. (#1427)
- 2018/08/31 (1.64) - added imgui_widgets.cpp file, extracted and moved widgets code out of imgui.cpp into imgui_widgets.cpp. Re-ordered some of the code remaining in imgui.cpp.
NONE OF THE FUNCTIONS HAVE CHANGED. THE CODE IS SEMANTICALLY 100% IDENTICAL, BUT _EVERY_ FUNCTION HAS BEEN MOVED.
Because of this, any local modifications to imgui.cpp will likely conflict when you update. Read docs/CHANGELOG.txt for suggestions.
- 2018/08/22 (1.63) - renamed IsItemDeactivatedAfterChange() to IsItemDeactivatedAfterEdit() for consistency with new IsItemEdited() API. Kept redirection function (will obsolete soonish as IsItemDeactivatedAfterChange() is very recent).
- 2018/08/21 (1.63) - renamed ImGuiTextEditCallback to ImGuiInputTextCallback, ImGuiTextEditCallbackData to ImGuiInputTextCallbackData for consistency. Kept redirection types (will obsolete).
- 2018/08/21 (1.63) - removed ImGuiInputTextCallbackData::ReadOnly since it is a duplication of (ImGuiInputTextCallbackData::Flags & ImGuiInputTextFlags_ReadOnly).
- 2018/08/01 (1.63) - removed per-window ImGuiWindowFlags_ResizeFromAnySide beta flag in favor of a global io.ConfigResizeWindowsFromEdges [update 1.67 renamed to ConfigWindowsResizeFromEdges] to enable the feature.
- 2018/08/01 (1.63) - renamed io.OptCursorBlink to io.ConfigCursorBlink [-> io.ConfigInputTextCursorBlink in 1.65], io.OptMacOSXBehaviors to ConfigMacOSXBehaviors for consistency.
- 2018/07/22 (1.63) - changed ImGui::GetTime() return value from float to double to avoid accumulating floating point imprecisions over time.
- 2018/07/08 (1.63) - style: renamed ImGuiCol_ModalWindowDarkening to ImGuiCol_ModalWindowDimBg for consistency with other features. Kept redirection enum (will obsolete).
- 2018/06/08 (1.62) - examples: the imgui_impl_xxx files have been split to separate platform (Win32, Glfw, SDL2, etc.) from renderer (DX11, OpenGL, Vulkan, etc.).
old bindings will still work as is, however prefer using the separated bindings as they will be updated to support multi-viewports.
when adopting new bindings follow the main.cpp code of your preferred examples/ folder to know which functions to call.
in particular, note that old bindings called ImGui::NewFrame() at the end of their ImGui_ImplXXXX_NewFrame() function.
- 2018/06/06 (1.62) - renamed GetGlyphRangesChinese() to GetGlyphRangesChineseFull() to distinguish other variants and discourage using the full set.
- 2018/06/06 (1.62) - TreeNodeEx()/TreeNodeBehavior(): the ImGuiTreeNodeFlags_CollapsingHeader helper now include the ImGuiTreeNodeFlags_NoTreePushOnOpen flag. See Changelog for details.
- 2018/05/03 (1.61) - DragInt(): the default compile-time format string has been changed from "%.0f" to "%d", as we are not using integers internally any more.
If you used DragInt() with custom format strings, make sure you change them to use %d or an integer-compatible format.
To honor backward-compatibility, the DragInt() code will currently parse and modify format strings to replace %*f with %d, giving time to users to upgrade their code.
If you have IMGUI_DISABLE_OBSOLETE_FUNCTIONS enabled, the code will instead assert! You may run a reg-exp search on your codebase for e.g. "DragInt.*%f" to help you find them.
- 2018/04/28 (1.61) - obsoleted InputFloat() functions taking an optional "int decimal_precision" in favor of an equivalent and more flexible "const char* format",
consistent with other functions. Kept redirection functions (will obsolete).
- 2018/04/09 (1.61) - IM_DELETE() helper function added in 1.60 doesn't clear the input _pointer_ reference, more consistent with expectation and allows passing r-value.
- 2018/03/20 (1.60) - renamed io.WantMoveMouse to io.WantSetMousePos for consistency and ease of understanding (was added in 1.52, _not_ used by core and only honored by some binding ahead of merging the Nav branch).
- 2018/03/12 (1.60) - removed ImGuiCol_CloseButton, ImGuiCol_CloseButtonActive, ImGuiCol_CloseButtonHovered as the closing cross uses regular button colors now.
- 2018/03/08 (1.60) - changed ImFont::DisplayOffset.y to default to 0 instead of +1. Fixed rounding of Ascent/Descent to match TrueType renderer. If you were adding or subtracting to ImFont::DisplayOffset check if your fonts are correctly aligned vertically.
- 2018/03/03 (1.60) - renamed ImGuiStyleVar_Count_ to ImGuiStyleVar_COUNT and ImGuiMouseCursor_Count_ to ImGuiMouseCursor_COUNT for consistency with other public enums.
- 2018/02/18 (1.60) - BeginDragDropSource(): temporarily removed the optional mouse_button=0 parameter because it is not really usable in many situations at the moment.
- 2018/02/16 (1.60) - obsoleted the io.RenderDrawListsFn callback, you can call your graphics engine render function after ImGui::Render(). Use ImGui::GetDrawData() to retrieve the ImDrawData* to display.
- 2018/02/07 (1.60) - reorganized context handling to be more explicit,
- YOU NOW NEED TO CALL ImGui::CreateContext() AT THE BEGINNING OF YOUR APP, AND CALL ImGui::DestroyContext() AT THE END.
- removed Shutdown() function, as DestroyContext() serve this purpose.
- you may pass a ImFontAtlas* pointer to CreateContext() to share a font atlas between contexts. Otherwise CreateContext() will create its own font atlas instance.
- removed allocator parameters from CreateContext(), they are now setup with SetAllocatorFunctions(), and shared by all contexts.
- removed the default global context and font atlas instance, which were confusing for users of DLL reloading and users of multiple contexts.
- 2018/01/31 (1.60) - moved sample TTF files from extra_fonts/ to misc/fonts/. If you loaded files directly from the imgui repo you may need to update your paths.
- 2018/01/11 (1.60) - obsoleted IsAnyWindowHovered() in favor of IsWindowHovered(ImGuiHoveredFlags_AnyWindow). Kept redirection function (will obsolete).
- 2018/01/11 (1.60) - obsoleted IsAnyWindowFocused() in favor of IsWindowFocused(ImGuiFocusedFlags_AnyWindow). Kept redirection function (will obsolete).
- 2018/01/03 (1.60) - renamed ImGuiSizeConstraintCallback to ImGuiSizeCallback, ImGuiSizeConstraintCallbackData to ImGuiSizeCallbackData.
- 2017/12/29 (1.60) - removed CalcItemRectClosestPoint() which was weird and not really used by anyone except demo code. If you need it it's easy to replicate on your side.
- 2017/12/24 (1.53) - renamed the emblematic ShowTestWindow() function to ShowDemoWindow(). Kept redirection function (will obsolete).
- 2017/12/21 (1.53) - ImDrawList: renamed style.AntiAliasedShapes to style.AntiAliasedFill for consistency and as a way to explicitly break code that manipulate those flag at runtime. You can now manipulate ImDrawList::Flags
- 2017/12/21 (1.53) - ImDrawList: removed 'bool anti_aliased = true' final parameter of ImDrawList::AddPolyline() and ImDrawList::AddConvexPolyFilled(). Prefer manipulating ImDrawList::Flags if you need to toggle them during the frame.
- 2017/12/14 (1.53) - using the ImGuiWindowFlags_NoScrollWithMouse flag on a child window forwards the mouse wheel event to the parent window, unless either ImGuiWindowFlags_NoInputs or ImGuiWindowFlags_NoScrollbar are also set.
- 2017/12/13 (1.53) - renamed GetItemsLineHeightWithSpacing() to GetFrameHeightWithSpacing(). Kept redirection function (will obsolete).
- 2017/12/13 (1.53) - obsoleted IsRootWindowFocused() in favor of using IsWindowFocused(ImGuiFocusedFlags_RootWindow). Kept redirection function (will obsolete).
- obsoleted IsRootWindowOrAnyChildFocused() in favor of using IsWindowFocused(ImGuiFocusedFlags_RootAndChildWindows). Kept redirection function (will obsolete).
- 2017/12/12 (1.53) - renamed ImGuiTreeNodeFlags_AllowOverlapMode to ImGuiTreeNodeFlags_AllowItemOverlap. Kept redirection enum (will obsolete).
- 2017/12/10 (1.53) - removed SetNextWindowContentWidth(), prefer using SetNextWindowContentSize(). Kept redirection function (will obsolete).
- 2017/11/27 (1.53) - renamed ImGuiTextBuffer::append() helper to appendf(), appendv() to appendfv(). If you copied the 'Log' demo in your code, it uses appendv() so that needs to be renamed.
- 2017/11/18 (1.53) - Style, Begin: removed ImGuiWindowFlags_ShowBorders window flag. Borders are now fully set up in the ImGuiStyle structure (see e.g. style.FrameBorderSize, style.WindowBorderSize). Use ImGui::ShowStyleEditor() to look them up.
Please note that the style system will keep evolving (hopefully stabilizing in Q1 2018), and so custom styles will probably subtly break over time. It is recommended you use the StyleColorsClassic(), StyleColorsDark(), StyleColorsLight() functions.
- 2017/11/18 (1.53) - Style: removed ImGuiCol_ComboBg in favor of combo boxes using ImGuiCol_PopupBg for consistency.
- 2017/11/18 (1.53) - Style: renamed ImGuiCol_ChildWindowBg to ImGuiCol_ChildBg.
- 2017/11/18 (1.53) - Style: renamed style.ChildWindowRounding to style.ChildRounding, ImGuiStyleVar_ChildWindowRounding to ImGuiStyleVar_ChildRounding.
- 2017/11/02 (1.53) - obsoleted IsRootWindowOrAnyChildHovered() in favor of using IsWindowHovered(ImGuiHoveredFlags_RootAndChildWindows);
- 2017/10/24 (1.52) - renamed IMGUI_DISABLE_WIN32_DEFAULT_CLIPBOARD_FUNCS/IMGUI_DISABLE_WIN32_DEFAULT_IME_FUNCS to IMGUI_DISABLE_WIN32_DEFAULT_CLIPBOARD_FUNCTIONS/IMGUI_DISABLE_WIN32_DEFAULT_IME_FUNCTIONS for consistency.
- 2017/10/20 (1.52) - changed IsWindowHovered() default parameters behavior to return false if an item is active in another window (e.g. click-dragging item from another window to this window). You can use the newly introduced IsWindowHovered() flags to requests this specific behavior if you need it.
- 2017/10/20 (1.52) - marked IsItemHoveredRect()/IsMouseHoveringWindow() as obsolete, in favor of using the newly introduced flags for IsItemHovered() and IsWindowHovered(). See https://github.com/ocornut/imgui/issues/1382 for details.
removed the IsItemRectHovered()/IsWindowRectHovered() names introduced in 1.51 since they were merely more consistent names for the two functions we are now obsoleting.
IsItemHoveredRect() --> IsItemHovered(ImGuiHoveredFlags_RectOnly)
IsMouseHoveringAnyWindow() --> IsWindowHovered(ImGuiHoveredFlags_AnyWindow)
IsMouseHoveringWindow() --> IsWindowHovered(ImGuiHoveredFlags_AllowWhenBlockedByPopup | ImGuiHoveredFlags_AllowWhenBlockedByActiveItem) [weird, old behavior]
- 2017/10/17 (1.52) - marked the old 5-parameters version of Begin() as obsolete (still available). Use SetNextWindowSize()+Begin() instead!
- 2017/10/11 (1.52) - renamed AlignFirstTextHeightToWidgets() to AlignTextToFramePadding(). Kept inline redirection function (will obsolete).
- 2017/09/26 (1.52) - renamed ImFont::Glyph to ImFontGlyph. Kept redirection typedef (will obsolete).
- 2017/09/25 (1.52) - removed SetNextWindowPosCenter() because SetNextWindowPos() now has the optional pivot information to do the same and more. Kept redirection function (will obsolete).
- 2017/08/25 (1.52) - io.MousePos needs to be set to ImVec2(-FLT_MAX,-FLT_MAX) when mouse is unavailable/missing. Previously ImVec2(-1,-1) was enough but we now accept negative mouse coordinates. In your binding if you need to support unavailable mouse, make sure to replace "io.MousePos = ImVec2(-1,-1)" with "io.MousePos = ImVec2(-FLT_MAX,-FLT_MAX)".
- 2017/08/22 (1.51) - renamed IsItemHoveredRect() to IsItemRectHovered(). Kept inline redirection function (will obsolete). -> (1.52) use IsItemHovered(ImGuiHoveredFlags_RectOnly)!
- renamed IsMouseHoveringAnyWindow() to IsAnyWindowHovered() for consistency. Kept inline redirection function (will obsolete).
- renamed IsMouseHoveringWindow() to IsWindowRectHovered() for consistency. Kept inline redirection function (will obsolete).
- 2017/08/20 (1.51) - renamed GetStyleColName() to GetStyleColorName() for consistency.
- 2017/08/20 (1.51) - added PushStyleColor(ImGuiCol idx, ImU32 col) overload, which _might_ cause an "ambiguous call" compilation error if you are using ImColor() with implicit cast. Cast to ImU32 or ImVec4 explicily to fix.
- 2017/08/15 (1.51) - marked the weird IMGUI_ONCE_UPON_A_FRAME helper macro as obsolete. prefer using the more explicit ImGuiOnceUponAFrame type.
- 2017/08/15 (1.51) - changed parameter order for BeginPopupContextWindow() from (const char*,int buttons,bool also_over_items) to (const char*,int buttons,bool also_over_items). Note that most calls relied on default parameters completely.
- 2017/08/13 (1.51) - renamed ImGuiCol_Column to ImGuiCol_Separator, ImGuiCol_ColumnHovered to ImGuiCol_SeparatorHovered, ImGuiCol_ColumnActive to ImGuiCol_SeparatorActive. Kept redirection enums (will obsolete).
- 2017/08/11 (1.51) - renamed ImGuiSetCond_Always to ImGuiCond_Always, ImGuiSetCond_Once to ImGuiCond_Once, ImGuiSetCond_FirstUseEver to ImGuiCond_FirstUseEver, ImGuiSetCond_Appearing to ImGuiCond_Appearing. Kept redirection enums (will obsolete).
- 2017/08/09 (1.51) - removed ValueColor() helpers, they are equivalent to calling Text(label) + SameLine() + ColorButton().
- 2017/08/08 (1.51) - removed ColorEditMode() and ImGuiColorEditMode in favor of ImGuiColorEditFlags and parameters to the various Color*() functions. The SetColorEditOptions() allows to initialize default but the user can still change them with right-click context menu.
- changed prototype of 'ColorEdit4(const char* label, float col[4], bool show_alpha = true)' to 'ColorEdit4(const char* label, float col[4], ImGuiColorEditFlags flags = 0)', where passing flags = 0x01 is a safe no-op (hello dodgy backward compatibility!). - check and run the demo window, under "Color/Picker Widgets", to understand the various new options.
- changed prototype of rarely used 'ColorButton(ImVec4 col, bool small_height = false, bool outline_border = true)' to 'ColorButton(const char* desc_id, ImVec4 col, ImGuiColorEditFlags flags = 0, ImVec2 size = ImVec2(0,0))'
- 2017/07/20 (1.51) - removed IsPosHoveringAnyWindow(ImVec2), which was partly broken and misleading. ASSERT + redirect user to io.WantCaptureMouse
- 2017/05/26 (1.50) - removed ImFontConfig::MergeGlyphCenterV in favor of a more multipurpose ImFontConfig::GlyphOffset.
- 2017/05/01 (1.50) - renamed ImDrawList::PathFill() (rarely used directly) to ImDrawList::PathFillConvex() for clarity.
- 2016/11/06 (1.50) - BeginChild(const char*) now applies the stack id to the provided label, consistently with other functions as it should always have been. It shouldn't affect you unless (extremely unlikely) you were appending multiple times to a same child from different locations of the stack id. If that's the case, generate an id with GetId() and use it instead of passing string to BeginChild().
- 2016/10/15 (1.50) - avoid 'void* user_data' parameter to io.SetClipboardTextFn/io.GetClipboardTextFn pointers. We pass io.ClipboardUserData to it.
- 2016/09/25 (1.50) - style.WindowTitleAlign is now a ImVec2 (ImGuiAlign enum was removed). set to (0.5f,0.5f) for horizontal+vertical centering, (0.0f,0.0f) for upper-left, etc.
- 2016/07/30 (1.50) - SameLine(x) with x>0.0f is now relative to left of column/group if any, and not always to left of window. This was sort of always the intent and hopefully breakage should be minimal.
- 2016/05/12 (1.49) - title bar (using ImGuiCol_TitleBg/ImGuiCol_TitleBgActive colors) isn't rendered over a window background (ImGuiCol_WindowBg color) anymore.
If your TitleBg/TitleBgActive alpha was 1.0f or you are using the default theme it will not affect you, otherwise if <1.0f you need tweak your custom theme to readjust for the fact that we don't draw a WindowBg background behind the title bar.
This helper function will convert an old TitleBg/TitleBgActive color into a new one with the same visual output, given the OLD color and the OLD WindowBg color:
ImVec4 ConvertTitleBgCol(const ImVec4& win_bg_col, const ImVec4& title_bg_col) { float new_a = 1.0f - ((1.0f - win_bg_col.w) * (1.0f - title_bg_col.w)), k = title_bg_col.w / new_a; return ImVec4((win_bg_col.x * win_bg_col.w + title_bg_col.x) * k, (win_bg_col.y * win_bg_col.w + title_bg_col.y) * k, (win_bg_col.z * win_bg_col.w + title_bg_col.z) * k, new_a); }
If this is confusing, pick the RGB value from title bar from an old screenshot and apply this as TitleBg/TitleBgActive. Or you may just create TitleBgActive from a tweaked TitleBg color.
- 2016/05/07 (1.49) - removed confusing set of GetInternalState(), GetInternalStateSize(), SetInternalState() functions. Now using CreateContext(), DestroyContext(), GetCurrentContext(), SetCurrentContext().
- 2016/05/02 (1.49) - renamed SetNextTreeNodeOpened() to SetNextTreeNodeOpen(), no redirection.
- 2016/05/01 (1.49) - obsoleted old signature of CollapsingHeader(const char* label, const char* str_id = NULL, bool display_frame = true, bool default_open = false) as extra parameters were badly designed and rarely used. You can replace the "default_open = true" flag in new API with CollapsingHeader(label, ImGuiTreeNodeFlags_DefaultOpen).
- 2016/04/26 (1.49) - changed ImDrawList::PushClipRect(ImVec4 rect) to ImDrawList::PushClipRect(Imvec2 min,ImVec2 max,bool intersect_with_current_clip_rect=false). Note that higher-level ImGui::PushClipRect() is preferable because it will clip at logic/widget level, whereas ImDrawList::PushClipRect() only affect your renderer.
- 2016/04/03 (1.48) - removed style.WindowFillAlphaDefault setting which was redundant. Bake default BG alpha inside style.Colors[ImGuiCol_WindowBg] and all other Bg color values. (ref github issue #337).
- 2016/04/03 (1.48) - renamed ImGuiCol_TooltipBg to ImGuiCol_PopupBg, used by popups/menus and tooltips. popups/menus were previously using ImGuiCol_WindowBg. (ref github issue #337)
- 2016/03/21 (1.48) - renamed GetWindowFont() to GetFont(), GetWindowFontSize() to GetFontSize(). Kept inline redirection function (will obsolete).
- 2016/03/02 (1.48) - InputText() completion/history/always callbacks: if you modify the text buffer manually (without using DeleteChars()/InsertChars() helper) you need to maintain the BufTextLen field. added an assert.
- 2016/01/23 (1.48) - fixed not honoring exact width passed to PushItemWidth(), previously it would add extra FramePadding.x*2 over that width. if you had manual pixel-perfect alignment in place it might affect you.
- 2015/12/27 (1.48) - fixed ImDrawList::AddRect() which used to render a rectangle 1 px too large on each axis.
- 2015/12/04 (1.47) - renamed Color() helpers to ValueColor() - dangerously named, rarely used and probably to be made obsolete.
- 2015/08/29 (1.45) - with the addition of horizontal scrollbar we made various fixes to inconsistencies with dealing with cursor position.
GetCursorPos()/SetCursorPos() functions now include the scrolled amount. It shouldn't affect the majority of users, but take note that SetCursorPosX(100.0f) puts you at +100 from the starting x position which may include scrolling, not at +100 from the window left side.
GetContentRegionMax()/GetWindowContentRegionMin()/GetWindowContentRegionMax() functions allow include the scrolled amount. Typically those were used in cases where no scrolling would happen so it may not be a problem, but watch out!
- 2015/08/29 (1.45) - renamed style.ScrollbarWidth to style.ScrollbarSize
- 2015/08/05 (1.44) - split imgui.cpp into extra files: imgui_demo.cpp imgui_draw.cpp imgui_internal.h that you need to add to your project.
- 2015/07/18 (1.44) - fixed angles in ImDrawList::PathArcTo(), PathArcToFast() (introduced in 1.43) being off by an extra PI for no justifiable reason
- 2015/07/14 (1.43) - add new ImFontAtlas::AddFont() API. For the old AddFont***, moved the 'font_no' parameter of ImFontAtlas::AddFont** functions to the ImFontConfig structure.
you need to render your textured triangles with bilinear filtering to benefit from sub-pixel positioning of text.
- 2015/07/08 (1.43) - switched rendering data to use indexed rendering. this is saving a fair amount of CPU/GPU and enables us to get anti-aliasing for a marginal cost.
this necessary change will break your rendering function! the fix should be very easy. sorry for that :(
- if you are using a vanilla copy of one of the imgui_impl_XXXX.cpp provided in the example, you just need to update your copy and you can ignore the rest.
- the signature of the io.RenderDrawListsFn handler has changed!
old: ImGui_XXXX_RenderDrawLists(ImDrawList** const cmd_lists, int cmd_lists_count)
new: ImGui_XXXX_RenderDrawLists(ImDrawData* draw_data).
parameters: 'cmd_lists' becomes 'draw_data->CmdLists', 'cmd_lists_count' becomes 'draw_data->CmdListsCount'
ImDrawList: 'commands' becomes 'CmdBuffer', 'vtx_buffer' becomes 'VtxBuffer', 'IdxBuffer' is new.
ImDrawCmd: 'vtx_count' becomes 'ElemCount', 'clip_rect' becomes 'ClipRect', 'user_callback' becomes 'UserCallback', 'texture_id' becomes 'TextureId'.
- each ImDrawList now contains both a vertex buffer and an index buffer. For each command, render ElemCount/3 triangles using indices from the index buffer.
- if you REALLY cannot render indexed primitives, you can call the draw_data->DeIndexAllBuffers() method to de-index the buffers. This is slow and a waste of CPU/GPU. Prefer using indexed rendering!
- refer to code in the examples/ folder or ask on the GitHub if you are unsure of how to upgrade. please upgrade!
- 2015/07/10 (1.43) - changed SameLine() parameters from int to float.
- 2015/07/02 (1.42) - renamed SetScrollPosHere() to SetScrollFromCursorPos(). Kept inline redirection function (will obsolete).
- 2015/07/02 (1.42) - renamed GetScrollPosY() to GetScrollY(). Necessary to reduce confusion along with other scrolling functions, because positions (e.g. cursor position) are not equivalent to scrolling amount.
- 2015/06/14 (1.41) - changed ImageButton() default bg_col parameter from (0,0,0,1) (black) to (0,0,0,0) (transparent) - makes a difference when texture have transparence
- 2015/06/14 (1.41) - changed Selectable() API from (label, selected, size) to (label, selected, flags, size). Size override should have been rarely be used. Sorry!
- 2015/05/31 (1.40) - renamed GetWindowCollapsed() to IsWindowCollapsed() for consistency. Kept inline redirection function (will obsolete).
- 2015/05/31 (1.40) - renamed IsRectClipped() to IsRectVisible() for consistency. Note that return value is opposite! Kept inline redirection function (will obsolete).
- 2015/05/27 (1.40) - removed the third 'repeat_if_held' parameter from Button() - sorry! it was rarely used and inconsistent. Use PushButtonRepeat(true) / PopButtonRepeat() to enable repeat on desired buttons.
- 2015/05/11 (1.40) - changed BeginPopup() API, takes a string identifier instead of a bool. ImGui needs to manage the open/closed state of popups. Call OpenPopup() to actually set the "open" state of a popup. BeginPopup() returns true if the popup is opened.
- 2015/05/03 (1.40) - removed style.AutoFitPadding, using style.WindowPadding makes more sense (the default values were already the same).
- 2015/04/13 (1.38) - renamed IsClipped() to IsRectClipped(). Kept inline redirection function until 1.50.
- 2015/04/09 (1.38) - renamed ImDrawList::AddArc() to ImDrawList::AddArcFast() for compatibility with future API
- 2015/04/03 (1.38) - removed ImGuiCol_CheckHovered, ImGuiCol_CheckActive, replaced with the more general ImGuiCol_FrameBgHovered, ImGuiCol_FrameBgActive.
- 2014/04/03 (1.38) - removed support for passing -FLT_MAX..+FLT_MAX as the range for a SliderFloat(). Use DragFloat() or Inputfloat() instead.
- 2015/03/17 (1.36) - renamed GetItemBoxMin()/GetItemBoxMax()/IsMouseHoveringBox() to GetItemRectMin()/GetItemRectMax()/IsMouseHoveringRect(). Kept inline redirection function until 1.50.
- 2015/03/15 (1.36) - renamed style.TreeNodeSpacing to style.IndentSpacing, ImGuiStyleVar_TreeNodeSpacing to ImGuiStyleVar_IndentSpacing
- 2015/03/13 (1.36) - renamed GetWindowIsFocused() to IsWindowFocused(). Kept inline redirection function until 1.50.
- 2015/03/08 (1.35) - renamed style.ScrollBarWidth to style.ScrollbarWidth (casing)
- 2015/02/27 (1.34) - renamed OpenNextNode(bool) to SetNextTreeNodeOpened(bool, ImGuiSetCond). Kept inline redirection function until 1.50.
- 2015/02/27 (1.34) - renamed ImGuiSetCondition_*** to ImGuiSetCond_***, and _FirstUseThisSession becomes _Once.
- 2015/02/11 (1.32) - changed text input callback ImGuiTextEditCallback return type from void-->int. reserved for future use, return 0 for now.
- 2015/02/10 (1.32) - renamed GetItemWidth() to CalcItemWidth() to clarify its evolving behavior
- 2015/02/08 (1.31) - renamed GetTextLineSpacing() to GetTextLineHeightWithSpacing()
- 2015/02/01 (1.31) - removed IO.MemReallocFn (unused)
- 2015/01/19 (1.30) - renamed ImGuiStorage::GetIntPtr()/GetFloatPtr() to GetIntRef()/GetIntRef() because Ptr was conflicting with actual pointer storage functions.
- 2015/01/11 (1.30) - big font/image API change! now loads TTF file. allow for multiple fonts. no need for a PNG loader.
- 2015/01/11 (1.30) - removed GetDefaultFontData(). uses io.Fonts->GetTextureData*() API to retrieve uncompressed pixels.
- old: const void* png_data; unsigned int png_size; ImGui::GetDefaultFontData(NULL, NULL, &png_data, &png_size); [..Upload texture to GPU..];
- new: unsigned char* pixels; int width, height; io.Fonts->GetTexDataAsRGBA32(&pixels, &width, &height); [..Upload texture to GPU..]; io.Fonts->TexId = YourTexIdentifier;
you now have more flexibility to load multiple TTF fonts and manage the texture buffer for internal needs. It is now recommended that you sample the font texture with bilinear interpolation.
- 2015/01/11 (1.30) - added texture identifier in ImDrawCmd passed to your render function (we can now render images). make sure to set io.Fonts->TexID.
- 2015/01/11 (1.30) - removed IO.PixelCenterOffset (unnecessary, can be handled in user projection matrix)
- 2015/01/11 (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)
================================
Read all answers online: https://www.dearimgui.org/faq, or in docs/FAQ.md (with a Markdown viewer)
Some answers are copied down here to facilitate searching in code.
Q&A: Basics
===========
Q: Where is the documentation?
A: This library is poorly documented at the moment and expects of the user to be acquainted with C/C++.
- Run the examples/ and explore them.
- See demo code in imgui_demo.cpp and particularly the ImGui::ShowDemoWindow() function.
- The demo covers most features of Dear ImGui, so you can read the code and see its output.
- See documentation and comments at the top of imgui.cpp + effectively imgui.h.
- Dozens of standalone example applications using e.g. OpenGL/DirectX are provided in the
examples/ folder to explain how to integrate Dear ImGui with your own engine/application.
- The Wiki (https://github.com/ocornut/imgui/wiki) has many resources and links.
- The Glossary (https://github.com/ocornut/imgui/wiki/Glossary) page also may be useful.
- Your programming IDE is your friend, find the type or function declaration to find comments
associated to it.
Q: What is this library called?
Q: Which version should I get?
>> This library is called "Dear ImGui", please don't call it "ImGui" :)
>> See https://www.dearimgui.org/faq
Q&A: Integration
================
Q: How can I tell whether to dispatch mouse/keyboard to Dear ImGui or to my application?
A: You should read the 'io.WantCaptureMouse', 'io.WantCaptureKeyboard' and 'io.WantTextInput' flags!
>> See https://www.dearimgui.org/faq for fully detailed answer. You really want to read this.
Q. How can I enable keyboard controls?
Q: How can I use this without a mouse, without a keyboard or without a screen? (gamepad, input share, remote display)
Q: I integrated Dear ImGui in my engine and the text or lines are blurry..
Q: I integrated Dear ImGui in my engine and some elements are clipping or disappearing when I move windows around..
>> See https://www.dearimgui.org/faq
Q&A: Usage
----------
Q: Why are multiple widgets reacting when I interact with a single one?
Q: How can I have multiple widgets with the same label or with an empty label?
A: A primer on labels and the ID Stack...
Dear ImGui internally need to uniquely identify UI elements.
Elements that are typically not clickable (such as calls to the Text functions) don't need an ID.
Interactive widgets (such as calls to Button buttons) need a unique ID.
Unique ID are used internally to track active widgets and occasionally associate state to widgets.
Unique ID are implicitly built from the hash of multiple elements that identify the "path" to the UI element.
- Unique ID are often derived from a string label:
Button("OK"); // Label = "OK", ID = hash of (..., "OK")
Button("Cancel"); // Label = "Cancel", ID = hash of (..., "Cancel")
- ID are uniquely scoped within windows, tree nodes, etc. which all pushes to the ID stack. Having
two buttons labeled "OK" in different windows or different tree locations is fine.
We used "..." above to signify whatever was already pushed to the ID stack previously:
Begin("MyWindow");
Button("OK"); // Label = "OK", ID = hash of ("MyWindow", "OK")
End();
Begin("MyOtherWindow");
Button("OK"); // Label = "OK", ID = hash of ("MyOtherWindow", "OK")
End();
- If you have a same ID twice in the same location, you'll have a conflict:
Button("OK");
Button("OK"); // ID collision! Interacting with either button will trigger the first one.
Fear not! this is easy to solve and there are many ways to solve it!
- Solving ID conflict in a simple/local context:
When passing a label you can optionally specify extra ID information within string itself.
Use "##" to pass a complement to the ID that won't be visible to the end-user.
This helps solving the simple collision cases when you know e.g. at compilation time which items
are going to be created:
Begin("MyWindow");
Button("Play"); // Label = "Play", ID = hash of ("MyWindow", "Play")
Button("Play##foo1"); // Label = "Play", ID = hash of ("MyWindow", "Play##foo1") // Different from above
Button("Play##foo2"); // Label = "Play", ID = hash of ("MyWindow", "Play##foo2") // Different from above
End();
- If you want to completely hide the label, but still need an ID:
Checkbox("##On", &b); // Label = "", ID = hash of (..., "##On") // No visible label, just a checkbox!
- Occasionally/rarely you might want change a label while preserving a constant ID. This allows
you to animate labels. For example you may want to include varying information in a window title bar,
but windows are uniquely identified by their ID. Use "###" to pass a label that isn't part of ID:
Button("Hello###ID"); // Label = "Hello", ID = hash of (..., "###ID")
Button("World###ID"); // Label = "World", ID = hash of (..., "###ID") // Same as above, even though the label looks different
sprintf(buf, "My game (%f FPS)###MyGame", fps);
Begin(buf); // Variable title, ID = hash of "MyGame"
- Solving ID conflict in a more general manner:
Use PushID() / PopID() to create scopes and manipulate the ID stack, as to avoid ID conflicts
within the same window. This is the most convenient way of distinguishing ID when iterating and
creating many UI elements programmatically.
You can push a pointer, a string or an integer value into the ID stack.
Remember that ID are formed from the concatenation of _everything_ pushed into the ID stack.
At each level of the stack we store the seed used for items at this level of the ID stack.
Begin("Window");
for (int i = 0; i < 100; i++)
{
PushID(i); // Push i to the id tack
Button("Click"); // Label = "Click", ID = hash of ("Window", i, "Click")
PopID();
}
for (int i = 0; i < 100; i++)
{
MyObject* obj = Objects[i];
PushID(obj);
Button("Click"); // Label = "Click", ID = hash of ("Window", obj pointer, "Click")
PopID();
}
for (int i = 0; i < 100; i++)
{
MyObject* obj = Objects[i];
PushID(obj->Name);
Button("Click"); // Label = "Click", ID = hash of ("Window", obj->Name, "Click")
PopID();
}
End();
- You can stack multiple prefixes into the ID stack:
Button("Click"); // Label = "Click", ID = hash of (..., "Click")
PushID("node");
Button("Click"); // Label = "Click", ID = hash of (..., "node", "Click")
PushID(my_ptr);
Button("Click"); // Label = "Click", ID = hash of (..., "node", my_ptr, "Click")
PopID();
PopID();
- Tree nodes implicitly creates a scope for you by calling PushID().
Button("Click"); // Label = "Click", ID = hash of (..., "Click")
if (TreeNode("node")) // <-- this function call will do a PushID() for you (unless instructed not to, with a special flag)
{
Button("Click"); // Label = "Click", ID = hash of (..., "node", "Click")
TreePop();
}
- When working with trees, ID are used to preserve the open/close state of each tree node.
Depending on your use cases you may want to use strings, indices or pointers as ID.
e.g. when following a single pointer that may change over time, using a static string as ID
will preserve your node open/closed state when the targeted object change.
e.g. when displaying a list of objects, using indices or pointers as ID will preserve the
node open/closed state differently. See what makes more sense in your situation!
Q: How can I display an image? What is ImTextureID, how does it works?
>> See https://www.dearimgui.org/faq and https://github.com/ocornut/imgui/wiki/Image-Loading-and-Displaying-Examples
Q: How can I use my own math types instead of ImVec2/ImVec4?
Q: How can I interact with standard C++ types (such as std::string and std::vector)?
Q: How can I display custom shapes? (using low-level ImDrawList API)
>> See https://www.dearimgui.org/faq
Q&A: Fonts, Text
================
Q: How can I load a different font than the default?
Q: How can I easily use icons in my application?
Q: How can I load multiple fonts?
Q: How can I display and input non-Latin characters such as Chinese, Japanese, Korean, Cyrillic?
>> See https://www.dearimgui.org/faq and docs/FONTS.txt
Q&A: Concerns
=============
Q: Who uses Dear ImGui?
Q: Can you create elaborate/serious tools with Dear ImGui?
Q: Can you reskin the look of Dear ImGui?
Q: Why using C++ (as opposed to C)?
>> See https://www.dearimgui.org/faq
Q&A: Community
==============
Q: How can I help?
A: - Businesses: please reach out to "contact AT dearimgui.org" if you work in a place using Dear ImGui!
We can discuss ways for your company to fund development via invoiced technical support, maintenance or sponsoring contacts.
This is among the most useful thing you can do for Dear ImGui. With increased funding we can hire more people working on this project.
- Individuals: you can support continued development via PayPal donations. See README.
- If you are experienced with Dear ImGui and C++, look at the github issues, look at the Wiki, read docs/TODO.txt
and see how you want to help and can help!
- Disclose your usage of Dear ImGui via a dev blog post, a tweet, a screenshot, a mention somewhere etc.
You may post screenshot or links in the gallery threads (github.com/ocornut/imgui/issues/2847). Visuals are ideal as they inspire other programmers.
But even without visuals, disclosing your use of dear imgui help the library grow credibility, and help other teams and programmers with taking decisions.
- If you have issues or if you need to hack into the library, even if you don't expect any support it is useful that you share your issues (on github or privately).
*/
//-------------------------------------------------------------------------
// [SECTION] INCLUDES
//-------------------------------------------------------------------------
#if defined(_MSC_VER) && !defined(_CRT_SECURE_NO_WARNINGS)
#define _CRT_SECURE_NO_WARNINGS
#endif
#include "imgui.h"
#ifndef IMGUI_DISABLE
#ifndef IMGUI_DEFINE_MATH_OPERATORS
#define IMGUI_DEFINE_MATH_OPERATORS
#endif
#include "imgui_internal.h"
// System includes
#include <ctype.h> // toupper
#include <stdio.h> // vsnprintf, sscanf, printf
#if defined(_MSC_VER) && _MSC_VER <= 1500 // MSVC 2008 or earlier
#include <stddef.h> // intptr_t
#else
#include <stdint.h> // intptr_t
#endif
// [Windows] OS specific includes (optional)
#if defined(_WIN32) && defined(IMGUI_DISABLE_DEFAULT_FILE_FUNCTIONS) && defined(IMGUI_DISABLE_WIN32_DEFAULT_CLIPBOARD_FUNCTIONS) && defined(IMGUI_DISABLE_WIN32_DEFAULT_IME_FUNCTIONS) && !defined(IMGUI_DISABLE_WIN32_FUNCTIONS)
#define IMGUI_DISABLE_WIN32_FUNCTIONS
#endif
#if defined(_WIN32) && !defined(IMGUI_DISABLE_WIN32_FUNCTIONS)
#ifndef WIN32_LEAN_AND_MEAN
#define WIN32_LEAN_AND_MEAN
#endif
#ifndef NOMINMAX
#define NOMINMAX
#endif
#ifndef __MINGW32__
#include <Windows.h> // _wfopen, OpenClipboard
#else
#include <windows.h>
#endif
#if defined(WINAPI_FAMILY) && (WINAPI_FAMILY == WINAPI_FAMILY_APP) // UWP doesn't have all Win32 functions
#define IMGUI_DISABLE_WIN32_DEFAULT_CLIPBOARD_FUNCTIONS
#define IMGUI_DISABLE_WIN32_DEFAULT_IME_FUNCTIONS
#endif
#endif
// [Apple] OS specific includes
#if defined(__APPLE__)
#include <TargetConditionals.h>
#endif
// Visual Studio warnings
#ifdef _MSC_VER
#pragma warning (disable: 4127) // condition expression is constant
#pragma warning (disable: 4996) // 'This function or variable may be unsafe': strcpy, strdup, sprintf, vsnprintf, sscanf, fopen
#if defined(_MSC_VER) && _MSC_VER >= 1922 // MSVC 2019 16.2 or later
#pragma warning (disable: 5054) // operator '|': deprecated between enumerations of different types
#endif
#endif
// Clang/GCC warnings with -Weverything
#if defined(__clang__)
#pragma clang diagnostic ignored "-Wunknown-pragmas" // warning : unknown warning group '-Wformat-pedantic *' // not all warnings are known by all clang versions.. so ignoring warnings triggers new warnings on some configuration. great!
#pragma clang diagnostic ignored "-Wold-style-cast" // warning : use of old-style cast // yes, they are more terse.
#pragma clang diagnostic ignored "-Wfloat-equal" // warning : comparing floating point with == or != is unsafe // storing and comparing against same constants (typically 0.0f) is ok.
#pragma clang diagnostic ignored "-Wformat-nonliteral" // warning : format string is not a string literal // passing non-literal to vsnformat(). yes, user passing incorrect format strings can crash the code.
#pragma clang diagnostic ignored "-Wexit-time-destructors" // warning : declaration requires an exit-time destructor // exit-time destruction order is undefined. if MemFree() leads to users code that has been disabled before exit it might cause problems. ImGui coding style welcomes static/globals.
#pragma clang diagnostic ignored "-Wglobal-constructors" // warning : declaration requires a global destructor // similar to above, not sure what the exact difference is.
#pragma clang diagnostic ignored "-Wsign-conversion" // warning : implicit conversion changes signedness //
#pragma clang diagnostic ignored "-Wformat-pedantic" // warning : format specifies type 'void *' but the argument has type 'xxxx *' // unreasonable, would lead to casting every %p arg to void*. probably enabled by -pedantic.
#pragma clang diagnostic ignored "-Wint-to-void-pointer-cast" // warning : cast to 'void *' from smaller integer type 'int'
#if __has_warning("-Wzero-as-null-pointer-constant")
#pragma clang diagnostic ignored "-Wzero-as-null-pointer-constant" // warning : zero as null pointer constant // some standard header variations use #define NULL 0
#endif
#if __has_warning("-Wdouble-promotion")
#pragma clang diagnostic ignored "-Wdouble-promotion" // warning: implicit conversion from 'float' to 'double' when passing argument to function // using printf() is a misery with this as C++ va_arg ellipsis changes float to double.
#endif
#elif defined(__GNUC__)
// We disable -Wpragmas because GCC doesn't provide an has_warning equivalent and some forks/patches may not following the warning/version association.
#pragma GCC diagnostic ignored "-Wpragmas" // warning: unknown option after '#pragma GCC diagnostic' kind
#pragma GCC diagnostic ignored "-Wunused-function" // warning: 'xxxx' defined but not used
#pragma GCC diagnostic ignored "-Wint-to-pointer-cast" // warning: cast to pointer from integer of different size
#pragma GCC diagnostic ignored "-Wformat" // warning: format '%p' expects argument of type 'void*', but argument 6 has type 'ImGuiWindow*'
#pragma GCC diagnostic ignored "-Wdouble-promotion" // warning: implicit conversion from 'float' to 'double' when passing argument to function
#pragma GCC diagnostic ignored "-Wconversion" // warning: conversion to 'xxxx' from 'xxxx' may alter its value
#pragma GCC diagnostic ignored "-Wformat-nonliteral" // warning: format not a string literal, format string not checked
#pragma GCC diagnostic ignored "-Wstrict-overflow" // warning: assuming signed overflow does not occur when assuming that (X - c) > X is always false
#pragma GCC diagnostic ignored "-Wclass-memaccess" // [__GNUC__ >= 8] warning: 'memset/memcpy' clearing/writing an object of type 'xxxx' with no trivial copy-assignment; use assignment or value-initialization instead
#endif
// Debug options
#define IMGUI_DEBUG_NAV_SCORING 0 // Display navigation scoring preview when hovering items. Display last moving direction matches when holding CTRL
#define IMGUI_DEBUG_NAV_RECTS 0 // Display the reference navigation rectangle for each window
#define IMGUI_DEBUG_INI_SETTINGS 0 // Save additional comments in .ini file (particularly helps for Docking, but makes saving slower)
// When using CTRL+TAB (or Gamepad Square+L/R) we delay the visual a little in order to reduce visual noise doing a fast switch.
static const float NAV_WINDOWING_HIGHLIGHT_DELAY = 0.20f; // Time before the highlight and screen dimming starts fading in
static const float NAV_WINDOWING_LIST_APPEAR_DELAY = 0.15f; // Time before the window list starts to appear
// Window resizing from edges (when io.ConfigWindowsResizeFromEdges = true and ImGuiBackendFlags_HasMouseCursors is set in io.BackendFlags by back-end)
static const float WINDOWS_RESIZE_FROM_EDGES_HALF_THICKNESS = 4.0f; // Extend outside and inside windows. Affect FindHoveredWindow().
static const float WINDOWS_RESIZE_FROM_EDGES_FEEDBACK_TIMER = 0.04f; // Reduce visual noise by only highlighting the border after a certain time.
static const float WINDOWS_MOUSE_WHEEL_SCROLL_LOCK_TIMER = 2.00f; // Lock scrolled window (so it doesn't pick child windows that are scrolling through) for a certaint time, unless mouse moved.
//-------------------------------------------------------------------------
// [SECTION] FORWARD DECLARATIONS
//-------------------------------------------------------------------------
static void SetCurrentWindow(ImGuiWindow* window);
static void FindHoveredWindow();
static ImGuiWindow* CreateNewWindow(const char* name, ImVec2 size, ImGuiWindowFlags flags);
static ImVec2 CalcNextScrollFromScrollTargetAndClamp(ImGuiWindow* window, bool snap_on_edges);
static void AddDrawListToDrawData(ImVector<ImDrawList*>* out_list, ImDrawList* draw_list);
static void AddWindowToSortBuffer(ImVector<ImGuiWindow*>* out_sorted_windows, ImGuiWindow* window);
static ImRect GetViewportRect();
// Settings
static void* WindowSettingsHandler_ReadOpen(ImGuiContext*, ImGuiSettingsHandler*, const char* name);
static void WindowSettingsHandler_ReadLine(ImGuiContext*, ImGuiSettingsHandler*, void* entry, const char* line);
static void WindowSettingsHandler_WriteAll(ImGuiContext*, ImGuiSettingsHandler*, ImGuiTextBuffer* buf);
// Platform Dependents default implementation for IO functions
static const char* GetClipboardTextFn_DefaultImpl(void* user_data);
static void SetClipboardTextFn_DefaultImpl(void* user_data, const char* text);
static void ImeSetInputScreenPosFn_DefaultImpl(int x, int y);
namespace ImGui
{
// Navigation
static void NavUpdate();
static void NavUpdateWindowing();
static void NavUpdateWindowingOverlay();
static void NavUpdateMoveResult();
static float NavUpdatePageUpPageDown();
static inline void NavUpdateAnyRequestFlag();
static bool NavScoreItem(ImGuiNavMoveResult* result, ImRect cand);
static void NavProcessItem(ImGuiWindow* window, const ImRect& nav_bb, ImGuiID id);
static ImVec2 NavCalcPreferredRefPos();
static void NavSaveLastChildNavWindowIntoParent(ImGuiWindow* nav_window);
static ImGuiWindow* NavRestoreLastChildNavWindow(ImGuiWindow* window);
static int FindWindowFocusIndex(ImGuiWindow* window);
// Error Checking
static void ErrorCheckEndFrame();
static void ErrorCheckBeginEndCompareStacksSize(ImGuiWindow* window, bool write);
// Misc
static void UpdateSettings();
static void UpdateMouseInputs();
static void UpdateMouseWheel();
static void UpdateTabFocus();
static void UpdateDebugToolItemPicker();
static bool UpdateWindowManualResize(ImGuiWindow* window, const ImVec2& size_auto_fit, int* border_held, int resize_grip_count, ImU32 resize_grip_col[4]);
static void RenderWindowOuterBorders(ImGuiWindow* window);
static void RenderWindowDecorations(ImGuiWindow* window, const ImRect& title_bar_rect, bool title_bar_is_highlight, int resize_grip_count, const ImU32 resize_grip_col[4], float resize_grip_draw_size);
static void RenderWindowTitleBarContents(ImGuiWindow* window, const ImRect& title_bar_rect, const char* name, bool* p_open);
}
//-----------------------------------------------------------------------------
// [SECTION] CONTEXT AND MEMORY ALLOCATORS
//-----------------------------------------------------------------------------
// Current context pointer. Implicitly used by all Dear ImGui functions. Always assumed to be != NULL.
// ImGui::CreateContext() will automatically set this pointer if it is NULL. Change to a different context by calling ImGui::SetCurrentContext().
// 1) Important: globals are not shared across DLL boundaries! If you use DLLs or any form of hot-reloading: you will need to call
// SetCurrentContext() (with the pointer you got from CreateContext) from each unique static/DLL boundary, and after each hot-reloading.
// In your debugger, add GImGui to your watch window and notice how its value changes depending on which location you are currently stepping into.
// 2) Important: Dear ImGui functions are not thread-safe because of this pointer.
// If you want thread-safety to allow N threads to access N different contexts, you can:
// - Change this variable to use thread local storage so each thread can refer to a different context, in imconfig.h:
// struct ImGuiContext;
// extern thread_local ImGuiContext* MyImGuiTLS;
// #define GImGui MyImGuiTLS
// And then define MyImGuiTLS in one of your cpp file. Note that thread_local is a C++11 keyword, earlier C++ uses compiler-specific keyword.
// - Future development aim to make this context pointer explicit to all calls. Also read https://github.com/ocornut/imgui/issues/586
// - If you need a finite number of contexts, you may compile and use multiple instances of the ImGui code from different namespace.
#ifndef GImGui
ImGuiContext* GImGui = NULL;
#endif
// Memory Allocator functions. Use SetAllocatorFunctions() to change them.
// If you use DLL hotreloading you might need to call SetAllocatorFunctions() after reloading code from this file.
// Otherwise, you probably don't want to modify them mid-program, and if you use global/static e.g. ImVector<> instances you may need to keep them accessible during program destruction.
#ifndef IMGUI_DISABLE_DEFAULT_ALLOCATORS
static void* MallocWrapper(size_t size, void* user_data) { IM_UNUSED(user_data); return malloc(size); }
static void FreeWrapper(void* ptr, void* user_data) { IM_UNUSED(user_data); free(ptr); }
#else
static void* MallocWrapper(size_t size, void* user_data) { IM_UNUSED(user_data); IM_UNUSED(size); IM_ASSERT(0); return NULL; }
static void FreeWrapper(void* ptr, void* user_data) { IM_UNUSED(user_data); IM_UNUSED(ptr); IM_ASSERT(0); }
#endif
static void* (*GImAllocatorAllocFunc)(size_t size, void* user_data) = MallocWrapper;
static void (*GImAllocatorFreeFunc)(void* ptr, void* user_data) = FreeWrapper;
static void* GImAllocatorUserData = NULL;
//-----------------------------------------------------------------------------
// [SECTION] USER FACING STRUCTURES (ImGuiStyle, ImGuiIO)
//-----------------------------------------------------------------------------
ImGuiStyle::ImGuiStyle()
{
Alpha = 1.0f; // Global alpha applies to everything in ImGui
WindowPadding = ImVec2(8,8); // Padding within a window
WindowRounding = 7.0f; // Radius of window corners rounding. Set to 0.0f to have rectangular windows
WindowBorderSize = 1.0f; // Thickness of border around windows. Generally set to 0.0f or 1.0f. Other values not well tested.
WindowMinSize = ImVec2(32,32); // Minimum window size
WindowTitleAlign = ImVec2(0.0f,0.5f);// Alignment for title bar text
WindowMenuButtonPosition= ImGuiDir_Left; // Position of the collapsing/docking button in the title bar (left/right). Defaults to ImGuiDir_Left.
ChildRounding = 0.0f; // Radius of child window corners rounding. Set to 0.0f to have rectangular child windows
ChildBorderSize = 1.0f; // Thickness of border around child windows. Generally set to 0.0f or 1.0f. Other values not well tested.
PopupRounding = 0.0f; // Radius of popup window corners rounding. Set to 0.0f to have rectangular child windows
PopupBorderSize = 1.0f; // Thickness of border around popup or tooltip windows. Generally set to 0.0f or 1.0f. Other values not well tested.
FramePadding = ImVec2(4,3); // Padding within a framed rectangle (used by most widgets)
FrameRounding = 0.0f; // Radius of frame corners rounding. Set to 0.0f to have rectangular frames (used by most widgets).
FrameBorderSize = 0.0f; // Thickness of border around frames. Generally set to 0.0f or 1.0f. Other values not well tested.
ItemSpacing = ImVec2(8,4); // Horizontal and vertical spacing between widgets/lines
ItemInnerSpacing = ImVec2(4,4); // Horizontal and vertical spacing between within elements of a composed widget (e.g. a slider and its label)
TouchExtraPadding = ImVec2(0,0); // Expand reactive bounding box for touch-based system where touch position is not accurate enough. Unfortunately we don't sort widgets so priority on overlap will always be given to the first widget. So don't grow this too much!
IndentSpacing = 21.0f; // Horizontal spacing when e.g. entering a tree node. Generally == (FontSize + FramePadding.x*2).
ColumnsMinSpacing = 6.0f; // Minimum horizontal spacing between two columns. Preferably > (FramePadding.x + 1).
ScrollbarSize = 14.0f; // Width of the vertical scrollbar, Height of the horizontal scrollbar
ScrollbarRounding = 9.0f; // Radius of grab corners rounding for scrollbar
GrabMinSize = 10.0f; // Minimum width/height of a grab box for slider/scrollbar
GrabRounding = 0.0f; // Radius of grabs corners rounding. Set to 0.0f to have rectangular slider grabs.
TabRounding = 4.0f; // Radius of upper corners of a tab. Set to 0.0f to have rectangular tabs.
TabBorderSize = 0.0f; // Thickness of border around tabs.
ColorButtonPosition = ImGuiDir_Right; // Side of the color button in the ColorEdit4 widget (left/right). Defaults to ImGuiDir_Right.
ButtonTextAlign = ImVec2(0.5f,0.5f);// Alignment of button text when button is larger than text.
SelectableTextAlign = ImVec2(0.0f,0.0f);// Alignment of selectable text when button is larger than text.
DisplayWindowPadding = ImVec2(19,19); // Window position are clamped to be visible within the display area or monitors by at least this amount. Only applies to regular windows.
DisplaySafeAreaPadding = ImVec2(3,3); // If you cannot see the edge of your screen (e.g. on a TV) increase the safe area padding. Covers popups/tooltips as well regular windows.
MouseCursorScale = 1.0f; // Scale software rendered mouse cursor (when io.MouseDrawCursor is enabled). May be removed later.
AntiAliasedLines = true; // Enable anti-aliasing on lines/borders. Disable if you are really short on CPU/GPU.
AntiAliasedFill = true; // Enable anti-aliasing on filled shapes (rounded rectangles, circles, etc.)
CurveTessellationTol = 1.25f; // Tessellation tolerance when using PathBezierCurveTo() without a specific number of segments. Decrease for highly tessellated curves (higher quality, more polygons), increase to reduce quality.
CircleSegmentMaxError = 1.60f; // Maximum error (in pixels) allowed when using AddCircle()/AddCircleFilled() or drawing rounded corner rectangles with no explicit segment count specified. Decrease for higher quality but more geometry.
// Default theme
ImGui::StyleColorsDark(this);
}
// To scale your entire UI (e.g. if you want your app to use High DPI or generally be DPI aware) you may use this helper function. Scaling the fonts is done separately and is up to you.
// Important: This operation is lossy because we round all sizes to integer. If you need to change your scale multiples, call this over a freshly initialized ImGuiStyle structure rather than scaling multiple times.
void ImGuiStyle::ScaleAllSizes(float scale_factor)
{
WindowPadding = ImFloor(WindowPadding * scale_factor);
WindowRounding = ImFloor(WindowRounding * scale_factor);
WindowMinSize = ImFloor(WindowMinSize * scale_factor);
ChildRounding = ImFloor(ChildRounding * scale_factor);
PopupRounding = ImFloor(PopupRounding * scale_factor);
FramePadding = ImFloor(FramePadding * scale_factor);
FrameRounding = ImFloor(FrameRounding * scale_factor);
ItemSpacing = ImFloor(ItemSpacing * scale_factor);
ItemInnerSpacing = ImFloor(ItemInnerSpacing * scale_factor);
TouchExtraPadding = ImFloor(TouchExtraPadding * scale_factor);
IndentSpacing = ImFloor(IndentSpacing * scale_factor);
ColumnsMinSpacing = ImFloor(ColumnsMinSpacing * scale_factor);
ScrollbarSize = ImFloor(ScrollbarSize * scale_factor);
ScrollbarRounding = ImFloor(ScrollbarRounding * scale_factor);
GrabMinSize = ImFloor(GrabMinSize * scale_factor);
GrabRounding = ImFloor(GrabRounding * scale_factor);
TabRounding = ImFloor(TabRounding * scale_factor);
DisplayWindowPadding = ImFloor(DisplayWindowPadding * scale_factor);
DisplaySafeAreaPadding = ImFloor(DisplaySafeAreaPadding * scale_factor);
MouseCursorScale = ImFloor(MouseCursorScale * scale_factor);
}
ImGuiIO::ImGuiIO()
{
// Most fields are initialized with zero
memset(this, 0, sizeof(*this));
IM_ASSERT(IM_ARRAYSIZE(ImGuiIO::MouseDown) == ImGuiMouseButton_COUNT && IM_ARRAYSIZE(ImGuiIO::MouseClicked) == ImGuiMouseButton_COUNT); // Our pre-C++11 IM_STATIC_ASSERT() macros triggers warning on modern compilers so we don't use it here.
// Settings
ConfigFlags = ImGuiConfigFlags_None;
BackendFlags = ImGuiBackendFlags_None;
DisplaySize = ImVec2(-1.0f, -1.0f);
DeltaTime = 1.0f/60.0f;
IniSavingRate = 5.0f;
IniFilename = "imgui.ini";
LogFilename = "imgui_log.txt";
MouseDoubleClickTime = 0.30f;
MouseDoubleClickMaxDist = 6.0f;
for (int i = 0; i < ImGuiKey_COUNT; i++)
KeyMap[i] = -1;
KeyRepeatDelay = 0.275f;
KeyRepeatRate = 0.050f;
UserData = NULL;
Fonts = NULL;
FontGlobalScale = 1.0f;
FontDefault = NULL;
FontAllowUserScaling = false;
DisplayFramebufferScale = ImVec2(1.0f, 1.0f);
// Miscellaneous options
MouseDrawCursor = false;
#ifdef __APPLE__
ConfigMacOSXBehaviors = true; // Set Mac OS X style defaults based on __APPLE__ compile time flag
#else
ConfigMacOSXBehaviors = false;
#endif
ConfigInputTextCursorBlink = true;
ConfigWindowsResizeFromEdges = true;
ConfigWindowsMoveFromTitleBarOnly = false;
ConfigWindowsMemoryCompactTimer = 60.0f;
// Platform Functions
BackendPlatformName = BackendRendererName = NULL;
BackendPlatformUserData = BackendRendererUserData = BackendLanguageUserData = NULL;
GetClipboardTextFn = GetClipboardTextFn_DefaultImpl; // Platform dependent default implementations
SetClipboardTextFn = SetClipboardTextFn_DefaultImpl;
ClipboardUserData = NULL;
ImeSetInputScreenPosFn = ImeSetInputScreenPosFn_DefaultImpl;
ImeWindowHandle = NULL;
#ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS
RenderDrawListsFn = NULL;
#endif
// Input (NB: we already have memset zero the entire structure!)
MousePos = ImVec2(-FLT_MAX, -FLT_MAX);
MousePosPrev = ImVec2(-FLT_MAX, -FLT_MAX);
MouseDragThreshold = 6.0f;
for (int i = 0; i < IM_ARRAYSIZE(MouseDownDuration); i++) MouseDownDuration[i] = MouseDownDurationPrev[i] = -1.0f;
for (int i = 0; i < IM_ARRAYSIZE(KeysDownDuration); i++) KeysDownDuration[i] = KeysDownDurationPrev[i] = -1.0f;
for (int i = 0; i < IM_ARRAYSIZE(NavInputsDownDuration); i++) NavInputsDownDuration[i] = -1.0f;
}
// Pass in translated ASCII characters for text input.
// - with glfw you can get those from the callback set in glfwSetCharCallback()
// - on Windows you can get those using ToAscii+keyboard state, or via the WM_CHAR message
void ImGuiIO::AddInputCharacter(unsigned int c)
{
InputQueueCharacters.push_back(c > 0 && c <= IM_UNICODE_CODEPOINT_MAX ? (ImWchar)c : IM_UNICODE_CODEPOINT_INVALID);
}
// UTF16 strings use surrogate pairs to encode codepoints >= 0x10000, so
// we should save the high surrogate.
void ImGuiIO::AddInputCharacterUTF16(ImWchar16 c)
{
if ((c & 0xFC00) == 0xD800) // High surrogate, must save
{
if (InputQueueSurrogate != 0)
InputQueueCharacters.push_back(0xFFFD);
InputQueueSurrogate = c;
return;
}
ImWchar cp = c;
if (InputQueueSurrogate != 0)
{
if ((c & 0xFC00) != 0xDC00) // Invalid low surrogate
InputQueueCharacters.push_back(IM_UNICODE_CODEPOINT_INVALID);
else if (IM_UNICODE_CODEPOINT_MAX == (0xFFFF)) // Codepoint will not fit in ImWchar (extra parenthesis around 0xFFFF somehow fixes -Wunreachable-code with Clang)
cp = IM_UNICODE_CODEPOINT_INVALID;
else
cp = (ImWchar)(((InputQueueSurrogate - 0xD800) << 10) + (c - 0xDC00) + 0x10000);
InputQueueSurrogate = 0;
}
InputQueueCharacters.push_back(cp);
}
void ImGuiIO::AddInputCharactersUTF8(const char* utf8_chars)
{
while (*utf8_chars != 0)
{
unsigned int c = 0;
utf8_chars += ImTextCharFromUtf8(&c, utf8_chars, NULL);
if (c > 0)
InputQueueCharacters.push_back((ImWchar)c);
}
}
void ImGuiIO::ClearInputCharacters()
{
InputQueueCharacters.resize(0);
}
//-----------------------------------------------------------------------------
// [SECTION] MISC HELPERS/UTILITIES (Geometry functions)
//-----------------------------------------------------------------------------
ImVec2 ImBezierClosestPoint(const ImVec2& p1, const ImVec2& p2, const ImVec2& p3, const ImVec2& p4, const ImVec2& p, int num_segments)
{
IM_ASSERT(num_segments > 0); // Use ImBezierClosestPointCasteljau()
ImVec2 p_last = p1;
ImVec2 p_closest;
float p_closest_dist2 = FLT_MAX;
float t_step = 1.0f / (float)num_segments;
for (int i_step = 1; i_step <= num_segments; i_step++)
{
ImVec2 p_current = ImBezierCalc(p1, p2, p3, p4, t_step * i_step);
ImVec2 p_line = ImLineClosestPoint(p_last, p_current, p);
float dist2 = ImLengthSqr(p - p_line);
if (dist2 < p_closest_dist2)
{
p_closest = p_line;
p_closest_dist2 = dist2;
}
p_last = p_current;
}
return p_closest;
}
// Closely mimics PathBezierToCasteljau() in imgui_draw.cpp
static void BezierClosestPointCasteljauStep(const ImVec2& p, ImVec2& p_closest, ImVec2& p_last, float& p_closest_dist2, float x1, float y1, float x2, float y2, float x3, float y3, float x4, float y4, float tess_tol, int level)
{
float dx = x4 - x1;
float dy = y4 - y1;
float d2 = ((x2 - x4) * dy - (y2 - y4) * dx);
float d3 = ((x3 - x4) * dy - (y3 - y4) * dx);
d2 = (d2 >= 0) ? d2 : -d2;
d3 = (d3 >= 0) ? d3 : -d3;
if ((d2+d3) * (d2+d3) < tess_tol * (dx*dx + dy*dy))
{
ImVec2 p_current(x4, y4);
ImVec2 p_line = ImLineClosestPoint(p_last, p_current, p);
float dist2 = ImLengthSqr(p - p_line);
if (dist2 < p_closest_dist2)
{
p_closest = p_line;
p_closest_dist2 = dist2;
}
p_last = p_current;
}
else if (level < 10)
{
float x12 = (x1+x2)*0.5f, y12 = (y1+y2)*0.5f;
float x23 = (x2+x3)*0.5f, y23 = (y2+y3)*0.5f;
float x34 = (x3+x4)*0.5f, y34 = (y3+y4)*0.5f;
float x123 = (x12+x23)*0.5f, y123 = (y12+y23)*0.5f;
float x234 = (x23+x34)*0.5f, y234 = (y23+y34)*0.5f;
float x1234 = (x123+x234)*0.5f, y1234 = (y123+y234)*0.5f;
BezierClosestPointCasteljauStep(p, p_closest, p_last, p_closest_dist2, x1, y1, x12, y12, x123, y123, x1234, y1234, tess_tol, level + 1);
BezierClosestPointCasteljauStep(p, p_closest, p_last, p_closest_dist2, x1234, y1234, x234, y234, x34, y34, x4, y4, tess_tol, level + 1);
}
}
// tess_tol is generally the same value you would find in ImGui::GetStyle().CurveTessellationTol
// Because those ImXXX functions are lower-level than ImGui:: we cannot access this value automatically.
ImVec2 ImBezierClosestPointCasteljau(const ImVec2& p1, const ImVec2& p2, const ImVec2& p3, const ImVec2& p4, const ImVec2& p, float tess_tol)
{
IM_ASSERT(tess_tol > 0.0f);
ImVec2 p_last = p1;
ImVec2 p_closest;
float p_closest_dist2 = FLT_MAX;
BezierClosestPointCasteljauStep(p, p_closest, p_last, p_closest_dist2, p1.x, p1.y, p2.x, p2.y, p3.x, p3.y, p4.x, p4.y, tess_tol, 0);
return p_closest;
}
ImVec2 ImLineClosestPoint(const ImVec2& a, const ImVec2& b, const ImVec2& p)
{
ImVec2 ap = p - a;
ImVec2 ab_dir = b - a;
float dot = ap.x * ab_dir.x + ap.y * ab_dir.y;
if (dot < 0.0f)
return a;
float ab_len_sqr = ab_dir.x * ab_dir.x + ab_dir.y * ab_dir.y;
if (dot > ab_len_sqr)
return b;
return a + ab_dir * dot / ab_len_sqr;
}
bool ImTriangleContainsPoint(const ImVec2& a, const ImVec2& b, const ImVec2& c, const ImVec2& p)
{
bool b1 = ((p.x - b.x) * (a.y - b.y) - (p.y - b.y) * (a.x - b.x)) < 0.0f;
bool b2 = ((p.x - c.x) * (b.y - c.y) - (p.y - c.y) * (b.x - c.x)) < 0.0f;
bool b3 = ((p.x - a.x) * (c.y - a.y) - (p.y - a.y) * (c.x - a.x)) < 0.0f;
return ((b1 == b2) && (b2 == b3));
}
void ImTriangleBarycentricCoords(const ImVec2& a, const ImVec2& b, const ImVec2& c, const ImVec2& p, float& out_u, float& out_v, float& out_w)
{
ImVec2 v0 = b - a;
ImVec2 v1 = c - a;
ImVec2 v2 = p - a;
const float denom = v0.x * v1.y - v1.x * v0.y;
out_v = (v2.x * v1.y - v1.x * v2.y) / denom;
out_w = (v0.x * v2.y - v2.x * v0.y) / denom;
out_u = 1.0f - out_v - out_w;
}
ImVec2 ImTriangleClosestPoint(const ImVec2& a, const ImVec2& b, const ImVec2& c, const ImVec2& p)
{
ImVec2 proj_ab = ImLineClosestPoint(a, b, p);
ImVec2 proj_bc = ImLineClosestPoint(b, c, p);
ImVec2 proj_ca = ImLineClosestPoint(c, a, p);
float dist2_ab = ImLengthSqr(p - proj_ab);
float dist2_bc = ImLengthSqr(p - proj_bc);
float dist2_ca = ImLengthSqr(p - proj_ca);
float m = ImMin(dist2_ab, ImMin(dist2_bc, dist2_ca));
if (m == dist2_ab)
return proj_ab;
if (m == dist2_bc)
return proj_bc;
return proj_ca;
}
//-----------------------------------------------------------------------------
// [SECTION] MISC HELPERS/UTILITIES (String, Format, Hash functions)
//-----------------------------------------------------------------------------
// Consider using _stricmp/_strnicmp under Windows or strcasecmp/strncasecmp. We don't actually use either ImStricmp/ImStrnicmp in the codebase any more.
int ImStricmp(const char* str1, const char* str2)
{
int d;
while ((d = toupper(*str2) - toupper(*str1)) == 0 && *str1) { str1++; str2++; }
return d;
}
int ImStrnicmp(const char* str1, const char* str2, size_t count)
{
int d = 0;
while (count > 0 && (d = toupper(*str2) - toupper(*str1)) == 0 && *str1) { str1++; str2++; count--; }
return d;
}
void ImStrncpy(char* dst, const char* src, size_t count)
{
if (count < 1)
return;
if (count > 1)
strncpy(dst, src, count - 1);
dst[count - 1] = 0;
}
char* ImStrdup(const char* str)
{
size_t len = strlen(str);
void* buf = IM_ALLOC(len + 1);
return (char*)memcpy(buf, (const void*)str, len + 1);
}
char* ImStrdupcpy(char* dst, size_t* p_dst_size, const char* src)
{
size_t dst_buf_size = p_dst_size ? *p_dst_size : strlen(dst) + 1;
size_t src_size = strlen(src) + 1;
if (dst_buf_size < src_size)
{
IM_FREE(dst);
dst = (char*)IM_ALLOC(src_size);
if (p_dst_size)
*p_dst_size = src_size;
}
return (char*)memcpy(dst, (const void*)src, src_size);
}
const char* ImStrchrRange(const char* str, const char* str_end, char c)
{
const char* p = (const char*)memchr(str, (int)c, str_end - str);
return p;
}
int ImStrlenW(const ImWchar* str)
{
//return (int)wcslen((const wchar_t*)str); // FIXME-OPT: Could use this when wchar_t are 16-bit
int n = 0;
while (*str++) n++;
return n;
}
// Find end-of-line. Return pointer will point to either first \n, either str_end.
const char* ImStreolRange(const char* str, const char* str_end)
{
const char* p = (const char*)memchr(str, '\n', str_end - str);
return p ? p : str_end;
}
const ImWchar* ImStrbolW(const ImWchar* buf_mid_line, const ImWchar* buf_begin) // find beginning-of-line
{
while (buf_mid_line > buf_begin && buf_mid_line[-1] != '\n')
buf_mid_line--;
return buf_mid_line;
}
const char* ImStristr(const char* haystack, const char* haystack_end, const char* needle, const char* needle_end)
{
if (!needle_end)
needle_end = needle + strlen(needle);
const char un0 = (char)toupper(*needle);
while ((!haystack_end && *haystack) || (haystack_end && haystack < haystack_end))
{
if (toupper(*haystack) == un0)
{
const char* b = needle + 1;
for (const char* a = haystack + 1; b < needle_end; a++, b++)
if (toupper(*a) != toupper(*b))
break;
if (b == needle_end)
return haystack;
}
haystack++;
}
return NULL;
}
// Trim str by offsetting contents when there's leading data + writing a \0 at the trailing position. We use this in situation where the cost is negligible.
void ImStrTrimBlanks(char* buf)
{
char* p = buf;
while (p[0] == ' ' || p[0] == '\t') // Leading blanks
p++;
char* p_start = p;
while (*p != 0) // Find end of string
p++;
while (p > p_start && (p[-1] == ' ' || p[-1] == '\t')) // Trailing blanks
p--;
if (p_start != buf) // Copy memory if we had leading blanks
memmove(buf, p_start, p - p_start);
buf[p - p_start] = 0; // Zero terminate
}
const char* ImStrSkipBlank(const char* str)
{
while (str[0] == ' ' || str[0] == '\t')
str++;
return str;
}
// A) MSVC version appears to return -1 on overflow, whereas glibc appears to return total count (which may be >= buf_size).
// Ideally we would test for only one of those limits at runtime depending on the behavior the vsnprintf(), but trying to deduct it at compile time sounds like a pandora can of worm.
// B) When buf==NULL vsnprintf() will return the output size.
#ifndef IMGUI_DISABLE_DEFAULT_FORMAT_FUNCTIONS
// We support stb_sprintf which is much faster (see: https://github.com/nothings/stb/blob/master/stb_sprintf.h)
// You may set IMGUI_USE_STB_SPRINTF to use our default wrapper, or set IMGUI_DISABLE_DEFAULT_FORMAT_FUNCTIONS
// and setup the wrapper yourself. (FIXME-OPT: Some of our high-level operations such as ImGuiTextBuffer::appendfv() are
// designed using two-passes worst case, which probably could be improved using the stbsp_vsprintfcb() function.)
#ifdef IMGUI_USE_STB_SPRINTF
#define STB_SPRINTF_IMPLEMENTATION
#include "stb_sprintf.h"
#endif
#if defined(_MSC_VER) && !defined(vsnprintf)
#define vsnprintf _vsnprintf
#endif
int ImFormatString(char* buf, size_t buf_size, const char* fmt, ...)
{
va_list args;
va_start(args, fmt);
#ifdef IMGUI_USE_STB_SPRINTF
int w = stbsp_vsnprintf(buf, (int)buf_size, fmt, args);
#else
int w = vsnprintf(buf, buf_size, fmt, args);
#endif
va_end(args);
if (buf == NULL)
return w;
if (w == -1 || w >= (int)buf_size)
w = (int)buf_size - 1;
buf[w] = 0;
return w;
}
int ImFormatStringV(char* buf, size_t buf_size, const char* fmt, va_list args)
{
#ifdef IMGUI_USE_STB_SPRINTF
int w = stbsp_vsnprintf(buf, (int)buf_size, fmt, args);
#else
int w = vsnprintf(buf, buf_size, fmt, args);
#endif
if (buf == NULL)
return w;
if (w == -1 || w >= (int)buf_size)
w = (int)buf_size - 1;
buf[w] = 0;
return w;
}
#endif // #ifdef IMGUI_DISABLE_DEFAULT_FORMAT_FUNCTIONS
// CRC32 needs a 1KB lookup table (not cache friendly)
// Although the code to generate the table is simple and shorter than the table itself, using a const table allows us to easily:
// - avoid an unnecessary branch/memory tap, - keep the ImHashXXX functions usable by static constructors, - make it thread-safe.
static const ImU32 GCrc32LookupTable[256] =
{
0x00000000,0x77073096,0xEE0E612C,0x990951BA,0x076DC419,0x706AF48F,0xE963A535,0x9E6495A3,0x0EDB8832,0x79DCB8A4,0xE0D5E91E,0x97D2D988,0x09B64C2B,0x7EB17CBD,0xE7B82D07,0x90BF1D91,
0x1DB71064,0x6AB020F2,0xF3B97148,0x84BE41DE,0x1ADAD47D,0x6DDDE4EB,0xF4D4B551,0x83D385C7,0x136C9856,0x646BA8C0,0xFD62F97A,0x8A65C9EC,0x14015C4F,0x63066CD9,0xFA0F3D63,0x8D080DF5,
0x3B6E20C8,0x4C69105E,0xD56041E4,0xA2677172,0x3C03E4D1,0x4B04D447,0xD20D85FD,0xA50AB56B,0x35B5A8FA,0x42B2986C,0xDBBBC9D6,0xACBCF940,0x32D86CE3,0x45DF5C75,0xDCD60DCF,0xABD13D59,
0x26D930AC,0x51DE003A,0xC8D75180,0xBFD06116,0x21B4F4B5,0x56B3C423,0xCFBA9599,0xB8BDA50F,0x2802B89E,0x5F058808,0xC60CD9B2,0xB10BE924,0x2F6F7C87,0x58684C11,0xC1611DAB,0xB6662D3D,
0x76DC4190,0x01DB7106,0x98D220BC,0xEFD5102A,0x71B18589,0x06B6B51F,0x9FBFE4A5,0xE8B8D433,0x7807C9A2,0x0F00F934,0x9609A88E,0xE10E9818,0x7F6A0DBB,0x086D3D2D,0x91646C97,0xE6635C01,
0x6B6B51F4,0x1C6C6162,0x856530D8,0xF262004E,0x6C0695ED,0x1B01A57B,0x8208F4C1,0xF50FC457,0x65B0D9C6,0x12B7E950,0x8BBEB8EA,0xFCB9887C,0x62DD1DDF,0x15DA2D49,0x8CD37CF3,0xFBD44C65,
0x4DB26158,0x3AB551CE,0xA3BC0074,0xD4BB30E2,0x4ADFA541,0x3DD895D7,0xA4D1C46D,0xD3D6F4FB,0x4369E96A,0x346ED9FC,0xAD678846,0xDA60B8D0,0x44042D73,0x33031DE5,0xAA0A4C5F,0xDD0D7CC9,
0x5005713C,0x270241AA,0xBE0B1010,0xC90C2086,0x5768B525,0x206F85B3,0xB966D409,0xCE61E49F,0x5EDEF90E,0x29D9C998,0xB0D09822,0xC7D7A8B4,0x59B33D17,0x2EB40D81,0xB7BD5C3B,0xC0BA6CAD,
0xEDB88320,0x9ABFB3B6,0x03B6E20C,0x74B1D29A,0xEAD54739,0x9DD277AF,0x04DB2615,0x73DC1683,0xE3630B12,0x94643B84,0x0D6D6A3E,0x7A6A5AA8,0xE40ECF0B,0x9309FF9D,0x0A00AE27,0x7D079EB1,
0xF00F9344,0x8708A3D2,0x1E01F268,0x6906C2FE,0xF762575D,0x806567CB,0x196C3671,0x6E6B06E7,0xFED41B76,0x89D32BE0,0x10DA7A5A,0x67DD4ACC,0xF9B9DF6F,0x8EBEEFF9,0x17B7BE43,0x60B08ED5,
0xD6D6A3E8,0xA1D1937E,0x38D8C2C4,0x4FDFF252,0xD1BB67F1,0xA6BC5767,0x3FB506DD,0x48B2364B,0xD80D2BDA,0xAF0A1B4C,0x36034AF6,0x41047A60,0xDF60EFC3,0xA867DF55,0x316E8EEF,0x4669BE79,
0xCB61B38C,0xBC66831A,0x256FD2A0,0x5268E236,0xCC0C7795,0xBB0B4703,0x220216B9,0x5505262F,0xC5BA3BBE,0xB2BD0B28,0x2BB45A92,0x5CB36A04,0xC2D7FFA7,0xB5D0CF31,0x2CD99E8B,0x5BDEAE1D,
0x9B64C2B0,0xEC63F226,0x756AA39C,0x026D930A,0x9C0906A9,0xEB0E363F,0x72076785,0x05005713,0x95BF4A82,0xE2B87A14,0x7BB12BAE,0x0CB61B38,0x92D28E9B,0xE5D5BE0D,0x7CDCEFB7,0x0BDBDF21,
0x86D3D2D4,0xF1D4E242,0x68DDB3F8,0x1FDA836E,0x81BE16CD,0xF6B9265B,0x6FB077E1,0x18B74777,0x88085AE6,0xFF0F6A70,0x66063BCA,0x11010B5C,0x8F659EFF,0xF862AE69,0x616BFFD3,0x166CCF45,
0xA00AE278,0xD70DD2EE,0x4E048354,0x3903B3C2,0xA7672661,0xD06016F7,0x4969474D,0x3E6E77DB,0xAED16A4A,0xD9D65ADC,0x40DF0B66,0x37D83BF0,0xA9BCAE53,0xDEBB9EC5,0x47B2CF7F,0x30B5FFE9,
0xBDBDF21C,0xCABAC28A,0x53B39330,0x24B4A3A6,0xBAD03605,0xCDD70693,0x54DE5729,0x23D967BF,0xB3667A2E,0xC4614AB8,0x5D681B02,0x2A6F2B94,0xB40BBE37,0xC30C8EA1,0x5A05DF1B,0x2D02EF8D,
};
// Known size hash
// It is ok to call ImHashData on a string with known length but the ### operator won't be supported.
// FIXME-OPT: Replace with e.g. FNV1a hash? CRC32 pretty much randomly access 1KB. Need to do proper measurements.
ImU32 ImHashData(const void* data_p, size_t data_size, ImU32 seed)
{
ImU32 crc = ~seed;
const unsigned char* data = (const unsigned char*)data_p;
const ImU32* crc32_lut = GCrc32LookupTable;
while (data_size-- != 0)
crc = (crc >> 8) ^ crc32_lut[(crc & 0xFF) ^ *data++];
return ~crc;
}
// Zero-terminated string hash, with support for ### to reset back to seed value
// We support a syntax of "label###id" where only "###id" is included in the hash, and only "label" gets displayed.
// Because this syntax is rarely used we are optimizing for the common case.
// - If we reach ### in the string we discard the hash so far and reset to the seed.
// - We don't do 'current += 2; continue;' after handling ### to keep the code smaller/faster (measured ~10% diff in Debug build)
// FIXME-OPT: Replace with e.g. FNV1a hash? CRC32 pretty much randomly access 1KB. Need to do proper measurements.
ImU32 ImHashStr(const char* data_p, size_t data_size, ImU32 seed)
{
seed = ~seed;
ImU32 crc = seed;
const unsigned char* data = (const unsigned char*)data_p;
const ImU32* crc32_lut = GCrc32LookupTable;
if (data_size != 0)
{
while (data_size-- != 0)
{
unsigned char c = *data++;
if (c == '#' && data_size >= 2 && data[0] == '#' && data[1] == '#')
crc = seed;
crc = (crc >> 8) ^ crc32_lut[(crc & 0xFF) ^ c];
}
}
else
{
while (unsigned char c = *data++)
{
if (c == '#' && data[0] == '#' && data[1] == '#')
crc = seed;
crc = (crc >> 8) ^ crc32_lut[(crc & 0xFF) ^ c];
}
}
return ~crc;
}
//-----------------------------------------------------------------------------
// [SECTION] MISC HELPERS/UTILITIES (File functions)
//-----------------------------------------------------------------------------
// Default file functions
#ifndef IMGUI_DISABLE_DEFAULT_FILE_FUNCTIONS
ImFileHandle ImFileOpen(const char* filename, const char* mode)
{
#if defined(_WIN32) && !defined(IMGUI_DISABLE_WIN32_FUNCTIONS) && !defined(__CYGWIN__) && !defined(__GNUC__)
// We need a fopen() wrapper because MSVC/Windows fopen doesn't handle UTF-8 filenames.
// Previously we used ImTextCountCharsFromUtf8/ImTextStrFromUtf8 here but we now need to support ImWchar16 and ImWchar32!
const int filename_wsize = ::MultiByteToWideChar(CP_UTF8, 0, filename, -1, NULL, 0);
const int mode_wsize = ::MultiByteToWideChar(CP_UTF8, 0, mode, -1, NULL, 0);
ImVector<ImWchar> buf;
buf.resize(filename_wsize + mode_wsize);
::MultiByteToWideChar(CP_UTF8, 0, filename, -1, (wchar_t*)&buf[0], filename_wsize);
::MultiByteToWideChar(CP_UTF8, 0, mode, -1, (wchar_t*)&buf[filename_wsize], mode_wsize);
return ::_wfopen((const wchar_t*)&buf[0], (const wchar_t*)&buf[filename_wsize]);
#else
return fopen(filename, mode);
#endif
}
// We should in theory be using fseeko()/ftello() with off_t and _fseeki64()/_ftelli64() with __int64, waiting for the PR that does that in a very portable pre-C++11 zero-warnings way.
bool ImFileClose(ImFileHandle f) { return fclose(f) == 0; }
ImU64 ImFileGetSize(ImFileHandle f) { long off = 0, sz = 0; return ((off = ftell(f)) != -1 && !fseek(f, 0, SEEK_END) && (sz = ftell(f)) != -1 && !fseek(f, off, SEEK_SET)) ? (ImU64)sz : (ImU64)-1; }
ImU64 ImFileRead(void* data, ImU64 sz, ImU64 count, ImFileHandle f) { return fread(data, (size_t)sz, (size_t)count, f); }
ImU64 ImFileWrite(const void* data, ImU64 sz, ImU64 count, ImFileHandle f) { return fwrite(data, (size_t)sz, (size_t)count, f); }
#endif // #ifndef IMGUI_DISABLE_DEFAULT_FILE_FUNCTIONS
// Helper: Load file content into memory
// Memory allocated with IM_ALLOC(), must be freed by user using IM_FREE() == ImGui::MemFree()
// This can't really be used with "rt" because fseek size won't match read size.
void* ImFileLoadToMemory(const char* filename, const char* mode, size_t* out_file_size, int padding_bytes)
{
IM_ASSERT(filename && mode);
if (out_file_size)
*out_file_size = 0;
ImFileHandle f;
if ((f = ImFileOpen(filename, mode)) == NULL)
return NULL;
size_t file_size = (size_t)ImFileGetSize(f);
if (file_size == (size_t)-1)
{
ImFileClose(f);
return NULL;
}
void* file_data = IM_ALLOC(file_size + padding_bytes);
if (file_data == NULL)
{
ImFileClose(f);
return NULL;
}
if (ImFileRead(file_data, 1, file_size, f) != file_size)
{
ImFileClose(f);
IM_FREE(file_data);
return NULL;
}
if (padding_bytes > 0)
memset((void*)(((char*)file_data) + file_size), 0, (size_t)padding_bytes);
ImFileClose(f);
if (out_file_size)
*out_file_size = file_size;
return file_data;
}
//-----------------------------------------------------------------------------
// [SECTION] MISC HELPERS/UTILITIES (ImText* functions)
//-----------------------------------------------------------------------------
// Convert UTF-8 to 32-bit 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 = IM_UNICODE_CODEPOINT_INVALID; // 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 = IM_UNICODE_CODEPOINT_INVALID; // 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 = IM_UNICODE_CODEPOINT_INVALID; // 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;
// If codepoint does not fit in ImWchar, use replacement character U+FFFD instead
if (c > IM_UNICODE_CODEPOINT_MAX) c = IM_UNICODE_CODEPOINT_INVALID;
*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;
*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;
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 < 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;
}
if (c <= 0x10FFFF)
{
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;
}
// Invalid code point, the max unicode is 0x10FFFF
return 0;
}
// Not optimal but we very rarely use this function.
int ImTextCountUtf8BytesFromChar(const char* in_text, const char* in_text_end)
{
unsigned int dummy = 0;
return ImTextCharFromUtf8(&dummy, in_text, in_text_end);
}
static inline int ImTextCountUtf8BytesFromChar(unsigned int c)
{
if (c < 0x80) return 1;
if (c < 0x800) return 2;
if (c < 0x10000) return 3;
if (c <= 0x10FFFF) return 4;
return 3;
}
int ImTextStrToUtf8(char* buf, int buf_size, const ImWchar* in_text, const ImWchar* in_text_end)
{
char* buf_out = buf;
const char* buf_end = buf + buf_size;
while (buf_out < buf_end-1 && (!in_text_end || in_text < in_text_end) && *in_text)
{
unsigned int c = (unsigned int)(*in_text++);
if (c < 0x80)
*buf_out++ = (char)c;
else
buf_out += ImTextCharToUtf8(buf_out, (int)(buf_end-buf_out-1), c);
}
*buf_out = 0;
return (int)(buf_out - buf);
}
int ImTextCountUtf8BytesFromStr(const ImWchar* in_text, const ImWchar* in_text_end)
{
int bytes_count = 0;
while ((!in_text_end || in_text < in_text_end) && *in_text)
{
unsigned int c = (unsigned int)(*in_text++);
if (c < 0x80)
bytes_count++;
else
bytes_count += ImTextCountUtf8BytesFromChar(c);
}
return bytes_count;
}
//-----------------------------------------------------------------------------
// [SECTION] MISC HELPERS/UTILITIES (Color functions)
// Note: The Convert functions are early design which are not consistent with other API.
//-----------------------------------------------------------------------------
IMGUI_API ImU32 ImAlphaBlendColors(ImU32 col_a, ImU32 col_b)
{
float t = ((col_b >> IM_COL32_A_SHIFT) & 0xFF) / 255.f;
int r = ImLerp((int)(col_a >> IM_COL32_R_SHIFT) & 0xFF, (int)(col_b >> IM_COL32_R_SHIFT) & 0xFF, t);
int g = ImLerp((int)(col_a >> IM_COL32_G_SHIFT) & 0xFF, (int)(col_b >> IM_COL32_G_SHIFT) & 0xFF, t);
int b = ImLerp((int)(col_a >> IM_COL32_B_SHIFT) & 0xFF, (int)(col_b >> IM_COL32_B_SHIFT) & 0xFF, t);
return IM_COL32(r, g, b, 0xFF);
}
ImVec4 ImGui::ColorConvertU32ToFloat4(ImU32 in)
{
float s = 1.0f/255.0f;
return ImVec4(
((in >> IM_COL32_R_SHIFT) & 0xFF) * s,
((in >> IM_COL32_G_SHIFT) & 0xFF) * s,
((in >> IM_COL32_B_SHIFT) & 0xFF) * s,
((in >> IM_COL32_A_SHIFT) & 0xFF) * s);
}
ImU32 ImGui::ColorConvertFloat4ToU32(const ImVec4& in)
{
ImU32 out;
out = ((ImU32)IM_F32_TO_INT8_SAT(in.x)) << IM_COL32_R_SHIFT;
out |= ((ImU32)IM_F32_TO_INT8_SAT(in.y)) << IM_COL32_G_SHIFT;
out |= ((ImU32)IM_F32_TO_INT8_SAT(in.z)) << IM_COL32_B_SHIFT;
out |= ((ImU32)IM_F32_TO_INT8_SAT(in.w)) << IM_COL32_A_SHIFT;
return out;
}
// Convert rgb floats ([0-1],[0-1],[0-1]) to hsv floats ([0-1],[0-1],[0-1]), from Foley & van Dam p592
// Optimized http://lolengine.net/blog/2013/01/13/fast-rgb-to-hsv
void ImGui::ColorConvertRGBtoHSV(float r, float g, float b, float& out_h, float& out_s, float& out_v)
{
float K = 0.f;
if (g < b)
{
ImSwap(g, b);
K = -1.f;
}
if (r < g)
{
ImSwap(r, g);
K = -2.f / 6.f - K;
}
const float chroma = r - (g < b ? g : b);
out_h = ImFabs(K + (g - b) / (6.f * chroma + 1e-20f));
out_s = chroma / (r + 1e-20f);
out_v = r;
}
// Convert hsv floats ([0-1],[0-1],[0-1]) to rgb floats ([0-1],[0-1],[0-1]), from Foley & van Dam p593
// also http://en.wikipedia.org/wiki/HSL_and_HSV
void ImGui::ColorConvertHSVtoRGB(float h, float s, float v, float& out_r, float& out_g, float& out_b)
{
if (s == 0.0f)
{
// gray
out_r = out_g = out_b = v;
return;
}
h = ImFmod(h, 1.0f) / (60.0f/360.0f);
int i = (int)h;
float f = h - (float)i;
float p = v * (1.0f - s);
float q = v * (1.0f - s * f);
float t = v * (1.0f - s * (1.0f - f));
switch (i)
{
case 0: out_r = v; out_g = t; out_b = p; break;
case 1: out_r = q; out_g = v; out_b = p; break;
case 2: out_r = p; out_g = v; out_b = t; break;
case 3: out_r = p; out_g = q; out_b = v; break;
case 4: out_r = t; out_g = p; out_b = v; break;
case 5: default: out_r = v; out_g = p; out_b = q; break;
}
}
//-----------------------------------------------------------------------------
// [SECTION] ImGuiStorage
// Helper: Key->value storage
//-----------------------------------------------------------------------------
// std::lower_bound but without the bullshit
static ImGuiStorage::ImGuiStoragePair* LowerBound(ImVector<ImGuiStorage::ImGuiStoragePair>& data, ImGuiID key)
{
ImGuiStorage::ImGuiStoragePair* first = data.Data;
ImGuiStorage::ImGuiStoragePair* last = data.Data + data.Size;
size_t count = (size_t)(last - first);
while (count > 0)
{
size_t count2 = count >> 1;
ImGuiStorage::ImGuiStoragePair* mid = first + count2;
if (mid->key < key)
{
first = ++mid;
count -= count2 + 1;
}
else
{
count = count2;
}
}
return first;
}
// For quicker full rebuild of a storage (instead of an incremental one), you may add all your contents and then sort once.
void ImGuiStorage::BuildSortByKey()
{
struct StaticFunc
{
static int IMGUI_CDECL PairCompareByID(const void* lhs, const void* rhs)
{
// We can't just do a subtraction because qsort uses signed integers and subtracting our ID doesn't play well with that.
if (((const ImGuiStoragePair*)lhs)->key > ((const ImGuiStoragePair*)rhs)->key) return +1;
if (((const ImGuiStoragePair*)lhs)->key < ((const ImGuiStoragePair*)rhs)->key) return -1;
return 0;
}
};
if (Data.Size > 1)
ImQsort(Data.Data, (size_t)Data.Size, sizeof(ImGuiStoragePair), StaticFunc::PairCompareByID);
}
int ImGuiStorage::GetInt(ImGuiID key, int default_val) const
{
ImGuiStoragePair* it = LowerBound(const_cast<ImVector<ImGuiStoragePair>&>(Data), key);
if (it == Data.end() || it->key != key)
return default_val;
return it->val_i;
}
bool ImGuiStorage::GetBool(ImGuiID key, bool default_val) const
{
return GetInt(key, default_val ? 1 : 0) != 0;
}
float ImGuiStorage::GetFloat(ImGuiID key, float default_val) const
{
ImGuiStoragePair* it = LowerBound(const_cast<ImVector<ImGuiStoragePair>&>(Data), key);
if (it == Data.end() || it->key != key)
return default_val;
return it->val_f;
}
void* ImGuiStorage::GetVoidPtr(ImGuiID key) const
{
ImGuiStoragePair* it = LowerBound(const_cast<ImVector<ImGuiStoragePair>&>(Data), key);
if (it == Data.end() || it->key != key)
return NULL;
return it->val_p;
}
// References are only valid until a new value is added to the storage. Calling a Set***() function or a Get***Ref() function invalidates the pointer.
int* ImGuiStorage::GetIntRef(ImGuiID key, int default_val)
{
ImGuiStoragePair* it = LowerBound(Data, key);
if (it == Data.end() || it->key != key)
it = Data.insert(it, ImGuiStoragePair(key, default_val));
return &it->val_i;
}
bool* ImGuiStorage::GetBoolRef(ImGuiID key, bool default_val)
{
return (bool*)GetIntRef(key, default_val ? 1 : 0);
}
float* ImGuiStorage::GetFloatRef(ImGuiID key, float default_val)
{
ImGuiStoragePair* it = LowerBound(Data, key);
if (it == Data.end() || it->key != key)
it = Data.insert(it, ImGuiStoragePair(key, default_val));
return &it->val_f;
}
void** ImGuiStorage::GetVoidPtrRef(ImGuiID key, void* default_val)
{
ImGuiStoragePair* it = LowerBound(Data, key);
if (it == Data.end() || it->key != key)
it = Data.insert(it, ImGuiStoragePair(key, default_val));
return &it->val_p;
}
// FIXME-OPT: Need a way to reuse the result of lower_bound when doing GetInt()/SetInt() - not too bad because it only happens on explicit interaction (maximum one a frame)
void ImGuiStorage::SetInt(ImGuiID key, int val)
{
ImGuiStoragePair* it = LowerBound(Data, key);
if (it == Data.end() || it->key != key)
{
Data.insert(it, ImGuiStoragePair(key, val));
return;
}
it->val_i = val;
}
void ImGuiStorage::SetBool(ImGuiID key, bool val)
{
SetInt(key, val ? 1 : 0);
}
void ImGuiStorage::SetFloat(ImGuiID key, float val)
{
ImGuiStoragePair* it = LowerBound(Data, key);
if (it == Data.end() || it->key != key)
{
Data.insert(it, ImGuiStoragePair(key, val));
return;
}
it->val_f = val;
}
void ImGuiStorage::SetVoidPtr(ImGuiID key, void* val)
{
ImGuiStoragePair* it = LowerBound(Data, key);
if (it == Data.end() || it->key != key)
{
Data.insert(it, ImGuiStoragePair(key, val));
return;
}
it->val_p = val;
}
void ImGuiStorage::SetAllInt(int v)
{
for (int i = 0; i < Data.Size; i++)
Data[i].val_i = v;
}
//-----------------------------------------------------------------------------
// [SECTION] ImGuiTextFilter
//-----------------------------------------------------------------------------
// Helper: Parse and apply text filters. In format "aaaaa[,bbbb][,ccccc]"
ImGuiTextFilter::ImGuiTextFilter(const char* default_filter)
{
if (default_filter)
{
ImStrncpy(InputBuf, default_filter, IM_ARRAYSIZE(InputBuf));
Build();
}
else
{
InputBuf[0] = 0;
CountGrep = 0;
}
}
bool ImGuiTextFilter::Draw(const char* label, float width)
{
if (width != 0.0f)
ImGui::SetNextItemWidth(width);
bool value_changed = ImGui::InputText(label, InputBuf, IM_ARRAYSIZE(InputBuf));
if (value_changed)
Build();
return value_changed;
}
void ImGuiTextFilter::ImGuiTextRange::split(char separator, ImVector<ImGuiTextRange>* out) const
{
out->resize(0);
const char* wb = b;
const char* we = wb;
while (we < e)
{
if (*we == separator)
{
out->push_back(ImGuiTextRange(wb, we));
wb = we + 1;
}
we++;
}
if (wb != we)
out->push_back(ImGuiTextRange(wb, we));
}
void ImGuiTextFilter::Build()
{
Filters.resize(0);
ImGuiTextRange input_range(InputBuf, InputBuf+strlen(InputBuf));
input_range.split(',', &Filters);
CountGrep = 0;
for (int i = 0; i != Filters.Size; i++)
{
ImGuiTextRange& f = Filters[i];
while (f.b < f.e && ImCharIsBlankA(f.b[0]))
f.b++;
while (f.e > f.b && ImCharIsBlankA(f.e[-1]))
f.e--;
if (f.empty())
continue;
if (Filters[i].b[0] != '-')
CountGrep += 1;
}
}
bool ImGuiTextFilter::PassFilter(const char* text, const char* text_end) const
{
if (Filters.empty())
return true;
if (text == NULL)
text = "";
for (int i = 0; i != Filters.Size; i++)
{
const ImGuiTextRange& f = Filters[i];
if (f.empty())
continue;
if (f.b[0] == '-')
{
// Subtract
if (ImStristr(text, text_end, f.b + 1, f.e) != NULL)
return false;
}
else
{
// Grep
if (ImStristr(text, text_end, f.b, f.e) != NULL)
return true;
}
}
// Implicit * grep
if (CountGrep == 0)
return true;
return false;
}
//-----------------------------------------------------------------------------
// [SECTION] ImGuiTextBuffer
//-----------------------------------------------------------------------------
// On some platform vsnprintf() takes va_list by reference and modifies it.
// va_copy is the 'correct' way to copy a va_list but Visual Studio prior to 2013 doesn't have it.
#ifndef va_copy
#if defined(__GNUC__) || defined(__clang__)
#define va_copy(dest, src) __builtin_va_copy(dest, src)
#else
#define va_copy(dest, src) (dest = src)
#endif
#endif
char ImGuiTextBuffer::EmptyString[1] = { 0 };
void ImGuiTextBuffer::append(const char* str, const char* str_end)
{
int len = str_end ? (int)(str_end - str) : (int)strlen(str);
// Add zero-terminator the first time
const int write_off = (Buf.Size != 0) ? Buf.Size : 1;
const int needed_sz = write_off + len;
if (write_off + len >= Buf.Capacity)
{
int new_capacity = Buf.Capacity * 2;
Buf.reserve(needed_sz > new_capacity ? needed_sz : new_capacity);
}
Buf.resize(needed_sz);
memcpy(&Buf[write_off - 1], str, (size_t)len);
Buf[write_off - 1 + len] = 0;
}
void ImGuiTextBuffer::appendf(const char* fmt, ...)
{
va_list args;
va_start(args, fmt);
appendfv(fmt, args);
va_end(args);
}
// Helper: Text buffer for logging/accumulating text
void ImGuiTextBuffer::appendfv(const char* fmt, va_list args)
{
va_list args_copy;
va_copy(args_copy, args);
int len = ImFormatStringV(NULL, 0, fmt, args); // FIXME-OPT: could do a first pass write attempt, likely successful on first pass.
if (len <= 0)
{
va_end(args_copy);
return;
}
// Add zero-terminator the first time
const int write_off = (Buf.Size != 0) ? Buf.Size : 1;
const int needed_sz = write_off + len;
if (write_off + len >= Buf.Capacity)
{
int new_capacity = Buf.Capacity * 2;
Buf.reserve(needed_sz > new_capacity ? needed_sz : new_capacity);
}
Buf.resize(needed_sz);
ImFormatStringV(&Buf[write_off - 1], (size_t)len + 1, fmt, args_copy);
va_end(args_copy);
}
//-----------------------------------------------------------------------------
// [SECTION] ImGuiListClipper
// This is currently not as flexible/powerful as it should be and really confusing/spaghetti, mostly because we changed
// the API mid-way through development and support two ways to using the clipper, needs some rework (see TODO)
//-----------------------------------------------------------------------------
// Helper to calculate coarse clipping of large list of evenly sized items.
// NB: Prefer using the ImGuiListClipper higher-level helper if you can! Read comments and instructions there on how those use this sort of pattern.
// NB: 'items_count' is only used to clamp the result, if you don't know your count you can use INT_MAX
void ImGui::CalcListClipping(int items_count, float items_height, int* out_items_display_start, int* out_items_display_end)
{
ImGuiContext& g = *GImGui;
ImGuiWindow* window = g.CurrentWindow;
if (g.LogEnabled)
{
// If logging is active, do not perform any clipping
*out_items_display_start = 0;
*out_items_display_end = items_count;
return;
}
if (window->SkipItems)
{
*out_items_display_start = *out_items_display_end = 0;
return;
}
// We create the union of the ClipRect and the NavScoringRect which at worst should be 1 page away from ClipRect
ImRect unclipped_rect = window->ClipRect;
if (g.NavMoveRequest)
unclipped_rect.Add(g.NavScoringRectScreen);
const ImVec2 pos = window->DC.CursorPos;
int start = (int)((unclipped_rect.Min.y - pos.y) / items_height);
int end = (int)((unclipped_rect.Max.y - pos.y) / items_height);
// When performing a navigation request, ensure we have one item extra in the direction we are moving to
if (g.NavMoveRequest && g.NavMoveClipDir == ImGuiDir_Up)
start--;
if (g.NavMoveRequest && g.NavMoveClipDir == ImGuiDir_Down)
end++;
start = ImClamp(start, 0, items_count);
end = ImClamp(end + 1, start, items_count);
*out_items_display_start = start;
*out_items_display_end = end;
}
static void SetCursorPosYAndSetupDummyPrevLine(float pos_y, float line_height)
{
// Set cursor position and a few other things so that SetScrollHereY() and Columns() can work when seeking cursor.
// FIXME: It is problematic that we have to do that here, because custom/equivalent end-user code would stumble on the same issue.
// The clipper should probably have a 4th step to display the last item in a regular manner.
ImGuiContext& g = *GImGui;
ImGuiWindow* window = g.CurrentWindow;
window->DC.CursorPos.y = pos_y;
window->DC.CursorMaxPos.y = ImMax(window->DC.CursorMaxPos.y, pos_y);
window->DC.CursorPosPrevLine.y = window->DC.CursorPos.y - line_height; // Setting those fields so that SetScrollHereY() can properly function after the end of our clipper usage.
window->DC.PrevLineSize.y = (line_height - g.Style.ItemSpacing.y); // If we end up needing more accurate data (to e.g. use SameLine) we may as well make the clipper have a fourth step to let user process and display the last item in their list.
if (ImGuiColumns* columns = window->DC.CurrentColumns)
columns->LineMinY = window->DC.CursorPos.y; // Setting this so that cell Y position are set properly
}
// Use case A: Begin() called from constructor with items_height<0, then called again from Sync() in StepNo 1
// Use case B: Begin() called from constructor with items_height>0
// FIXME-LEGACY: Ideally we should remove the Begin/End functions but they are part of the legacy API we still support. This is why some of the code in Step() calling Begin() and reassign some fields, spaghetti style.
void ImGuiListClipper::Begin(int count, float items_height)
{
ImGuiContext& g = *GImGui;
ImGuiWindow* window = g.CurrentWindow;
StartPosY = window->DC.CursorPos.y;
ItemsHeight = items_height;
ItemsCount = count;
StepNo = 0;
DisplayEnd = DisplayStart = -1;
if (ItemsHeight > 0.0f)
{
ImGui::CalcListClipping(ItemsCount, ItemsHeight, &DisplayStart, &DisplayEnd); // calculate how many to clip/display
if (DisplayStart > 0)
SetCursorPosYAndSetupDummyPrevLine(StartPosY + DisplayStart * ItemsHeight, ItemsHeight); // advance cursor
StepNo = 2;
}
}
void ImGuiListClipper::End()
{
if (ItemsCount < 0)
return;
// In theory here we should assert that ImGui::GetCursorPosY() == StartPosY + DisplayEnd * ItemsHeight, but it feels saner to just seek at the end and not assert/crash the user.
if (ItemsCount < INT_MAX)
SetCursorPosYAndSetupDummyPrevLine(StartPosY + ItemsCount * ItemsHeight, ItemsHeight); // advance cursor
ItemsCount = -1;
StepNo = 3;
}
bool ImGuiListClipper::Step()
{
ImGuiContext& g = *GImGui;
ImGuiWindow* window = g.CurrentWindow;
if (ItemsCount == 0 || window->SkipItems)
{
ItemsCount = -1;
return false;
}
if (StepNo == 0) // Step 0: the clipper let you process the first element, regardless of it being visible or not, so we can measure the element height.
{
DisplayStart = 0;
DisplayEnd = 1;
StartPosY = window->DC.CursorPos.y;
StepNo = 1;
return true;
}
if (StepNo == 1) // Step 1: the clipper infer height from first element, calculate the actual range of elements to display, and position the cursor before the first element.
{
if (ItemsCount == 1) { ItemsCount = -1; return false; }
float items_height = window->DC.CursorPos.y - StartPosY;
IM_ASSERT(items_height > 0.0f); // If this triggers, it means Item 0 hasn't moved the cursor vertically
Begin(ItemsCount - 1, items_height);
DisplayStart++;
DisplayEnd++;
StepNo = 3;
return true;
}
if (StepNo == 2) // Step 2: dummy step only required if an explicit items_height was passed to constructor or Begin() and user still call Step(). Does nothing and switch to Step 3.
{
IM_ASSERT(DisplayStart >= 0 && DisplayEnd >= 0);
StepNo = 3;
return true;
}
if (StepNo == 3) // Step 3: the clipper validate that we have reached the expected Y position (corresponding to element DisplayEnd), advance the cursor to the end of the list and then returns 'false' to end the loop.
End();
return false;
}
//-----------------------------------------------------------------------------
// [SECTION] STYLING
//-----------------------------------------------------------------------------
ImGuiStyle& ImGui::GetStyle()
{
IM_ASSERT(GImGui != NULL && "No current context. Did you call ImGui::CreateContext() and ImGui::SetCurrentContext() ?");
return GImGui->Style;
}
ImU32 ImGui::GetColorU32(ImGuiCol idx, float alpha_mul)
{
ImGuiStyle& style = GImGui->Style;
ImVec4 c = style.Colors[idx];
c.w *= style.Alpha * alpha_mul;
return ColorConvertFloat4ToU32(c);
}
ImU32 ImGui::GetColorU32(const ImVec4& col)
{
ImGuiStyle& style = GImGui->Style;
ImVec4 c = col;
c.w *= style.Alpha;
return ColorConvertFloat4ToU32(c);
}
const ImVec4& ImGui::GetStyleColorVec4(ImGuiCol idx)
{
ImGuiStyle& style = GImGui->Style;
return style.Colors[idx];
}
ImU32 ImGui::GetColorU32(ImU32 col)
{
ImGuiStyle& style = GImGui->Style;
if (style.Alpha >= 1.0f)
return col;
ImU32 a = (col & IM_COL32_A_MASK) >> IM_COL32_A_SHIFT;
a = (ImU32)(a * style.Alpha); // We don't need to clamp 0..255 because Style.Alpha is in 0..1 range.
return (col & ~IM_COL32_A_MASK) | (a << IM_COL32_A_SHIFT);
}
// FIXME: This may incur a round-trip (if the end user got their data from a float4) but eventually we aim to store the in-flight colors as ImU32
void ImGui::PushStyleColor(ImGuiCol idx, ImU32 col)
{
ImGuiContext& g = *GImGui;
ImGuiColorMod backup;
backup.Col = idx;
backup.BackupValue = g.Style.Colors[idx];
g.ColorModifiers.push_back(backup);
g.Style.Colors[idx] = ColorConvertU32ToFloat4(col);
}
void ImGui::PushStyleColor(ImGuiCol idx, const ImVec4& col)
{
ImGuiContext& g = *GImGui;
ImGuiColorMod backup;
backup.Col = idx;
backup.BackupValue = g.Style.Colors[idx];
g.ColorModifiers.push_back(backup);
g.Style.Colors[idx] = col;
}
void ImGui::PopStyleColor(int count)
{
ImGuiContext& g = *GImGui;
while (count > 0)
{
ImGuiColorMod& backup = g.ColorModifiers.back();
g.Style.Colors[backup.Col] = backup.BackupValue;
g.ColorModifiers.pop_back();
count--;
}
}
struct ImGuiStyleVarInfo
{
ImGuiDataType Type;
ImU32 Count;
ImU32 Offset;
void* GetVarPtr(ImGuiStyle* style) const { return (void*)((unsigned char*)style + Offset); }
};
static const ImGuiStyleVarInfo GStyleVarInfo[] =
{
{ ImGuiDataType_Float, 1, (ImU32)IM_OFFSETOF(ImGuiStyle, Alpha) }, // ImGuiStyleVar_Alpha
{ ImGuiDataType_Float, 2, (ImU32)IM_OFFSETOF(ImGuiStyle, WindowPadding) }, // ImGuiStyleVar_WindowPadding
{ ImGuiDataType_Float, 1, (ImU32)IM_OFFSETOF(ImGuiStyle, WindowRounding) }, // ImGuiStyleVar_WindowRounding
{ ImGuiDataType_Float, 1, (ImU32)IM_OFFSETOF(ImGuiStyle, WindowBorderSize) }, // ImGuiStyleVar_WindowBorderSize
{ ImGuiDataType_Float, 2, (ImU32)IM_OFFSETOF(ImGuiStyle, WindowMinSize) }, // ImGuiStyleVar_WindowMinSize
{ ImGuiDataType_Float, 2, (ImU32)IM_OFFSETOF(ImGuiStyle, WindowTitleAlign) }, // ImGuiStyleVar_WindowTitleAlign
{ ImGuiDataType_Float, 1, (ImU32)IM_OFFSETOF(ImGuiStyle, ChildRounding) }, // ImGuiStyleVar_ChildRounding
{ ImGuiDataType_Float, 1, (ImU32)IM_OFFSETOF(ImGuiStyle, ChildBorderSize) }, // ImGuiStyleVar_ChildBorderSize
{ ImGuiDataType_Float, 1, (ImU32)IM_OFFSETOF(ImGuiStyle, PopupRounding) }, // ImGuiStyleVar_PopupRounding
{ ImGuiDataType_Float, 1, (ImU32)IM_OFFSETOF(ImGuiStyle, PopupBorderSize) }, // ImGuiStyleVar_PopupBorderSize
{ ImGuiDataType_Float, 2, (ImU32)IM_OFFSETOF(ImGuiStyle, FramePadding) }, // ImGuiStyleVar_FramePadding
{ ImGuiDataType_Float, 1, (ImU32)IM_OFFSETOF(ImGuiStyle, FrameRounding) }, // ImGuiStyleVar_FrameRounding
{ ImGuiDataType_Float, 1, (ImU32)IM_OFFSETOF(ImGuiStyle, FrameBorderSize) }, // ImGuiStyleVar_FrameBorderSize
{ ImGuiDataType_Float, 2, (ImU32)IM_OFFSETOF(ImGuiStyle, ItemSpacing) }, // ImGuiStyleVar_ItemSpacing
{ ImGuiDataType_Float, 2, (ImU32)IM_OFFSETOF(ImGuiStyle, ItemInnerSpacing) }, // ImGuiStyleVar_ItemInnerSpacing
{ ImGuiDataType_Float, 1, (ImU32)IM_OFFSETOF(ImGuiStyle, IndentSpacing) }, // ImGuiStyleVar_IndentSpacing
{ ImGuiDataType_Float, 1, (ImU32)IM_OFFSETOF(ImGuiStyle, ScrollbarSize) }, // ImGuiStyleVar_ScrollbarSize
{ ImGuiDataType_Float, 1, (ImU32)IM_OFFSETOF(ImGuiStyle, ScrollbarRounding) }, // ImGuiStyleVar_ScrollbarRounding
{ ImGuiDataType_Float, 1, (ImU32)IM_OFFSETOF(ImGuiStyle, GrabMinSize) }, // ImGuiStyleVar_GrabMinSize
{ ImGuiDataType_Float, 1, (ImU32)IM_OFFSETOF(ImGuiStyle, GrabRounding) }, // ImGuiStyleVar_GrabRounding
{ ImGuiDataType_Float, 1, (ImU32)IM_OFFSETOF(ImGuiStyle, TabRounding) }, // ImGuiStyleVar_TabRounding
{ ImGuiDataType_Float, 2, (ImU32)IM_OFFSETOF(ImGuiStyle, ButtonTextAlign) }, // ImGuiStyleVar_ButtonTextAlign
{ ImGuiDataType_Float, 2, (ImU32)IM_OFFSETOF(ImGuiStyle, SelectableTextAlign) }, // ImGuiStyleVar_SelectableTextAlign
};
static const ImGuiStyleVarInfo* GetStyleVarInfo(ImGuiStyleVar idx)
{
IM_ASSERT(idx >= 0 && idx < ImGuiStyleVar_COUNT);
IM_ASSERT(IM_ARRAYSIZE(GStyleVarInfo) == ImGuiStyleVar_COUNT);
return &GStyleVarInfo[idx];
}
void ImGui::PushStyleVar(ImGuiStyleVar idx, float val)
{
const ImGuiStyleVarInfo* var_info = GetStyleVarInfo(idx);
if (var_info->Type == ImGuiDataType_Float && var_info->Count == 1)
{
ImGuiContext& g = *GImGui;
float* pvar = (float*)var_info->GetVarPtr(&g.Style);
g.StyleModifiers.push_back(ImGuiStyleMod(idx, *pvar));
*pvar = val;
return;
}
IM_ASSERT(0 && "Called PushStyleVar() float variant but variable is not a float!");
}
void ImGui::PushStyleVar(ImGuiStyleVar idx, const ImVec2& val)
{
const ImGuiStyleVarInfo* var_info = GetStyleVarInfo(idx);
if (var_info->Type == ImGuiDataType_Float && var_info->Count == 2)
{
ImGuiContext& g = *GImGui;
ImVec2* pvar = (ImVec2*)var_info->GetVarPtr(&g.Style);
g.StyleModifiers.push_back(ImGuiStyleMod(idx, *pvar));
*pvar = val;
return;
}
IM_ASSERT(0 && "Called PushStyleVar() ImVec2 variant but variable is not a ImVec2!");
}
void ImGui::PopStyleVar(int count)
{
ImGuiContext& g = *GImGui;
while (count > 0)
{
// We avoid a generic memcpy(data, &backup.Backup.., GDataTypeSize[info->Type] * info->Count), the overhead in Debug is not worth it.
ImGuiStyleMod& backup = g.StyleModifiers.back();
const ImGuiStyleVarInfo* info = GetStyleVarInfo(backup.VarIdx);
void* data = info->GetVarPtr(&g.Style);
if (info->Type == ImGuiDataType_Float && info->Count == 1) { ((float*)data)[0] = backup.BackupFloat[0]; }
else if (info->Type == ImGuiDataType_Float && info->Count == 2) { ((float*)data)[0] = backup.BackupFloat[0]; ((float*)data)[1] = backup.BackupFloat[1]; }
g.StyleModifiers.pop_back();
count--;
}
}
const char* ImGui::GetStyleColorName(ImGuiCol idx)
{
// Create switch-case from enum with regexp: ImGuiCol_{.*}, --> case ImGuiCol_\1: return "\1";
switch (idx)
{
case ImGuiCol_Text: return "Text";
case ImGuiCol_TextDisabled: return "TextDisabled";
case ImGuiCol_WindowBg: return "WindowBg";
case ImGuiCol_ChildBg: return "ChildBg";
case ImGuiCol_PopupBg: return "PopupBg";
case ImGuiCol_Border: return "Border";
case ImGuiCol_BorderShadow: return "BorderShadow";
case ImGuiCol_FrameBg: return "FrameBg";
case ImGuiCol_FrameBgHovered: return "FrameBgHovered";
case ImGuiCol_FrameBgActive: return "FrameBgActive";
case ImGuiCol_TitleBg: return "TitleBg";
case ImGuiCol_TitleBgActive: return "TitleBgActive";
case ImGuiCol_TitleBgCollapsed: return "TitleBgCollapsed";
case ImGuiCol_MenuBarBg: return "MenuBarBg";
case ImGuiCol_ScrollbarBg: return "ScrollbarBg";
case ImGuiCol_ScrollbarGrab: return "ScrollbarGrab";
case ImGuiCol_ScrollbarGrabHovered: return "ScrollbarGrabHovered";
case ImGuiCol_ScrollbarGrabActive: return "ScrollbarGrabActive";
case ImGuiCol_CheckMark: return "CheckMark";
case ImGuiCol_SliderGrab: return "SliderGrab";
case ImGuiCol_SliderGrabActive: return "SliderGrabActive";
case ImGuiCol_Button: return "Button";
case ImGuiCol_ButtonHovered: return "ButtonHovered";
case ImGuiCol_ButtonActive: return "ButtonActive";
case ImGuiCol_Header: return "Header";
case ImGuiCol_HeaderHovered: return "HeaderHovered";
case ImGuiCol_HeaderActive: return "HeaderActive";
case ImGuiCol_Separator: return "Separator";
case ImGuiCol_SeparatorHovered: return "SeparatorHovered";
case ImGuiCol_SeparatorActive: return "SeparatorActive";
case ImGuiCol_ResizeGrip: return "ResizeGrip";
case ImGuiCol_ResizeGripHovered: return "ResizeGripHovered";
case ImGuiCol_ResizeGripActive: return "ResizeGripActive";
case ImGuiCol_Tab: return "Tab";
case ImGuiCol_TabHovered: return "TabHovered";
case ImGuiCol_TabActive: return "TabActive";
case ImGuiCol_TabUnfocused: return "TabUnfocused";
case ImGuiCol_TabUnfocusedActive: return "TabUnfocusedActive";
case ImGuiCol_PlotLines: return "PlotLines";
case ImGuiCol_PlotLinesHovered: return "PlotLinesHovered";
case ImGuiCol_PlotHistogram: return "PlotHistogram";
case ImGuiCol_PlotHistogramHovered: return "PlotHistogramHovered";
case ImGuiCol_TextSelectedBg: return "TextSelectedBg";
case ImGuiCol_DragDropTarget: return "DragDropTarget";
case ImGuiCol_NavHighlight: return "NavHighlight";
case ImGuiCol_NavWindowingHighlight: return "NavWindowingHighlight";
case ImGuiCol_NavWindowingDimBg: return "NavWindowingDimBg";
case ImGuiCol_ModalWindowDimBg: return "ModalWindowDimBg";
}
IM_ASSERT(0);
return "Unknown";
}
//-----------------------------------------------------------------------------
// [SECTION] RENDER HELPERS
// Some of those (internal) functions are currently quite a legacy mess - their signature and behavior will change,
// we need a nicer separation between low-level functions and high-level functions relying on the ImGui context.
// Also see imgui_draw.cpp for some more which have been reworked to not rely on ImGui:: context.
//-----------------------------------------------------------------------------
const char* ImGui::FindRenderedTextEnd(const char* text, const char* text_end)
{
const char* text_display_end = text;
if (!text_end)
text_end = (const char*)-1;
while (text_display_end < text_end && *text_display_end != '\0' && (text_display_end[0] != '#' || text_display_end[1] != '#'))
text_display_end++;
return text_display_end;
}
// Internal ImGui functions to render text
// RenderText***() functions calls ImDrawList::AddText() calls ImBitmapFont::RenderText()
void ImGui::RenderText(ImVec2 pos, const char* text, const char* text_end, bool hide_text_after_hash)
{
ImGuiContext& g = *GImGui;
ImGuiWindow* window = g.CurrentWindow;
// Hide anything after a '##' string
const char* text_display_end;
if (hide_text_after_hash)
{
text_display_end = FindRenderedTextEnd(text, text_end);
}
else
{
if (!text_end)
text_end = text + strlen(text); // FIXME-OPT
text_display_end = text_end;
}
if (text != text_display_end)
{
window->DrawList->AddText(g.Font, g.FontSize, pos, GetColorU32(ImGuiCol_Text), text, text_display_end);
if (g.LogEnabled)
LogRenderedText(&pos, text, text_display_end);
}
}
void ImGui::RenderTextWrapped(ImVec2 pos, const char* text, const char* text_end, float wrap_width)
{
ImGuiContext& g = *GImGui;
ImGuiWindow* window = g.CurrentWindow;
if (!text_end)
text_end = text + strlen(text); // FIXME-OPT
if (text != text_end)
{
window->DrawList->AddText(g.Font, g.FontSize, pos, GetColorU32(ImGuiCol_Text), text, text_end, wrap_width);
if (g.LogEnabled)
LogRenderedText(&pos, text, text_end);
}
}
// Default clip_rect uses (pos_min,pos_max)
// Handle clipping on CPU immediately (vs typically let the GPU clip the triangles that are overlapping the clipping rectangle edges)
void ImGui::RenderTextClippedEx(ImDrawList* draw_list, const ImVec2& pos_min, const ImVec2& pos_max, const char* text, const char* text_display_end, const ImVec2* text_size_if_known, const ImVec2& align, const ImRect* clip_rect)
{
// Perform CPU side clipping for single clipped element to avoid using scissor state
ImVec2 pos = pos_min;
const ImVec2 text_size = text_size_if_known ? *text_size_if_known : CalcTextSize(text, text_display_end, false, 0.0f);
const ImVec2* clip_min = clip_rect ? &clip_rect->Min : &pos_min;
const ImVec2* clip_max = clip_rect ? &clip_rect->Max : &pos_max;
bool need_clipping = (pos.x + text_size.x >= clip_max->x) || (pos.y + text_size.y >= clip_max->y);
if (clip_rect) // If we had no explicit clipping rectangle then pos==clip_min
need_clipping |= (pos.x < clip_min->x) || (pos.y < clip_min->y);
// Align whole block. We should defer that to the better rendering function when we'll have support for individual line alignment.
if (align.x > 0.0f) pos.x = ImMax(pos.x, pos.x + (pos_max.x - pos.x - text_size.x) * align.x);
if (align.y > 0.0f) pos.y = ImMax(pos.y, pos.y + (pos_max.y - pos.y - text_size.y) * align.y);
// Render
if (need_clipping)
{
ImVec4 fine_clip_rect(clip_min->x, clip_min->y, clip_max->x, clip_max->y);
draw_list->AddText(NULL, 0.0f, pos, GetColorU32(ImGuiCol_Text), text, text_display_end, 0.0f, &fine_clip_rect);
}
else
{
draw_list->AddText(NULL, 0.0f, pos, GetColorU32(ImGuiCol_Text), text, text_display_end, 0.0f, NULL);
}
}
void ImGui::RenderTextClipped(const ImVec2& pos_min, const ImVec2& pos_max, const char* text, const char* text_end, const ImVec2* text_size_if_known, const ImVec2& align, const ImRect* clip_rect)
{
// Hide anything after a '##' string
const char* text_display_end = FindRenderedTextEnd(text, text_end);
const int text_len = (int)(text_display_end - text);
if (text_len == 0)
return;
ImGuiContext& g = *GImGui;
ImGuiWindow* window = g.CurrentWindow;
RenderTextClippedEx(window->DrawList, pos_min, pos_max, text, text_display_end, text_size_if_known, align, clip_rect);
if (g.LogEnabled)
LogRenderedText(&pos_min, text, text_display_end);
}
// Another overly complex function until we reorganize everything into a nice all-in-one helper.
// This is made more complex because we have dissociated the layout rectangle (pos_min..pos_max) which define _where_ the ellipsis is, from actual clipping of text and limit of the ellipsis display.
// This is because in the context of tabs we selectively hide part of the text when the Close Button appears, but we don't want the ellipsis to move.
void ImGui::RenderTextEllipsis(ImDrawList* draw_list, const ImVec2& pos_min, const ImVec2& pos_max, float clip_max_x, float ellipsis_max_x, const char* text, const char* text_end_full, const ImVec2* text_size_if_known)
{
ImGuiContext& g = *GImGui;
if (text_end_full == NULL)
text_end_full = FindRenderedTextEnd(text);
const ImVec2 text_size = text_size_if_known ? *text_size_if_known : CalcTextSize(text, text_end_full, false, 0.0f);
//draw_list->AddLine(ImVec2(pos_max.x, pos_min.y - 4), ImVec2(pos_max.x, pos_max.y + 4), IM_COL32(0, 0, 255, 255));
//draw_list->AddLine(ImVec2(ellipsis_max_x, pos_min.y-2), ImVec2(ellipsis_max_x, pos_max.y+2), IM_COL32(0, 255, 0, 255));
//draw_list->AddLine(ImVec2(clip_max_x, pos_min.y), ImVec2(clip_max_x, pos_max.y), IM_COL32(255, 0, 0, 255));
// FIXME: We could technically remove (last_glyph->AdvanceX - last_glyph->X1) from text_size.x here and save a few pixels.
if (text_size.x > pos_max.x - pos_min.x)
{
// Hello wo...
// | | |
// min max ellipsis_max
// <-> this is generally some padding value
const ImFont* font = draw_list->_Data->Font;
const float font_size = draw_list->_Data->FontSize;
const char* text_end_ellipsis = NULL;
ImWchar ellipsis_char = font->EllipsisChar;
int ellipsis_char_count = 1;
if (ellipsis_char == (ImWchar)-1)
{
ellipsis_char = (ImWchar)'.';
ellipsis_char_count = 3;
}
const ImFontGlyph* glyph = font->FindGlyph(ellipsis_char);
float ellipsis_glyph_width = glyph->X1; // Width of the glyph with no padding on either side
float ellipsis_total_width = ellipsis_glyph_width; // Full width of entire ellipsis
if (ellipsis_char_count > 1)
{
// Full ellipsis size without free spacing after it.
const float spacing_between_dots = 1.0f * (draw_list->_Data->FontSize / font->FontSize);
ellipsis_glyph_width = glyph->X1 - glyph->X0 + spacing_between_dots;
ellipsis_total_width = ellipsis_glyph_width * (float)ellipsis_char_count - spacing_between_dots;
}
// We can now claim the space between pos_max.x and ellipsis_max.x
const float text_avail_width = ImMax((ImMax(pos_max.x, ellipsis_max_x) - ellipsis_total_width) - pos_min.x, 1.0f);
float text_size_clipped_x = font->CalcTextSizeA(font_size, text_avail_width, 0.0f, text, text_end_full, &text_end_ellipsis).x;
if (text == text_end_ellipsis && text_end_ellipsis < text_end_full)
{
// Always display at least 1 character if there's no room for character + ellipsis
text_end_ellipsis = text + ImTextCountUtf8BytesFromChar(text, text_end_full);
text_size_clipped_x = font->CalcTextSizeA(font_size, FLT_MAX, 0.0f, text, text_end_ellipsis).x;
}
while (text_end_ellipsis > text && ImCharIsBlankA(text_end_ellipsis[-1]))
{
// Trim trailing space before ellipsis (FIXME: Supporting non-ascii blanks would be nice, for this we need a function to backtrack in UTF-8 text)
text_end_ellipsis--;
text_size_clipped_x -= font->CalcTextSizeA(font_size, FLT_MAX, 0.0f, text_end_ellipsis, text_end_ellipsis + 1).x; // Ascii blanks are always 1 byte
}
// Render text, render ellipsis
RenderTextClippedEx(draw_list, pos_min, ImVec2(clip_max_x, pos_max.y), text, text_end_ellipsis, &text_size, ImVec2(0.0f, 0.0f));
float ellipsis_x = pos_min.x + text_size_clipped_x;
if (ellipsis_x + ellipsis_total_width <= ellipsis_max_x)
for (int i = 0; i < ellipsis_char_count; i++)
{
font->RenderChar(draw_list, font_size, ImVec2(ellipsis_x, pos_min.y), GetColorU32(ImGuiCol_Text), ellipsis_char);
ellipsis_x += ellipsis_glyph_width;
}
}
else
{
RenderTextClippedEx(draw_list, pos_min, ImVec2(clip_max_x, pos_max.y), text, text_end_full, &text_size, ImVec2(0.0f, 0.0f));
}
if (g.LogEnabled)
LogRenderedText(&pos_min, text, text_end_full);
}
// Render a rectangle shaped with optional rounding and borders
void ImGui::RenderFrame(ImVec2 p_min, ImVec2 p_max, ImU32 fill_col, bool border, float rounding)
{
ImGuiContext& g = *GImGui;
ImGuiWindow* window = g.CurrentWindow;
window->DrawList->AddRectFilled(p_min, p_max, fill_col, rounding);
const float border_size = g.Style.FrameBorderSize;
if (border && border_size > 0.0f)
{
window->DrawList->AddRect(p_min+ImVec2(1,1), p_max+ImVec2(1,1), GetColorU32(ImGuiCol_BorderShadow), rounding, ImDrawCornerFlags_All, border_size);
window->DrawList->AddRect(p_min, p_max, GetColorU32(ImGuiCol_Border), rounding, ImDrawCornerFlags_All, border_size);
}
}
void ImGui::RenderFrameBorder(ImVec2 p_min, ImVec2 p_max, float rounding)
{
ImGuiContext& g = *GImGui;
ImGuiWindow* window = g.CurrentWindow;
const float border_size = g.Style.FrameBorderSize;
if (border_size > 0.0f)
{
window->DrawList->AddRect(p_min+ImVec2(1,1), p_max+ImVec2(1,1), GetColorU32(ImGuiCol_BorderShadow), rounding, ImDrawCornerFlags_All, border_size);
window->DrawList->AddRect(p_min, p_max, GetColorU32(ImGuiCol_Border), rounding, ImDrawCornerFlags_All, border_size);
}
}
void ImGui::RenderNavHighlight(const ImRect& bb, ImGuiID id, ImGuiNavHighlightFlags flags)
{
ImGuiContext& g = *GImGui;
if (id != g.NavId)
return;
if (g.NavDisableHighlight && !(flags & ImGuiNavHighlightFlags_AlwaysDraw))
return;
ImGuiWindow* window = g.CurrentWindow;
if (window->DC.NavHideHighlightOneFrame)
return;
float rounding = (flags & ImGuiNavHighlightFlags_NoRounding) ? 0.0f : g.Style.FrameRounding;
ImRect display_rect = bb;
display_rect.ClipWith(window->ClipRect);
if (flags & ImGuiNavHighlightFlags_TypeDefault)
{
const float THICKNESS = 2.0f;
const float DISTANCE = 3.0f + THICKNESS * 0.5f;
display_rect.Expand(ImVec2(DISTANCE,DISTANCE));
bool fully_visible = window->ClipRect.Contains(display_rect);
if (!fully_visible)
window->DrawList->PushClipRect(display_rect.Min, display_rect.Max);
window->DrawList->AddRect(display_rect.Min + ImVec2(THICKNESS*0.5f,THICKNESS*0.5f), display_rect.Max - ImVec2(THICKNESS*0.5f,THICKNESS*0.5f), GetColorU32(ImGuiCol_NavHighlight), rounding, ImDrawCornerFlags_All, THICKNESS);
if (!fully_visible)
window->DrawList->PopClipRect();
}
if (flags & ImGuiNavHighlightFlags_TypeThin)
{
window->DrawList->AddRect(display_rect.Min, display_rect.Max, GetColorU32(ImGuiCol_NavHighlight), rounding, ~0, 1.0f);
}
}
//-----------------------------------------------------------------------------
// [SECTION] MAIN CODE (most of the code! lots of stuff, needs tidying up!)
//-----------------------------------------------------------------------------
// ImGuiWindow is mostly a dumb struct. It merely has a constructor and a few helper methods
ImGuiWindow::ImGuiWindow(ImGuiContext* context, const char* name)
: DrawListInst(&context->DrawListSharedData)
{
Name = ImStrdup(name);
ID = ImHashStr(name);
IDStack.push_back(ID);
Flags = ImGuiWindowFlags_None;
Pos = ImVec2(0.0f, 0.0f);
Size = SizeFull = ImVec2(0.0f, 0.0f);
ContentSize = ContentSizeExplicit = ImVec2(0.0f, 0.0f);
WindowPadding = ImVec2(0.0f, 0.0f);
WindowRounding = 0.0f;
WindowBorderSize = 0.0f;
NameBufLen = (int)strlen(name) + 1;
MoveId = GetID("#MOVE");
ChildId = 0;
Scroll = ImVec2(0.0f, 0.0f);
ScrollTarget = ImVec2(FLT_MAX, FLT_MAX);
ScrollTargetCenterRatio = ImVec2(0.5f, 0.5f);
ScrollbarSizes = ImVec2(0.0f, 0.0f);
ScrollbarX = ScrollbarY = false;
Active = WasActive = false;
WriteAccessed = false;
Collapsed = false;
WantCollapseToggle = false;
SkipItems = false;
Appearing = false;
Hidden = false;
IsFallbackWindow = false;
HasCloseButton = false;
ResizeBorderHeld = -1;
BeginCount = 0;
BeginOrderWithinParent = -1;
BeginOrderWithinContext = -1;
PopupId = 0;
AutoFitFramesX = AutoFitFramesY = -1;
AutoFitChildAxises = 0x00;
AutoFitOnlyGrows = false;
AutoPosLastDirection = ImGuiDir_None;
HiddenFramesCanSkipItems = HiddenFramesCannotSkipItems = 0;
SetWindowPosAllowFlags = SetWindowSizeAllowFlags = SetWindowCollapsedAllowFlags = ImGuiCond_Always | ImGuiCond_Once | ImGuiCond_FirstUseEver | ImGuiCond_Appearing;
SetWindowPosVal = SetWindowPosPivot = ImVec2(FLT_MAX, FLT_MAX);
InnerRect = ImRect(0.0f, 0.0f, 0.0f, 0.0f); // Clear so the InnerRect.GetSize() code in Begin() doesn't lead to overflow even if the result isn't used.
LastFrameActive = -1;
LastTimeActive = -1.0f;
ItemWidthDefault = 0.0f;
FontWindowScale = 1.0f;
SettingsOffset = -1;
DrawList = &DrawListInst;
DrawList->_OwnerName = Name;
ParentWindow = NULL;
RootWindow = NULL;
RootWindowForTitleBarHighlight = NULL;
RootWindowForNav = NULL;
NavLastIds[0] = NavLastIds[1] = 0;
NavRectRel[0] = NavRectRel[1] = ImRect();
NavLastChildNavWindow = NULL;
MemoryCompacted = false;
MemoryDrawListIdxCapacity = MemoryDrawListVtxCapacity = 0;
}
ImGuiWindow::~ImGuiWindow()
{
IM_ASSERT(DrawList == &DrawListInst);
IM_DELETE(Name);
for (int i = 0; i != ColumnsStorage.Size; i++)
ColumnsStorage[i].~ImGuiColumns();
}
ImGuiID ImGuiWindow::GetID(const char* str, const char* str_end)
{
ImGuiID seed = IDStack.back();
ImGuiID id = ImHashStr(str, str_end ? (str_end - str) : 0, seed);
ImGui::KeepAliveID(id);
return id;
}
ImGuiID ImGuiWindow::GetID(const void* ptr)
{
ImGuiID seed = IDStack.back();
ImGuiID id = ImHashData(&ptr, sizeof(void*), seed);
ImGui::KeepAliveID(id);
return id;
}
ImGuiID ImGuiWindow::GetID(int n)
{
ImGuiID seed = IDStack.back();
ImGuiID id = ImHashData(&n, sizeof(n), seed);
ImGui::KeepAliveID(id);
return id;
}
ImGuiID ImGuiWindow::GetIDNoKeepAlive(const char* str, const char* str_end)
{
ImGuiID seed = IDStack.back();
return ImHashStr(str, str_end ? (str_end - str) : 0, seed);
}
ImGuiID ImGuiWindow::GetIDNoKeepAlive(const void* ptr)
{
ImGuiID seed = IDStack.back();
return ImHashData(&ptr, sizeof(void*), seed);
}
ImGuiID ImGuiWindow::GetIDNoKeepAlive(int n)
{
ImGuiID seed = IDStack.back();
return ImHashData(&n, sizeof(n), seed);
}
// This is only used in rare/specific situations to manufacture an ID out of nowhere.
ImGuiID ImGuiWindow::GetIDFromRectangle(const ImRect& r_abs)
{
ImGuiID seed = IDStack.back();
const int r_rel[4] = { (int)(r_abs.Min.x - Pos.x), (int)(r_abs.Min.y - Pos.y), (int)(r_abs.Max.x - Pos.x), (int)(r_abs.Max.y - Pos.y) };
ImGuiID id = ImHashData(&r_rel, sizeof(r_rel), seed);
ImGui::KeepAliveID(id);
return id;
}
static void SetCurrentWindow(ImGuiWindow* window)
{
ImGuiContext& g = *GImGui;
g.CurrentWindow = window;
if (window)
g.FontSize = g.DrawListSharedData.FontSize = window->CalcFontSize();
}
// Free up/compact internal window buffers, we can use this when a window becomes unused.
// This is currently unused by the library, but you may call this yourself for easy GC.
// Not freed:
// - ImGuiWindow, ImGuiWindowSettings, Name
// - StateStorage, ColumnsStorage (may hold useful data)
// This should have no noticeable visual effect. When the window reappear however, expect new allocation/buffer growth/copy cost.
void ImGui::GcCompactTransientWindowBuffers(ImGuiWindow* window)
{
window->MemoryCompacted = true;
window->MemoryDrawListIdxCapacity = window->DrawList->IdxBuffer.Capacity;
window->MemoryDrawListVtxCapacity = window->DrawList->VtxBuffer.Capacity;
window->IDStack.clear();
window->DrawList->ClearFreeMemory();
window->DC.ChildWindows.clear();
window->DC.ItemFlagsStack.clear();
window->DC.ItemWidthStack.clear();
window->DC.TextWrapPosStack.clear();
window->DC.GroupStack.clear();
}
void ImGui::GcAwakeTransientWindowBuffers(ImGuiWindow* window)
{
// We stored capacity of the ImDrawList buffer to reduce growth-caused allocation/copy when awakening.
// The other buffers tends to amortize much faster.
window->MemoryCompacted = false;
window->DrawList->IdxBuffer.reserve(window->MemoryDrawListIdxCapacity);
window->DrawList->VtxBuffer.reserve(window->MemoryDrawListVtxCapacity);
window->MemoryDrawListIdxCapacity = window->MemoryDrawListVtxCapacity = 0;
}
void ImGui::SetActiveID(ImGuiID id, ImGuiWindow* window)
{
ImGuiContext& g = *GImGui;
g.ActiveIdIsJustActivated = (g.ActiveId != id);
if (g.ActiveIdIsJustActivated)
{
g.ActiveIdTimer = 0.0f;
g.ActiveIdHasBeenPressedBefore = false;
g.ActiveIdHasBeenEditedBefore = false;
if (id != 0)
{
g.LastActiveId = id;
g.LastActiveIdTimer = 0.0f;
}
}
g.ActiveId = id;
g.ActiveIdAllowOverlap = false;
g.ActiveIdWindow = window;
g.ActiveIdHasBeenEditedThisFrame = false;
if (id)
{
g.ActiveIdIsAlive = id;
g.ActiveIdSource = (g.NavActivateId == id || g.NavInputId == id || g.NavJustTabbedId == id || g.NavJustMovedToId == id) ? ImGuiInputSource_Nav : ImGuiInputSource_Mouse;
}
// Clear declaration of inputs claimed by the widget
// (Please note that this is WIP and not all keys/inputs are thoroughly declared by all widgets yet)
g.ActiveIdUsingNavDirMask = 0x00;
g.ActiveIdUsingNavInputMask = 0x00;
g.ActiveIdUsingKeyInputMask = 0x00;
}
void ImGui::ClearActiveID()
{
SetActiveID(0, NULL);
}
void ImGui::SetHoveredID(ImGuiID id)
{
ImGuiContext& g = *GImGui;
g.HoveredId = id;
g.HoveredIdAllowOverlap = false;
if (id != 0 && g.HoveredIdPreviousFrame != id)
g.HoveredIdTimer = g.HoveredIdNotActiveTimer = 0.0f;
}
ImGuiID ImGui::GetHoveredID()
{
ImGuiContext& g = *GImGui;
return g.HoveredId ? g.HoveredId : g.HoveredIdPreviousFrame;
}
void ImGui::KeepAliveID(ImGuiID id)
{
ImGuiContext& g = *GImGui;
if (g.ActiveId == id)
g.ActiveIdIsAlive = id;
if (g.ActiveIdPreviousFrame == id)
g.ActiveIdPreviousFrameIsAlive = true;
}
void ImGui::MarkItemEdited(ImGuiID id)
{
// This marking is solely to be able to provide info for IsItemDeactivatedAfterEdit().
// ActiveId might have been released by the time we call this (as in the typical press/release button behavior) but still need need to fill the data.
ImGuiContext& g = *GImGui;
IM_ASSERT(g.ActiveId == id || g.ActiveId == 0 || g.DragDropActive);
IM_UNUSED(id); // Avoid unused variable warnings when asserts are compiled out.
//IM_ASSERT(g.CurrentWindow->DC.LastItemId == id);
g.ActiveIdHasBeenEditedThisFrame = true;
g.ActiveIdHasBeenEditedBefore = true;
g.CurrentWindow->DC.LastItemStatusFlags |= ImGuiItemStatusFlags_Edited;
}
static inline bool IsWindowContentHoverable(ImGuiWindow* window, ImGuiHoveredFlags flags)
{
// An active popup disable hovering on other windows (apart from its own children)
// FIXME-OPT: This could be cached/stored within the window.
ImGuiContext& g = *GImGui;
if (g.NavWindow)
if (ImGuiWindow* focused_root_window = g.NavWindow->RootWindow)
if (focused_root_window->WasActive && focused_root_window != window->RootWindow)
{
// For the purpose of those flags we differentiate "standard popup" from "modal popup"
// NB: The order of those two tests is important because Modal windows are also Popups.
if (focused_root_window->Flags & ImGuiWindowFlags_Modal)
return false;
if ((focused_root_window->Flags & ImGuiWindowFlags_Popup) && !(flags & ImGuiHoveredFlags_AllowWhenBlockedByPopup))
return false;
}
return true;
}
// This is roughly matching the behavior of internal-facing ItemHoverable()
// - we allow hovering to be true when ActiveId==window->MoveID, so that clicking on non-interactive items such as a Text() item still returns true with IsItemHovered()
// - this should work even for non-interactive items that have no ID, so we cannot use LastItemId
bool ImGui::IsItemHovered(ImGuiHoveredFlags flags)
{
ImGuiContext& g = *GImGui;
ImGuiWindow* window = g.CurrentWindow;
if (g.NavDisableMouseHover && !g.NavDisableHighlight)
return IsItemFocused();
// Test for bounding box overlap, as updated as ItemAdd()
if (!(window->DC.LastItemStatusFlags & ImGuiItemStatusFlags_HoveredRect))
return false;
IM_ASSERT((flags & (ImGuiHoveredFlags_RootWindow | ImGuiHoveredFlags_ChildWindows)) == 0); // Flags not supported by this function
// Test if we are hovering the right window (our window could be behind another window)
// [2017/10/16] Reverted commit 344d48be3 and testing RootWindow instead. I believe it is correct to NOT test for RootWindow but this leaves us unable to use IsItemHovered() after EndChild() itself.
// Until a solution is found I believe reverting to the test from 2017/09/27 is safe since this was the test that has been running for a long while.
//if (g.HoveredWindow != window)
// return false;
if (g.HoveredRootWindow != window->RootWindow && !(flags & ImGuiHoveredFlags_AllowWhenOverlapped))
return false;
// Test if another item is active (e.g. being dragged)
if (!(flags & ImGuiHoveredFlags_AllowWhenBlockedByActiveItem))
if (g.ActiveId != 0 && g.ActiveId != window->DC.LastItemId && !g.ActiveIdAllowOverlap && g.ActiveId != window->MoveId)
return false;
// Test if interactions on this window are blocked by an active popup or modal.
// The ImGuiHoveredFlags_AllowWhenBlockedByPopup flag will be tested here.
if (!IsWindowContentHoverable(window, flags))
return false;
// Test if the item is disabled
if ((window->DC.ItemFlags & ImGuiItemFlags_Disabled) && !(flags & ImGuiHoveredFlags_AllowWhenDisabled))
return false;
// Special handling for the dummy item after Begin() which represent the title bar or tab.
// When the window is collapsed (SkipItems==true) that last item will never be overwritten so we need to detect the case.
if (window->DC.LastItemId == window->MoveId && window->WriteAccessed)
return false;
return true;
}
// Internal facing ItemHoverable() used when submitting widgets. Differs slightly from IsItemHovered().
bool ImGui::ItemHoverable(const ImRect& bb, ImGuiID id)
{
ImGuiContext& g = *GImGui;
if (g.HoveredId != 0 && g.HoveredId != id && !g.HoveredIdAllowOverlap)
return false;
ImGuiWindow* window = g.CurrentWindow;
if (g.HoveredWindow != window)
return false;
if (g.ActiveId != 0 && g.ActiveId != id && !g.ActiveIdAllowOverlap)
return false;
if (!IsMouseHoveringRect(bb.Min, bb.Max))
return false;
if (g.NavDisableMouseHover || !IsWindowContentHoverable(window, ImGuiHoveredFlags_None))
return false;
if (window->DC.ItemFlags & ImGuiItemFlags_Disabled)
return false;
SetHoveredID(id);
// [DEBUG] Item Picker tool!
// We perform the check here because SetHoveredID() is not frequently called (1~ time a frame), making
// the cost of this tool near-zero. We can get slightly better call-stack and support picking non-hovered
// items if we perform the test in ItemAdd(), but that would incur a small runtime cost.
// #define IMGUI_DEBUG_TOOL_ITEM_PICKER_EX in imconfig.h if you want this check to also be performed in ItemAdd().
if (g.DebugItemPickerActive && g.HoveredIdPreviousFrame == id)
GetForegroundDrawList()->AddRect(bb.Min, bb.Max, IM_COL32(255, 255, 0, 255));
if (g.DebugItemPickerBreakId == id)
IM_DEBUG_BREAK();
return true;
}
bool ImGui::IsClippedEx(const ImRect& bb, ImGuiID id, bool clip_even_when_logged)
{
ImGuiContext& g = *GImGui;
ImGuiWindow* window = g.CurrentWindow;
if (!bb.Overlaps(window->ClipRect))
if (id == 0 || id != g.ActiveId)
if (clip_even_when_logged || !g.LogEnabled)
return true;
return false;
}
// Process TAB/Shift+TAB. Be mindful that this function may _clear_ the ActiveID when tabbing out.
bool ImGui::FocusableItemRegister(ImGuiWindow* window, ImGuiID id)
{
ImGuiContext& g = *GImGui;
// Increment counters
const bool is_tab_stop = (window->DC.ItemFlags & (ImGuiItemFlags_NoTabStop | ImGuiItemFlags_Disabled)) == 0;
window->DC.FocusCounterRegular++;
if (is_tab_stop)
window->DC.FocusCounterTabStop++;
// Process TAB/Shift-TAB to tab *OUT* of the currently focused item.
// (Note that we can always TAB out of a widget that doesn't allow tabbing in)
if (g.ActiveId == id && g.FocusTabPressed && !IsActiveIdUsingKey(ImGuiKey_Tab) && g.FocusRequestNextWindow == NULL)
{
g.FocusRequestNextWindow = window;
g.FocusRequestNextCounterTabStop = window->DC.FocusCounterTabStop + (g.IO.KeyShift ? (is_tab_stop ? -1 : 0) : +1); // Modulo on index will be applied at the end of frame once we've got the total counter of items.
}
// Handle focus requests
if (g.FocusRequestCurrWindow == window)
{
if (window->DC.FocusCounterRegular == g.FocusRequestCurrCounterRegular)
return true;
if (is_tab_stop && window->DC.FocusCounterTabStop == g.FocusRequestCurrCounterTabStop)
{
g.NavJustTabbedId = id;
return true;
}
// If another item is about to be focused, we clear our own active id
if (g.ActiveId == id)
ClearActiveID();
}
return false;
}
void ImGui::FocusableItemUnregister(ImGuiWindow* window)
{
window->DC.FocusCounterRegular--;
window->DC.FocusCounterTabStop--;
}
float ImGui::CalcWrapWidthForPos(const ImVec2& pos, float wrap_pos_x)
{
if (wrap_pos_x < 0.0f)
return 0.0f;
ImGuiWindow* window = GImGui->CurrentWindow;
if (wrap_pos_x == 0.0f)
wrap_pos_x = window->WorkRect.Max.x;
else if (wrap_pos_x > 0.0f)
wrap_pos_x += window->Pos.x - window->Scroll.x; // wrap_pos_x is provided is window local space
return ImMax(wrap_pos_x - pos.x, 1.0f);
}
// IM_ALLOC() == ImGui::MemAlloc()
void* ImGui::MemAlloc(size_t size)
{
if (ImGuiContext* ctx = GImGui)
ctx->IO.MetricsActiveAllocations++;
return GImAllocatorAllocFunc(size, GImAllocatorUserData);
}
// IM_FREE() == ImGui::MemFree()
void ImGui::MemFree(void* ptr)
{
if (ptr)
if (ImGuiContext* ctx = GImGui)
ctx->IO.MetricsActiveAllocations--;
return GImAllocatorFreeFunc(ptr, GImAllocatorUserData);
}
const char* ImGui::GetClipboardText()
{
ImGuiContext& g = *GImGui;
return g.IO.GetClipboardTextFn ? g.IO.GetClipboardTextFn(g.IO.ClipboardUserData) : "";
}
void ImGui::SetClipboardText(const char* text)
{
ImGuiContext& g = *GImGui;
if (g.IO.SetClipboardTextFn)
g.IO.SetClipboardTextFn(g.IO.ClipboardUserData, text);
}
const char* ImGui::GetVersion()
{
return IMGUI_VERSION;
}
// Internal state access - if you want to share Dear ImGui state between modules (e.g. DLL) or allocate it yourself
// Note that we still point to some static data and members (such as GFontAtlas), so the state instance you end up using will point to the static data within its module
ImGuiContext* ImGui::GetCurrentContext()
{
return GImGui;
}
void ImGui::SetCurrentContext(ImGuiContext* ctx)
{
#ifdef IMGUI_SET_CURRENT_CONTEXT_FUNC
IMGUI_SET_CURRENT_CONTEXT_FUNC(ctx); // For custom thread-based hackery you may want to have control over this.
#else
GImGui = ctx;
#endif
}
void ImGui::SetAllocatorFunctions(void* (*alloc_func)(size_t sz, void* user_data), void (*free_func)(void* ptr, void* user_data), void* user_data)
{
GImAllocatorAllocFunc = alloc_func;
GImAllocatorFreeFunc = free_func;
GImAllocatorUserData = user_data;
}
ImGuiContext* ImGui::CreateContext(ImFontAtlas* shared_font_atlas)
{
ImGuiContext* ctx = IM_NEW(ImGuiContext)(shared_font_atlas);
if (GImGui == NULL)
SetCurrentContext(ctx);
Initialize(ctx);
return ctx;
}
void ImGui::DestroyContext(ImGuiContext* ctx)
{
if (ctx == NULL)
ctx = GImGui;
Shutdown(ctx);
if (GImGui == ctx)
SetCurrentContext(NULL);
IM_DELETE(ctx);
}
ImGuiIO& ImGui::GetIO()
{
IM_ASSERT(GImGui != NULL && "No current context. Did you call ImGui::CreateContext() and ImGui::SetCurrentContext() ?");
return GImGui->IO;
}
// Same value as passed to the old io.RenderDrawListsFn function. Valid after Render() and until the next call to NewFrame()
ImDrawData* ImGui::GetDrawData()
{
ImGuiContext& g = *GImGui;
return g.DrawData.Valid ? &g.DrawData : NULL;
}
double ImGui::GetTime()
{
return GImGui->Time;
}
int ImGui::GetFrameCount()
{
return GImGui->FrameCount;
}
ImDrawList* ImGui::GetBackgroundDrawList()
{
return &GImGui->BackgroundDrawList;
}
ImDrawList* ImGui::GetForegroundDrawList()
{
return &GImGui->ForegroundDrawList;
}
ImDrawListSharedData* ImGui::GetDrawListSharedData()
{
return &GImGui->DrawListSharedData;
}
void ImGui::StartMouseMovingWindow(ImGuiWindow* window)
{
// Set ActiveId even if the _NoMove flag is set. Without it, dragging away from a window with _NoMove would activate hover on other windows.
// We _also_ call this when clicking in a window empty space when io.ConfigWindowsMoveFromTitleBarOnly is set, but clear g.MovingWindow afterward.
// This is because we want ActiveId to be set even when the window is not permitted to move.
ImGuiContext& g = *GImGui;
FocusWindow(window);
SetActiveID(window->MoveId, window);
g.NavDisableHighlight = true;
g.ActiveIdClickOffset = g.IO.MousePos - window->RootWindow->Pos;
bool can_move_window = true;
if ((window->Flags & ImGuiWindowFlags_NoMove) || (window->RootWindow->Flags & ImGuiWindowFlags_NoMove))
can_move_window = false;
if (can_move_window)
g.MovingWindow = window;
}
// Handle mouse moving window
// Note: moving window with the navigation keys (Square + d-pad / CTRL+TAB + Arrows) are processed in NavUpdateWindowing()
// FIXME: We don't have strong guarantee that g.MovingWindow stay synched with g.ActiveId == g.MovingWindow->MoveId.
// This is currently enforced by the fact that BeginDragDropSource() is setting all g.ActiveIdUsingXXXX flags to inhibit navigation inputs,
// but if we should more thoroughly test cases where g.ActiveId or g.MovingWindow gets changed and not the other.
void ImGui::UpdateMouseMovingWindowNewFrame()
{
ImGuiContext& g = *GImGui;
if (g.MovingWindow != NULL)
{
// We actually want to move the root window. g.MovingWindow == window we clicked on (could be a child window).
// We track it to preserve Focus and so that generally ActiveIdWindow == MovingWindow and ActiveId == MovingWindow->MoveId for consistency.
KeepAliveID(g.ActiveId);
IM_ASSERT(g.MovingWindow && g.MovingWindow->RootWindow);
ImGuiWindow* moving_window = g.MovingWindow->RootWindow;
if (g.IO.MouseDown[0] && IsMousePosValid(&g.IO.MousePos))
{
ImVec2 pos = g.IO.MousePos - g.ActiveIdClickOffset;
if (moving_window->Pos.x != pos.x || moving_window->Pos.y != pos.y)
{
MarkIniSettingsDirty(moving_window);
SetWindowPos(moving_window, pos, ImGuiCond_Always);
}
FocusWindow(g.MovingWindow);
}
else
{
ClearActiveID();
g.MovingWindow = NULL;
}
}
else
{
// When clicking/dragging from a window that has the _NoMove flag, we still set the ActiveId in order to prevent hovering others.
if (g.ActiveIdWindow && g.ActiveIdWindow->MoveId == g.ActiveId)
{
KeepAliveID(g.ActiveId);
if (!g.IO.MouseDown[0])
ClearActiveID();
}
}
}
// Initiate moving window when clicking on empty space or title bar.
// Handle left-click and right-click focus.
void ImGui::UpdateMouseMovingWindowEndFrame()
{
ImGuiContext& g = *GImGui;
if (g.ActiveId != 0 || g.HoveredId != 0)
return;
// Unless we just made a window/popup appear
if (g.NavWindow && g.NavWindow->Appearing)
return;
// Click to focus window and start moving (after we're done with all our widgets)
if (g.IO.MouseClicked[0])
{
if (g.HoveredRootWindow != NULL)
{
StartMouseMovingWindow(g.HoveredWindow);
if (g.IO.ConfigWindowsMoveFromTitleBarOnly && !(g.HoveredRootWindow->Flags & ImGuiWindowFlags_NoTitleBar))
if (!g.HoveredRootWindow->TitleBarRect().Contains(g.IO.MouseClickedPos[0]))
g.MovingWindow = NULL;
}
else if (g.NavWindow != NULL && GetTopMostPopupModal() == NULL)
{
// Clicking on void disable focus
FocusWindow(NULL);
}
}
// With right mouse button we close popups without changing focus based on where the mouse is aimed
// Instead, focus will be restored to the window under the bottom-most closed popup.
// (The left mouse button path calls FocusWindow on the hovered window, which will lead NewFrame->ClosePopupsOverWindow to trigger)
if (g.IO.MouseClicked[1])
{
// Find the top-most window between HoveredWindow and the top-most Modal Window.
// This is where we can trim the popup stack.
ImGuiWindow* modal = GetTopMostPopupModal();
bool hovered_window_above_modal = false;
if (modal == NULL)
hovered_window_above_modal = true;
for (int i = g.Windows.Size - 1; i >= 0 && hovered_window_above_modal == false; i--)
{
ImGuiWindow* window = g.Windows[i];
if (window == modal)
break;
if (window == g.HoveredWindow)
hovered_window_above_modal = true;
}
ClosePopupsOverWindow(hovered_window_above_modal ? g.HoveredWindow : modal, true);
}
}
static bool IsWindowActiveAndVisible(ImGuiWindow* window)
{
return (window->Active) && (!window->Hidden);
}
static void ImGui::UpdateMouseInputs()
{
ImGuiContext& g = *GImGui;
// Round mouse position to avoid spreading non-rounded position (e.g. UpdateManualResize doesn't support them well)
if (IsMousePosValid(&g.IO.MousePos))
g.IO.MousePos = g.LastValidMousePos = ImFloor(g.IO.MousePos);
// If mouse just appeared or disappeared (usually denoted by -FLT_MAX components) we cancel out movement in MouseDelta
if (IsMousePosValid(&g.IO.MousePos) && IsMousePosValid(&g.IO.MousePosPrev))
g.IO.MouseDelta = g.IO.MousePos - g.IO.MousePosPrev;
else
g.IO.MouseDelta = ImVec2(0.0f, 0.0f);
if (g.IO.MouseDelta.x != 0.0f || g.IO.MouseDelta.y != 0.0f)
g.NavDisableMouseHover = false;
g.IO.MousePosPrev = g.IO.MousePos;
for (int i = 0; i < IM_ARRAYSIZE(g.IO.MouseDown); i++)
{
g.IO.MouseClicked[i] = g.IO.MouseDown[i] && g.IO.MouseDownDuration[i] < 0.0f;
g.IO.MouseReleased[i] = !g.IO.MouseDown[i] && g.IO.MouseDownDuration[i] >= 0.0f;
g.IO.MouseDownDurationPrev[i] = g.IO.MouseDownDuration[i];
g.IO.MouseDownDuration[i] = g.IO.MouseDown[i] ? (g.IO.MouseDownDuration[i] < 0.0f ? 0.0f : g.IO.MouseDownDuration[i] + g.IO.DeltaTime) : -1.0f;
g.IO.MouseDoubleClicked[i] = false;
if (g.IO.MouseClicked[i])
{
if ((float)(g.Time - g.IO.MouseClickedTime[i]) < g.IO.MouseDoubleClickTime)
{
ImVec2 delta_from_click_pos = IsMousePosValid(&g.IO.MousePos) ? (g.IO.MousePos - g.IO.MouseClickedPos[i]) : ImVec2(0.0f, 0.0f);
if (ImLengthSqr(delta_from_click_pos) < g.IO.MouseDoubleClickMaxDist * g.IO.MouseDoubleClickMaxDist)
g.IO.MouseDoubleClicked[i] = true;
g.IO.MouseClickedTime[i] = -DBL_MAX; // so the third click isn't turned into a double-click
}
else
{
g.IO.MouseClickedTime[i] = g.Time;
}
g.IO.MouseClickedPos[i] = g.IO.MousePos;
g.IO.MouseDownWasDoubleClick[i] = g.IO.MouseDoubleClicked[i];
g.IO.MouseDragMaxDistanceAbs[i] = ImVec2(0.0f, 0.0f);
g.IO.MouseDragMaxDistanceSqr[i] = 0.0f;
}
else if (g.IO.MouseDown[i])
{
// Maintain the maximum distance we reaching from the initial click position, which is used with dragging threshold
ImVec2 delta_from_click_pos = IsMousePosValid(&g.IO.MousePos) ? (g.IO.MousePos - g.IO.MouseClickedPos[i]) : ImVec2(0.0f, 0.0f);
g.IO.MouseDragMaxDistanceSqr[i] = ImMax(g.IO.MouseDragMaxDistanceSqr[i], ImLengthSqr(delta_from_click_pos));
g.IO.MouseDragMaxDistanceAbs[i].x = ImMax(g.IO.MouseDragMaxDistanceAbs[i].x, delta_from_click_pos.x < 0.0f ? -delta_from_click_pos.x : delta_from_click_pos.x);
g.IO.MouseDragMaxDistanceAbs[i].y = ImMax(g.IO.MouseDragMaxDistanceAbs[i].y, delta_from_click_pos.y < 0.0f ? -delta_from_click_pos.y : delta_from_click_pos.y);
}
if (!g.IO.MouseDown[i] && !g.IO.MouseReleased[i])
g.IO.MouseDownWasDoubleClick[i] = false;
if (g.IO.MouseClicked[i]) // Clicking any mouse button reactivate mouse hovering which may have been deactivated by gamepad/keyboard navigation
g.NavDisableMouseHover = false;
}
}
static void StartLockWheelingWindow(ImGuiWindow* window)
{
ImGuiContext& g = *GImGui;
if (g.WheelingWindow == window)
return;
g.WheelingWindow = window;
g.WheelingWindowRefMousePos = g.IO.MousePos;
g.WheelingWindowTimer = WINDOWS_MOUSE_WHEEL_SCROLL_LOCK_TIMER;
}
void ImGui::UpdateMouseWheel()
{
ImGuiContext& g = *GImGui;
// Reset the locked window if we move the mouse or after the timer elapses
if (g.WheelingWindow != NULL)
{
g.WheelingWindowTimer -= g.IO.DeltaTime;
if (IsMousePosValid() && ImLengthSqr(g.IO.MousePos - g.WheelingWindowRefMousePos) > g.IO.MouseDragThreshold * g.IO.MouseDragThreshold)
g.WheelingWindowTimer = 0.0f;
if (g.WheelingWindowTimer <= 0.0f)
{
g.WheelingWindow = NULL;
g.WheelingWindowTimer = 0.0f;
}
}
if (g.IO.MouseWheel == 0.0f && g.IO.MouseWheelH == 0.0f)
return;
ImGuiWindow* window = g.WheelingWindow ? g.WheelingWindow : g.HoveredWindow;
if (!window || window->Collapsed)
return;
// Zoom / Scale window
// FIXME-OBSOLETE: This is an old feature, it still works but pretty much nobody is using it and may be best redesigned.
if (g.IO.MouseWheel != 0.0f && g.IO.KeyCtrl && g.IO.FontAllowUserScaling)
{
StartLockWheelingWindow(window);
const float new_font_scale = ImClamp(window->FontWindowScale + g.IO.MouseWheel * 0.10f, 0.50f, 2.50f);
const float scale = new_font_scale / window->FontWindowScale;
window->FontWindowScale = new_font_scale;
if (!(window->Flags & ImGuiWindowFlags_ChildWindow))
{
const ImVec2 offset = window->Size * (1.0f - scale) * (g.IO.MousePos - window->Pos) / window->Size;
SetWindowPos(window, window->Pos + offset, 0);
window->Size = ImFloor(window->Size * scale);
window->SizeFull = ImFloor(window->SizeFull * scale);
}
return;
}
// Mouse wheel scrolling
// If a child window has the ImGuiWindowFlags_NoScrollWithMouse flag, we give a chance to scroll its parent
// Vertical Mouse Wheel scrolling
const float wheel_y = (g.IO.MouseWheel != 0.0f && !g.IO.KeyShift) ? g.IO.MouseWheel : 0.0f;
if (wheel_y != 0.0f && !g.IO.KeyCtrl)
{
StartLockWheelingWindow(window);
while ((window->Flags & ImGuiWindowFlags_ChildWindow) && ((window->ScrollMax.y == 0.0f) || ((window->Flags & ImGuiWindowFlags_NoScrollWithMouse) && !(window->Flags & ImGuiWindowFlags_NoMouseInputs))))
window = window->ParentWindow;
if (!(window->Flags & ImGuiWindowFlags_NoScrollWithMouse) && !(window->Flags & ImGuiWindowFlags_NoMouseInputs))
{
float max_step = window->InnerRect.GetHeight() * 0.67f;
float scroll_step = ImFloor(ImMin(5 * window->CalcFontSize(), max_step));
SetScrollY(window, window->Scroll.y - wheel_y * scroll_step);
}
}
// Horizontal Mouse Wheel scrolling, or Vertical Mouse Wheel w/ Shift held
const float wheel_x = (g.IO.MouseWheelH != 0.0f && !g.IO.KeyShift) ? g.IO.MouseWheelH : (g.IO.MouseWheel != 0.0f && g.IO.KeyShift) ? g.IO.MouseWheel : 0.0f;
if (wheel_x != 0.0f && !g.IO.KeyCtrl)
{
StartLockWheelingWindow(window);
while ((window->Flags & ImGuiWindowFlags_ChildWindow) && ((window->ScrollMax.x == 0.0f) || ((window->Flags & ImGuiWindowFlags_NoScrollWithMouse) && !(window->Flags & ImGuiWindowFlags_NoMouseInputs))))
window = window->ParentWindow;
if (!(window->Flags & ImGuiWindowFlags_NoScrollWithMouse) && !(window->Flags & ImGuiWindowFlags_NoMouseInputs))
{
float max_step = window->InnerRect.GetWidth() * 0.67f;
float scroll_step = ImFloor(ImMin(2 * window->CalcFontSize(), max_step));
SetScrollX(window, window->Scroll.x - wheel_x * scroll_step);
}
}
}
void ImGui::UpdateTabFocus()
{
ImGuiContext& g = *GImGui;
// Pressing TAB activate widget focus
g.FocusTabPressed = (g.NavWindow && g.NavWindow->Active && !(g.NavWindow->Flags & ImGuiWindowFlags_NoNavInputs) && !g.IO.KeyCtrl && IsKeyPressedMap(ImGuiKey_Tab));
if (g.ActiveId == 0 && g.FocusTabPressed)
{
// Note that SetKeyboardFocusHere() sets the Next fields mid-frame. To be consistent we also
// manipulate the Next fields even, even though they will be turned into Curr fields by the code below.
g.FocusRequestNextWindow = g.NavWindow;
g.FocusRequestNextCounterRegular = INT_MAX;
if (g.NavId != 0 && g.NavIdTabCounter != INT_MAX)
g.FocusRequestNextCounterTabStop = g.NavIdTabCounter + 1 + (g.IO.KeyShift ? -1 : 1);
else
g.FocusRequestNextCounterTabStop = g.IO.KeyShift ? -1 : 0;
}
// Turn queued focus request into current one
g.FocusRequestCurrWindow = NULL;
g.FocusRequestCurrCounterRegular = g.FocusRequestCurrCounterTabStop = INT_MAX;
if (g.FocusRequestNextWindow != NULL)
{
ImGuiWindow* window = g.FocusRequestNextWindow;
g.FocusRequestCurrWindow = window;
if (g.FocusRequestNextCounterRegular != INT_MAX && window->DC.FocusCounterRegular != -1)
g.FocusRequestCurrCounterRegular = ImModPositive(g.FocusRequestNextCounterRegular, window->DC.FocusCounterRegular + 1);
if (g.FocusRequestNextCounterTabStop != INT_MAX && window->DC.FocusCounterTabStop != -1)
g.FocusRequestCurrCounterTabStop = ImModPositive(g.FocusRequestNextCounterTabStop, window->DC.FocusCounterTabStop + 1);
g.FocusRequestNextWindow = NULL;
g.FocusRequestNextCounterRegular = g.FocusRequestNextCounterTabStop = INT_MAX;
}
g.NavIdTabCounter = INT_MAX;
}
// The reason this is exposed in imgui_internal.h is: on touch-based system that don't have hovering, we want to dispatch inputs to the right target (imgui vs imgui+app)
void ImGui::UpdateHoveredWindowAndCaptureFlags()
{
ImGuiContext& g = *GImGui;
// Find the window hovered by mouse:
// - Child windows can extend beyond the limit of their parent so we need to derive HoveredRootWindow from HoveredWindow.
// - When moving a window we can skip the search, which also conveniently bypasses the fact that window->WindowRectClipped is lagging as this point of the frame.
// - We also support the moved window toggling the NoInputs flag after moving has started in order to be able to detect windows below it, which is useful for e.g. docking mechanisms.
FindHoveredWindow();
// Modal windows prevents cursor from hovering behind them.
ImGuiWindow* modal_window = GetTopMostPopupModal();
if (modal_window)
if (g.HoveredRootWindow && !IsWindowChildOf(g.HoveredRootWindow, modal_window))
g.HoveredRootWindow = g.HoveredWindow = NULL;
// Disabled mouse?
if (g.IO.ConfigFlags & ImGuiConfigFlags_NoMouse)
g.HoveredWindow = g.HoveredRootWindow = NULL;
// We track click ownership. When clicked outside of a window the click is owned by the application and won't report hovering nor request capture even while dragging over our windows afterward.
int mouse_earliest_button_down = -1;
bool mouse_any_down = false;
for (int i = 0; i < IM_ARRAYSIZE(g.IO.MouseDown); i++)
{
if (g.IO.MouseClicked[i])
g.IO.MouseDownOwned[i] = (g.HoveredWindow != NULL) || (!g.OpenPopupStack.empty());
mouse_any_down |= g.IO.MouseDown[i];
if (g.IO.MouseDown[i])
if (mouse_earliest_button_down == -1 || g.IO.MouseClickedTime[i] < g.IO.MouseClickedTime[mouse_earliest_button_down])
mouse_earliest_button_down = i;
}
const bool mouse_avail_to_imgui = (mouse_earliest_button_down == -1) || g.IO.MouseDownOwned[mouse_earliest_button_down];
// If mouse was first clicked outside of ImGui bounds we also cancel out hovering.
// FIXME: For patterns of drag and drop across OS windows, we may need to rework/remove this test (first committed 311c0ca9 on 2015/02)
const bool mouse_dragging_extern_payload = g.DragDropActive && (g.DragDropSourceFlags & ImGuiDragDropFlags_SourceExtern) != 0;
if (!mouse_avail_to_imgui && !mouse_dragging_extern_payload)
g.HoveredWindow = g.HoveredRootWindow = NULL;
// Update io.WantCaptureMouse for the user application (true = dispatch mouse info to imgui, false = dispatch mouse info to Dear ImGui + app)
if (g.WantCaptureMouseNextFrame != -1)
g.IO.WantCaptureMouse = (g.WantCaptureMouseNextFrame != 0);
else
g.IO.WantCaptureMouse = (mouse_avail_to_imgui && (g.HoveredWindow != NULL || mouse_any_down)) || (!g.OpenPopupStack.empty());
// Update io.WantCaptureKeyboard for the user application (true = dispatch keyboard info to imgui, false = dispatch keyboard info to Dear ImGui + app)
if (g.WantCaptureKeyboardNextFrame != -1)
g.IO.WantCaptureKeyboard = (g.WantCaptureKeyboardNextFrame != 0);
else
g.IO.WantCaptureKeyboard = (g.ActiveId != 0) || (modal_window != NULL);
if (g.IO.NavActive && (g.IO.ConfigFlags & ImGuiConfigFlags_NavEnableKeyboard) && !(g.IO.ConfigFlags & ImGuiConfigFlags_NavNoCaptureKeyboard))
g.IO.WantCaptureKeyboard = true;
// Update io.WantTextInput flag, this is to allow systems without a keyboard (e.g. mobile, hand-held) to show a software keyboard if possible
g.IO.WantTextInput = (g.WantTextInputNextFrame != -1) ? (g.WantTextInputNextFrame != 0) : false;
}
static void NewFrameSanityChecks()
{
ImGuiContext& g = *GImGui;
// Check user data
// (We pass an error message in the assert expression to make it visible to programmers who are not using a debugger, as most assert handlers display their argument)
IM_ASSERT(g.Initialized);
IM_ASSERT((g.IO.DeltaTime > 0.0f || g.FrameCount == 0) && "Need a positive DeltaTime!");
IM_ASSERT((g.FrameCount == 0 || g.FrameCountEnded == g.FrameCount) && "Forgot to call Render() or EndFrame() at the end of the previous frame?");
IM_ASSERT(g.IO.DisplaySize.x >= 0.0f && g.IO.DisplaySize.y >= 0.0f && "Invalid DisplaySize value!");
IM_ASSERT(g.IO.Fonts->Fonts.Size > 0 && "Font Atlas not built. Did you call io.Fonts->GetTexDataAsRGBA32() / GetTexDataAsAlpha8() ?");
IM_ASSERT(g.IO.Fonts->Fonts[0]->IsLoaded() && "Font Atlas not built. Did you call io.Fonts->GetTexDataAsRGBA32() / GetTexDataAsAlpha8() ?");
IM_ASSERT(g.Style.CurveTessellationTol > 0.0f && "Invalid style setting!");
IM_ASSERT(g.Style.CircleSegmentMaxError > 0.0f && "Invalid style setting!");
IM_ASSERT(g.Style.Alpha >= 0.0f && g.Style.Alpha <= 1.0f && "Invalid style setting. Alpha cannot be negative (allows us to avoid a few clamps in color computations)!");
IM_ASSERT(g.Style.WindowMinSize.x >= 1.0f && g.Style.WindowMinSize.y >= 1.0f && "Invalid style setting.");
IM_ASSERT(g.Style.WindowMenuButtonPosition == ImGuiDir_None || g.Style.WindowMenuButtonPosition == ImGuiDir_Left || g.Style.WindowMenuButtonPosition == ImGuiDir_Right);
for (int n = 0; n < ImGuiKey_COUNT; n++)
IM_ASSERT(g.IO.KeyMap[n] >= -1 && g.IO.KeyMap[n] < IM_ARRAYSIZE(g.IO.KeysDown) && "io.KeyMap[] contains an out of bound value (need to be 0..512, or -1 for unmapped key)");
// Perform simple check: required key mapping (we intentionally do NOT check all keys to not pressure user into setting up everything, but Space is required and was only recently added in 1.60 WIP)
if (g.IO.ConfigFlags & ImGuiConfigFlags_NavEnableKeyboard)
IM_ASSERT(g.IO.KeyMap[ImGuiKey_Space] != -1 && "ImGuiKey_Space is not mapped, required for keyboard navigation.");
// Perform simple check: the beta io.ConfigWindowsResizeFromEdges option requires back-end to honor mouse cursor changes and set the ImGuiBackendFlags_HasMouseCursors flag accordingly.
if (g.IO.ConfigWindowsResizeFromEdges && !(g.IO.BackendFlags & ImGuiBackendFlags_HasMouseCursors))
g.IO.ConfigWindowsResizeFromEdges = false;
}
void ImGui::NewFrame()
{
IM_ASSERT(GImGui != NULL && "No current context. Did you call ImGui::CreateContext() and ImGui::SetCurrentContext() ?");
ImGuiContext& g = *GImGui;
#ifdef IMGUI_ENABLE_TEST_ENGINE
ImGuiTestEngineHook_PreNewFrame(&g);
#endif
// Check and assert for various common IO and Configuration mistakes
NewFrameSanityChecks();
// Load settings on first frame, save settings when modified (after a delay)
UpdateSettings();
g.Time += g.IO.DeltaTime;
g.WithinFrameScope = true;
g.FrameCount += 1;
g.TooltipOverrideCount = 0;
g.WindowsActiveCount = 0;
g.MenusIdSubmittedThisFrame.resize(0);
// Calculate frame-rate for the user, as a purely luxurious feature
g.FramerateSecPerFrameAccum += g.IO.DeltaTime - g.FramerateSecPerFrame[g.FramerateSecPerFrameIdx];
g.FramerateSecPerFrame[g.FramerateSecPerFrameIdx] = g.IO.DeltaTime;
g.FramerateSecPerFrameIdx = (g.FramerateSecPerFrameIdx + 1) % IM_ARRAYSIZE(g.FramerateSecPerFrame);
g.IO.Framerate = (g.FramerateSecPerFrameAccum > 0.0f) ? (1.0f / (g.FramerateSecPerFrameAccum / (float)IM_ARRAYSIZE(g.FramerateSecPerFrame))) : FLT_MAX;
// Setup current font and draw list shared data
g.IO.Fonts->Locked = true;
SetCurrentFont(GetDefaultFont());
IM_ASSERT(g.Font->IsLoaded());
g.DrawListSharedData.ClipRectFullscreen = ImVec4(0.0f, 0.0f, g.IO.DisplaySize.x, g.IO.DisplaySize.y);
g.DrawListSharedData.CurveTessellationTol = g.Style.CurveTessellationTol;
g.DrawListSharedData.SetCircleSegmentMaxError(g.Style.CircleSegmentMaxError);
g.DrawListSharedData.InitialFlags = ImDrawListFlags_None;
if (g.Style.AntiAliasedLines)
g.DrawListSharedData.InitialFlags |= ImDrawListFlags_AntiAliasedLines;
if (g.Style.AntiAliasedFill)
g.DrawListSharedData.InitialFlags |= ImDrawListFlags_AntiAliasedFill;
if (g.IO.BackendFlags & ImGuiBackendFlags_RendererHasVtxOffset)
g.DrawListSharedData.InitialFlags |= ImDrawListFlags_AllowVtxOffset;
g.BackgroundDrawList.Clear();
g.BackgroundDrawList.PushTextureID(g.IO.Fonts->TexID);
g.BackgroundDrawList.PushClipRectFullScreen();
g.ForegroundDrawList.Clear();
g.ForegroundDrawList.PushTextureID(g.IO.Fonts->TexID);
g.ForegroundDrawList.PushClipRectFullScreen();
// Mark rendering data as invalid to prevent user who may have a handle on it to use it.
g.DrawData.Clear();
// Drag and drop keep the source ID alive so even if the source disappear our state is consistent
if (g.DragDropActive && g.DragDropPayload.SourceId == g.ActiveId)
KeepAliveID(g.DragDropPayload.SourceId);
// Update HoveredId data
if (!g.HoveredIdPreviousFrame)
g.HoveredIdTimer = 0.0f;
if (!g.HoveredIdPreviousFrame || (g.HoveredId && g.ActiveId == g.HoveredId))
g.HoveredIdNotActiveTimer = 0.0f;
if (g.HoveredId)
g.HoveredIdTimer += g.IO.DeltaTime;
if (g.HoveredId && g.ActiveId != g.HoveredId)
g.HoveredIdNotActiveTimer += g.IO.DeltaTime;
g.HoveredIdPreviousFrame = g.HoveredId;
g.HoveredId = 0;
g.HoveredIdAllowOverlap = false;
// Update ActiveId data (clear reference to active widget if the widget isn't alive anymore)
if (g.ActiveIdIsAlive != g.ActiveId && g.ActiveIdPreviousFrame == g.ActiveId && g.ActiveId != 0)
ClearActiveID();
if (g.ActiveId)
g.ActiveIdTimer += g.IO.DeltaTime;
g.LastActiveIdTimer += g.IO.DeltaTime;
g.ActiveIdPreviousFrame = g.ActiveId;
g.ActiveIdPreviousFrameWindow = g.ActiveIdWindow;
g.ActiveIdPreviousFrameHasBeenEditedBefore = g.ActiveIdHasBeenEditedBefore;
g.ActiveIdIsAlive = 0;
g.ActiveIdHasBeenEditedThisFrame = false;
g.ActiveIdPreviousFrameIsAlive = false;
g.ActiveIdIsJustActivated = false;
if (g.TempInputId != 0 && g.ActiveId != g.TempInputId)
g.TempInputId = 0;
if (g.ActiveId == 0)
{
g.ActiveIdUsingNavDirMask = 0x00;
g.ActiveIdUsingNavInputMask = 0x00;
g.ActiveIdUsingKeyInputMask = 0x00;
}
// Drag and drop
g.DragDropAcceptIdPrev = g.DragDropAcceptIdCurr;
g.DragDropAcceptIdCurr = 0;
g.DragDropAcceptIdCurrRectSurface = FLT_MAX;
g.DragDropWithinSource = false;
g.DragDropWithinTarget = false;
// Update keyboard input state
memcpy(g.IO.KeysDownDurationPrev, g.IO.KeysDownDuration, sizeof(g.IO.KeysDownDuration));
for (int i = 0; i < IM_ARRAYSIZE(g.IO.KeysDown); i++)
g.IO.KeysDownDuration[i] = g.IO.KeysDown[i] ? (g.IO.KeysDownDuration[i] < 0.0f ? 0.0f : g.IO.KeysDownDuration[i] + g.IO.DeltaTime) : -1.0f;
// Update gamepad/keyboard directional navigation
NavUpdate();
// Update mouse input state
UpdateMouseInputs();
// Find hovered window
// (needs to be before UpdateMouseMovingWindowNewFrame so we fill g.HoveredWindowUnderMovingWindow on the mouse release frame)
UpdateHoveredWindowAndCaptureFlags();
// Handle user moving window with mouse (at the beginning of the frame to avoid input lag or sheering)
UpdateMouseMovingWindowNewFrame();
// Background darkening/whitening
if (GetTopMostPopupModal() != NULL || (g.NavWindowingTarget != NULL && g.NavWindowingHighlightAlpha > 0.0f))
g.DimBgRatio = ImMin(g.DimBgRatio + g.IO.DeltaTime * 6.0f, 1.0f);
else
g.DimBgRatio = ImMax(g.DimBgRatio - g.IO.DeltaTime * 10.0f, 0.0f);
g.MouseCursor = ImGuiMouseCursor_Arrow;
g.WantCaptureMouseNextFrame = g.WantCaptureKeyboardNextFrame = g.WantTextInputNextFrame = -1;
g.PlatformImePos = ImVec2(1.0f, 1.0f); // OS Input Method Editor showing on top-left of our window by default
// Mouse wheel scrolling, scale
UpdateMouseWheel();
// Update legacy TAB focus
UpdateTabFocus();
// Mark all windows as not visible and compact unused memory.
IM_ASSERT(g.WindowsFocusOrder.Size == g.Windows.Size);
const float memory_compact_start_time = (g.IO.ConfigWindowsMemoryCompactTimer >= 0.0f) ? (float)g.Time - g.IO.ConfigWindowsMemoryCompactTimer : FLT_MAX;
for (int i = 0; i != g.Windows.Size; i++)
{
ImGuiWindow* window = g.Windows[i];
window->WasActive = window->Active;
window->BeginCount = 0;
window->Active = false;
window->WriteAccessed = false;
// Garbage collect transient buffers of recently unused windows
if (!window->WasActive && !window->MemoryCompacted && window->LastTimeActive < memory_compact_start_time)
GcCompactTransientWindowBuffers(window);
}
// Closing the focused window restore focus to the first active root window in descending z-order
if (g.NavWindow && !g.NavWindow->WasActive)
FocusTopMostWindowUnderOne(NULL, NULL);
// No window should be open at the beginning of the frame.
// But in order to allow the user to call NewFrame() multiple times without calling Render(), we are doing an explicit clear.
g.CurrentWindowStack.resize(0);
g.BeginPopupStack.resize(0);
ClosePopupsOverWindow(g.NavWindow, false);
// [DEBUG] Item picker tool - start with DebugStartItemPicker() - useful to visually select an item and break into its call-stack.
UpdateDebugToolItemPicker();
// Create implicit/fallback window - which we will only render it if the user has added something to it.
// We don't use "Debug" to avoid colliding with user trying to create a "Debug" window with custom flags.
// This fallback is particularly important as it avoid ImGui:: calls from crashing.
g.WithinFrameScopeWithImplicitWindow = true;
SetNextWindowSize(ImVec2(400,400), ImGuiCond_FirstUseEver);
Begin("Debug##Default");
IM_ASSERT(g.CurrentWindow->IsFallbackWindow == true);
#ifdef IMGUI_ENABLE_TEST_ENGINE
ImGuiTestEngineHook_PostNewFrame(&g);
#endif
}
// [DEBUG] Item picker tool - start with DebugStartItemPicker() - useful to visually select an item and break into its call-stack.
void ImGui::UpdateDebugToolItemPicker()
{
ImGuiContext& g = *GImGui;
g.DebugItemPickerBreakId = 0;
if (g.DebugItemPickerActive)
{
const ImGuiID hovered_id = g.HoveredIdPreviousFrame;
ImGui::SetMouseCursor(ImGuiMouseCursor_Hand);
if (ImGui::IsKeyPressedMap(ImGuiKey_Escape))
g.DebugItemPickerActive = false;
if (ImGui::IsMouseClicked(0) && hovered_id)
{
g.DebugItemPickerBreakId = hovered_id;
g.DebugItemPickerActive = false;
}
ImGui::SetNextWindowBgAlpha(0.60f);
ImGui::BeginTooltip();
ImGui::Text("HoveredId: 0x%08X", hovered_id);
ImGui::Text("Press ESC to abort picking.");
ImGui::TextColored(GetStyleColorVec4(hovered_id ? ImGuiCol_Text : ImGuiCol_TextDisabled), "Click to break in debugger!");
ImGui::EndTooltip();
}
}
void ImGui::Initialize(ImGuiContext* context)
{
ImGuiContext& g = *context;
IM_ASSERT(!g.Initialized && !g.SettingsLoaded);
// Add .ini handle for ImGuiWindow type
{
ImGuiSettingsHandler ini_handler;
ini_handler.TypeName = "Window";
ini_handler.TypeHash = ImHashStr("Window");
ini_handler.ReadOpenFn = WindowSettingsHandler_ReadOpen;
ini_handler.ReadLineFn = WindowSettingsHandler_ReadLine;
ini_handler.WriteAllFn = WindowSettingsHandler_WriteAll;
g.SettingsHandlers.push_back(ini_handler);
}
#ifdef IMGUI_HAS_TABLE
// Add .ini handle for ImGuiTable type
{
ImGuiSettingsHandler ini_handler;
ini_handler.TypeName = "Table";
ini_handler.TypeHash = ImHashStr("Table");
ini_handler.ReadOpenFn = TableSettingsHandler_ReadOpen;
ini_handler.ReadLineFn = TableSettingsHandler_ReadLine;
ini_handler.WriteAllFn = TableSettingsHandler_WriteAll;
g.SettingsHandlers.push_back(ini_handler);
}
#endif // #ifdef IMGUI_HAS_TABLE
#ifdef IMGUI_HAS_DOCK
#endif // #ifdef IMGUI_HAS_DOCK
g.Initialized = true;
}
// This function is merely here to free heap allocations.
void ImGui::Shutdown(ImGuiContext* context)
{
// The fonts atlas can be used prior to calling NewFrame(), so we clear it even if g.Initialized is FALSE (which would happen if we never called NewFrame)
ImGuiContext& g = *context;
if (g.IO.Fonts && g.FontAtlasOwnedByContext)
{
g.IO.Fonts->Locked = false;
IM_DELETE(g.IO.Fonts);
}
g.IO.Fonts = NULL;
// Cleanup of other data are conditional on actually having initialized Dear ImGui.
if (!g.Initialized)
return;
// Save settings (unless we haven't attempted to load them: CreateContext/DestroyContext without a call to NewFrame shouldn't save an empty file)
if (g.SettingsLoaded && g.IO.IniFilename != NULL)
{
ImGuiContext* backup_context = GImGui;
SetCurrentContext(context);
SaveIniSettingsToDisk(g.IO.IniFilename);
SetCurrentContext(backup_context);
}
// Clear everything else
for (int i = 0; i < g.Windows.Size; i++)
IM_DELETE(g.Windows[i]);
g.Windows.clear();
g.WindowsFocusOrder.clear();
g.WindowsTempSortBuffer.clear();
g.CurrentWindow = NULL;
g.CurrentWindowStack.clear();
g.WindowsById.Clear();
g.NavWindow = NULL;
g.HoveredWindow = g.HoveredRootWindow = NULL;
g.ActiveIdWindow = g.ActiveIdPreviousFrameWindow = NULL;
g.MovingWindow = NULL;
g.ColorModifiers.clear();
g.StyleModifiers.clear();
g.FontStack.clear();
g.OpenPopupStack.clear();
g.BeginPopupStack.clear();
g.DrawDataBuilder.ClearFreeMemory();
g.BackgroundDrawList.ClearFreeMemory();
g.ForegroundDrawList.ClearFreeMemory();
g.TabBars.Clear();
g.CurrentTabBarStack.clear();
g.ShrinkWidthBuffer.clear();
g.PrivateClipboard.clear();
g.MenusIdSubmittedThisFrame.clear();
g.InputTextState.ClearFreeMemory();
g.SettingsWindows.clear();
g.SettingsHandlers.clear();
if (g.LogFile)
{
#ifndef IMGUI_DISABLE_TTY_FUNCTIONS
if (g.LogFile != stdout)
#endif
ImFileClose(g.LogFile);
g.LogFile = NULL;
}
g.LogBuffer.clear();
g.Initialized = false;
}
// FIXME: Add a more explicit sort order in the window structure.
static int IMGUI_CDECL ChildWindowComparer(const void* lhs, const void* rhs)
{
const ImGuiWindow* const a = *(const ImGuiWindow* const *)lhs;
const ImGuiWindow* const b = *(const ImGuiWindow* const *)rhs;
if (int d = (a->Flags & ImGuiWindowFlags_Popup) - (b->Flags & ImGuiWindowFlags_Popup))
return d;
if (int d = (a->Flags & ImGuiWindowFlags_Tooltip) - (b->Flags & ImGuiWindowFlags_Tooltip))
return d;
return (a->BeginOrderWithinParent - b->BeginOrderWithinParent);
}
static void AddWindowToSortBuffer(ImVector<ImGuiWindow*>* out_sorted_windows, ImGuiWindow* window)
{
out_sorted_windows->push_back(window);
if (window->Active)
{
int count = window->DC.ChildWindows.Size;
if (count > 1)
ImQsort(window->DC.ChildWindows.Data, (size_t)count, sizeof(ImGuiWindow*), ChildWindowComparer);
for (int i = 0; i < count; i++)
{
ImGuiWindow* child = window->DC.ChildWindows[i];
if (child->Active)
AddWindowToSortBuffer(out_sorted_windows, child);
}
}
}
static void AddDrawListToDrawData(ImVector<ImDrawList*>* out_list, ImDrawList* draw_list)
{
if (draw_list->CmdBuffer.empty())
return;
// Remove trailing command if unused
ImDrawCmd& last_cmd = draw_list->CmdBuffer.back();
if (last_cmd.ElemCount == 0 && last_cmd.UserCallback == NULL)
{
draw_list->CmdBuffer.pop_back();
if (draw_list->CmdBuffer.empty())
return;
}
// Draw list sanity check. Detect mismatch between PrimReserve() calls and incrementing _VtxCurrentIdx, _VtxWritePtr etc.
// May trigger for you if you are using PrimXXX functions incorrectly.
IM_ASSERT(draw_list->VtxBuffer.Size == 0 || draw_list->_VtxWritePtr == draw_list->VtxBuffer.Data + draw_list->VtxBuffer.Size);
IM_ASSERT(draw_list->IdxBuffer.Size == 0 || draw_list->_IdxWritePtr == draw_list->IdxBuffer.Data + draw_list->IdxBuffer.Size);
if (!(draw_list->Flags & ImDrawListFlags_AllowVtxOffset))
IM_ASSERT((int)draw_list->_VtxCurrentIdx == draw_list->VtxBuffer.Size);
// Check that draw_list doesn't use more vertices than indexable (default ImDrawIdx = unsigned short = 2 bytes = 64K vertices per ImDrawList = per window)
// If this assert triggers because you are drawing lots of stuff manually:
// - First, make sure you are coarse clipping yourself and not trying to draw many things outside visible bounds.
// Be mindful that the ImDrawList API doesn't filter vertices. Use the Metrics window to inspect draw list contents.
// - If you want large meshes with more than 64K vertices, you can either:
// (A) Handle the ImDrawCmd::VtxOffset value in your renderer back-end, and set 'io.BackendFlags |= ImGuiBackendFlags_RendererHasVtxOffset'.
// Most example back-ends already support this from 1.71. Pre-1.71 back-ends won't.
// Some graphics API such as GL ES 1/2 don't have a way to offset the starting vertex so it is not supported for them.
// (B) Or handle 32-bit indices in your renderer back-end, and uncomment '#define ImDrawIdx unsigned int' line in imconfig.h.
// Most example back-ends already support this. For example, the OpenGL example code detect index size at compile-time:
// glDrawElements(GL_TRIANGLES, (GLsizei)pcmd->ElemCount, sizeof(ImDrawIdx) == 2 ? GL_UNSIGNED_SHORT : GL_UNSIGNED_INT, idx_buffer_offset);
// Your own engine or render API may use different parameters or function calls to specify index sizes.
// 2 and 4 bytes indices are generally supported by most graphics API.
// - If for some reason neither of those solutions works for you, a workaround is to call BeginChild()/EndChild() before reaching
// the 64K limit to split your draw commands in multiple draw lists.
if (sizeof(ImDrawIdx) == 2)
IM_ASSERT(draw_list->_VtxCurrentIdx < (1 << 16) && "Too many vertices in ImDrawList using 16-bit indices. Read comment above");
out_list->push_back(draw_list);
}
static void AddWindowToDrawData(ImVector<ImDrawList*>* out_render_list, ImGuiWindow* window)
{
ImGuiContext& g = *GImGui;
g.IO.MetricsRenderWindows++;
AddDrawListToDrawData(out_render_list, window->DrawList);
for (int i = 0; i < window->DC.ChildWindows.Size; i++)
{
ImGuiWindow* child = window->DC.ChildWindows[i];
if (IsWindowActiveAndVisible(child)) // clipped children may have been marked not active
AddWindowToDrawData(out_render_list, child);
}
}
// Layer is locked for the root window, however child windows may use a different viewport (e.g. extruding menu)
static void AddRootWindowToDrawData(ImGuiWindow* window)
{
ImGuiContext& g = *GImGui;
int layer = (window->Flags & ImGuiWindowFlags_Tooltip) ? 1 : 0;
AddWindowToDrawData(&g.DrawDataBuilder.Layers[layer], window);
}
void ImDrawDataBuilder::FlattenIntoSingleLayer()
{
int n = Layers[0].Size;
int size = n;
for (int i = 1; i < IM_ARRAYSIZE(Layers); i++)
size += Layers[i].Size;
Layers[0].resize(size);
for (int layer_n = 1; layer_n < IM_ARRAYSIZE(Layers); layer_n++)
{
ImVector<ImDrawList*>& layer = Layers[layer_n];
if (layer.empty())
continue;
memcpy(&Layers[0][n], &layer[0], layer.Size * sizeof(ImDrawList*));
n += layer.Size;
layer.resize(0);
}
}
static void SetupDrawData(ImVector<ImDrawList*>* draw_lists, ImDrawData* draw_data)
{
ImGuiIO& io = ImGui::GetIO();
draw_data->Valid = true;
draw_data->CmdLists = (draw_lists->Size > 0) ? draw_lists->Data : NULL;
draw_data->CmdListsCount = draw_lists->Size;
draw_data->TotalVtxCount = draw_data->TotalIdxCount = 0;
draw_data->DisplayPos = ImVec2(0.0f, 0.0f);
draw_data->DisplaySize = io.DisplaySize;
draw_data->FramebufferScale = io.DisplayFramebufferScale;
for (int n = 0; n < draw_lists->Size; n++)
{
draw_data->TotalVtxCount += draw_lists->Data[n]->VtxBuffer.Size;
draw_data->TotalIdxCount += draw_lists->Data[n]->IdxBuffer.Size;
}
}
// When using this function it is sane to ensure that float are perfectly rounded to integer values, to that e.g. (int)(max.x-min.x) in user's render produce correct result.
void ImGui::PushClipRect(const ImVec2& clip_rect_min, const ImVec2& clip_rect_max, bool intersect_with_current_clip_rect)
{
ImGuiWindow* window = GetCurrentWindow();
window->DrawList->PushClipRect(clip_rect_min, clip_rect_max, intersect_with_current_clip_rect);
window->ClipRect = window->DrawList->_ClipRectStack.back();
}
void ImGui::PopClipRect()
{
ImGuiWindow* window = GetCurrentWindow();
window->DrawList->PopClipRect();
window->ClipRect = window->DrawList->_ClipRectStack.back();
}
// This is normally called by Render(). You may want to call it directly if you want to avoid calling Render() but the gain will be very minimal.
void ImGui::EndFrame()
{
ImGuiContext& g = *GImGui;
IM_ASSERT(g.Initialized);
if (g.FrameCountEnded == g.FrameCount) // Don't process EndFrame() multiple times.
return;
IM_ASSERT(g.WithinFrameScope && "Forgot to call ImGui::NewFrame()?");
// Notify OS when our Input Method Editor cursor has moved (e.g. CJK inputs using Microsoft IME)
if (g.IO.ImeSetInputScreenPosFn && (g.PlatformImeLastPos.x == FLT_MAX || ImLengthSqr(g.PlatformImeLastPos - g.PlatformImePos) > 0.0001f))
{
g.IO.ImeSetInputScreenPosFn((int)g.PlatformImePos.x, (int)g.PlatformImePos.y);
g.PlatformImeLastPos = g.PlatformImePos;
}
ErrorCheckEndFrame();
// Hide implicit/fallback "Debug" window if it hasn't been used
g.WithinFrameScopeWithImplicitWindow = false;
if (g.CurrentWindow && !g.CurrentWindow->WriteAccessed)
g.CurrentWindow->Active = false;
End();
// Show CTRL+TAB list window
if (g.NavWindowingTarget != NULL)
NavUpdateWindowingOverlay();
// Drag and Drop: Elapse payload (if delivered, or if source stops being submitted)
if (g.DragDropActive)
{
bool is_delivered = g.DragDropPayload.Delivery;
bool is_elapsed = (g.DragDropPayload.DataFrameCount + 1 < g.FrameCount) && ((g.DragDropSourceFlags & ImGuiDragDropFlags_SourceAutoExpirePayload) || !IsMouseDown(g.DragDropMouseButton));
if (is_delivered || is_elapsed)
ClearDragDrop();
}
// Drag and Drop: Fallback for source tooltip. This is not ideal but better than nothing.
if (g.DragDropActive && g.DragDropSourceFrameCount < g.FrameCount)
{
g.DragDropWithinSource = true;
SetTooltip("...");
g.DragDropWithinSource = false;
}
// End frame
g.WithinFrameScope = false;
g.FrameCountEnded = g.FrameCount;
// Initiate moving window + handle left-click and right-click focus
UpdateMouseMovingWindowEndFrame();
// Sort the window list so that all child windows are after their parent
// We cannot do that on FocusWindow() because childs may not exist yet
g.WindowsTempSortBuffer.resize(0);
g.WindowsTempSortBuffer.reserve(g.Windows.Size);
for (int i = 0; i != g.Windows.Size; i++)
{
ImGuiWindow* window = g.Windows[i];
if (window->Active && (window->Flags & ImGuiWindowFlags_ChildWindow)) // if a child is active its parent will add it
continue;
AddWindowToSortBuffer(&g.WindowsTempSortBuffer, window);
}
// This usually assert if there is a mismatch between the ImGuiWindowFlags_ChildWindow / ParentWindow values and DC.ChildWindows[] in parents, aka we've done something wrong.
IM_ASSERT(g.Windows.Size == g.WindowsTempSortBuffer.Size);
g.Windows.swap(g.WindowsTempSortBuffer);
g.IO.MetricsActiveWindows = g.WindowsActiveCount;
// Unlock font atlas
g.IO.Fonts->Locked = false;
// Clear Input data for next frame
g.IO.MouseWheel = g.IO.MouseWheelH = 0.0f;
g.IO.InputQueueCharacters.resize(0);
memset(g.IO.NavInputs, 0, sizeof(g.IO.NavInputs));
}
void ImGui::Render()
{
ImGuiContext& g = *GImGui;
IM_ASSERT(g.Initialized);
if (g.FrameCountEnded != g.FrameCount)
EndFrame();
g.FrameCountRendered = g.FrameCount;
g.IO.MetricsRenderWindows = 0;
g.DrawDataBuilder.Clear();
// Add background ImDrawList
if (!g.BackgroundDrawList.VtxBuffer.empty())
AddDrawListToDrawData(&g.DrawDataBuilder.Layers[0], &g.BackgroundDrawList);
// Add ImDrawList to render
ImGuiWindow* windows_to_render_top_most[2];
windows_to_render_top_most[0] = (g.NavWindowingTarget && !(g.NavWindowingTarget->Flags & ImGuiWindowFlags_NoBringToFrontOnFocus)) ? g.NavWindowingTarget->RootWindow : NULL;
windows_to_render_top_most[1] = (g.NavWindowingTarget ? g.NavWindowingList : NULL);
for (int n = 0; n != g.Windows.Size; n++)
{
ImGuiWindow* window = g.Windows[n];
if (IsWindowActiveAndVisible(window) && (window->Flags & ImGuiWindowFlags_ChildWindow) == 0 && window != windows_to_render_top_most[0] && window != windows_to_render_top_most[1])
AddRootWindowToDrawData(window);
}
for (int n = 0; n < IM_ARRAYSIZE(windows_to_render_top_most); n++)
if (windows_to_render_top_most[n] && IsWindowActiveAndVisible(windows_to_render_top_most[n])) // NavWindowingTarget is always temporarily displayed as the top-most window
AddRootWindowToDrawData(windows_to_render_top_most[n]);
g.DrawDataBuilder.FlattenIntoSingleLayer();
// Draw software mouse cursor if requested
if (g.IO.MouseDrawCursor)
RenderMouseCursor(&g.ForegroundDrawList, g.IO.MousePos, g.Style.MouseCursorScale, g.MouseCursor, IM_COL32_WHITE, IM_COL32_BLACK, IM_COL32(0, 0, 0, 48));
// Add foreground ImDrawList
if (!g.ForegroundDrawList.VtxBuffer.empty())
AddDrawListToDrawData(&g.DrawDataBuilder.Layers[0], &g.ForegroundDrawList);
// Setup ImDrawData structure for end-user
SetupDrawData(&g.DrawDataBuilder.Layers[0], &g.DrawData);
g.IO.MetricsRenderVertices = g.DrawData.TotalVtxCount;
g.IO.MetricsRenderIndices = g.DrawData.TotalIdxCount;
// (Legacy) Call the Render callback function. The current prefer way is to let the user retrieve GetDrawData() and call the render function themselves.
#ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS
if (g.DrawData.CmdListsCount > 0 && g.IO.RenderDrawListsFn != NULL)
g.IO.RenderDrawListsFn(&g.DrawData);
#endif
}
// Calculate text size. Text can be multi-line. Optionally ignore text after a ## marker.
// CalcTextSize("") should return ImVec2(0.0f, g.FontSize)
ImVec2 ImGui::CalcTextSize(const char* text, const char* text_end, bool hide_text_after_double_hash, float wrap_width)
{
ImGuiContext& g = *GImGui;
const char* text_display_end;
if (hide_text_after_double_hash)
text_display_end = FindRenderedTextEnd(text, text_end); // Hide anything after a '##' string
else
text_display_end = text_end;
ImFont* font = g.Font;
const float font_size = g.FontSize;
if (text == text_display_end)
return ImVec2(0.0f, font_size);
ImVec2 text_size = font->CalcTextSizeA(font_size, FLT_MAX, wrap_width, text, text_display_end, NULL);
// Round
text_size.x = IM_FLOOR(text_size.x + 0.95f);
return text_size;
}
// Find window given position, search front-to-back
// FIXME: Note that we have an inconsequential lag here: OuterRectClipped is updated in Begin(), so windows moved programatically
// with SetWindowPos() and not SetNextWindowPos() will have that rectangle lagging by a frame at the time FindHoveredWindow() is
// called, aka before the next Begin(). Moving window isn't affected.
static void FindHoveredWindow()
{
ImGuiContext& g = *GImGui;
ImGuiWindow* hovered_window = NULL;
if (g.MovingWindow && !(g.MovingWindow->Flags & ImGuiWindowFlags_NoMouseInputs))
hovered_window = g.MovingWindow;
ImVec2 padding_regular = g.Style.TouchExtraPadding;
ImVec2 padding_for_resize_from_edges = g.IO.ConfigWindowsResizeFromEdges ? ImMax(g.Style.TouchExtraPadding, ImVec2(WINDOWS_RESIZE_FROM_EDGES_HALF_THICKNESS, WINDOWS_RESIZE_FROM_EDGES_HALF_THICKNESS)) : padding_regular;
for (int i = g.Windows.Size - 1; i >= 0; i--)
{
ImGuiWindow* window = g.Windows[i];
if (!window->Active || window->Hidden)
continue;
if (window->Flags & ImGuiWindowFlags_NoMouseInputs)
continue;
// Using the clipped AABB, a child window will typically be clipped by its parent (not always)
ImRect bb(window->OuterRectClipped);
if (window->Flags & (ImGuiWindowFlags_ChildWindow | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_AlwaysAutoResize))
bb.Expand(padding_regular);
else
bb.Expand(padding_for_resize_from_edges);
if (!bb.Contains(g.IO.MousePos))
continue;
// Those seemingly unnecessary extra tests are because the code here is a little different in viewport/docking branches.
if (hovered_window == NULL)
hovered_window = window;
if (hovered_window)
break;
}
g.HoveredWindow = hovered_window;
g.HoveredRootWindow = g.HoveredWindow ? g.HoveredWindow->RootWindow : NULL;
}
// Test if mouse cursor is hovering given rectangle
// NB- Rectangle is clipped by our current clip setting
// NB- Expand the rectangle to be generous on imprecise inputs systems (g.Style.TouchExtraPadding)
bool ImGui::IsMouseHoveringRect(const ImVec2& r_min, const ImVec2& r_max, bool clip)
{
ImGuiContext& g = *GImGui;
// Clip
ImRect rect_clipped(r_min, r_max);
if (clip)
rect_clipped.ClipWith(g.CurrentWindow->ClipRect);
// Expand for touch input
const ImRect rect_for_touch(rect_clipped.Min - g.Style.TouchExtraPadding, rect_clipped.Max + g.Style.TouchExtraPadding);
if (!rect_for_touch.Contains(g.IO.MousePos))
return false;
return true;
}
int ImGui::GetKeyIndex(ImGuiKey imgui_key)
{
IM_ASSERT(imgui_key >= 0 && imgui_key < ImGuiKey_COUNT);
ImGuiContext& g = *GImGui;
return g.IO.KeyMap[imgui_key];
}
// Note that dear imgui doesn't know the semantic of each entry of io.KeysDown[]!
// Use your own indices/enums according to how your back-end/engine stored them into io.KeysDown[]!
bool ImGui::IsKeyDown(int user_key_index)
{
if (user_key_index < 0)
return false;
ImGuiContext& g = *GImGui;
IM_ASSERT(user_key_index >= 0 && user_key_index < IM_ARRAYSIZE(g.IO.KeysDown));
return g.IO.KeysDown[user_key_index];
}
// t0 = previous time (e.g.: g.Time - g.IO.DeltaTime)
// t1 = current time (e.g.: g.Time)
// An event is triggered at:
// t = 0.0f t = repeat_delay, t = repeat_delay + repeat_rate*N
int ImGui::CalcTypematicRepeatAmount(float t0, float t1, float repeat_delay, float repeat_rate)
{
if (t1 == 0.0f)
return 1;
if (t0 >= t1)
return 0;
if (repeat_rate <= 0.0f)
return (t0 < repeat_delay) && (t1 >= repeat_delay);
const int count_t0 = (t0 < repeat_delay) ? -1 : (int)((t0 - repeat_delay) / repeat_rate);
const int count_t1 = (t1 < repeat_delay) ? -1 : (int)((t1 - repeat_delay) / repeat_rate);
const int count = count_t1 - count_t0;
return count;
}
int ImGui::GetKeyPressedAmount(int key_index, float repeat_delay, float repeat_rate)
{
ImGuiContext& g = *GImGui;
if (key_index < 0)
return 0;
IM_ASSERT(key_index >= 0 && key_index < IM_ARRAYSIZE(g.IO.KeysDown));
const float t = g.IO.KeysDownDuration[key_index];
return CalcTypematicRepeatAmount(t - g.IO.DeltaTime, t, repeat_delay, repeat_rate);
}
bool ImGui::IsKeyPressed(int user_key_index, bool repeat)
{
ImGuiContext& g = *GImGui;
if (user_key_index < 0)
return false;
IM_ASSERT(user_key_index >= 0 && user_key_index < IM_ARRAYSIZE(g.IO.KeysDown));
const float t = g.IO.KeysDownDuration[user_key_index];
if (t == 0.0f)
return true;
if (repeat && t > g.IO.KeyRepeatDelay)
return GetKeyPressedAmount(user_key_index, g.IO.KeyRepeatDelay, g.IO.KeyRepeatRate) > 0;
return false;
}
bool ImGui::IsKeyReleased(int user_key_index)
{
ImGuiContext& g = *GImGui;
if (user_key_index < 0) return false;
IM_ASSERT(user_key_index >= 0 && user_key_index < IM_ARRAYSIZE(g.IO.KeysDown));
return g.IO.KeysDownDurationPrev[user_key_index] >= 0.0f && !g.IO.KeysDown[user_key_index];
}
bool ImGui::IsMouseDown(ImGuiMouseButton button)
{
ImGuiContext& g = *GImGui;
IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown));
return g.IO.MouseDown[button];
}
bool ImGui::IsMouseClicked(ImGuiMouseButton button, bool repeat)
{
ImGuiContext& g = *GImGui;
IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown));
const float t = g.IO.MouseDownDuration[button];
if (t == 0.0f)
return true;
if (repeat && t > g.IO.KeyRepeatDelay)
{
// FIXME: 2019/05/03: Our old repeat code was wrong here and led to doubling the repeat rate, which made it an ok rate for repeat on mouse hold.
int amount = CalcTypematicRepeatAmount(t - g.IO.DeltaTime, t, g.IO.KeyRepeatDelay, g.IO.KeyRepeatRate * 0.50f);
if (amount > 0)
return true;
}
return false;
}
bool ImGui::IsMouseReleased(ImGuiMouseButton button)
{
ImGuiContext& g = *GImGui;
IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown));
return g.IO.MouseReleased[button];
}
bool ImGui::IsMouseDoubleClicked(ImGuiMouseButton button)
{
ImGuiContext& g = *GImGui;
IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown));
return g.IO.MouseDoubleClicked[button];
}
// [Internal] This doesn't test if the button is pressed
bool ImGui::IsMouseDragPastThreshold(ImGuiMouseButton button, float lock_threshold)
{
ImGuiContext& g = *GImGui;
IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown));
if (lock_threshold < 0.0f)
lock_threshold = g.IO.MouseDragThreshold;
return g.IO.MouseDragMaxDistanceSqr[button] >= lock_threshold * lock_threshold;
}
bool ImGui::IsMouseDragging(ImGuiMouseButton button, float lock_threshold)
{
ImGuiContext& g = *GImGui;
IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown));
if (!g.IO.MouseDown[button])
return false;
return IsMouseDragPastThreshold(button, lock_threshold);
}
ImVec2 ImGui::GetMousePos()
{
ImGuiContext& g = *GImGui;
return g.IO.MousePos;
}
// NB: prefer to call right after BeginPopup(). At the time Selectable/MenuItem is activated, the popup is already closed!
ImVec2 ImGui::GetMousePosOnOpeningCurrentPopup()
{
ImGuiContext& g = *GImGui;
if (g.BeginPopupStack.Size > 0)
return g.OpenPopupStack[g.BeginPopupStack.Size-1].OpenMousePos;
return g.IO.MousePos;
}
// We typically use ImVec2(-FLT_MAX,-FLT_MAX) to denote an invalid mouse position.
bool ImGui::IsMousePosValid(const ImVec2* mouse_pos)
{
// The assert is only to silence a false-positive in XCode Static Analysis.
// Because GImGui is not dereferenced in every code path, the static analyzer assume that it may be NULL (which it doesn't for other functions).
IM_ASSERT(GImGui != NULL);
const float MOUSE_INVALID = -256000.0f;
ImVec2 p = mouse_pos ? *mouse_pos : GImGui->IO.MousePos;
return p.x >= MOUSE_INVALID && p.y >= MOUSE_INVALID;
}
bool ImGui::IsAnyMouseDown()
{
ImGuiContext& g = *GImGui;
for (int n = 0; n < IM_ARRAYSIZE(g.IO.MouseDown); n++)
if (g.IO.MouseDown[n])
return true;
return false;
}
// Return the delta from the initial clicking position while the mouse button is clicked or was just released.
// This is locked and return 0.0f until the mouse moves past a distance threshold at least once.
// NB: This is only valid if IsMousePosValid(). Back-ends in theory should always keep mouse position valid when dragging even outside the client window.
ImVec2 ImGui::GetMouseDragDelta(ImGuiMouseButton button, float lock_threshold)
{
ImGuiContext& g = *GImGui;
IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown));
if (lock_threshold < 0.0f)
lock_threshold = g.IO.MouseDragThreshold;
if (g.IO.MouseDown[button] || g.IO.MouseReleased[button])
if (g.IO.MouseDragMaxDistanceSqr[button] >= lock_threshold * lock_threshold)
if (IsMousePosValid(&g.IO.MousePos) && IsMousePosValid(&g.IO.MouseClickedPos[button]))
return g.IO.MousePos - g.IO.MouseClickedPos[button];
return ImVec2(0.0f, 0.0f);
}
void ImGui::ResetMouseDragDelta(ImGuiMouseButton button)
{
ImGuiContext& g = *GImGui;
IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown));
// NB: We don't need to reset g.IO.MouseDragMaxDistanceSqr
g.IO.MouseClickedPos[button] = g.IO.MousePos;
}
ImGuiMouseCursor ImGui::GetMouseCursor()
{
return GImGui->MouseCursor;
}
void ImGui::SetMouseCursor(ImGuiMouseCursor cursor_type)
{
GImGui->MouseCursor = cursor_type;
}
void ImGui::CaptureKeyboardFromApp(bool capture)
{
GImGui->WantCaptureKeyboardNextFrame = capture ? 1 : 0;
}
void ImGui::CaptureMouseFromApp(bool capture)
{
GImGui->WantCaptureMouseNextFrame = capture ? 1 : 0;
}
bool ImGui::IsItemActive()
{
ImGuiContext& g = *GImGui;
if (g.ActiveId)
{
ImGuiWindow* window = g.CurrentWindow;
return g.ActiveId == window->DC.LastItemId;
}
return false;
}
bool ImGui::IsItemActivated()
{
ImGuiContext& g = *GImGui;
if (g.ActiveId)
{
ImGuiWindow* window = g.CurrentWindow;
if (g.ActiveId == window->DC.LastItemId && g.ActiveIdPreviousFrame != window->DC.LastItemId)
return true;
}
return false;
}
bool ImGui::IsItemDeactivated()
{
ImGuiContext& g = *GImGui;
ImGuiWindow* window = g.CurrentWindow;
if (window->DC.LastItemStatusFlags & ImGuiItemStatusFlags_HasDeactivated)
return (window->DC.LastItemStatusFlags & ImGuiItemStatusFlags_Deactivated) != 0;
return (g.ActiveIdPreviousFrame == window->DC.LastItemId && g.ActiveIdPreviousFrame != 0 && g.ActiveId != window->DC.LastItemId);
}
bool ImGui::IsItemDeactivatedAfterEdit()
{
ImGuiContext& g = *GImGui;
return IsItemDeactivated() && (g.ActiveIdPreviousFrameHasBeenEditedBefore || (g.ActiveId == 0 && g.ActiveIdHasBeenEditedBefore));
}
bool ImGui::IsItemFocused()
{
ImGuiContext& g = *GImGui;
ImGuiWindow* window = g.CurrentWindow;
if (g.NavId == 0 || g.NavDisableHighlight || g.NavId != window->DC.LastItemId)
return false;
return true;
}
bool ImGui::IsItemClicked(ImGuiMouseButton mouse_button)
{
return IsMouseClicked(mouse_button) && IsItemHovered(ImGuiHoveredFlags_None);
}
bool ImGui::IsItemToggledOpen()
{
ImGuiContext& g = *GImGui;
return (g.CurrentWindow->DC.LastItemStatusFlags & ImGuiItemStatusFlags_ToggledOpen) ? true : false;
}
bool ImGui::IsItemToggledSelection()
{
ImGuiContext& g = *GImGui;
return (g.CurrentWindow->DC.LastItemStatusFlags & ImGuiItemStatusFlags_ToggledSelection) ? true : false;
}
bool ImGui::IsAnyItemHovered()
{
ImGuiContext& g = *GImGui;
return g.HoveredId != 0 || g.HoveredIdPreviousFrame != 0;
}
bool ImGui::IsAnyItemActive()
{
ImGuiContext& g = *GImGui;
return g.ActiveId != 0;
}
bool ImGui::IsAnyItemFocused()
{
ImGuiContext& g = *GImGui;
return g.NavId != 0 && !g.NavDisableHighlight;
}
bool ImGui::IsItemVisible()
{
ImGuiWindow* window = GetCurrentWindowRead();
return window->ClipRect.Overlaps(window->DC.LastItemRect);
}
bool ImGui::IsItemEdited()
{
ImGuiWindow* window = GetCurrentWindowRead();
return (window->DC.LastItemStatusFlags & ImGuiItemStatusFlags_Edited) != 0;
}
// Allow last item to be overlapped by a subsequent item. Both may be activated during the same frame before the later one takes priority.
void ImGui::SetItemAllowOverlap()
{
ImGuiContext& g = *GImGui;
if (g.HoveredId == g.CurrentWindow->DC.LastItemId)
g.HoveredIdAllowOverlap = true;
if (g.ActiveId == g.CurrentWindow->DC.LastItemId)
g.ActiveIdAllowOverlap = true;
}
ImVec2 ImGui::GetItemRectMin()
{
ImGuiWindow* window = GetCurrentWindowRead();
return window->DC.LastItemRect.Min;
}
ImVec2 ImGui::GetItemRectMax()
{
ImGuiWindow* window = GetCurrentWindowRead();
return window->DC.LastItemRect.Max;
}
ImVec2 ImGui::GetItemRectSize()
{
ImGuiWindow* window = GetCurrentWindowRead();
return window->DC.LastItemRect.GetSize();
}
static ImRect GetViewportRect()
{
ImGuiContext& g = *GImGui;
return ImRect(0.0f, 0.0f, g.IO.DisplaySize.x, g.IO.DisplaySize.y);
}
bool ImGui::BeginChildEx(const char* name, ImGuiID id, const ImVec2& size_arg, bool border, ImGuiWindowFlags flags)
{
ImGuiContext& g = *GImGui;
ImGuiWindow* parent_window = g.CurrentWindow;
flags |= ImGuiWindowFlags_NoTitleBar|ImGuiWindowFlags_NoResize|ImGuiWindowFlags_NoSavedSettings|ImGuiWindowFlags_ChildWindow;
flags |= (parent_window->Flags & ImGuiWindowFlags_NoMove); // Inherit the NoMove flag
// Size
const ImVec2 content_avail = GetContentRegionAvail();
ImVec2 size = ImFloor(size_arg);
const int auto_fit_axises = ((size.x == 0.0f) ? (1 << ImGuiAxis_X) : 0x00) | ((size.y == 0.0f) ? (1 << ImGuiAxis_Y) : 0x00);
if (size.x <= 0.0f)
size.x = ImMax(content_avail.x + size.x, 4.0f); // Arbitrary minimum child size (0.0f causing too much issues)
if (size.y <= 0.0f)
size.y = ImMax(content_avail.y + size.y, 4.0f);
SetNextWindowSize(size);
// Build up name. If you need to append to a same child from multiple location in the ID stack, use BeginChild(ImGuiID id) with a stable value.
char title[256];
if (name)
ImFormatString(title, IM_ARRAYSIZE(title), "%s/%s_%08X", parent_window->Name, name, id);
else
ImFormatString(title, IM_ARRAYSIZE(title), "%s/%08X", parent_window->Name, id);
const float backup_border_size = g.Style.ChildBorderSize;
if (!border)
g.Style.ChildBorderSize = 0.0f;
bool ret = Begin(title, NULL, flags);
g.Style.ChildBorderSize = backup_border_size;
ImGuiWindow* child_window = g.CurrentWindow;
child_window->ChildId = id;
child_window->AutoFitChildAxises = (ImS8)auto_fit_axises;
// Set the cursor to handle case where the user called SetNextWindowPos()+BeginChild() manually.
// While this is not really documented/defined, it seems that the expected thing to do.
if (child_window->BeginCount == 1)
parent_window->DC.CursorPos = child_window->Pos;
// Process navigation-in immediately so NavInit can run on first frame
if (g.NavActivateId == id && !(flags & ImGuiWindowFlags_NavFlattened) && (child_window->DC.NavLayerActiveMask != 0 || child_window->DC.NavHasScroll))
{
FocusWindow(child_window);
NavInitWindow(child_window, false);
SetActiveID(id+1, child_window); // Steal ActiveId with a dummy id so that key-press won't activate child item
g.ActiveIdSource = ImGuiInputSource_Nav;
}
return ret;
}
bool ImGui::BeginChild(const char* str_id, const ImVec2& size_arg, bool border, ImGuiWindowFlags extra_flags)
{
ImGuiWindow* window = GetCurrentWindow();
return BeginChildEx(str_id, window->GetID(str_id), size_arg, border, extra_flags);
}
bool ImGui::BeginChild(ImGuiID id, const ImVec2& size_arg, bool border, ImGuiWindowFlags extra_flags)
{
IM_ASSERT(id != 0);
return BeginChildEx(NULL, id, size_arg, border, extra_flags);
}
void ImGui::EndChild()
{
ImGuiContext& g = *GImGui;
ImGuiWindow* window = g.CurrentWindow;
IM_ASSERT(g.WithinEndChild == false);
IM_ASSERT(window->Flags & ImGuiWindowFlags_ChildWindow); // Mismatched BeginChild()/EndChild() calls
g.WithinEndChild = true;
if (window->BeginCount > 1)
{
End();
}
else
{
ImVec2 sz = window->Size;
if (window->AutoFitChildAxises & (1 << ImGuiAxis_X)) // Arbitrary minimum zero-ish child size of 4.0f causes less trouble than a 0.0f
sz.x = ImMax(4.0f, sz.x);
if (window->AutoFitChildAxises & (1 << ImGuiAxis_Y))
sz.y = ImMax(4.0f, sz.y);
End();
ImGuiWindow* parent_window = g.CurrentWindow;
ImRect bb(parent_window->DC.CursorPos, parent_window->DC.CursorPos + sz);
ItemSize(sz);
if ((window->DC.NavLayerActiveMask != 0 || window->DC.NavHasScroll) && !(window->Flags & ImGuiWindowFlags_NavFlattened))
{
ItemAdd(bb, window->ChildId);
RenderNavHighlight(bb, window->ChildId);
// When browsing a window that has no activable items (scroll only) we keep a highlight on the child
if (window->DC.NavLayerActiveMask == 0 && window == g.NavWindow)
RenderNavHighlight(ImRect(bb.Min - ImVec2(2,2), bb.Max + ImVec2(2,2)), g.NavId, ImGuiNavHighlightFlags_TypeThin);
}
else
{
// Not navigable into
ItemAdd(bb, 0);
}
}
g.WithinEndChild = false;
}
// Helper to create a child window / scrolling region that looks like a normal widget frame.
bool ImGui::BeginChildFrame(ImGuiID id, const ImVec2& size, ImGuiWindowFlags extra_flags)
{
ImGuiContext& g = *GImGui;
const ImGuiStyle& style = g.Style;
PushStyleColor(ImGuiCol_ChildBg, style.Colors[ImGuiCol_FrameBg]);
PushStyleVar(ImGuiStyleVar_ChildRounding, style.FrameRounding);
PushStyleVar(ImGuiStyleVar_ChildBorderSize, style.FrameBorderSize);
PushStyleVar(ImGuiStyleVar_WindowPadding, style.FramePadding);
bool ret = BeginChild(id, size, true, ImGuiWindowFlags_NoMove | ImGuiWindowFlags_AlwaysUseWindowPadding | extra_flags);
PopStyleVar(3);
PopStyleColor();
return ret;
}
void ImGui::EndChildFrame()
{
EndChild();
}
static void SetWindowConditionAllowFlags(ImGuiWindow* window, ImGuiCond flags, bool enabled)
{
window->SetWindowPosAllowFlags = enabled ? (window->SetWindowPosAllowFlags | flags) : (window->SetWindowPosAllowFlags & ~flags);
window->SetWindowSizeAllowFlags = enabled ? (window->SetWindowSizeAllowFlags | flags) : (window->SetWindowSizeAllowFlags & ~flags);
window->SetWindowCollapsedAllowFlags = enabled ? (window->SetWindowCollapsedAllowFlags | flags) : (window->SetWindowCollapsedAllowFlags & ~flags);
}
ImGuiWindow* ImGui::FindWindowByID(ImGuiID id)
{
ImGuiContext& g = *GImGui;
return (ImGuiWindow*)g.WindowsById.GetVoidPtr(id);
}
ImGuiWindow* ImGui::FindWindowByName(const char* name)
{
ImGuiID id = ImHashStr(name);
return FindWindowByID(id);
}
static ImGuiWindow* CreateNewWindow(const char* name, ImVec2 size, ImGuiWindowFlags flags)
{
ImGuiContext& g = *GImGui;
//IMGUI_DEBUG_LOG("CreateNewWindow '%s', flags = 0x%08X\n", name, flags);
// Create window the first time
ImGuiWindow* window = IM_NEW(ImGuiWindow)(&g, name);
window->Flags = flags;
g.WindowsById.SetVoidPtr(window->ID, window);
// Default/arbitrary window position. Use SetNextWindowPos() with the appropriate condition flag to change the initial position of a window.
window->Pos = ImVec2(60, 60);
// User can disable loading and saving of settings. Tooltip and child windows also don't store settings.
if (!(flags & ImGuiWindowFlags_NoSavedSettings))
if (ImGuiWindowSettings* settings = ImGui::FindWindowSettings(window->ID))
{
// Retrieve settings from .ini file
window->SettingsOffset = g.SettingsWindows.offset_from_ptr(settings);
SetWindowConditionAllowFlags(window, ImGuiCond_FirstUseEver, false);
window->Pos = ImVec2(settings->Pos.x, settings->Pos.y);
window->Collapsed = settings->Collapsed;
if (settings->Size.x > 0 && settings->Size.y > 0)
size = ImVec2(settings->Size.x, settings->Size.y);
}
window->Size = window->SizeFull = ImFloor(size);
window->DC.CursorStartPos = window->DC.CursorMaxPos = window->Pos; // So first call to CalcContentSize() doesn't return crazy values
if ((flags & ImGuiWindowFlags_AlwaysAutoResize) != 0)
{
window->AutoFitFramesX = window->AutoFitFramesY = 2;
window->AutoFitOnlyGrows = false;
}
else
{
if (window->Size.x <= 0.0f)
window->AutoFitFramesX = 2;
if (window->Size.y <= 0.0f)
window->AutoFitFramesY = 2;
window->AutoFitOnlyGrows = (window->AutoFitFramesX > 0) || (window->AutoFitFramesY > 0);
}
g.WindowsFocusOrder.push_back(window);
if (flags & ImGuiWindowFlags_NoBringToFrontOnFocus)
g.Windows.push_front(window); // Quite slow but rare and only once
else
g.Windows.push_back(window);
return window;
}
static ImVec2 CalcWindowSizeAfterConstraint(ImGuiWindow* window, ImVec2 new_size)
{
ImGuiContext& g = *GImGui;
if (g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasSizeConstraint)
{
// Using -1,-1 on either X/Y axis to preserve the current size.
ImRect cr = g.NextWindowData.SizeConstraintRect;
new_size.x = (cr.Min.x >= 0 && cr.Max.x >= 0) ? ImClamp(new_size.x, cr.Min.x, cr.Max.x) : window->SizeFull.x;
new_size.y = (cr.Min.y >= 0 && cr.Max.y >= 0) ? ImClamp(new_size.y, cr.Min.y, cr.Max.y) : window->SizeFull.y;
if (g.NextWindowData.SizeCallback)
{
ImGuiSizeCallbackData data;
data.UserData = g.NextWindowData.SizeCallbackUserData;
data.Pos = window->Pos;
data.CurrentSize = window->SizeFull;
data.DesiredSize = new_size;
g.NextWindowData.SizeCallback(&data);
new_size = data.DesiredSize;
}
new_size.x = IM_FLOOR(new_size.x);
new_size.y = IM_FLOOR(new_size.y);
}
// Minimum size
if (!(window->Flags & (ImGuiWindowFlags_ChildWindow | ImGuiWindowFlags_AlwaysAutoResize)))
{
ImGuiWindow* window_for_height = window;
new_size = ImMax(new_size, g.Style.WindowMinSize);
new_size.y = ImMax(new_size.y, window_for_height->TitleBarHeight() + window_for_height->MenuBarHeight() + ImMax(0.0f, g.Style.WindowRounding - 1.0f)); // Reduce artifacts with very small windows
}
return new_size;
}
static ImVec2 CalcWindowContentSize(ImGuiWindow* window)
{
if (window->Collapsed)
if (window->AutoFitFramesX <= 0 && window->AutoFitFramesY <= 0)
return window->ContentSize;
if (window->Hidden && window->HiddenFramesCannotSkipItems == 0 && window->HiddenFramesCanSkipItems > 0)
return window->ContentSize;
ImVec2 sz;
sz.x = IM_FLOOR((window->ContentSizeExplicit.x != 0.0f) ? window->ContentSizeExplicit.x : window->DC.CursorMaxPos.x - window->DC.CursorStartPos.x);
sz.y = IM_FLOOR((window->ContentSizeExplicit.y != 0.0f) ? window->ContentSizeExplicit.y : window->DC.CursorMaxPos.y - window->DC.CursorStartPos.y);
return sz;
}
static ImVec2 CalcWindowAutoFitSize(ImGuiWindow* window, const ImVec2& size_contents)
{
ImGuiContext& g = *GImGui;
ImGuiStyle& style = g.Style;
ImVec2 size_decorations = ImVec2(0.0f, window->TitleBarHeight() + window->MenuBarHeight());
ImVec2 size_pad = window->WindowPadding * 2.0f;
ImVec2 size_desired = size_contents + size_pad + size_decorations;
if (window->Flags & ImGuiWindowFlags_Tooltip)
{
// Tooltip always resize
return size_desired;
}
else
{
// Maximum window size is determined by the viewport size or monitor size
const bool is_popup = (window->Flags & ImGuiWindowFlags_Popup) != 0;
const bool is_menu = (window->Flags & ImGuiWindowFlags_ChildMenu) != 0;
ImVec2 size_min = style.WindowMinSize;
if (is_popup || is_menu) // Popups and menus bypass style.WindowMinSize by default, but we give then a non-zero minimum size to facilitate understanding problematic cases (e.g. empty popups)
size_min = ImMin(size_min, ImVec2(4.0f, 4.0f));
ImVec2 size_auto_fit = ImClamp(size_desired, size_min, ImMax(size_min, g.IO.DisplaySize - style.DisplaySafeAreaPadding * 2.0f));
// When the window cannot fit all contents (either because of constraints, either because screen is too small),
// we are growing the size on the other axis to compensate for expected scrollbar. FIXME: Might turn bigger than ViewportSize-WindowPadding.
ImVec2 size_auto_fit_after_constraint = CalcWindowSizeAfterConstraint(window, size_auto_fit);
bool will_have_scrollbar_x = (size_auto_fit_after_constraint.x - size_pad.x - size_decorations.x < size_contents.x && !(window->Flags & ImGuiWindowFlags_NoScrollbar) && (window->Flags & ImGuiWindowFlags_HorizontalScrollbar)) || (window->Flags & ImGuiWindowFlags_AlwaysHorizontalScrollbar);
bool will_have_scrollbar_y = (size_auto_fit_after_constraint.y - size_pad.y - size_decorations.y < size_contents.y && !(window->Flags & ImGuiWindowFlags_NoScrollbar)) || (window->Flags & ImGuiWindowFlags_AlwaysVerticalScrollbar);
if (will_have_scrollbar_x)
size_auto_fit.y += style.ScrollbarSize;
if (will_have_scrollbar_y)
size_auto_fit.x += style.ScrollbarSize;
return size_auto_fit;
}
}
ImVec2 ImGui::CalcWindowExpectedSize(ImGuiWindow* window)
{
ImVec2 size_contents = CalcWindowContentSize(window);
ImVec2 size_auto_fit = CalcWindowAutoFitSize(window, size_contents);
ImVec2 size_final = CalcWindowSizeAfterConstraint(window, size_auto_fit);
return size_final;
}
static ImGuiCol GetWindowBgColorIdxFromFlags(ImGuiWindowFlags flags)
{
if (flags & (ImGuiWindowFlags_Tooltip | ImGuiWindowFlags_Popup))
return ImGuiCol_PopupBg;
if (flags & ImGuiWindowFlags_ChildWindow)
return ImGuiCol_ChildBg;
return ImGuiCol_WindowBg;
}
static void CalcResizePosSizeFromAnyCorner(ImGuiWindow* window, const ImVec2& corner_target, const ImVec2& corner_norm, ImVec2* out_pos, ImVec2* out_size)
{
ImVec2 pos_min = ImLerp(corner_target, window->Pos, corner_norm); // Expected window upper-left
ImVec2 pos_max = ImLerp(window->Pos + window->Size, corner_target, corner_norm); // Expected window lower-right
ImVec2 size_expected = pos_max - pos_min;
ImVec2 size_constrained = CalcWindowSizeAfterConstraint(window, size_expected);
*out_pos = pos_min;
if (corner_norm.x == 0.0f)
out_pos->x -= (size_constrained.x - size_expected.x);
if (corner_norm.y == 0.0f)
out_pos->y -= (size_constrained.y - size_expected.y);
*out_size = size_constrained;
}
struct ImGuiResizeGripDef
{
ImVec2 CornerPosN;
ImVec2 InnerDir;
int AngleMin12, AngleMax12;
};
static const ImGuiResizeGripDef resize_grip_def[4] =
{
{ ImVec2(1,1), ImVec2(-1,-1), 0, 3 }, // Lower-right
{ ImVec2(0,1), ImVec2(+1,-1), 3, 6 }, // Lower-left
{ ImVec2(0,0), ImVec2(+1,+1), 6, 9 }, // Upper-left (Unused)
{ ImVec2(1,0), ImVec2(-1,+1), 9,12 }, // Upper-right (Unused)
};
static ImRect GetResizeBorderRect(ImGuiWindow* window, int border_n, float perp_padding, float thickness)
{
ImRect rect = window->Rect();
if (thickness == 0.0f) rect.Max -= ImVec2(1,1);
if (border_n == 0) return ImRect(rect.Min.x + perp_padding, rect.Min.y - thickness, rect.Max.x - perp_padding, rect.Min.y + thickness); // Top
if (border_n == 1) return ImRect(rect.Max.x - thickness, rect.Min.y + perp_padding, rect.Max.x + thickness, rect.Max.y - perp_padding); // Right
if (border_n == 2) return ImRect(rect.Min.x + perp_padding, rect.Max.y - thickness, rect.Max.x - perp_padding, rect.Max.y + thickness); // Bottom
if (border_n == 3) return ImRect(rect.Min.x - thickness, rect.Min.y + perp_padding, rect.Min.x + thickness, rect.Max.y - perp_padding); // Left
IM_ASSERT(0);
return ImRect();
}
// 0..3: corners (Lower-right, Lower-left, Unused, Unused)
// 4..7: borders (Top, Right, Bottom, Left)
ImGuiID ImGui::GetWindowResizeID(ImGuiWindow* window, int n)
{
IM_ASSERT(n >= 0 && n <= 7);
ImGuiID id = window->ID;
id = ImHashStr("#RESIZE", 0, id);
id = ImHashData(&n, sizeof(int), id);
return id;
}
// Handle resize for: Resize Grips, Borders, Gamepad
// Return true when using auto-fit (double click on resize grip)
static bool ImGui::UpdateWindowManualResize(ImGuiWindow* window, const ImVec2& size_auto_fit, int* border_held, int resize_grip_count, ImU32 resize_grip_col[4])
{
ImGuiContext& g = *GImGui;
ImGuiWindowFlags flags = window->Flags;
if ((flags & ImGuiWindowFlags_NoResize) || (flags & ImGuiWindowFlags_AlwaysAutoResize) || window->AutoFitFramesX > 0 || window->AutoFitFramesY > 0)
return false;
if (window->WasActive == false) // Early out to avoid running this code for e.g. an hidden implicit/fallback Debug window.
return false;
bool ret_auto_fit = false;
const int resize_border_count = g.IO.ConfigWindowsResizeFromEdges ? 4 : 0;
const float grip_draw_size = IM_FLOOR(ImMax(g.FontSize * 1.35f, window->WindowRounding + 1.0f + g.FontSize * 0.2f));
const float grip_hover_inner_size = IM_FLOOR(grip_draw_size * 0.75f);
const float grip_hover_outer_size = g.IO.ConfigWindowsResizeFromEdges ? WINDOWS_RESIZE_FROM_EDGES_HALF_THICKNESS : 0.0f;
ImVec2 pos_target(FLT_MAX, FLT_MAX);
ImVec2 size_target(FLT_MAX, FLT_MAX);
// Resize grips and borders are on layer 1
window->DC.NavLayerCurrent = ImGuiNavLayer_Menu;
window->DC.NavLayerCurrentMask = (1 << ImGuiNavLayer_Menu);
// Manual resize grips
PushID("#RESIZE");
for (int resize_grip_n = 0; resize_grip_n < resize_grip_count; resize_grip_n++)
{
const ImGuiResizeGripDef& grip = resize_grip_def[resize_grip_n];
const ImVec2 corner = ImLerp(window->Pos, window->Pos + window->Size, grip.CornerPosN);
// Using the FlattenChilds button flag we make the resize button accessible even if we are hovering over a child window
ImRect resize_rect(corner - grip.InnerDir * grip_hover_outer_size, corner + grip.InnerDir * grip_hover_inner_size);
if (resize_rect.Min.x > resize_rect.Max.x) ImSwap(resize_rect.Min.x, resize_rect.Max.x);
if (resize_rect.Min.y > resize_rect.Max.y) ImSwap(resize_rect.Min.y, resize_rect.Max.y);
bool hovered, held;
ButtonBehavior(resize_rect, window->GetID(resize_grip_n), &hovered, &held, ImGuiButtonFlags_FlattenChildren | ImGuiButtonFlags_NoNavFocus);
//GetForegroundDrawList(window)->AddRect(resize_rect.Min, resize_rect.Max, IM_COL32(255, 255, 0, 255));
if (hovered || held)
g.MouseCursor = (resize_grip_n & 1) ? ImGuiMouseCursor_ResizeNESW : ImGuiMouseCursor_ResizeNWSE;
if (held && g.IO.MouseDoubleClicked[0] && resize_grip_n == 0)
{
// Manual auto-fit when double-clicking
size_target = CalcWindowSizeAfterConstraint(window, size_auto_fit);
ret_auto_fit = true;
ClearActiveID();
}
else if (held)
{
// Resize from any of the four corners
// We don't use an incremental MouseDelta but rather compute an absolute target size based on mouse position
ImVec2 corner_target = g.IO.MousePos - g.ActiveIdClickOffset + ImLerp(grip.InnerDir * grip_hover_outer_size, grip.InnerDir * -grip_hover_inner_size, grip.CornerPosN); // Corner of the window corresponding to our corner grip
CalcResizePosSizeFromAnyCorner(window, corner_target, grip.CornerPosN, &pos_target, &size_target);
}
if (resize_grip_n == 0 || held || hovered)
resize_grip_col[resize_grip_n] = GetColorU32(held ? ImGuiCol_ResizeGripActive : hovered ? ImGuiCol_ResizeGripHovered : ImGuiCol_ResizeGrip);
}
for (int border_n = 0; border_n < resize_border_count; border_n++)
{
bool hovered, held;
ImRect border_rect = GetResizeBorderRect(window, border_n, grip_hover_inner_size, WINDOWS_RESIZE_FROM_EDGES_HALF_THICKNESS);
ButtonBehavior(border_rect, window->GetID(border_n + 4), &hovered, &held, ImGuiButtonFlags_FlattenChildren);
//GetForegroundDrawLists(window)->AddRect(border_rect.Min, border_rect.Max, IM_COL32(255, 255, 0, 255));
if ((hovered && g.HoveredIdTimer > WINDOWS_RESIZE_FROM_EDGES_FEEDBACK_TIMER) || held)
{
g.MouseCursor = (border_n & 1) ? ImGuiMouseCursor_ResizeEW : ImGuiMouseCursor_ResizeNS;
if (held)
*border_held = border_n;
}
if (held)
{
ImVec2 border_target = window->Pos;
ImVec2 border_posn;
if (border_n == 0) { border_posn = ImVec2(0, 0); border_target.y = (g.IO.MousePos.y - g.ActiveIdClickOffset.y + WINDOWS_RESIZE_FROM_EDGES_HALF_THICKNESS); } // Top
if (border_n == 1) { border_posn = ImVec2(1, 0); border_target.x = (g.IO.MousePos.x - g.ActiveIdClickOffset.x + WINDOWS_RESIZE_FROM_EDGES_HALF_THICKNESS); } // Right
if (border_n == 2) { border_posn = ImVec2(0, 1); border_target.y = (g.IO.MousePos.y - g.ActiveIdClickOffset.y + WINDOWS_RESIZE_FROM_EDGES_HALF_THICKNESS); } // Bottom
if (border_n == 3) { border_posn = ImVec2(0, 0); border_target.x = (g.IO.MousePos.x - g.ActiveIdClickOffset.x + WINDOWS_RESIZE_FROM_EDGES_HALF_THICKNESS); } // Left
CalcResizePosSizeFromAnyCorner(window, border_target, border_posn, &pos_target, &size_target);
}
}
PopID();
// Restore nav layer
window->DC.NavLayerCurrent = ImGuiNavLayer_Main;
window->DC.NavLayerCurrentMask = (1 << ImGuiNavLayer_Main);
// Navigation resize (keyboard/gamepad)
if (g.NavWindowingTarget && g.NavWindowingTarget->RootWindow == window)
{
ImVec2 nav_resize_delta;
if (g.NavInputSource == ImGuiInputSource_NavKeyboard && g.IO.KeyShift)
nav_resize_delta = GetNavInputAmount2d(ImGuiNavDirSourceFlags_Keyboard, ImGuiInputReadMode_Down);
if (g.NavInputSource == ImGuiInputSource_NavGamepad)
nav_resize_delta = GetNavInputAmount2d(ImGuiNavDirSourceFlags_PadDPad, ImGuiInputReadMode_Down);
if (nav_resize_delta.x != 0.0f || nav_resize_delta.y != 0.0f)
{
const float NAV_RESIZE_SPEED = 600.0f;
nav_resize_delta *= ImFloor(NAV_RESIZE_SPEED * g.IO.DeltaTime * ImMin(g.IO.DisplayFramebufferScale.x, g.IO.DisplayFramebufferScale.y));
g.NavWindowingToggleLayer = false;
g.NavDisableMouseHover = true;
resize_grip_col[0] = GetColorU32(ImGuiCol_ResizeGripActive);
// FIXME-NAV: Should store and accumulate into a separate size buffer to handle sizing constraints properly, right now a constraint will make us stuck.
size_target = CalcWindowSizeAfterConstraint(window, window->SizeFull + nav_resize_delta);
}
}
// Apply back modified position/size to window
if (size_target.x != FLT_MAX)
{
window->SizeFull = size_target;
MarkIniSettingsDirty(window);
}
if (pos_target.x != FLT_MAX)
{
window->Pos = ImFloor(pos_target);
MarkIniSettingsDirty(window);
}
window->Size = window->SizeFull;
return ret_auto_fit;
}
static inline void ClampWindowRect(ImGuiWindow* window, const ImRect& rect, const ImVec2& padding)
{
ImGuiContext& g = *GImGui;
ImVec2 size_for_clamping = (g.IO.ConfigWindowsMoveFromTitleBarOnly && !(window->Flags & ImGuiWindowFlags_NoTitleBar)) ? ImVec2(window->Size.x, window->TitleBarHeight()) : window->Size;
window->Pos = ImMin(rect.Max - padding, ImMax(window->Pos + size_for_clamping, rect.Min + padding) - size_for_clamping);
}
static void ImGui::RenderWindowOuterBorders(ImGuiWindow* window)
{
ImGuiContext& g = *GImGui;
float rounding = window->WindowRounding;
float border_size = window->WindowBorderSize;
if (border_size > 0.0f && !(window->Flags & ImGuiWindowFlags_NoBackground))
window->DrawList->AddRect(window->Pos, window->Pos + window->Size, GetColorU32(ImGuiCol_Border), rounding, ImDrawCornerFlags_All, border_size);
int border_held = window->ResizeBorderHeld;
if (border_held != -1)
{
struct ImGuiResizeBorderDef
{
ImVec2 InnerDir;
ImVec2 CornerPosN1, CornerPosN2;
float OuterAngle;
};
static const ImGuiResizeBorderDef resize_border_def[4] =
{
{ ImVec2(0,+1), ImVec2(0,0), ImVec2(1,0), IM_PI*1.50f }, // Top
{ ImVec2(-1,0), ImVec2(1,0), ImVec2(1,1), IM_PI*0.00f }, // Right
{ ImVec2(0,-1), ImVec2(1,1), ImVec2(0,1), IM_PI*0.50f }, // Bottom
{ ImVec2(+1,0), ImVec2(0,1), ImVec2(0,0), IM_PI*1.00f } // Left
};
const ImGuiResizeBorderDef& def = resize_border_def[border_held];
ImRect border_r = GetResizeBorderRect(window, border_held, rounding, 0.0f);
window->DrawList->PathArcTo(ImLerp(border_r.Min, border_r.Max, def.CornerPosN1) + ImVec2(0.5f, 0.5f) + def.InnerDir * rounding, rounding, def.OuterAngle - IM_PI*0.25f, def.OuterAngle);
window->DrawList->PathArcTo(ImLerp(border_r.Min, border_r.Max, def.CornerPosN2) + ImVec2(0.5f, 0.5f) + def.InnerDir * rounding, rounding, def.OuterAngle, def.OuterAngle + IM_PI*0.25f);
window->DrawList->PathStroke(GetColorU32(ImGuiCol_SeparatorActive), false, ImMax(2.0f, border_size)); // Thicker than usual
}
if (g.Style.FrameBorderSize > 0 && !(window->Flags & ImGuiWindowFlags_NoTitleBar))
{
float y = window->Pos.y + window->TitleBarHeight() - 1;
window->DrawList->AddLine(ImVec2(window->Pos.x + border_size, y), ImVec2(window->Pos.x + window->Size.x - border_size, y), GetColorU32(ImGuiCol_Border), g.Style.FrameBorderSize);
}
}
// Draw background and borders
// Draw and handle scrollbars
void ImGui::RenderWindowDecorations(ImGuiWindow* window, const ImRect& title_bar_rect, bool title_bar_is_highlight, int resize_grip_count, const ImU32 resize_grip_col[4], float resize_grip_draw_size)
{
ImGuiContext& g = *GImGui;
ImGuiStyle& style = g.Style;
ImGuiWindowFlags flags = window->Flags;
// Ensure that ScrollBar doesn't read last frame's SkipItems
window->SkipItems = false;
// Draw window + handle manual resize
// As we highlight the title bar when want_focus is set, multiple reappearing windows will have have their title bar highlighted on their reappearing frame.
const float window_rounding = window->WindowRounding;
const float window_border_size = window->WindowBorderSize;
if (window->Collapsed)
{
// Title bar only
float backup_border_size = style.FrameBorderSize;
g.Style.FrameBorderSize = window->WindowBorderSize;
ImU32 title_bar_col = GetColorU32((title_bar_is_highlight && !g.NavDisableHighlight) ? ImGuiCol_TitleBgActive : ImGuiCol_TitleBgCollapsed);
RenderFrame(title_bar_rect.Min, title_bar_rect.Max, title_bar_col, true, window_rounding);
g.Style.FrameBorderSize = backup_border_size;
}
else
{
// Window background
if (!(flags & ImGuiWindowFlags_NoBackground))
{
ImU32 bg_col = GetColorU32(GetWindowBgColorIdxFromFlags(flags));
bool override_alpha = false;
float alpha = 1.0f;
if (g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasBgAlpha)
{
alpha = g.NextWindowData.BgAlphaVal;
override_alpha = true;
}
if (override_alpha)
bg_col = (bg_col & ~IM_COL32_A_MASK) | (IM_F32_TO_INT8_SAT(alpha) << IM_COL32_A_SHIFT);
window->DrawList->AddRectFilled(window->Pos + ImVec2(0, window->TitleBarHeight()), window->Pos + window->Size, bg_col, window_rounding, (flags & ImGuiWindowFlags_NoTitleBar) ? ImDrawCornerFlags_All : ImDrawCornerFlags_Bot);
}
// Title bar
if (!(flags & ImGuiWindowFlags_NoTitleBar))
{
ImU32 title_bar_col = GetColorU32(title_bar_is_highlight ? ImGuiCol_TitleBgActive : ImGuiCol_TitleBg);
window->DrawList->AddRectFilled(title_bar_rect.Min, title_bar_rect.Max, title_bar_col, window_rounding, ImDrawCornerFlags_Top);
}
// Menu bar
if (flags & ImGuiWindowFlags_MenuBar)
{
ImRect menu_bar_rect = window->MenuBarRect();
menu_bar_rect.ClipWith(window->Rect()); // Soft clipping, in particular child window don't have minimum size covering the menu bar so this is useful for them.
window->DrawList->AddRectFilled(menu_bar_rect.Min + ImVec2(window_border_size, 0), menu_bar_rect.Max - ImVec2(window_border_size, 0), GetColorU32(ImGuiCol_MenuBarBg), (flags & ImGuiWindowFlags_NoTitleBar) ? window_rounding : 0.0f, ImDrawCornerFlags_Top);
if (style.FrameBorderSize > 0.0f && menu_bar_rect.Max.y < window->Pos.y + window->Size.y)
window->DrawList->AddLine(menu_bar_rect.GetBL(), menu_bar_rect.GetBR(), GetColorU32(ImGuiCol_Border), style.FrameBorderSize);
}
// Scrollbars
if (window->ScrollbarX)
Scrollbar(ImGuiAxis_X);
if (window->ScrollbarY)
Scrollbar(ImGuiAxis_Y);
// Render resize grips (after their input handling so we don't have a frame of latency)
if (!(flags & ImGuiWindowFlags_NoResize))
{
for (int resize_grip_n = 0; resize_grip_n < resize_grip_count; resize_grip_n++)
{
const ImGuiResizeGripDef& grip = resize_grip_def[resize_grip_n];
const ImVec2 corner = ImLerp(window->Pos, window->Pos + window->Size, grip.CornerPosN);
window->DrawList->PathLineTo(corner + grip.InnerDir * ((resize_grip_n & 1) ? ImVec2(window_border_size, resize_grip_draw_size) : ImVec2(resize_grip_draw_size, window_border_size)));
window->DrawList->PathLineTo(corner + grip.InnerDir * ((resize_grip_n & 1) ? ImVec2(resize_grip_draw_size, window_border_size) : ImVec2(window_border_size, resize_grip_draw_size)));
window->DrawList->PathArcToFast(ImVec2(corner.x + grip.InnerDir.x * (window_rounding + window_border_size), corner.y + grip.InnerDir.y * (window_rounding + window_border_size)), window_rounding, grip.AngleMin12, grip.AngleMax12);
window->DrawList->PathFillConvex(resize_grip_col[resize_grip_n]);
}
}
// Borders
RenderWindowOuterBorders(window);
}
}
// Render title text, collapse button, close button
void ImGui::RenderWindowTitleBarContents(ImGuiWindow* window, const ImRect& title_bar_rect, const char* name, bool* p_open)
{
ImGuiContext& g = *GImGui;
ImGuiStyle& style = g.Style;
ImGuiWindowFlags flags = window->Flags;
const bool has_close_button = (p_open != NULL);
const bool has_collapse_button = !(flags & ImGuiWindowFlags_NoCollapse) && (style.WindowMenuButtonPosition != ImGuiDir_None);
// Close & Collapse button are on the Menu NavLayer and don't default focus (unless there's nothing else on that layer)
const ImGuiItemFlags item_flags_backup = window->DC.ItemFlags;
window->DC.ItemFlags |= ImGuiItemFlags_NoNavDefaultFocus;
window->DC.NavLayerCurrent = ImGuiNavLayer_Menu;
window->DC.NavLayerCurrentMask = (1 << ImGuiNavLayer_Menu);
// Layout buttons
// FIXME: Would be nice to generalize the subtleties expressed here into reusable code.
float pad_l = style.FramePadding.x;
float pad_r = style.FramePadding.x;
float button_sz = g.FontSize;
ImVec2 close_button_pos;
ImVec2 collapse_button_pos;
if (has_close_button)
{
pad_r += button_sz;
close_button_pos = ImVec2(title_bar_rect.Max.x - pad_r - style.FramePadding.x, title_bar_rect.Min.y);
}
if (has_collapse_button && style.WindowMenuButtonPosition == ImGuiDir_Right)
{
pad_r += button_sz;
collapse_button_pos = ImVec2(title_bar_rect.Max.x - pad_r - style.FramePadding.x, title_bar_rect.Min.y);
}
if (has_collapse_button && style.WindowMenuButtonPosition == ImGuiDir_Left)
{
collapse_button_pos = ImVec2(title_bar_rect.Min.x + pad_l - style.FramePadding.x, title_bar_rect.Min.y);
pad_l += button_sz;
}
// Collapse button (submitting first so it gets priority when choosing a navigation init fallback)
if (has_collapse_button)
if (CollapseButton(window->GetID("#COLLAPSE"), collapse_button_pos))
window->WantCollapseToggle = true; // Defer actual collapsing to next frame as we are too far in the Begin() function
// Close button
if (has_close_button)
if (CloseButton(window->GetID("#CLOSE"), close_button_pos))
*p_open = false;
window->DC.NavLayerCurrent = ImGuiNavLayer_Main;
window->DC.NavLayerCurrentMask = (1 << ImGuiNavLayer_Main);
window->DC.ItemFlags = item_flags_backup;
// Title bar text (with: horizontal alignment, avoiding collapse/close button, optional "unsaved document" marker)
// FIXME: Refactor text alignment facilities along with RenderText helpers, this is WAY too much messy code..
const char* UNSAVED_DOCUMENT_MARKER = "*";
const float marker_size_x = (flags & ImGuiWindowFlags_UnsavedDocument) ? CalcTextSize(UNSAVED_DOCUMENT_MARKER, NULL, false).x : 0.0f;
const ImVec2 text_size = CalcTextSize(name, NULL, true) + ImVec2(marker_size_x, 0.0f);
// As a nice touch we try to ensure that centered title text doesn't get affected by visibility of Close/Collapse button,
// while uncentered title text will still reach edges correct.
if (pad_l > style.FramePadding.x)
pad_l += g.Style.ItemInnerSpacing.x;
if (pad_r > style.FramePadding.x)
pad_r += g.Style.ItemInnerSpacing.x;
if (style.WindowTitleAlign.x > 0.0f && style.WindowTitleAlign.x < 1.0f)
{
float centerness = ImSaturate(1.0f - ImFabs(style.WindowTitleAlign.x - 0.5f) * 2.0f); // 0.0f on either edges, 1.0f on center
float pad_extend = ImMin(ImMax(pad_l, pad_r), title_bar_rect.GetWidth() - pad_l - pad_r - text_size.x);
pad_l = ImMax(pad_l, pad_extend * centerness);
pad_r = ImMax(pad_r, pad_extend * centerness);
}
ImRect layout_r(title_bar_rect.Min.x + pad_l, title_bar_rect.Min.y, title_bar_rect.Max.x - pad_r, title_bar_rect.Max.y);
ImRect clip_r(layout_r.Min.x, layout_r.Min.y, layout_r.Max.x + g.Style.ItemInnerSpacing.x, layout_r.Max.y);
//if (g.IO.KeyCtrl) window->DrawList->AddRect(layout_r.Min, layout_r.Max, IM_COL32(255, 128, 0, 255)); // [DEBUG]
RenderTextClipped(layout_r.Min, layout_r.Max, name, NULL, &text_size, style.WindowTitleAlign, &clip_r);
if (flags & ImGuiWindowFlags_UnsavedDocument)
{
ImVec2 marker_pos = ImVec2(ImMax(layout_r.Min.x, layout_r.Min.x + (layout_r.GetWidth() - text_size.x) * style.WindowTitleAlign.x) + text_size.x, layout_r.Min.y) + ImVec2(2 - marker_size_x, 0.0f);
ImVec2 off = ImVec2(0.0f, IM_FLOOR(-g.FontSize * 0.25f));
RenderTextClipped(marker_pos + off, layout_r.Max + off, UNSAVED_DOCUMENT_MARKER, NULL, NULL, ImVec2(0, style.WindowTitleAlign.y), &clip_r);
}
}
void ImGui::UpdateWindowParentAndRootLinks(ImGuiWindow* window, ImGuiWindowFlags flags, ImGuiWindow* parent_window)
{
window->ParentWindow = parent_window;
window->RootWindow = window->RootWindowForTitleBarHighlight = window->RootWindowForNav = window;
if (parent_window && (flags & ImGuiWindowFlags_ChildWindow) && !(flags & ImGuiWindowFlags_Tooltip))
window->RootWindow = parent_window->RootWindow;
if (parent_window && !(flags & ImGuiWindowFlags_Modal) && (flags & (ImGuiWindowFlags_ChildWindow | ImGuiWindowFlags_Popup)))
window->RootWindowForTitleBarHighlight = parent_window->RootWindowForTitleBarHighlight;
while (window->RootWindowForNav->Flags & ImGuiWindowFlags_NavFlattened)
{
IM_ASSERT(window->RootWindowForNav->ParentWindow != NULL);
window->RootWindowForNav = window->RootWindowForNav->ParentWindow;
}
}
// Push a new Dear ImGui window to add widgets to.
// - A default window called "Debug" is automatically stacked at the beginning of every frame so you can use widgets without explicitly calling a Begin/End pair.
// - Begin/End can be called multiple times during the frame with the same window name to append content.
// - The window name is used as a unique identifier to preserve window information across frames (and save rudimentary information to the .ini file).
// You can use the "##" or "###" markers to use the same label with different id, or same id with different label. See documentation at the top of this file.
// - Return false when window is collapsed, so you can early out in your code. You always need to call ImGui::End() even if false is returned.
// - Passing 'bool* p_open' displays a Close button on the upper-right corner of the window, the pointed value will be set to false when the button is pressed.
bool ImGui::Begin(const char* name, bool* p_open, ImGuiWindowFlags flags)
{
ImGuiContext& g = *GImGui;
const ImGuiStyle& style = g.Style;
IM_ASSERT(name != NULL && name[0] != '\0'); // Window name required
IM_ASSERT(g.WithinFrameScope); // Forgot to call ImGui::NewFrame()
IM_ASSERT(g.FrameCountEnded != g.FrameCount); // Called ImGui::Render() or ImGui::EndFrame() and haven't called ImGui::NewFrame() again yet
// Find or create
ImGuiWindow* window = FindWindowByName(name);
const bool window_just_created = (window == NULL);
if (window_just_created)
{
ImVec2 size_on_first_use = (g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasSize) ? g.NextWindowData.SizeVal : ImVec2(0.0f, 0.0f); // Any condition flag will do since we are creating a new window here.
window = CreateNewWindow(name, size_on_first_use, flags);
}
// Automatically disable manual moving/resizing when NoInputs is set
if ((flags & ImGuiWindowFlags_NoInputs) == ImGuiWindowFlags_NoInputs)
flags |= ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoResize;
if (flags & ImGuiWindowFlags_NavFlattened)
IM_ASSERT(flags & ImGuiWindowFlags_ChildWindow);
const int current_frame = g.FrameCount;
const bool first_begin_of_the_frame = (window->LastFrameActive != current_frame);
window->IsFallbackWindow = (g.CurrentWindowStack.Size == 0 && g.WithinFrameScopeWithImplicitWindow);
// Update the Appearing flag
bool window_just_activated_by_user = (window->LastFrameActive < current_frame - 1); // Not using !WasActive because the implicit "Debug" window would always toggle off->on
const bool window_just_appearing_after_hidden_for_resize = (window->HiddenFramesCannotSkipItems > 0);
if (flags & ImGuiWindowFlags_Popup)
{
ImGuiPopupData& popup_ref = g.OpenPopupStack[g.BeginPopupStack.Size];
window_just_activated_by_user |= (window->PopupId != popup_ref.PopupId); // We recycle popups so treat window as activated if popup id changed
window_just_activated_by_user |= (window != popup_ref.Window);
}
window->Appearing = (window_just_activated_by_user || window_just_appearing_after_hidden_for_resize);
if (window->Appearing)
SetWindowConditionAllowFlags(window, ImGuiCond_Appearing, true);
// Update Flags, LastFrameActive, BeginOrderXXX fields
if (first_begin_of_the_frame)
{
window->Flags = (ImGuiWindowFlags)flags;
window->LastFrameActive = current_frame;
window->LastTimeActive = (float)g.Time;
window->BeginOrderWithinParent = 0;
window->BeginOrderWithinContext = (short)(g.WindowsActiveCount++);
}
else
{
flags = window->Flags;
}
// Parent window is latched only on the first call to Begin() of the frame, so further append-calls can be done from a different window stack
ImGuiWindow* parent_window_in_stack = g.CurrentWindowStack.empty() ? NULL : g.CurrentWindowStack.back();
ImGuiWindow* parent_window = first_begin_of_the_frame ? ((flags & (ImGuiWindowFlags_ChildWindow | ImGuiWindowFlags_Popup)) ? parent_window_in_stack : NULL) : window->ParentWindow;
IM_ASSERT(parent_window != NULL || !(flags & ImGuiWindowFlags_ChildWindow));
// We allow window memory to be compacted so recreate the base stack when needed.
if (window->IDStack.Size == 0)
window->IDStack.push_back(window->ID);
// Add to stack
// We intentionally set g.CurrentWindow to NULL to prevent usage until when the viewport is set, then will call SetCurrentWindow()
g.CurrentWindowStack.push_back(window);
g.CurrentWindow = NULL;
ErrorCheckBeginEndCompareStacksSize(window, true);
if (flags & ImGuiWindowFlags_Popup)
{
ImGuiPopupData& popup_ref = g.OpenPopupStack[g.BeginPopupStack.Size];
popup_ref.Window = window;
g.BeginPopupStack.push_back(popup_ref);
window->PopupId = popup_ref.PopupId;
}
if (window_just_appearing_after_hidden_for_resize && !(flags & ImGuiWindowFlags_ChildWindow))
window->NavLastIds[0] = 0;
// Update ->RootWindow and others pointers (before any possible call to FocusWindow)
if (first_begin_of_the_frame)
UpdateWindowParentAndRootLinks(window, flags, parent_window);
// Process SetNextWindow***() calls
bool window_pos_set_by_api = false;
bool window_size_x_set_by_api = false, window_size_y_set_by_api = false;
if (g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasPos)
{
window_pos_set_by_api = (window->SetWindowPosAllowFlags & g.NextWindowData.PosCond) != 0;
if (window_pos_set_by_api && ImLengthSqr(g.NextWindowData.PosPivotVal) > 0.00001f)
{
// May be processed on the next frame if this is our first frame and we are measuring size
// FIXME: Look into removing the branch so everything can go through this same code path for consistency.
window->SetWindowPosVal = g.NextWindowData.PosVal;
window->SetWindowPosPivot = g.NextWindowData.PosPivotVal;
window->SetWindowPosAllowFlags &= ~(ImGuiCond_Once | ImGuiCond_FirstUseEver | ImGuiCond_Appearing);
}
else
{
SetWindowPos(window, g.NextWindowData.PosVal, g.NextWindowData.PosCond);
}
}
if (g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasSize)
{
window_size_x_set_by_api = (window->SetWindowSizeAllowFlags & g.NextWindowData.SizeCond) != 0 && (g.NextWindowData.SizeVal.x > 0.0f);
window_size_y_set_by_api = (window->SetWindowSizeAllowFlags & g.NextWindowData.SizeCond) != 0 && (g.NextWindowData.SizeVal.y > 0.0f);
SetWindowSize(window, g.NextWindowData.SizeVal, g.NextWindowData.SizeCond);
}
if (g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasContentSize)
window->ContentSizeExplicit = g.NextWindowData.ContentSizeVal;
else if (first_begin_of_the_frame)
window->ContentSizeExplicit = ImVec2(0.0f, 0.0f);
if (g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasCollapsed)
SetWindowCollapsed(window, g.NextWindowData.CollapsedVal, g.NextWindowData.CollapsedCond);
if (g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasFocus)
FocusWindow(window);
if (window->Appearing)
SetWindowConditionAllowFlags(window, ImGuiCond_Appearing, false);
// When reusing window again multiple times a frame, just append content (don't need to setup again)
if (first_begin_of_the_frame)
{
// Initialize
const bool window_is_child_tooltip = (flags & ImGuiWindowFlags_ChildWindow) && (flags & ImGuiWindowFlags_Tooltip); // FIXME-WIP: Undocumented behavior of Child+Tooltip for pinned tooltip (#1345)
window->Active = true;
window->HasCloseButton = (p_open != NULL);
window->ClipRect = ImVec4(-FLT_MAX,-FLT_MAX,+FLT_MAX,+FLT_MAX);
window->IDStack.resize(1);
// Restore buffer capacity when woken from a compacted state, to avoid
if (window->MemoryCompacted)
GcAwakeTransientWindowBuffers(window);
// Update stored window name when it changes (which can _only_ happen with the "###" operator, so the ID would stay unchanged).
// The title bar always display the 'name' parameter, so we only update the string storage if it needs to be visible to the end-user elsewhere.
bool window_title_visible_elsewhere = false;
if (g.NavWindowingList != NULL && (window->Flags & ImGuiWindowFlags_NoNavFocus) == 0) // Window titles visible when using CTRL+TAB
window_title_visible_elsewhere = true;
if (window_title_visible_elsewhere && !window_just_created && strcmp(name, window->Name) != 0)
{
size_t buf_len = (size_t)window->NameBufLen;
window->Name = ImStrdupcpy(window->Name, &buf_len, name);
window->NameBufLen = (int)buf_len;
}
// UPDATE CONTENTS SIZE, UPDATE HIDDEN STATUS
// Update contents size from last frame for auto-fitting (or use explicit size)
window->ContentSize = CalcWindowContentSize(window);
if (window->HiddenFramesCanSkipItems > 0)
window->HiddenFramesCanSkipItems--;
if (window->HiddenFramesCannotSkipItems > 0)
window->HiddenFramesCannotSkipItems--;
// Hide new windows for one frame until they calculate their size
if (window_just_created && (!window_size_x_set_by_api || !window_size_y_set_by_api))
window->HiddenFramesCannotSkipItems = 1;
// Hide popup/tooltip window when re-opening while we measure size (because we recycle the windows)
// We reset Size/ContentSize for reappearing popups/tooltips early in this function, so further code won't be tempted to use the old size.
if (window_just_activated_by_user && (flags & (ImGuiWindowFlags_Popup | ImGuiWindowFlags_Tooltip)) != 0)
{
window->HiddenFramesCannotSkipItems = 1;
if (flags & ImGuiWindowFlags_AlwaysAutoResize)
{
if (!window_size_x_set_by_api)
window->Size.x = window->SizeFull.x = 0.f;
if (!window_size_y_set_by_api)
window->Size.y = window->SizeFull.y = 0.f;
window->ContentSize = ImVec2(0.f, 0.f);
}
}
// SELECT VIEWPORT
// FIXME-VIEWPORT: In the docking/viewport branch, this is the point where we select the current viewport (which may affect the style)
SetCurrentWindow(window);
// LOCK BORDER SIZE AND PADDING FOR THE FRAME (so that altering them doesn't cause inconsistencies)
if (flags & ImGuiWindowFlags_ChildWindow)
window->WindowBorderSize = style.ChildBorderSize;
else
window->WindowBorderSize = ((flags & (ImGuiWindowFlags_Popup | ImGuiWindowFlags_Tooltip)) && !(flags & ImGuiWindowFlags_Modal)) ? style.PopupBorderSize : style.WindowBorderSize;
window->WindowPadding = style.WindowPadding;
if ((flags & ImGuiWindowFlags_ChildWindow) && !(flags & (ImGuiWindowFlags_AlwaysUseWindowPadding | ImGuiWindowFlags_Popup)) && window->WindowBorderSize == 0.0f)
window->WindowPadding = ImVec2(0.0f, (flags & ImGuiWindowFlags_MenuBar) ? style.WindowPadding.y : 0.0f);
// Collapse window by double-clicking on title bar
// At this point we don't have a clipping rectangle setup yet, so we can use the title bar area for hit detection and drawing
if (!(flags & ImGuiWindowFlags_NoTitleBar) && !(flags & ImGuiWindowFlags_NoCollapse))
{
// We don't use a regular button+id to test for double-click on title bar (mostly due to legacy reason, could be fixed), so verify that we don't have items over the title bar.
ImRect title_bar_rect = window->TitleBarRect();
if (g.HoveredWindow == window && g.HoveredId == 0 && g.HoveredIdPreviousFrame == 0 && IsMouseHoveringRect(title_bar_rect.Min, title_bar_rect.Max) && g.IO.MouseDoubleClicked[0])
window->WantCollapseToggle = true;
if (window->WantCollapseToggle)
{
window->Collapsed = !window->Collapsed;
MarkIniSettingsDirty(window);
FocusWindow(window);
}
}
else
{
window->Collapsed = false;
}
window->WantCollapseToggle = false;
// SIZE
// Calculate auto-fit size, handle automatic resize
const ImVec2 size_auto_fit = CalcWindowAutoFitSize(window, window->ContentSize);
bool use_current_size_for_scrollbar_x = window_just_created;
bool use_current_size_for_scrollbar_y = window_just_created;
if ((flags & ImGuiWindowFlags_AlwaysAutoResize) && !window->Collapsed)
{
// Using SetNextWindowSize() overrides ImGuiWindowFlags_AlwaysAutoResize, so it can be used on tooltips/popups, etc.
if (!window_size_x_set_by_api)
{
window->SizeFull.x = size_auto_fit.x;
use_current_size_for_scrollbar_x = true;
}
if (!window_size_y_set_by_api)
{
window->SizeFull.y = size_auto_fit.y;
use_current_size_for_scrollbar_y = true;
}
}
else if (window->AutoFitFramesX > 0 || window->AutoFitFramesY > 0)
{
// Auto-fit may only grow window during the first few frames
// We still process initial auto-fit on collapsed windows to get a window width, but otherwise don't honor ImGuiWindowFlags_AlwaysAutoResize when collapsed.
if (!window_size_x_set_by_api && window->AutoFitFramesX > 0)
{
window->SizeFull.x = window->AutoFitOnlyGrows ? ImMax(window->SizeFull.x, size_auto_fit.x) : size_auto_fit.x;
use_current_size_for_scrollbar_x = true;
}
if (!window_size_y_set_by_api && window->AutoFitFramesY > 0)
{
window->SizeFull.y = window->AutoFitOnlyGrows ? ImMax(window->SizeFull.y, size_auto_fit.y) : size_auto_fit.y;
use_current_size_for_scrollbar_y = true;
}
if (!window->Collapsed)
MarkIniSettingsDirty(window);
}
// Apply minimum/maximum window size constraints and final size
window->SizeFull = CalcWindowSizeAfterConstraint(window, window->SizeFull);
window->Size = window->Collapsed && !(flags & ImGuiWindowFlags_ChildWindow) ? window->TitleBarRect().GetSize() : window->SizeFull;
// Decoration size
const float decoration_up_height = window->TitleBarHeight() + window->MenuBarHeight();
// POSITION
// Popup latch its initial position, will position itself when it appears next frame
if (window_just_activated_by_user)
{
window->AutoPosLastDirection = ImGuiDir_None;
if ((flags & ImGuiWindowFlags_Popup) != 0 && !window_pos_set_by_api)
window->Pos = g.BeginPopupStack.back().OpenPopupPos;
}
// Position child window
if (flags & ImGuiWindowFlags_ChildWindow)
{
IM_ASSERT(parent_window && parent_window->Active);
window->BeginOrderWithinParent = (short)parent_window->DC.ChildWindows.Size;
parent_window->DC.ChildWindows.push_back(window);
if (!(flags & ImGuiWindowFlags_Popup) && !window_pos_set_by_api && !window_is_child_tooltip)
window->Pos = parent_window->DC.CursorPos;
}
const bool window_pos_with_pivot = (window->SetWindowPosVal.x != FLT_MAX && window->HiddenFramesCannotSkipItems == 0);
if (window_pos_with_pivot)
SetWindowPos(window, window->SetWindowPosVal - window->SizeFull * window->SetWindowPosPivot, 0); // Position given a pivot (e.g. for centering)
else if ((flags & ImGuiWindowFlags_ChildMenu) != 0)
window->Pos = FindBestWindowPosForPopup(window);
else if ((flags & ImGuiWindowFlags_Popup) != 0 && !window_pos_set_by_api && window_just_appearing_after_hidden_for_resize)
window->Pos = FindBestWindowPosForPopup(window);
else if ((flags & ImGuiWindowFlags_Tooltip) != 0 && !window_pos_set_by_api && !window_is_child_tooltip)
window->Pos = FindBestWindowPosForPopup(window);
// Clamp position/size so window stays visible within its viewport or monitor
// Ignore zero-sized display explicitly to avoid losing positions if a window manager reports zero-sized window when initializing or minimizing.
ImRect viewport_rect(GetViewportRect());
if (!window_pos_set_by_api && !(flags & ImGuiWindowFlags_ChildWindow) && window->AutoFitFramesX <= 0 && window->AutoFitFramesY <= 0)
{
ImVec2 clamp_padding = ImMax(style.DisplayWindowPadding, style.DisplaySafeAreaPadding);
if (viewport_rect.GetWidth() > 0 && viewport_rect.GetHeight() > 0.0f)
{
ClampWindowRect(window, viewport_rect, clamp_padding);
}
}
window->Pos = ImFloor(window->Pos);
// Lock window rounding for the frame (so that altering them doesn't cause inconsistencies)
window->WindowRounding = (flags & ImGuiWindowFlags_ChildWindow) ? style.ChildRounding : ((flags & ImGuiWindowFlags_Popup) && !(flags & ImGuiWindowFlags_Modal)) ? style.PopupRounding : style.WindowRounding;
// Apply window focus (new and reactivated windows are moved to front)
bool want_focus = false;
if (window_just_activated_by_user && !(flags & ImGuiWindowFlags_NoFocusOnAppearing))
{
if (flags & ImGuiWindowFlags_Popup)
want_focus = true;
else if ((flags & (ImGuiWindowFlags_ChildWindow | ImGuiWindowFlags_Tooltip)) == 0)
want_focus = true;
}
// Handle manual resize: Resize Grips, Borders, Gamepad
int border_held = -1;
ImU32 resize_grip_col[4] = {};
const int resize_grip_count = g.IO.ConfigWindowsResizeFromEdges ? 2 : 1; // Allow resize from lower-left if we have the mouse cursor feedback for it.
const float resize_grip_draw_size = IM_FLOOR(ImMax(g.FontSize * 1.35f, window->WindowRounding + 1.0f + g.FontSize * 0.2f));
if (!window->Collapsed)
if (UpdateWindowManualResize(window, size_auto_fit, &border_held, resize_grip_count, &resize_grip_col[0]))
use_current_size_for_scrollbar_x = use_current_size_for_scrollbar_y = true;
window->ResizeBorderHeld = (signed char)border_held;
// SCROLLBAR VISIBILITY
// Update scrollbar visibility (based on the Size that was effective during last frame or the auto-resized Size).
if (!window->Collapsed)
{
// When reading the current size we need to read it after size constraints have been applied.
// When we use InnerRect here we are intentionally reading last frame size, same for ScrollbarSizes values before we set them again.
ImVec2 avail_size_from_current_frame = ImVec2(window->SizeFull.x, window->SizeFull.y - decoration_up_height);
ImVec2 avail_size_from_last_frame = window->InnerRect.GetSize() + window->ScrollbarSizes;
ImVec2 needed_size_from_last_frame = window_just_created ? ImVec2(0, 0) : window->ContentSize + window->WindowPadding * 2.0f;
float size_x_for_scrollbars = use_current_size_for_scrollbar_x ? avail_size_from_current_frame.x : avail_size_from_last_frame.x;
float size_y_for_scrollbars = use_current_size_for_scrollbar_y ? avail_size_from_current_frame.y : avail_size_from_last_frame.y;
//bool scrollbar_y_from_last_frame = window->ScrollbarY; // FIXME: May want to use that in the ScrollbarX expression? How many pros vs cons?
window->ScrollbarY = (flags & ImGuiWindowFlags_AlwaysVerticalScrollbar) || ((needed_size_from_last_frame.y > size_y_for_scrollbars) && !(flags & ImGuiWindowFlags_NoScrollbar));
window->ScrollbarX = (flags & ImGuiWindowFlags_AlwaysHorizontalScrollbar) || ((needed_size_from_last_frame.x > size_x_for_scrollbars - (window->ScrollbarY ? style.ScrollbarSize : 0.0f)) && !(flags & ImGuiWindowFlags_NoScrollbar) && (flags & ImGuiWindowFlags_HorizontalScrollbar));
if (window->ScrollbarX && !window->ScrollbarY)
window->ScrollbarY = (needed_size_from_last_frame.y > size_y_for_scrollbars) && !(flags & ImGuiWindowFlags_NoScrollbar);
window->ScrollbarSizes = ImVec2(window->ScrollbarY ? style.ScrollbarSize : 0.0f, window->ScrollbarX ? style.ScrollbarSize : 0.0f);
}
// UPDATE RECTANGLES (1- THOSE NOT AFFECTED BY SCROLLING)
// Update various regions. Variables they depends on should be set above in this function.
// We set this up after processing the resize grip so that our rectangles doesn't lag by a frame.
// Outer rectangle
// Not affected by window border size. Used by:
// - FindHoveredWindow() (w/ extra padding when border resize is enabled)
// - Begin() initial clipping rect for drawing window background and borders.
// - Begin() clipping whole child
const ImRect host_rect = ((flags & ImGuiWindowFlags_ChildWindow) && !(flags & ImGuiWindowFlags_Popup) && !window_is_child_tooltip) ? parent_window->ClipRect : viewport_rect;
const ImRect outer_rect = window->Rect();
const ImRect title_bar_rect = window->TitleBarRect();
window->OuterRectClipped = outer_rect;
window->OuterRectClipped.ClipWith(host_rect);
// Inner rectangle
// Not affected by window border size. Used by:
// - InnerClipRect
// - ScrollToBringRectIntoView()
// - NavUpdatePageUpPageDown()
// - Scrollbar()
window->InnerRect.Min.x = window->Pos.x;
window->InnerRect.Min.y = window->Pos.y + decoration_up_height;
window->InnerRect.Max.x = window->Pos.x + window->Size.x - window->ScrollbarSizes.x;
window->InnerRect.Max.y = window->Pos.y + window->Size.y - window->ScrollbarSizes.y;
// Inner clipping rectangle.
// Will extend a little bit outside the normal work region.
// This is to allow e.g. Selectable or CollapsingHeader or some separators to cover that space.
// Force round operator last to ensure that e.g. (int)(max.x-min.x) in user's render code produce correct result.
// Note that if our window is collapsed we will end up with an inverted (~null) clipping rectangle which is the correct behavior.
// Affected by window/frame border size. Used by:
// - Begin() initial clip rect
float top_border_size = (((flags & ImGuiWindowFlags_MenuBar) || !(flags & ImGuiWindowFlags_NoTitleBar)) ? style.FrameBorderSize : window->WindowBorderSize);
window->InnerClipRect.Min.x = ImFloor(0.5f + window->InnerRect.Min.x + ImMax(ImFloor(window->WindowPadding.x * 0.5f), window->WindowBorderSize));
window->InnerClipRect.Min.y = ImFloor(0.5f + window->InnerRect.Min.y + top_border_size);
window->InnerClipRect.Max.x = ImFloor(0.5f + window->InnerRect.Max.x - ImMax(ImFloor(window->WindowPadding.x * 0.5f), window->WindowBorderSize));
window->InnerClipRect.Max.y = ImFloor(0.5f + window->InnerRect.Max.y - window->WindowBorderSize);
window->InnerClipRect.ClipWithFull(host_rect);
// Default item width. Make it proportional to window size if window manually resizes
if (window->Size.x > 0.0f && !(flags & ImGuiWindowFlags_Tooltip) && !(flags & ImGuiWindowFlags_AlwaysAutoResize))
window->ItemWidthDefault = ImFloor(window->Size.x * 0.65f);
else
window->ItemWidthDefault = ImFloor(g.FontSize * 16.0f);
// SCROLLING
// Lock down maximum scrolling
// The value of ScrollMax are ahead from ScrollbarX/ScrollbarY which is intentionally using InnerRect from previous rect in order to accommodate
// for right/bottom aligned items without creating a scrollbar.
window->ScrollMax.x = ImMax(0.0f, window->ContentSize.x + window->WindowPadding.x * 2.0f - window->InnerRect.GetWidth());
window->ScrollMax.y = ImMax(0.0f, window->ContentSize.y + window->WindowPadding.y * 2.0f - window->InnerRect.GetHeight());
// Apply scrolling
window->Scroll = CalcNextScrollFromScrollTargetAndClamp(window, true);
window->ScrollTarget = ImVec2(FLT_MAX, FLT_MAX);
// DRAWING
// Setup draw list and outer clipping rectangle
window->DrawList->Clear();
window->DrawList->PushTextureID(g.Font->ContainerAtlas->TexID);
PushClipRect(host_rect.Min, host_rect.Max, false);
// Draw modal window background (darkens what is behind them, all viewports)
const bool dim_bg_for_modal = (flags & ImGuiWindowFlags_Modal) && window == GetTopMostPopupModal() && window->HiddenFramesCannotSkipItems <= 0;
const bool dim_bg_for_window_list = g.NavWindowingTargetAnim && (window == g.NavWindowingTargetAnim->RootWindow);
if (dim_bg_for_modal || dim_bg_for_window_list)
{
const ImU32 dim_bg_col = GetColorU32(dim_bg_for_modal ? ImGuiCol_ModalWindowDimBg : ImGuiCol_NavWindowingDimBg, g.DimBgRatio);
window->DrawList->AddRectFilled(viewport_rect.Min, viewport_rect.Max, dim_bg_col);
}
// Draw navigation selection/windowing rectangle background
if (dim_bg_for_window_list && window == g.NavWindowingTargetAnim)
{
ImRect bb = window->Rect();
bb.Expand(g.FontSize);
if (!bb.Contains(viewport_rect)) // Avoid drawing if the window covers all the viewport anyway
window->DrawList->AddRectFilled(bb.Min, bb.Max, GetColorU32(ImGuiCol_NavWindowingHighlight, g.NavWindowingHighlightAlpha * 0.25f), g.Style.WindowRounding);
}
// Since 1.71, child window can render their decoration (bg color, border, scrollbars, etc.) within their parent to save a draw call.
// When using overlapping child windows, this will break the assumption that child z-order is mapped to submission order.
// We disable this when the parent window has zero vertices, which is a common pattern leading to laying out multiple overlapping child.
// We also disabled this when we have dimming overlay behind this specific one child.
// FIXME: More code may rely on explicit sorting of overlapping child window and would need to disable this somehow. Please get in contact if you are affected.
{
bool render_decorations_in_parent = false;
if ((flags & ImGuiWindowFlags_ChildWindow) && !(flags & ImGuiWindowFlags_Popup) && !window_is_child_tooltip)
if (window->DrawList->CmdBuffer.back().ElemCount == 0 && parent_window->DrawList->VtxBuffer.Size > 0)
render_decorations_in_parent = true;
if (render_decorations_in_parent)
window->DrawList = parent_window->DrawList;
// Handle title bar, scrollbar, resize grips and resize borders
const ImGuiWindow* window_to_highlight = g.NavWindowingTarget ? g.NavWindowingTarget : g.NavWindow;
const bool title_bar_is_highlight = want_focus || (window_to_highlight && window->RootWindowForTitleBarHighlight == window_to_highlight->RootWindowForTitleBarHighlight);
RenderWindowDecorations(window, title_bar_rect, title_bar_is_highlight, resize_grip_count, resize_grip_col, resize_grip_draw_size);
if (render_decorations_in_parent)
window->DrawList = &window->DrawListInst;
}
// Draw navigation selection/windowing rectangle border
if (g.NavWindowingTargetAnim == window)
{
float rounding = ImMax(window->WindowRounding, g.Style.WindowRounding);
ImRect bb = window->Rect();
bb.Expand(g.FontSize);
if (bb.Contains(viewport_rect)) // If a window fits the entire viewport, adjust its highlight inward
{
bb.Expand(-g.FontSize - 1.0f);
rounding = window->WindowRounding;
}
window->DrawList->AddRect(bb.Min, bb.Max, GetColorU32(ImGuiCol_NavWindowingHighlight, g.NavWindowingHighlightAlpha), rounding, ~0, 3.0f);
}
// UPDATE RECTANGLES (2- THOSE AFFECTED BY SCROLLING)
// Work rectangle.
// Affected by window padding and border size. Used by:
// - Columns() for right-most edge
// - TreeNode(), CollapsingHeader() for right-most edge
// - BeginTabBar() for right-most edge
const bool allow_scrollbar_x = !(flags & ImGuiWindowFlags_NoScrollbar) && (flags & ImGuiWindowFlags_HorizontalScrollbar);
const bool allow_scrollbar_y = !(flags & ImGuiWindowFlags_NoScrollbar);
const float work_rect_size_x = (window->ContentSizeExplicit.x != 0.0f ? window->ContentSizeExplicit.x : ImMax(allow_scrollbar_x ? window->ContentSize.x : 0.0f, window->Size.x - window->WindowPadding.x * 2.0f - window->ScrollbarSizes.x));
const float work_rect_size_y = (window->ContentSizeExplicit.y != 0.0f ? window->ContentSizeExplicit.y : ImMax(allow_scrollbar_y ? window->ContentSize.y : 0.0f, window->Size.y - window->WindowPadding.y * 2.0f - decoration_up_height - window->ScrollbarSizes.y));
window->WorkRect.Min.x = ImFloor(window->InnerRect.Min.x - window->Scroll.x + ImMax(window->WindowPadding.x, window->WindowBorderSize));
window->WorkRect.Min.y = ImFloor(window->InnerRect.Min.y - window->Scroll.y + ImMax(window->WindowPadding.y, window->WindowBorderSize));
window->WorkRect.Max.x = window->WorkRect.Min.x + work_rect_size_x;
window->WorkRect.Max.y = window->WorkRect.Min.y + work_rect_size_y;
// [LEGACY] Content Region
// FIXME-OBSOLETE: window->ContentRegionRect.Max is currently very misleading / partly faulty, but some BeginChild() patterns relies on it.
// Used by:
// - Mouse wheel scrolling + many other things
window->ContentRegionRect.Min.x = window->Pos.x - window->Scroll.x + window->WindowPadding.x;
window->ContentRegionRect.Min.y = window->Pos.y - window->Scroll.y + window->WindowPadding.y + decoration_up_height;
window->ContentRegionRect.Max.x = window->ContentRegionRect.Min.x + (window->ContentSizeExplicit.x != 0.0f ? window->ContentSizeExplicit.x : (window->Size.x - window->WindowPadding.x * 2.0f - window->ScrollbarSizes.x));
window->ContentRegionRect.Max.y = window->ContentRegionRect.Min.y + (window->ContentSizeExplicit.y != 0.0f ? window->ContentSizeExplicit.y : (window->Size.y - window->WindowPadding.y * 2.0f - decoration_up_height - window->ScrollbarSizes.y));
// Setup drawing context
// (NB: That term "drawing context / DC" lost its meaning a long time ago. Initially was meant to hold transient data only. Nowadays difference between window-> and window->DC-> is dubious.)
window->DC.Indent.x = 0.0f + window->WindowPadding.x - window->Scroll.x;
window->DC.GroupOffset.x = 0.0f;
window->DC.ColumnsOffset.x = 0.0f;
window->DC.CursorStartPos = window->Pos + ImVec2(window->DC.Indent.x + window->DC.ColumnsOffset.x, decoration_up_height + window->WindowPadding.y - window->Scroll.y);
window->DC.CursorPos = window->DC.CursorStartPos;
window->DC.CursorPosPrevLine = window->DC.CursorPos;
window->DC.CursorMaxPos = window->DC.CursorStartPos;
window->DC.CurrLineSize = window->DC.PrevLineSize = ImVec2(0.0f, 0.0f);
window->DC.CurrLineTextBaseOffset = window->DC.PrevLineTextBaseOffset = 0.0f;
window->DC.NavLayerCurrent = ImGuiNavLayer_Main;
window->DC.NavLayerCurrentMask = (1 << ImGuiNavLayer_Main);
window->DC.NavLayerActiveMask = window->DC.NavLayerActiveMaskNext;
window->DC.NavLayerActiveMaskNext = 0x00;
window->DC.NavFocusScopeIdCurrent = parent_window ? parent_window->DC.NavFocusScopeIdCurrent : 0;
window->DC.NavHideHighlightOneFrame = false;
window->DC.NavHasScroll = (window->ScrollMax.y > 0.0f);
window->DC.MenuBarAppending = false;
window->DC.MenuBarOffset.x = ImMax(ImMax(window->WindowPadding.x, style.ItemSpacing.x), g.NextWindowData.MenuBarOffsetMinVal.x);
window->DC.MenuBarOffset.y = g.NextWindowData.MenuBarOffsetMinVal.y;
window->DC.MenuColumns.Update(3, style.ItemSpacing.x, window_just_activated_by_user);
window->DC.TreeDepth = 0;
window->DC.TreeJumpToParentOnPopMask = 0x00;
window->DC.ChildWindows.resize(0);
window->DC.StateStorage = &window->StateStorage;
window->DC.CurrentColumns = NULL;
window->DC.LayoutType = ImGuiLayoutType_Vertical;
window->DC.ParentLayoutType = parent_window ? parent_window->DC.LayoutType : ImGuiLayoutType_Vertical;
window->DC.FocusCounterRegular = window->DC.FocusCounterTabStop = -1;
window->DC.ItemWidth = window->ItemWidthDefault;
window->DC.TextWrapPos = -1.0f; // disabled
window->DC.ItemFlagsStack.resize(0);
window->DC.ItemWidthStack.resize(0);
window->DC.TextWrapPosStack.resize(0);
window->DC.GroupStack.resize(0);
window->DC.ItemFlags = parent_window ? parent_window->DC.ItemFlags : ImGuiItemFlags_Default_;
if (parent_window)
window->DC.ItemFlagsStack.push_back(window->DC.ItemFlags);
if (window->AutoFitFramesX > 0)
window->AutoFitFramesX--;
if (window->AutoFitFramesY > 0)
window->AutoFitFramesY--;
// Apply focus (we need to call FocusWindow() AFTER setting DC.CursorStartPos so our initial navigation reference rectangle can start around there)
if (want_focus)
{
FocusWindow(window);
NavInitWindow(window, false);
}
// Title bar
if (!(flags & ImGuiWindowFlags_NoTitleBar))
RenderWindowTitleBarContents(window, title_bar_rect, name, p_open);
// Pressing CTRL+C while holding on a window copy its content to the clipboard
// This works but 1. doesn't handle multiple Begin/End pairs, 2. recursing into another Begin/End pair - so we need to work that out and add better logging scope.
// Maybe we can support CTRL+C on every element?
/*
if (g.ActiveId == move_id)
if (g.IO.KeyCtrl && IsKeyPressedMap(ImGuiKey_C))
LogToClipboard();
*/
// We fill last item data based on Title Bar/Tab, in order for IsItemHovered() and IsItemActive() to be usable after Begin().
// This is useful to allow creating context menus on title bar only, etc.
window->DC.LastItemId = window->MoveId;
window->DC.LastItemStatusFlags = IsMouseHoveringRect(title_bar_rect.Min, title_bar_rect.Max, false) ? ImGuiItemStatusFlags_HoveredRect : 0;
window->DC.LastItemRect = title_bar_rect;
#ifdef IMGUI_ENABLE_TEST_ENGINE
if (!(window->Flags & ImGuiWindowFlags_NoTitleBar))
IMGUI_TEST_ENGINE_ITEM_ADD(window->DC.LastItemRect, window->DC.LastItemId);
#endif
}
else
{
// Append
SetCurrentWindow(window);
}
PushClipRect(window->InnerClipRect.Min, window->InnerClipRect.Max, true);
// Clear 'accessed' flag last thing (After PushClipRect which will set the flag. We want the flag to stay false when the default "Debug" window is unused)
if (first_begin_of_the_frame)
window->WriteAccessed = false;
window->BeginCount++;
g.NextWindowData.ClearFlags();
if (flags & ImGuiWindowFlags_ChildWindow)
{
// Child window can be out of sight and have "negative" clip windows.
// Mark them as collapsed so commands are skipped earlier (we can't manually collapse them because they have no title bar).
IM_ASSERT((flags & ImGuiWindowFlags_NoTitleBar) != 0);
if (!(flags & ImGuiWindowFlags_AlwaysAutoResize) && window->AutoFitFramesX <= 0 && window->AutoFitFramesY <= 0)
if (window->OuterRectClipped.Min.x >= window->OuterRectClipped.Max.x || window->OuterRectClipped.Min.y >= window->OuterRectClipped.Max.y)
window->HiddenFramesCanSkipItems = 1;
// Hide along with parent or if parent is collapsed
if (parent_window && (parent_window->Collapsed || parent_window->HiddenFramesCanSkipItems > 0))
window->HiddenFramesCanSkipItems = 1;
if (parent_window && (parent_window->Collapsed || parent_window->HiddenFramesCannotSkipItems > 0))
window->HiddenFramesCannotSkipItems = 1;
}
// Don't render if style alpha is 0.0 at the time of Begin(). This is arbitrary and inconsistent but has been there for a long while (may remove at some point)
if (style.Alpha <= 0.0f)
window->HiddenFramesCanSkipItems = 1;
// Update the Hidden flag
window->Hidden = (window->HiddenFramesCanSkipItems > 0) || (window->HiddenFramesCannotSkipItems > 0);
// Update the SkipItems flag, used to early out of all items functions (no layout required)
bool skip_items = false;
if (window->Collapsed || !window->Active || window->Hidden)
if (window->AutoFitFramesX <= 0 && window->AutoFitFramesY <= 0 && window->HiddenFramesCannotSkipItems <= 0)
skip_items = true;
window->SkipItems = skip_items;
return !skip_items;
}
void ImGui::End()
{
ImGuiContext& g = *GImGui;
ImGuiWindow* window = g.CurrentWindow;
// Error checking: verify that user hasn't called End() too many times!
if (g.CurrentWindowStack.Size <= 1 && g.WithinFrameScopeWithImplicitWindow)
{
IM_ASSERT_USER_ERROR(g.CurrentWindowStack.Size > 1, "Calling End() too many times!");
return;
}
IM_ASSERT(g.CurrentWindowStack.Size > 0);
// Error checking: verify that user doesn't directly call End() on a child window.
if (window->Flags & ImGuiWindowFlags_ChildWindow)
IM_ASSERT_USER_ERROR(g.WithinEndChild, "Must call EndChild() and not End()!");
// Close anything that is open
if (window->DC.CurrentColumns)
EndColumns();
PopClipRect(); // Inner window clip rectangle
// Stop logging
if (!(window->Flags & ImGuiWindowFlags_ChildWindow)) // FIXME: add more options for scope of logging
LogFinish();
// Pop from window stack
g.CurrentWindowStack.pop_back();
if (window->Flags & ImGuiWindowFlags_Popup)
g.BeginPopupStack.pop_back();
ErrorCheckBeginEndCompareStacksSize(window, false);
SetCurrentWindow(g.CurrentWindowStack.empty() ? NULL : g.CurrentWindowStack.back());
}
void ImGui::BringWindowToFocusFront(ImGuiWindow* window)
{
ImGuiContext& g = *GImGui;
if (g.WindowsFocusOrder.back() == window)
return;
for (int i = g.WindowsFocusOrder.Size - 2; i >= 0; i--) // We can ignore the top-most window
if (g.WindowsFocusOrder[i] == window)
{
memmove(&g.WindowsFocusOrder[i], &g.WindowsFocusOrder[i + 1], (size_t)(g.WindowsFocusOrder.Size - i - 1) * sizeof(ImGuiWindow*));
g.WindowsFocusOrder[g.WindowsFocusOrder.Size - 1] = window;
break;
}
}
void ImGui::BringWindowToDisplayFront(ImGuiWindow* window)
{
ImGuiContext& g = *GImGui;
ImGuiWindow* current_front_window = g.Windows.back();
if (current_front_window == window || current_front_window->RootWindow == window)
return;
for (int i = g.Windows.Size - 2; i >= 0; i--) // We can ignore the top-most window
if (g.Windows[i] == window)
{
memmove(&g.Windows[i], &g.Windows[i + 1], (size_t)(g.Windows.Size - i - 1) * sizeof(ImGuiWindow*));
g.Windows[g.Windows.Size - 1] = window;
break;
}
}
void ImGui::BringWindowToDisplayBack(ImGuiWindow* window)
{
ImGuiContext& g = *GImGui;
if (g.Windows[0] == window)
return;
for (int i = 0; i < g.Windows.Size; i++)
if (g.Windows[i] == window)
{
memmove(&g.Windows[1], &g.Windows[0], (size_t)i * sizeof(ImGuiWindow*));
g.Windows[0] = window;
break;
}
}
// Moving window to front of display and set focus (which happens to be back of our sorted list)
void ImGui::FocusWindow(ImGuiWindow* window)
{
ImGuiContext& g = *GImGui;
if (g.NavWindow != window)
{
g.NavWindow = window;
if (window && g.NavDisableMouseHover)
g.NavMousePosDirty = true;
g.NavInitRequest = false;
g.NavId = window ? window->NavLastIds[0] : 0; // Restore NavId
g.NavFocusScopeId = 0;
g.NavIdIsAlive = false;
g.NavLayer = ImGuiNavLayer_Main;
//IMGUI_DEBUG_LOG("FocusWindow(\"%s\")\n", window ? window->Name : NULL);
}
// Close popups if any
ClosePopupsOverWindow(window, false);
// Passing NULL allow to disable keyboard focus
if (!window)
return;
// Move the root window to the top of the pile
IM_ASSERT(window->RootWindow != NULL);
ImGuiWindow* focus_front_window = window->RootWindow; // NB: In docking branch this is window->RootWindowDockStop
ImGuiWindow* display_front_window = window->RootWindow;
// Steal focus on active widgets
if (focus_front_window->Flags & ImGuiWindowFlags_Popup) // FIXME: This statement may be unnecessary? Need further testing before removing it..
if (g.ActiveId != 0 && g.ActiveIdWindow && g.ActiveIdWindow->RootWindow != focus_front_window)
ClearActiveID();
// Bring to front
BringWindowToFocusFront(focus_front_window);
if (((window->Flags | display_front_window->Flags) & ImGuiWindowFlags_NoBringToFrontOnFocus) == 0)
BringWindowToDisplayFront(display_front_window);
}
void ImGui::FocusTopMostWindowUnderOne(ImGuiWindow* under_this_window, ImGuiWindow* ignore_window)
{
ImGuiContext& g = *GImGui;
int start_idx = g.WindowsFocusOrder.Size - 1;
if (under_this_window != NULL)
{
int under_this_window_idx = FindWindowFocusIndex(under_this_window);
if (under_this_window_idx != -1)
start_idx = under_this_window_idx - 1;
}
for (int i = start_idx; i >= 0; i--)
{
// We may later decide to test for different NoXXXInputs based on the active navigation input (mouse vs nav) but that may feel more confusing to the user.
ImGuiWindow* window = g.WindowsFocusOrder[i];
if (window != ignore_window && window->WasActive && !(window->Flags & ImGuiWindowFlags_ChildWindow))
if ((window->Flags & (ImGuiWindowFlags_NoMouseInputs | ImGuiWindowFlags_NoNavInputs)) != (ImGuiWindowFlags_NoMouseInputs | ImGuiWindowFlags_NoNavInputs))
{
ImGuiWindow* focus_window = NavRestoreLastChildNavWindow(window);
FocusWindow(focus_window);
return;
}
}
FocusWindow(NULL);
}
void ImGui::SetCurrentFont(ImFont* font)
{
ImGuiContext& g = *GImGui;
IM_ASSERT(font && font->IsLoaded()); // Font Atlas not created. Did you call io.Fonts->GetTexDataAsRGBA32 / GetTexDataAsAlpha8 ?
IM_ASSERT(font->Scale > 0.0f);
g.Font = font;
g.FontBaseSize = ImMax(1.0f, g.IO.FontGlobalScale * g.Font->FontSize * g.Font->Scale);
g.FontSize = g.CurrentWindow ? g.CurrentWindow->CalcFontSize() : 0.0f;
ImFontAtlas* atlas = g.Font->ContainerAtlas;
g.DrawListSharedData.TexUvWhitePixel = atlas->TexUvWhitePixel;
g.DrawListSharedData.Font = g.Font;
g.DrawListSharedData.FontSize = g.FontSize;
}
void ImGui::PushFont(ImFont* font)
{
ImGuiContext& g = *GImGui;
if (!font)
font = GetDefaultFont();
SetCurrentFont(font);
g.FontStack.push_back(font);
g.CurrentWindow->DrawList->PushTextureID(font->ContainerAtlas->TexID);
}
void ImGui::PopFont()
{
ImGuiContext& g = *GImGui;
g.CurrentWindow->DrawList->PopTextureID();
g.FontStack.pop_back();
SetCurrentFont(g.FontStack.empty() ? GetDefaultFont() : g.FontStack.back());
}
void ImGui::PushItemFlag(ImGuiItemFlags option, bool enabled)
{
ImGuiWindow* window = GetCurrentWindow();
if (enabled)
window->DC.ItemFlags |= option;
else
window->DC.ItemFlags &= ~option;
window->DC.ItemFlagsStack.push_back(window->DC.ItemFlags);
}
void ImGui::PopItemFlag()
{
ImGuiWindow* window = GetCurrentWindow();
window->DC.ItemFlagsStack.pop_back();
window->DC.ItemFlags = window->DC.ItemFlagsStack.empty() ? ImGuiItemFlags_Default_ : window->DC.ItemFlagsStack.back();
}
// FIXME: Look into renaming this once we have settled the new Focus/Activation/TabStop system.
void ImGui::PushAllowKeyboardFocus(bool allow_keyboard_focus)
{
PushItemFlag(ImGuiItemFlags_NoTabStop, !allow_keyboard_focus);
}
void ImGui::PopAllowKeyboardFocus()
{
PopItemFlag();
}
void ImGui::PushButtonRepeat(bool repeat)
{
PushItemFlag(ImGuiItemFlags_ButtonRepeat, repeat);
}
void ImGui::PopButtonRepeat()
{
PopItemFlag();
}
void ImGui::PushTextWrapPos(float wrap_pos_x)
{
ImGuiWindow* window = GetCurrentWindow();
window->DC.TextWrapPos = wrap_pos_x;
window->DC.TextWrapPosStack.push_back(wrap_pos_x);
}
void ImGui::PopTextWrapPos()
{
ImGuiWindow* window = GetCurrentWindow();
window->DC.TextWrapPosStack.pop_back();
window->DC.TextWrapPos = window->DC.TextWrapPosStack.empty() ? -1.0f : window->DC.TextWrapPosStack.back();
}
bool ImGui::IsWindowChildOf(ImGuiWindow* window, ImGuiWindow* potential_parent)
{
if (window->RootWindow == potential_parent)
return true;
while (window != NULL)
{
if (window == potential_parent)
return true;
window = window->ParentWindow;
}
return false;
}
bool ImGui::IsWindowHovered(ImGuiHoveredFlags flags)
{
IM_ASSERT((flags & ImGuiHoveredFlags_AllowWhenOverlapped) == 0); // Flags not supported by this function
ImGuiContext& g = *GImGui;
if (flags & ImGuiHoveredFlags_AnyWindow)
{
if (g.HoveredWindow == NULL)
return false;
}
else
{
switch (flags & (ImGuiHoveredFlags_RootWindow | ImGuiHoveredFlags_ChildWindows))
{
case ImGuiHoveredFlags_RootWindow | ImGuiHoveredFlags_ChildWindows:
if (g.HoveredRootWindow != g.CurrentWindow->RootWindow)
return false;
break;
case ImGuiHoveredFlags_RootWindow:
if (g.HoveredWindow != g.CurrentWindow->RootWindow)
return false;
break;
case ImGuiHoveredFlags_ChildWindows:
if (g.HoveredWindow == NULL || !IsWindowChildOf(g.HoveredWindow, g.CurrentWindow))
return false;
break;
default:
if (g.HoveredWindow != g.CurrentWindow)
return false;
break;
}
}
if (!IsWindowContentHoverable(g.HoveredWindow, flags))
return false;
if (!(flags & ImGuiHoveredFlags_AllowWhenBlockedByActiveItem))
if (g.ActiveId != 0 && !g.ActiveIdAllowOverlap && g.ActiveId != g.HoveredWindow->MoveId)
return false;
return true;
}
bool ImGui::IsWindowFocused(ImGuiFocusedFlags flags)
{
ImGuiContext& g = *GImGui;
if (flags & ImGuiFocusedFlags_AnyWindow)
return g.NavWindow != NULL;
IM_ASSERT(g.CurrentWindow); // Not inside a Begin()/End()
switch (flags & (ImGuiFocusedFlags_RootWindow | ImGuiFocusedFlags_ChildWindows))
{
case ImGuiFocusedFlags_RootWindow | ImGuiFocusedFlags_ChildWindows:
return g.NavWindow && g.NavWindow->RootWindow == g.CurrentWindow->RootWindow;
case ImGuiFocusedFlags_RootWindow:
return g.NavWindow == g.CurrentWindow->RootWindow;
case ImGuiFocusedFlags_ChildWindows:
return g.NavWindow && IsWindowChildOf(g.NavWindow, g.CurrentWindow);
default:
return g.NavWindow == g.CurrentWindow;
}
}
// Can we focus this window with CTRL+TAB (or PadMenu + PadFocusPrev/PadFocusNext)
// Note that NoNavFocus makes the window not reachable with CTRL+TAB but it can still be focused with mouse or programmaticaly.
// If you want a window to never be focused, you may use the e.g. NoInputs flag.
bool ImGui::IsWindowNavFocusable(ImGuiWindow* window)
{
return window->Active && window == window->RootWindow && !(window->Flags & ImGuiWindowFlags_NoNavFocus);
}
float ImGui::GetWindowWidth()
{
ImGuiWindow* window = GImGui->CurrentWindow;
return window->Size.x;
}
float ImGui::GetWindowHeight()
{
ImGuiWindow* window = GImGui->CurrentWindow;
return window->Size.y;
}
ImVec2 ImGui::GetWindowPos()
{
ImGuiContext& g = *GImGui;
ImGuiWindow* window = g.CurrentWindow;
return window->Pos;
}
void ImGui::SetWindowPos(ImGuiWindow* window, const ImVec2& pos, ImGuiCond cond)
{
// Test condition (NB: bit 0 is always true) and clear flags for next time
if (cond && (window->SetWindowPosAllowFlags & cond) == 0)
return;
IM_ASSERT(cond == 0 || ImIsPowerOfTwo(cond)); // Make sure the user doesn't attempt to combine multiple condition flags.
window->SetWindowPosAllowFlags &= ~(ImGuiCond_Once | ImGuiCond_FirstUseEver | ImGuiCond_Appearing);
window->SetWindowPosVal = ImVec2(FLT_MAX, FLT_MAX);
// Set
const ImVec2 old_pos = window->Pos;
window->Pos = ImFloor(pos);
ImVec2 offset = window->Pos - old_pos;
window->DC.CursorPos += offset; // As we happen to move the window while it is being appended to (which is a bad idea - will smear) let's at least offset the cursor
window->DC.CursorMaxPos += offset; // And more importantly we need to offset CursorMaxPos/CursorStartPos this so ContentSize calculation doesn't get affected.
window->DC.CursorStartPos += offset;
}
void ImGui::SetWindowPos(const ImVec2& pos, ImGuiCond cond)
{
ImGuiWindow* window = GetCurrentWindowRead();
SetWindowPos(window, pos, cond);
}
void ImGui::SetWindowPos(const char* name, const ImVec2& pos, ImGuiCond cond)
{
if (ImGuiWindow* window = FindWindowByName(name))
SetWindowPos(window, pos, cond);
}
ImVec2 ImGui::GetWindowSize()
{
ImGuiWindow* window = GetCurrentWindowRead();
return window->Size;
}
void ImGui::SetWindowSize(ImGuiWindow* window, const ImVec2& size, ImGuiCond cond)
{
// Test condition (NB: bit 0 is always true) and clear flags for next time
if (cond && (window->SetWindowSizeAllowFlags & cond) == 0)
return;
IM_ASSERT(cond == 0 || ImIsPowerOfTwo(cond)); // Make sure the user doesn't attempt to combine multiple condition flags.
window->SetWindowSizeAllowFlags &= ~(ImGuiCond_Once | ImGuiCond_FirstUseEver | ImGuiCond_Appearing);
// Set
if (size.x > 0.0f)
{
window->AutoFitFramesX = 0;
window->SizeFull.x = IM_FLOOR(size.x);
}
else
{
window->AutoFitFramesX = 2;
window->AutoFitOnlyGrows = false;
}
if (size.y > 0.0f)
{
window->AutoFitFramesY = 0;
window->SizeFull.y = IM_FLOOR(size.y);
}
else
{
window->AutoFitFramesY = 2;
window->AutoFitOnlyGrows = false;
}
}
void ImGui::SetWindowSize(const ImVec2& size, ImGuiCond cond)
{
SetWindowSize(GImGui->CurrentWindow, size, cond);
}
void ImGui::SetWindowSize(const char* name, const ImVec2& size, ImGuiCond cond)
{
if (ImGuiWindow* window = FindWindowByName(name))
SetWindowSize(window, size, cond);
}
void ImGui::SetWindowCollapsed(ImGuiWindow* window, bool collapsed, ImGuiCond cond)
{
// Test condition (NB: bit 0 is always true) and clear flags for next time
if (cond && (window->SetWindowCollapsedAllowFlags & cond) == 0)
return;
window->SetWindowCollapsedAllowFlags &= ~(ImGuiCond_Once | ImGuiCond_FirstUseEver | ImGuiCond_Appearing);
// Set
window->Collapsed = collapsed;
}
void ImGui::SetWindowCollapsed(bool collapsed, ImGuiCond cond)
{
SetWindowCollapsed(GImGui->CurrentWindow, collapsed, cond);
}
bool ImGui::IsWindowCollapsed()
{
ImGuiWindow* window = GetCurrentWindowRead();
return window->Collapsed;
}
bool ImGui::IsWindowAppearing()
{
ImGuiWindow* window = GetCurrentWindowRead();
return window->Appearing;
}
void ImGui::SetWindowCollapsed(const char* name, bool collapsed, ImGuiCond cond)
{
if (ImGuiWindow* window = FindWindowByName(name))
SetWindowCollapsed(window, collapsed, cond);
}
void ImGui::SetWindowFocus()
{
FocusWindow(GImGui->CurrentWindow);
}
void ImGui::SetWindowFocus(const char* name)
{
if (name)
{
if (ImGuiWindow* window = FindWindowByName(name))
FocusWindow(window);
}
else
{
FocusWindow(NULL);
}
}
void ImGui::SetNextWindowPos(const ImVec2& pos, ImGuiCond cond, const ImVec2& pivot)
{
ImGuiContext& g = *GImGui;
IM_ASSERT(cond == 0 || ImIsPowerOfTwo(cond)); // Make sure the user doesn't attempt to combine multiple condition flags.
g.NextWindowData.Flags |= ImGuiNextWindowDataFlags_HasPos;
g.NextWindowData.PosVal = pos;
g.NextWindowData.PosPivotVal = pivot;
g.NextWindowData.PosCond = cond ? cond : ImGuiCond_Always;
}
void ImGui::SetNextWindowSize(const ImVec2& size, ImGuiCond cond)
{
ImGuiContext& g = *GImGui;
IM_ASSERT(cond == 0 || ImIsPowerOfTwo(cond)); // Make sure the user doesn't attempt to combine multiple condition flags.
g.NextWindowData.Flags |= ImGuiNextWindowDataFlags_HasSize;
g.NextWindowData.SizeVal = size;
g.NextWindowData.SizeCond = cond ? cond : ImGuiCond_Always;
}
void ImGui::SetNextWindowSizeConstraints(const ImVec2& size_min, const ImVec2& size_max, ImGuiSizeCallback custom_callback, void* custom_callback_user_data)
{
ImGuiContext& g = *GImGui;
g.NextWindowData.Flags |= ImGuiNextWindowDataFlags_HasSizeConstraint;
g.NextWindowData.SizeConstraintRect = ImRect(size_min, size_max);
g.NextWindowData.SizeCallback = custom_callback;
g.NextWindowData.SizeCallbackUserData = custom_callback_user_data;
}
// Content size = inner scrollable rectangle, padded with WindowPadding.
// SetNextWindowContentSize(ImVec2(100,100) + ImGuiWindowFlags_AlwaysAutoResize will always allow submitting a 100x100 item.
void ImGui::SetNextWindowContentSize(const ImVec2& size)
{
ImGuiContext& g = *GImGui;
g.NextWindowData.Flags |= ImGuiNextWindowDataFlags_HasContentSize;
g.NextWindowData.ContentSizeVal = size;
}
void ImGui::SetNextWindowCollapsed(bool collapsed, ImGuiCond cond)
{
ImGuiContext& g = *GImGui;
IM_ASSERT(cond == 0 || ImIsPowerOfTwo(cond)); // Make sure the user doesn't attempt to combine multiple condition flags.
g.NextWindowData.Flags |= ImGuiNextWindowDataFlags_HasCollapsed;
g.NextWindowData.CollapsedVal = collapsed;
g.NextWindowData.CollapsedCond = cond ? cond : ImGuiCond_Always;
}
void ImGui::SetNextWindowFocus()
{
ImGuiContext& g = *GImGui;
g.NextWindowData.Flags |= ImGuiNextWindowDataFlags_HasFocus;
}
void ImGui::SetNextWindowBgAlpha(float alpha)
{
ImGuiContext& g = *GImGui;
g.NextWindowData.Flags |= ImGuiNextWindowDataFlags_HasBgAlpha;
g.NextWindowData.BgAlphaVal = alpha;
}
ImDrawList* ImGui::GetWindowDrawList()
{
ImGuiWindow* window = GetCurrentWindow();
return window->DrawList;
}
ImFont* ImGui::GetFont()
{
return GImGui->Font;
}
float ImGui::GetFontSize()
{
return GImGui->FontSize;
}
ImVec2 ImGui::GetFontTexUvWhitePixel()
{
return GImGui->DrawListSharedData.TexUvWhitePixel;
}
void ImGui::SetWindowFontScale(float scale)
{
ImGuiContext& g = *GImGui;
ImGuiWindow* window = GetCurrentWindow();
window->FontWindowScale = scale;
g.FontSize = g.DrawListSharedData.FontSize = window->CalcFontSize();
}
void ImGui::ActivateItem(ImGuiID id)
{
ImGuiContext& g = *GImGui;
g.NavNextActivateId = id;
}
void ImGui::PushFocusScope(ImGuiID id)
{
ImGuiContext& g = *GImGui;
ImGuiWindow* window = g.CurrentWindow;
window->IDStack.push_back(window->DC.NavFocusScopeIdCurrent);
window->DC.NavFocusScopeIdCurrent = id;
}
void ImGui::PopFocusScope()
{
ImGuiContext& g = *GImGui;
ImGuiWindow* window = g.CurrentWindow;
window->DC.NavFocusScopeIdCurrent = window->IDStack.back();
window->IDStack.pop_back();
}
void ImGui::SetKeyboardFocusHere(int offset)
{
IM_ASSERT(offset >= -1); // -1 is allowed but not below
ImGuiContext& g = *GImGui;
ImGuiWindow* window = g.CurrentWindow;
g.FocusRequestNextWindow = window;
g.FocusRequestNextCounterRegular = window->DC.FocusCounterRegular + 1 + offset;
g.FocusRequestNextCounterTabStop = INT_MAX;
}
void ImGui::SetItemDefaultFocus()
{
ImGuiContext& g = *GImGui;
ImGuiWindow* window = g.CurrentWindow;
if (!window->Appearing)
return;
if (g.NavWindow == window->RootWindowForNav && (g.NavInitRequest || g.NavInitResultId != 0) && g.NavLayer == g.NavWindow->DC.NavLayerCurrent)
{
g.NavInitRequest = false;
g.NavInitResultId = g.NavWindow->DC.LastItemId;
g.NavInitResultRectRel = ImRect(g.NavWindow->DC.LastItemRect.Min - g.NavWindow->Pos, g.NavWindow->DC.LastItemRect.Max - g.NavWindow->Pos);
NavUpdateAnyRequestFlag();
if (!IsItemVisible())
SetScrollHereY();
}
}
void ImGui::SetStateStorage(ImGuiStorage* tree)
{
ImGuiWindow* window = GImGui->CurrentWindow;
window->DC.StateStorage = tree ? tree : &window->StateStorage;
}
ImGuiStorage* ImGui::GetStateStorage()
{
ImGuiWindow* window = GImGui->CurrentWindow;
return window->DC.StateStorage;
}
void ImGui::PushID(const char* str_id)
{
ImGuiWindow* window = GImGui->CurrentWindow;
window->IDStack.push_back(window->GetIDNoKeepAlive(str_id));
}
void ImGui::PushID(const char* str_id_begin, const char* str_id_end)
{
ImGuiWindow* window = GImGui->CurrentWindow;
window->IDStack.push_back(window->GetIDNoKeepAlive(str_id_begin, str_id_end));
}
void ImGui::PushID(const void* ptr_id)
{
ImGuiWindow* window = GImGui->CurrentWindow;
window->IDStack.push_back(window->GetIDNoKeepAlive(ptr_id));
}
void ImGui::PushID(int int_id)
{
ImGuiWindow* window = GImGui->CurrentWindow;
window->IDStack.push_back(window->GetIDNoKeepAlive(int_id));
}
// Push a given id value ignoring the ID stack as a seed.
void ImGui::PushOverrideID(ImGuiID id)
{
ImGuiWindow* window = GImGui->CurrentWindow;
window->IDStack.push_back(id);
}
void ImGui::PopID()
{
ImGuiWindow* window = GImGui->CurrentWindow;
window->IDStack.pop_back();
}
ImGuiID ImGui::GetID(const char* str_id)
{
ImGuiWindow* window = GImGui->CurrentWindow;
return window->GetID(str_id);
}
ImGuiID ImGui::GetID(const char* str_id_begin, const char* str_id_end)
{
ImGuiWindow* window = GImGui->CurrentWindow;
return window->GetID(str_id_begin, str_id_end);
}
ImGuiID ImGui::GetID(const void* ptr_id)
{
ImGuiWindow* window = GImGui->CurrentWindow;
return window->GetID(ptr_id);
}
bool ImGui::IsRectVisible(const ImVec2& size)
{
ImGuiWindow* window = GImGui->CurrentWindow;
return window->ClipRect.Overlaps(ImRect(window->DC.CursorPos, window->DC.CursorPos + size));
}
bool ImGui::IsRectVisible(const ImVec2& rect_min, const ImVec2& rect_max)
{
ImGuiWindow* window = GImGui->CurrentWindow;
return window->ClipRect.Overlaps(ImRect(rect_min, rect_max));
}
//-----------------------------------------------------------------------------
// [SECTION] ERROR CHECKING
//-----------------------------------------------------------------------------
// Helper function to verify ABI compatibility between caller code and compiled version of Dear ImGui.
// Verify that the type sizes are matching between the calling file's compilation unit and imgui.cpp's compilation unit
// If the user has inconsistent compilation settings, imgui configuration #define, packing pragma, etc. your user code
// may see different structures than what imgui.cpp sees, which is problematic.
// We usually require settings to be in imconfig.h to make sure that they are accessible to all compilation units involved with Dear ImGui.
bool ImGui::DebugCheckVersionAndDataLayout(const char* version, size_t sz_io, size_t sz_style, size_t sz_vec2, size_t sz_vec4, size_t sz_vert, size_t sz_idx)
{
bool error = false;
if (strcmp(version, IMGUI_VERSION) != 0) { error = true; IM_ASSERT(strcmp(version, IMGUI_VERSION) == 0 && "Mismatched version string!"); }
if (sz_io != sizeof(ImGuiIO)) { error = true; IM_ASSERT(sz_io == sizeof(ImGuiIO) && "Mismatched struct layout!"); }
if (sz_style != sizeof(ImGuiStyle)) { error = true; IM_ASSERT(sz_style == sizeof(ImGuiStyle) && "Mismatched struct layout!"); }
if (sz_vec2 != sizeof(ImVec2)) { error = true; IM_ASSERT(sz_vec2 == sizeof(ImVec2) && "Mismatched struct layout!"); }
if (sz_vec4 != sizeof(ImVec4)) { error = true; IM_ASSERT(sz_vec4 == sizeof(ImVec4) && "Mismatched struct layout!"); }
if (sz_vert != sizeof(ImDrawVert)) { error = true; IM_ASSERT(sz_vert == sizeof(ImDrawVert) && "Mismatched struct layout!"); }
if (sz_idx != sizeof(ImDrawIdx)) { error = true; IM_ASSERT(sz_idx == sizeof(ImDrawIdx) && "Mismatched struct layout!"); }
return !error;
}
static void ImGui::ErrorCheckEndFrame()
{
// Report when there is a mismatch of Begin/BeginChild vs End/EndChild calls. Important: Remember that the Begin/BeginChild API requires you
// to always call End/EndChild even if Begin/BeginChild returns false! (this is unfortunately inconsistent with most other Begin* API).
ImGuiContext& g = *GImGui;
if (g.CurrentWindowStack.Size != 1)
{
if (g.CurrentWindowStack.Size > 1)
{
IM_ASSERT_USER_ERROR(g.CurrentWindowStack.Size == 1, "Mismatched Begin/BeginChild vs End/EndChild calls: did you forget to call End/EndChild?");
while (g.CurrentWindowStack.Size > 1)
End();
}
else
{
IM_ASSERT_USER_ERROR(g.CurrentWindowStack.Size == 1, "Mismatched Begin/BeginChild vs End/EndChild calls: did you call End/EndChild too much?");
}
}
}
// Save and compare stack sizes on Begin()/End() to detect usage errors
// Begin() calls this with write=true
// End() calls this with write=false
static void ImGui::ErrorCheckBeginEndCompareStacksSize(ImGuiWindow* window, bool write)
{
ImGuiContext& g = *GImGui;
short* p = &window->DC.StackSizesBackup[0];
// Window stacks
// 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)
{ int n = window->IDStack.Size; if (write) *p = (short)n; else IM_ASSERT(*p == n && "PushID/PopID or TreeNode/TreePop Mismatch!"); p++; } // Too few or too many PopID()/TreePop()
{ int n = window->DC.GroupStack.Size; if (write) *p = (short)n; else IM_ASSERT(*p == n && "BeginGroup/EndGroup Mismatch!"); p++; } // Too few or too many EndGroup()
// Global stacks
// For color, style and font stacks there is an incentive to use Push/Begin/Pop/.../End patterns, so we relax our checks a little to allow them.
{ int n = g.BeginPopupStack.Size; if (write) *p = (short)n; else IM_ASSERT(*p == n && "BeginMenu/EndMenu or BeginPopup/EndPopup Mismatch!"); p++; }// Too few or too many EndMenu()/EndPopup()
{ int n = g.ColorModifiers.Size; if (write) *p = (short)n; else IM_ASSERT(*p >= n && "PushStyleColor/PopStyleColor Mismatch!"); p++; } // Too few or too many PopStyleColor()
{ int n = g.StyleModifiers.Size; if (write) *p = (short)n; else IM_ASSERT(*p >= n && "PushStyleVar/PopStyleVar Mismatch!"); p++; } // Too few or too many PopStyleVar()
{ int n = g.FontStack.Size; if (write) *p = (short)n; else IM_ASSERT(*p >= n && "PushFont/PopFont Mismatch!"); p++; } // Too few or too many PopFont()
IM_ASSERT(p == window->DC.StackSizesBackup + IM_ARRAYSIZE(window->DC.StackSizesBackup));
}
//-----------------------------------------------------------------------------
// [SECTION] LAYOUT
//-----------------------------------------------------------------------------
// - ItemSize()
// - ItemAdd()
// - SameLine()
// - GetCursorScreenPos()
// - SetCursorScreenPos()
// - GetCursorPos(), GetCursorPosX(), GetCursorPosY()
// - SetCursorPos(), SetCursorPosX(), SetCursorPosY()
// - GetCursorStartPos()
// - Indent()
// - Unindent()
// - SetNextItemWidth()
// - PushItemWidth()
// - PushMultiItemsWidths()
// - PopItemWidth()
// - CalcItemWidth()
// - CalcItemSize()
// - GetTextLineHeight()
// - GetTextLineHeightWithSpacing()
// - GetFrameHeight()
// - GetFrameHeightWithSpacing()
// - GetContentRegionMax()
// - GetContentRegionMaxAbs() [Internal]
// - GetContentRegionAvail(),
// - GetWindowContentRegionMin(), GetWindowContentRegionMax()
// - GetWindowContentRegionWidth()
// - BeginGroup()
// - EndGroup()
// Also see in imgui_widgets: tab bars, columns.
//-----------------------------------------------------------------------------
// Advance cursor given item size for layout.
void ImGui::ItemSize(const ImVec2& size, float text_baseline_y)
{
ImGuiContext& g = *GImGui;
ImGuiWindow* window = g.CurrentWindow;
if (window->SkipItems)
return;
// We increase the height in this function to accommodate for baseline offset.
// In theory we should be offsetting the starting position (window->DC.CursorPos), that will be the topic of a larger refactor,
// but since ItemSize() is not yet an API that moves the cursor (to handle e.g. wrapping) enlarging the height has the same effect.
const float offset_to_match_baseline_y = (text_baseline_y >= 0) ? ImMax(0.0f, window->DC.CurrLineTextBaseOffset - text_baseline_y) : 0.0f;
const float line_height = ImMax(window->DC.CurrLineSize.y, size.y + offset_to_match_baseline_y);
// Always align ourselves on pixel boundaries
//if (g.IO.KeyAlt) window->DrawList->AddRect(window->DC.CursorPos, window->DC.CursorPos + ImVec2(size.x, line_height), IM_COL32(255,0,0,200)); // [DEBUG]
window->DC.CursorPosPrevLine.x = window->DC.CursorPos.x + size.x;
window->DC.CursorPosPrevLine.y = window->DC.CursorPos.y;
window->DC.CursorPos.x = IM_FLOOR(window->Pos.x + window->DC.Indent.x + window->DC.ColumnsOffset.x); // Next line
window->DC.CursorPos.y = IM_FLOOR(window->DC.CursorPos.y + line_height + g.Style.ItemSpacing.y); // Next line
window->DC.CursorMaxPos.x = ImMax(window->DC.CursorMaxPos.x, window->DC.CursorPosPrevLine.x);
window->DC.CursorMaxPos.y = ImMax(window->DC.CursorMaxPos.y, window->DC.CursorPos.y - g.Style.ItemSpacing.y);
//if (g.IO.KeyAlt) window->DrawList->AddCircle(window->DC.CursorMaxPos, 3.0f, IM_COL32(255,0,0,255), 4); // [DEBUG]
window->DC.PrevLineSize.y = line_height;
window->DC.CurrLineSize.y = 0.0f;
window->DC.PrevLineTextBaseOffset = ImMax(window->DC.CurrLineTextBaseOffset, text_baseline_y);
window->DC.CurrLineTextBaseOffset = 0.0f;
// Horizontal layout mode
if (window->DC.LayoutType == ImGuiLayoutType_Horizontal)
SameLine();
}
void ImGui::ItemSize(const ImRect& bb, float text_baseline_y)
{
ItemSize(bb.GetSize(), text_baseline_y);
}
// Declare item bounding box for clipping and interaction.
// Note that the size can be different than the one provided to ItemSize(). Typically, widgets that spread over available surface
// declare their minimum size requirement to ItemSize() and then use a larger region for drawing/interaction, which is passed to ItemAdd().
bool ImGui::ItemAdd(const ImRect& bb, ImGuiID id, const ImRect* nav_bb_arg)
{
ImGuiContext& g = *GImGui;
ImGuiWindow* window = g.CurrentWindow;
if (id != 0)
{
// Navigation processing runs prior to clipping early-out
// (a) So that NavInitRequest can be honored, for newly opened windows to select a default widget
// (b) So that we can scroll up/down past clipped items. This adds a small O(N) cost to regular navigation requests
// unfortunately, but it is still limited to one window. It may not scale very well for windows with ten of
// thousands of item, but at least NavMoveRequest is only set on user interaction, aka maximum once a frame.
// We could early out with "if (is_clipped && !g.NavInitRequest) return false;" but when we wouldn't be able
// to reach unclipped widgets. This would work if user had explicit scrolling control (e.g. mapped on a stick).
// We intentionally don't check if g.NavWindow != NULL because g.NavAnyRequest should only be set when it is non null.
// If we crash on a NULL g.NavWindow we need to fix the bug elsewhere.
window->DC.NavLayerActiveMaskNext |= window->DC.NavLayerCurrentMask;
if (g.NavId == id || g.NavAnyRequest)
if (g.NavWindow->RootWindowForNav == window->RootWindowForNav)
if (window == g.NavWindow || ((window->Flags | g.NavWindow->Flags) & ImGuiWindowFlags_NavFlattened))
NavProcessItem(window, nav_bb_arg ? *nav_bb_arg : bb, id);
// [DEBUG] Item Picker tool, when enabling the "extended" version we perform the check in ItemAdd()
#ifdef IMGUI_DEBUG_TOOL_ITEM_PICKER_EX
if (id == g.DebugItemPickerBreakId)
{
IM_DEBUG_BREAK();
g.DebugItemPickerBreakId = 0;
}
#endif
}
window->DC.LastItemId = id;
window->DC.LastItemRect = bb;
window->DC.LastItemStatusFlags = ImGuiItemStatusFlags_None;
g.NextItemData.Flags = ImGuiNextItemDataFlags_None;
#ifdef IMGUI_ENABLE_TEST_ENGINE
if (id != 0)
IMGUI_TEST_ENGINE_ITEM_ADD(nav_bb_arg ? *nav_bb_arg : bb, id);
#endif
// Clipping test
const bool is_clipped = IsClippedEx(bb, id, false);
if (is_clipped)
return false;
//if (g.IO.KeyAlt) window->DrawList->AddRect(bb.Min, bb.Max, IM_COL32(255,255,0,120)); // [DEBUG]
// We need to calculate this now to take account of the current clipping rectangle (as items like Selectable may change them)
if (IsMouseHoveringRect(bb.Min, bb.Max))
window->DC.LastItemStatusFlags |= ImGuiItemStatusFlags_HoveredRect;
return true;
}
// Gets back to previous line and continue with horizontal layout
// offset_from_start_x == 0 : follow right after previous item
// offset_from_start_x != 0 : align to specified x position (relative to window/group left)
// spacing_w < 0 : use default spacing if pos_x == 0, no spacing if pos_x != 0
// spacing_w >= 0 : enforce spacing amount
void ImGui::SameLine(float offset_from_start_x, float spacing_w)
{
ImGuiWindow* window = GetCurrentWindow();
if (window->SkipItems)
return;
ImGuiContext& g = *GImGui;
if (offset_from_start_x != 0.0f)
{
if (spacing_w < 0.0f) spacing_w = 0.0f;
window->DC.CursorPos.x = window->Pos.x - window->Scroll.x + offset_from_start_x + spacing_w + window->DC.GroupOffset.x + window->DC.ColumnsOffset.x;
window->DC.CursorPos.y = window->DC.CursorPosPrevLine.y;
}
else
{
if (spacing_w < 0.0f) spacing_w = g.Style.ItemSpacing.x;
window->DC.CursorPos.x = window->DC.CursorPosPrevLine.x + spacing_w;
window->DC.CursorPos.y = window->DC.CursorPosPrevLine.y;
}
window->DC.CurrLineSize = window->DC.PrevLineSize;
window->DC.CurrLineTextBaseOffset = window->DC.PrevLineTextBaseOffset;
}
ImVec2 ImGui::GetCursorScreenPos()
{
ImGuiWindow* window = GetCurrentWindowRead();
return window->DC.CursorPos;
}
void ImGui::SetCursorScreenPos(const ImVec2& pos)
{
ImGuiWindow* window = GetCurrentWindow();
window->DC.CursorPos = pos;
window->DC.CursorMaxPos = ImMax(window->DC.CursorMaxPos, window->DC.CursorPos);
}
// 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;
}
void ImGui::Indent(float indent_w)
{
ImGuiContext& g = *GImGui;
ImGuiWindow* window = GetCurrentWindow();
window->DC.Indent.x += (indent_w != 0.0f) ? indent_w : g.Style.IndentSpacing;
window->DC.CursorPos.x = window->Pos.x + window->DC.Indent.x + window->DC.ColumnsOffset.x;
}
void ImGui::Unindent(float indent_w)
{
ImGuiContext& g = *GImGui;
ImGuiWindow* window = GetCurrentWindow();
window->DC.Indent.x -= (indent_w != 0.0f) ? indent_w : g.Style.IndentSpacing;
window->DC.CursorPos.x = window->Pos.x + window->DC.Indent.x + window->DC.ColumnsOffset.x;
}
// Affect large frame+labels widgets only.
void ImGui::SetNextItemWidth(float item_width)
{
ImGuiContext& g = *GImGui;
g.NextItemData.Flags |= ImGuiNextItemDataFlags_HasWidth;
g.NextItemData.Width = item_width;
}
void ImGui::PushItemWidth(float item_width)
{
ImGuiContext& g = *GImGui;
ImGuiWindow* window = g.CurrentWindow;
window->DC.ItemWidth = (item_width == 0.0f ? window->ItemWidthDefault : item_width);
window->DC.ItemWidthStack.push_back(window->DC.ItemWidth);
g.NextItemData.Flags &= ~ImGuiNextItemDataFlags_HasWidth;
}
void ImGui::PushMultiItemsWidths(int components, float w_full)
{
ImGuiContext& g = *GImGui;
ImGuiWindow* window = g.CurrentWindow;
const ImGuiStyle& style = g.Style;
const float w_item_one = ImMax(1.0f, IM_FLOOR((w_full - (style.ItemInnerSpacing.x) * (components-1)) / (float)components));
const float w_item_last = ImMax(1.0f, IM_FLOOR(w_full - (w_item_one + style.ItemInnerSpacing.x) * (components-1)));
window->DC.ItemWidthStack.push_back(w_item_last);
for (int i = 0; i < components-1; i++)
window->DC.ItemWidthStack.push_back(w_item_one);
window->DC.ItemWidth = window->DC.ItemWidthStack.back();
g.NextItemData.Flags &= ~ImGuiNextItemDataFlags_HasWidth;
}
void ImGui::PopItemWidth()
{
ImGuiWindow* window = GetCurrentWindow();
window->DC.ItemWidthStack.pop_back();
window->DC.ItemWidth = window->DC.ItemWidthStack.empty() ? window->ItemWidthDefault : window->DC.ItemWidthStack.back();
}
// Calculate default item width given value passed to PushItemWidth() or SetNextItemWidth().
// The SetNextItemWidth() data is generally cleared/consumed by ItemAdd() or NextItemData.ClearFlags()
float ImGui::CalcItemWidth()
{
ImGuiContext& g = *GImGui;
ImGuiWindow* window = g.CurrentWindow;
float w;
if (g.NextItemData.Flags & ImGuiNextItemDataFlags_HasWidth)
w = g.NextItemData.Width;
else
w = window->DC.ItemWidth;
if (w < 0.0f)
{
float region_max_x = GetContentRegionMaxAbs().x;
w = ImMax(1.0f, region_max_x - window->DC.CursorPos.x + w);
}
w = IM_FLOOR(w);
return w;
}
// [Internal] Calculate full item size given user provided 'size' parameter and default width/height. Default width is often == CalcItemWidth().
// Those two functions CalcItemWidth vs CalcItemSize are awkwardly named because they are not fully symmetrical.
// Note that only CalcItemWidth() is publicly exposed.
// The 4.0f here may be changed to match CalcItemWidth() and/or BeginChild() (right now we have a mismatch which is harmless but undesirable)
ImVec2 ImGui::CalcItemSize(ImVec2 size, float default_w, float default_h)
{
ImGuiWindow* window = GImGui->CurrentWindow;
ImVec2 region_max;
if (size.x < 0.0f || size.y < 0.0f)
region_max = GetContentRegionMaxAbs();
if (size.x == 0.0f)
size.x = default_w;
else if (size.x < 0.0f)
size.x = ImMax(4.0f, region_max.x - window->DC.CursorPos.x + size.x);
if (size.y == 0.0f)
size.y = default_h;
else if (size.y < 0.0f)
size.y = ImMax(4.0f, region_max.y - window->DC.CursorPos.y + size.y);
return size;
}
float ImGui::GetTextLineHeight()
{
ImGuiContext& g = *GImGui;
return g.FontSize;
}
float ImGui::GetTextLineHeightWithSpacing()
{
ImGuiContext& g = *GImGui;
return g.FontSize + g.Style.ItemSpacing.y;
}
float ImGui::GetFrameHeight()
{
ImGuiContext& g = *GImGui;
return g.FontSize + g.Style.FramePadding.y * 2.0f;
}
float ImGui::GetFrameHeightWithSpacing()
{
ImGuiContext& g = *GImGui;
return g.FontSize + g.Style.FramePadding.y * 2.0f + g.Style.ItemSpacing.y;
}
// FIXME: All the Contents Region function are messy or misleading. WE WILL AIM TO OBSOLETE ALL OF THEM WITH A NEW "WORK RECT" API. Thanks for your patience!
// FIXME: This is in window space (not screen space!).
ImVec2 ImGui::GetContentRegionMax()
{
ImGuiContext& g = *GImGui;
ImGuiWindow* window = g.CurrentWindow;
ImVec2 mx = window->ContentRegionRect.Max - window->Pos;
if (window->DC.CurrentColumns)
mx.x = window->WorkRect.Max.x - window->Pos.x;
return mx;
}
// [Internal] Absolute coordinate. Saner. This is not exposed until we finishing refactoring work rect features.
ImVec2 ImGui::GetContentRegionMaxAbs()
{
ImGuiContext& g = *GImGui;
ImGuiWindow* window = g.CurrentWindow;
ImVec2 mx = window->ContentRegionRect.Max;
if (window->DC.CurrentColumns)
mx.x = window->WorkRect.Max.x;
return mx;
}
ImVec2 ImGui::GetContentRegionAvail()
{
ImGuiWindow* window = GImGui->CurrentWindow;
return GetContentRegionMaxAbs() - window->DC.CursorPos;
}
// In window space (not screen space!)
ImVec2 ImGui::GetWindowContentRegionMin()
{
ImGuiWindow* window = GImGui->CurrentWindow;
return window->ContentRegionRect.Min - window->Pos;
}
ImVec2 ImGui::GetWindowContentRegionMax()
{
ImGuiWindow* window = GImGui->CurrentWindow;
return window->ContentRegionRect.Max - window->Pos;
}
float ImGui::GetWindowContentRegionWidth()
{
ImGuiWindow* window = GImGui->CurrentWindow;
return window->ContentRegionRect.GetWidth();
}
// Lock horizontal starting position + capture group bounding box into one "item" (so you can use IsItemHovered() or layout primitives such as SameLine() on whole group, etc.)
void ImGui::BeginGroup()
{
ImGuiContext& g = *GImGui;
ImGuiWindow* window = GetCurrentWindow();
window->DC.GroupStack.resize(window->DC.GroupStack.Size + 1);
ImGuiGroupData& group_data = window->DC.GroupStack.back();
group_data.BackupCursorPos = window->DC.CursorPos;
group_data.BackupCursorMaxPos = window->DC.CursorMaxPos;
group_data.BackupIndent = window->DC.Indent;
group_data.BackupGroupOffset = window->DC.GroupOffset;
group_data.BackupCurrLineSize = window->DC.CurrLineSize;
group_data.BackupCurrLineTextBaseOffset = window->DC.CurrLineTextBaseOffset;
group_data.BackupActiveIdIsAlive = g.ActiveIdIsAlive;
group_data.BackupActiveIdPreviousFrameIsAlive = g.ActiveIdPreviousFrameIsAlive;
group_data.EmitItem = true;
window->DC.GroupOffset.x = window->DC.CursorPos.x - window->Pos.x - window->DC.ColumnsOffset.x;
window->DC.Indent = window->DC.GroupOffset;
window->DC.CursorMaxPos = window->DC.CursorPos;
window->DC.CurrLineSize = ImVec2(0.0f, 0.0f);
if (g.LogEnabled)
g.LogLinePosY = -FLT_MAX; // To enforce Log carriage return
}
void ImGui::EndGroup()
{
ImGuiContext& g = *GImGui;
ImGuiWindow* window = GetCurrentWindow();
IM_ASSERT(!window->DC.GroupStack.empty()); // Mismatched BeginGroup()/EndGroup() calls
ImGuiGroupData& group_data = window->DC.GroupStack.back();
ImRect group_bb(group_data.BackupCursorPos, ImMax(window->DC.CursorMaxPos, group_data.BackupCursorPos));
window->DC.CursorPos = group_data.BackupCursorPos;
window->DC.CursorMaxPos = ImMax(group_data.BackupCursorMaxPos, window->DC.CursorMaxPos);
window->DC.Indent = group_data.BackupIndent;
window->DC.GroupOffset = group_data.BackupGroupOffset;
window->DC.CurrLineSize = group_data.BackupCurrLineSize;
window->DC.CurrLineTextBaseOffset = group_data.BackupCurrLineTextBaseOffset;
if (g.LogEnabled)
g.LogLinePosY = -FLT_MAX; // To enforce Log carriage return
if (!group_data.EmitItem)
{
window->DC.GroupStack.pop_back();
return;
}
window->DC.CurrLineTextBaseOffset = ImMax(window->DC.PrevLineTextBaseOffset, group_data.BackupCurrLineTextBaseOffset); // FIXME: Incorrect, we should grab the base offset from the *first line* of the group but it is hard to obtain now.
ItemSize(group_bb.GetSize());
ItemAdd(group_bb, 0);
// If the current ActiveId was declared within the boundary of our group, we copy it to LastItemId so IsItemActive(), IsItemDeactivated() etc. will be functional on the entire group.
// It would be be neater if we replaced window.DC.LastItemId by e.g. 'bool LastItemIsActive', but would put a little more burden on individual widgets.
// Also if you grep for LastItemId you'll notice it is only used in that context.
// (The tests not symmetrical because ActiveIdIsAlive is an ID itself, in order to be able to handle ActiveId being overwritten during the frame.)
const bool group_contains_curr_active_id = (group_data.BackupActiveIdIsAlive != g.ActiveId) && (g.ActiveIdIsAlive == g.ActiveId) && g.ActiveId;
const bool group_contains_prev_active_id = !group_data.BackupActiveIdPreviousFrameIsAlive && g.ActiveIdPreviousFrameIsAlive;
if (group_contains_curr_active_id)
window->DC.LastItemId = g.ActiveId;
else if (group_contains_prev_active_id)
window->DC.LastItemId = g.ActiveIdPreviousFrame;
window->DC.LastItemRect = group_bb;
// Forward Edited flag
if (group_contains_curr_active_id && g.ActiveIdHasBeenEditedThisFrame)
window->DC.LastItemStatusFlags |= ImGuiItemStatusFlags_Edited;
// Forward Deactivated flag
window->DC.LastItemStatusFlags |= ImGuiItemStatusFlags_HasDeactivated;
if (group_contains_prev_active_id && g.ActiveId != g.ActiveIdPreviousFrame)
window->DC.LastItemStatusFlags |= ImGuiItemStatusFlags_Deactivated;
window->DC.GroupStack.pop_back();
//window->DrawList->AddRect(group_bb.Min, group_bb.Max, IM_COL32(255,0,255,255)); // [Debug]
}
//-----------------------------------------------------------------------------
// [SECTION] SCROLLING
//-----------------------------------------------------------------------------
static ImVec2 CalcNextScrollFromScrollTargetAndClamp(ImGuiWindow* window, bool snap_on_edges)
{
ImGuiContext& g = *GImGui;
ImVec2 scroll = window->Scroll;
if (window->ScrollTarget.x < FLT_MAX)
{
float cr_x = window->ScrollTargetCenterRatio.x;
float target_x = window->ScrollTarget.x;
if (snap_on_edges && cr_x <= 0.0f && target_x <= window->WindowPadding.x)
target_x = 0.0f;
else if (snap_on_edges && cr_x >= 1.0f && target_x >= window->ContentSize.x + window->WindowPadding.x + g.Style.ItemSpacing.x)
target_x = window->ContentSize.x + window->WindowPadding.x * 2.0f;
scroll.x = target_x - cr_x * (window->SizeFull.x - window->ScrollbarSizes.x);
}
if (window->ScrollTarget.y < FLT_MAX)
{
// 'snap_on_edges' allows for a discontinuity at the edge of scrolling limits to take account of WindowPadding so that scrolling to make the last item visible scroll far enough to see the padding.
float decoration_up_height = window->TitleBarHeight() + window->MenuBarHeight();
float cr_y = window->ScrollTargetCenterRatio.y;
float target_y = window->ScrollTarget.y;
if (snap_on_edges && cr_y <= 0.0f && target_y <= window->WindowPadding.y)
target_y = 0.0f;
if (snap_on_edges && cr_y >= 1.0f && target_y >= window->ContentSize.y + window->WindowPadding.y + g.Style.ItemSpacing.y)
target_y = window->ContentSize.y + window->WindowPadding.y * 2.0f;
scroll.y = target_y - cr_y * (window->SizeFull.y - window->ScrollbarSizes.y - decoration_up_height);
}
scroll = ImMax(scroll, ImVec2(0.0f, 0.0f));
if (!window->Collapsed && !window->SkipItems)
{
scroll.x = ImMin(scroll.x, window->ScrollMax.x);
scroll.y = ImMin(scroll.y, window->ScrollMax.y);
}
return scroll;
}
// Scroll to keep newly navigated item fully into view
ImVec2 ImGui::ScrollToBringRectIntoView(ImGuiWindow* window, const ImRect& item_rect)
{
ImGuiContext& g = *GImGui;
ImRect window_rect(window->InnerRect.Min - ImVec2(1, 1), window->InnerRect.Max + ImVec2(1, 1));
//GetForegroundDrawList(window)->AddRect(window_rect.Min, window_rect.Max, IM_COL32_WHITE); // [DEBUG]
ImVec2 delta_scroll;
if (!window_rect.Contains(item_rect))
{
if (window->ScrollbarX && item_rect.Min.x < window_rect.Min.x)
SetScrollFromPosX(window, item_rect.Min.x - window->Pos.x + g.Style.ItemSpacing.x, 0.0f);
else if (window->ScrollbarX && item_rect.Max.x >= window_rect.Max.x)
SetScrollFromPosX(window, item_rect.Max.x - window->Pos.x + g.Style.ItemSpacing.x, 1.0f);
if (item_rect.Min.y < window_rect.Min.y)
SetScrollFromPosY(window, item_rect.Min.y - window->Pos.y - g.Style.ItemSpacing.y, 0.0f);
else if (item_rect.Max.y >= window_rect.Max.y)
SetScrollFromPosY(window, item_rect.Max.y - window->Pos.y + g.Style.ItemSpacing.y, 1.0f);
ImVec2 next_scroll = CalcNextScrollFromScrollTargetAndClamp(window, false);
delta_scroll = next_scroll - window->Scroll;
}
// Also scroll parent window to keep us into view if necessary
if (window->Flags & ImGuiWindowFlags_ChildWindow)
delta_scroll += ScrollToBringRectIntoView(window->ParentWindow, ImRect(item_rect.Min - delta_scroll, item_rect.Max - delta_scroll));
return delta_scroll;
}
float ImGui::GetScrollX()
{
ImGuiWindow* window = GImGui->CurrentWindow;
return window->Scroll.x;
}
float ImGui::GetScrollY()
{
ImGuiWindow* window = GImGui->CurrentWindow;
return window->Scroll.y;
}
float ImGui::GetScrollMaxX()
{
ImGuiWindow* window = GImGui->CurrentWindow;
return window->ScrollMax.x;
}
float ImGui::GetScrollMaxY()
{
ImGuiWindow* window = GImGui->CurrentWindow;
return window->ScrollMax.y;
}
void ImGui::SetScrollX(float scroll_x)
{
ImGuiWindow* window = GetCurrentWindow();
window->ScrollTarget.x = scroll_x;
window->ScrollTargetCenterRatio.x = 0.0f;
}
void ImGui::SetScrollY(float scroll_y)
{
ImGuiWindow* window = GetCurrentWindow();
window->ScrollTarget.y = scroll_y;
window->ScrollTargetCenterRatio.y = 0.0f;
}
void ImGui::SetScrollX(ImGuiWindow* window, float new_scroll_x)
{
window->ScrollTarget.x = new_scroll_x;
window->ScrollTargetCenterRatio.x = 0.0f;
}
void ImGui::SetScrollY(ImGuiWindow* window, float new_scroll_y)
{
window->ScrollTarget.y = new_scroll_y;
window->ScrollTargetCenterRatio.y = 0.0f;
}
void ImGui::SetScrollFromPosX(ImGuiWindow* window, float local_x, float center_x_ratio)
{
// We store a target position so centering can occur on the next frame when we are guaranteed to have a known window size
IM_ASSERT(center_x_ratio >= 0.0f && center_x_ratio <= 1.0f);
window->ScrollTarget.x = IM_FLOOR(local_x + window->Scroll.x);
window->ScrollTargetCenterRatio.x = center_x_ratio;
}
void ImGui::SetScrollFromPosY(ImGuiWindow* window, float local_y, float center_y_ratio)
{
// We store a target position so centering can occur on the next frame when we are guaranteed to have a known window size
IM_ASSERT(center_y_ratio >= 0.0f && center_y_ratio <= 1.0f);
const float decoration_up_height = window->TitleBarHeight() + window->MenuBarHeight();
local_y -= decoration_up_height;
window->ScrollTarget.y = IM_FLOOR(local_y + window->Scroll.y);
window->ScrollTargetCenterRatio.y = center_y_ratio;
}
void ImGui::SetScrollFromPosX(float local_x, float center_x_ratio)
{
ImGuiContext& g = *GImGui;
SetScrollFromPosX(g.CurrentWindow, local_x, center_x_ratio);
}
void ImGui::SetScrollFromPosY(float local_y, float center_y_ratio)
{
ImGuiContext& g = *GImGui;
SetScrollFromPosY(g.CurrentWindow, local_y, center_y_ratio);
}
// center_x_ratio: 0.0f left of last item, 0.5f horizontal center of last item, 1.0f right of last item.
void ImGui::SetScrollHereX(float center_x_ratio)
{
ImGuiContext& g = *GImGui;
ImGuiWindow* window = g.CurrentWindow;
float target_x = window->DC.LastItemRect.Min.x - window->Pos.x; // Left of last item, in window space
float last_item_width = window->DC.LastItemRect.GetWidth();
target_x += (last_item_width * center_x_ratio) + (g.Style.ItemSpacing.x * (center_x_ratio - 0.5f) * 2.0f); // Precisely aim before, in the middle or after the last item.
SetScrollFromPosX(target_x, center_x_ratio);
}
// center_y_ratio: 0.0f top of last item, 0.5f vertical center of last item, 1.0f bottom of last item.
void ImGui::SetScrollHereY(float center_y_ratio)
{
ImGuiContext& g = *GImGui;
ImGuiWindow* window = g.CurrentWindow;
float target_y = window->DC.CursorPosPrevLine.y - window->Pos.y; // Top of last item, in window space
target_y += (window->DC.PrevLineSize.y * center_y_ratio) + (g.Style.ItemSpacing.y * (center_y_ratio - 0.5f) * 2.0f); // Precisely aim above, in the middle or below the last line.
SetScrollFromPosY(target_y, center_y_ratio);
}
//-----------------------------------------------------------------------------
// [SECTION] TOOLTIPS
//-----------------------------------------------------------------------------
void ImGui::BeginTooltip()
{
BeginTooltipEx(ImGuiWindowFlags_None, ImGuiTooltipFlags_None);
}
void ImGui::BeginTooltipEx(ImGuiWindowFlags extra_flags, ImGuiTooltipFlags tooltip_flags)
{
ImGuiContext& g = *GImGui;
if (g.DragDropWithinSource || g.DragDropWithinTarget)
{
// The default tooltip position is a little offset to give space to see the context menu (it's also clamped within the current viewport/monitor)
// In the context of a dragging tooltip we try to reduce that offset and we enforce following the cursor.
// Whatever we do we want to call SetNextWindowPos() to enforce a tooltip position and disable clipping the tooltip without our display area, like regular tooltip do.
//ImVec2 tooltip_pos = g.IO.MousePos - g.ActiveIdClickOffset - g.Style.WindowPadding;
ImVec2 tooltip_pos = g.IO.MousePos + ImVec2(16 * g.Style.MouseCursorScale, 8 * g.Style.MouseCursorScale);
SetNextWindowPos(tooltip_pos);
SetNextWindowBgAlpha(g.Style.Colors[ImGuiCol_PopupBg].w * 0.60f);
//PushStyleVar(ImGuiStyleVar_Alpha, g.Style.Alpha * 0.60f); // This would be nice but e.g ColorButton with checkboard has issue with transparent colors :(
tooltip_flags |= ImGuiTooltipFlags_OverridePreviousTooltip;
}
char window_name[16];
ImFormatString(window_name, IM_ARRAYSIZE(window_name), "##Tooltip_%02d", g.TooltipOverrideCount);
if (tooltip_flags & ImGuiTooltipFlags_OverridePreviousTooltip)
if (ImGuiWindow* window = FindWindowByName(window_name))
if (window->Active)
{
// Hide previous tooltip from being displayed. We can't easily "reset" the content of a window so we create a new one.
window->Hidden = true;
window->HiddenFramesCanSkipItems = 1;
ImFormatString(window_name, IM_ARRAYSIZE(window_name), "##Tooltip_%02d", ++g.TooltipOverrideCount);
}
ImGuiWindowFlags flags = ImGuiWindowFlags_Tooltip|ImGuiWindowFlags_NoInputs|ImGuiWindowFlags_NoTitleBar|ImGuiWindowFlags_NoMove|ImGuiWindowFlags_NoResize|ImGuiWindowFlags_NoSavedSettings|ImGuiWindowFlags_AlwaysAutoResize;
Begin(window_name, NULL, flags | extra_flags);
}
void ImGui::EndTooltip()
{
IM_ASSERT(GetCurrentWindowRead()->Flags & ImGuiWindowFlags_Tooltip); // Mismatched BeginTooltip()/EndTooltip() calls
End();
}
void ImGui::SetTooltipV(const char* fmt, va_list args)
{
BeginTooltipEx(0, ImGuiTooltipFlags_OverridePreviousTooltip);
TextV(fmt, args);
EndTooltip();
}
void ImGui::SetTooltip(const char* fmt, ...)
{
va_list args;
va_start(args, fmt);
SetTooltipV(fmt, args);
va_end(args);
}
//-----------------------------------------------------------------------------
// [SECTION] POPUPS
//-----------------------------------------------------------------------------
bool ImGui::IsPopupOpen(ImGuiID id)
{
ImGuiContext& g = *GImGui;
return g.OpenPopupStack.Size > g.BeginPopupStack.Size && g.OpenPopupStack[g.BeginPopupStack.Size].PopupId == id;
}
bool ImGui::IsPopupOpen(const char* str_id)
{
ImGuiContext& g = *GImGui;
return g.OpenPopupStack.Size > g.BeginPopupStack.Size && g.OpenPopupStack[g.BeginPopupStack.Size].PopupId == g.CurrentWindow->GetID(str_id);
}
ImGuiWindow* ImGui::GetTopMostPopupModal()
{
ImGuiContext& g = *GImGui;
for (int n = g.OpenPopupStack.Size-1; n >= 0; n--)
if (ImGuiWindow* popup = g.OpenPopupStack.Data[n].Window)
if (popup->Flags & ImGuiWindowFlags_Modal)
return popup;
return NULL;
}
void ImGui::OpenPopup(const char* str_id)
{
ImGuiContext& g = *GImGui;
OpenPopupEx(g.CurrentWindow->GetID(str_id));
}
// Mark popup as open (toggle toward open state).
// Popups are closed when user click outside, or activate a pressable item, or CloseCurrentPopup() is called within a BeginPopup()/EndPopup() block.
// Popup identifiers are relative to the current ID-stack (so OpenPopup and BeginPopup needs to be at the same level).
// One open popup per level of the popup hierarchy (NB: when assigning we reset the Window member of ImGuiPopupRef to NULL)
void ImGui::OpenPopupEx(ImGuiID id)
{
ImGuiContext& g = *GImGui;
ImGuiWindow* parent_window = g.CurrentWindow;
int current_stack_size = g.BeginPopupStack.Size;
ImGuiPopupData popup_ref; // Tagged as new ref as Window will be set back to NULL if we write this into OpenPopupStack.
popup_ref.PopupId = id;
popup_ref.Window = NULL;
popup_ref.SourceWindow = g.NavWindow;
popup_ref.OpenFrameCount = g.FrameCount;
popup_ref.OpenParentId = parent_window->IDStack.back();
popup_ref.OpenPopupPos = NavCalcPreferredRefPos();
popup_ref.OpenMousePos = IsMousePosValid(&g.IO.MousePos) ? g.IO.MousePos : popup_ref.OpenPopupPos;
//IMGUI_DEBUG_LOG("OpenPopupEx(0x%08X)\n", g.FrameCount, id);
if (g.OpenPopupStack.Size < current_stack_size + 1)
{
g.OpenPopupStack.push_back(popup_ref);
}
else
{
// Gently handle the user mistakenly calling OpenPopup() every frame. It is a programming mistake! However, if we were to run the regular code path, the ui
// would become completely unusable because the popup will always be in hidden-while-calculating-size state _while_ claiming focus. Which would be a very confusing
// situation for the programmer. Instead, we silently allow the popup to proceed, it will keep reappearing and the programming error will be more obvious to understand.
if (g.OpenPopupStack[current_stack_size].PopupId == id && g.OpenPopupStack[current_stack_size].OpenFrameCount == g.FrameCount - 1)
{
g.OpenPopupStack[current_stack_size].OpenFrameCount = popup_ref.OpenFrameCount;
}
else
{
// Close child popups if any, then flag popup for open/reopen
g.OpenPopupStack.resize(current_stack_size + 1);
g.OpenPopupStack[current_stack_size] = popup_ref;
}
// When reopening a popup we first refocus its parent, otherwise if its parent is itself a popup it would get closed by ClosePopupsOverWindow().
// This is equivalent to what ClosePopupToLevel() does.
//if (g.OpenPopupStack[current_stack_size].PopupId == id)
// FocusWindow(parent_window);
}
}
void ImGui::ClosePopupsOverWindow(ImGuiWindow* ref_window, bool restore_focus_to_window_under_popup)
{
ImGuiContext& g = *GImGui;
if (g.OpenPopupStack.empty())
return;
// When popups are stacked, clicking on a lower level popups puts focus back to it and close popups above it.
// Don't close our own child popup windows.
int popup_count_to_keep = 0;
if (ref_window)
{
// Find the highest popup which is a descendant of the reference window (generally reference window = NavWindow)
for (; popup_count_to_keep < g.OpenPopupStack.Size; popup_count_to_keep++)
{
ImGuiPopupData& popup = g.OpenPopupStack[popup_count_to_keep];
if (!popup.Window)
continue;
IM_ASSERT((popup.Window->Flags & ImGuiWindowFlags_Popup) != 0);
if (popup.Window->Flags & ImGuiWindowFlags_ChildWindow)
continue;
// Trim the stack when popups are not direct descendant of the reference window (the reference window is often the NavWindow)
bool popup_or_descendent_is_ref_window = false;
for (int m = popup_count_to_keep; m < g.OpenPopupStack.Size && !popup_or_descendent_is_ref_window; m++)
if (ImGuiWindow* popup_window = g.OpenPopupStack[m].Window)
if (popup_window->RootWindow == ref_window->RootWindow)
popup_or_descendent_is_ref_window = true;
if (!popup_or_descendent_is_ref_window)
break;
}
}
if (popup_count_to_keep < g.OpenPopupStack.Size) // This test is not required but it allows to set a convenient breakpoint on the statement below
{
//IMGUI_DEBUG_LOG("ClosePopupsOverWindow(%s) -> ClosePopupToLevel(%d)\n", ref_window->Name, popup_count_to_keep);
ClosePopupToLevel(popup_count_to_keep, restore_focus_to_window_under_popup);
}
}
void ImGui::ClosePopupToLevel(int remaining, bool restore_focus_to_window_under_popup)
{
ImGuiContext& g = *GImGui;
IM_ASSERT(remaining >= 0 && remaining < g.OpenPopupStack.Size);
ImGuiWindow* focus_window = g.OpenPopupStack[remaining].SourceWindow;
ImGuiWindow* popup_window = g.OpenPopupStack[remaining].Window;
g.OpenPopupStack.resize(remaining);
if (restore_focus_to_window_under_popup)
{
if (focus_window && !focus_window->WasActive && popup_window)
{
// Fallback
FocusTopMostWindowUnderOne(popup_window, NULL);
}
else
{
if (g.NavLayer == 0 && focus_window)
focus_window = NavRestoreLastChildNavWindow(focus_window);
FocusWindow(focus_window);
}
}
}
// Close the popup we have begin-ed into.
void ImGui::CloseCurrentPopup()
{
ImGuiContext& g = *GImGui;
int popup_idx = g.BeginPopupStack.Size - 1;
if (popup_idx < 0 || popup_idx >= g.OpenPopupStack.Size || g.BeginPopupStack[popup_idx].PopupId != g.OpenPopupStack[popup_idx].PopupId)
return;
// Closing a menu closes its top-most parent popup (unless a modal)
while (popup_idx > 0)
{
ImGuiWindow* popup_window = g.OpenPopupStack[popup_idx].Window;
ImGuiWindow* parent_popup_window = g.OpenPopupStack[popup_idx - 1].Window;
bool close_parent = false;
if (popup_window && (popup_window->Flags & ImGuiWindowFlags_ChildMenu))
if (parent_popup_window == NULL || !(parent_popup_window->Flags & ImGuiWindowFlags_Modal))
close_parent = true;
if (!close_parent)
break;
popup_idx--;
}
//IMGUI_DEBUG_LOG("CloseCurrentPopup %d -> %d\n", g.BeginPopupStack.Size - 1, popup_idx);
ClosePopupToLevel(popup_idx, true);
// A common pattern is to close a popup when selecting a menu item/selectable that will open another window.
// To improve this usage pattern, we avoid nav highlight for a single frame in the parent window.
// Similarly, we could avoid mouse hover highlight in this window but it is less visually problematic.
if (ImGuiWindow* window = g.NavWindow)
window->DC.NavHideHighlightOneFrame = true;
}
bool ImGui::BeginPopupEx(ImGuiID id, ImGuiWindowFlags flags)
{
ImGuiContext& g = *GImGui;
if (!IsPopupOpen(id))
{
g.NextWindowData.ClearFlags(); // We behave like Begin() and need to consume those values
return false;
}
char name[20];
if (flags & ImGuiWindowFlags_ChildMenu)
ImFormatString(name, IM_ARRAYSIZE(name), "##Menu_%02d", g.BeginPopupStack.Size); // Recycle windows based on depth
else
ImFormatString(name, IM_ARRAYSIZE(name), "##Popup_%08x", id); // Not recycling, so we can close/open during the same frame
flags |= ImGuiWindowFlags_Popup;
bool is_open = Begin(name, NULL, flags);
if (!is_open) // NB: Begin can return false when the popup is completely clipped (e.g. zero size display)
EndPopup();
return is_open;
}
bool ImGui::BeginPopup(const char* str_id, ImGuiWindowFlags flags)
{
ImGuiContext& g = *GImGui;
if (g.OpenPopupStack.Size <= g.BeginPopupStack.Size) // Early out for performance
{
g.NextWindowData.ClearFlags(); // We behave like Begin() and need to consume those values
return false;
}
flags |= ImGuiWindowFlags_AlwaysAutoResize | ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoSavedSettings;
return BeginPopupEx(g.CurrentWindow->GetID(str_id), flags);
}
// If 'p_open' is specified for a modal popup window, the popup will have a regular close button which will close the popup.
// Note that popup visibility status is owned by Dear ImGui (and manipulated with e.g. OpenPopup) so the actual value of *p_open is meaningless here.
bool ImGui::BeginPopupModal(const char* name, bool* p_open, ImGuiWindowFlags flags)
{
ImGuiContext& g = *GImGui;
ImGuiWindow* window = g.CurrentWindow;
const ImGuiID id = window->GetID(name);
if (!IsPopupOpen(id))
{
g.NextWindowData.ClearFlags(); // We behave like Begin() and need to consume those values
return false;
}
// Center modal windows by default
// FIXME: Should test for (PosCond & window->SetWindowPosAllowFlags) with the upcoming window.
if ((g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasPos) == 0)
SetNextWindowPos(g.IO.DisplaySize * 0.5f, ImGuiCond_Appearing, ImVec2(0.5f, 0.5f));
flags |= ImGuiWindowFlags_Popup | ImGuiWindowFlags_Modal | ImGuiWindowFlags_NoCollapse | ImGuiWindowFlags_NoSavedSettings;
const bool is_open = Begin(name, p_open, flags);
if (!is_open || (p_open && !*p_open)) // NB: is_open can be 'false' when the popup is completely clipped (e.g. zero size display)
{
EndPopup();
if (is_open)
ClosePopupToLevel(g.BeginPopupStack.Size, true);
return false;
}
return is_open;
}
void ImGui::EndPopup()
{
ImGuiContext& g = *GImGui;
ImGuiWindow* window = g.CurrentWindow;
IM_ASSERT(window->Flags & ImGuiWindowFlags_Popup); // Mismatched BeginPopup()/EndPopup() calls
IM_ASSERT(g.BeginPopupStack.Size > 0);
// Make all menus and popups wrap around for now, may need to expose that policy.
NavMoveRequestTryWrapping(window, ImGuiNavMoveFlags_LoopY);
// Child-popups don't need to be layed out
IM_ASSERT(g.WithinEndChild == false);
if (window->Flags & ImGuiWindowFlags_ChildWindow)
g.WithinEndChild = true;
End();
g.WithinEndChild = false;
}
bool ImGui::OpenPopupOnItemClick(const char* str_id, ImGuiMouseButton mouse_button)
{
ImGuiWindow* window = GImGui->CurrentWindow;
if (IsMouseReleased(mouse_button) && IsItemHovered(ImGuiHoveredFlags_AllowWhenBlockedByPopup))
{
ImGuiID id = str_id ? window->GetID(str_id) : window->DC.LastItemId; // If user hasn't passed an ID, we can use the LastItemID. Using LastItemID as a Popup ID won't conflict!
IM_ASSERT(id != 0); // You cannot pass a NULL str_id if the last item has no identifier (e.g. a Text() item)
OpenPopupEx(id);
return true;
}
return false;
}
// This is a helper to handle the simplest case of associating one named popup to one given widget.
// You may want to handle this on user side if you have specific needs (e.g. tweaking IsItemHovered() parameters).
// You can pass a NULL str_id to use the identifier of the last item.
bool ImGui::BeginPopupContextItem(const char* str_id, ImGuiMouseButton mouse_button)
{
ImGuiWindow* window = GImGui->CurrentWindow;
if (window->SkipItems)
return false;
ImGuiID id = str_id ? window->GetID(str_id) : window->DC.LastItemId; // If user hasn't passed an ID, we can use the LastItemID. Using LastItemID as a Popup ID won't conflict!
IM_ASSERT(id != 0); // You cannot pass a NULL str_id if the last item has no identifier (e.g. a Text() item)
if (IsMouseReleased(mouse_button) && IsItemHovered(ImGuiHoveredFlags_AllowWhenBlockedByPopup))
OpenPopupEx(id);
return BeginPopupEx(id, ImGuiWindowFlags_AlwaysAutoResize|ImGuiWindowFlags_NoTitleBar|ImGuiWindowFlags_NoSavedSettings);
}
bool ImGui::BeginPopupContextWindow(const char* str_id, ImGuiMouseButton mouse_button, bool also_over_items)
{
if (!str_id)
str_id = "window_context";
ImGuiID id = GImGui->CurrentWindow->GetID(str_id);
if (IsMouseReleased(mouse_button) && IsWindowHovered(ImGuiHoveredFlags_AllowWhenBlockedByPopup))
if (also_over_items || !IsAnyItemHovered())
OpenPopupEx(id);
return BeginPopupEx(id, ImGuiWindowFlags_AlwaysAutoResize|ImGuiWindowFlags_NoTitleBar|ImGuiWindowFlags_NoSavedSettings);
}
bool ImGui::BeginPopupContextVoid(const char* str_id, ImGuiMouseButton mouse_button)
{
if (!str_id)
str_id = "void_context";
ImGuiID id = GImGui->CurrentWindow->GetID(str_id);
if (IsMouseReleased(mouse_button) && !IsWindowHovered(ImGuiHoveredFlags_AnyWindow))
OpenPopupEx(id);
return BeginPopupEx(id, ImGuiWindowFlags_AlwaysAutoResize|ImGuiWindowFlags_NoTitleBar|ImGuiWindowFlags_NoSavedSettings);
}
// r_avoid = the rectangle to avoid (e.g. for tooltip it is a rectangle around the mouse cursor which we want to avoid. for popups it's a small point around the cursor.)
// r_outer = the visible area rectangle, minus safe area padding. If our popup size won't fit because of safe area padding we ignore it.
ImVec2 ImGui::FindBestWindowPosForPopupEx(const ImVec2& ref_pos, const ImVec2& size, ImGuiDir* last_dir, const ImRect& r_outer, const ImRect& r_avoid, ImGuiPopupPositionPolicy policy)
{
ImVec2 base_pos_clamped = ImClamp(ref_pos, r_outer.Min, r_outer.Max - size);
//GetForegroundDrawList()->AddRect(r_avoid.Min, r_avoid.Max, IM_COL32(255,0,0,255));
//GetForegroundDrawList()->AddRect(r_outer.Min, r_outer.Max, IM_COL32(0,255,0,255));
// Combo Box policy (we want a connecting edge)
if (policy == ImGuiPopupPositionPolicy_ComboBox)
{
const ImGuiDir dir_prefered_order[ImGuiDir_COUNT] = { ImGuiDir_Down, ImGuiDir_Right, ImGuiDir_Left, ImGuiDir_Up };
for (int n = (*last_dir != ImGuiDir_None) ? -1 : 0; n < ImGuiDir_COUNT; n++)
{
const ImGuiDir dir = (n == -1) ? *last_dir : dir_prefered_order[n];
if (n != -1 && dir == *last_dir) // Already tried this direction?
continue;
ImVec2 pos;
if (dir == ImGuiDir_Down) pos = ImVec2(r_avoid.Min.x, r_avoid.Max.y); // Below, Toward Right (default)
if (dir == ImGuiDir_Right) pos = ImVec2(r_avoid.Min.x, r_avoid.Min.y - size.y); // Above, Toward Right
if (dir == ImGuiDir_Left) pos = ImVec2(r_avoid.Max.x - size.x, r_avoid.Max.y); // Below, Toward Left
if (dir == ImGuiDir_Up) pos = ImVec2(r_avoid.Max.x - size.x, r_avoid.Min.y - size.y); // Above, Toward Left
if (!r_outer.Contains(ImRect(pos, pos + size)))
continue;
*last_dir = dir;
return pos;
}
}
// Default popup policy
const ImGuiDir dir_prefered_order[ImGuiDir_COUNT] = { ImGuiDir_Right, ImGuiDir_Down, ImGuiDir_Up, ImGuiDir_Left };
for (int n = (*last_dir != ImGuiDir_None) ? -1 : 0; n < ImGuiDir_COUNT; n++)
{
const ImGuiDir dir = (n == -1) ? *last_dir : dir_prefered_order[n];
if (n != -1 && dir == *last_dir) // Already tried this direction?
continue;
float avail_w = (dir == ImGuiDir_Left ? r_avoid.Min.x : r_outer.Max.x) - (dir == ImGuiDir_Right ? r_avoid.Max.x : r_outer.Min.x);
float avail_h = (dir == ImGuiDir_Up ? r_avoid.Min.y : r_outer.Max.y) - (dir == ImGuiDir_Down ? r_avoid.Max.y : r_outer.Min.y);
if (avail_w < size.x || avail_h < size.y)
continue;
ImVec2 pos;
pos.x = (dir == ImGuiDir_Left) ? r_avoid.Min.x - size.x : (dir == ImGuiDir_Right) ? r_avoid.Max.x : base_pos_clamped.x;
pos.y = (dir == ImGuiDir_Up) ? r_avoid.Min.y - size.y : (dir == ImGuiDir_Down) ? r_avoid.Max.y : base_pos_clamped.y;
*last_dir = dir;
return pos;
}
// Fallback, try to keep within display
*last_dir = ImGuiDir_None;
ImVec2 pos = ref_pos;
pos.x = ImMax(ImMin(pos.x + size.x, r_outer.Max.x) - size.x, r_outer.Min.x);
pos.y = ImMax(ImMin(pos.y + size.y, r_outer.Max.y) - size.y, r_outer.Min.y);
return pos;
}
ImRect ImGui::GetWindowAllowedExtentRect(ImGuiWindow* window)
{
IM_UNUSED(window);
ImVec2 padding = GImGui->Style.DisplaySafeAreaPadding;
ImRect r_screen = GetViewportRect();
r_screen.Expand(ImVec2((r_screen.GetWidth() > padding.x * 2) ? -padding.x : 0.0f, (r_screen.GetHeight() > padding.y * 2) ? -padding.y : 0.0f));
return r_screen;
}
ImVec2 ImGui::FindBestWindowPosForPopup(ImGuiWindow* window)
{
ImGuiContext& g = *GImGui;
ImRect r_outer = GetWindowAllowedExtentRect(window);
if (window->Flags & ImGuiWindowFlags_ChildMenu)
{
// Child menus typically request _any_ position within the parent menu item, and then we move the new menu outside the parent bounds.
// This is how we end up with child menus appearing (most-commonly) on the right of the parent menu.
IM_ASSERT(g.CurrentWindow == window);
ImGuiWindow* parent_window = g.CurrentWindowStack[g.CurrentWindowStack.Size - 2];
float horizontal_overlap = g.Style.ItemInnerSpacing.x; // We want some overlap to convey the relative depth of each menu (currently the amount of overlap is hard-coded to style.ItemSpacing.x).
ImRect r_avoid;
if (parent_window->DC.MenuBarAppending)
r_avoid = ImRect(-FLT_MAX, parent_window->ClipRect.Min.y, FLT_MAX, parent_window->ClipRect.Max.y); // Avoid parent menu-bar. If we wanted multi-line menu-bar, we may instead want to have the calling window setup e.g. a NextWindowData.PosConstraintAvoidRect field
else
r_avoid = ImRect(parent_window->Pos.x + horizontal_overlap, -FLT_MAX, parent_window->Pos.x + parent_window->Size.x - horizontal_overlap - parent_window->ScrollbarSizes.x, FLT_MAX);
return FindBestWindowPosForPopupEx(window->Pos, window->Size, &window->AutoPosLastDirection, r_outer, r_avoid);
}
if (window->Flags & ImGuiWindowFlags_Popup)
{
ImRect r_avoid = ImRect(window->Pos.x - 1, window->Pos.y - 1, window->Pos.x + 1, window->Pos.y + 1);
return FindBestWindowPosForPopupEx(window->Pos, window->Size, &window->AutoPosLastDirection, r_outer, r_avoid);
}
if (window->Flags & ImGuiWindowFlags_Tooltip)
{
// Position tooltip (always follows mouse)
float sc = g.Style.MouseCursorScale;
ImVec2 ref_pos = NavCalcPreferredRefPos();
ImRect r_avoid;
if (!g.NavDisableHighlight && g.NavDisableMouseHover && !(g.IO.ConfigFlags & ImGuiConfigFlags_NavEnableSetMousePos))
r_avoid = ImRect(ref_pos.x - 16, ref_pos.y - 8, ref_pos.x + 16, ref_pos.y + 8);
else
r_avoid = ImRect(ref_pos.x - 16, ref_pos.y - 8, ref_pos.x + 24 * sc, ref_pos.y + 24 * sc); // FIXME: Hard-coded based on mouse cursor shape expectation. Exact dimension not very important.
ImVec2 pos = FindBestWindowPosForPopupEx(ref_pos, window->Size, &window->AutoPosLastDirection, r_outer, r_avoid);
if (window->AutoPosLastDirection == ImGuiDir_None)
pos = ref_pos + ImVec2(2, 2); // If there's not enough room, for tooltip we prefer avoiding the cursor at all cost even if it means that part of the tooltip won't be visible.
return pos;
}
IM_ASSERT(0);
return window->Pos;
}
//-----------------------------------------------------------------------------
// [SECTION] KEYBOARD/GAMEPAD NAVIGATION
//-----------------------------------------------------------------------------
// FIXME-NAV: The existence of SetNavID vs SetNavIDWithRectRel vs SetFocusID is incredibly messy and confusing,
// and needs some explanation or serious refactoring.
void ImGui::SetNavID(ImGuiID id, int nav_layer, ImGuiID focus_scope_id)
{
ImGuiContext& g = *GImGui;
IM_ASSERT(g.NavWindow);
IM_ASSERT(nav_layer == 0 || nav_layer == 1);
g.NavId = id;
g.NavFocusScopeId = focus_scope_id;
g.NavWindow->NavLastIds[nav_layer] = id;
}
void ImGui::SetNavIDWithRectRel(ImGuiID id, int nav_layer, ImGuiID focus_scope_id, const ImRect& rect_rel)
{
ImGuiContext& g = *GImGui;
SetNavID(id, nav_layer, focus_scope_id);
g.NavWindow->NavRectRel[nav_layer] = rect_rel;
g.NavMousePosDirty = true;
g.NavDisableHighlight = false;
g.NavDisableMouseHover = true;
}
void ImGui::SetFocusID(ImGuiID id, ImGuiWindow* window)
{
ImGuiContext& g = *GImGui;
IM_ASSERT(id != 0);
// Assume that SetFocusID() is called in the context where its window->DC.NavLayerCurrent and window->DC.NavFocusScopeIdCurrent are valid.
// Note that window may be != g.CurrentWindow (e.g. SetFocusID call in InputTextEx for multi-line text)
const ImGuiNavLayer nav_layer = window->DC.NavLayerCurrent;
if (g.NavWindow != window)
g.NavInitRequest = false;
g.NavWindow = window;
g.NavId = id;
g.NavLayer = nav_layer;
g.NavFocusScopeId = window->DC.NavFocusScopeIdCurrent;
window->NavLastIds[nav_layer] = id;
if (window->DC.LastItemId == id)
window->NavRectRel[nav_layer] = ImRect(window->DC.LastItemRect.Min - window->Pos, window->DC.LastItemRect.Max - window->Pos);
if (g.ActiveIdSource == ImGuiInputSource_Nav)
g.NavDisableMouseHover = true;
else
g.NavDisableHighlight = true;
}
ImGuiDir ImGetDirQuadrantFromDelta(float dx, float dy)
{
if (ImFabs(dx) > ImFabs(dy))
return (dx > 0.0f) ? ImGuiDir_Right : ImGuiDir_Left;
return (dy > 0.0f) ? ImGuiDir_Down : ImGuiDir_Up;
}
static float inline NavScoreItemDistInterval(float a0, float a1, float b0, float b1)
{
if (a1 < b0)
return a1 - b0;
if (b1 < a0)
return a0 - b1;
return 0.0f;
}
static void inline NavClampRectToVisibleAreaForMoveDir(ImGuiDir move_dir, ImRect& r, const ImRect& clip_rect)
{
if (move_dir == ImGuiDir_Left || move_dir == ImGuiDir_Right)
{
r.Min.y = ImClamp(r.Min.y, clip_rect.Min.y, clip_rect.Max.y);
r.Max.y = ImClamp(r.Max.y, clip_rect.Min.y, clip_rect.Max.y);
}
else
{
r.Min.x = ImClamp(r.Min.x, clip_rect.Min.x, clip_rect.Max.x);
r.Max.x = ImClamp(r.Max.x, clip_rect.Min.x, clip_rect.Max.x);
}
}
// Scoring function for directional navigation. Based on https://gist.github.com/rygorous/6981057
static bool ImGui::NavScoreItem(ImGuiNavMoveResult* result, ImRect cand)
{
ImGuiContext& g = *GImGui;
ImGuiWindow* window = g.CurrentWindow;
if (g.NavLayer != window->DC.NavLayerCurrent)
return false;
const ImRect& curr = g.NavScoringRectScreen; // Current modified source rect (NB: we've applied Max.x = Min.x in NavUpdate() to inhibit the effect of having varied item width)
g.NavScoringCount++;
// When entering through a NavFlattened border, we consider child window items as fully clipped for scoring
if (window->ParentWindow == g.NavWindow)
{
IM_ASSERT((window->Flags | g.NavWindow->Flags) & ImGuiWindowFlags_NavFlattened);
if (!window->ClipRect.Overlaps(cand))
return false;
cand.ClipWithFull(window->ClipRect); // This allows the scored item to not overlap other candidates in the parent window
}
// We perform scoring on items bounding box clipped by the current clipping rectangle on the other axis (clipping on our movement axis would give us equal scores for all clipped items)
// For example, this ensure that items in one column are not reached when moving vertically from items in another column.
NavClampRectToVisibleAreaForMoveDir(g.NavMoveClipDir, cand, window->ClipRect);
// Compute distance between boxes
// FIXME-NAV: Introducing biases for vertical navigation, needs to be removed.
float dbx = NavScoreItemDistInterval(cand.Min.x, cand.Max.x, curr.Min.x, curr.Max.x);
float dby = NavScoreItemDistInterval(ImLerp(cand.Min.y, cand.Max.y, 0.2f), ImLerp(cand.Min.y, cand.Max.y, 0.8f), ImLerp(curr.Min.y, curr.Max.y, 0.2f), ImLerp(curr.Min.y, curr.Max.y, 0.8f)); // Scale down on Y to keep using box-distance for vertically touching items
if (dby != 0.0f && dbx != 0.0f)
dbx = (dbx/1000.0f) + ((dbx > 0.0f) ? +1.0f : -1.0f);
float dist_box = ImFabs(dbx) + ImFabs(dby);
// Compute distance between centers (this is off by a factor of 2, but we only compare center distances with each other so it doesn't matter)
float dcx = (cand.Min.x + cand.Max.x) - (curr.Min.x + curr.Max.x);
float dcy = (cand.Min.y + cand.Max.y) - (curr.Min.y + curr.Max.y);
float dist_center = ImFabs(dcx) + ImFabs(dcy); // L1 metric (need this for our connectedness guarantee)
// Determine which quadrant of 'curr' our candidate item 'cand' lies in based on distance
ImGuiDir quadrant;
float dax = 0.0f, day = 0.0f, dist_axial = 0.0f;
if (dbx != 0.0f || dby != 0.0f)
{
// For non-overlapping boxes, use distance between boxes
dax = dbx;
day = dby;
dist_axial = dist_box;
quadrant = ImGetDirQuadrantFromDelta(dbx, dby);
}
else if (dcx != 0.0f || dcy != 0.0f)
{
// For overlapping boxes with different centers, use distance between centers
dax = dcx;
day = dcy;
dist_axial = dist_center;
quadrant = ImGetDirQuadrantFromDelta(dcx, dcy);
}
else
{
// Degenerate case: two overlapping buttons with same center, break ties arbitrarily (note that LastItemId here is really the _previous_ item order, but it doesn't matter)
quadrant = (window->DC.LastItemId < g.NavId) ? ImGuiDir_Left : ImGuiDir_Right;
}
#if IMGUI_DEBUG_NAV_SCORING
char buf[128];
if (IsMouseHoveringRect(cand.Min, cand.Max))
{
ImFormatString(buf, IM_ARRAYSIZE(buf), "dbox (%.2f,%.2f->%.4f)\ndcen (%.2f,%.2f->%.4f)\nd (%.2f,%.2f->%.4f)\nnav %c, quadrant %c", dbx, dby, dist_box, dcx, dcy, dist_center, dax, day, dist_axial, "WENS"[g.NavMoveDir], "WENS"[quadrant]);
ImDrawList* draw_list = GetForegroundDrawList(window);
draw_list->AddRect(curr.Min, curr.Max, IM_COL32(255,200,0,100));
draw_list->AddRect(cand.Min, cand.Max, IM_COL32(255,255,0,200));
draw_list->AddRectFilled(cand.Max - ImVec2(4,4), cand.Max + CalcTextSize(buf) + ImVec2(4,4), IM_COL32(40,0,0,150));
draw_list->AddText(g.IO.FontDefault, 13.0f, cand.Max, ~0U, buf);
}
else if (g.IO.KeyCtrl) // Hold to preview score in matching quadrant. Press C to rotate.
{
if (IsKeyPressedMap(ImGuiKey_C)) { g.NavMoveDirLast = (ImGuiDir)((g.NavMoveDirLast + 1) & 3); g.IO.KeysDownDuration[g.IO.KeyMap[ImGuiKey_C]] = 0.01f; }
if (quadrant == g.NavMoveDir)
{
ImFormatString(buf, IM_ARRAYSIZE(buf), "%.0f/%.0f", dist_box, dist_center);
ImDrawList* draw_list = GetForegroundDrawList(window);
draw_list->AddRectFilled(cand.Min, cand.Max, IM_COL32(255, 0, 0, 200));
draw_list->AddText(g.IO.FontDefault, 13.0f, cand.Min, IM_COL32(255, 255, 255, 255), buf);
}
}
#endif
// Is it in the quadrant we're interesting in moving to?
bool new_best = false;
if (quadrant == g.NavMoveDir)
{
// Does it beat the current best candidate?
if (dist_box < result->DistBox)
{
result->DistBox = dist_box;
result->DistCenter = dist_center;
return true;
}
if (dist_box == result->DistBox)
{
// Try using distance between center points to break ties
if (dist_center < result->DistCenter)
{
result->DistCenter = dist_center;
new_best = true;
}
else if (dist_center == result->DistCenter)
{
// Still tied! we need to be extra-careful to make sure everything gets linked properly. We consistently break ties by symbolically moving "later" items
// (with higher index) to the right/downwards by an infinitesimal amount since we the current "best" button already (so it must have a lower index),
// this is fairly easy. This rule ensures that all buttons with dx==dy==0 will end up being linked in order of appearance along the x axis.
if (((g.NavMoveDir == ImGuiDir_Up || g.NavMoveDir == ImGuiDir_Down) ? dby : dbx) < 0.0f) // moving bj to the right/down decreases distance
new_best = true;
}
}
}
// Axial check: if 'curr' has no link at all in some direction and 'cand' lies roughly in that direction, add a tentative link. This will only be kept if no "real" matches
// are found, so it only augments the graph produced by the above method using extra links. (important, since it doesn't guarantee strong connectedness)
// This is just to avoid buttons having no links in a particular direction when there's a suitable neighbor. you get good graphs without this too.
// 2017/09/29: FIXME: This now currently only enabled inside menu bars, ideally we'd disable it everywhere. Menus in particular need to catch failure. For general navigation it feels awkward.
// Disabling it may lead to disconnected graphs when nodes are very spaced out on different axis. Perhaps consider offering this as an option?
if (result->DistBox == FLT_MAX && dist_axial < result->DistAxial) // Check axial match
if (g.NavLayer == 1 && !(g.NavWindow->Flags & ImGuiWindowFlags_ChildMenu))
if ((g.NavMoveDir == ImGuiDir_Left && dax < 0.0f) || (g.NavMoveDir == ImGuiDir_Right && dax > 0.0f) || (g.NavMoveDir == ImGuiDir_Up && day < 0.0f) || (g.NavMoveDir == ImGuiDir_Down && day > 0.0f))
{
result->DistAxial = dist_axial;
new_best = true;
}
return new_best;
}
// We get there when either NavId == id, or when g.NavAnyRequest is set (which is updated by NavUpdateAnyRequestFlag above)
static void ImGui::NavProcessItem(ImGuiWindow* window, const ImRect& nav_bb, const ImGuiID id)
{
ImGuiContext& g = *GImGui;
//if (!g.IO.NavActive) // [2017/10/06] Removed this possibly redundant test but I am not sure of all the side-effects yet. Some of the feature here will need to work regardless of using a _NoNavInputs flag.
// return;
const ImGuiItemFlags item_flags = window->DC.ItemFlags;
const ImRect nav_bb_rel(nav_bb.Min - window->Pos, nav_bb.Max - window->Pos);
// Process Init Request
if (g.NavInitRequest && g.NavLayer == window->DC.NavLayerCurrent)
{
// Even if 'ImGuiItemFlags_NoNavDefaultFocus' is on (typically collapse/close button) we record the first ResultId so they can be used as a fallback
if (!(item_flags & ImGuiItemFlags_NoNavDefaultFocus) || g.NavInitResultId == 0)
{
g.NavInitResultId = id;
g.NavInitResultRectRel = nav_bb_rel;
}
if (!(item_flags & ImGuiItemFlags_NoNavDefaultFocus))
{
g.NavInitRequest = false; // Found a match, clear request
NavUpdateAnyRequestFlag();
}
}
// Process Move Request (scoring for navigation)
// FIXME-NAV: Consider policy for double scoring (scoring from NavScoringRectScreen + scoring from a rect wrapped according to current wrapping policy)
if ((g.NavId != id || (g.NavMoveRequestFlags & ImGuiNavMoveFlags_AllowCurrentNavId)) && !(item_flags & (ImGuiItemFlags_Disabled|ImGuiItemFlags_NoNav)))
{
ImGuiNavMoveResult* result = (window == g.NavWindow) ? &g.NavMoveResultLocal : &g.NavMoveResultOther;
#if IMGUI_DEBUG_NAV_SCORING
// [DEBUG] Score all items in NavWindow at all times
if (!g.NavMoveRequest)
g.NavMoveDir = g.NavMoveDirLast;
bool new_best = NavScoreItem(result, nav_bb) && g.NavMoveRequest;
#else
bool new_best = g.NavMoveRequest && NavScoreItem(result, nav_bb);
#endif
if (new_best)
{
result->Window = window;
result->ID = id;
result->FocusScopeId = window->DC.NavFocusScopeIdCurrent;
result->RectRel = nav_bb_rel;
}
// Features like PageUp/PageDown need to maintain a separate score for the visible set of items.
const float VISIBLE_RATIO = 0.70f;
if ((g.NavMoveRequestFlags & ImGuiNavMoveFlags_AlsoScoreVisibleSet) && window->ClipRect.Overlaps(nav_bb))
if (ImClamp(nav_bb.Max.y, window->ClipRect.Min.y, window->ClipRect.Max.y) - ImClamp(nav_bb.Min.y, window->ClipRect.Min.y, window->ClipRect.Max.y) >= (nav_bb.Max.y - nav_bb.Min.y) * VISIBLE_RATIO)
if (NavScoreItem(&g.NavMoveResultLocalVisibleSet, nav_bb))
{
result = &g.NavMoveResultLocalVisibleSet;
result->Window = window;
result->ID = id;
result->FocusScopeId = window->DC.NavFocusScopeIdCurrent;
result->RectRel = nav_bb_rel;
}
}
// Update window-relative bounding box of navigated item
if (g.NavId == id)
{
g.NavWindow = window; // Always refresh g.NavWindow, because some operations such as FocusItem() don't have a window.
g.NavLayer = window->DC.NavLayerCurrent;
g.NavFocusScopeId = window->DC.NavFocusScopeIdCurrent;
g.NavIdIsAlive = true;
g.NavIdTabCounter = window->DC.FocusCounterTabStop;
window->NavRectRel[window->DC.NavLayerCurrent] = nav_bb_rel; // Store item bounding box (relative to window position)
}
}
bool ImGui::NavMoveRequestButNoResultYet()
{
ImGuiContext& g = *GImGui;
return g.NavMoveRequest && g.NavMoveResultLocal.ID == 0 && g.NavMoveResultOther.ID == 0;
}
void ImGui::NavMoveRequestCancel()
{
ImGuiContext& g = *GImGui;
g.NavMoveRequest = false;
NavUpdateAnyRequestFlag();
}
void ImGui::NavMoveRequestForward(ImGuiDir move_dir, ImGuiDir clip_dir, const ImRect& bb_rel, ImGuiNavMoveFlags move_flags)
{
ImGuiContext& g = *GImGui;
IM_ASSERT(g.NavMoveRequestForward == ImGuiNavForward_None);
NavMoveRequestCancel();
g.NavMoveDir = move_dir;
g.NavMoveClipDir = clip_dir;
g.NavMoveRequestForward = ImGuiNavForward_ForwardQueued;
g.NavMoveRequestFlags = move_flags;
g.NavWindow->NavRectRel[g.NavLayer] = bb_rel;
}
void ImGui::NavMoveRequestTryWrapping(ImGuiWindow* window, ImGuiNavMoveFlags move_flags)
{
ImGuiContext& g = *GImGui;
if (g.NavWindow != window || !NavMoveRequestButNoResultYet() || g.NavMoveRequestForward != ImGuiNavForward_None || g.NavLayer != 0)
return;
IM_ASSERT(move_flags != 0); // No points calling this with no wrapping
ImRect bb_rel = window->NavRectRel[0];
ImGuiDir clip_dir = g.NavMoveDir;
if (g.NavMoveDir == ImGuiDir_Left && (move_flags & (ImGuiNavMoveFlags_WrapX | ImGuiNavMoveFlags_LoopX)))
{
bb_rel.Min.x = bb_rel.Max.x = ImMax(window->SizeFull.x, window->ContentSize.x + window->WindowPadding.x * 2.0f) - window->Scroll.x;
if (move_flags & ImGuiNavMoveFlags_WrapX) { bb_rel.TranslateY(-bb_rel.GetHeight()); clip_dir = ImGuiDir_Up; }
NavMoveRequestForward(g.NavMoveDir, clip_dir, bb_rel, move_flags);
}
if (g.NavMoveDir == ImGuiDir_Right && (move_flags & (ImGuiNavMoveFlags_WrapX | ImGuiNavMoveFlags_LoopX)))
{
bb_rel.Min.x = bb_rel.Max.x = -window->Scroll.x;
if (move_flags & ImGuiNavMoveFlags_WrapX) { bb_rel.TranslateY(+bb_rel.GetHeight()); clip_dir = ImGuiDir_Down; }
NavMoveRequestForward(g.NavMoveDir, clip_dir, bb_rel, move_flags);
}
if (g.NavMoveDir == ImGuiDir_Up && (move_flags & (ImGuiNavMoveFlags_WrapY | ImGuiNavMoveFlags_LoopY)))
{
bb_rel.Min.y = bb_rel.Max.y = ImMax(window->SizeFull.y, window->ContentSize.y + window->WindowPadding.y * 2.0f) - window->Scroll.y;
if (move_flags & ImGuiNavMoveFlags_WrapY) { bb_rel.TranslateX(-bb_rel.GetWidth()); clip_dir = ImGuiDir_Left; }
NavMoveRequestForward(g.NavMoveDir, clip_dir, bb_rel, move_flags);
}
if (g.NavMoveDir == ImGuiDir_Down && (move_flags & (ImGuiNavMoveFlags_WrapY | ImGuiNavMoveFlags_LoopY)))
{
bb_rel.Min.y = bb_rel.Max.y = -window->Scroll.y;
if (move_flags & ImGuiNavMoveFlags_WrapY) { bb_rel.TranslateX(+bb_rel.GetWidth()); clip_dir = ImGuiDir_Right; }
NavMoveRequestForward(g.NavMoveDir, clip_dir, bb_rel, move_flags);
}
}
// FIXME: This could be replaced by updating a frame number in each window when (window == NavWindow) and (NavLayer == 0).
// This way we could find the last focused window among our children. It would be much less confusing this way?
static void ImGui::NavSaveLastChildNavWindowIntoParent(ImGuiWindow* nav_window)
{
ImGuiWindow* parent_window = nav_window;
while (parent_window && (parent_window->Flags & ImGuiWindowFlags_ChildWindow) != 0 && (parent_window->Flags & (ImGuiWindowFlags_Popup | ImGuiWindowFlags_ChildMenu)) == 0)
parent_window = parent_window->ParentWindow;
if (parent_window && parent_window != nav_window)
parent_window->NavLastChildNavWindow = nav_window;
}
// Restore the last focused child.
// Call when we are expected to land on the Main Layer (0) after FocusWindow()
static ImGuiWindow* ImGui::NavRestoreLastChildNavWindow(ImGuiWindow* window)
{
return window->NavLastChildNavWindow ? window->NavLastChildNavWindow : window;
}
static void NavRestoreLayer(ImGuiNavLayer layer)
{
ImGuiContext& g = *GImGui;
g.NavLayer = layer;
if (layer == 0)
g.NavWindow = ImGui::NavRestoreLastChildNavWindow(g.NavWindow);
ImGuiWindow* window = g.NavWindow;
if (layer == 0 && window->NavLastIds[0] != 0)
ImGui::SetNavIDWithRectRel(window->NavLastIds[0], layer, 0, window->NavRectRel[0]);
else
ImGui::NavInitWindow(window, true);
}
static inline void ImGui::NavUpdateAnyRequestFlag()
{
ImGuiContext& g = *GImGui;
g.NavAnyRequest = g.NavMoveRequest || g.NavInitRequest || (IMGUI_DEBUG_NAV_SCORING && g.NavWindow != NULL);
if (g.NavAnyRequest)
IM_ASSERT(g.NavWindow != NULL);
}
// This needs to be called before we submit any widget (aka in or before Begin)
void ImGui::NavInitWindow(ImGuiWindow* window, bool force_reinit)
{
ImGuiContext& g = *GImGui;
IM_ASSERT(window == g.NavWindow);
bool init_for_nav = false;
if (!(window->Flags & ImGuiWindowFlags_NoNavInputs))
if (!(window->Flags & ImGuiWindowFlags_ChildWindow) || (window->Flags & ImGuiWindowFlags_Popup) || (window->NavLastIds[0] == 0) || force_reinit)
init_for_nav = true;
//IMGUI_DEBUG_LOG("[Nav] NavInitWindow() init_for_nav=%d, window=\"%s\", layer=%d\n", init_for_nav, window->Name, g.NavLayer);
if (init_for_nav)
{
SetNavID(0, g.NavLayer, 0);
g.NavInitRequest = true;
g.NavInitRequestFromMove = false;
g.NavInitResultId = 0;
g.NavInitResultRectRel = ImRect();
NavUpdateAnyRequestFlag();
}
else
{
g.NavId = window->NavLastIds[0];
g.NavFocusScopeId = 0;
}
}
static ImVec2 ImGui::NavCalcPreferredRefPos()
{
ImGuiContext& g = *GImGui;
if (g.NavDisableHighlight || !g.NavDisableMouseHover || !g.NavWindow)
{
// Mouse (we need a fallback in case the mouse becomes invalid after being used)
if (IsMousePosValid(&g.IO.MousePos))
return g.IO.MousePos;
return g.LastValidMousePos;
}
else
{
// When navigation is active and mouse is disabled, decide on an arbitrary position around the bottom left of the currently navigated item.
const ImRect& rect_rel = g.NavWindow->NavRectRel[g.NavLayer];
ImVec2 pos = g.NavWindow->Pos + ImVec2(rect_rel.Min.x + ImMin(g.Style.FramePadding.x * 4, rect_rel.GetWidth()), rect_rel.Max.y - ImMin(g.Style.FramePadding.y, rect_rel.GetHeight()));
ImRect visible_rect = GetViewportRect();
return ImFloor(ImClamp(pos, visible_rect.Min, visible_rect.Max)); // ImFloor() is important because non-integer mouse position application in back-end might be lossy and result in undesirable non-zero delta.
}
}
float ImGui::GetNavInputAmount(ImGuiNavInput n, ImGuiInputReadMode mode)
{
ImGuiContext& g = *GImGui;
if (mode == ImGuiInputReadMode_Down)
return g.IO.NavInputs[n]; // Instant, read analog input (0.0f..1.0f, as provided by user)
const float t = g.IO.NavInputsDownDuration[n];
if (t < 0.0f && mode == ImGuiInputReadMode_Released) // Return 1.0f when just released, no repeat, ignore analog input.
return (g.IO.NavInputsDownDurationPrev[n] >= 0.0f ? 1.0f : 0.0f);
if (t < 0.0f)
return 0.0f;
if (mode == ImGuiInputReadMode_Pressed) // Return 1.0f when just pressed, no repeat, ignore analog input.
return (t == 0.0f) ? 1.0f : 0.0f;
if (mode == ImGuiInputReadMode_Repeat)
return (float)CalcTypematicRepeatAmount(t - g.IO.DeltaTime, t, g.IO.KeyRepeatDelay * 0.72f, g.IO.KeyRepeatRate * 0.80f);
if (mode == ImGuiInputReadMode_RepeatSlow)
return (float)CalcTypematicRepeatAmount(t - g.IO.DeltaTime, t, g.IO.KeyRepeatDelay * 1.25f, g.IO.KeyRepeatRate * 2.00f);
if (mode == ImGuiInputReadMode_RepeatFast)
return (float)CalcTypematicRepeatAmount(t - g.IO.DeltaTime, t, g.IO.KeyRepeatDelay * 0.72f, g.IO.KeyRepeatRate * 0.30f);
return 0.0f;
}
ImVec2 ImGui::GetNavInputAmount2d(ImGuiNavDirSourceFlags dir_sources, ImGuiInputReadMode mode, float slow_factor, float fast_factor)
{
ImVec2 delta(0.0f, 0.0f);
if (dir_sources & ImGuiNavDirSourceFlags_Keyboard)
delta += ImVec2(GetNavInputAmount(ImGuiNavInput_KeyRight_, mode) - GetNavInputAmount(ImGuiNavInput_KeyLeft_, mode), GetNavInputAmount(ImGuiNavInput_KeyDown_, mode) - GetNavInputAmount(ImGuiNavInput_KeyUp_, mode));
if (dir_sources & ImGuiNavDirSourceFlags_PadDPad)
delta += ImVec2(GetNavInputAmount(ImGuiNavInput_DpadRight, mode) - GetNavInputAmount(ImGuiNavInput_DpadLeft, mode), GetNavInputAmount(ImGuiNavInput_DpadDown, mode) - GetNavInputAmount(ImGuiNavInput_DpadUp, mode));
if (dir_sources & ImGuiNavDirSourceFlags_PadLStick)
delta += ImVec2(GetNavInputAmount(ImGuiNavInput_LStickRight, mode) - GetNavInputAmount(ImGuiNavInput_LStickLeft, mode), GetNavInputAmount(ImGuiNavInput_LStickDown, mode) - GetNavInputAmount(ImGuiNavInput_LStickUp, mode));
if (slow_factor != 0.0f && IsNavInputDown(ImGuiNavInput_TweakSlow))
delta *= slow_factor;
if (fast_factor != 0.0f && IsNavInputDown(ImGuiNavInput_TweakFast))
delta *= fast_factor;
return delta;
}
static void ImGui::NavUpdate()
{
ImGuiContext& g = *GImGui;
g.IO.WantSetMousePos = false;
#if 0
if (g.NavScoringCount > 0) IMGUI_DEBUG_LOG("NavScoringCount %d for '%s' layer %d (Init:%d, Move:%d)\n", g.FrameCount, g.NavScoringCount, g.NavWindow ? g.NavWindow->Name : "NULL", g.NavLayer, g.NavInitRequest || g.NavInitResultId != 0, g.NavMoveRequest);
#endif
// Set input source as Gamepad when buttons are pressed (as some features differs when used with Gamepad vs Keyboard)
// (do it before we map Keyboard input!)
bool nav_keyboard_active = (g.IO.ConfigFlags & ImGuiConfigFlags_NavEnableKeyboard) != 0;
bool nav_gamepad_active = (g.IO.ConfigFlags & ImGuiConfigFlags_NavEnableGamepad) != 0 && (g.IO.BackendFlags & ImGuiBackendFlags_HasGamepad) != 0;
if (nav_gamepad_active)
if (g.IO.NavInputs[ImGuiNavInput_Activate] > 0.0f || g.IO.NavInputs[ImGuiNavInput_Input] > 0.0f || g.IO.NavInputs[ImGuiNavInput_Cancel] > 0.0f || g.IO.NavInputs[ImGuiNavInput_Menu] > 0.0f)
g.NavInputSource = ImGuiInputSource_NavGamepad;
// Update Keyboard->Nav inputs mapping
if (nav_keyboard_active)
{
#define NAV_MAP_KEY(_KEY, _NAV_INPUT) do { if (IsKeyDown(g.IO.KeyMap[_KEY])) { g.IO.NavInputs[_NAV_INPUT] = 1.0f; g.NavInputSource = ImGuiInputSource_NavKeyboard; } } while (0)
NAV_MAP_KEY(ImGuiKey_Space, ImGuiNavInput_Activate );
NAV_MAP_KEY(ImGuiKey_Enter, ImGuiNavInput_Input );
NAV_MAP_KEY(ImGuiKey_Escape, ImGuiNavInput_Cancel );
NAV_MAP_KEY(ImGuiKey_LeftArrow, ImGuiNavInput_KeyLeft_ );
NAV_MAP_KEY(ImGuiKey_RightArrow,ImGuiNavInput_KeyRight_);
NAV_MAP_KEY(ImGuiKey_UpArrow, ImGuiNavInput_KeyUp_ );
NAV_MAP_KEY(ImGuiKey_DownArrow, ImGuiNavInput_KeyDown_ );
if (g.IO.KeyCtrl)
g.IO.NavInputs[ImGuiNavInput_TweakSlow] = 1.0f;
if (g.IO.KeyShift)
g.IO.NavInputs[ImGuiNavInput_TweakFast] = 1.0f;
if (g.IO.KeyAlt && !g.IO.KeyCtrl) // AltGR is Alt+Ctrl, also even on keyboards without AltGR we don't want Alt+Ctrl to open menu.
g.IO.NavInputs[ImGuiNavInput_KeyMenu_] = 1.0f;
#undef NAV_MAP_KEY
}
memcpy(g.IO.NavInputsDownDurationPrev, g.IO.NavInputsDownDuration, sizeof(g.IO.NavInputsDownDuration));
for (int i = 0; i < IM_ARRAYSIZE(g.IO.NavInputs); i++)
g.IO.NavInputsDownDuration[i] = (g.IO.NavInputs[i] > 0.0f) ? (g.IO.NavInputsDownDuration[i] < 0.0f ? 0.0f : g.IO.NavInputsDownDuration[i] + g.IO.DeltaTime) : -1.0f;
// Process navigation init request (select first/default focus)
// In very rare cases g.NavWindow may be null (e.g. clearing focus after requesting an init request, which does happen when releasing Alt while clicking on void)
if (g.NavInitResultId != 0 && (!g.NavDisableHighlight || g.NavInitRequestFromMove) && g.NavWindow)
{
// Apply result from previous navigation init request (will typically select the first item, unless SetItemDefaultFocus() has been called)
//IMGUI_DEBUG_LOG("[Nav] Apply NavInitRequest result: 0x%08X Layer %d in \"%s\"\n", g.NavInitResultId, g.NavLayer, g.NavWindow->Name);
if (g.NavInitRequestFromMove)
SetNavIDWithRectRel(g.NavInitResultId, g.NavLayer, 0, g.NavInitResultRectRel);
else
SetNavID(g.NavInitResultId, g.NavLayer, 0);
g.NavWindow->NavRectRel[g.NavLayer] = g.NavInitResultRectRel;
}
g.NavInitRequest = false;
g.NavInitRequestFromMove = false;
g.NavInitResultId = 0;
g.NavJustMovedToId = 0;
// Process navigation move request
if (g.NavMoveRequest)
NavUpdateMoveResult();
// When a forwarded move request failed, we restore the highlight that we disabled during the forward frame
if (g.NavMoveRequestForward == ImGuiNavForward_ForwardActive)
{
IM_ASSERT(g.NavMoveRequest);
if (g.NavMoveResultLocal.ID == 0 && g.NavMoveResultOther.ID == 0)
g.NavDisableHighlight = false;
g.NavMoveRequestForward = ImGuiNavForward_None;
}
// Apply application mouse position movement, after we had a chance to process move request result.
if (g.NavMousePosDirty && g.NavIdIsAlive)
{
// Set mouse position given our knowledge of the navigated item position from last frame
if ((g.IO.ConfigFlags & ImGuiConfigFlags_NavEnableSetMousePos) && (g.IO.BackendFlags & ImGuiBackendFlags_HasSetMousePos))
{
if (!g.NavDisableHighlight && g.NavDisableMouseHover && g.NavWindow)
{
g.IO.MousePos = g.IO.MousePosPrev = NavCalcPreferredRefPos();
g.IO.WantSetMousePos = true;
}
}
g.NavMousePosDirty = false;
}
g.NavIdIsAlive = false;
g.NavJustTabbedId = 0;
IM_ASSERT(g.NavLayer == 0 || g.NavLayer == 1);
// Store our return window (for returning from Layer 1 to Layer 0) and clear it as soon as we step back in our own Layer 0
if (g.NavWindow)
NavSaveLastChildNavWindowIntoParent(g.NavWindow);
if (g.NavWindow && g.NavWindow->NavLastChildNavWindow != NULL && g.NavLayer == 0)
g.NavWindow->NavLastChildNavWindow = NULL;
// Update CTRL+TAB and Windowing features (hold Square to move/resize/etc.)
NavUpdateWindowing();
// Set output flags for user application
g.IO.NavActive = (nav_keyboard_active || nav_gamepad_active) && g.NavWindow && !(g.NavWindow->Flags & ImGuiWindowFlags_NoNavInputs);
g.IO.NavVisible = (g.IO.NavActive && g.NavId != 0 && !g.NavDisableHighlight) || (g.NavWindowingTarget != NULL);
// Process NavCancel input (to close a popup, get back to parent, clear focus)
if (IsNavInputTest(ImGuiNavInput_Cancel, ImGuiInputReadMode_Pressed))
{
if (g.ActiveId != 0)
{
if (!IsActiveIdUsingNavInput(ImGuiNavInput_Cancel))
ClearActiveID();
}
else if (g.NavWindow && (g.NavWindow->Flags & ImGuiWindowFlags_ChildWindow) && !(g.NavWindow->Flags & ImGuiWindowFlags_Popup) && g.NavWindow->ParentWindow)
{
// Exit child window
ImGuiWindow* child_window = g.NavWindow;
ImGuiWindow* parent_window = g.NavWindow->ParentWindow;
IM_ASSERT(child_window->ChildId != 0);
FocusWindow(parent_window);
SetNavID(child_window->ChildId, 0, 0);
// Reassigning with same value, we're being explicit here.
g.NavIdIsAlive = false; // -V1048
if (g.NavDisableMouseHover)
g.NavMousePosDirty = true;
}
else if (g.OpenPopupStack.Size > 0)
{
// Close open popup/menu
if (!(g.OpenPopupStack.back().Window->Flags & ImGuiWindowFlags_Modal))
ClosePopupToLevel(g.OpenPopupStack.Size - 1, true);
}
else if (g.NavLayer != 0)
{
// Leave the "menu" layer
NavRestoreLayer(ImGuiNavLayer_Main);
}
else
{
// Clear NavLastId for popups but keep it for regular child window so we can leave one and come back where we were
if (g.NavWindow && ((g.NavWindow->Flags & ImGuiWindowFlags_Popup) || !(g.NavWindow->Flags & ImGuiWindowFlags_ChildWindow)))
g.NavWindow->NavLastIds[0] = 0;
g.NavId = g.NavFocusScopeId = 0;
}
}
// Process manual activation request
g.NavActivateId = g.NavActivateDownId = g.NavActivatePressedId = g.NavInputId = 0;
if (g.NavId != 0 && !g.NavDisableHighlight && !g.NavWindowingTarget && g.NavWindow && !(g.NavWindow->Flags & ImGuiWindowFlags_NoNavInputs))
{
bool activate_down = IsNavInputDown(ImGuiNavInput_Activate);
bool activate_pressed = activate_down && IsNavInputTest(ImGuiNavInput_Activate, ImGuiInputReadMode_Pressed);
if (g.ActiveId == 0 && activate_pressed)
g.NavActivateId = g.NavId;
if ((g.ActiveId == 0 || g.ActiveId == g.NavId) && activate_down)
g.NavActivateDownId = g.NavId;
if ((g.ActiveId == 0 || g.ActiveId == g.NavId) && activate_pressed)
g.NavActivatePressedId = g.NavId;
if ((g.ActiveId == 0 || g.ActiveId == g.NavId) && IsNavInputTest(ImGuiNavInput_Input, ImGuiInputReadMode_Pressed))
g.NavInputId = g.NavId;
}
if (g.NavWindow && (g.NavWindow->Flags & ImGuiWindowFlags_NoNavInputs))
g.NavDisableHighlight = true;
if (g.NavActivateId != 0)
IM_ASSERT(g.NavActivateDownId == g.NavActivateId);
g.NavMoveRequest = false;
// Process programmatic activation request
if (g.NavNextActivateId != 0)
g.NavActivateId = g.NavActivateDownId = g.NavActivatePressedId = g.NavInputId = g.NavNextActivateId;
g.NavNextActivateId = 0;
// Initiate directional inputs request
if (g.NavMoveRequestForward == ImGuiNavForward_None)
{
g.NavMoveDir = ImGuiDir_None;
g.NavMoveRequestFlags = ImGuiNavMoveFlags_None;
if (g.NavWindow && !g.NavWindowingTarget && !(g.NavWindow->Flags & ImGuiWindowFlags_NoNavInputs))
{
const ImGuiInputReadMode read_mode = ImGuiInputReadMode_Repeat;
if (!IsActiveIdUsingNavDir(ImGuiDir_Left) && (IsNavInputTest(ImGuiNavInput_DpadLeft, read_mode) || IsNavInputTest(ImGuiNavInput_KeyLeft_, read_mode))) { g.NavMoveDir = ImGuiDir_Left; }
if (!IsActiveIdUsingNavDir(ImGuiDir_Right) && (IsNavInputTest(ImGuiNavInput_DpadRight, read_mode) || IsNavInputTest(ImGuiNavInput_KeyRight_, read_mode))) { g.NavMoveDir = ImGuiDir_Right; }
if (!IsActiveIdUsingNavDir(ImGuiDir_Up) && (IsNavInputTest(ImGuiNavInput_DpadUp, read_mode) || IsNavInputTest(ImGuiNavInput_KeyUp_, read_mode))) { g.NavMoveDir = ImGuiDir_Up; }
if (!IsActiveIdUsingNavDir(ImGuiDir_Down) && (IsNavInputTest(ImGuiNavInput_DpadDown, read_mode) || IsNavInputTest(ImGuiNavInput_KeyDown_, read_mode))) { g.NavMoveDir = ImGuiDir_Down; }
}
g.NavMoveClipDir = g.NavMoveDir;
}
else
{
// Forwarding previous request (which has been modified, e.g. wrap around menus rewrite the requests with a starting rectangle at the other side of the window)
// (Preserve g.NavMoveRequestFlags, g.NavMoveClipDir which were set by the NavMoveRequestForward() function)
IM_ASSERT(g.NavMoveDir != ImGuiDir_None && g.NavMoveClipDir != ImGuiDir_None);
IM_ASSERT(g.NavMoveRequestForward == ImGuiNavForward_ForwardQueued);
g.NavMoveRequestForward = ImGuiNavForward_ForwardActive;
}
// Update PageUp/PageDown/Home/End scroll
// FIXME-NAV: Consider enabling those keys even without the master ImGuiConfigFlags_NavEnableKeyboard flag?
float nav_scoring_rect_offset_y = 0.0f;
if (nav_keyboard_active)
nav_scoring_rect_offset_y = NavUpdatePageUpPageDown();
// If we initiate a movement request and have no current NavId, we initiate a InitDefautRequest that will be used as a fallback if the direction fails to find a match
if (g.NavMoveDir != ImGuiDir_None)
{
g.NavMoveRequest = true;
g.NavMoveDirLast = g.NavMoveDir;
}
if (g.NavMoveRequest && g.NavId == 0)
{
//IMGUI_DEBUG_LOG("[Nav] NavInitRequest from move, window \"%s\", layer=%d\n", g.NavWindow->Name, g.NavLayer);
g.NavInitRequest = g.NavInitRequestFromMove = true;
// Reassigning with same value, we're being explicit here.
g.NavInitResultId = 0; // -V1048
g.NavDisableHighlight = false;
}
NavUpdateAnyRequestFlag();
// Scrolling
if (g.NavWindow && !(g.NavWindow->Flags & ImGuiWindowFlags_NoNavInputs) && !g.NavWindowingTarget)
{
// *Fallback* manual-scroll with Nav directional keys when window has no navigable item
ImGuiWindow* window = g.NavWindow;
const float scroll_speed = IM_ROUND(window->CalcFontSize() * 100 * g.IO.DeltaTime); // We need round the scrolling speed because sub-pixel scroll isn't reliably supported.
if (window->DC.NavLayerActiveMask == 0x00 && window->DC.NavHasScroll && g.NavMoveRequest)
{
if (g.NavMoveDir == ImGuiDir_Left || g.NavMoveDir == ImGuiDir_Right)
SetScrollX(window, ImFloor(window->Scroll.x + ((g.NavMoveDir == ImGuiDir_Left) ? -1.0f : +1.0f) * scroll_speed));
if (g.NavMoveDir == ImGuiDir_Up || g.NavMoveDir == ImGuiDir_Down)
SetScrollY(window, ImFloor(window->Scroll.y + ((g.NavMoveDir == ImGuiDir_Up) ? -1.0f : +1.0f) * scroll_speed));
}
// *Normal* Manual scroll with NavScrollXXX keys
// Next movement request will clamp the NavId reference rectangle to the visible area, so navigation will resume within those bounds.
ImVec2 scroll_dir = GetNavInputAmount2d(ImGuiNavDirSourceFlags_PadLStick, ImGuiInputReadMode_Down, 1.0f/10.0f, 10.0f);
if (scroll_dir.x != 0.0f && window->ScrollbarX)
{
SetScrollX(window, ImFloor(window->Scroll.x + scroll_dir.x * scroll_speed));
g.NavMoveFromClampedRefRect = true;
}
if (scroll_dir.y != 0.0f)
{
SetScrollY(window, ImFloor(window->Scroll.y + scroll_dir.y * scroll_speed));
g.NavMoveFromClampedRefRect = true;
}
}
// Reset search results
g.NavMoveResultLocal.Clear();
g.NavMoveResultLocalVisibleSet.Clear();
g.NavMoveResultOther.Clear();
// When we have manually scrolled (without using navigation) and NavId becomes out of bounds, we project its bounding box to the visible area to restart navigation within visible items
if (g.NavMoveRequest && g.NavMoveFromClampedRefRect && g.NavLayer == 0)
{
ImGuiWindow* window = g.NavWindow;
ImRect window_rect_rel(window->InnerRect.Min - window->Pos - ImVec2(1,1), window->InnerRect.Max - window->Pos + ImVec2(1,1));
if (!window_rect_rel.Contains(window->NavRectRel[g.NavLayer]))
{
float pad = window->CalcFontSize() * 0.5f;
window_rect_rel.Expand(ImVec2(-ImMin(window_rect_rel.GetWidth(), pad), -ImMin(window_rect_rel.GetHeight(), pad))); // Terrible approximation for the intent of starting navigation from first fully visible item
window->NavRectRel[g.NavLayer].ClipWith(window_rect_rel);
g.NavId = g.NavFocusScopeId = 0;
}
g.NavMoveFromClampedRefRect = false;
}
// For scoring we use a single segment on the left side our current item bounding box (not touching the edge to avoid box overlap with zero-spaced items)
ImRect nav_rect_rel = (g.NavWindow && !g.NavWindow->NavRectRel[g.NavLayer].IsInverted()) ? g.NavWindow->NavRectRel[g.NavLayer] : ImRect(0,0,0,0);
g.NavScoringRectScreen = g.NavWindow ? ImRect(g.NavWindow->Pos + nav_rect_rel.Min, g.NavWindow->Pos + nav_rect_rel.Max) : GetViewportRect();
g.NavScoringRectScreen.TranslateY(nav_scoring_rect_offset_y);
g.NavScoringRectScreen.Min.x = ImMin(g.NavScoringRectScreen.Min.x + 1.0f, g.NavScoringRectScreen.Max.x);
g.NavScoringRectScreen.Max.x = g.NavScoringRectScreen.Min.x;
IM_ASSERT(!g.NavScoringRectScreen.IsInverted()); // Ensure if we have a finite, non-inverted bounding box here will allows us to remove extraneous ImFabs() calls in NavScoreItem().
//GetForegroundDrawList()->AddRect(g.NavScoringRectScreen.Min, g.NavScoringRectScreen.Max, IM_COL32(255,200,0,255)); // [DEBUG]
g.NavScoringCount = 0;
#if IMGUI_DEBUG_NAV_RECTS
if (g.NavWindow)
{
ImDrawList* draw_list = GetForegroundDrawList(g.NavWindow);
if (1) { for (int layer = 0; layer < 2; layer++) draw_list->AddRect(g.NavWindow->Pos + g.NavWindow->NavRectRel[layer].Min, g.NavWindow->Pos + g.NavWindow->NavRectRel[layer].Max, IM_COL32(255,200,0,255)); } // [DEBUG]
if (1) { ImU32 col = (!g.NavWindow->Hidden) ? IM_COL32(255,0,255,255) : IM_COL32(255,0,0,255); ImVec2 p = NavCalcPreferredRefPos(); char buf[32]; ImFormatString(buf, 32, "%d", g.NavLayer); draw_list->AddCircleFilled(p, 3.0f, col); draw_list->AddText(NULL, 13.0f, p + ImVec2(8,-4), col, buf); }
}
#endif
}
// Apply result from previous frame navigation directional move request
static void ImGui::NavUpdateMoveResult()
{
ImGuiContext& g = *GImGui;
if (g.NavMoveResultLocal.ID == 0 && g.NavMoveResultOther.ID == 0)
{
// In a situation when there is no results but NavId != 0, re-enable the Navigation highlight (because g.NavId is not considered as a possible result)
if (g.NavId != 0)
{
g.NavDisableHighlight = false;
g.NavDisableMouseHover = true;
}
return;
}
// Select which result to use
ImGuiNavMoveResult* result = (g.NavMoveResultLocal.ID != 0) ? &g.NavMoveResultLocal : &g.NavMoveResultOther;
// PageUp/PageDown behavior first jumps to the bottom/top mostly visible item, _otherwise_ use the result from the previous/next page.
if (g.NavMoveRequestFlags & ImGuiNavMoveFlags_AlsoScoreVisibleSet)
if (g.NavMoveResultLocalVisibleSet.ID != 0 && g.NavMoveResultLocalVisibleSet.ID != g.NavId)
result = &g.NavMoveResultLocalVisibleSet;
// Maybe entering a flattened child from the outside? In this case solve the tie using the regular scoring rules.
if (result != &g.NavMoveResultOther && g.NavMoveResultOther.ID != 0 && g.NavMoveResultOther.Window->ParentWindow == g.NavWindow)
if ((g.NavMoveResultOther.DistBox < result->DistBox) || (g.NavMoveResultOther.DistBox == result->DistBox && g.NavMoveResultOther.DistCenter < result->DistCenter))
result = &g.NavMoveResultOther;
IM_ASSERT(g.NavWindow && result->Window);
// Scroll to keep newly navigated item fully into view.
if (g.NavLayer == 0)
{
ImVec2 delta_scroll;
if (g.NavMoveRequestFlags & ImGuiNavMoveFlags_ScrollToEdge)
{
float scroll_target = (g.NavMoveDir == ImGuiDir_Up) ? result->Window->ScrollMax.y : 0.0f;
delta_scroll.y = result->Window->Scroll.y - scroll_target;
SetScrollY(result->Window, scroll_target);
}
else
{
ImRect rect_abs = ImRect(result->RectRel.Min + result->Window->Pos, result->RectRel.Max + result->Window->Pos);
delta_scroll = ScrollToBringRectIntoView(result->Window, rect_abs);
}
// Offset our result position so mouse position can be applied immediately after in NavUpdate()
result->RectRel.TranslateX(-delta_scroll.x);
result->RectRel.TranslateY(-delta_scroll.y);
}
ClearActiveID();
g.NavWindow = result->Window;
if (g.NavId != result->ID)
{
// Don't set NavJustMovedToId if just landed on the same spot (which may happen with ImGuiNavMoveFlags_AllowCurrentNavId)
g.NavJustMovedToId = result->ID;
g.NavJustMovedToFocusScopeId = result->FocusScopeId;
}
SetNavIDWithRectRel(result->ID, g.NavLayer, result->FocusScopeId, result->RectRel);
g.NavMoveFromClampedRefRect = false;
}
// Handle PageUp/PageDown/Home/End keys
static float ImGui::NavUpdatePageUpPageDown()
{
ImGuiContext& g = *GImGui;
if (g.NavMoveDir != ImGuiDir_None || g.NavWindow == NULL)
return 0.0f;
if ((g.NavWindow->Flags & ImGuiWindowFlags_NoNavInputs) || g.NavWindowingTarget != NULL || g.NavLayer != 0)
return 0.0f;
ImGuiWindow* window = g.NavWindow;
const bool page_up_held = IsKeyDown(g.IO.KeyMap[ImGuiKey_PageUp]) && !IsActiveIdUsingKey(ImGuiKey_PageUp);
const bool page_down_held = IsKeyDown(g.IO.KeyMap[ImGuiKey_PageDown]) && !IsActiveIdUsingKey(ImGuiKey_PageDown);
const bool home_pressed = IsKeyPressed(g.IO.KeyMap[ImGuiKey_Home]) && !IsActiveIdUsingKey(ImGuiKey_Home);
const bool end_pressed = IsKeyPressed(g.IO.KeyMap[ImGuiKey_End]) && !IsActiveIdUsingKey(ImGuiKey_End);
if (page_up_held != page_down_held || home_pressed != end_pressed) // If either (not both) are pressed
{
if (window->DC.NavLayerActiveMask == 0x00 && window->DC.NavHasScroll)
{
// Fallback manual-scroll when window has no navigable item
if (IsKeyPressed(g.IO.KeyMap[ImGuiKey_PageUp], true))
SetScrollY(window, window->Scroll.y - window->InnerRect.GetHeight());
else if (IsKeyPressed(g.IO.KeyMap[ImGuiKey_PageDown], true))
SetScrollY(window, window->Scroll.y + window->InnerRect.GetHeight());
else if (home_pressed)
SetScrollY(window, 0.0f);
else if (end_pressed)
SetScrollY(window, window->ScrollMax.y);
}
else
{
ImRect& nav_rect_rel = window->NavRectRel[g.NavLayer];
const float page_offset_y = ImMax(0.0f, window->InnerRect.GetHeight() - window->CalcFontSize() * 1.0f + nav_rect_rel.GetHeight());
float nav_scoring_rect_offset_y = 0.0f;
if (IsKeyPressed(g.IO.KeyMap[ImGuiKey_PageUp], true))
{
nav_scoring_rect_offset_y = -page_offset_y;
g.NavMoveDir = ImGuiDir_Down; // Because our scoring rect is offset up, we request the down direction (so we can always land on the last item)
g.NavMoveClipDir = ImGuiDir_Up;
g.NavMoveRequestFlags = ImGuiNavMoveFlags_AllowCurrentNavId | ImGuiNavMoveFlags_AlsoScoreVisibleSet;
}
else if (IsKeyPressed(g.IO.KeyMap[ImGuiKey_PageDown], true))
{
nav_scoring_rect_offset_y = +page_offset_y;
g.NavMoveDir = ImGuiDir_Up; // Because our scoring rect is offset down, we request the up direction (so we can always land on the last item)
g.NavMoveClipDir = ImGuiDir_Down;
g.NavMoveRequestFlags = ImGuiNavMoveFlags_AllowCurrentNavId | ImGuiNavMoveFlags_AlsoScoreVisibleSet;
}
else if (home_pressed)
{
// FIXME-NAV: handling of Home/End is assuming that the top/bottom most item will be visible with Scroll.y == 0/ScrollMax.y
// Scrolling will be handled via the ImGuiNavMoveFlags_ScrollToEdge flag, we don't scroll immediately to avoid scrolling happening before nav result.
// Preserve current horizontal position if we have any.
nav_rect_rel.Min.y = nav_rect_rel.Max.y = -window->Scroll.y;
if (nav_rect_rel.IsInverted())
nav_rect_rel.Min.x = nav_rect_rel.Max.x = 0.0f;
g.NavMoveDir = ImGuiDir_Down;
g.NavMoveRequestFlags = ImGuiNavMoveFlags_AllowCurrentNavId | ImGuiNavMoveFlags_ScrollToEdge;
}
else if (end_pressed)
{
nav_rect_rel.Min.y = nav_rect_rel.Max.y = window->ScrollMax.y + window->SizeFull.y - window->Scroll.y;
if (nav_rect_rel.IsInverted())
nav_rect_rel.Min.x = nav_rect_rel.Max.x = 0.0f;
g.NavMoveDir = ImGuiDir_Up;
g.NavMoveRequestFlags = ImGuiNavMoveFlags_AllowCurrentNavId | ImGuiNavMoveFlags_ScrollToEdge;
}
return nav_scoring_rect_offset_y;
}
}
return 0.0f;
}
static int ImGui::FindWindowFocusIndex(ImGuiWindow* window) // FIXME-OPT O(N)
{
ImGuiContext& g = *GImGui;
for (int i = g.WindowsFocusOrder.Size-1; i >= 0; i--)
if (g.WindowsFocusOrder[i] == window)
return i;
return -1;
}
static ImGuiWindow* FindWindowNavFocusable(int i_start, int i_stop, int dir) // FIXME-OPT O(N)
{
ImGuiContext& g = *GImGui;
for (int i = i_start; i >= 0 && i < g.WindowsFocusOrder.Size && i != i_stop; i += dir)
if (ImGui::IsWindowNavFocusable(g.WindowsFocusOrder[i]))
return g.WindowsFocusOrder[i];
return NULL;
}
static void NavUpdateWindowingHighlightWindow(int focus_change_dir)
{
ImGuiContext& g = *GImGui;
IM_ASSERT(g.NavWindowingTarget);
if (g.NavWindowingTarget->Flags & ImGuiWindowFlags_Modal)
return;
const int i_current = ImGui::FindWindowFocusIndex(g.NavWindowingTarget);
ImGuiWindow* window_target = FindWindowNavFocusable(i_current + focus_change_dir, -INT_MAX, focus_change_dir);
if (!window_target)
window_target = FindWindowNavFocusable((focus_change_dir < 0) ? (g.WindowsFocusOrder.Size - 1) : 0, i_current, focus_change_dir);
if (window_target) // Don't reset windowing target if there's a single window in the list
g.NavWindowingTarget = g.NavWindowingTargetAnim = window_target;
g.NavWindowingToggleLayer = false;
}
// Windowing management mode
// Keyboard: CTRL+Tab (change focus/move/resize), Alt (toggle menu layer)
// Gamepad: Hold Menu/Square (change focus/move/resize), Tap Menu/Square (toggle menu layer)
static void ImGui::NavUpdateWindowing()
{
ImGuiContext& g = *GImGui;
ImGuiWindow* apply_focus_window = NULL;
bool apply_toggle_layer = false;
ImGuiWindow* modal_window = GetTopMostPopupModal();
if (modal_window != NULL)
{
g.NavWindowingTarget = NULL;
return;
}
// Fade out
if (g.NavWindowingTargetAnim && g.NavWindowingTarget == NULL)
{
g.NavWindowingHighlightAlpha = ImMax(g.NavWindowingHighlightAlpha - g.IO.DeltaTime * 10.0f, 0.0f);
if (g.DimBgRatio <= 0.0f && g.NavWindowingHighlightAlpha <= 0.0f)
g.NavWindowingTargetAnim = NULL;
}
// Start CTRL-TAB or Square+L/R window selection
bool start_windowing_with_gamepad = !g.NavWindowingTarget && IsNavInputTest(ImGuiNavInput_Menu, ImGuiInputReadMode_Pressed);
bool start_windowing_with_keyboard = !g.NavWindowingTarget && g.IO.KeyCtrl && IsKeyPressedMap(ImGuiKey_Tab) && (g.IO.ConfigFlags & ImGuiConfigFlags_NavEnableKeyboard);
if (start_windowing_with_gamepad || start_windowing_with_keyboard)
if (ImGuiWindow* window = g.NavWindow ? g.NavWindow : FindWindowNavFocusable(g.WindowsFocusOrder.Size - 1, -INT_MAX, -1))
{
g.NavWindowingTarget = g.NavWindowingTargetAnim = window->RootWindow; // FIXME-DOCK: Will need to use RootWindowDockStop
g.NavWindowingTimer = g.NavWindowingHighlightAlpha = 0.0f;
g.NavWindowingToggleLayer = start_windowing_with_keyboard ? false : true;
g.NavInputSource = start_windowing_with_keyboard ? ImGuiInputSource_NavKeyboard : ImGuiInputSource_NavGamepad;
}
// Gamepad update
g.NavWindowingTimer += g.IO.DeltaTime;
if (g.NavWindowingTarget && g.NavInputSource == ImGuiInputSource_NavGamepad)
{
// Highlight only appears after a brief time holding the button, so that a fast tap on PadMenu (to toggle NavLayer) doesn't add visual noise
g.NavWindowingHighlightAlpha = ImMax(g.NavWindowingHighlightAlpha, ImSaturate((g.NavWindowingTimer - NAV_WINDOWING_HIGHLIGHT_DELAY) / 0.05f));
// Select window to focus
const int focus_change_dir = (int)IsNavInputTest(ImGuiNavInput_FocusPrev, ImGuiInputReadMode_RepeatSlow) - (int)IsNavInputTest(ImGuiNavInput_FocusNext, ImGuiInputReadMode_RepeatSlow);
if (focus_change_dir != 0)
{
NavUpdateWindowingHighlightWindow(focus_change_dir);
g.NavWindowingHighlightAlpha = 1.0f;
}
// Single press toggles NavLayer, long press with L/R apply actual focus on release (until then the window was merely rendered top-most)
if (!IsNavInputDown(ImGuiNavInput_Menu))
{
g.NavWindowingToggleLayer &= (g.NavWindowingHighlightAlpha < 1.0f); // Once button was held long enough we don't consider it a tap-to-toggle-layer press anymore.
if (g.NavWindowingToggleLayer && g.NavWindow)
apply_toggle_layer = true;
else if (!g.NavWindowingToggleLayer)
apply_focus_window = g.NavWindowingTarget;
g.NavWindowingTarget = NULL;
}
}
// Keyboard: Focus
if (g.NavWindowingTarget && g.NavInputSource == ImGuiInputSource_NavKeyboard)
{
// Visuals only appears after a brief time after pressing TAB the first time, so that a fast CTRL+TAB doesn't add visual noise
g.NavWindowingHighlightAlpha = ImMax(g.NavWindowingHighlightAlpha, ImSaturate((g.NavWindowingTimer - NAV_WINDOWING_HIGHLIGHT_DELAY) / 0.05f)); // 1.0f
if (IsKeyPressedMap(ImGuiKey_Tab, true))
NavUpdateWindowingHighlightWindow(g.IO.KeyShift ? +1 : -1);
if (!g.IO.KeyCtrl)
apply_focus_window = g.NavWindowingTarget;
}
// Keyboard: Press and Release ALT to toggle menu layer
// FIXME: We lack an explicit IO variable for "is the imgui window focused", so compare mouse validity to detect the common case of back-end clearing releases all keys on ALT-TAB
if (IsNavInputTest(ImGuiNavInput_KeyMenu_, ImGuiInputReadMode_Pressed))
g.NavWindowingToggleLayer = true;
if ((g.ActiveId == 0 || g.ActiveIdAllowOverlap) && g.NavWindowingToggleLayer && IsNavInputTest(ImGuiNavInput_KeyMenu_, ImGuiInputReadMode_Released))
if (IsMousePosValid(&g.IO.MousePos) == IsMousePosValid(&g.IO.MousePosPrev))
apply_toggle_layer = true;
// Move window
if (g.NavWindowingTarget && !(g.NavWindowingTarget->Flags & ImGuiWindowFlags_NoMove))
{
ImVec2 move_delta;
if (g.NavInputSource == ImGuiInputSource_NavKeyboard && !g.IO.KeyShift)
move_delta = GetNavInputAmount2d(ImGuiNavDirSourceFlags_Keyboard, ImGuiInputReadMode_Down);
if (g.NavInputSource == ImGuiInputSource_NavGamepad)
move_delta = GetNavInputAmount2d(ImGuiNavDirSourceFlags_PadLStick, ImGuiInputReadMode_Down);
if (move_delta.x != 0.0f || move_delta.y != 0.0f)
{
const float NAV_MOVE_SPEED = 800.0f;
const float move_speed = ImFloor(NAV_MOVE_SPEED * g.IO.DeltaTime * ImMin(g.IO.DisplayFramebufferScale.x, g.IO.DisplayFramebufferScale.y)); // FIXME: Doesn't code variable framerate very well
SetWindowPos(g.NavWindowingTarget->RootWindow, g.NavWindowingTarget->RootWindow->Pos + move_delta * move_speed, ImGuiCond_Always);
g.NavDisableMouseHover = true;
MarkIniSettingsDirty(g.NavWindowingTarget);
}
}
// Apply final focus
if (apply_focus_window && (g.NavWindow == NULL || apply_focus_window != g.NavWindow->RootWindow))
{
ClearActiveID();
g.NavDisableHighlight = false;
g.NavDisableMouseHover = true;
apply_focus_window = NavRestoreLastChildNavWindow(apply_focus_window);
ClosePopupsOverWindow(apply_focus_window, false);
FocusWindow(apply_focus_window);
if (apply_focus_window->NavLastIds[0] == 0)
NavInitWindow(apply_focus_window, false);
// If the window only has a menu layer, select it directly
if (apply_focus_window->DC.NavLayerActiveMask == (1 << ImGuiNavLayer_Menu))
g.NavLayer = ImGuiNavLayer_Menu;
}
if (apply_focus_window)
g.NavWindowingTarget = NULL;
// Apply menu/layer toggle
if (apply_toggle_layer && g.NavWindow)
{
// Move to parent menu if necessary
ImGuiWindow* new_nav_window = g.NavWindow;
while (new_nav_window->ParentWindow
&& (new_nav_window->DC.NavLayerActiveMask & (1 << ImGuiNavLayer_Menu)) == 0
&& (new_nav_window->Flags & ImGuiWindowFlags_ChildWindow) != 0
&& (new_nav_window->Flags & (ImGuiWindowFlags_Popup | ImGuiWindowFlags_ChildMenu)) == 0)
new_nav_window = new_nav_window->ParentWindow;
if (new_nav_window != g.NavWindow)
{
ImGuiWindow* old_nav_window = g.NavWindow;
FocusWindow(new_nav_window);
new_nav_window->NavLastChildNavWindow = old_nav_window;
}
g.NavDisableHighlight = false;
g.NavDisableMouseHover = true;
// When entering a regular menu bar with the Alt key, we always reinitialize the navigation ID.
const ImGuiNavLayer new_nav_layer = (g.NavWindow->DC.NavLayerActiveMask & (1 << ImGuiNavLayer_Menu)) ? (ImGuiNavLayer)((int)g.NavLayer ^ 1) : ImGuiNavLayer_Main;
NavRestoreLayer(new_nav_layer);
}
}
// Window has already passed the IsWindowNavFocusable()
static const char* GetFallbackWindowNameForWindowingList(ImGuiWindow* window)
{
if (window->Flags & ImGuiWindowFlags_Popup)
return "(Popup)";
if ((window->Flags & ImGuiWindowFlags_MenuBar) && strcmp(window->Name, "##MainMenuBar") == 0)
return "(Main menu bar)";
return "(Untitled)";
}
// Overlay displayed when using CTRL+TAB. Called by EndFrame().
void ImGui::NavUpdateWindowingOverlay()
{
ImGuiContext& g = *GImGui;
IM_ASSERT(g.NavWindowingTarget != NULL);
if (g.NavWindowingTimer < NAV_WINDOWING_LIST_APPEAR_DELAY)
return;
if (g.NavWindowingList == NULL)
g.NavWindowingList = FindWindowByName("###NavWindowingList");
SetNextWindowSizeConstraints(ImVec2(g.IO.DisplaySize.x * 0.20f, g.IO.DisplaySize.y * 0.20f), ImVec2(FLT_MAX, FLT_MAX));
SetNextWindowPos(g.IO.DisplaySize * 0.5f, ImGuiCond_Always, ImVec2(0.5f, 0.5f));
PushStyleVar(ImGuiStyleVar_WindowPadding, g.Style.WindowPadding * 2.0f);
Begin("###NavWindowingList", NULL, ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoFocusOnAppearing | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoInputs | ImGuiWindowFlags_AlwaysAutoResize | ImGuiWindowFlags_NoSavedSettings);
for (int n = g.WindowsFocusOrder.Size - 1; n >= 0; n--)
{
ImGuiWindow* window = g.WindowsFocusOrder[n];
if (!IsWindowNavFocusable(window))
continue;
const char* label = window->Name;
if (label == FindRenderedTextEnd(label))
label = GetFallbackWindowNameForWindowingList(window);
Selectable(label, g.NavWindowingTarget == window);
}
End();
PopStyleVar();
}
//-----------------------------------------------------------------------------
// [SECTION] DRAG AND DROP
//-----------------------------------------------------------------------------
void ImGui::ClearDragDrop()
{
ImGuiContext& g = *GImGui;
g.DragDropActive = false;
g.DragDropPayload.Clear();
g.DragDropAcceptFlags = ImGuiDragDropFlags_None;
g.DragDropAcceptIdCurr = g.DragDropAcceptIdPrev = 0;
g.DragDropAcceptIdCurrRectSurface = FLT_MAX;
g.DragDropAcceptFrameCount = -1;
g.DragDropPayloadBufHeap.clear();
memset(&g.DragDropPayloadBufLocal, 0, sizeof(g.DragDropPayloadBufLocal));
}
// Call when current ID is active.
// When this returns true you need to: a) call SetDragDropPayload() exactly once, b) you may render the payload visual/description, c) call EndDragDropSource()
bool ImGui::BeginDragDropSource(ImGuiDragDropFlags flags)
{
ImGuiContext& g = *GImGui;
ImGuiWindow* window = g.CurrentWindow;
bool source_drag_active = false;
ImGuiID source_id = 0;
ImGuiID source_parent_id = 0;
ImGuiMouseButton mouse_button = ImGuiMouseButton_Left;
if (!(flags & ImGuiDragDropFlags_SourceExtern))
{
source_id = window->DC.LastItemId;
if (source_id != 0 && g.ActiveId != source_id) // Early out for most common case
return false;
if (g.IO.MouseDown[mouse_button] == false)
return false;
if (source_id == 0)
{
// If you want to use BeginDragDropSource() on an item with no unique identifier for interaction, such as Text() or Image(), you need to:
// A) Read the explanation below, B) Use the ImGuiDragDropFlags_SourceAllowNullID flag, C) Swallow your programmer pride.
if (!(flags & ImGuiDragDropFlags_SourceAllowNullID))
{
IM_ASSERT(0);
return false;
}
// Early out
if ((window->DC.LastItemStatusFlags & ImGuiItemStatusFlags_HoveredRect) == 0 && (g.ActiveId == 0 || g.ActiveIdWindow != window))
return false;
// Magic fallback (=somehow reprehensible) to handle items with no assigned ID, e.g. Text(), Image()
// We build a throwaway ID based on current ID stack + relative AABB of items in window.
// THE IDENTIFIER WON'T SURVIVE ANY REPOSITIONING OF THE WIDGET, so if your widget moves your dragging operation will be canceled.
// We don't need to maintain/call ClearActiveID() as releasing the button will early out this function and trigger !ActiveIdIsAlive.
source_id = window->DC.LastItemId = window->GetIDFromRectangle(window->DC.LastItemRect);
bool is_hovered = ItemHoverable(window->DC.LastItemRect, source_id);
if (is_hovered && g.IO.MouseClicked[mouse_button])
{
SetActiveID(source_id, window);
FocusWindow(window);
}
if (g.ActiveId == source_id) // Allow the underlying widget to display/return hovered during the mouse release frame, else we would get a flicker.
g.ActiveIdAllowOverlap = is_hovered;
}
else
{
g.ActiveIdAllowOverlap = false;
}
if (g.ActiveId != source_id)
return false;
source_parent_id = window->IDStack.back();
source_drag_active = IsMouseDragging(mouse_button);
// Disable navigation and key inputs while dragging
g.ActiveIdUsingNavDirMask = ~(ImU32)0;
g.ActiveIdUsingNavInputMask = ~(ImU32)0;
g.ActiveIdUsingKeyInputMask = ~(ImU64)0;
}
else
{
window = NULL;
source_id = ImHashStr("#SourceExtern");
source_drag_active = true;
}
if (source_drag_active)
{
if (!g.DragDropActive)
{
IM_ASSERT(source_id != 0);
ClearDragDrop();
ImGuiPayload& payload = g.DragDropPayload;
payload.SourceId = source_id;
payload.SourceParentId = source_parent_id;
g.DragDropActive = true;
g.DragDropSourceFlags = flags;
g.DragDropMouseButton = mouse_button;
}
g.DragDropSourceFrameCount = g.FrameCount;
g.DragDropWithinSource = true;
if (!(flags & ImGuiDragDropFlags_SourceNoPreviewTooltip))
{
// Target can request the Source to not display its tooltip (we use a dedicated flag to make this request explicit)
// We unfortunately can't just modify the source flags and skip the call to BeginTooltip, as caller may be emitting contents.
BeginTooltip();
if (g.DragDropAcceptIdPrev && (g.DragDropAcceptFlags & ImGuiDragDropFlags_AcceptNoPreviewTooltip))
{
ImGuiWindow* tooltip_window = g.CurrentWindow;
tooltip_window->SkipItems = true;
tooltip_window->HiddenFramesCanSkipItems = 1;
}
}
if (!(flags & ImGuiDragDropFlags_SourceNoDisableHover) && !(flags & ImGuiDragDropFlags_SourceExtern))
window->DC.LastItemStatusFlags &= ~ImGuiItemStatusFlags_HoveredRect;
return true;
}
return false;
}
void ImGui::EndDragDropSource()
{
ImGuiContext& g = *GImGui;
IM_ASSERT(g.DragDropActive);
IM_ASSERT(g.DragDropWithinSource && "Not after a BeginDragDropSource()?");
if (!(g.DragDropSourceFlags & ImGuiDragDropFlags_SourceNoPreviewTooltip))
EndTooltip();
// Discard the drag if have not called SetDragDropPayload()
if (g.DragDropPayload.DataFrameCount == -1)
ClearDragDrop();
g.DragDropWithinSource = false;
}
// Use 'cond' to choose to submit payload on drag start or every frame
bool ImGui::SetDragDropPayload(const char* type, const void* data, size_t data_size, ImGuiCond cond)
{
ImGuiContext& g = *GImGui;
ImGuiPayload& payload = g.DragDropPayload;
if (cond == 0)
cond = ImGuiCond_Always;
IM_ASSERT(type != NULL);
IM_ASSERT(strlen(type) < IM_ARRAYSIZE(payload.DataType) && "Payload type can be at most 32 characters long");
IM_ASSERT((data != NULL && data_size > 0) || (data == NULL && data_size == 0));
IM_ASSERT(cond == ImGuiCond_Always || cond == ImGuiCond_Once);
IM_ASSERT(payload.SourceId != 0); // Not called between BeginDragDropSource() and EndDragDropSource()
if (cond == ImGuiCond_Always || payload.DataFrameCount == -1)
{
// Copy payload
ImStrncpy(payload.DataType, type, IM_ARRAYSIZE(payload.DataType));
g.DragDropPayloadBufHeap.resize(0);
if (data_size > sizeof(g.DragDropPayloadBufLocal))
{
// Store in heap
g.DragDropPayloadBufHeap.resize((int)data_size);
payload.Data = g.DragDropPayloadBufHeap.Data;
memcpy(payload.Data, data, data_size);
}
else if (data_size > 0)
{
// Store locally
memset(&g.DragDropPayloadBufLocal, 0, sizeof(g.DragDropPayloadBufLocal));
payload.Data = g.DragDropPayloadBufLocal;
memcpy(payload.Data, data, data_size);
}
else
{
payload.Data = NULL;
}
payload.DataSize = (int)data_size;
}
payload.DataFrameCount = g.FrameCount;
return (g.DragDropAcceptFrameCount == g.FrameCount) || (g.DragDropAcceptFrameCount == g.FrameCount - 1);
}
bool ImGui::BeginDragDropTargetCustom(const ImRect& bb, ImGuiID id)
{
ImGuiContext& g = *GImGui;
if (!g.DragDropActive)
return false;
ImGuiWindow* window = g.CurrentWindow;
if (g.HoveredWindow == NULL || window->RootWindow != g.HoveredWindow->RootWindow)
return false;
IM_ASSERT(id != 0);
if (!IsMouseHoveringRect(bb.Min, bb.Max) || (id == g.DragDropPayload.SourceId))
return false;
if (window->SkipItems)
return false;
IM_ASSERT(g.DragDropWithinTarget == false);
g.DragDropTargetRect = bb;
g.DragDropTargetId = id;
g.DragDropWithinTarget = true;
return true;
}
// We don't use BeginDragDropTargetCustom() and duplicate its code because:
// 1) we use LastItemRectHoveredRect which handles items that pushes a temporarily clip rectangle in their code. Calling BeginDragDropTargetCustom(LastItemRect) would not handle them.
// 2) and it's faster. as this code may be very frequently called, we want to early out as fast as we can.
// Also note how the HoveredWindow test is positioned differently in both functions (in both functions we optimize for the cheapest early out case)
bool ImGui::BeginDragDropTarget()
{
ImGuiContext& g = *GImGui;
if (!g.DragDropActive)
return false;
ImGuiWindow* window = g.CurrentWindow;
if (!(window->DC.LastItemStatusFlags & ImGuiItemStatusFlags_HoveredRect))
return false;
if (g.HoveredWindow == NULL || window->RootWindow != g.HoveredWindow->RootWindow)
return false;
const ImRect& display_rect = (window->DC.LastItemStatusFlags & ImGuiItemStatusFlags_HasDisplayRect) ? window->DC.LastItemDisplayRect : window->DC.LastItemRect;
ImGuiID id = window->DC.LastItemId;
if (id == 0)
id = window->GetIDFromRectangle(display_rect);
if (g.DragDropPayload.SourceId == id)
return false;
IM_ASSERT(g.DragDropWithinTarget == false);
g.DragDropTargetRect = display_rect;
g.DragDropTargetId = id;
g.DragDropWithinTarget = true;
return true;
}
bool ImGui::IsDragDropPayloadBeingAccepted()
{
ImGuiContext& g = *GImGui;
return g.DragDropActive && g.DragDropAcceptIdPrev != 0;
}
const ImGuiPayload* ImGui::AcceptDragDropPayload(const char* type, ImGuiDragDropFlags flags)
{
ImGuiContext& g = *GImGui;
ImGuiWindow* window = g.CurrentWindow;
ImGuiPayload& payload = g.DragDropPayload;
IM_ASSERT(g.DragDropActive); // Not called between BeginDragDropTarget() and EndDragDropTarget() ?
IM_ASSERT(payload.DataFrameCount != -1); // Forgot to call EndDragDropTarget() ?
if (type != NULL && !payload.IsDataType(type))
return NULL;
// Accept smallest drag target bounding box, this allows us to nest drag targets conveniently without ordering constraints.
// NB: We currently accept NULL id as target. However, overlapping targets requires a unique ID to function!
const bool was_accepted_previously = (g.DragDropAcceptIdPrev == g.DragDropTargetId);
ImRect r = g.DragDropTargetRect;
float r_surface = r.GetWidth() * r.GetHeight();
if (r_surface < g.DragDropAcceptIdCurrRectSurface)
{
g.DragDropAcceptFlags = flags;
g.DragDropAcceptIdCurr = g.DragDropTargetId;
g.DragDropAcceptIdCurrRectSurface = r_surface;
}
// Render default drop visuals
payload.Preview = was_accepted_previously;
flags |= (g.DragDropSourceFlags & ImGuiDragDropFlags_AcceptNoDrawDefaultRect); // Source can also inhibit the preview (useful for external sources that lives for 1 frame)
if (!(flags & ImGuiDragDropFlags_AcceptNoDrawDefaultRect) && payload.Preview)
{
// FIXME-DRAG: Settle on a proper default visuals for drop target.
r.Expand(3.5f);
bool push_clip_rect = !window->ClipRect.Contains(r);
if (push_clip_rect) window->DrawList->PushClipRect(r.Min-ImVec2(1,1), r.Max+ImVec2(1,1));
window->DrawList->AddRect(r.Min, r.Max, GetColorU32(ImGuiCol_DragDropTarget), 0.0f, ~0, 2.0f);
if (push_clip_rect) window->DrawList->PopClipRect();
}
g.DragDropAcceptFrameCount = g.FrameCount;
payload.Delivery = was_accepted_previously && !IsMouseDown(g.DragDropMouseButton); // For extern drag sources affecting os window focus, it's easier to just test !IsMouseDown() instead of IsMouseReleased()
if (!payload.Delivery && !(flags & ImGuiDragDropFlags_AcceptBeforeDelivery))
return NULL;
return &payload;
}
const ImGuiPayload* ImGui::GetDragDropPayload()
{
ImGuiContext& g = *GImGui;
return g.DragDropActive ? &g.DragDropPayload : NULL;
}
// We don't really use/need this now, but added it for the sake of consistency and because we might need it later.
void ImGui::EndDragDropTarget()
{
ImGuiContext& g = *GImGui;
IM_ASSERT(g.DragDropActive);
IM_ASSERT(g.DragDropWithinTarget);
g.DragDropWithinTarget = false;
}
//-----------------------------------------------------------------------------
// [SECTION] LOGGING/CAPTURING
//-----------------------------------------------------------------------------
// All text output from the interface can be captured into tty/file/clipboard.
// By default, tree nodes are automatically opened during logging.
//-----------------------------------------------------------------------------
// Pass text data straight to log (without being displayed)
void ImGui::LogText(const char* fmt, ...)
{
ImGuiContext& g = *GImGui;
if (!g.LogEnabled)
return;
va_list args;
va_start(args, fmt);
if (g.LogFile)
{
g.LogBuffer.Buf.resize(0);
g.LogBuffer.appendfv(fmt, args);
ImFileWrite(g.LogBuffer.c_str(), sizeof(char), (ImU64)g.LogBuffer.size(), g.LogFile);
}
else
{
g.LogBuffer.appendfv(fmt, args);
}
va_end(args);
}
// Internal version that takes a position to decide on newline placement and pad items according to their depth.
// We split text into individual lines to add current tree level padding
void ImGui::LogRenderedText(const ImVec2* ref_pos, const char* text, const char* text_end)
{
ImGuiContext& g = *GImGui;
ImGuiWindow* window = g.CurrentWindow;
if (!text_end)
text_end = FindRenderedTextEnd(text, text_end);
const bool log_new_line = ref_pos && (ref_pos->y > g.LogLinePosY + 1);
if (ref_pos)
g.LogLinePosY = ref_pos->y;
if (log_new_line)
g.LogLineFirstItem = true;
const char* text_remaining = text;
if (g.LogDepthRef > window->DC.TreeDepth) // Re-adjust padding if we have popped out of our starting depth
g.LogDepthRef = window->DC.TreeDepth;
const int tree_depth = (window->DC.TreeDepth - g.LogDepthRef);
for (;;)
{
// Split the string. Each new line (after a '\n') is followed by spacing corresponding to the current depth of our log entry.
// We don't add a trailing \n to allow a subsequent item on the same line to be captured.
const char* line_start = text_remaining;
const char* line_end = ImStreolRange(line_start, text_end);
const bool is_first_line = (line_start == text);
const bool is_last_line = (line_end == text_end);
if (!is_last_line || (line_start != line_end))
{
const int char_count = (int)(line_end - line_start);
if (log_new_line || !is_first_line)
LogText(IM_NEWLINE "%*s%.*s", tree_depth * 4, "", char_count, line_start);
else if (g.LogLineFirstItem)
LogText("%*s%.*s", tree_depth * 4, "", char_count, line_start);
else
LogText(" %.*s", char_count, line_start);
g.LogLineFirstItem = false;
}
else if (log_new_line)
{
// An empty "" string at a different Y position should output a carriage return.
LogText(IM_NEWLINE);
break;
}
if (is_last_line)
break;
text_remaining = line_end + 1;
}
}
// Start logging/capturing text output
void ImGui::LogBegin(ImGuiLogType type, int auto_open_depth)
{
ImGuiContext& g = *GImGui;
ImGuiWindow* window = g.CurrentWindow;
IM_ASSERT(g.LogEnabled == false);
IM_ASSERT(g.LogFile == NULL);
IM_ASSERT(g.LogBuffer.empty());
g.LogEnabled = true;
g.LogType = type;
g.LogDepthRef = window->DC.TreeDepth;
g.LogDepthToExpand = ((auto_open_depth >= 0) ? auto_open_depth : g.LogDepthToExpandDefault);
g.LogLinePosY = FLT_MAX;
g.LogLineFirstItem = true;
}
void ImGui::LogToTTY(int auto_open_depth)
{
ImGuiContext& g = *GImGui;
if (g.LogEnabled)
return;
IM_UNUSED(auto_open_depth);
#ifndef IMGUI_DISABLE_TTY_FUNCTIONS
LogBegin(ImGuiLogType_TTY, auto_open_depth);
g.LogFile = stdout;
#endif
}
// Start logging/capturing text output to given file
void ImGui::LogToFile(int auto_open_depth, const char* filename)
{
ImGuiContext& g = *GImGui;
if (g.LogEnabled)
return;
// FIXME: We could probably open the file in text mode "at", however note that clipboard/buffer logging will still
// be subject to outputting OS-incompatible carriage return if within strings the user doesn't use IM_NEWLINE.
// By opening the file in binary mode "ab" we have consistent output everywhere.
if (!filename)
filename = g.IO.LogFilename;
if (!filename || !filename[0])
return;
ImFileHandle f = ImFileOpen(filename, "ab");
if (!f)
{
IM_ASSERT(0);
return;
}
LogBegin(ImGuiLogType_File, auto_open_depth);
g.LogFile = f;
}
// Start logging/capturing text output to clipboard
void ImGui::LogToClipboard(int auto_open_depth)
{
ImGuiContext& g = *GImGui;
if (g.LogEnabled)
return;
LogBegin(ImGuiLogType_Clipboard, auto_open_depth);
}
void ImGui::LogToBuffer(int auto_open_depth)
{
ImGuiContext& g = *GImGui;
if (g.LogEnabled)
return;
LogBegin(ImGuiLogType_Buffer, auto_open_depth);
}
void ImGui::LogFinish()
{
ImGuiContext& g = *GImGui;
if (!g.LogEnabled)
return;
LogText(IM_NEWLINE);
switch (g.LogType)
{
case ImGuiLogType_TTY:
#ifndef IMGUI_DISABLE_TTY_FUNCTIONS
fflush(g.LogFile);
#endif
break;
case ImGuiLogType_File:
ImFileClose(g.LogFile);
break;
case ImGuiLogType_Buffer:
break;
case ImGuiLogType_Clipboard:
if (!g.LogBuffer.empty())
SetClipboardText(g.LogBuffer.begin());
break;
case ImGuiLogType_None:
IM_ASSERT(0);
break;
}
g.LogEnabled = false;
g.LogType = ImGuiLogType_None;
g.LogFile = NULL;
g.LogBuffer.clear();
}
// Helper to display logging buttons
// FIXME-OBSOLETE: We should probably obsolete this and let the user have their own helper (this is one of the oldest function alive!)
void ImGui::LogButtons()
{
ImGuiContext& g = *GImGui;
PushID("LogButtons");
#ifndef IMGUI_DISABLE_TTY_FUNCTIONS
const bool log_to_tty = Button("Log To TTY"); SameLine();
#else
const bool log_to_tty = false;
#endif
const bool log_to_file = Button("Log To File"); SameLine();
const bool log_to_clipboard = Button("Log To Clipboard"); SameLine();
PushAllowKeyboardFocus(false);
SetNextItemWidth(80.0f);
SliderInt("Default Depth", &g.LogDepthToExpandDefault, 0, 9, NULL);
PopAllowKeyboardFocus();
PopID();
// Start logging at the end of the function so that the buttons don't appear in the log
if (log_to_tty)
LogToTTY();
if (log_to_file)
LogToFile();
if (log_to_clipboard)
LogToClipboard();
}
//-----------------------------------------------------------------------------
// [SECTION] SETTINGS
//-----------------------------------------------------------------------------
// Called by NewFrame()
void ImGui::UpdateSettings()
{
// Load settings on first frame (if not explicitly loaded manually before)
ImGuiContext& g = *GImGui;
if (!g.SettingsLoaded)
{
IM_ASSERT(g.SettingsWindows.empty());
if (g.IO.IniFilename)
LoadIniSettingsFromDisk(g.IO.IniFilename);
g.SettingsLoaded = true;
}
// Save settings (with a delay after the last modification, so we don't spam disk too much)
if (g.SettingsDirtyTimer > 0.0f)
{
g.SettingsDirtyTimer -= g.IO.DeltaTime;
if (g.SettingsDirtyTimer <= 0.0f)
{
if (g.IO.IniFilename != NULL)
SaveIniSettingsToDisk(g.IO.IniFilename);
else
g.IO.WantSaveIniSettings = true; // Let user know they can call SaveIniSettingsToMemory(). user will need to clear io.WantSaveIniSettings themselves.
g.SettingsDirtyTimer = 0.0f;
}
}
}
void ImGui::MarkIniSettingsDirty()
{
ImGuiContext& g = *GImGui;
if (g.SettingsDirtyTimer <= 0.0f)
g.SettingsDirtyTimer = g.IO.IniSavingRate;
}
void ImGui::MarkIniSettingsDirty(ImGuiWindow* window)
{
ImGuiContext& g = *GImGui;
if (!(window->Flags & ImGuiWindowFlags_NoSavedSettings))
if (g.SettingsDirtyTimer <= 0.0f)
g.SettingsDirtyTimer = g.IO.IniSavingRate;
}
ImGuiWindowSettings* ImGui::CreateNewWindowSettings(const char* name)
{
ImGuiContext& g = *GImGui;
#if !IMGUI_DEBUG_INI_SETTINGS
// Skip to the "###" marker if any. We don't skip past to match the behavior of GetID()
// Preserve the full string when IMGUI_DEBUG_INI_SETTINGS is set to make .ini inspection easier.
if (const char* p = strstr(name, "###"))
name = p;
#endif
const size_t name_len = strlen(name);
// Allocate chunk
const size_t chunk_size = sizeof(ImGuiWindowSettings) + name_len + 1;
ImGuiWindowSettings* settings = g.SettingsWindows.alloc_chunk(chunk_size);
IM_PLACEMENT_NEW(settings) ImGuiWindowSettings();
settings->ID = ImHashStr(name, name_len);
memcpy(settings->GetName(), name, name_len + 1); // Store with zero terminator
return settings;
}
ImGuiWindowSettings* ImGui::FindWindowSettings(ImGuiID id)
{
ImGuiContext& g = *GImGui;
for (ImGuiWindowSettings* settings = g.SettingsWindows.begin(); settings != NULL; settings = g.SettingsWindows.next_chunk(settings))
if (settings->ID == id)
return settings;
return NULL;
}
ImGuiWindowSettings* ImGui::FindOrCreateWindowSettings(const char* name)
{
if (ImGuiWindowSettings* settings = FindWindowSettings(ImHashStr(name)))
return settings;
return CreateNewWindowSettings(name);
}
void ImGui::LoadIniSettingsFromDisk(const char* ini_filename)
{
size_t file_data_size = 0;
char* file_data = (char*)ImFileLoadToMemory(ini_filename, "rb", &file_data_size);
if (!file_data)
return;
LoadIniSettingsFromMemory(file_data, (size_t)file_data_size);
IM_FREE(file_data);
}
ImGuiSettingsHandler* ImGui::FindSettingsHandler(const char* type_name)
{
ImGuiContext& g = *GImGui;
const ImGuiID type_hash = ImHashStr(type_name);
for (int handler_n = 0; handler_n < g.SettingsHandlers.Size; handler_n++)
if (g.SettingsHandlers[handler_n].TypeHash == type_hash)
return &g.SettingsHandlers[handler_n];
return NULL;
}
// Zero-tolerance, no error reporting, cheap .ini parsing
void ImGui::LoadIniSettingsFromMemory(const char* ini_data, size_t ini_size)
{
ImGuiContext& g = *GImGui;
IM_ASSERT(g.Initialized);
IM_ASSERT(g.SettingsLoaded == false && g.FrameCount == 0);
// For user convenience, we allow passing a non zero-terminated string (hence the ini_size parameter).
// For our convenience and to make the code simpler, we'll also write zero-terminators within the buffer. So let's create a writable copy..
if (ini_size == 0)
ini_size = strlen(ini_data);
char* buf = (char*)IM_ALLOC(ini_size + 1);
char* buf_end = buf + ini_size;
memcpy(buf, ini_data, ini_size);
buf[ini_size] = 0;
void* entry_data = NULL;
ImGuiSettingsHandler* entry_handler = NULL;
char* line_end = NULL;
for (char* line = buf; line < buf_end; line = line_end + 1)
{
// Skip new lines markers, then find end of the line
while (*line == '\n' || *line == '\r')
line++;
line_end = line;
while (line_end < buf_end && *line_end != '\n' && *line_end != '\r')
line_end++;
line_end[0] = 0;
if (line[0] == ';')
continue;
if (line[0] == '[' && line_end > line && line_end[-1] == ']')
{
// Parse "[Type][Name]". Note that 'Name' can itself contains [] characters, which is acceptable with the current format and parsing code.
line_end[-1] = 0;
const char* name_end = line_end - 1;
const char* type_start = line + 1;
char* type_end = (char*)(void*)ImStrchrRange(type_start, name_end, ']');
const char* name_start = type_end ? ImStrchrRange(type_end + 1, name_end, '[') : NULL;
if (!type_end || !name_start)
continue;
*type_end = 0; // Overwrite first ']'
name_start++; // Skip second '['
entry_handler = FindSettingsHandler(type_start);
entry_data = entry_handler ? entry_handler->ReadOpenFn(&g, entry_handler, name_start) : NULL;
}
else if (entry_handler != NULL && entry_data != NULL)
{
// Let type handler parse the line
entry_handler->ReadLineFn(&g, entry_handler, entry_data, line);
}
}
IM_FREE(buf);
g.SettingsLoaded = true;
}
void ImGui::SaveIniSettingsToDisk(const char* ini_filename)
{
ImGuiContext& g = *GImGui;
g.SettingsDirtyTimer = 0.0f;
if (!ini_filename)
return;
size_t ini_data_size = 0;
const char* ini_data = SaveIniSettingsToMemory(&ini_data_size);
ImFileHandle f = ImFileOpen(ini_filename, "wt");
if (!f)
return;
ImFileWrite(ini_data, sizeof(char), ini_data_size, f);
ImFileClose(f);
}
// Call registered handlers (e.g. SettingsHandlerWindow_WriteAll() + custom handlers) to write their stuff into a text buffer
const char* ImGui::SaveIniSettingsToMemory(size_t* out_size)
{
ImGuiContext& g = *GImGui;
g.SettingsDirtyTimer = 0.0f;
g.SettingsIniData.Buf.resize(0);
g.SettingsIniData.Buf.push_back(0);
for (int handler_n = 0; handler_n < g.SettingsHandlers.Size; handler_n++)
{
ImGuiSettingsHandler* handler = &g.SettingsHandlers[handler_n];
handler->WriteAllFn(&g, handler, &g.SettingsIniData);
}
if (out_size)
*out_size = (size_t)g.SettingsIniData.size();
return g.SettingsIniData.c_str();
}
static void* WindowSettingsHandler_ReadOpen(ImGuiContext*, ImGuiSettingsHandler*, const char* name)
{
ImGuiWindowSettings* settings = ImGui::FindWindowSettings(ImHashStr(name));
if (!settings)
settings = ImGui::CreateNewWindowSettings(name);
return (void*)settings;
}
static void WindowSettingsHandler_ReadLine(ImGuiContext*, ImGuiSettingsHandler*, void* entry, const char* line)
{
ImGuiWindowSettings* settings = (ImGuiWindowSettings*)entry;
int x, y;
int i;
if (sscanf(line, "Pos=%i,%i", &x, &y) == 2) settings->Pos = ImVec2ih((short)x, (short)y);
else if (sscanf(line, "Size=%i,%i", &x, &y) == 2) settings->Size = ImVec2ih((short)x, (short)y);
else if (sscanf(line, "Collapsed=%d", &i) == 1) settings->Collapsed = (i != 0);
}
static void WindowSettingsHandler_WriteAll(ImGuiContext* ctx, ImGuiSettingsHandler* handler, ImGuiTextBuffer* buf)
{
// Gather data from windows that were active during this session
// (if a window wasn't opened in this session we preserve its settings)
ImGuiContext& g = *ctx;
for (int i = 0; i != g.Windows.Size; i++)
{
ImGuiWindow* window = g.Windows[i];
if (window->Flags & ImGuiWindowFlags_NoSavedSettings)
continue;
ImGuiWindowSettings* settings = (window->SettingsOffset != -1) ? g.SettingsWindows.ptr_from_offset(window->SettingsOffset) : ImGui::FindWindowSettings(window->ID);
if (!settings)
{
settings = ImGui::CreateNewWindowSettings(window->Name);
window->SettingsOffset = g.SettingsWindows.offset_from_ptr(settings);
}
IM_ASSERT(settings->ID == window->ID);
settings->Pos = ImVec2ih((short)window->Pos.x, (short)window->Pos.y);
settings->Size = ImVec2ih((short)window->SizeFull.x, (short)window->SizeFull.y);
settings->Collapsed = window->Collapsed;
}
// Write to text buffer
buf->reserve(buf->size() + g.SettingsWindows.size() * 6); // ballpark reserve
for (ImGuiWindowSettings* settings = g.SettingsWindows.begin(); settings != NULL; settings = g.SettingsWindows.next_chunk(settings))
{
const char* settings_name = settings->GetName();
buf->appendf("[%s][%s]\n", handler->TypeName, settings_name);
buf->appendf("Pos=%d,%d\n", settings->Pos.x, settings->Pos.y);
buf->appendf("Size=%d,%d\n", settings->Size.x, settings->Size.y);
buf->appendf("Collapsed=%d\n", settings->Collapsed);
buf->append("\n");
}
}
//-----------------------------------------------------------------------------
// [SECTION] VIEWPORTS, PLATFORM WINDOWS
//-----------------------------------------------------------------------------
// (this section is filled in the 'docking' branch)
//-----------------------------------------------------------------------------
// [SECTION] DOCKING
//-----------------------------------------------------------------------------
// (this section is filled in the 'docking' branch)
//-----------------------------------------------------------------------------
// [SECTION] PLATFORM DEPENDENT HELPERS
//-----------------------------------------------------------------------------
#if defined(_WIN32) && !defined(IMGUI_DISABLE_WIN32_FUNCTIONS) && !defined(IMGUI_DISABLE_WIN32_DEFAULT_CLIPBOARD_FUNCTIONS)
#ifdef _MSC_VER
#pragma comment(lib, "user32")
#pragma comment(lib, "kernel32")
#endif
// Win32 clipboard implementation
static const char* GetClipboardTextFn_DefaultImpl(void*)
{
static ImVector<char> buf_local;
buf_local.clear();
if (!::OpenClipboard(NULL))
return NULL;
HANDLE wbuf_handle = ::GetClipboardData(CF_UNICODETEXT);
if (wbuf_handle == NULL)
{
::CloseClipboard();
return NULL;
}
if (const WCHAR* wbuf_global = (const WCHAR*)::GlobalLock(wbuf_handle))
{
int buf_len = ::WideCharToMultiByte(CP_UTF8, 0, wbuf_global, -1, NULL, 0, NULL, NULL);
buf_local.resize(buf_len);
::WideCharToMultiByte(CP_UTF8, 0, wbuf_global, -1, buf_local.Data, buf_len, NULL, NULL);
}
::GlobalUnlock(wbuf_handle);
::CloseClipboard();
return buf_local.Data;
}
static void SetClipboardTextFn_DefaultImpl(void*, const char* text)
{
if (!::OpenClipboard(NULL))
return;
const int wbuf_length = ::MultiByteToWideChar(CP_UTF8, 0, text, -1, NULL, 0);
HGLOBAL wbuf_handle = ::GlobalAlloc(GMEM_MOVEABLE, (SIZE_T)wbuf_length * sizeof(WCHAR));
if (wbuf_handle == NULL)
{
::CloseClipboard();
return;
}
WCHAR* wbuf_global = (WCHAR*)::GlobalLock(wbuf_handle);
::MultiByteToWideChar(CP_UTF8, 0, text, -1, wbuf_global, wbuf_length);
::GlobalUnlock(wbuf_handle);
::EmptyClipboard();
if (::SetClipboardData(CF_UNICODETEXT, wbuf_handle) == NULL)
::GlobalFree(wbuf_handle);
::CloseClipboard();
}
#elif defined(__APPLE__) && TARGET_OS_OSX && defined(IMGUI_ENABLE_OSX_DEFAULT_CLIPBOARD_FUNCTIONS)
#include <Carbon/Carbon.h> // Use old API to avoid need for separate .mm file
static PasteboardRef main_clipboard = 0;
// OSX clipboard implementation
// If you enable this you will need to add '-framework ApplicationServices' to your linker command-line!
static void SetClipboardTextFn_DefaultImpl(void*, const char* text)
{
if (!main_clipboard)
PasteboardCreate(kPasteboardClipboard, &main_clipboard);
PasteboardClear(main_clipboard);
CFDataRef cf_data = CFDataCreate(kCFAllocatorDefault, (const UInt8*)text, strlen(text));
if (cf_data)
{
PasteboardPutItemFlavor(main_clipboard, (PasteboardItemID)1, CFSTR("public.utf8-plain-text"), cf_data, 0);
CFRelease(cf_data);
}
}
static const char* GetClipboardTextFn_DefaultImpl(void*)
{
if (!main_clipboard)
PasteboardCreate(kPasteboardClipboard, &main_clipboard);
PasteboardSynchronize(main_clipboard);
ItemCount item_count = 0;
PasteboardGetItemCount(main_clipboard, &item_count);
for (ItemCount i = 0; i < item_count; i++)
{
PasteboardItemID item_id = 0;
PasteboardGetItemIdentifier(main_clipboard, i + 1, &item_id);
CFArrayRef flavor_type_array = 0;
PasteboardCopyItemFlavors(main_clipboard, item_id, &flavor_type_array);
for (CFIndex j = 0, nj = CFArrayGetCount(flavor_type_array); j < nj; j++)
{
CFDataRef cf_data;
if (PasteboardCopyItemFlavorData(main_clipboard, item_id, CFSTR("public.utf8-plain-text"), &cf_data) == noErr)
{
static ImVector<char> clipboard_text;
int length = (int)CFDataGetLength(cf_data);
clipboard_text.resize(length + 1);
CFDataGetBytes(cf_data, CFRangeMake(0, length), (UInt8*)clipboard_text.Data);
clipboard_text[length] = 0;
CFRelease(cf_data);
return clipboard_text.Data;
}
}
}
return NULL;
}
#else
// Local Dear ImGui-only clipboard implementation, if user hasn't defined better clipboard handlers.
static const char* GetClipboardTextFn_DefaultImpl(void*)
{
ImGuiContext& g = *GImGui;
return g.PrivateClipboard.empty() ? NULL : g.PrivateClipboard.begin();
}
static void SetClipboardTextFn_DefaultImpl(void*, const char* text)
{
ImGuiContext& g = *GImGui;
g.PrivateClipboard.clear();
const char* text_end = text + strlen(text);
g.PrivateClipboard.resize((int)(text_end - text) + 1);
memcpy(&g.PrivateClipboard[0], text, (size_t)(text_end - text));
g.PrivateClipboard[(int)(text_end - text)] = 0;
}
#endif
// Win32 API IME support (for Asian languages, etc.)
#if defined(_WIN32) && !defined(__GNUC__) && !defined(IMGUI_DISABLE_WIN32_FUNCTIONS) && !defined(IMGUI_DISABLE_WIN32_DEFAULT_IME_FUNCTIONS)
#include <imm.h>
#ifdef _MSC_VER
#pragma comment(lib, "imm32")
#endif
static void ImeSetInputScreenPosFn_DefaultImpl(int x, int y)
{
// Notify OS Input Method Editor of text input position
ImGuiIO& io = ImGui::GetIO();
if (HWND hwnd = (HWND)io.ImeWindowHandle)
if (HIMC himc = ::ImmGetContext(hwnd))
{
COMPOSITIONFORM cf;
cf.ptCurrentPos.x = x;
cf.ptCurrentPos.y = y;
cf.dwStyle = CFS_FORCE_POSITION;
::ImmSetCompositionWindow(himc, &cf);
::ImmReleaseContext(hwnd, himc);
}
}
#else
static void ImeSetInputScreenPosFn_DefaultImpl(int, int) {}
#endif
//-----------------------------------------------------------------------------
// [SECTION] METRICS/DEBUG WINDOW
//-----------------------------------------------------------------------------
#ifndef IMGUI_DISABLE_METRICS_WINDOW
// Avoid naming collision with imgui_demo.cpp's HelpMarker() for unity builds.
static void MetricsHelpMarker(const char* desc)
{
ImGui::TextDisabled("(?)");
if (ImGui::IsItemHovered())
{
ImGui::BeginTooltip();
ImGui::PushTextWrapPos(ImGui::GetFontSize() * 35.0f);
ImGui::TextUnformatted(desc);
ImGui::PopTextWrapPos();
ImGui::EndTooltip();
}
}
void ImGui::ShowMetricsWindow(bool* p_open)
{
if (!ImGui::Begin("Dear ImGui Metrics", p_open))
{
ImGui::End();
return;
}
// Debugging enums
enum { WRT_OuterRect, WRT_OuterRectClipped, WRT_InnerRect, WRT_InnerClipRect, WRT_WorkRect, WRT_Content, WRT_ContentRegionRect, WRT_Count }; // Windows Rect Type
const char* wrt_rects_names[WRT_Count] = { "OuterRect", "OuterRectClipped", "InnerRect", "InnerClipRect", "WorkRect", "Content", "ContentRegionRect" };
enum { TRT_OuterRect, TRT_WorkRect, TRT_HostClipRect, TRT_InnerClipRect, TRT_BackgroundClipRect, TRT_ColumnsRect, TRT_ColumnsClipRect, TRT_ColumnsContentHeadersUsed, TRT_ColumnsContentHeadersDesired, TRT_ColumnsContentRowsFrozen, TRT_ColumnsContentRowsUnfrozen, TRT_Count }; // Tables Rect Type
const char* trt_rects_names[TRT_Count] = { "OuterRect", "WorkRect", "HostClipRect", "InnerClipRect", "BackgroundClipRect", "ColumnsRect", "ColumnsClipRect", "ColumnsContentHeadersUsed", "ColumnsContentHeadersDesired", "ColumnsContentRowsFrozen", "ColumnsContentRowsUnfrozen" };
// State
static bool show_windows_rects = false;
static int show_windows_rect_type = WRT_WorkRect;
static bool show_windows_begin_order = false;
static bool show_tables_rects = false;
static int show_tables_rect_type = TRT_WorkRect;
static bool show_drawcmd_details = true;
// Basic info
ImGuiContext& g = *GImGui;
ImGuiIO& io = ImGui::GetIO();
ImGui::Text("Dear ImGui %s", ImGui::GetVersion());
ImGui::Text("Application average %.3f ms/frame (%.1f FPS)", 1000.0f / io.Framerate, io.Framerate);
ImGui::Text("%d vertices, %d indices (%d triangles)", io.MetricsRenderVertices, io.MetricsRenderIndices, io.MetricsRenderIndices / 3);
ImGui::Text("%d active windows (%d visible)", io.MetricsActiveWindows, io.MetricsRenderWindows);
ImGui::Text("%d active allocations", io.MetricsActiveAllocations);
ImGui::Separator();
// Helper functions to display common structures:
// - NodeDrawList()
// - NodeColumns()
// - NodeWindow()
// - NodeWindows()
// - NodeTabBar()
// - NodeStorage()
struct Funcs
{
static ImRect GetWindowRect(ImGuiWindow* window, int rect_type)
{
if (rect_type == WRT_OuterRect) { return window->Rect(); }
else if (rect_type == WRT_OuterRectClipped) { return window->OuterRectClipped; }
else if (rect_type == WRT_InnerRect) { return window->InnerRect; }
else if (rect_type == WRT_InnerClipRect) { return window->InnerClipRect; }
else if (rect_type == WRT_WorkRect) { return window->WorkRect; }
else if (rect_type == WRT_Content) { ImVec2 min = window->InnerRect.Min - window->Scroll + window->WindowPadding; return ImRect(min, min + window->ContentSize); }
else if (rect_type == WRT_ContentRegionRect) { return window->ContentRegionRect; }
IM_ASSERT(0);
return ImRect();
}
static void NodeDrawList(ImGuiWindow* window, ImDrawList* draw_list, const char* label)
{
bool node_open = ImGui::TreeNode(draw_list, "%s: '%s' %d vtx, %d indices, %d cmds", label, draw_list->_OwnerName ? draw_list->_OwnerName : "", draw_list->VtxBuffer.Size, draw_list->IdxBuffer.Size, draw_list->CmdBuffer.Size);
if (draw_list == ImGui::GetWindowDrawList())
{
ImGui::SameLine();
ImGui::TextColored(ImVec4(1.0f,0.4f,0.4f,1.0f), "CURRENTLY APPENDING"); // Can't display stats for active draw list! (we don't have the data double-buffered)
if (node_open) ImGui::TreePop();
return;
}
ImDrawList* fg_draw_list = GetForegroundDrawList(window); // Render additional visuals into the top-most draw list
if (window && IsItemHovered())
fg_draw_list->AddRect(window->Pos, window->Pos + window->Size, IM_COL32(255, 255, 0, 255));
if (!node_open)
return;
if (window && !window->WasActive)
ImGui::TextDisabled("Warning: owning Window is inactive. This DrawList is not being rendered!");
unsigned int elem_offset = 0;
for (const ImDrawCmd* pcmd = draw_list->CmdBuffer.begin(); pcmd < draw_list->CmdBuffer.end(); elem_offset += pcmd->ElemCount, pcmd++)
{
if (pcmd->UserCallback == NULL && pcmd->ElemCount == 0)
continue;
if (pcmd->UserCallback)
{
ImGui::BulletText("Callback %p, user_data %p", pcmd->UserCallback, pcmd->UserCallbackData);
continue;
}
ImDrawIdx* idx_buffer = (draw_list->IdxBuffer.Size > 0) ? draw_list->IdxBuffer.Data : NULL;
char buf[300];
ImFormatString(buf, IM_ARRAYSIZE(buf), "DrawCmd: %4d triangles, Tex 0x%p, ClipRect (%4.0f,%4.0f)-(%4.0f,%4.0f)",
pcmd->ElemCount/3, (void*)(intptr_t)pcmd->TextureId,
pcmd->ClipRect.x, pcmd->ClipRect.y, pcmd->ClipRect.z, pcmd->ClipRect.w);
bool pcmd_node_open = ImGui::TreeNode((void*)(pcmd - draw_list->CmdBuffer.begin()), "%s", buf);
if (show_drawcmd_details && fg_draw_list && ImGui::IsItemHovered())
{
ImRect clip_rect = pcmd->ClipRect;
ImRect vtxs_rect(FLT_MAX, FLT_MAX, -FLT_MAX, -FLT_MAX);
for (unsigned int i = elem_offset; i < elem_offset + (int)pcmd->ElemCount; i++)
vtxs_rect.Add(draw_list->VtxBuffer[idx_buffer ? idx_buffer[i] : i].pos);
fg_draw_list->AddRect(ImFloor(clip_rect.Min), ImFloor(clip_rect.Max), IM_COL32(255,0,255,255));
fg_draw_list->AddRect(ImFloor(vtxs_rect.Min), ImFloor(vtxs_rect.Max), IM_COL32(255,255,0,255));
}
if (!pcmd_node_open)
continue;
// Calculate approximate coverage area (touched pixel count)
// This will be in pixels squared as long there's no post-scaling happening to the renderer output.
float total_area = 0.0f;
for (unsigned int base_idx = elem_offset; base_idx < (elem_offset + pcmd->ElemCount); base_idx += 3)
{
ImVec2 triangle[3];
for (int n = 0; n < 3; n++)
triangle[n] = draw_list->VtxBuffer[idx_buffer ? idx_buffer[base_idx + n] : (base_idx + n)].pos;
total_area += ImTriangleArea(triangle[0], triangle[1], triangle[2]);
}
// Display vertex information summary. Hover to get all triangles drawn in wire-frame
ImFormatString(buf, IM_ARRAYSIZE(buf), "Mesh: ElemCount: %d, VtxOffset: +%d, IdxOffset: +%d, Area: ~%0.f px", pcmd->ElemCount, pcmd->VtxOffset, pcmd->IdxOffset, total_area);
ImGui::Selectable(buf);
if (fg_draw_list && ImGui::IsItemHovered() && show_drawcmd_details)
{
// Draw wire-frame version of everything
ImDrawListFlags backup_flags = fg_draw_list->Flags;
fg_draw_list->Flags &= ~ImDrawListFlags_AntiAliasedLines; // Disable AA on triangle outlines is more readable for very large and thin triangles.
ImRect clip_rect = pcmd->ClipRect;
fg_draw_list->AddRect(ImFloor(clip_rect.Min), ImFloor(clip_rect.Max), IM_COL32(255, 0, 255, 255));
for (unsigned int base_idx = elem_offset; base_idx < (elem_offset + pcmd->ElemCount); base_idx += 3)
{
ImVec2 triangle[3];
for (int n = 0; n < 3; n++)
triangle[n] = draw_list->VtxBuffer[idx_buffer ? idx_buffer[base_idx + n] : (base_idx + n)].pos;
fg_draw_list->AddPolyline(triangle, 3, IM_COL32(255, 255, 0, 255), true, 1.0f);
}
fg_draw_list->Flags = backup_flags;
}
// Display individual triangles/vertices. Hover on to get the corresponding triangle highlighted.
ImGuiListClipper clipper(pcmd->ElemCount/3); // Manually coarse clip our print out of individual vertices to save CPU, only items that may be visible.
while (clipper.Step())
for (int prim = clipper.DisplayStart, idx_i = elem_offset + clipper.DisplayStart*3; prim < clipper.DisplayEnd; prim++)
{
char *buf_p = buf, *buf_end = buf + IM_ARRAYSIZE(buf);
ImVec2 triangle[3];
for (int n = 0; n < 3; n++, idx_i++)
{
ImDrawVert& v = draw_list->VtxBuffer[idx_buffer ? idx_buffer[idx_i] : idx_i];
triangle[n] = v.pos;
buf_p += ImFormatString(buf_p, buf_end - buf_p, "%s %04d: pos (%8.2f,%8.2f), uv (%.6f,%.6f), col %08X\n",
(n == 0) ? "Vert:" : " ", idx_i, v.pos.x, v.pos.y, v.uv.x, v.uv.y, v.col);
}
ImGui::Selectable(buf, false);
if (fg_draw_list && ImGui::IsItemHovered())
{
ImDrawListFlags backup_flags = fg_draw_list->Flags;
fg_draw_list->Flags &= ~ImDrawListFlags_AntiAliasedLines; // Disable AA on triangle outlines is more readable for very large and thin triangles.
fg_draw_list->AddPolyline(triangle, 3, IM_COL32(255,255,0,255), true, 1.0f);
fg_draw_list->Flags = backup_flags;
}
}
ImGui::TreePop();
}
ImGui::TreePop();
}
static void NodeColumns(const ImGuiColumns* columns)
{
if (!ImGui::TreeNode((void*)(uintptr_t)columns->ID, "Columns Id: 0x%08X, Count: %d, Flags: 0x%04X", columns->ID, columns->Count, columns->Flags))
return;
ImGui::BulletText("Width: %.1f (MinX: %.1f, MaxX: %.1f)", columns->OffMaxX - columns->OffMinX, columns->OffMinX, columns->OffMaxX);
for (int column_n = 0; column_n < columns->Columns.Size; column_n++)
ImGui::BulletText("Column %02d: OffsetNorm %.3f (= %.1f px)", column_n, columns->Columns[column_n].OffsetNorm, GetColumnOffsetFromNorm(columns, columns->Columns[column_n].OffsetNorm));
ImGui::TreePop();
}
static void NodeWindows(ImVector<ImGuiWindow*>& windows, const char* label)
{
if (!ImGui::TreeNode(label, "%s (%d)", label, windows.Size))
return;
for (int i = 0; i < windows.Size; i++)
{
ImGui::PushID(windows[i]);
Funcs::NodeWindow(windows[i], "Window");
ImGui::PopID();
}
ImGui::TreePop();
}
static void NodeWindow(ImGuiWindow* window, const char* label)
{
if (window == NULL)
{
ImGui::BulletText("%s: NULL", label);
return;
}
bool open = ImGui::TreeNode(label, "%s '%s', %d @ 0x%p", label, window->Name, (window->Active || window->WasActive), window);
if (ImGui::IsItemHovered() && window->WasActive)
ImGui::GetForegroundDrawList()->AddRect(window->Pos, window->Pos + window->Size, IM_COL32(255, 255, 0, 255));
if (!open)
return;
ImGuiWindowFlags flags = window->Flags;
NodeDrawList(window, window->DrawList, "DrawList");
ImGui::BulletText("Pos: (%.1f,%.1f), Size: (%.1f,%.1f), ContentSize (%.1f,%.1f)", window->Pos.x, window->Pos.y, window->Size.x, window->Size.y, window->ContentSize.x, window->ContentSize.y);
ImGui::BulletText("Flags: 0x%08X (%s%s%s%s%s%s%s%s%s..)", flags,
(flags & ImGuiWindowFlags_ChildWindow) ? "Child " : "", (flags & ImGuiWindowFlags_Tooltip) ? "Tooltip " : "", (flags & ImGuiWindowFlags_Popup) ? "Popup " : "",
(flags & ImGuiWindowFlags_Modal) ? "Modal " : "", (flags & ImGuiWindowFlags_ChildMenu) ? "ChildMenu " : "", (flags & ImGuiWindowFlags_NoSavedSettings) ? "NoSavedSettings " : "",
(flags & ImGuiWindowFlags_NoMouseInputs)? "NoMouseInputs":"", (flags & ImGuiWindowFlags_NoNavInputs) ? "NoNavInputs" : "", (flags & ImGuiWindowFlags_AlwaysAutoResize) ? "AlwaysAutoResize" : "");
ImGui::BulletText("Scroll: (%.2f/%.2f,%.2f/%.2f) Scrollbar:%s%s", window->Scroll.x, window->ScrollMax.x, window->Scroll.y, window->ScrollMax.y, window->ScrollbarX ? "X" : "", window->ScrollbarY ? "Y" : "");
ImGui::BulletText("Active: %d/%d, WriteAccessed: %d, BeginOrderWithinContext: %d", window->Active, window->WasActive, window->WriteAccessed, (window->Active || window->WasActive) ? window->BeginOrderWithinContext : -1);
ImGui::BulletText("Appearing: %d, Hidden: %d (CanSkip %d Cannot %d), SkipItems: %d", window->Appearing, window->Hidden, window->HiddenFramesCanSkipItems, window->HiddenFramesCannotSkipItems, window->SkipItems);
ImGui::BulletText("NavLastIds: 0x%08X,0x%08X, NavLayerActiveMask: %X", window->NavLastIds[0], window->NavLastIds[1], window->DC.NavLayerActiveMask);
ImGui::BulletText("NavLastChildNavWindow: %s", window->NavLastChildNavWindow ? window->NavLastChildNavWindow->Name : "NULL");
if (!window->NavRectRel[0].IsInverted())
ImGui::BulletText("NavRectRel[0]: (%.1f,%.1f)(%.1f,%.1f)", window->NavRectRel[0].Min.x, window->NavRectRel[0].Min.y, window->NavRectRel[0].Max.x, window->NavRectRel[0].Max.y);
else
ImGui::BulletText("NavRectRel[0]: <None>");
if (window->RootWindow != window) NodeWindow(window->RootWindow, "RootWindow");
if (window->ParentWindow != NULL) NodeWindow(window->ParentWindow, "ParentWindow");
if (window->DC.ChildWindows.Size > 0) NodeWindows(window->DC.ChildWindows, "ChildWindows");
if (window->ColumnsStorage.Size > 0 && ImGui::TreeNode("Columns", "Columns sets (%d)", window->ColumnsStorage.Size))
{
for (int n = 0; n < window->ColumnsStorage.Size; n++)
NodeColumns(&window->ColumnsStorage[n]);
ImGui::TreePop();
}
NodeStorage(&window->StateStorage, "Storage");
ImGui::TreePop();
}
static void NodeTabBar(ImGuiTabBar* tab_bar)
{
// Standalone tab bars (not associated to docking/windows functionality) currently hold no discernible strings.
char buf[256];
char* p = buf;
const char* buf_end = buf + IM_ARRAYSIZE(buf);
p += ImFormatString(p, buf_end - p, "TabBar (%d tabs)%s", tab_bar->Tabs.Size, (tab_bar->PrevFrameVisible < ImGui::GetFrameCount() - 2) ? " *Inactive*" : "");
if (ImGui::TreeNode(tab_bar, "%s", buf))
{
for (int tab_n = 0; tab_n < tab_bar->Tabs.Size; tab_n++)
{
const ImGuiTabItem* tab = &tab_bar->Tabs[tab_n];
ImGui::PushID(tab);
if (ImGui::SmallButton("<")) { TabBarQueueChangeTabOrder(tab_bar, tab, -1); } ImGui::SameLine(0, 2);
if (ImGui::SmallButton(">")) { TabBarQueueChangeTabOrder(tab_bar, tab, +1); } ImGui::SameLine();
ImGui::Text("%02d%c Tab 0x%08X '%s'", tab_n, (tab->ID == tab_bar->SelectedTabId) ? '*' : ' ', tab->ID, (tab->NameOffset != -1) ? tab_bar->GetTabName(tab) : "");
ImGui::PopID();
}
ImGui::TreePop();
}
}
static void NodeStorage(ImGuiStorage* storage, const char* label)
{
if (!ImGui::TreeNode(label, "%s: %d entries, %d bytes", label, storage->Data.Size, storage->Data.size_in_bytes()))
return;
for (int n = 0; n < storage->Data.Size; n++)
{
const ImGuiStorage::ImGuiStoragePair& p = storage->Data[n];
ImGui::BulletText("Key 0x%08X Value { i: %d }", p.key, p.val_i); // Important: we currently don't store a type, real value may not be integer.
}
ImGui::TreePop();
}
};
Funcs::NodeWindows(g.Windows, "Windows");
//Funcs::NodeWindows(g.WindowsFocusOrder, "WindowsFocusOrder");
if (ImGui::TreeNode("DrawLists", "Active DrawLists (%d)", g.DrawDataBuilder.Layers[0].Size))
{
for (int i = 0; i < g.DrawDataBuilder.Layers[0].Size; i++)
Funcs::NodeDrawList(NULL, g.DrawDataBuilder.Layers[0][i], "DrawList");
ImGui::TreePop();
}
// Details for Popups
if (ImGui::TreeNode("Popups", "Popups (%d)", g.OpenPopupStack.Size))
{
for (int i = 0; i < g.OpenPopupStack.Size; i++)
{
ImGuiWindow* window = g.OpenPopupStack[i].Window;
ImGui::BulletText("PopupID: %08x, Window: '%s'%s%s", g.OpenPopupStack[i].PopupId, window ? window->Name : "NULL", window && (window->Flags & ImGuiWindowFlags_ChildWindow) ? " ChildWindow" : "", window && (window->Flags & ImGuiWindowFlags_ChildMenu) ? " ChildMenu" : "");
}
ImGui::TreePop();
}
// Details for TabBars
if (ImGui::TreeNode("TabBars", "Tab Bars (%d)", g.TabBars.GetSize()))
{
for (int n = 0; n < g.TabBars.GetSize(); n++)
Funcs::NodeTabBar(g.TabBars.GetByIndex(n));
ImGui::TreePop();
}
// Details for Tables
IM_UNUSED(trt_rects_names);
IM_UNUSED(show_tables_rects);
IM_UNUSED(show_tables_rect_type);
#ifdef IMGUI_HAS_TABLE
if (ImGui::TreeNode("Tables", "Tables (%d)", g.Tables.GetSize()))
{
for (int n = 0; n < g.Tables.GetSize(); n++)
Funcs::NodeTable(g.Tables.GetByIndex(n));
ImGui::TreePop();
}
#endif // #define IMGUI_HAS_TABLE
// Details for Docking
#ifdef IMGUI_HAS_DOCK
if (ImGui::TreeNode("Docking"))
{
ImGui::TreePop();
}
#endif // #define IMGUI_HAS_DOCK
// Misc Details
if (ImGui::TreeNode("Internal state"))
{
const char* input_source_names[] = { "None", "Mouse", "Nav", "NavKeyboard", "NavGamepad" }; IM_ASSERT(IM_ARRAYSIZE(input_source_names) == ImGuiInputSource_COUNT);
ImGui::Text("HoveredWindow: '%s'", g.HoveredWindow ? g.HoveredWindow->Name : "NULL");
ImGui::Text("HoveredRootWindow: '%s'", g.HoveredRootWindow ? g.HoveredRootWindow->Name : "NULL");
ImGui::Text("HoveredId: 0x%08X/0x%08X (%.2f sec), AllowOverlap: %d", g.HoveredId, g.HoveredIdPreviousFrame, g.HoveredIdTimer, g.HoveredIdAllowOverlap); // Data is "in-flight" so depending on when the Metrics window is called we may see current frame information or not
ImGui::Text("ActiveId: 0x%08X/0x%08X (%.2f sec), AllowOverlap: %d, Source: %s", g.ActiveId, g.ActiveIdPreviousFrame, g.ActiveIdTimer, g.ActiveIdAllowOverlap, input_source_names[g.ActiveIdSource]);
ImGui::Text("ActiveIdWindow: '%s'", g.ActiveIdWindow ? g.ActiveIdWindow->Name : "NULL");
ImGui::Text("MovingWindow: '%s'", g.MovingWindow ? g.MovingWindow->Name : "NULL");
ImGui::Text("NavWindow: '%s'", g.NavWindow ? g.NavWindow->Name : "NULL");
ImGui::Text("NavId: 0x%08X, NavLayer: %d", g.NavId, g.NavLayer);
ImGui::Text("NavInputSource: %s", input_source_names[g.NavInputSource]);
ImGui::Text("NavActive: %d, NavVisible: %d", g.IO.NavActive, g.IO.NavVisible);
ImGui::Text("NavActivateId: 0x%08X, NavInputId: 0x%08X", g.NavActivateId, g.NavInputId);
ImGui::Text("NavDisableHighlight: %d, NavDisableMouseHover: %d", g.NavDisableHighlight, g.NavDisableMouseHover);
ImGui::Text("NavWindowingTarget: '%s'", g.NavWindowingTarget ? g.NavWindowingTarget->Name : "NULL");
ImGui::Text("DragDrop: %d, SourceId = 0x%08X, Payload \"%s\" (%d bytes)", g.DragDropActive, g.DragDropPayload.SourceId, g.DragDropPayload.DataType, g.DragDropPayload.DataSize);
ImGui::TreePop();
}
// Tools
if (ImGui::TreeNode("Tools"))
{
// The Item Picker tool is super useful to visually select an item and break into the call-stack of where it was submitted.
if (ImGui::Button("Item Picker.."))
ImGui::DebugStartItemPicker();
ImGui::SameLine();
MetricsHelpMarker("Will call the IM_DEBUG_BREAK() macro to break in debugger.\nWarning: If you don't have a debugger attached, this will probably crash.");
ImGui::Checkbox("Show windows begin order", &show_windows_begin_order);
ImGui::Checkbox("Show windows rectangles", &show_windows_rects);
ImGui::SameLine();
ImGui::SetNextItemWidth(ImGui::GetFontSize() * 12);
show_windows_rects |= ImGui::Combo("##show_windows_rect_type", &show_windows_rect_type, wrt_rects_names, WRT_Count, WRT_Count);
if (show_windows_rects && g.NavWindow)
{
ImGui::BulletText("'%s':", g.NavWindow->Name);
ImGui::Indent();
for (int rect_n = 0; rect_n < WRT_Count; rect_n++)
{
ImRect r = Funcs::GetWindowRect(g.NavWindow, rect_n);
ImGui::Text("(%6.1f,%6.1f) (%6.1f,%6.1f) Size (%6.1f,%6.1f) %s", r.Min.x, r.Min.y, r.Max.x, r.Max.y, r.GetWidth(), r.GetHeight(), wrt_rects_names[rect_n]);
}
ImGui::Unindent();
}
ImGui::Checkbox("Show details when hovering ImDrawCmd node", &show_drawcmd_details);
ImGui::TreePop();
}
// Overlay: Display windows Rectangles and Begin Order
if (show_windows_rects || show_windows_begin_order)
{
for (int n = 0; n < g.Windows.Size; n++)
{
ImGuiWindow* window = g.Windows[n];
if (!window->WasActive)
continue;
ImDrawList* draw_list = GetForegroundDrawList(window);
if (show_windows_rects)
{
ImRect r = Funcs::GetWindowRect(window, show_windows_rect_type);
draw_list->AddRect(r.Min, r.Max, IM_COL32(255, 0, 128, 255));
}
if (show_windows_begin_order && !(window->Flags & ImGuiWindowFlags_ChildWindow))
{
char buf[32];
ImFormatString(buf, IM_ARRAYSIZE(buf), "%d", window->BeginOrderWithinContext);
float font_size = ImGui::GetFontSize();
draw_list->AddRectFilled(window->Pos, window->Pos + ImVec2(font_size, font_size), IM_COL32(200, 100, 100, 255));
draw_list->AddText(window->Pos, IM_COL32(255, 255, 255, 255), buf);
}
}
}
#ifdef IMGUI_HAS_TABLE
// Overlay: Display Tables Rectangles
if (show_tables_rects)
{
for (int table_n = 0; table_n < g.Tables.GetSize(); table_n++)
{
ImGuiTable* table = g.Tables.GetByIndex(table_n);
}
}
#endif // #define IMGUI_HAS_TABLE
#ifdef IMGUI_HAS_DOCK
// Overlay: Display Docking info
if (show_docking_nodes && g.IO.KeyCtrl)
{
}
#endif // #define IMGUI_HAS_DOCK
ImGui::End();
}
#else
void ImGui::ShowMetricsWindow(bool*) { }
#endif
//-----------------------------------------------------------------------------
// Include imgui_user.inl at the end of imgui.cpp to access private data/functions that aren't exposed.
// Prefer just including imgui_internal.h from your code rather than using this define. If a declaration is missing from imgui_internal.h add it or request it on the github.
#ifdef IMGUI_INCLUDE_IMGUI_USER_INL
#include "imgui_user.inl"
#endif
//-----------------------------------------------------------------------------
#endif // #ifndef IMGUI_DISABLE
| [
"[email protected]"
] | |
f4252c273118e2bc54cbede9faa6c8f7e776c14d | 1ae7e3c269e0bd2df0bc725a33f307971816d40d | /app/src/main/cpp/boost/thread/win32/basic_recursive_mutex.hpp | 97bfa4e56b34a29ac03779b1491a55b8c5284e6b | [] | no_license | HOTFIGHTER/XmLogger | 347902372bf2afc88cf26d2342434c1ea556201f | 433a0420c99a883bd65e99fd5f04ac353ac6d7b6 | refs/heads/master | 2021-02-18T08:46:12.122640 | 2020-03-05T14:16:39 | 2020-03-05T14:16:39 | 245,178,943 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,306 | hpp | #ifndef BOOST_BASIC_RECURSIVE_MUTEX_WIN32_HPP
#define BOOST_BASIC_RECURSIVE_MUTEX_WIN32_HPP
// basic_recursive_mutex.hpp
//
// (C) Copyright 2006-8 Anthony Williams
// (C) Copyright 2011-2012 Vicente J. Botet Escriba
//
// 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)
#include <boost/thread/win32/thread_primitives.hpp>
#include <boost/thread/win32/basic_timed_mutex.hpp>
#ifdef BOOST_THREAD_USES_CHRONO
#include <boost/chrono/system_clocks.hpp>
#include <boost/chrono/ceil.hpp>
#endif
#include <boost/config/abi_prefix.hpp>
namespace mars_boost {}
namespace boost = mars_boost;
namespace mars_boost {
namespace detail {
template<typename underlying_mutex_type>
struct basic_recursive_mutex_impl {
long recursion_count;
long locking_thread_id;
underlying_mutex_type mutex;
void initialize() {
recursion_count = 0;
locking_thread_id = 0;
mutex.initialize();
}
void destroy() {
mutex.destroy();
}
bool try_lock()
BOOST_NOEXCEPT
{
long const current_thread_id = win32::GetCurrentThreadId();
return try_recursive_lock(current_thread_id) || try_basic_lock(current_thread_id);
}
void lock() {
long const current_thread_id = win32::GetCurrentThreadId();
if (!try_recursive_lock(current_thread_id)) {
mutex.lock();
BOOST_INTERLOCKED_EXCHANGE(&locking_thread_id, current_thread_id);
recursion_count = 1;
}
}
#if defined BOOST_THREAD_USES_DATETIME
bool timed_lock(::boost::system_time const& target)
{
long const current_thread_id=win32::GetCurrentThreadId();
return try_recursive_lock(current_thread_id) || try_timed_lock(current_thread_id,target);
}
template<typename Duration>
bool timed_lock(Duration const& timeout)
{
return timed_lock(get_system_time()+timeout);
}
#endif
#ifdef BOOST_THREAD_USES_CHRONO
template <class Rep, class Period>
bool try_lock_for(const chrono::duration<Rep, Period>& rel_time)
{
long const current_thread_id=win32::GetCurrentThreadId();
return try_recursive_lock(current_thread_id) || try_timed_lock_for(current_thread_id,rel_time);
}
template <class Clock, class Duration>
bool try_lock_until(const chrono::time_point<Clock, Duration>& t)
{
long const current_thread_id=win32::GetCurrentThreadId();
return try_recursive_lock(current_thread_id) || try_timed_lock_until(current_thread_id,t);
}
#endif
void unlock() {
if (!--recursion_count) {
BOOST_INTERLOCKED_EXCHANGE(&locking_thread_id, 0);
mutex.unlock();
}
}
private:
bool try_recursive_lock(long current_thread_id)
BOOST_NOEXCEPT
{
if (::boost::detail::interlocked_read_acquire(&locking_thread_id) == current_thread_id) {
++recursion_count;
return true;
}
return false;
}
bool try_basic_lock(long current_thread_id)
BOOST_NOEXCEPT
{
if (mutex.try_lock()) {
BOOST_INTERLOCKED_EXCHANGE(&locking_thread_id, current_thread_id);
recursion_count = 1;
return true;
}
return false;
}
#if defined BOOST_THREAD_USES_DATETIME
bool try_timed_lock(long current_thread_id,::boost::system_time const& target)
{
if(mutex.timed_lock(target))
{
BOOST_INTERLOCKED_EXCHANGE(&locking_thread_id,current_thread_id);
recursion_count=1;
return true;
}
return false;
}
#endif
template<typename TP>
bool try_timed_lock_until(long current_thread_id, TP const &target) {
if (mutex.try_lock_until(target)) {
BOOST_INTERLOCKED_EXCHANGE(&locking_thread_id, current_thread_id);
recursion_count = 1;
return true;
}
return false;
}
template<typename D>
bool try_timed_lock_for(long current_thread_id, D const &target) {
if (mutex.try_lock_for(target)) {
BOOST_INTERLOCKED_EXCHANGE(&locking_thread_id, current_thread_id);
recursion_count = 1;
return true;
}
return false;
}
};
typedef basic_recursive_mutex_impl<basic_timed_mutex> basic_recursive_mutex;
typedef basic_recursive_mutex_impl<basic_timed_mutex> basic_recursive_timed_mutex;
}
}
#define BOOST_BASIC_RECURSIVE_MUTEX_INITIALIZER {0}
#include <boost/config/abi_suffix.hpp>
#endif
| [
"[email protected]"
] | |
cf5907dbcbb8848ee4b577c5b623839d26e7bf94 | 84a6bf8338698b81aad5524264af78ed7eff1c03 | /src/Magnum/DebugTools/Screenshot.cpp | 60f5ca1fac067c5c2916bb20c6e282f10caf5257 | [
"MIT"
] | permissive | Croydon/magnum | 93f943cc22713678fb4160b246204799b5fcd4ce | fb27ecd87d3c10d898dadb9ee6d0dbe1f7b13a4f | refs/heads/master | 2020-05-05T05:26:16.073682 | 2019-04-04T20:03:00 | 2019-04-05T10:45:26 | 179,752,195 | 0 | 1 | NOASSERTION | 2019-04-05T20:43:50 | 2019-04-05T20:43:50 | null | UTF-8 | C++ | false | false | 3,881 | cpp | /*
This file is part of Magnum.
Copyright © 2010, 2011, 2012, 2013, 2014, 2015, 2016, 2017, 2018, 2019
Vladimír Vondruš <[email protected]>
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 "Screenshot.h"
#include <Corrade/Containers/Optional.h>
#include <Corrade/PluginManager/Manager.h>
#include "Magnum/PixelFormat.h"
#include "Magnum/Image.h"
#include "Magnum/GL/AbstractFramebuffer.h"
#include "Magnum/GL/PixelFormat.h"
#include "Magnum/Trade/AbstractImageConverter.h"
namespace Magnum { namespace DebugTools {
bool screenshot(GL::AbstractFramebuffer& framebuffer, const std::string& filename) {
PluginManager::Manager<Trade::AbstractImageConverter> manager;
return screenshot(manager, framebuffer, filename);
}
bool screenshot(PluginManager::Manager<Trade::AbstractImageConverter>& manager, GL::AbstractFramebuffer& framebuffer, const std::string& filename) {
/* Get the implementation-specific color read format for given framebuffer */
const GL::PixelFormat format = framebuffer.implementationColorReadFormat();
const GL::PixelType type = framebuffer.implementationColorReadType();
auto genericFormat = [](GL::PixelFormat format, GL::PixelType type) -> Containers::Optional<PixelFormat> {
#ifndef DOXYGEN_GENERATING_OUTPUT /* It gets *really* confused */
#define _c(generic, glFormat, glType) if(format == GL::PixelFormat::glFormat && type == GL::PixelType::glType) return PixelFormat::generic;
#define _s(generic) return {};
#include "Magnum/GL/Implementation/pixelFormatMapping.hpp"
#undef _c
#undef _s
#endif
return {};
}(format, type);
if(!genericFormat) {
Error{} << "DebugTools::screenshot(): can't map (" << Debug::nospace << format << Debug::nospace << "," << type << Debug::nospace << ") to a generic pixel format";
return false;
}
return screenshot(manager, framebuffer, *genericFormat, filename);
}
bool screenshot(GL::AbstractFramebuffer& framebuffer, const PixelFormat format, const std::string& filename) {
PluginManager::Manager<Trade::AbstractImageConverter> manager;
return screenshot(manager, framebuffer, format, filename);
}
bool screenshot(PluginManager::Manager<Trade::AbstractImageConverter>& manager, GL::AbstractFramebuffer& framebuffer, const PixelFormat format, const std::string& filename) {
Containers::Pointer<Trade::AbstractImageConverter> converter;
if(!(converter = manager.loadAndInstantiate("AnyImageConverter")))
return false;
Image2D image = framebuffer.read(framebuffer.viewport(), {format});
if(!converter->exportToFile(image, filename))
return false;
Debug{} << "DebugTools::screenshot(): saved a" << format << "image of size" << image.size() << "to" << filename;
return true;
}
}}
| [
"[email protected]"
] | |
84baa35ab9e80cc72b9031bec33975796cb3cce6 | c33c269d2bc08dc7e38f9ed394ee9470ac9e113e | /03/coffee/Portion.h | 3778edda372cb364e904ef9a70ff6c1a47f0a0b4 | [] | no_license | lm1458777/ood-labs | 68ea4ff69d713556b1506ede56d42f7265120672 | f03b778df011bbdaa01bb31c254d0dd2bfcd4680 | refs/heads/master | 2021-04-30T06:02:20.357401 | 2018-07-06T06:41:52 | 2018-07-06T06:41:52 | 121,432,767 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 591 | h | #pragma once
#include "IBeverage.h"
class Portion final : public IBeverage
{
public:
Portion(IBeveragePtr beverage, std::string portion, double price)
: m_beverage(std::move(beverage))
, m_portion(std::move(portion))
, m_price(price)
{
if (!m_beverage)
{
throw std::invalid_argument("The beverage must not be null");
}
}
std::string GetDescription() const override
{
return m_portion + " " + m_beverage->GetDescription();
}
double GetCost() const override
{
return m_price;
}
private:
IBeveragePtr m_beverage;
std::string m_portion;
double m_price = 0;
};
| [
"[email protected]"
] | |
569e8d32427503ba86dcd6a18e97aee527414935 | 5b673d4ebc7e874c9bec9bacfd62a6a5d1c38298 | /Engine/src/scene/sceneobject.cpp | 5a727564abef7c9aa0cc891ea54bb294a4be380d | [] | no_license | Julian-Gallegos/Animator | 94e19b83a4a8e0e498ed4449560d16c75b851756 | 3dc28e4030b3932f4bd98bc4069620d50aa0a4cc | refs/heads/master | 2023-08-02T16:04:03.167605 | 2020-05-28T01:35:28 | 2020-05-28T01:35:28 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,944 | cpp | /****************************************************************************
* Copyright ©2017 Brian Curless. All rights reserved. Permission is hereby
* granted to students registered for University of Washington CSE 457 or CSE
* 557 for use solely during Autumn Quarter 2017 for purposes of the course.
* No other use, copying, distribution, or modification is permitted without
* prior written consent. Copyrights for third-party components of this work
* must be honored. Instructors interested in reusing these course materials
* should contact the author.
****************************************************************************/
#include "sceneobject.h"
#include <scene/scene.h>
#include <scene/components/geometry.h>
#include <scene/components/robotarmprop.h>
#include <scene/components/customprop.h>
SceneObject::SceneObject(const std::string& name, int flag) :
uid_(SceneObject::uid_counter_++),
name_(name),
parent_(nullptr),
enabled_(true),
flag_(flag)
{
AddComponent<Transform>();
}
SceneObject::~SceneObject() {
// Clear all signals
ComponentAdded.Clear();
ComponentRemoved.Clear();
LightSourceAdded.Clear();
NameChanged.Clear();
EnabledChanged.Clear();
ParentChanged.Clear();
}
Component* SceneObject::AddComponent(std::string classname) {
Component* component = Component::Create(classname);
AddComponent(component);
return component;
}
void SceneObject::AddComponent(Component* component) {
// Let whomever know that this object is now a light source
if (dynamic_cast<PointLight*>(component) || dynamic_cast<DirectionalLight*>(component)) LightSourceAdded.Emit(*this);
// Let whomever know that this object is now a particle system
if (dynamic_cast<ParticleSystem*>(component)) ParticleSystemAdded.Emit(*this);
assert(components_.find(component->GetBaseType()) == components_.end());
components_[component->GetBaseType()] = component;
ComponentAdded.Emit(*component);
}
void SceneObject::SetParticleGeom(std::string name) {
if (GetComponent<Sphere>() != nullptr) {
RemoveComponent<Sphere>();
} else if (GetComponent<Cylinder>() != nullptr) {
RemoveComponent<Cylinder>();
} else if (GetComponent<Plane>() != nullptr) {
RemoveComponent<Plane>();
} else if (GetComponent<TriangleMesh>() != nullptr) {
RemoveComponent<TriangleMesh>();
} else {
qDebug("Invalid particle geometry state!");
return;
}
if (name == "Sphere") {
AddComponent<Sphere>();
} else if (name == "Cylinder") {
AddComponent<Cylinder>();
} else if (name == "Plane") {
AddComponent<Plane>();
} else if (name == "Mesh") {
AddComponent<TriangleMesh>();
AssetManager& asset_manager = *(AssetManager::Instance());
auto mesh = asset_manager.GetMesh("Cube");
assert(mesh != nullptr);
GetComponent<TriangleMesh>()->MeshFilter.Set(mesh);
}
}
void SceneObject::SaveToYAML(YAML::Emitter &out) const
{
out << YAML::BeginMap;
out << YAML::Key << "Name" << YAML::Value << name_;
out << YAML::Key << "Enabled" << YAML::Value << enabled_;
out << YAML::Key << "Components" << YAML::Value << YAML::BeginMap;
for(auto it = components_.begin(); it!=components_.end(); it++) {
out << YAML::Key << it->second->GetTypeName() << YAML::Value;
it->second->SaveToYAML(out);
}
out << YAML::EndMap;
out << YAML::Key << "Children" << YAML::Value << YAML::BeginSeq;
for (auto it=children_.begin(); it!=children_.end(); it++) {
if (!it->second->IsInternal()) {
out << YAML::Value;
it->second->SaveToYAML(out);
}
}
out << YAML::EndSeq;
out << YAML::EndMap;
}
void SceneObject::LoadFromYAML(const YAML::Node &node)
{
assert(node.IsMap());
assert(node["Name"]);
SetName(node["Name"].as<std::string>());
SetEnabled(node["Enabled"] ? node["Enabled"].as<bool>() : true);
assert(node["Components"] && node["Components"].IsMap());
for(auto it=node["Components"].begin(); it!=node["Components"].end(); it++)
{
Component* added = it->first.as<std::string>()=="Transform" ? &GetTransform() : AddComponent(it->first.as<std::string>());
added->LoadFromYAML(it->second);
std::string comp_name = it->first.as<std::string>();
if (comp_name == "RobotArmProp")
dynamic_cast<RobotArmProp*>(added)->SetRoot(this);
else if (comp_name == "CustomProp")
dynamic_cast<CustomProp*>(added)->SetRoot(this);
}
assert(node["Children"] && node["Children"].IsSequence());
for(auto it=node["Children"].begin(); it!=node["Children"].end(); it++) {
SceneObject* added = &(Scene::Instance()->CreateSceneObject("temp"));
added->LoadFromYAML(*it);
added->SetParent(*this);
}
}
uint64_t SceneObject::uid_counter_ = 0;
| [
"[email protected]"
] | |
9a53b475951a089e3b7c1e5e53032204c3c52dd1 | b5721f085233f6c64d8c233f9bc7e2876cd23f1e | /tests/test_log.cpp | abcd03d17460303c5b7ed867a5bef84953635803 | [] | no_license | zhongluqiang/mysylar | 0825a2e3ff21a5212578a42f0e73a56d5eed6f4b | e4d0af8facde4e72a8c6db98596edb44cb447099 | refs/heads/master | 2021-06-17T19:20:43.706837 | 2019-12-14T15:12:06 | 2019-12-14T15:12:06 | 212,983,352 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,126 | cpp | #include "sylar/log.h"
#include <iostream>
int main() {
sylar::Logger::ptr logger(new sylar::Logger);
//[日期时间] 文件名:行号 线程号:协程号 日志级别 日志内容\n
sylar::LogFormatter::ptr fmt(
new sylar::LogFormatter("[%d] %f:%l %t:%F %p %m%n"));
sylar::FileLogAppender::ptr file_appender(
new sylar::FileLogAppender("./log.txt"));
file_appender->setFormater(fmt);
file_appender->setLevel(sylar::LogLevel::ERROR);
logger->addAppender(file_appender);
sylar::StdoutLogAppender::ptr stdout_appender(
new sylar::StdoutLogAppender());
stdout_appender->setFormater(fmt);
logger->addAppender(stdout_appender);
std::cout << "hello sylar log" << std::endl;
SYLAR_LOG_DEBUG(logger) << "test macro debug";
SYLAR_LOG_INFO(logger) << "test macro info";
SYLAR_LOG_WARN(logger) << "test macro logger";
SYLAR_LOG_ERROR(logger) << "test macro error";
SYLAR_LOG_FATAL(logger) << "test macro fatal";
SYLAR_LOG_ERROR(SYLAR_LOG_ROOT()) << "test macro SYLAR_LOG_ROOT";
return 0;
} | [
"[email protected]"
] | |
938dad1bd1f9e168ee085e75015248e9e04ed9b6 | a3d6556180e74af7b555f8d47d3fea55b94bcbda | /ash/style/combobox.cc | 985a7a3b5687cda514ca77ff9e34027677dfb21b | [
"BSD-3-Clause"
] | permissive | chromium/chromium | aaa9eda10115b50b0616d2f1aed5ef35d1d779d6 | a401d6cf4f7bf0e2d2e964c512ebb923c3d8832c | refs/heads/main | 2023-08-24T00:35:12.585945 | 2023-08-23T22:01:11 | 2023-08-23T22:01:11 | 120,360,765 | 17,408 | 7,102 | BSD-3-Clause | 2023-09-10T23:44:27 | 2018-02-05T20:55:32 | null | UTF-8 | C++ | false | false | 15,308 | cc | // Copyright 2023 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "ash/style/combobox.h"
#include <memory>
#include "ash/public/cpp/shell_window_ids.h"
#include "ash/public/cpp/style/color_provider.h"
#include "ash/resources/vector_icons/vector_icons.h"
#include "ash/style/blurred_background_shield.h"
#include "ash/style/radio_button.h"
#include "ash/style/radio_button_group.h"
#include "ash/style/style_util.h"
#include "ash/style/typography.h"
#include "base/functional/bind.h"
#include "ui/aura/env.h"
#include "ui/aura/window.h"
#include "ui/base/metadata/metadata_impl_macros.h"
#include "ui/base/models/combobox_model.h"
#include "ui/chromeos/styles/cros_tokens_color_mappings.h"
#include "ui/compositor/layer.h"
#include "ui/events/event.h"
#include "ui/events/event_handler.h"
#include "ui/events/event_target.h"
#include "ui/events/types/event_type.h"
#include "ui/gfx/geometry/insets.h"
#include "ui/gfx/geometry/rounded_corners_f.h"
#include "ui/views/background.h"
#include "ui/views/controls/highlight_path_generator.h"
#include "ui/views/controls/image_view.h"
#include "ui/views/controls/label.h"
#include "ui/views/highlight_border.h"
#include "ui/views/layout/box_layout.h"
#include "ui/views/layout/fill_layout.h"
#include "ui/views/mouse_constants.h"
#include "ui/views/widget/widget.h"
#include "ui/wm/core/coordinate_conversion.h"
namespace ash {
namespace {
// The color constants.
constexpr ui::ColorId kActiveTitleAndIconColorId =
cros_tokens::kCrosSysSystemOnPrimaryContainer;
constexpr ui::ColorId kInactiveTitleAndIconColorId =
cros_tokens::kCrosSysOnSurface;
constexpr ui::ColorId kMenuTextColorId = cros_tokens::kCrosSysOnSurface;
constexpr ui::ColorId kMenuBackgroundColorId =
cros_tokens::kCrosSysSystemBaseElevated;
constexpr ui::ColorId kComboboxActiveColorId =
cros_tokens::kCrosSysSystemPrimaryContainer;
// The layout parameters.
constexpr gfx::RoundedCornersF kComboboxRoundedCorners =
gfx::RoundedCornersF(12, 12, 12, 4);
constexpr gfx::RoundedCornersF kMenuRoundedCorners =
gfx::RoundedCornersF(4, 12, 12, 12);
constexpr gfx::Insets kComboboxBorderInsets = gfx::Insets::TLBR(4, 10, 4, 4);
constexpr gfx::Insets kMenuBorderInsets = gfx::Insets::TLBR(16, 0, 12, 0);
constexpr gfx::Insets kMenuItemInnerPadding = gfx::Insets::VH(8, 16);
constexpr int kArrowIconSize = 20;
constexpr int kCheckmarkLabelSpacing = 16;
constexpr int kMinMenuWidth = 256;
constexpr gfx::Vector2d kMenuOffset(0, 8);
constexpr int kMenuShadowElevation = 12;
} // namespace
//------------------------------------------------------------------------------
// Combobox::ComboboxMenuView:
// The contents of combobox drop down menu which contains a list of items
// corresponding to the items in combobox model. The selected item will show a
// leading checked icon.
class Combobox::ComboboxMenuView : public views::View {
public:
METADATA_HEADER(ComboboxMenuView);
explicit ComboboxMenuView(base::WeakPtr<Combobox> combobox)
: combobox_(combobox),
background_shield_(this,
kMenuBackgroundColorId,
ColorProvider::kBackgroundBlurSigma,
kMenuRoundedCorners) {
SetLayoutManager(std::make_unique<views::FillLayout>());
// Create a radio buttons group for item list.
menu_item_group_ = AddChildView(std::make_unique<RadioButtonGroup>(
kMinMenuWidth, kMenuBorderInsets, 0,
RadioButton::IconDirection::kLeading, RadioButton::IconType::kCheck,
kMenuItemInnerPadding, kCheckmarkLabelSpacing));
UpdateMenuContent();
// Set border.
SetBorder(std::make_unique<views::HighlightBorder>(
kMenuRoundedCorners,
views::HighlightBorder::Type::kHighlightBorderOnShadow));
}
ComboboxMenuView(const ComboboxMenuView&) = delete;
ComboboxMenuView& operator=(const ComboboxMenuView&) = delete;
~ComboboxMenuView() override = default;
void SelectItem(int index) { menu_item_group_->SelectButtonAtIndex(index); }
void UpdateMenuContent() {
menu_item_group_->RemoveAllChildViews();
// Build a radio button group according to current combobox model.
for (size_t i = 0; i < combobox_->model_->GetItemCount(); i++) {
auto* item = menu_item_group_->AddButton(
base::BindRepeating(&Combobox::MenuSelectionAt, combobox_, i),
combobox_->model_->GetDropDownTextAt(i));
item->SetLabelStyle(TypographyToken::kCrosButton2);
item->SetLabelColorId(kMenuTextColorId);
item->SetSelected(combobox_->selected_index_.value() == i);
}
}
private:
const base::WeakPtr<Combobox> combobox_;
const BlurredBackgroundShield background_shield_;
// Owned by this.
raw_ptr<RadioButtonGroup> menu_item_group_;
};
BEGIN_METADATA(Combobox, ComboboxMenuView, views::View)
END_METADATA
//------------------------------------------------------------------------------
// Combobox::ComboboxEventHandler:
// Handles the mouse and touch event that happens outside combobox and its drop
// down menu.
class Combobox::ComboboxEventHandler : public ui::EventHandler {
public:
explicit ComboboxEventHandler(Combobox* combobox) : combobox_(combobox) {
aura::Env::GetInstance()->AddPreTargetHandler(
this, ui::EventTarget::Priority::kSystem);
}
ComboboxEventHandler(const ComboboxEventHandler&) = delete;
ComboboxEventHandler& operator=(const ComboboxEventHandler&) = delete;
~ComboboxEventHandler() override {
aura::Env::GetInstance()->RemovePreTargetHandler(this);
}
// ui::EventHandler:
void OnMouseEvent(ui::MouseEvent* event) override { OnLocatedEvent(event); }
void OnTouchEvent(ui::TouchEvent* event) override { OnLocatedEvent(event); }
private:
void OnLocatedEvent(ui::LocatedEvent* event) {
// If there is a mouse or touch event happening outside the combobox and
// drop down menu, the drop down menu should be closed.
if (event->type() != ui::ET_MOUSE_PRESSED &&
event->type() != ui::ET_TOUCH_PRESSED) {
return;
}
if (!combobox_->IsMenuRunning()) {
return;
}
gfx::Point event_location = event->location();
aura::Window* event_target = static_cast<aura::Window*>(event->target());
wm::ConvertPointToScreen(event_target, &event_location);
if (!combobox_->menu_->GetWindowBoundsInScreen().Contains(event_location) &&
!combobox_->GetBoundsInScreen().Contains(event_location)) {
combobox_->CloseDropDownMenu();
}
}
const raw_ptr<Combobox> combobox_;
};
//------------------------------------------------------------------------------
// Combobox:
Combobox::Combobox(std::unique_ptr<ui::ComboboxModel> model)
: Combobox(model.get()) {
owned_model_ = std::move(model);
}
Combobox::Combobox(ui::ComboboxModel* model)
: views::Button(base::BindRepeating(&Combobox::OnComboboxPressed,
base::Unretained(this))),
model_(model),
title_(AddChildView(std::make_unique<views::Label>())),
drop_down_arrow_(AddChildView(std::make_unique<views::ImageView>(
ui::ImageModel::FromVectorIcon(kDropDownArrowIcon,
kInactiveTitleAndIconColorId,
kArrowIconSize)))) {
// Initialize the combobox with given model.
CHECK(model_);
observation_.Observe(model_.get());
SetSelectedIndex(model_->GetDefaultIndex());
OnComboboxModelChanged(model_);
// Set up layout.
SetLayoutManager(std::make_unique<views::BoxLayout>(
/*orientation=*/views::BoxLayout::Orientation::kHorizontal,
/*inside_border_insets=*/kComboboxBorderInsets));
// Stylize the title.
TypographyProvider::Get()->StyleLabel(TypographyToken::kCrosTitle1,
*title_.get());
title_->SetAutoColorReadabilityEnabled(false);
title_->SetEnabledColorId(kInactiveTitleAndIconColorId);
SetFocusBehavior(views::View::FocusBehavior::ALWAYS);
SetPaintToLayer();
layer()->SetFillsBoundsOpaquely(false);
// Set up the ink drop.
StyleUtil::InstallRoundedCornerHighlightPathGenerator(
this, kComboboxRoundedCorners);
StyleUtil::SetUpInkDropForButton(this);
event_handler_ = std::make_unique<ComboboxEventHandler>(this);
}
Combobox::~Combobox() = default;
void Combobox::SetSelectionChangedCallback(base::RepeatingClosure callback) {
callback_ = std::move(callback);
}
void Combobox::SetSelectedIndex(absl::optional<size_t> index) {
if (selected_index_ == index) {
return;
}
if (index.has_value()) {
CHECK_LT(index.value(), model_->GetItemCount());
}
selected_index_ = index;
if (!selected_index_.has_value()) {
return;
}
// Update selected item on menu if the menu is opening.
if (menu_view_) {
menu_view_->SelectItem(selected_index_.value());
}
OnPerformAction();
}
bool Combobox::SelectValue(const std::u16string& value) {
for (size_t i = 0; i < model_->GetItemCount(); ++i) {
if (value == model_->GetItemAt(i)) {
SetSelectedIndex(i);
return true;
}
}
return false;
}
bool Combobox::IsMenuRunning() const {
return !!menu_;
}
void Combobox::SetCallback(PressedCallback callback) {
NOTREACHED() << "Clients shouldn't modify this. Maybe you want to use "
"SetSelectionChangedCallback?";
}
void Combobox::OnBoundsChanged(const gfx::Rect& previous_bounds) {
// Move menu with combobox accordingly.
if (menu_) {
menu_->SetBounds(GetExpectedMenuBounds());
}
}
std::u16string Combobox::GetTextForRow(size_t row) const {
return model_->IsItemSeparatorAt(row) ? std::u16string()
: model_->GetItemAt(row);
}
void Combobox::SelectMenuItemForTest(size_t row) {
MenuSelectionAt(row);
}
gfx::Rect Combobox::GetExpectedMenuBounds() const {
CHECK(menu_view_);
return gfx::Rect(GetBoundsInScreen().bottom_left() + kMenuOffset,
menu_view_->GetPreferredSize());
}
void Combobox::MenuSelectionAt(size_t index) {
SetSelectedIndex(index);
// Close the menu once a selection is made.
CloseDropDownMenu();
}
void Combobox::OnComboboxPressed() {
if (!GetEnabled()) {
return;
}
if ((base::TimeTicks::Now() - closed_time_) >
views::kMinimumTimeBetweenButtonClicks) {
ShowDropDownMenu();
}
}
void Combobox::ShowDropDownMenu() {
auto* widget = GetWidget();
if (!widget) {
return;
}
auto menu_view =
std::make_unique<ComboboxMenuView>(weak_ptr_factory_.GetWeakPtr());
menu_view_ = menu_view.get();
views::Widget::InitParams params(views::Widget::InitParams::TYPE_POPUP);
params.opacity = views::Widget::InitParams::WindowOpacity::kTranslucent;
params.shadow_type = views::Widget::InitParams::ShadowType::kDrop;
params.shadow_elevation = kMenuShadowElevation;
params.corner_radius = kMenuRoundedCorners.lower_left();
aura::Window* root_window = widget->GetNativeWindow()->GetRootWindow();
params.parent = root_window->GetChildById(kShellWindowId_MenuContainer);
params.bounds = GetExpectedMenuBounds();
menu_ = std::make_unique<views::Widget>(std::move(params));
menu_->SetContentsView(std::move(menu_view));
menu_->Show();
SetBackground(views::CreateThemedRoundedRectBackground(
kComboboxActiveColorId, kComboboxRoundedCorners,
/*for_border_thickness=*/0));
title_->SetEnabledColorId(kActiveTitleAndIconColorId);
drop_down_arrow_->SetImage(ui::ImageModel::FromVectorIcon(
kDropDownArrowIcon, kActiveTitleAndIconColorId, kArrowIconSize));
RequestFocus();
}
void Combobox::CloseDropDownMenu() {
menu_view_ = nullptr;
menu_.reset();
closed_time_ = base::TimeTicks::Now();
SetBackground(nullptr);
title_->SetEnabledColorId(kInactiveTitleAndIconColorId);
drop_down_arrow_->SetImage(ui::ImageModel::FromVectorIcon(
kDropDownArrowIcon, kInactiveTitleAndIconColorId, kArrowIconSize));
}
void Combobox::OnPerformAction() {
CHECK(selected_index_.has_value());
title_->SetText(model_->GetItemAt(selected_index_.value()));
SchedulePaint();
if (callback_) {
callback_.Run();
}
}
void Combobox::OnComboboxModelChanged(ui::ComboboxModel* model) {
DCHECK_EQ(model_, model);
// If the selection is no longer valid (or the model is empty), restore the
// default index.
if (selected_index_ >= model_->GetItemCount() ||
model_->GetItemCount() == 0 ||
model_->IsItemSeparatorAt(selected_index_.value())) {
SetSelectedIndex(model_->GetDefaultIndex());
}
if (menu_view_) {
menu_view_->UpdateMenuContent();
}
}
void Combobox::OnComboboxModelDestroying(ui::ComboboxModel* model) {
CloseDropDownMenu();
model_ = nullptr;
observation_.Reset();
}
bool Combobox::SkipDefaultKeyEventProcessing(const ui::KeyEvent& e) {
// Escape should close the drop down list when it is active, not host UI.
if (e.key_code() != ui::VKEY_ESCAPE || e.IsShiftDown() || e.IsControlDown() ||
e.IsAltDown() || e.IsAltGrDown()) {
return false;
}
return IsMenuRunning();
}
bool Combobox::OnKeyPressed(const ui::KeyEvent& e) {
CHECK_EQ(e.type(), ui::ET_KEY_PRESSED);
CHECK(selected_index_.has_value());
CHECK_LT(selected_index_.value(), model_->GetItemCount());
const auto index_at_or_after = [](ui::ComboboxModel* model,
size_t index) -> absl::optional<size_t> {
for (; index < model->GetItemCount(); ++index) {
if (!model->IsItemSeparatorAt(index) && model->IsItemEnabledAt(index)) {
return index;
}
}
return absl::nullopt;
};
const auto index_before = [](ui::ComboboxModel* model,
size_t index) -> absl::optional<size_t> {
for (; index > 0; --index) {
const auto prev = index - 1;
if (!model->IsItemSeparatorAt(prev) && model->IsItemEnabledAt(prev)) {
return prev;
}
}
return absl::nullopt;
};
absl::optional<size_t> new_index;
switch (e.key_code()) {
// Show the menu on F4 without modifiers.
case ui::VKEY_F4:
if (e.IsAltDown() || e.IsAltGrDown() || e.IsControlDown()) {
return false;
}
ShowDropDownMenu();
return true;
// Move to the next item if any, or show the menu on Alt+Down like Windows.
case ui::VKEY_DOWN:
if (e.IsAltDown()) {
ShowDropDownMenu();
return true;
}
new_index = index_at_or_after(model_, selected_index_.value() + 1);
break;
// Move to the end of the list.
case ui::VKEY_END:
case ui::VKEY_NEXT: // Page down.
new_index = index_before(model_, model_->GetItemCount());
break;
// Move to the beginning of the list.
case ui::VKEY_HOME:
case ui::VKEY_PRIOR: // Page up.
new_index = index_at_or_after(model_, 0);
break;
// Move to the previous item if any.
case ui::VKEY_UP:
new_index = index_before(model_, selected_index_.value());
break;
case ui::VKEY_RETURN:
case ui::VKEY_SPACE:
ShowDropDownMenu();
return true;
default:
return false;
}
if (new_index.has_value()) {
SetSelectedIndex(new_index);
}
return true;
}
BEGIN_METADATA(Combobox, views::Button)
END_METADATA
} // namespace ash
| [
"[email protected]"
] | |
f7574ba014e822201bf12da80d8869a06725d64a | 14508c4faf7fe967bb0b981c835d64d2d9a31d7d | /build-GUI-Desktop_Qt_5_9_2_MinGW_32bit-Debug/debug/moc_fileexplorar.cpp | 1324b386388cb0f963137bb7e702e7294851f63d | [] | no_license | r17v1/connect | de620955274becbfe1f7d6ebceb36c17d9767af3 | 8089840d0c8706f47ca0e727fe025d86813881c1 | refs/heads/master | 2021-06-23T18:14:42.155783 | 2021-01-21T14:25:21 | 2021-01-21T14:25:21 | 170,814,214 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,667 | cpp | /****************************************************************************
** Meta object code from reading C++ file 'fileexplorar.h'
**
** Created by: The Qt Meta Object Compiler version 67 (Qt 5.9.2)
**
** WARNING! All changes made in this file will be lost!
*****************************************************************************/
#include "../../MainClientNew/fileexplorar.h"
#include <QtCore/qbytearray.h>
#include <QtCore/qmetatype.h>
#if !defined(Q_MOC_OUTPUT_REVISION)
#error "The header file 'fileexplorar.h' doesn't include <QObject>."
#elif Q_MOC_OUTPUT_REVISION != 67
#error "This file was generated using the moc from 5.9.2. It"
#error "cannot be used with the include files from this version of Qt."
#error "(The moc has changed too much.)"
#endif
QT_BEGIN_MOC_NAMESPACE
QT_WARNING_PUSH
QT_WARNING_DISABLE_DEPRECATED
struct qt_meta_stringdata_FileExplorar_t {
QByteArrayData data[10];
char stringdata0[137];
};
#define QT_MOC_LITERAL(idx, ofs, len) \
Q_STATIC_BYTE_ARRAY_DATA_HEADER_INITIALIZER_WITH_OFFSET(len, \
qptrdiff(offsetof(qt_meta_stringdata_FileExplorar_t, stringdata0) + ofs \
- idx * sizeof(QByteArrayData)) \
)
static const qt_meta_stringdata_FileExplorar_t qt_meta_stringdata_FileExplorar = {
{
QT_MOC_LITERAL(0, 0, 12), // "FileExplorar"
QT_MOC_LITERAL(1, 13, 19), // "on_treeView_clicked"
QT_MOC_LITERAL(2, 33, 0), // ""
QT_MOC_LITERAL(3, 34, 5), // "index"
QT_MOC_LITERAL(4, 40, 19), // "on_listView_clicked"
QT_MOC_LITERAL(5, 60, 22), // "on_send_button_clicked"
QT_MOC_LITERAL(6, 83, 24), // "on_cancel_button_clicked"
QT_MOC_LITERAL(7, 108, 10), // "upLoadFile"
QT_MOC_LITERAL(8, 119, 10), // "fileStatus"
QT_MOC_LITERAL(9, 130, 6) // "status"
},
"FileExplorar\0on_treeView_clicked\0\0"
"index\0on_listView_clicked\0"
"on_send_button_clicked\0on_cancel_button_clicked\0"
"upLoadFile\0fileStatus\0status"
};
#undef QT_MOC_LITERAL
static const uint qt_meta_data_FileExplorar[] = {
// content:
7, // revision
0, // classname
0, 0, // classinfo
6, 14, // methods
0, 0, // properties
0, 0, // enums/sets
0, 0, // constructors
0, // flags
0, // signalCount
// slots: name, argc, parameters, tag, flags
1, 1, 44, 2, 0x08 /* Private */,
4, 1, 47, 2, 0x08 /* Private */,
5, 0, 50, 2, 0x08 /* Private */,
6, 0, 51, 2, 0x08 /* Private */,
7, 0, 52, 2, 0x08 /* Private */,
8, 1, 53, 2, 0x08 /* Private */,
// slots: parameters
QMetaType::Void, QMetaType::QModelIndex, 3,
QMetaType::Void, QMetaType::QModelIndex, 3,
QMetaType::Void,
QMetaType::Void,
QMetaType::Void,
QMetaType::Void, QMetaType::Bool, 9,
0 // eod
};
void FileExplorar::qt_static_metacall(QObject *_o, QMetaObject::Call _c, int _id, void **_a)
{
if (_c == QMetaObject::InvokeMetaMethod) {
FileExplorar *_t = static_cast<FileExplorar *>(_o);
Q_UNUSED(_t)
switch (_id) {
case 0: _t->on_treeView_clicked((*reinterpret_cast< const QModelIndex(*)>(_a[1]))); break;
case 1: _t->on_listView_clicked((*reinterpret_cast< const QModelIndex(*)>(_a[1]))); break;
case 2: _t->on_send_button_clicked(); break;
case 3: _t->on_cancel_button_clicked(); break;
case 4: _t->upLoadFile(); break;
case 5: _t->fileStatus((*reinterpret_cast< bool(*)>(_a[1]))); break;
default: ;
}
}
}
const QMetaObject FileExplorar::staticMetaObject = {
{ &QDialog::staticMetaObject, qt_meta_stringdata_FileExplorar.data,
qt_meta_data_FileExplorar, qt_static_metacall, nullptr, nullptr}
};
const QMetaObject *FileExplorar::metaObject() const
{
return QObject::d_ptr->metaObject ? QObject::d_ptr->dynamicMetaObject() : &staticMetaObject;
}
void *FileExplorar::qt_metacast(const char *_clname)
{
if (!_clname) return nullptr;
if (!strcmp(_clname, qt_meta_stringdata_FileExplorar.stringdata0))
return static_cast<void*>(this);
return QDialog::qt_metacast(_clname);
}
int FileExplorar::qt_metacall(QMetaObject::Call _c, int _id, void **_a)
{
_id = QDialog::qt_metacall(_c, _id, _a);
if (_id < 0)
return _id;
if (_c == QMetaObject::InvokeMetaMethod) {
if (_id < 6)
qt_static_metacall(this, _c, _id, _a);
_id -= 6;
} else if (_c == QMetaObject::RegisterMethodArgumentMetaType) {
if (_id < 6)
*reinterpret_cast<int*>(_a[0]) = -1;
_id -= 6;
}
return _id;
}
QT_WARNING_POP
QT_END_MOC_NAMESPACE
| [
"[email protected]"
] | |
271631737b9bce7e24e904e05d3e9bdbf7be51fd | d0a3dff524a2c561ea9eedba0311855aff21968f | /src/output_graph_as_dimacs.cpp | 742394c4ecaa4ba4cf0883dcc4b48a74bc280ab2 | [] | no_license | avadapal/Combinatorial-Min-Cost-Flow | 637ca42c75fb1080ea22cb58dde02209353d9522 | e2afdfcad3d1fd06a837020d71256236f6b33d5c | refs/heads/master | 2020-07-25T02:11:33.157959 | 2019-09-14T22:38:30 | 2019-09-14T22:38:30 | 208,127,593 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,998 | cpp | #include "graph.h"
#include "random.h"
#include "min_cost_flow_sspvariant.h"
#include "min_cost_flow_sspvariant_default.h"
//#include "min_cost_flow_sspvariant_apex_grid.h"
#include <iostream>
#include <queue>
#include <stack>
#include <vector>
#include <algorithm>
#include <math.h>
#include <fstream>
#include <boost/rational.hpp>
#include <tuple>
#include <chrono>
using namespace std;
int main(){
cout << "Enter filepath to input graph.. " << endl;
string filename;
cin >> filename;
// check if file exists
if (!std::ifstream(filename)) {
std::cerr << "File not found: " << filename << std::endl;
exit(1);
}
/*
if (boost::ends_with(filename, ".pgm") || boost::ends_with(filename, ".ppm")) {
#ifndef NEW_OPTIMIZATION
ifstream file(filename);
PPMImage image(file);
file.close();
InstanceConversion<8> instance(image);
auto start = std::chrono::steady_clock::now();
#ifdef RESP_CAP
successive_shortest_path_rc<decltype(instance.apexgrid), ApexGridNodeIterator, ApexGridEdgeIterator, ApexGridNodeAccessor, ApexGridEdgeAccessor, ApexGridIncidentEdgesIterator>(
instance.apexgrid,
ApexGridNodeIterator(instance.apexgrid, -1, -1),
ApexGridNodeIterator(instance.apexgrid, instance.apexgrid.height, 0),
ApexGridEdgeIterator(instance.apexgrid, -1, -1),
ApexGridEdgeIterator(instance.apexgrid, instance.apexgrid.height, 0));
#else
successive_shortest_path<decltype(instance.apexgrid), ApexGridNodeIterator, ApexGridEdgeIterator, ApexGridNodeAccessor, ApexGridEdgeAccessor, ApexGridIncidentEdgesIterator>(
instance.apexgrid,
ApexGridNodeIterator(instance.apexgrid, -1, -1),
ApexGridNodeIterator(instance.apexgrid, instance.apexgrid.height, 0));
#endif
auto elapsed_time = std::chrono::duration<double>(std::chrono::steady_clock::now() - start);
std::cout << "total time: " << elapsed_time.count() << "s" << std::endl;
assert(instance.apexgrid.check(0, instance.apexgrid.height, 0, instance.apexgrid.width));
#endif
return 0;
}
*/
using RationalType = long long int;
using IntegerType = long long int;
Graph<IntegerType, RationalType> G(filename);
#ifdef RESP_CAP
Network<decltype(G), IntegerType, RationalType, SSPVariantNodeData<IntegerType, RationalType>, SSPVariantRCArcData<IntegerType, RationalType>> N(G, filename);
#else
#ifdef RESTORE_BALANCED_NODES
Network<decltype(G), IntegerType, RationalType, SSPVariantNodeData<IntegerType, RationalType>, SSPVariantRBNArcData<RationalType>> N(G, filename);
#else
Network<decltype(G), IntegerType, RationalType, SSPVariantNodeData<IntegerType, RationalType>, BasicArcData<RationalType>> N(G, filename);
#endif
#endif
ofstream dimacs_out(filename + ".min");
N.write_dimacs(dimacs_out);
dimacs_out.close();
exit(0);
//cout << "Number of Edges: " << N.G.no_of_edges << endl;
//cout << "Number of Nodes: " << N.G.no_of_vertices << endl;
// unsigned int q;
return 0;
}
| [
"[email protected]"
] | |
ac79877fe8b67cd909950468d1eda7496587e420 | 58a70f395f61f905f7c51946a95acd8a92cd922c | /Tugas2/1.cpp | 118990eb2941eb5ed585273509d820143a78efc2 | [] | no_license | JustForC/KumpulanTugasAnalgo | f10f4fcaf6c8fb0805e6d00980e2d8cdb1869186 | 87dc1119c84dd5b7309b2b3b401788ebd65a05f8 | refs/heads/master | 2020-06-04T13:41:32.026231 | 2019-06-15T06:55:16 | 2019-06-15T06:55:16 | 192,046,741 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 422 | cpp | /*
Nama : Ghema Allan F
Kelas : B
NPM : 140810170048
Nama Program : Mencari nilai maks
*/
#include<iostream>
using namespace std;
int main(){
int x[99];
int n,maks,i;
cout<<"Masukkan Jumlah Angka : ";cin>>n;
for(int i=0;i<n;i++){
cout<<"Bilangan ke - "<<i+1<<" : ";cin>>x[i];
}
maks = 0;
for(int i=0;i<n;i++){
if(x[i]>maks)
maks=x[i];
}
cout<<"Output = "<<maks<<endl;
}
| [
"[email protected]"
] | |
e9408db972fd21d4372fdbb8368a07ff43b6b446 | f532dfc68d8ad1a6e7b8aaf5b7dbc92fbf0efc62 | /win32_C++/ConsolProJ02/C_495p_unicode01.cpp | b6eba9510168a7dad401a7ad86ca03cf6f8dcf51 | [] | no_license | NamYoonJae/InhaGame | 691fda687490fb70699f4018ac2888c0b08b5474 | 6e9872436cecccee44f97694f3a047a1d51d86ab | refs/heads/main | 2023-01-19T11:59:35.578386 | 2020-11-26T08:18:34 | 2020-11-26T08:18:34 | 305,272,697 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 246 | cpp | #include "stdafx.h"
#include <conio.h>
#include <windows.h>
#include <stdlib.h>
#include <string.h>
int main(void) {
wchar_t *pwszData = L"String";
wchar_t wszData[32];
wcscpy(wszData, pwszData);
wprintf(L"%s\n", wszData);
return 0;
} | [
"[email protected]"
] | |
64c693740275e666a00985f20ac4806a9c8534f3 | 232bc68c3ee472f244e9cb273488a2017e34d962 | /src/main/cpp/subsys/MechanismTypes.h | 87165289f549e806290075be43e88598b4f17423 | [
"BSD-3-Clause",
"MIT"
] | permissive | Team302/2019Beta | 3a3de9d1ae128c89a7c275d388b026c6057ed766 | aa8b5ef82f78aac2cc9d4e206753c2b38d28b6bd | refs/heads/master | 2022-04-07T09:45:51.004453 | 2020-01-02T05:09:39 | 2020-01-02T05:09:39 | 211,968,100 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,382 | h |
//====================================================================================================================================================
// Copyright 2019 Lake Orion Robotics FIRST Team 302
//
// 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.
//====================================================================================================================================================
#pragma once
//========================================================================================================
/// @class MechanismTypes
/// @brief This contains the enum for the mechanism types
//========================================================================================================
class MechanismTypes
{
public:
//==================================================================================
/// enum: MECHANISM_TYPE
/// description: Indicates the type of mechanism
//==================================================================================
enum MECHANISM_TYPE
{
UNKNOWN_MECHANISM = -1,
DRIVETRAIN_SIDE,
SHOOTER,
ELEVATOR,
WRIST,
INTAKE,
ARM,
EXTENDER,
CLIMBER,
BEAK,
TAIL,
MAX_MECHANISM_TYPES
};
};
| [
"[email protected]"
] | |
b18b4c4acd4e671213390d8d8fe84eac583f4d0b | 4d3a5f0f0bae49d665906048281575d36b96b0c8 | /include/box_parameters.h | 987f78d322c67fb3d74c43bf1dcf0910f73fb7f9 | [
"Apache-2.0"
] | permissive | rgiordan/LinearResponseVariationalBayes.cpp | 10f33d5c40379b5b6704ccc5aa73126f604ba87e | 99b0666bbb9e1c8a1b020b133bcc289f894c07c4 | refs/heads/master | 2021-01-17T02:53:58.890034 | 2016-11-28T20:22:53 | 2016-11-28T20:26:32 | 59,386,996 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,845 | h | # ifndef BOX_PARAMETERS_H
# define BOX_PARAMETERS_H
# include <limits>
// # include <stan/math.hpp>
# include "stan/math/mix/mat.hpp"
using stan::math::logit;
using stan::math::inv_logit;
// template<typename T> T inv_logit(T x) {
// if (x < 0) {
// throw std::runtime_error("x is less than zero");
// }
// if (x > 1) {
// throw std::runtime_error("x is greater than one");
// }
// return -1 * log(1.0 / x - 1);
// };
//
// template<typename T> T logit(T x) {
// return 1.0 / (1.0 + exp(-1.0 * x));
// };
template<typename T>
T unbox_parameter(T x, double lower_bound, double upper_bound, double scale) {
if (lower_bound > upper_bound) {
throw std::runtime_error("lower_bound must be less than upper_bound.");
}
if (x < lower_bound) {
throw std::runtime_error("lower_bound must be less than x.");
}
if (x > upper_bound) {
throw std::runtime_error("upper_bound must be greater than x.");
}
// If the upper bound is infinity, just interpret it as a positivity constraint.
if (upper_bound == std::numeric_limits<double>::infinity()) {
return log(x - lower_bound) * scale;
} else {
T x_bounded = (x - lower_bound) / (upper_bound - lower_bound);
return logit(x_bounded) * scale;
}
}
template<typename T>
T box_parameter(T x, double lower_bound, double upper_bound, double scale) {
if (lower_bound > upper_bound) {
throw std::runtime_error("lower_bound must be less than upper_bound.");
}
// If the upper bound is infinity, just interpret it as a positivity constraint.
if (upper_bound == std::numeric_limits<double>::infinity()) {
return exp(x / scale) + lower_bound;
} else {
return inv_logit(x / scale) * (upper_bound - lower_bound) + lower_bound;
}
}
# endif
| [
"[email protected]"
] | |
d6831cbbceb1b8a6e440eef9bb5f985895550124 | 3726ce663a4be9318c4e6d37ef25d95e3ace8cc9 | /UE4_ThirdParty/HarfBuzz/harfbuzz-2.4.0/src/hb-cache.hh | fc2f88810462a6c3eaf5dc37cc0bc2dfb3db5aac | [
"LicenseRef-scancode-other-permissive",
"LicenseRef-scancode-unknown-license-reference",
"MIT-Modern-Variant"
] | permissive | fdsalbj/UE4-HTML5-TPS | acd8d5e8c41d5e7804e8f01fc25d55bf4a6958a0 | be3518d02d53c2e29fd6039d9c7606e62536e435 | refs/heads/master | 2022-11-05T14:28:19.024569 | 2020-06-09T22:04:32 | 2020-06-09T22:04:32 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,675 | hh | /*
* Copyright © 2012 Google, Inc.
*
* This is part of HarfBuzz, a text shaping library.
*
* Permission is hereby granted, without written agreement and without
* license or royalty fees, to use, copy, modify, and distribute this
* software and its documentation for any purpose, provided that the
* above copyright notice and the following two paragraphs appear in
* all copies of this software.
*
* IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE TO ANY PARTY FOR
* DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES
* ARISING OUT OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN
* IF THE COPYRIGHT HOLDER HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH
* DAMAGE.
*
* THE COPYRIGHT HOLDER SPECIFICALLY DISCLAIMS ANY WARRANTIES, INCLUDING,
* BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
* FITNESS FOR A PARTICULAR PURPOSE. THE SOFTWARE PROVIDED HEREUNDER IS
* ON AN "AS IS" BASIS, AND THE COPYRIGHT HOLDER HAS NO OBLIGATION TO
* PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
*
* Google Author(s): Behdad Esfahbod
*/
#ifndef HB_CACHE_HH
#define HB_CACHE_HH
#include "hb.hh"
/* Implements a lock-free cache for int->int functions. */
template <unsigned int key_bits, unsigned int value_bits, unsigned int cache_bits>
struct hb_cache_t
{
static_assert ((key_bits >= cache_bits), "");
static_assert ((key_bits + value_bits - cache_bits <= 8 * sizeof (hb_atomic_int_t)), "");
static_assert (sizeof (hb_atomic_int_t) == sizeof (unsigned int), "");
void init () { clear (); }
void fini () {}
void clear ()
{
for (unsigned i = 0; i < ARRAY_LENGTH (values); i++)
values[i].set_relaxed (-1);
}
bool get (unsigned int key, unsigned int *value) const
{
unsigned int k = key & ((1u<<cache_bits)-1);
unsigned int v = values[k].get_relaxed ();
if ((key_bits + value_bits - cache_bits == 8 * sizeof (hb_atomic_int_t) && v == (unsigned int) -1) ||
(v >> value_bits) != (key >> cache_bits))
return false;
*value = v & ((1u<<value_bits)-1);
return true;
}
bool set (unsigned int key, unsigned int value)
{
if (unlikely ((key >> key_bits) || (value >> value_bits)))
return false; /* Overflows */
unsigned int k = key & ((1u<<cache_bits)-1);
unsigned int v = ((key>>cache_bits)<<value_bits) | value;
values[k].set_relaxed (v);
return true;
}
private:
hb_atomic_int_t values[1u<<cache_bits];
};
typedef hb_cache_t<21, 16, 8> hb_cmap_cache_t;
typedef hb_cache_t<16, 24, 8> hb_advance_cache_t;
#endif /* HB_CACHE_HH */
| [
"[email protected]"
] | |
6d57a8da92d4680c7197be7ef0698d30d6c6e894 | a6ed3dd9aa5429895c86875e7463caf298bfc16d | /Final/Source/Client/main.cpp | 3579c5b28b708a4339dcf47130abded24962fd3b | [] | no_license | glewn/ChatterBox | 4b77f7a976a6f1a5b6e708e73254f6f3fbdc54f2 | 9508c6eaac88f74e97bdfd9e2a49715a1d6bdecf | refs/heads/development | 2021-01-10T10:45:35.780645 | 2016-03-25T05:43:41 | 2016-03-25T05:43:41 | 53,089,384 | 1 | 2 | null | 2016-03-25T05:43:42 | 2016-03-03T22:37:08 | C++ | UTF-8 | C++ | false | false | 1,218 | cpp | /*------------------------------------------------------------------------------------------------------------------
-- SOURCE FILE: main.cpp
--
-- PROGRAM: ChatterBox
--
-- FUNCTIONS:
-- int main(int argc, char *argv[])
--
-- DATE: March 09, 2016
--
-- DESIGNER: Gabriel Lee
--
-- PROGRAMMER: Gabriel Lee
--
-- NOTES:
-- The entry point of the program.
----------------------------------------------------------------------------------------------------------------------*/
#include "mainwindow.h"
#include <QApplication>
/*------------------------------------------------------------------------------------------------------------------
-- FUNCTION: main
--
-- DATE: March 09, 2016
--
-- REVISIONS: (Date and Description)
-- March 09, 2016 - Function created.
--
-- DESIGNER: Gabriel Lee
--
-- PROGRAMMER: Gabriel Lee
--
-- INTERFACE: int main(int argc, char *argv[])
--
-- RETURNS: int - the exit code of the program
--
-- NOTES:
-- The main entry point of the program
----------------------------------------------------------------------------------------------------------------------*/
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
MainWindow w;
w.show();
return a.exec();
}
| [
"[email protected]"
] | |
0ba56819ef7525cff4bb4cf71ec611616bc9984e | cf27989ba7d00342358b63e55558c075a35c9ac4 | /global/1.cpp | 64ad0d41df33c4f810ccb52ce489cf260bc0619e | [] | no_license | VishalKhurana/DSA | 1b9f2888cd332b6741a61e6426b0586615157143 | 6fc90621f97dee4c10e3911f8f2cc95e4a0a7903 | refs/heads/master | 2022-12-04T12:31:32.104914 | 2020-08-30T14:57:03 | 2020-08-30T14:57:03 | 285,479,440 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 760 | cpp | #include<bits/stdc++.h>
using namespace std;
long long int sol( long long int a, long long int b, long long int n)
{
long long int count=0;
while(1)
{
if(a>n||b>n)
{
break;
}
if(a<b)
{
a=a+b;
count++;
}
else
{
b=b+a;
count++;
}
}
return count;
}
int main()
{
int t;
cin>>t;
for(int p=0;p<t;p++)
{
long long int n;
long long int a;
long long int b;
cin>>a;
cin>>b;
cin>>n;
long long ans=sol(a,b,n);
cout<<ans<<endl;
}
} | [
"[email protected]"
] | |
af6f673c31fc006c680a5c83c786ffac087c4e9a | 4e7f736969804451a12bf2a1124b964f15cc15e8 | /AOJ/GRL/1/B.cpp | fea7b90d21cd9fe92fa85424fc5f9c919692c629 | [] | no_license | hayaten0415/Competitive-programming | bb753303f9d8d1864991eb06fa823a9f74e42a4c | ea8bf51c1570566e631699aa7739cda973133f82 | refs/heads/master | 2022-11-26T07:11:46.953867 | 2022-11-01T16:18:04 | 2022-11-01T16:18:04 | 171,068,479 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,715 | cpp | #include <bits/stdc++.h>
#define rep(i, n) for (int i = 0; i < (n); i++)
#define rrep(i, n) for (int i = (n - 1); i >= 0; i--)
#define ALL(v) v.begin(), v.end()
using namespace std;
using P = pair<int, int>;
typedef long long ll;
template<class T> inline bool chmax(T& a, T b) { if (a < b) { a = b; return 1; } return 0; }
template<class T> inline bool chmin(T& a, T b) { if (a > b) { a = b; return 1; } return 0; }
const int dx[4] = {1, 0, -1, 0};
const int dy[4] = {0, 1, 0, -1};
const ll INF = (1LL << 60);
int n, m;
struct Edge {
int from, to;
ll cost;
};
vector<Edge> v;
ll dist[2200];
bool negative[2200];
void bellman_ford(int start){
rep(i, n) dist[i] = INF;
dist[start] = 0;
for (int i = 0; i < n-1; i++){
for (int j = 0; j < v.size(); j++){
Edge e = v[j];
if(dist[e.from] != INF && dist[e.to] > dist[e.from] + e.cost){
dist[e.to] = dist[e.from] + e.cost;
}
}
}
return;
}
void negative_loop(){
rep(i, n) negative[i] = false;
rep(i, n){
for (int j = 0; j < v.size(); j++){
Edge e = v[j];
if(dist[e.to] != INF && dist[e.to] > dist[e.from] + e.cost){
dist[e.to] = dist[e.from] + e.cost;
negative[e.to] = true;
}
if(negative[e.from])negative[e.to] = true;
}
}
}
int main() {
int r;
cin >> n >> m >> r;
rep(i, m){
int a, b;
ll c;
cin >> a >> b >> c;
v.push_back((Edge{a, b, c}));
}
bellman_ford(r);
negative_loop();
bool ng = false;
rep(i, n){
if(negative[i])ng = true;
}
if(ng){
cout << "NEGATIVE CYCLE" << endl;
}else{
rep(i, n){
if(dist[i] == INF){
cout << "INF" << endl;
}else{
cout << dist[i] << endl;
}
}
}
} | [
"[email protected]"
] | |
e925c7085ba8736a7f2b970a6a16bcc46aa165e4 | 9606558f5b185751703c10ab29b851cdea35c33c | /Sources/yocto_wakeupmonitor.cpp | 99bb4e498135cb5b56913e75b44d77bd7eb68554 | [] | no_license | LudovicRousseau/yoctolib_cpp | b4847ce2d7ed89d06e455d0eeb939abf988dc5d3 | 148282fccee5d9d7232683bd64c86fbafff051a8 | refs/heads/master | 2022-12-13T13:45:26.752285 | 2022-12-02T18:31:20 | 2022-12-02T18:31:20 | 12,010,115 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 18,544 | cpp | /*********************************************************************
*
* $Id: yocto_wakeupmonitor.cpp 48183 2022-01-20 10:26:11Z mvuilleu $
*
* Implements yFindWakeUpMonitor(), the high-level API for WakeUpMonitor functions
*
* - - - - - - - - - License information: - - - - - - - - -
*
* Copyright (C) 2011 and beyond by Yoctopuce Sarl, Switzerland.
*
* Yoctopuce Sarl (hereafter Licensor) grants to you a perpetual
* non-exclusive license to use, modify, copy and integrate this
* file into your software for the sole purpose of interfacing
* with Yoctopuce products.
*
* You may reproduce and distribute copies of this file in
* source or object form, as long as the sole purpose of this
* code is to interface with Yoctopuce products. You must retain
* this notice in the distributed source file.
*
* You should refer to Yoctopuce General Terms and Conditions
* for additional information regarding your rights and
* obligations.
*
* THE SOFTWARE AND DOCUMENTATION ARE PROVIDED 'AS IS' WITHOUT
* WARRANTY OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING
* WITHOUT LIMITATION, ANY WARRANTY OF MERCHANTABILITY, FITNESS
* FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO
* EVENT SHALL LICENSOR BE LIABLE FOR ANY INCIDENTAL, SPECIAL,
* INDIRECT OR CONSEQUENTIAL DAMAGES, LOST PROFITS OR LOST DATA,
* COST OF PROCUREMENT OF SUBSTITUTE GOODS, TECHNOLOGY OR
* SERVICES, ANY CLAIMS BY THIRD PARTIES (INCLUDING BUT NOT
* LIMITED TO ANY DEFENSE THEREOF), ANY CLAIMS FOR INDEMNITY OR
* CONTRIBUTION, OR OTHER SIMILAR COSTS, WHETHER ASSERTED ON THE
* BASIS OF CONTRACT, TORT (INCLUDING NEGLIGENCE), BREACH OF
* WARRANTY, OR OTHERWISE.
*
*********************************************************************/
#define _CRT_SECURE_NO_DEPRECATE //do not use windows secure crt
#include <string.h>
#include <stdio.h>
#include <math.h>
#include <stdlib.h>
#include "yocto_wakeupmonitor.h"
#include "yapi/yjson.h"
#include "yapi/yapi.h"
#define __FILE_ID__ "wakeupmonitor"
#ifdef YOCTOLIB_NAMESPACE
using namespace YOCTOLIB_NAMESPACE;
#endif
YWakeUpMonitor::YWakeUpMonitor(const string& func): YFunction(func)
//--- (YWakeUpMonitor initialization)
,_powerDuration(POWERDURATION_INVALID)
,_sleepCountdown(SLEEPCOUNTDOWN_INVALID)
,_nextWakeUp(NEXTWAKEUP_INVALID)
,_wakeUpReason(WAKEUPREASON_INVALID)
,_wakeUpState(WAKEUPSTATE_INVALID)
,_rtcTime(RTCTIME_INVALID)
,_endOfTime(2145960000)
,_valueCallbackWakeUpMonitor(NULL)
//--- (end of YWakeUpMonitor initialization)
{
_className="WakeUpMonitor";
}
YWakeUpMonitor::~YWakeUpMonitor()
{
//--- (YWakeUpMonitor cleanup)
//--- (end of YWakeUpMonitor cleanup)
}
//--- (YWakeUpMonitor implementation)
// static attributes
int YWakeUpMonitor::_parseAttr(YJSONObject *json_val)
{
if(json_val->has("powerDuration")) {
_powerDuration = json_val->getInt("powerDuration");
}
if(json_val->has("sleepCountdown")) {
_sleepCountdown = json_val->getInt("sleepCountdown");
}
if(json_val->has("nextWakeUp")) {
_nextWakeUp = json_val->getLong("nextWakeUp");
}
if(json_val->has("wakeUpReason")) {
_wakeUpReason = (Y_WAKEUPREASON_enum)json_val->getInt("wakeUpReason");
}
if(json_val->has("wakeUpState")) {
_wakeUpState = (Y_WAKEUPSTATE_enum)json_val->getInt("wakeUpState");
}
if(json_val->has("rtcTime")) {
_rtcTime = json_val->getLong("rtcTime");
}
return YFunction::_parseAttr(json_val);
}
/**
* Returns the maximal wake up time (in seconds) before automatically going to sleep.
*
* @return an integer corresponding to the maximal wake up time (in seconds) before automatically going to sleep
*
* On failure, throws an exception or returns YWakeUpMonitor::POWERDURATION_INVALID.
*/
int YWakeUpMonitor::get_powerDuration(void)
{
int res = 0;
yEnterCriticalSection(&_this_cs);
try {
if (_cacheExpiration <= YAPI::GetTickCount()) {
if (this->_load_unsafe(YAPI::_yapiContext.GetCacheValidity()) != YAPI_SUCCESS) {
{
yLeaveCriticalSection(&_this_cs);
return YWakeUpMonitor::POWERDURATION_INVALID;
}
}
}
res = _powerDuration;
} catch (std::exception &) {
yLeaveCriticalSection(&_this_cs);
throw;
}
yLeaveCriticalSection(&_this_cs);
return res;
}
/**
* Changes the maximal wake up time (seconds) before automatically going to sleep.
* Remember to call the saveToFlash() method of the module if the
* modification must be kept.
*
* @param newval : an integer corresponding to the maximal wake up time (seconds) before automatically
* going to sleep
*
* @return YAPI::SUCCESS if the call succeeds.
*
* On failure, throws an exception or returns a negative error code.
*/
int YWakeUpMonitor::set_powerDuration(int newval)
{
string rest_val;
int res;
yEnterCriticalSection(&_this_cs);
try {
char buf[32]; sprintf(buf, "%d", newval); rest_val = string(buf);
res = _setAttr("powerDuration", rest_val);
} catch (std::exception &) {
yLeaveCriticalSection(&_this_cs);
throw;
}
yLeaveCriticalSection(&_this_cs);
return res;
}
/**
* Returns the delay before the next sleep period.
*
* @return an integer corresponding to the delay before the next sleep period
*
* On failure, throws an exception or returns YWakeUpMonitor::SLEEPCOUNTDOWN_INVALID.
*/
int YWakeUpMonitor::get_sleepCountdown(void)
{
int res = 0;
yEnterCriticalSection(&_this_cs);
try {
if (_cacheExpiration <= YAPI::GetTickCount()) {
if (this->_load_unsafe(YAPI::_yapiContext.GetCacheValidity()) != YAPI_SUCCESS) {
{
yLeaveCriticalSection(&_this_cs);
return YWakeUpMonitor::SLEEPCOUNTDOWN_INVALID;
}
}
}
res = _sleepCountdown;
} catch (std::exception &) {
yLeaveCriticalSection(&_this_cs);
throw;
}
yLeaveCriticalSection(&_this_cs);
return res;
}
/**
* Changes the delay before the next sleep period.
*
* @param newval : an integer corresponding to the delay before the next sleep period
*
* @return YAPI::SUCCESS if the call succeeds.
*
* On failure, throws an exception or returns a negative error code.
*/
int YWakeUpMonitor::set_sleepCountdown(int newval)
{
string rest_val;
int res;
yEnterCriticalSection(&_this_cs);
try {
char buf[32]; sprintf(buf, "%d", newval); rest_val = string(buf);
res = _setAttr("sleepCountdown", rest_val);
} catch (std::exception &) {
yLeaveCriticalSection(&_this_cs);
throw;
}
yLeaveCriticalSection(&_this_cs);
return res;
}
/**
* Returns the next scheduled wake up date/time (UNIX format).
*
* @return an integer corresponding to the next scheduled wake up date/time (UNIX format)
*
* On failure, throws an exception or returns YWakeUpMonitor::NEXTWAKEUP_INVALID.
*/
s64 YWakeUpMonitor::get_nextWakeUp(void)
{
s64 res = 0;
yEnterCriticalSection(&_this_cs);
try {
if (_cacheExpiration <= YAPI::GetTickCount()) {
if (this->_load_unsafe(YAPI::_yapiContext.GetCacheValidity()) != YAPI_SUCCESS) {
{
yLeaveCriticalSection(&_this_cs);
return YWakeUpMonitor::NEXTWAKEUP_INVALID;
}
}
}
res = _nextWakeUp;
} catch (std::exception &) {
yLeaveCriticalSection(&_this_cs);
throw;
}
yLeaveCriticalSection(&_this_cs);
return res;
}
/**
* Changes the days of the week when a wake up must take place.
*
* @param newval : an integer corresponding to the days of the week when a wake up must take place
*
* @return YAPI::SUCCESS if the call succeeds.
*
* On failure, throws an exception or returns a negative error code.
*/
int YWakeUpMonitor::set_nextWakeUp(s64 newval)
{
string rest_val;
int res;
yEnterCriticalSection(&_this_cs);
try {
char buf[32]; sprintf(buf, "%u", (u32)newval); rest_val = string(buf);
res = _setAttr("nextWakeUp", rest_val);
} catch (std::exception &) {
yLeaveCriticalSection(&_this_cs);
throw;
}
yLeaveCriticalSection(&_this_cs);
return res;
}
/**
* Returns the latest wake up reason.
*
* @return a value among YWakeUpMonitor::WAKEUPREASON_USBPOWER, YWakeUpMonitor::WAKEUPREASON_EXTPOWER,
* YWakeUpMonitor::WAKEUPREASON_ENDOFSLEEP, YWakeUpMonitor::WAKEUPREASON_EXTSIG1,
* YWakeUpMonitor::WAKEUPREASON_SCHEDULE1 and YWakeUpMonitor::WAKEUPREASON_SCHEDULE2 corresponding to
* the latest wake up reason
*
* On failure, throws an exception or returns YWakeUpMonitor::WAKEUPREASON_INVALID.
*/
Y_WAKEUPREASON_enum YWakeUpMonitor::get_wakeUpReason(void)
{
Y_WAKEUPREASON_enum res;
yEnterCriticalSection(&_this_cs);
try {
if (_cacheExpiration <= YAPI::GetTickCount()) {
if (this->_load_unsafe(YAPI::_yapiContext.GetCacheValidity()) != YAPI_SUCCESS) {
{
yLeaveCriticalSection(&_this_cs);
return YWakeUpMonitor::WAKEUPREASON_INVALID;
}
}
}
res = _wakeUpReason;
} catch (std::exception &) {
yLeaveCriticalSection(&_this_cs);
throw;
}
yLeaveCriticalSection(&_this_cs);
return res;
}
/**
* Returns the current state of the monitor.
*
* @return either YWakeUpMonitor::WAKEUPSTATE_SLEEPING or YWakeUpMonitor::WAKEUPSTATE_AWAKE, according
* to the current state of the monitor
*
* On failure, throws an exception or returns YWakeUpMonitor::WAKEUPSTATE_INVALID.
*/
Y_WAKEUPSTATE_enum YWakeUpMonitor::get_wakeUpState(void)
{
Y_WAKEUPSTATE_enum res;
yEnterCriticalSection(&_this_cs);
try {
if (_cacheExpiration <= YAPI::GetTickCount()) {
if (this->_load_unsafe(YAPI::_yapiContext.GetCacheValidity()) != YAPI_SUCCESS) {
{
yLeaveCriticalSection(&_this_cs);
return YWakeUpMonitor::WAKEUPSTATE_INVALID;
}
}
}
res = _wakeUpState;
} catch (std::exception &) {
yLeaveCriticalSection(&_this_cs);
throw;
}
yLeaveCriticalSection(&_this_cs);
return res;
}
int YWakeUpMonitor::set_wakeUpState(Y_WAKEUPSTATE_enum newval)
{
string rest_val;
int res;
yEnterCriticalSection(&_this_cs);
try {
char buf[32]; sprintf(buf, "%d", newval); rest_val = string(buf);
res = _setAttr("wakeUpState", rest_val);
} catch (std::exception &) {
yLeaveCriticalSection(&_this_cs);
throw;
}
yLeaveCriticalSection(&_this_cs);
return res;
}
s64 YWakeUpMonitor::get_rtcTime(void)
{
s64 res = 0;
yEnterCriticalSection(&_this_cs);
try {
if (_cacheExpiration <= YAPI::GetTickCount()) {
if (this->_load_unsafe(YAPI::_yapiContext.GetCacheValidity()) != YAPI_SUCCESS) {
{
yLeaveCriticalSection(&_this_cs);
return YWakeUpMonitor::RTCTIME_INVALID;
}
}
}
res = _rtcTime;
} catch (std::exception &) {
yLeaveCriticalSection(&_this_cs);
throw;
}
yLeaveCriticalSection(&_this_cs);
return res;
}
/**
* Retrieves a wake-up monitor for a given identifier.
* The identifier can be specified using several formats:
* <ul>
* <li>FunctionLogicalName</li>
* <li>ModuleSerialNumber.FunctionIdentifier</li>
* <li>ModuleSerialNumber.FunctionLogicalName</li>
* <li>ModuleLogicalName.FunctionIdentifier</li>
* <li>ModuleLogicalName.FunctionLogicalName</li>
* </ul>
*
* This function does not require that the wake-up monitor is online at the time
* it is invoked. The returned object is nevertheless valid.
* Use the method isOnline() to test if the wake-up monitor is
* indeed online at a given time. In case of ambiguity when looking for
* a wake-up monitor by logical name, no error is notified: the first instance
* found is returned. The search is performed first by hardware name,
* then by logical name.
*
* If a call to this object's is_online() method returns FALSE although
* you are certain that the matching device is plugged, make sure that you did
* call registerHub() at application initialization time.
*
* @param func : a string that uniquely characterizes the wake-up monitor, for instance
* YHUBGSM5.wakeUpMonitor.
*
* @return a YWakeUpMonitor object allowing you to drive the wake-up monitor.
*/
YWakeUpMonitor* YWakeUpMonitor::FindWakeUpMonitor(string func)
{
YWakeUpMonitor* obj = NULL;
int taken = 0;
if (YAPI::_apiInitialized) {
yEnterCriticalSection(&YAPI::_global_cs);
taken = 1;
}try {
obj = (YWakeUpMonitor*) YFunction::_FindFromCache("WakeUpMonitor", func);
if (obj == NULL) {
obj = new YWakeUpMonitor(func);
YFunction::_AddToCache("WakeUpMonitor", func, obj);
}
} catch (std::exception &) {
if (taken) yLeaveCriticalSection(&YAPI::_global_cs);
throw;
}
if (taken) yLeaveCriticalSection(&YAPI::_global_cs);
return obj;
}
/**
* Registers the callback function that is invoked on every change of advertised value.
* The callback is invoked only during the execution of ySleep or yHandleEvents.
* This provides control over the time when the callback is triggered. For good responsiveness, remember to call
* one of these two functions periodically. To unregister a callback, pass a NULL pointer as argument.
*
* @param callback : the callback function to call, or a NULL pointer. The callback function should take two
* arguments: the function object of which the value has changed, and the character string describing
* the new advertised value.
* @noreturn
*/
int YWakeUpMonitor::registerValueCallback(YWakeUpMonitorValueCallback callback)
{
string val;
if (callback != NULL) {
YFunction::_UpdateValueCallbackList(this, true);
} else {
YFunction::_UpdateValueCallbackList(this, false);
}
_valueCallbackWakeUpMonitor = callback;
// Immediately invoke value callback with current value
if (callback != NULL && this->isOnline()) {
val = _advertisedValue;
if (!(val == "")) {
this->_invokeValueCallback(val);
}
}
return 0;
}
int YWakeUpMonitor::_invokeValueCallback(string value)
{
if (_valueCallbackWakeUpMonitor != NULL) {
_valueCallbackWakeUpMonitor(this, value);
} else {
YFunction::_invokeValueCallback(value);
}
return 0;
}
/**
* Forces a wake up.
*/
int YWakeUpMonitor::wakeUp(void)
{
return this->set_wakeUpState(Y_WAKEUPSTATE_AWAKE);
}
/**
* Goes to sleep until the next wake up condition is met, the
* RTC time must have been set before calling this function.
*
* @param secBeforeSleep : number of seconds before going into sleep mode,
*
* @return YAPI::SUCCESS if the call succeeds.
*
* On failure, throws an exception or returns a negative error code.
*/
int YWakeUpMonitor::sleep(int secBeforeSleep)
{
int currTime = 0;
currTime = (int)(this->get_rtcTime());
if (!(currTime != 0)) {
_throw(YAPI_RTC_NOT_READY,"RTC time not set");
return YAPI_RTC_NOT_READY;
}
this->set_nextWakeUp(_endOfTime);
this->set_sleepCountdown(secBeforeSleep);
return YAPI_SUCCESS;
}
/**
* Goes to sleep for a specific duration or until the next wake up condition is met, the
* RTC time must have been set before calling this function. The count down before sleep
* can be canceled with resetSleepCountDown.
*
* @param secUntilWakeUp : number of seconds before next wake up
* @param secBeforeSleep : number of seconds before going into sleep mode
*
* @return YAPI::SUCCESS if the call succeeds.
*
* On failure, throws an exception or returns a negative error code.
*/
int YWakeUpMonitor::sleepFor(int secUntilWakeUp,int secBeforeSleep)
{
int currTime = 0;
currTime = (int)(this->get_rtcTime());
if (!(currTime != 0)) {
_throw(YAPI_RTC_NOT_READY,"RTC time not set");
return YAPI_RTC_NOT_READY;
}
this->set_nextWakeUp(currTime+secUntilWakeUp);
this->set_sleepCountdown(secBeforeSleep);
return YAPI_SUCCESS;
}
/**
* Go to sleep until a specific date is reached or until the next wake up condition is met, the
* RTC time must have been set before calling this function. The count down before sleep
* can be canceled with resetSleepCountDown.
*
* @param wakeUpTime : wake-up datetime (UNIX format)
* @param secBeforeSleep : number of seconds before going into sleep mode
*
* @return YAPI::SUCCESS if the call succeeds.
*
* On failure, throws an exception or returns a negative error code.
*/
int YWakeUpMonitor::sleepUntil(int wakeUpTime,int secBeforeSleep)
{
int currTime = 0;
currTime = (int)(this->get_rtcTime());
if (!(currTime != 0)) {
_throw(YAPI_RTC_NOT_READY,"RTC time not set");
return YAPI_RTC_NOT_READY;
}
this->set_nextWakeUp(wakeUpTime);
this->set_sleepCountdown(secBeforeSleep);
return YAPI_SUCCESS;
}
/**
* Resets the sleep countdown.
*
* @return YAPI::SUCCESS if the call succeeds.
* On failure, throws an exception or returns a negative error code.
*/
int YWakeUpMonitor::resetSleepCountDown(void)
{
this->set_sleepCountdown(0);
this->set_nextWakeUp(0);
return YAPI_SUCCESS;
}
YWakeUpMonitor *YWakeUpMonitor::nextWakeUpMonitor(void)
{
string hwid;
if(YISERR(_nextFunction(hwid)) || hwid=="") {
return NULL;
}
return YWakeUpMonitor::FindWakeUpMonitor(hwid);
}
YWakeUpMonitor *YWakeUpMonitor::FirstWakeUpMonitor(void)
{
vector<YFUN_DESCR> v_fundescr;
YDEV_DESCR ydevice;
string serial, funcId, funcName, funcVal, errmsg;
if(YISERR(YapiWrapper::getFunctionsByClass("WakeUpMonitor", 0, v_fundescr, sizeof(YFUN_DESCR), errmsg)) ||
v_fundescr.size() == 0 ||
YISERR(YapiWrapper::getFunctionInfo(v_fundescr[0], ydevice, serial, funcId, funcName, funcVal, errmsg))) {
return NULL;
}
return YWakeUpMonitor::FindWakeUpMonitor(serial+"."+funcId);
}
//--- (end of YWakeUpMonitor implementation)
//--- (YWakeUpMonitor functions)
//--- (end of YWakeUpMonitor functions)
| [
"[email protected]"
] | |
2ff03e865698987b622575c0a75982e4a68cb153 | 59eb08a8296e3d427f5b1ce05eb131515b88594c | /Day3/sample.hpp | 7120bd07d1a12c3edee78213c160169b72688c9e | [] | no_license | tsukasan3/Cpp_one_week_learning | 630713b6d20cf843f3766fdd47a19d9e1cd97518 | 465df89df108ea45f86d4519df7ca8665befdec0 | refs/heads/main | 2023-01-24T17:06:10.213245 | 2020-12-01T07:55:50 | 2020-12-01T07:55:50 | 314,215,360 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 145 | hpp | #ifndef SAMPLE_HPP
#define SAMPLE_HPP
class Sample{
public:
int a;
void func1();
private:
int b;
void func2();
};
#endif // SAMPLE_HPP
| [
"[email protected]"
] | |
e695ba1abb171a4177df6e8ad0b3a3bfc4193c73 | 0b7a69ea4cbaf01f82723dbd7206fe0fbaa99f4c | /GeometryAlgorithm.cpp | e52f1cd6136e86d35411cbd70efd18dad1e3f5e8 | [
"MIT"
] | permissive | gisdevelope/LidarProc | 2492aee6ed679968a8350931a1ec8d448d69cb4b | 1b6047d6c35cedc4a4ac1fb63410b9db81b1c48b | refs/heads/master | 2020-04-02T22:29:50.375740 | 2018-10-17T12:36:22 | 2018-10-17T12:36:22 | null | 0 | 0 | null | null | null | null | GB18030 | C++ | false | false | 13,666 | cpp | #include <assert.h>
#include <stdio.h>
#include "../LidarAlgorithm/GeometryAlgorithm.h"
#include "../LidarAlgorithm/GeometryAlgorithm.h"
#include "../LidarBase/tsmToUTM.h"
#pragma warning(disable:4996)
static bool Is_Equal_Eps(double v1, double v2, double epsilon)
{
return abs(v1 - v2) <= epsilon;
}
#ifndef EPSILON
const static double EPSILON = 1.0e-8;
#endif // !EPSILON
#ifndef EPSILONF
const static float EPSILONF = 1.0e-6F;
#endif // !EPSILONF
int GeometryRelation::IsPointOnPolyline(double x, double y, const double* polyline, int doubleArrayCnt,
double tolerance, bool isClosed, int offset)
{
int ptsCnt = doubleArrayCnt / offset;
assert(ptsCnt >= 2);
int cnt = ptsCnt - 1;
int index, index2;
for (int k = 0; k < cnt; k++)
{
index = k * offset;
index2 = index + offset;
if (IsPointOnLine(x, y, polyline[index], polyline[index + 1], polyline[index2],
polyline[index2 + 1], tolerance))
{
return k;
}
}
if (isClosed)
{
index = cnt * offset;
if (IsPointOnLine(x, y, polyline[index], polyline[index + 1], polyline[0], polyline[1], tolerance))
{
return cnt;
}
}
return -1;
}
bool GeometryRelation::IsPointOnLine(double x, double y, double x0, double y0, double x1, double y1, double tolerance)
{
assert(tolerance >= 0);
Rect2D rect;
rect.minx = min(x0, x1);
rect.maxx = max(x0, x1);
rect.miny = min(y0, y1);
rect.maxy = max(y0, y1);
rect.Normalize();
rect.minx -= tolerance;
rect.maxx += tolerance;
rect.miny -= tolerance;
rect.maxy += tolerance;
if (rect.IsInclude(x, y))
{
return IsPointOnBeeline(x, y, x0, y0, x1, y1, tolerance);
}
return false;
}
bool GeometryRelation::IsPointOnBeeline(double x, double y, double x0, double y0, double x1, double y1,
double tolerance)
{
assert(tolerance >= 0);
double dissqr = DistanceComputation::SquarePointToBeeline(x, y, x0, y0, x1, y1);
return dissqr < tolerance * tolerance;
}
bool GeometryRelation::IsPointInPolygon(double x, double y, const double* polygon, double doubleArrayCnt,
bool allowonisin, double tolerance, int offset)
{
int ptsCnt = int(doubleArrayCnt / offset);
assert(ptsCnt >= 3);
bool isin = false;
if (allowonisin)
{
int index = IsPointOnPolyline(x, y, polygon, (int)doubleArrayCnt, tolerance, true, offset);
isin = index != -1;
}
if (!isin)
{
isin = IsPointInPolygon(x, y, polygon, (int)doubleArrayCnt, offset);
}
return isin;
}
bool GeometryRelation::IsPointInPolygon(double x, double y, const Point2Ds& polygon)
{
return GeometryRelation::IsPointInPolygon(x, y, (const double*)&(polygon[0].x), polygon.size() * 2, Point2D::SizeofPoint2);
}
bool GeometryRelation::IsPointInPolygon(double x, double y, const double* polygon,
int doubleArrayCnt, int offset)
{
int ptsCnt = doubleArrayCnt / offset;
assert(ptsCnt >= 3);
int wn = 0; // the winding number counter
double startx, starty, nextx, nexty;
for (int i = 0; i < ptsCnt - 1; i++)
{
int index = i * offset;
startx = polygon[index];
starty = polygon[index + 1];
nextx = polygon[index + offset];
nexty = polygon[index + offset + 1];
if (starty <= y) // start y <= pt->y
{
if (nexty > y) // an upward crossing
if (IsLeft(startx, starty, nextx, nexty, x, y) > 0) // P left of edge
++wn; // have a valid up intersect
}
else// start y > P.y (no test needed)
{
if (nexty <= y) // a downward crossing
if (IsLeft(startx, starty, nextx, nexty, x, y) < 0) // P right of edge
--wn; // have a valid down intersect
}
}
int index = (ptsCnt - 1) * offset;
startx = polygon[index];
starty = polygon[index + 1];
nextx = polygon[0];
nexty = polygon[1];
if (starty <= y) // start y <= pt->y
{
if (nexty > y) // an upward crossing
if (IsLeft(startx, starty, nextx, nexty, x, y) > 0) // P left of edge
++wn; // have a valid up intersect
}
else
{ // start y > P.y (no test needed)
if (nexty <= y) // a downward crossing
if (IsLeft(startx, starty, nextx, nexty, x, y) < 0) // P right of edge
--wn; // have a valid down intersect
}
if (wn == 0)
return false;
return true;
}
double GeometryRelation::IsLeft(double startx, double starty, double endx, double endy,
double x, double y)
{
return ((endx - startx) * (y - starty) - (x - startx) * (endy - starty));
}
bool GeometryRelation::IsPointOnRect(double x, double y, double xmin, double ymin,
double xmax, double ymax, double tolerance)
{
bool b = (x >= xmin - tolerance && x <= xmax + tolerance
&& (Is_Equal_Eps(y, ymin, tolerance) || Is_Equal_Eps(y, ymax, tolerance)))
|| (y >= ymin - tolerance && y <= ymax + tolerance
&& (Is_Equal_Eps(x, xmin, tolerance) || Is_Equal_Eps(x, xmax, tolerance)));
return b;
}
bool GeometryRelation::IsPolylineInRect(const double* polyline, int doubleArrayCnt, double minx,
double miny, double maxx, double maxy, int offset)
{
Rect2D user(minx, miny, maxx, maxy);
user.Normalize();
int ptsCnt = doubleArrayCnt / offset;
for (int i = 0; i < ptsCnt; i++)
{
int index = i * offset;
double x = polyline[index];
double y = polyline[index + 1];
if (!user.IsInclude(x, y))
{
return false;
}
}
return true;
}
bool GeometryRelation::IsLineIntersectRect(double x0, double y0, double x1, double y1, double xmin,
double ymin, double xmax, double ymax)
{
double deltax = x1 - x0;
double deltay = y1 - y0;
if (deltax == 0 && deltay == 0)
{
if (GeometryRelation::IsPointOnRect(x0, y0, xmin, ymin, xmax, ymax, EPSILON))
{
return true;
}
}
else
{
if (deltax != 0)
{
//????
double u = (xmin - x0) / deltax;
if (u >= 0 && u <= 1)//???xmin???line??
{
double y = y0 + u * deltay;
if (y >= ymin && y <= ymax)
{
return true;
}
}
//????
u = (xmax - x0) / deltax;
if (u >= 0 && u <= 1)//???xmax???line??
{
double y = y0 + u * deltay;
if (y >= ymin && y <= ymax)
{
return true;
}
}
}
if (deltay != 0)
{
//???
double u = (ymin - y0) / deltay;
if (u >= 0 && u <= 1)//???ymin???line??
{
double x = x0 + u * deltax;
if (x >= xmin && x <= xmax)
{
return true;
}
}
//????
u = (ymax - y0) / deltay;
if (u >= 0 && u <= 1)//???ymax???line??
{
double x = x0 + u * deltax;
if (x >= xmin && x <= xmax)
{
return true;
}
}
}
}
return false;
}
bool GeometryRelation::IsRectIntersectPolyline(double xmin, double ymin, double xmax,
double ymax, const double* polyline, int doubleArrayCnt, bool isClosed, int offset)
{
int ptsCnt = doubleArrayCnt / offset;
int index = -1, index2 = -1;
for (int k = 1; k < ptsCnt; k++)
{
index2 = k * offset;
index = index2 - offset;
double x1 = polyline[index];
double y1 = polyline[index + 1];
double x2 = polyline[index2];
double y2 = polyline[index2 + 1];
if (IsLineIntersectRect(x1, y1, x2, y2, xmin, ymin, xmax, ymax))
{
return true;
}
}
if (isClosed)
{
index = (ptsCnt - 1) * offset;
double x1 = polyline[index];
double y1 = polyline[index + 1];
double x2 = polyline[0];
double y2 = polyline[1];
if (IsLineIntersectRect(x1, y1, x2, y2, xmin, ymin, xmax, ymax))
{
return true;
}
}
return false;
}
bool GeometryRelation::IsPointInRect(int x, int y, int rect_x1, int rect_y1, int rect_x2, int rect_y2)
{
if (((x < rect_x1 && x > rect_x2) || (x >rect_x1 && x < rect_x2)) &&
((y < rect_y1 && y > rect_y2) || (y >rect_y1 && y < rect_y2)))
return true;
return false;
}
bool GeometryRelation::IsRectIntersectSlantingRect(const Rect2D& rect, const Point2Ds& pts)
{
assert(pts.size() == 4);
Rect2D bound; // ?????????
size_t ptId = 0;
size_t ptCnt = pts.size();
for (ptId = 0; ptId < ptCnt; ptId++)
{
bound.Merge(pts[ptId].x, pts[ptId].y);
}
return GeometryRelation::IsRectIntersectSlantingRect(rect, pts, bound);
}
bool GeometryRelation::IsRectIntersectSlantingRect(const Rect2D& rect, const Point2Ds& pts,
const Rect2D& slantingRect)
{
if (!rect.IsIntersect(slantingRect))
{
return false;
}
size_t lineId = 0;
size_t startPtId, endPtId, crossPtId;
for (lineId = 0; lineId < 4; lineId++)
{
startPtId = lineId;
endPtId = (startPtId + 1) % 4;
crossPtId = (endPtId + 1) % 4;
double crossDir = GeometryRelation::IsLeft(pts[startPtId].x, pts[startPtId].y,
pts[endPtId].x, pts[endPtId].y, pts[crossPtId].x, pts[crossPtId].y);
double curDir0 = GeometryRelation::IsLeft(pts[startPtId].x, pts[startPtId].y,
pts[endPtId].x, pts[endPtId].y, rect.minx, rect.miny);
if (crossDir > EPSILON && curDir0 > EPSILON ||
crossDir < -EPSILON && curDir0 < -EPSILON)
{
continue;
}
double curDir1 = GeometryRelation::IsLeft(pts[startPtId].x, pts[startPtId].y,
pts[endPtId].x, pts[endPtId].y, rect.minx, rect.maxy);
if (crossDir > EPSILON && curDir1 > EPSILON ||
crossDir < -EPSILON && curDir1 < -EPSILON)
{
continue;
}
double curDir2 = GeometryRelation::IsLeft(pts[startPtId].x, pts[startPtId].y,
pts[endPtId].x, pts[endPtId].y, rect.maxx, rect.miny);
if (crossDir > EPSILON && curDir2 > EPSILON ||
crossDir < -EPSILON && curDir2 < -EPSILON)
{
continue;
}
double curDir3 = GeometryRelation::IsLeft(pts[startPtId].x, pts[startPtId].y,
pts[endPtId].x, pts[endPtId].y, rect.maxx, rect.maxy);
if (crossDir > EPSILON && curDir3 > EPSILON ||
crossDir < -EPSILON && curDir3 < -EPSILON)
{
continue;
}
return false;
}
return true;
}
bool GeometryRelation::IsRectIntersectRect(const Rect2D& rect1, const Rect2D& rect2)
{
//判断矩形相交的代码有错误
//if (IsPointInRect(rect1.minx, rect1.miny, rect2.minx, rect2.miny, rect2.maxx, rect2.maxy))
//{
// return true;
//}
//else if (IsPointInRect(rect1.minx, rect1.maxy, rect2.minx, rect2.miny, rect2.maxx, rect2.maxy))
//{
// return true;
//}
//else if (IsPointInRect(rect1.maxx, rect1.miny, rect2.minx, rect2.miny, rect2.maxx, rect2.maxy))
//{
// return true;
//}
//else if (IsPointInRect(rect1.maxx, rect1.maxy, rect2.minx, rect2.miny, rect2.maxx, rect2.maxy))
//{
// return true;
//}
//else if (IsPointInRect(rect2.minx, rect2.miny, rect1.minx, rect1.miny, rect1.maxx, rect1.maxy))
//{
// return true;
//}
//else if (IsPointInRect(rect2.minx, rect2.maxy, rect1.minx, rect1.miny, rect1.maxx, rect1.maxy))
//{
// return true;
//}
//else if (IsPointInRect(rect2.maxx, rect2.miny, rect1.minx, rect1.miny, rect1.maxx, rect1.maxy))
//{
// return true;
//}
//else if (IsPointInRect(rect2.maxx, rect2.maxy, rect1.minx, rect1.miny, rect1.maxx, rect1.maxy))
//{
// return true;
//}
//else
// return false;
double minx = max(rect1.minx, rect2.minx);
double miny = max(rect1.miny, rect2.miny);
double maxx = min(rect1.maxx, rect2.maxx);
double maxy = min(rect1.maxy, rect2.maxy);
if (minx > maxx || miny > maxy)
{
//#ifdef _DEBUG
// FILE* ofs = fopen("E:\\rect.txt", "a+");
// fprintf(ofs, "%lf,%lf,%lf,%lf;%lf,%lf,%lf,%lf;\n", rect1.minx, rect1.miny, rect1.maxx, rect1.maxy,
// rect2.minx, rect2.miny, rect2.maxx, rect2.maxy);
// fclose(ofs);
//#endif // DEBUG
return false;
}
else
return true;
}
/*****************************************************************************
* @brief : ???????
* @author : W.W.Frank
* @date : 2015/11/30 14:53
* @version : version 1.0
* @inparam :
* @outparam :
*****************************************************************************/
double DistanceComputation::SquarePointToBeeline(double x, double y, double x0, double y0,
double x1, double y1)
{
Point2D pt = PointJointComputation::PointJointBeeline(x, y, x0, y0, x1, y1);
double xx = pt.x - x;
double yy = pt.y - y;
return xx * xx + yy * yy;
}
double DistanceComputation::Distance(Point2Ds& pts, bool isclosed)
{
double dis = 0.0;
for (size_t i = 0; i < pts.size() - 1; i++)
{
dis += pts[i].Distance(pts[i + 1]);
}
if (isclosed)
{
dis += pts[pts.size() - 1].Distance(pts[0]);
}
return dis;
}
/*****************************************************************************
* @brief : ?????????
* @author : W.W.Frank
* @date : 2015/11/30 14:55
* @version : version 1.0
* @inparam :
* @outparam :
*****************************************************************************/
void PointJointComputation::PointJointBeeline(double x, double y, double bln0x, double bln0y, double bln1x,
double bln1y, double& ratio)
{
double x0 = bln0x;
double y0 = bln0y;
double x1 = bln1x;
double y1 = bln1y;
double deltax = x1 - x0;
double deltay = y1 - y0;
double xp = x;
double yp = y;
if (deltay == 0 && deltax == 0)
ratio = 0;
else
ratio = ((xp - x0) * deltax + (yp - y0) * deltay) / (deltax * deltax + deltay * deltay);
}
Point2D PointJointComputation::PointJointBeeline(double x, double y, double bln0x, double bln0y, double bln1x,
double bln1y)
{
double u;
PointJointBeeline(x, y, bln0x, bln0y, bln1x, bln1y, u);
double x0 = bln0x;
double y0 = bln0y;
double x1 = bln1x;
double y1 = bln1y;
double deltax = x1 - x0;
double deltay = y1 - y0;
return Point2D(x0 + u * deltax, y0 + u * deltay);
}
void PointProjection::PointProjectLatLngToUTM(double lat, double lng, int nZone, double &x, double &y)
{
tsmLatLongToUTM(lat, lng, &nZone, &x, &y);
} | [
"[email protected]"
] | |
3090e285cd88c1e2250b37cadaa27ca6ec6d00ff | 1754c9ca732121677ac6a9637db31419d32dbcf1 | /dependencies/libsbml-vs2017-release-64/include/sbml/extension/ISBMLExtensionNamespaces.h | 1be650b3f918bb36b8dbfe6c412e18fb97d6fcd0 | [
"LicenseRef-scancode-unknown-license-reference",
"BSD-2-Clause"
] | permissive | sys-bio/Libstructural | 1701e239e3f4f64674b86e9e1053e9c61fe868a7 | fb698bcaeaef95f0d07c010f80c84d2cb6e93793 | refs/heads/master | 2021-09-14T17:54:17.538528 | 2018-05-16T21:12:24 | 2018-05-16T21:12:24 | 114,693,721 | 3 | 1 | null | 2017-12-18T22:25:11 | 2017-12-18T22:25:10 | null | UTF-8 | C++ | false | false | 2,802 | h | /**
* @cond doxygenLibsbmlInternal
*
* @file ISBMLExtensionNamespaces.h
* @brief ISBMLExtensionNamespaces interface to the SBMLExtensionNamespaces class
* @author Frank Bergmann
*
* <!--------------------------------------------------------------------------
* This file is part of libSBML. Please visit http://sbml.org for more
* information about SBML, and the latest version of libSBML.
*
* Copyright (C) 2013-2017 jointly by the following organizations:
* 1. California Institute of Technology, Pasadena, CA, USA
* 2. EMBL European Bioinformatics Institute (EMBL-EBI), Hinxton, UK
* 3. University of Heidelberg, Heidelberg, Germany
*
* Copyright (C) 2009-2013 jointly by the following organizations:
* 1. California Institute of Technology, Pasadena, CA, USA
* 2. EMBL European Bioinformatics Institute (EMBL-EBI), Hinxton, UK
*
* Copyright (C) 2006-2008 by the California Institute of Technology,
* Pasadena, CA, USA
*
* Copyright (C) 2002-2005 jointly by the following organizations:
* 1. California Institute of Technology, Pasadena, CA, USA
* 2. Japan Science and Technology Agency, Japan
*
* This library is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation. A copy of the license agreement is provided
* in the file named "LICENSE.txt" included with this software distribution
* and also available online as http://sbml.org/software/libsbml/license.html
* ------------------------------------------------------------------------ -->
*
* @class ISBMLExtensionNamespaces
* @sbmlbrief{core}
*
* @htmlinclude not-sbml-warning.html
*/
#ifndef ISBMLExtensionNamespaces_h
#define ISBMLExtensionNamespaces_h
#include <sbml/SBMLNamespaces.h>
#include <sbml/common/common.h>
#ifdef __cplusplus
#include <string>
#include <stdexcept>
LIBSBML_CPP_NAMESPACE_BEGIN
class LIBSBML_EXTERN ISBMLExtensionNamespaces : public SBMLNamespaces
{
public:
ISBMLExtensionNamespaces();
ISBMLExtensionNamespaces(unsigned int level,
unsigned int version,
const std::string &pkgName,
unsigned int pkgVersion,
const std::string& pkgPrefix = "");
ISBMLExtensionNamespaces(const ISBMLExtensionNamespaces& orig);
virtual ~ISBMLExtensionNamespaces();
virtual std::string getURI() const = 0;
virtual unsigned int getPackageVersion() const = 0;
virtual const std::string& getPackageName() const = 0;
virtual void setPackageVersion(unsigned int pkgVersion) = 0;
};
LIBSBML_CPP_NAMESPACE_END
#endif /* __cplusplus */
#endif /* ISBMLExtensionNamespaces_h */
/** @endcond */
| [
"[email protected]"
] | |
8cecd6468c37d3f7c185c16ab432bdb9fd42da84 | 4eb7413b650e54a657b39e6ee2de8b863672aec3 | /psps/11051.cpp | 0cb23b737e1314b37109048f2fcdb137bc903399 | [] | no_license | 0x9576/PS | be776b5a0f792d62fc6f85c881aa802738b8cc50 | e48bb87c61f4d75dc78d40260af646ae3ec8c0d5 | refs/heads/main | 2023-06-07T09:38:37.331420 | 2021-06-20T06:06:08 | 2021-06-20T06:06:08 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 274 | cpp | #include<iostream>
using namespace std;
int dp[1005][1005];
int main() {
dp[0][0] = 1;
for (int i = 1; i < 1005; i++)
for (int j = 0; j <= i; j++) {
dp[i][j] = dp[i - 1][j - 1] + dp[i - 1][j];
dp[i][j] %= 10007;
}
int N, K;
cin >> N >> K;
cout << dp[N][K];
}
| [
"[email protected]"
] | |
3380d98c52a8d8ab71351f7d9eb12eae340d80f2 | 0d61f5201ac4b059691a6425562a12743615f0f1 | /fwk/LinkedQueue.h | d9c385f730f69e20744280a9b5ba1df19754d829 | [] | no_license | haowei01/MazeWar | 8c4ea039d38f3a1808de25aba05e44f8e6fe9627 | 0ca928ab6625efea6ff2d1686fd8a882eb1d9285 | refs/heads/master | 2021-05-27T08:23:44.808791 | 2014-04-20T20:07:36 | 2014-04-20T20:07:36 | 18,972,743 | 2 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 10,279 | h | // Copyright(c) 1993-2006_2007, David R. Cheriton, all rights reserved.
//
// <h2>LinkedQueue</h2>
// Linked queue of pointers to objects of type T that support smart pointers
// and that provide a "next" attribute (actually lqNext)
// that can be used by this implementation.
// The next attribute must accept and return a raw pointer but store a smart
// pointer of type T.
// Only to be used as an internal implementation data structure
// Use the provided iterators to iterate over entries in a list.
// Insert/delete at the head using "newHead" and "deleteHead"
// Otherwise, use "newCurrent" or "newNext" in an iterator.
// Intended iterator structure in a for loop is:
// for( FooList::IteratorConst i=list_.constIterator(); i; ++i){
// Foo * f = *i;
// . . . // do something
// }
// Use the non-const iterator if adding and deleting entries in the list.
// There is no protection against increments an iterator that is null and
// it should not be done.
// The virtual function onDeleteMemberNotFound is called if an member to be deleted
// was not found in the list. Default definition does nothing.
// There is no concurrency control provided. Moreover, a single client should
// not add or delete objects except through an iterator when any iterator is
// in existence.
// Note: removal of an member does not clear the next attribute, but relies on
// the client setting it as part of adding to some other data structure.
// This implementation does not allocate any memory or throw any exceptions.
//
#ifndef FWK_LINKEDQUEUE_H
#define FWK_LINKEDQUEUE_H
#include <fwk/Ptr.h>
#include <fwk/BaseCollection.h>
namespace Fwk {
template< typename T, typename P = T, typename V = T * >
class LinkedQueue : public BaseRefCollection<T> {
public:
typedef LinkedQueue< T, P, V > Self;
LinkedQueue() : version_(0), members_(0),head_(0), tail_(0) {}
U32 version() const { return version_; }
U32 members() const { return members_; }
T * head() const { return head_.ptr(); }
T * tail() const { return tail_; }
void newHead( const typename T::Ptr& newMember ) {
newHead( newMember.ptr() );
}
void newHead( T * newMember ) {
if( !head_ ) tail_ = newMember;
newMember->lqNextIs( head_.ptr() );
head_ = newMember;
++version_;
++members_;
}
void newMember( T * _newMember ) {
if( tail_ ) {
tail_->lqNextIs(_newMember);
}
else head_ = _newMember;
_newMember->lqNextIs(0);
tail_ = _newMember;
++version_;
++members_;
}
void newMember( const Ptr<T>& _newMember ) {
newMember(_newMember.ptr());
}
Ptr<T> headDel() {
Ptr<T> ptr = head_.ptr();
if( ptr ) {
if( tail_ == ptr ) tail_ = 0;
head_ = ptr->lqNext();
ptr->lqNextIs(0);
++version_;
--members_;
}
return ptr;
}
void deleteHead() {
T * ptr = head_.ptr();
if( ptr ) {
if( tail_ == ptr ) tail_ = 0;
head_ = ptr->lqNext();
ptr->lqNextIs(0);
++version_;
--members_;
}
}
T const * operator[]( T const * m ) const {
for( T * c=head_.ptr();c;c=c->lqNext() ) if( c==m ) return c;
return 0;
}
T const * member( T const * m ) const { return operator[](m); }
T * operator[]( T const * m ) {
for( T * c=head_.ptr();c;c=c->lqNext() ) if( c==m ) return c;
return 0;
}
T const * operator[]( const typename T::Ptr& m ) const {
return operator[](m.ptr());
}
T * operator[]( const typename T::Ptr& m ) { return operator[](m.ptr()); }
Ptr<T> deleteMember( T * member ) {
T * prev = 0;
for( T * c = head_.ptr(); c; c = c->lqNext() ) {
if( c == member ) {
if( !c->lqNext() ) tail_ = prev;
if( prev ) prev->lqNextIs( c->lqNext() );
else head_ = c->lqNext();
c->lqNextIs( 0 );
++version_;
--members_;
return c;
}
prev = c;
}
onDeleteMemberNotFound( member );
return 0;
}
Ptr<T> deleteMember( const typename T::Ptr& _member ) {
return deleteMember(_member.ptr() );
}
virtual void onDeleteMemberNotFound( T * ) {}
// Override if some action required.
class IteratorConst : public BaseIteratorConst<T> {
public:
P const * ptr() const { return _ptr()->fwkPtr(); }
P const * operator->() const { return _ptr()->fwkPtr(); }
V operator*() const {
T * p = const_cast< T * >( _ptr() );
// Cast away const-ness because for invasive collections, operator* usually
// returns "this", so it's more convenient if the user doesn't have to declare
// fwkValue() const; if they did, they'd have to const_cast "this" themselves.
return p->fwkValue();
}
IteratorConst& operator++() {
const T * c = _ptr();
ptrIs( c->lqNext() );
return *this;
}
Self * list() const {
return static_cast<Self *>(collection_);
}
T const * _ptr() const { return BaseIteratorConst<T>::ptr(); }
// proivde access to this internal pointer for DelAlias impl
// FixMe: provide "direct" iterator like with HashMap.
protected:
using BaseIteratorConst<T>::collection_;
friend class LinkedQueue< T, P, V >;
IteratorConst( Self const * lq, T * mem ) :
BaseIteratorConst<T>( const_cast<Self*>(lq), mem ) {}
IteratorConst( Self * lq, T * mem ) :
BaseIteratorConst<T>(lq,mem) {}
};
IteratorConst iterator() const {
return IteratorConst( this, const_cast<T *>(head_.ptr()) );
}
IteratorConst iterator( const Ptr<T>& start ) const {
T * p = start.ptr();
bool search = false;
if( p && (p!=head_) && (p != tail_) ) {
p = head_.ptr();
search = true;
}
IteratorConst ii( this, p );
if( search ) {
p = start.ptr();
while( ii && ii != p ) ++ii;
}
return ii;
}
class Iterator : public IteratorConst {
public:
using IteratorConst::_ptr;
P * ptr() const { return const_cast< P * >( _ptr()->fwkPtr() ); }
P * operator->() const { return const_cast< P * >( _ptr()->fwkPtr() ); }
V operator*() const { return _ptr()->fwkValue(); }
Self* list() const {
return const_cast<Self *>(
static_cast<Self const *>( collection_ ));
}
Iterator& operator++() {
T * c = _ptr();
prev_ = c;
ptrIs( c->lqNext() );
return *this;
}
void newPtr( T * newMember ) {
T * p = prev_.ptr();
if( p ) {
newMember->lqNextIs( ptr() );
p->lqNextIs( newMember );
}
else {
newMember->lqNextIs( list()->head() );
list()->head_ = newMember;
}
if( p == list()->tail_ ) list()->tail_ = newMember;
ptrIs( newMember );
++list()->version_;
++list()->members_;
}
struct PointerConversion {
int valid;
};
// For conversion to bool/int to ensure the following deleter does not
// take precedent.
operator int PointerConversion::*() const {
return _ptr() ? &PointerConversion::valid : 0;
}
struct IterDeleter {
~IterDeleter() {}
void operator delete( void * thisPtr ) {
Iterator * i = (Iterator *) thisPtr;
i->deletePtr();
}
};
operator IterDeleter * () { return _ptr() ? (IterDeleter*) this : 0; }
// Conversion required for the delete operator, causing
// Return null if null so test for null still works.
// Note: the IterDeleter class is used because operator delete calls
// the destructor. delete iter; is just a way of invoking deletePtr.
// FixMe: can IterDeleter and PointerConversion be combined?
void deletePtr() {
T * p = prev_.ptr();
T * c = _ptr();
T * newC = c->lqNext();
if( !newC ) list()->tail_ = p;
if( p ) p->lqNextIs( newC );
else list()->head_ = newC;
ptrIs( newC );
++list()->version_;
--list()->members_;
}
void newMember( T * newMember ) {
T * c = _ptr();
newMember->lqNextIs( c->lqNext() );
c->lqNextIs( newMember );
if( !newMember->lqNext() ) tail_ = newMember;
++version_;
++members_;
}
// After the iterator pointer
T * _ptr() const { return const_cast<T *>(BaseIteratorConst<T>::ptr()); }
protected:
using BaseIteratorConst<T>::collection_;
Ptr<T> prev_;
friend class LinkedQueue< T, P, V >;
Iterator( const Self* lq, T * mem ) :
IteratorConst( lq, mem ), prev_(0) {}
Iterator( Self * lq, T * mem ) :
IteratorConst(lq,mem), prev_(0) {}
};
Iterator iterator() {
return Iterator( this, head_.ptr() );
}
void deleteAll() {
Ptr<T> c = head_.ptr();
head_ = 0;
if( c ) {
for( Fwk::Ptr<T> nextC = c->lqNext(); nextC; c = nextC ) {
nextC = c->lqNext();
c->lqNextIs( 0 ); // Deference next member
}
}
tail_ = 0;
++version_;
members_ = 0;
}
virtual ~LinkedQueue() { deleteAll(); }
U32 auditErrors( U32 scope ) const {
U32 count = 0;
for( T * c=head_.ptr();c;c=c->lqNext() ) ++count;
return count != members_;
}
private:
typedef BaseCollection::StrepIterator StrepIterator;
virtual bool iteratorMoreLeft( StrepIterator const & bi ) const {
IteratorConst const * tmp = static_cast<IteratorConst const *>( &bi );
return *tmp;
}
virtual void iteratorIncr( StrepIterator& bi ) const {
IteratorConst * tmp = static_cast<IteratorConst *>( &bi );
++(*tmp);
}
// virtual void iteratorDelete( StrepIterator& ) const {}
virtual String iteratorStrep( StrepIterator const & bi ) const {
IteratorConst const * tmp = static_cast<IteratorConst const *>( &bi );
return valueToStrep( **tmp );
}
private:
U32 version_;
U32 members_;
Ptr<T> head_;
T * tail_; // depend on the head/next reference to packet, not tail
};
}
#endif
| [
"[email protected]"
] | |
fbf3d936faaa1f95256e48faf98dd17ef76c1f99 | 8cd433650402dacace74ef1875004ac0208317f1 | /SciGame/Archer/Archer.h | c139ce1ff654ded1b5db7a183f122d0011ad7ccf | [] | no_license | ScienceDiscoverer/SciEngine | 7685002a91918ef588813b6201364d2037c94f76 | f23f3a9e9fac2839c89b35142752ca15e187d772 | refs/heads/master | 2020-03-17T07:13:39.604454 | 2018-05-14T16:19:42 | 2018-05-14T16:19:42 | 133,389,113 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,114 | h | #ifndef ARCHER_H
#define ARCHER_H
#include <SciEntities2D.h>
#include <SciHierarchy.h>
#include <SciControls.h>
// Component classes
class LeftHand : public SciEntity
{
friend class Archer;
public:
// Constructors
LeftHand();
// Interface functions
virtual void Update(float dt);
virtual void Render(float alpha);
private:
// Data
SciVector2 w_pos;
SciMatrix2x2 w_orient;
MouseTracker m_stalker;
};
class RightHand : public SciEntity
{
friend class Archer;
public:
// Constructors
RightHand();
// Interface functions
virtual void Update(float dt = -1.0f);
virtual void Render(float alpha);
private:
// Data
SciVector2 w_pos;
SciMatrix2x2 w_orient;
};
class Arrow : public SciPhysicsEntity
{
friend class Archer;
friend class Bow;
public:
// Constructors
Arrow();
// Interface functions
virtual void Update(float dt = -1.0f);
virtual void Render(float alpha);
private:
// Private functions
void Penetrate();
// Data
SciVector2 w_pos;
SciMatrix2x2 w_orient;
SciVector2 cent_disp; // Displacement of center
bool is_penning; // Arrow is penetrating something
bool in_bow; // Arrow is inside bow
};
class Bow : public SciEntity
{
friend class Archer;
public:
// Constructors
Bow();
// Interface functions
virtual void Update(float dt);
virtual void Render(float alpha);
// Core operations
void InsertArrow(Arrow* arw) { ya = arw; }
void ReleaseArrow();
private:
// Data
SciVector2 w_pos;
SciMatrix2x2 w_orient;
Arrow* ya;
float draw; // Current draw power
float last_draw;
float relese_draw; // Draw power upon arrow relese
float draw_spd; // Draw speed pixels/second
float release_spd; // Release speed pixels/second
SciArray<Arrow>* w_yas;
};
// Main class
class Archer : public SciPhysicsEntity
{
public:
// Constructors
Archer();
// Interface functions
virtual void Update(float dt);
virtual void Render(float alpha);
// Access functions
void LinkWorldArrows(SciArray<Arrow>* w_arrs) { yumi.w_yas = w_arrs; }
private:
// Data
LeftHand l_hand;
RightHand r_hand;
Bow yumi;
Arrow ya;
SciHierarchy hier;
};
#endif /* ARCHER_H */ | [
"[email protected]"
] | |
9c836d577feeb39708fc03348c61f22fcaf73f99 | 430f81fe25dc9e1c3d01d7d628dfa61f17704aba | /Cpp_reference_file/acmicpc/11729.cpp | fbfe05edd06ebb04c848f223128b1e8229d7b897 | [] | no_license | blogSoul/Cpp_summary | 693691e086a4af70a7bef2594e32c7da160fd14d | 9efafab6d04cb5674e860d7c749760e941f3a3df | refs/heads/master | 2022-12-26T13:36:58.150349 | 2020-09-29T14:24:20 | 2020-09-29T14:25:47 | 260,205,835 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 604 | cpp | #include<iostream>
using namespace std;
int functionA(int N) {
if (N == 1)
return 1;
else
return 2 * functionA(N - 1) + 1;
}
void functionB(int N, int a, int b, int c) {
if (N == 1) {
cout << a << " " << c << "\n";
}
else if (N == 2) {
cout << a << " " << b << "\n";
cout << a << " " << c << "\n";
cout << b << " " << c << "\n";
}
else {
functionB(N - 1, a, c, b);
functionB(1, a, b, c);
functionB(N - 1, b, a, c);
}
}
int main(void) {
int N, i, j;
cin >> N;
cin.tie(NULL);
ios::sync_with_stdio(false);
cout << functionA(N) << "\n";
functionB(N, 1, 2, 3);
return 0;
} | [
"[email protected]"
] | |
8b15d1305a34ff380299ae6c05767dec2b259791 | dfa1f54c7c6f9719aef797e785c32cdf69a19d37 | /99-RTT+emXGUI综合桌面/User/app/GUI_Demo/GUI_DEMO_ShowWave.cpp | 6acd958d8508d8ad53441b2980927ed35eed077c | [] | no_license | downloade/emXGUI_demo_stm32f429 | 8a08c53c62bedb132fc27ee3f964567ec2503ee3 | d66607913cdc7cb14beb4c0b5c9686a8f659db1b | refs/heads/master | 2023-04-20T00:51:23.819639 | 2020-07-14T03:58:53 | 2020-07-14T03:59:12 | null | 0 | 0 | null | null | null | null | GB18030 | C++ | false | false | 44,685 | cpp |
/*============================================================================*/
#include <math.h>
#include "emXGUI.h"
#include "GUI_Font_XFT.h"
#include "x_libc.h"
#include "x_obj.h"
#include "GUI_AppDef.h"
/*============================================================================*/
extern "C" const char ASCII_20_4BPP[];
extern "C" const char ASCII_24_4BPP[];
/*============================================================================*/
#define BK_W rc_main.w
#define BK_H rc_main.h
#define LEFT_OFFSET 84
#define TOP_OFFSET 30
#define RIGHT_OFFSET (50)
#define BOTTOM_OFFSET (30)
#define CUR_BOX_SIZE 30
//static POINT pt_wav[800];
static POINT *pt_wav,*pt_wav2;
/* 是否要重新生成随机数波形 */
static u8 scatter_init = 0;
//static int x_cur,y_cur;
//static SURFACE *pSurfTop=NULL;
//static HDC hdcTop=NULL;
//static HFONT hFont20,hFont24;
static RECT rc_main,rc_wav,rc_button,rc_label,rc_x1_cur,rc_x2_cur,rc_y1_cur,rc_y2_cur;
static int wave_freq,wave_amp;
enum WAVE_FORMAT{
SINE_WAVE,
SQUARE_WAVE,
TRIANGULAR_WAVE,
SCATTER,
};
static WAVE_FORMAT wave_format = SINE_WAVE;
// static int x_step;
#define Y_STEP_NUM 9
#define X_STEP_NUM 9
static int y_step_cur=0;
static int x_step_cur=0;
// static const float y_step[Y_STEP_NUM]={0.1,0.2,0.5,1.0,2.0,5.0,10.0,20.0,50.0};
// static const WCHAR *y_step_str[Y_STEP_NUM]={
// L"0.1mV",
// L"0.2mV",
// L"0.5mV",
// L"1mV",
// L"2mV",
// L"5mV",
// L"10mV",
// L"20mV",
// L"50mV",
// };
static const float y_step[Y_STEP_NUM]={1.1,1.2,1.3,1.4,1.5,2.0,5.0,6.0,7.0};
static const WCHAR *y_step_str[Y_STEP_NUM]={
L"1.1mV",
L"1.2mV",
L"1.3mV",
L"1.4mV",
L"1.5mV",
L"2.0mV",
L"5.0mV",
L"6.0mV",
L"7.0mV",
};
static const int x_step[X_STEP_NUM]={50,60,70,80,90,100,110,120,130};
static const WCHAR *x_step_str[X_STEP_NUM]={
L"50mS",
L"60mS",
L"70mS",
L"80mS",
L"90mS",
L"100mS",
L"110mS",
L"120mS",
L"130mS",
};
// static const int x_step[X_STEP_NUM]={1000,2000};
// static const WCHAR *x_step_str[X_STEP_NUM]={
// L"1000mS",
// L"2000mS",
// };
#define CUR_X1 1
#define CUR_X2 2
#define CUR_Y1 3
#define CUR_Y2 4
static int focus_cur=0;
static int x1_cur,x2_cur,y1_cur,y2_cur;
/*============================================================================*/
struct __alco_cfg{
char tag[8]; //"ALCO.CFG"
u32 B2_ref;
u32 B10_ref;
u32 B2_max;
u32 B10_max;
};
/*============================================================================*/
enum eMSG{
MY_MSG_FISRT =WM_USER,
MSG_CUR_X1_CHANGE, //X1 光标位置有变动.
MSG_CUR_X2_CHANGE, //X2 光标位置有变动.
MSG_CUR_Y1_CHANGE, //Y1 光标位置有变动.
MSG_CUR_Y2_CHANGE, //Y2 光标位置有变动.
};
enum eID{
ID_BTN_BEGIN,////////////
ID_EXIT =1,
ID_START,
ID_SENSOR_ON,
ID_SENSOR_OFF,
ID_Y_STEP,
ID_X_STEP,
ID_PUMP,
ID_BTN_END,//////////////
ID_LISTBOX,
ID_X1_CUR,
ID_X2_CUR,
ID_Y1_CUR,
ID_Y2_CUR,
ID_Y_STEP_SUB,
ID_Y_STEP_ADD,
ID_X_STEP_SUB,
ID_X_STEP_ADD,
ID_TEST,
ID_X_STR,
ID_Y_STR,
ID_SCROLL1,
ID_SCROLL2,
ID_RB1,
ID_RB2,
ID_RB3,
ID_RB4,
ID_TEXT1,
ID_TEXT2,
ID_TEXT3,
ID_TEXT4,
ID_TEXT5,
ID_TEXT6,
ID_TEXT7,
ID_TEXT8,
ID_WAVE,
};
static struct __x_obj_item *focus_obj =NULL;
static struct __x_obj_item *button_item =NULL;
//static struct __x_obj_item *text_item =NULL;
static struct __x_obj_item *x1_cur_obj =NULL;
static struct __x_obj_item *x2_cur_obj =NULL;
static struct __x_obj_item *y1_cur_obj =NULL;
static struct __x_obj_item *y2_cur_obj =NULL;
/*============================================================================*/
/**
* @brief 主函数
* @param back_c 背景颜色
* @param Page_c 滚动条颜色
* @param fore_c 滑块颜色 *
* @retval 无
*/
/*
* @brief 绘制滚动条
* @param hwnd: 滚动条的句柄值
* @param hdc: 绘图上下文
* @param back_c:背景颜色
* @param Page_c: 滚动条Page处的颜色
* @param fore_c:滚动条滑块的颜色
* @retval NONE
*/
static void draw_scrollbar(HWND hwnd, HDC hdc, COLOR_RGB32 back_c, COLOR_RGB32 Page_c, COLOR_RGB32 fore_c)
{
RECT rc;
RECT rc_scrollbar;
GetClientRect(hwnd, &rc);
/* 背景 */
SetBrushColor(hdc, back_c);
FillRect(hdc, &rc);
rc_scrollbar.x = rc.x;
rc_scrollbar.y = rc.h/2-1;
rc_scrollbar.w = rc.w;
rc_scrollbar.h = 2;
SetBrushColor(hdc, MapRGB888(hdc, Page_c));
FillRect(hdc, &rc_scrollbar);
/* 滑块 */
SendMessage(hwnd, SBM_GETTRACKRECT, 0, (LPARAM)&rc);
SetBrushColor(hdc, MapRGB(hdc, 169, 169, 169));
//rc.y += (rc.h >> 2) >> 1;
//rc.h -= (rc.h >> 2);
/* 边框 */
//FillRoundRect(hdc, &rc, MIN(rc.w, rc.h) >> 2);
FillCircle(hdc, rc.x + rc.w / 2, rc.y + rc.h / 2, rc.h / 2 - 1);
InflateRect(&rc, -2, -2);
SetBrushColor(hdc, MapRGB888(hdc, fore_c));
FillCircle(hdc, rc.x + rc.w / 2, rc.y + rc.h / 2, rc.h / 2 - 1);
//FillRoundRect(hdc, &rc, MIN(rc.w, rc.h) >> 2);
}
static void exit_owner_draw(DRAWITEM_HDR *ds) //绘制一个按钮外观
{
HWND hwnd;
HDC hdc;
RECT rc;
WCHAR wbuf[128];
hwnd = ds->hwnd; //button的窗口句柄.
hdc = ds->hDC; //button的绘图上下文句柄.
rc = ds->rc; //button的绘制矩形区.
//
// SetBrushColor(hdc, MapRGB(hdc, 0,0,0));
// FillRect(hdc, &rc); //用矩形填充背景
SetBrushColor(hdc, MapRGB(hdc, COLOR_DESKTOP_BACK_GROUND));
FillCircle(hdc, rc.x+rc.w, rc.y, rc.w);
if (ds->State & BST_PUSHED)
{ //按钮是按下状态
// GUI_DEBUG("ds->ID=%d,BST_PUSHED",ds->ID);
// SetBrushColor(hdc,MapRGB(hdc,150,200,250)); //设置填充色(BrushColor用于所有Fill类型的绘图函数)
// SetPenColor(hdc,MapRGB(hdc,250,0,0)); //设置绘制色(PenColor用于所有Draw类型的绘图函数)
SetTextColor(hdc, MapRGB(hdc, 105, 105, 105)); //设置文字色
}
else
{ //按钮是弹起状态
// SetBrushColor(hdc,MapRGB(hdc,255,255,255));
// SetPenColor(hdc,MapRGB(hdc,0,250,0));
SetTextColor(hdc, MapRGB(hdc, 255, 255, 255));
}
/* 使用控制图标字体 */
SetFont(hdc, controlFont_64);
// SetTextColor(hdc,MapRGB(hdc,255,255,255));
GetWindowText(ds->hwnd, wbuf, 128); //获得按钮控件的文字
rc.y = -10;
rc.x = 16;
DrawText(hdc, wbuf, -1, &rc, NULL);//绘制文字(居中对齐方式)
/* 恢复默认字体 */
SetFont(hdc, defaultFont);
}
static void RB_owner_draw(DRAWITEM_HDR *ds) //绘制一个按钮外观
{
HWND hwnd;
HDC hdc;
RECT rc;
WCHAR wbuf[128];
hwnd = ds->hwnd; //button的窗口句柄.
hdc = ds->hDC; //button的绘图上下文句柄.
rc = ds->rc; //button的绘制矩形区.
SetBrushColor(hdc, MapRGB(hdc, 0,0,0));
//
FillRect(hdc, &rc); //用矩形填充背景
if (ds->State & BST_CHECKED)
{ //按钮是选中状态
// GUI_DEBUG("ds->ID=%d,BST_PUSHED",ds->ID);
SetBrushColor(hdc,MapRGB(hdc,220,200,200)); //设置填充色(BrushColor用于所有Fill类型的绘图函数)
SetPenColor(hdc,MapRGB(hdc,30,30,230)); //设置绘制色(PenColor用于所有Draw类型的绘图函数)
FillCircle(hdc, rc.x+rc.w/2, rc.y+rc.w/2, rc.w/2);
SetBrushColor(hdc,MapRGB(hdc,90,174,22));
FillCircle(hdc, rc.x+rc.w/2, rc.y+rc.w/2, rc.w/2-8);
}
else
{
SetBrushColor(hdc,MapRGB(hdc,200,220,200));
SetPenColor(hdc,MapRGB(hdc,50,50,50));
FillCircle(hdc, rc.x+rc.w/2, rc.y+rc.w/2, rc.w/2);
}
}
/*
* @brief 自定义滑动条绘制函数
* @param ds: 自定义绘制结构体
* @retval NONE
*/
static void scrollbar_owner_draw(DRAWITEM_HDR *ds)
{
HWND hwnd;
HDC hdc;
HDC hdc_mem;
HDC hdc_mem1;
RECT rc;
RECT rc_cli;
// int i;
hwnd = ds->hwnd;
hdc = ds->hDC;
GetClientRect(hwnd, &rc_cli);
hdc_mem = CreateMemoryDC(SURF_SCREEN, rc_cli.w, rc_cli.h);
hdc_mem1 = CreateMemoryDC(SURF_SCREEN, rc_cli.w, rc_cli.h);
//绘制白色类型的滚动条
draw_scrollbar(hwnd, hdc_mem1, RGB888(0, 0, 0), RGB888( 250, 250, 250), RGB888( 255, 255, 255));
//绘制绿色类型的滚动条
draw_scrollbar(hwnd, hdc_mem, RGB888(0, 0, 0), RGB888( 50, 205, 50), RGB888(50, 205, 50));
SendMessage(hwnd, SBM_GETTRACKRECT, 0, (LPARAM)&rc);
//左
BitBlt(hdc, rc_cli.x, rc_cli.y, rc.x, rc_cli.h, hdc_mem, 0, 0, SRCCOPY);
//右
BitBlt(hdc, rc.x + rc.w, 0, rc_cli.w - (rc.x + rc.w) , rc_cli.h, hdc_mem1, rc.x + rc.w, 0, SRCCOPY);
//绘制滑块
if (ds->State & SST_THUMBTRACK)//按下
{
BitBlt(hdc, rc.x, 0, rc.w, rc_cli.h, hdc_mem1, rc.x, 0, SRCCOPY);
}
else//未选中
{
BitBlt(hdc, rc.x, 0, rc.w, rc_cli.h, hdc_mem, rc.x, 0, SRCCOPY);
}
//释放内存MemoryDC
DeleteDC(hdc_mem1);
DeleteDC(hdc_mem);
}
static void btn_draw(HDC hdc,struct __x_obj_item * obj)
{
// HFONT hFont;
// hFont =GetFont(hdc);
if(obj->rc.w > 60 && obj->rc.h > 20)
{
// SetFont(hdc,hFont20);
}
if(obj == focus_obj)
{
SetTextColor(hdc,MapRGB(hdc,255,0,255));
SetPenColor(hdc,MapRGB(hdc,200,0,200));
SetBrushColor(hdc,MapRGB(hdc,100,0,100));
DrawText(hdc,obj->pszText,-1,&obj->rc,DT_SINGLELINE|DT_VCENTER|DT_CENTER|DT_BKGND|DT_BORDER);
}
else
{
// RECT rc;
/* 阴影 */
// CopyRect(&rc,&obj->rc);
// OffsetRect(&rc,2,2);
// SetBrushColor(hdc,MapRGB(hdc,20,20,20));
// FillRect(hdc,&rc);
SetTextColor(hdc,MapRGB(hdc,255,255,255));
SetPenColor(hdc,MapRGB(hdc,255,255,255));
SetBrushColor(hdc,MapRGB(hdc,90,174,22));
DrawText(hdc,obj->pszText,-1,&obj->rc,DT_SINGLELINE|DT_VCENTER|DT_CENTER|DT_BKGND|DT_BORDER);
}
// SetFont(hdc,hFont);
}
/**
* @brief 绘制示波器中间的窗口
*/
static void DrawFrame(HDC hdc,const POINT *pt,int count,COLORREF color)
{
int i,x,y;
WCHAR wbuf[128];
RECT rc;
ClrDisplay(hdc,NULL,MapRGB(hdc,0,0,0));
ClrDisplay(hdc,&rc_wav,MapRGB(hdc,0,40,40));
////Draw Y
SetPenColor(hdc,MapRGB(hdc,0,60,80));
SetTextColor(hdc,MapRGB(hdc,255,255,255));
i=0;
x =rc_wav.x;
y =rc_wav.y+rc_wav.h-1;
rc.x =0;
rc.y =y-8;
rc.w =LEFT_OFFSET-2;
rc.h =40;
while(y >= rc_wav.y)
{
/* 不画第一条线,看起来更好看 */
if(i!=0)
HLine(hdc,x,y,x+rc_wav.w);
if(i>0)
{
x_wsprintf(wbuf,L"%.1f",i*y_step[y_step_cur]*40);
DrawText(hdc,wbuf,-1,&rc,DT_SINGLELINE|DT_TOP|DT_RIGHT);
}
i++;
y -= 40;
rc.y -= 40;
}
////Draw X
SetPenColor(hdc,MapRGB(hdc,0,60,80));
SetTextColor(hdc,MapRGB(hdc,255,255,255));
i=0;
x=rc_wav.x;
y=rc_wav.y;
rc.x =x-8;
rc.y =rc_wav.y+rc_wav.h+1;
rc.w =40;
rc.h =20;
while(x < (rc_wav.x+rc_wav.w))
{
/* 不画第一条线,看起来更好看 */
if(i!=0)
VLine(hdc,x,y,y+rc_wav.h);
if(i>0)
{
x_wsprintf(wbuf,L"%d",i*x_step[x_step_cur]*40/1000);
DrawText(hdc,wbuf,-1,&rc,DT_SINGLELINE|DT_VCENTER|DT_LEFT);
}
i++;
x+=40;
rc.x+=40;
}
/////DrawFrame
if(count>0)
{
int x1,y1,x2,y2;
SetPenColor(hdc,color);
for(i=1;i<count;i++)
{
x1 = pt[i-1].x + rc_wav.x;
y1 =-pt[i-1].y + rc_wav.y+rc_wav.h-1;
x1 =MAX(x1,rc_wav.x);
x1 =MIN(x1,rc_wav.x+rc_wav.w-1);
y1 =MAX(y1,rc_wav.y);
y1 =MIN(y1,rc_wav.y+rc_wav.h-1);
x2 = pt[i].x + rc_wav.x;
y2 =-pt[i].y + rc_wav.y+rc_wav.h-1;
x2 =MAX(x2,rc_wav.x);
x2 =MIN(x2,rc_wav.x+rc_wav.w-1);
y2 =MAX(y2,rc_wav.y);
y2 =MIN(y2,rc_wav.y+rc_wav.h-1);
Line(hdc,x1,y1,x2,y2);
// AA_DrawLine(hdc,x1,y1,x2,y2);
// AA_DrawBoldLine(hdc,x1,y1,x2,y2);
}
}
////Cursor X1
SetPenColor(hdc,MapRGB(hdc,90,174,22));
x=x1_cur+rc_wav.x;
VLine(hdc,x,rc_wav.y-2,rc_wav.y+rc_wav.h-1);
////Cursor X2
x=x2_cur+rc_wav.x;
VLine(hdc,x,rc_wav.y-2,rc_wav.y+rc_wav.h-1);
////Cursor Y1
SetPenColor(hdc,MapRGB(hdc,238,206,31));
y=rc_wav.y+rc_wav.h-y1_cur;
HLine(hdc,rc_wav.x,y,rc_wav.x+rc_wav.w-1+2);
////Cursor Y2
y=rc_wav.y+rc_wav.h-y2_cur;
HLine(hdc,rc_wav.x,y,rc_wav.x+rc_wav.w-1+2);
////button obj
x_obj_draw(hdc,button_item);
// x_obj_draw(hdc,text_item);
}
#define PI (float)(3.14)
/*
三角波参数与正弦函数相似,标准周期为2π,占空比p (上升时间比周期)表示三角波上升下降段的比例
p=0.5为上升下降对称的。在[0,2π×p] 上为上升沿,
在2π×p,2π,2π区间为下降沿。
*/
static float trianglewav(float t,float p)
{
//三角波函数,p:0到1占空比
//trianglewav(t,p)的周期为2pi
//返回值在-1到+1间
float y;
//将t归化于0到2pi区间
if(t>=0)
t=(t/(2*PI)-(int)(t/(2*PI)))*2*PI;
else
t=2*PI+(t/(2*PI)-(int)(t/(2*PI)))*2*PI;
//检查占空比参数范围是否合法
if(p<0 || p>1){return 0;}
p=p*2*PI;
//当p为0或2*pi时的近似处理
p=(p-2*PI==0)?2*PI-1e-10:p;
p=(p==0)?1e-10:p;
if(t<p)
{
y=2*t/p-1;//计算上升沿
}
else
{
y=-2*t/(2*PI-p)+(2*PI+p)/(2*PI-p);//下降沿
}
return y;
}
/*
方波函数参数与正弦函数相似,标准周期为2π,占空比p
p=0.5为上升下降对称的。在[0,2π×p] 上为高电平,
在2π×p,2π,2π区间为低电平。
*/
static int squarewav(float t ,float p)
{
//方波函数,p:0到1占空比
//squarewav(t,p)的周期为2pi
//返回值在-1到+1间
int y;
//将t归化于0到2pi区间
if(t>=0)
t=(t/(2*PI)-(int)(t/(2*PI)))*2*PI;
else
t=2*PI+(t/(2*PI)-(int)(t/(2*PI)))*2*PI;
//检查占空比参数范围是否合法
if(p<0 || p>1){return 0;}
p=p*2*PI;
//当p为0或2*pi时的近似处理
p=(p-2*PI==0)?2*PI-1e-10:p;
p=(p==0)?1e-10:p;
if(t<p)
{
y=1;//高电平
}
else
{
y=-1;//低电平
}
return y;
}
static void wave_owner_draw(HDC hdc)
{
int x_cur,y_cur;
switch(wave_format)
{
case SINE_WAVE:
for(x_cur=0;x_cur < rc_wav.w;x_cur++)
{
float mV;
/*
* y = A sin(2*pi*f*t + p) + k
* 其中
* A:幅值
* pi:圆周率
* f:频率
* t:时间
* p:相位
* k:偏移
*/
/* 把时间按真实量程计算比较麻烦,且示例波形频率要适应特定量程,不方便展示 */
// mV = wave_amp*(sin(2*3.14*(1.0*x_cur*x_step[x_step_cur]/1000)*wave_freq)+1);
float t;
/* 800是大概把它分成800个点 */
t=-1+1.0/800*x_cur;
// t=-1+1.0/800*x_cur*x_step[x_step_cur]/1000;
/* 直接用像素点表示 */
mV = wave_amp*(sin(2*3.14*(t)*wave_freq)+1);
y_cur =(int)(mV/y_step[y_step_cur]);
pt_wav[x_cur].x =x_cur;
pt_wav[x_cur].y =y_cur;
}
break;
case TRIANGULAR_WAVE:
for(x_cur=0;x_cur < rc_wav.w;x_cur++)
{
float mV;
/*
* y = A trianglewav(2*pi*f*t + p) + k
* 其中
* A:幅值
* pi:圆周率
* f:频率
* t:时间
* p:相位
* k:偏移
*/
/* 把时间按真实量程计算比较麻烦,且示例波形频率要适应特定量程,不方便展示 */
// mV = wave_amp*(sin(2*3.14*(1.0*x_cur*x_step[x_step_cur]/1000)*wave_freq)+1);
float t;
t=-1+1.0/800*x_cur;
// t=-1+1.0/800*x_cur*x_step[x_step_cur]/1000;
/* 直接用像素点表示 */
mV = wave_amp*(trianglewav(2*3.14*(t)*wave_freq,0.5)+1);
y_cur =(int)(mV/y_step[y_step_cur]);
pt_wav[x_cur].x =x_cur;
pt_wav[x_cur].y =y_cur;
}
break;
case SQUARE_WAVE:
for(x_cur=0;x_cur < rc_wav.w;x_cur++)
{
float mV;
/*
* y = A squarewav(2*pi*f*t + p) + k
* 其中
* A:幅值
* pi:圆周率
* f:频率
* t:时间
* p:相位
* k:偏移
*/
/* 把时间按真实量程计算比较麻烦,且示例波形频率要适应特定量程,不方便展示 */
// mV = wave_amp*(sin(2*3.14*(1.0*x_cur*x_step[x_step_cur]/1000)*wave_freq)+1);
float t;
t=-1+1.0/800*x_cur;
// t=-1+1.0/800*x_cur*x_step[x_step_cur]/1000;
/* 直接用像素点表示 */
mV = wave_amp*(squarewav(2*3.14*(t)*wave_freq,0.5)+1);
y_cur =(int)(mV/y_step[y_step_cur]);
pt_wav[x_cur].x =x_cur;
pt_wav[x_cur].y =y_cur;
}
break;
case SCATTER:
{
/* 是否要重新生成随机数 */
if(scatter_init == 0)
{
for(x_cur=0;x_cur < rc_wav.w;x_cur++)
{
y_cur = x_rand()%200;
pt_wav2[x_cur].x =x_cur;
pt_wav2[x_cur].y =y_cur;
}
scatter_init =1;
}
for(x_cur=0;x_cur < rc_wav.w;x_cur++)
{
pt_wav[x_cur].x =pt_wav2[x_cur].x;
pt_wav[x_cur].y =pt_wav2[x_cur].y;
}
}
break;
default:
break;
}
DrawFrame(hdc,pt_wav,x_cur,MapRGB(hdc,255,255,255));
}
/*============================================================================*/
static float ADS1120_GetVoltage_mV(u16 addata);
//波形显示的窗口过程.
static LRESULT WaveWinProc(HWND hwnd,UINT msg,WPARAM wParam,LPARAM lParam)
{
RECT rc;
switch(msg)
{
case WM_CREATE:
x1_cur=15;
x2_cur=50;
y1_cur=30;
y2_cur=70;
// x_step=50; //50ms
y_step_cur=2;
x_step_cur=0;
focus_obj =NULL;
// hFont20 =XFT_CreateFont(ASCII_20_4BPP);
// hFont24 =XFT_CreateFont(ASCII_24_4BPP);
GetClientRect(hwnd,&rc);
// pSurfTop =CreateSurface(SURF_ARGB4444,rc.w,rc.h,NULL,0);
// hdcTop =CreateDC(pSurfTop,NULL);
// ClrDisplay(hdcTop,NULL,MapARGB(hdcTop,0,0,0,0));
GetClientRect(hwnd,&rc_main);
CopyRect(&rc_wav,&rc_main);
InflateRectEx(&rc_wav,-LEFT_OFFSET,-TOP_OFFSET,-RIGHT_OFFSET,-BOTTOM_OFFSET);
rc_x1_cur.x =rc_wav.x+x1_cur-CUR_BOX_SIZE/2;
rc_x1_cur.y =rc_wav.y-CUR_BOX_SIZE;
rc_x1_cur.w =CUR_BOX_SIZE;
rc_x1_cur.h =CUR_BOX_SIZE;
rc_x2_cur.x =rc_wav.x+x2_cur-CUR_BOX_SIZE/2;
rc_x2_cur.y =rc_wav.y-CUR_BOX_SIZE;
rc_x2_cur.w =CUR_BOX_SIZE;
rc_x2_cur.h =CUR_BOX_SIZE;
rc_y1_cur.x =rc_wav.x+rc_wav.w;
rc_y1_cur.y =rc_wav.y+rc_wav.h-y1_cur-CUR_BOX_SIZE/2;
rc_y1_cur.w =CUR_BOX_SIZE;
rc_y1_cur.h =CUR_BOX_SIZE;
rc_y2_cur.x =rc_wav.x+rc_wav.w;
rc_y2_cur.y =rc_wav.y+rc_wav.h-y2_cur-CUR_BOX_SIZE/2;
rc_y2_cur.w =CUR_BOX_SIZE;
rc_y2_cur.h =CUR_BOX_SIZE;
if(1)
{
/* 光标 */
x1_cur_obj =x_obj_create(L"X1", ID_X1_CUR, &rc_x1_cur, X_OBJ_VISIBLE,0,button_item);
x2_cur_obj =x_obj_create(L"X2", ID_X2_CUR, &rc_x2_cur, X_OBJ_VISIBLE,0,button_item);
y1_cur_obj =x_obj_create(L"Y1", ID_Y1_CUR, &rc_y1_cur, X_OBJ_VISIBLE,0,button_item);
y2_cur_obj =x_obj_create(L"Y2", ID_Y2_CUR, &rc_y2_cur, X_OBJ_VISIBLE,0,button_item);
}
return TRUE;
////
case WM_NOTIFY:
{
// U16 code,id;
// NMHDR *nr;
// code =HIWORD(wParam);
// id =LOWORD(wParam);
// nr =(NMHDR*)lParam; //lParam参数,是以NMHDR结构体开头.
}
return DefWindowProc(hwnd,msg,wParam,lParam);
/////
case WM_LBUTTONDOWN: //
{
int x,y;
x=GET_LPARAM_X(lParam);
y=GET_LPARAM_Y(lParam);
focus_obj =x_obj_get_from_pos(button_item,x,y); //从x,y坐标值获得 x_obj对象.
if(focus_obj==NULL)
{ //没有
return DefWindowProc(hwnd,msg,wParam,lParam);
}
if(focus_obj->id == ID_X1_CUR)
{
focus_cur =CUR_X1;
InvalidateRect(hwnd,&x1_cur_obj->rc,FALSE);
}
if(focus_obj->id == ID_X2_CUR)
{
focus_cur =CUR_X2;
InvalidateRect(hwnd,&x2_cur_obj->rc,FALSE);
}
if(focus_obj->id == ID_Y1_CUR)
{
focus_cur =CUR_Y1;
InvalidateRect(hwnd,&y1_cur_obj->rc,FALSE);
}
if(focus_obj->id == ID_Y2_CUR)
{
focus_cur =CUR_Y2;
InvalidateRect(hwnd,&y2_cur_obj->rc,FALSE);
}
}
return DefWindowProc(hwnd,msg,wParam,lParam);
////
case WM_MOUSELEAVE:
case WM_LBUTTONUP:
{
if(focus_obj!=NULL)
{
InvalidateRect(hwnd,&focus_obj->rc,FALSE);
}
/////
focus_cur =0;
focus_obj =NULL;
}
return DefWindowProc(hwnd,msg,wParam,lParam);
////
case WM_MOUSEMOVE:
{
int x,y;
x=GET_LPARAM_X(lParam);
y=GET_LPARAM_Y(lParam);
x =x-rc_wav.x;
x=MAX(x,0);
x=MIN(x,rc_wav.w-1);
y =y-rc_wav.y;
y=MAX(y,0);
y=MIN(y,rc_wav.h-1);
if(focus_cur == CUR_X1) // X1光标.
{
////移动前的位置刷新.
rc.x =x1_cur + rc_wav.x;
rc.y =rc_wav.y;
rc.w =1;
rc.h =rc_wav.h;
InvalidateRect(hwnd,&rc,FALSE);
InvalidateRect(hwnd,&x1_cur_obj->rc,FALSE);
////移动到新的位置.
x1_cur =x;
x_obj_move_to(x1_cur_obj,(x1_cur+rc_wav.x)-(x1_cur_obj->rc.w/2),x1_cur_obj->rc.y);
//移动后的位置刷新.
rc.x =x1_cur + rc_wav.x;
rc.y =rc_wav.y;
rc.w =1;
rc.h =rc_wav.h;
InvalidateRect(hwnd,&rc,FALSE);
InvalidateRect(hwnd,&x1_cur_obj->rc,FALSE);
////给父窗口发 MSG_CUR_X1_CAHNGLE 消息.
PostMessage(GetParent(hwnd),MSG_CUR_X1_CHANGE,x1_cur,0);
}
if(focus_cur == CUR_X2) // X1光标.
{
rc.x =x2_cur + rc_wav.x;
rc.y =rc_wav.y;
rc.w =1;
rc.h =rc_wav.h;
InvalidateRect(hwnd,&rc,FALSE);
InvalidateRect(hwnd,&x2_cur_obj->rc,FALSE);
x2_cur =x;
x_obj_move_to(x2_cur_obj,(x+rc_wav.x)-(x2_cur_obj->rc.w/2),x2_cur_obj->rc.y);
rc.x =x2_cur + rc_wav.x;
rc.y =rc_wav.y;
rc.w =1;
rc.h =rc_wav.h;
InvalidateRect(hwnd,&rc,FALSE);
InvalidateRect(hwnd,&x2_cur_obj->rc,FALSE);
////
PostMessage(GetParent(hwnd),MSG_CUR_X2_CHANGE,x2_cur,0);
}
if(focus_cur == CUR_Y1)
{
rc.x =rc_wav.x;
rc.y =rc_wav.y+rc_wav.h-y1_cur;
rc.w =rc_wav.w;
rc.h =1;
InvalidateRect(hwnd,&rc,FALSE);
InvalidateRect(hwnd,&y1_cur_obj->rc,FALSE);
y1_cur =rc_wav.h-y;
x_obj_move_to(y1_cur_obj,y1_cur_obj->rc.x,(y+rc_wav.y)-(y1_cur_obj->rc.h/2));
rc.x =rc_wav.x;
rc.y =rc_wav.y+rc_wav.h-y1_cur;
rc.w =rc_wav.w;
rc.h =1;
InvalidateRect(hwnd,&rc,FALSE);
InvalidateRect(hwnd,&y1_cur_obj->rc,FALSE);
////
PostMessage(GetParent(hwnd),MSG_CUR_Y1_CHANGE,y1_cur,0);
}
if(focus_cur == CUR_Y2)
{
rc.x =rc_wav.x;
rc.y =rc_wav.y+rc_wav.h-y2_cur;
rc.w =rc_wav.w;
rc.h =1;
InvalidateRect(hwnd,&rc,FALSE);
InvalidateRect(hwnd,&y2_cur_obj->rc,FALSE);
y2_cur =rc_wav.h-y;
x_obj_move_to(y2_cur_obj,y2_cur_obj->rc.x,(y+rc_wav.y)-(y2_cur_obj->rc.h/2));
rc.x =rc_wav.x;
rc.y =rc_wav.y+rc_wav.h-y2_cur;
rc.w =rc_wav.w;
rc.h =1;
InvalidateRect(hwnd,&rc,FALSE);
InvalidateRect(hwnd,&y2_cur_obj->rc,FALSE);
////
PostMessage(GetParent(hwnd),MSG_CUR_Y2_CHANGE,y2_cur,0);
}
}
return DefWindowProc(hwnd,msg,wParam,lParam);
////
case WM_ERASEBKGND:
{
// HDC hdc=(HDC)wParam;
// RECT rc;
// GetClientRect(hwnd,&rc);
// SetBrushColor(hdc,MapRGB(hdc,0,0,0));
// FillRect(hdc,&rc);
return TRUE;
}
////
case WM_PAINT:
{
HDC hdc;
PAINTSTRUCT ps;
hdc =BeginPaint(hwnd,&ps);
///////
wave_owner_draw(hdc);
EndPaint(hwnd,&ps);
}
break;
////
case WM_DESTROY:
{
// x_obj_del(button_item);
// x_obj_del(text_item);
// DeleteDC(hdcTop);
// DeleteSurface(pSurfTop);
// DeleteFont(hFont20);
// DeleteFont(hFont24);
return DefWindowProc(hwnd,msg,wParam,lParam);
}
////
default:
return DefWindowProc(hwnd,msg,wParam,lParam);
}
return WM_NULL;
}
static LRESULT WinProc(HWND hwnd,UINT msg,WPARAM wParam,LPARAM lParam)
{
RECT rc;
switch(msg)
{
case WM_CREATE:
/* 波形数据需要使用的空间 */
pt_wav = (POINT*)GUI_VMEM_Alloc(sizeof(POINT)*800);
pt_wav2 = (POINT*)GUI_VMEM_Alloc(sizeof(POINT)*800);
x1_cur=15;
x2_cur=50;
y1_cur=30;
y2_cur=70;
// x_step=50; //50ms
y_step_cur=2;
x_step_cur=0;
focus_obj =NULL;
// hFont20 =XFT_CreateFont(ASCII_20_4BPP);
// hFont24 =XFT_CreateFont(ASCII_24_4BPP);
GetClientRect(hwnd,&rc);
// pSurfTop =CreateSurface(SURF_ARGB4444,rc.w,rc.h,NULL,0);
// hdcTop =CreateDC(pSurfTop,NULL);
// ClrDisplay(hdcTop,NULL,MapARGB(hdcTop,0,0,0,0));
GetClientRect(hwnd,&rc_main);
CopyRect(&rc_wav,&rc_main);
InflateRectEx(&rc_wav,-LEFT_OFFSET,-TOP_OFFSET,-RIGHT_OFFSET,-BOTTOM_OFFSET);
rc_x1_cur.x =rc_wav.x+x1_cur-CUR_BOX_SIZE/2;
rc_x1_cur.y =rc_wav.y-CUR_BOX_SIZE;
rc_x1_cur.w =CUR_BOX_SIZE;
rc_x1_cur.h =CUR_BOX_SIZE;
rc_x2_cur.x =rc_wav.x+x2_cur-CUR_BOX_SIZE/2;
rc_x2_cur.y =rc_wav.y-CUR_BOX_SIZE;
rc_x2_cur.w =CUR_BOX_SIZE;
rc_x2_cur.h =CUR_BOX_SIZE;
rc_y1_cur.x =rc_wav.x+rc_wav.w;
rc_y1_cur.y =rc_wav.y+rc_wav.h-y1_cur-CUR_BOX_SIZE/2;
rc_y1_cur.w =CUR_BOX_SIZE;
rc_y1_cur.h =CUR_BOX_SIZE;
rc_y2_cur.x =rc_wav.x+rc_wav.w;
rc_y2_cur.y =rc_wav.y+rc_wav.h-y2_cur-CUR_BOX_SIZE/2;
rc_y2_cur.w =CUR_BOX_SIZE;
rc_y2_cur.h =CUR_BOX_SIZE;
/* 底部的标签栏 */
rc_label.x =LEFT_OFFSET-10;
rc_label.h =64;
rc_label.y =rc_main.h-rc_label.h;
rc_label.w =620-LEFT_OFFSET-RIGHT_OFFSET+20;
rc_button.w =150;
rc_button.h =rc_main.h-80;
rc_button.x =rc_main.w-RIGHT_OFFSET+10;
rc_button.y =60;
if(1)
{
RECT rc,m_rc[8],cb_rc;
HWND wnd;
rc.w =rc_main.w-60*2;
rc.h =40;
rc.x = 60;
rc.y =0;
CreateWindow(TEXTBOX,L"波形显示",TBS_FLAT|TBS_CENTER|WS_VISIBLE,rc.x,rc.y,rc.w,rc.h,hwnd,ID_TEXT5,NULL,NULL);
rc.w =70;
rc.h =70;
rc.x = 730;
rc.y =0;
/* 关闭按钮 */
wnd=CreateWindow(BUTTON,L"O", BS_FLAT|WS_OWNERDRAW|WS_TRANSPARENT|WS_VISIBLE,rc.x,rc.y,rc.w,rc.h,hwnd,ID_EXIT,NULL,NULL); //创建一个按钮.
//SetWindowFont(wnd,controlFont_72); //设置控件窗口字体.
MakeMatrixRect(m_rc,&rc_button,2,20,1,7);
// text_item =x_obj_create_class(L"TextItem", 0xFFFFFFFF, &rc_button,X_OBJ_VISIBLE,0,text_draw);
rc =m_rc[0];
//OffsetRect(&rc,-100,0);
rc.x =rc_main.w-rc.w-20;
rc.y += 28;
CreateWindow(TEXTBOX,L"模拟输入数据",TBS_FLAT|TBS_CENTER|WS_VISIBLE,rc.x,rc.y,rc.w,rc.h,hwnd,ID_TEXT1,NULL,NULL);
OffsetRect(&rc,0,rc.h+20);
CreateWindow(TEXTBOX,L"频率,单位Hz",TBS_FLAT|TBS_CENTER|WS_VISIBLE,rc.x,rc.y,rc.w,rc.h,hwnd,ID_TEXT2,NULL,NULL);
OffsetRect(&rc,0,rc.h);
{
SCROLLINFO sif;
sif.cbSize =sizeof(sif);
sif.fMask =SIF_ALL;
sif.nMin =10;
sif.nMax =20;
wave_freq = sif.nValue =15;
sif.TrackSize =30;
sif.ArrowSize =0;//20;
wnd = CreateWindow(SCROLLBAR,L"HScroll1",WS_OWNERDRAW|WS_VISIBLE,rc.x,rc.y,rc.w,rc.h,hwnd,ID_SCROLL1,NULL,NULL);
SendMessage(wnd,SBM_SETSCROLLINFO,TRUE,(LPARAM)&sif);
sif.nMin =10;
sif.nMax =500;
wave_amp = sif.nValue =100;
OffsetRect(&rc,0,rc.h+10);
CreateWindow(TEXTBOX,L"幅值,单位mV",TBS_FLAT|TBS_CENTER|WS_VISIBLE,rc.x,rc.y,rc.w,rc.h,hwnd,ID_TEXT3,NULL,NULL);
OffsetRect(&rc,0,rc.h);
wnd = CreateWindow(SCROLLBAR,L"HScroll2",WS_OWNERDRAW|WS_VISIBLE,rc.x,rc.y,rc.w,rc.h,hwnd,ID_SCROLL2,NULL,NULL);
SendMessage(wnd,SBM_SETSCROLLINFO,TRUE,(LPARAM)&sif);
}
OffsetRect(&rc,0,rc.h+20);
CopyRect(&cb_rc,&rc);
cb_rc.x +=5;
cb_rc.h -=5;
cb_rc.w = cb_rc.h-2;
//创建单选按钮(GroupID号为1).
CreateWindow(BUTTON,L"",WS_OWNERDRAW|BS_RADIOBOX|WS_VISIBLE,cb_rc.x,cb_rc.y,cb_rc.w,cb_rc.h,hwnd,ID_RB1,NULL,NULL);
OffsetRect(&cb_rc,cb_rc.w+7,0);
CreateWindow(BUTTON,L"",WS_OWNERDRAW|BS_RADIOBOX|WS_VISIBLE,cb_rc.x,cb_rc.y,cb_rc.w,cb_rc.h,hwnd,ID_RB2,NULL,NULL);
OffsetRect(&cb_rc,cb_rc.w+7,0);
CreateWindow(BUTTON,L"",WS_OWNERDRAW|BS_RADIOBOX|WS_VISIBLE,cb_rc.x,cb_rc.y,cb_rc.w,cb_rc.h,hwnd,ID_RB3,NULL,NULL);
OffsetRect(&cb_rc,cb_rc.w+7,0);
CreateWindow(BUTTON,L"",WS_OWNERDRAW|BS_RADIOBOX|WS_VISIBLE,cb_rc.x,cb_rc.y,cb_rc.w,cb_rc.h,hwnd,ID_RB4,NULL,NULL);
/* 设置默认按钮 i g*/
SendMessage(GetDlgItem(hwnd,ID_RB1),BM_SETSTATE,BST_CHECKED,0);
OffsetRect(&rc,0,rc.h);
wnd = CreateWindow(TEXTBOX,L"j",TBS_FLAT|TBS_CENTER|WS_VISIBLE,rc.x,rc.y,cb_rc.w,rc.h,hwnd,ID_TEXT4,NULL,NULL);
SetWindowFont(wnd,controlFont_48);
OffsetRect(&rc,cb_rc.w+7,0);
wnd = CreateWindow(TEXTBOX,L"h",TBS_FLAT|TBS_CENTER|WS_VISIBLE,rc.x,rc.y,cb_rc.w,rc.h,hwnd,ID_TEXT6,NULL,NULL);
SetWindowFont(wnd,controlFont_48);
OffsetRect(&rc,cb_rc.w+7,0);
wnd = CreateWindow(TEXTBOX,L"i",TBS_FLAT|TBS_CENTER|WS_VISIBLE,rc.x,rc.y,cb_rc.w,rc.h,hwnd,ID_TEXT7,NULL,NULL);
SetWindowFont(wnd,controlFont_48);
OffsetRect(&rc,cb_rc.w+10,0);
wnd = CreateWindow(TEXTBOX,L"g",TBS_FLAT|TBS_CENTER|WS_VISIBLE,rc.x,rc.y,cb_rc.w,rc.h,hwnd,ID_TEXT8,NULL,NULL);
SetWindowFont(wnd,controlFont_48);
/* 按钮 */
button_item =x_obj_create_class(L"ButtonItem", 0xFFFFFFFF, &rc_button,X_OBJ_VISIBLE,0,btn_draw);
rc.w =rc_main.w-RIGHT_OFFSET-170;
rc.h =30;
rc.x =10;
rc.y =rc_main.h - 2*rc.h-4;
////创建一个 TEXTBOX.
// x_wsprintf(wbuf,L"X1: % 5dmS, X2: % 5dmS, X2-X1: % 5dmS",x1_cur*x_step[x_step_cur],x2_cur*x_step[x_step_cur],(x2_cur-x1_cur)*x_step[x_step_cur]);
// CreateWindow(TEXTBOX,wbuf,WS_BORDER|WS_VISIBLE,rc.x,rc.y,rc.w,rc.h,hwnd,ID_X_STR,NULL,NULL);
// ////创建一个 TEXTBOX.
// OffsetRect(&rc,0,rc.h+2);
// x_wsprintf(wbuf,L"Y1: %6.1fmV, Y2: %6.1fmV, Y2-Y1: %6.1fmV",y1_cur*y_step[y_step_cur],y2_cur*y_step[y_step_cur],(y2_cur-y1_cur)*y_step[y_step_cur]);
// CreateWindow(TEXTBOX,wbuf,WS_BORDER|WS_VISIBLE,rc.x,rc.y,rc.w,rc.h,hwnd,ID_Y_STR,NULL,NULL);
rc.w =30;
rc.h =30;
rc.x =rc_main.w-rc.w-20;
rc.y =rc_main.h - 2*rc.h-4;
x_obj_create(L"+", ID_Y_STEP_ADD, &rc, X_OBJ_VISIBLE,0,button_item);
rc.w =80;
OffsetRect(&rc,-(rc.w+2),0);
x_obj_create(y_step_str[y_step_cur],ID_Y_STEP, &rc, X_OBJ_VISIBLE,0,button_item);
rc.w =30;
OffsetRect(&rc,-(rc.w+2),0);
x_obj_create(L"-", ID_Y_STEP_SUB, &rc, X_OBJ_VISIBLE,0,button_item);
rc.w =30;
rc.h =30;
rc.x =rc_main.w-rc.w-20;
rc.y =rc_main.h - 2*rc.h-4;
OffsetRect(&rc,0,rc.h+2);
x_obj_create(L"+", ID_X_STEP_ADD, &rc, X_OBJ_VISIBLE,0,button_item);
rc.w =80;
OffsetRect(&rc,-(rc.w+2),0);
x_obj_create(x_step_str[x_step_cur],ID_X_STEP, &rc, X_OBJ_VISIBLE,0,button_item);
rc.w =30;
OffsetRect(&rc,-(rc.w+2),0);
x_obj_create(L"-", ID_X_STEP_SUB, &rc, X_OBJ_VISIBLE,0,button_item);
OffsetRect(&rc,-(rc.w+2),0);
}
if(1)
{
WNDCLASS wcex;
wcex.Tag = WNDCLASS_TAG;
wcex.Style = CS_HREDRAW | CS_VREDRAW;
wcex.lpfnWndProc = (WNDPROC)WaveWinProc;
wcex.cbClsExtra = 0;
wcex.cbWndExtra = 0;
wcex.hInstance = NULL;
wcex.hIcon = NULL;
wcex.hCursor = NULL;
rc.x =0;
rc.y =40;
rc.w =620;
rc.h =rc_main.h-rc.y-70;
////创建"波形显示"的控件.
CreateWindow(&wcex,L"---",WS_CLIPCHILDREN|WS_VISIBLE,rc.x,rc.y,rc.w,rc.h,hwnd,ID_WAVE,NULL,NULL);
// ////创建一个 TEXTBOX.
// OffsetRect(&rc,0,rc.h+4);
// rc.h =24;
// CreateWindow(TEXTBOX,L"---",WS_VISIBLE,rc.x,rc.y,rc.w,rc.h,hwnd,ID_X_STR,NULL,NULL);
// ////创建一个 TEXTBOX.
// OffsetRect(&rc,0,rc.h);
// CreateWindow(TEXTBOX,L"---",WS_VISIBLE,rc.x,rc.y,rc.w,rc.h,hwnd,ID_Y_STR,NULL,NULL);
}
return TRUE;
////
case WM_CTLCOLOR:
{
u16 id;
id =LOWORD(wParam);
if(id >= ID_TEXT1 && id <= ID_TEXT8)
{
CTLCOLOR *cr;
cr =(CTLCOLOR*)lParam;
cr->TextColor =RGB888(255,255,255);
cr->BackColor =RGB888(0,0,0);
cr->BorderColor =RGB888(0,0,0);
return TRUE;
}
// else if(id >= ID_RB1 && id <= ID_RB4)
// {
// CTLCOLOR *cr;
// cr =(CTLCOLOR*)lParam;
// if(SendMessage(GetDlgItem(hwnd,id),BM_GETSTATE,0,0)&BST_CHECKED)
// {
// cr->TextColor =RGB888(0,0,0); //文字颜色(RGB32颜色格式)
// cr->BackColor =RGB888(220,200,200); //背景颜色(RGB32颜色格式)
// cr->BorderColor =RGB888(30,30,230); //边框颜色(RGB32颜色格式)
// cr->ForeColor =RGB888(90,174,22); //前景颜色(RGB32颜色格式)
// }
// else
// {
// cr->TextColor =RGB888(0,0,0);
// cr->BackColor =RGB888(200,220,200);
// cr->BorderColor =RGB888(50,50,50);
// cr->ForeColor =RGB888(180,200,230);
// }
//
// return TRUE;
// }
else if(id == ID_X_STR || id == ID_Y_STR)
{
CTLCOLOR *cr;
cr =(CTLCOLOR*)lParam;
cr->TextColor =RGB888(255,255,255); //文字颜色(RGB32颜色格式)
cr->BackColor =RGB888(90,174,22); //背景颜色(RGB32颜色格式)
cr->BorderColor =RGB888(255,255,255); //边框颜色(RGB32颜色格式)
// cr->ForeColor =RGB888(90,174,22); //前景颜色(RGB32颜色格式)
return TRUE;
}
else
{
//其它按钮使用系统默认的颜色进行绘制,所以直接返回FALSE.
return FALSE;
}
}
case WM_LBUTTONDOWN: //
{
int x,y;
x=GET_LPARAM_X(lParam);
y=GET_LPARAM_Y(lParam);
focus_obj =x_obj_get_from_pos(button_item,x,y); //从x,y坐标值获得 x_obj对象.
if(focus_obj==NULL)
{ //没有
return DefWindowProc(hwnd,msg,wParam,lParam);
}
else if(focus_obj->id == ID_Y_STEP_SUB)
{
InvalidateRect(hwnd,&focus_obj->rc,FALSE);
if(y_step_cur > 0)
{
y_step_cur--;
x_obj_set_text(x_obj_get_from_id(button_item,ID_Y_STEP),y_step_str[y_step_cur]);
InvalidateRect(hwnd,&x_obj_get_from_id(button_item,ID_Y_STEP)->rc,FALSE);
InvalidateRect(GetDlgItem(hwnd,ID_WAVE),NULL,FALSE);
// InvalidateRect(GetDlgItem(hwnd,ID_Y_STR),NULL,FALSE);
//发 MSG_CUR_Y_CAHNGLE 消息.
PostMessage(hwnd,MSG_CUR_Y1_CHANGE,x1_cur,0);
}
}
else if(focus_obj->id == ID_Y_STEP_ADD)
{
InvalidateRect(hwnd,&focus_obj->rc,FALSE);
if(y_step_cur < (Y_STEP_NUM-1))
{
y_step_cur++;
x_obj_set_text(x_obj_get_from_id(button_item,ID_Y_STEP),y_step_str[y_step_cur]);
InvalidateRect(hwnd,&x_obj_get_from_id(button_item,ID_Y_STEP)->rc,FALSE);
InvalidateRect(GetDlgItem(hwnd,ID_WAVE),NULL,FALSE);
// InvalidateRect(GetDlgItem(hwnd,ID_Y_STR),NULL,FALSE);
PostMessage(hwnd,MSG_CUR_Y1_CHANGE,x1_cur,0);
}
}
else if(focus_obj->id == ID_X_STEP_SUB)
{
InvalidateRect(hwnd,&focus_obj->rc,FALSE);
if(x_step_cur > 0)
{
x_step_cur--;
x_obj_set_text(x_obj_get_from_id(button_item,ID_X_STEP),x_step_str[x_step_cur]);
InvalidateRect(hwnd,&x_obj_get_from_id(button_item,ID_X_STEP)->rc,FALSE);
InvalidateRect(GetDlgItem(hwnd,ID_WAVE),NULL,FALSE);
// InvalidateRect(GetDlgItem(hwnd,ID_X_STR),NULL,FALSE);
//发 MSG_CUR_X1_CAHNGLE 消息.
PostMessage(hwnd,MSG_CUR_X1_CHANGE,x1_cur,0);
}
}
else if(focus_obj->id == ID_X_STEP_ADD)
{
InvalidateRect(hwnd,&focus_obj->rc,FALSE);
if(x_step_cur < (X_STEP_NUM-1))
{
x_step_cur++;
x_obj_set_text(x_obj_get_from_id(button_item,ID_X_STEP),x_step_str[x_step_cur]);
InvalidateRect(hwnd,&x_obj_get_from_id(button_item,ID_X_STEP)->rc,FALSE);
InvalidateRect(GetDlgItem(hwnd,ID_WAVE),NULL,FALSE);
// InvalidateRect(GetDlgItem(hwnd,ID_X_STR),NULL,FALSE);
//发 MSG_CUR_X1_CAHNGLE 消息.
PostMessage(hwnd,MSG_CUR_X1_CHANGE,x1_cur,0);
}
}
}
return DefWindowProc(hwnd,msg,wParam,lParam);
////
case WM_MOUSELEAVE:
case WM_LBUTTONUP:
{
/////
if(focus_obj!=NULL)
{
InvalidateRect(hwnd,&focus_obj->rc,FALSE);
}
focus_cur =0;
focus_obj =NULL;
// InvalidateRect(hwnd,NULL,TRUE);
}
return DefWindowProc(hwnd,msg,wParam,lParam);
////
case WM_NOTIFY:
{
U16 code,id;
NMHDR *nr;
code =HIWORD(wParam);
id =LOWORD(wParam);
nr =(NMHDR*)lParam; //lParam参数,是以NMHDR结构体开头.
if(id==ID_EXIT && code==BN_CLICKED)
{
PostCloseMessage(hwnd);
}
else if(id == ID_SCROLL1 || id == ID_SCROLL2 )
{
NM_SCROLLBAR *sb_nr;
int i;
sb_nr =(NM_SCROLLBAR*)nr; //Scrollbar的通知消息实际为 NM_SCROLLBAR扩展结构,里面附带了更多的信息.
switch(nr->code)
{
case SBN_THUMBTRACK: //滑块移动
{
i =sb_nr->nTrackValue; //获得滑块当前位置值
if(id == ID_SCROLL1)
wave_freq = i;
else if(id == ID_SCROLL2)
wave_amp = i;
SendMessage(nr->hwndFrom,SBM_SETVALUE,TRUE,i); //设置位置值
// InvalidateRect();
// SendMessage(GetDlgItem(hwnd,ID_WAVE),WM_PAINT,NULL,NULL); //设置位置值
// if(wave_format != SCATTER)
InvalidateRect(GetDlgItem(hwnd,ID_WAVE),NULL,FALSE);
/* 重置随机波形标志 */
scatter_init = 0;
}
break;
default:
break;
}
}
else if(id >= ID_RB1 && id<= ID_RB4)
{
if(code == BN_CLICKED) //被点击了
{
/* 重置随机波形标志 */
scatter_init = 0;
switch(id)
{
case ID_RB1:
wave_format = SINE_WAVE;
break;
case ID_RB2:
wave_format = SQUARE_WAVE;
break;
case ID_RB3:
wave_format = TRIANGULAR_WAVE;
break;
case ID_RB4:
wave_format = SCATTER;
break;
default:
wave_format = SINE_WAVE;
break;
}
/* 重绘波形*/
InvalidateRect(GetDlgItem(hwnd,ID_WAVE),NULL,FALSE);
}
}
}
break;
/////
case MSG_CUR_X1_CHANGE:
case MSG_CUR_X2_CHANGE:
{
InvalidateRect(hwnd,&rc_label,TRUE);
// WCHAR wbuf[128];
// x_wsprintf(wbuf,L"X1: % 5dmS, X2: % 5dmS, X2-X1: % 5dmS",x1_cur*x_step[x_step_cur],x2_cur*x_step[x_step_cur],(x2_cur-x1_cur)*x_step[x_step_cur]);
// SetWindowText(GetDlgItem(hwnd,ID_X_STR),wbuf);
}
break;
////
case MSG_CUR_Y1_CHANGE:
case MSG_CUR_Y2_CHANGE:
{
InvalidateRect(hwnd,&rc_label,TRUE);
// WCHAR wbuf[128];
// x_wsprintf(wbuf,L"Y1: %6.1fmV, Y2: %6.1fmV, Y2-Y1: %6.1fmV",y1_cur*y_step[y_step_cur],y2_cur*y_step[y_step_cur],(y2_cur-y1_cur)*y_step[y_step_cur]);
// SetWindowText(GetDlgItem(hwnd,ID_Y_STR),wbuf);
}
break;
case WM_ERASEBKGND:
{
HDC hdc=(HDC)wParam;
RECT rc;
GetClientRect(hwnd,&rc);
SetBrushColor(hdc,MapRGB(hdc,0,0,0));
FillRect(hdc,&rc);
return TRUE;
}
case WM_DRAWITEM:
{
DRAWITEM_HDR *ds;
ds =(DRAWITEM_HDR*)lParam;
if(ds->ID == ID_SCROLL1 || ds->ID == ID_SCROLL2)
{
scrollbar_owner_draw(ds);
return TRUE;
}
if(ds->ID == ID_EXIT)
{
exit_owner_draw(ds);
return TRUE;
}
if(ds->ID >= ID_RB1 && ds->ID <= ID_RB4)
{
RB_owner_draw(ds);
return TRUE;
}
}
break;
////
case WM_PAINT:
{
HDC hdc;
PAINTSTRUCT ps;
RECT m_rc[8];;
WCHAR wbuf[128];
hdc =BeginPaint(hwnd,&ps);
x_obj_draw(hdc,button_item);
#if 1
{
MakeMatrixRect(m_rc,&rc_label,10,2,3,2);
////X Text
SetTextColor(hdc,MapRGB(hdc,255,255,255));
SetPenColor(hdc,MapRGB(hdc,255,255,255));
SetBrushColor(hdc,MapRGB(hdc,90,174,22));
x_wsprintf(wbuf,L"X1:%dmS",x1_cur*x_step[x_step_cur]);
DrawText(hdc,wbuf,-1,&m_rc[0],DT_SINGLELINE|DT_VCENTER|DT_CENTER|DT_BKGND|DT_BORDER);
x_wsprintf(wbuf,L"X2:%dmS",x2_cur*x_step[x_step_cur]);
DrawText(hdc,wbuf,-1,&m_rc[1],DT_SINGLELINE|DT_VCENTER|DT_CENTER|DT_BKGND|DT_BORDER);
x_wsprintf(wbuf,L"X2-X1:%dmS",(x2_cur-x1_cur)*x_step[x_step_cur]);
DrawText(hdc,wbuf,-1,&m_rc[2],DT_SINGLELINE|DT_VCENTER|DT_CENTER|DT_BKGND|DT_BORDER);
////Y Text
SetTextColor(hdc,MapRGB(hdc,255,255,255));
SetPenColor(hdc,MapRGB(hdc,255,255,255));
SetBrushColor(hdc,MapRGB(hdc,90,174,22));
x_wsprintf(wbuf,L"Y1:%.1fmV",y1_cur*y_step[y_step_cur]);
DrawText(hdc,wbuf,-1,&m_rc[3],DT_SINGLELINE|DT_VCENTER|DT_CENTER|DT_BKGND|DT_BORDER);
x_wsprintf(wbuf,L"Y2:%.1fmV",y2_cur*y_step[y_step_cur]);
DrawText(hdc,wbuf,-1,&m_rc[4],DT_SINGLELINE|DT_VCENTER|DT_CENTER|DT_BKGND|DT_BORDER);
x_wsprintf(wbuf,L"Y2-Y1:%.1fmV",(y2_cur-y1_cur)*y_step[y_step_cur]);
DrawText(hdc,wbuf,-1,&m_rc[5],DT_SINGLELINE|DT_VCENTER|DT_CENTER|DT_BKGND|DT_BORDER);
}
#endif
EndPaint(hwnd,&ps);
}
break;
////
case WM_DESTROY:
{
x_obj_del(button_item);
// DeleteFont(hFont20);
// DeleteFont(hFont24);
GUI_VMEM_Free(pt_wav);
GUI_VMEM_Free(pt_wav2);
/* 重置随机波形标志 */
scatter_init = 0;
return DefWindowProc(hwnd,msg,wParam,lParam);
}
////
default:
return DefWindowProc(hwnd,msg,wParam,lParam);
}
return WM_NULL;
}
/*============================================================================*/
static void ADS1120_Init(void)
{
// sensor_enable();
}
static u16 ADS1120_GetData(void)
{
//return get_alco_data();
return x_rand()%0x7FFF;
}
static float ADS1120_GetVoltage_mV(u16 addata)
{
float val;
addata=ADS1120_GetData();
val=(float)addata*(float)2048/32768;
return val;
}
extern "C" void GUI_DEMO_ShowWave(void)
{
HWND hwnd;
MSG msg;
WNDCLASS wcex;
RECT rc;
////
ShowCursor(FALSE);
ADS1120_Init();
wcex.Tag = WNDCLASS_TAG;
wcex.Style = CS_HREDRAW | CS_VREDRAW;
wcex.lpfnWndProc = (WNDPROC)WinProc;
wcex.cbClsExtra = 0;
wcex.cbWndExtra = 0;
wcex.hInstance = NULL;
wcex.hIcon = NULL;
wcex.hCursor = NULL;
rc.x =0;
rc.y =0;
rc.w =GUI_XSIZE;
rc.h =GUI_YSIZE;
hwnd =CreateWindowEx( WS_EX_NODRAG|WS_EX_FRAMEBUFFER,&wcex,
L"Show Wave",
WS_CLIPCHILDREN,
rc.x,rc.y,rc.w,rc.h,
NULL,0,NULL,NULL);
ShowWindow(hwnd,SW_SHOW);
UpdateWindow(hwnd);
ShowWindow(hwnd,SW_SHOW);
while(GetMessage(&msg,hwnd))
{
TranslateMessage(&msg);
DispatchMessage(&msg);
}
ShowCursor(TRUE);
}
| [
"[email protected]"
] | |
3a7ac521bbeb318f284c827d316bc83c2c366cd9 | fa889d051a1b3c4d861fb06b10aa5b2e21f97123 | /kbe/res/client/sdk_templates/ue4/Source/KBEnginePlugins/Private/PacketSender.cpp | c1f01a0e5d68d55ce9301ced669ce6ff96920985 | [
"MIT",
"LGPL-3.0-only"
] | permissive | BuddhistDeveloper/HeroLegendServer | bcaa837e3bbd6544ce0cf8920fd54a1a324d95c8 | 8bf77679595a2c49c6f381c961e6c52d31a88245 | refs/heads/master | 2022-12-08T00:32:45.623725 | 2018-01-15T02:01:44 | 2018-01-15T02:01:44 | 117,069,431 | 1 | 1 | MIT | 2022-11-19T15:58:30 | 2018-01-11T08:05:32 | Python | UTF-8 | C++ | false | false | 415 | cpp |
#include "PacketSender.h"
#include "MemoryStream.h"
#include "KBDebug.h"
PacketSender::PacketSender(NetworkInterface* pNetworkInterface) :
pNetworkInterface_(pNetworkInterface)
{
}
PacketSender::~PacketSender()
{
}
bool PacketSender::send(MemoryStream* pMemoryStream)
{
int32 sent = 0;
return pNetworkInterface_->socket()->Send(pMemoryStream->data() + pMemoryStream->rpos(), pMemoryStream->length(), sent);
} | [
"[email protected]"
] | |
caf03fcf3972307b95009a8132cfb8fcbb7053f8 | ce9998a2370fc81f4e3c3b328456fa20c25291cd | /models.h | 5320aab5b422f52da53c7d9fb06bcbc20e507fb9 | [] | no_license | RoyalSix/SpellingRecognitionHMM | 1704732e405722f028b23e0523f19cf1f5434896 | cb208630fcc524c9bc7357d27d4a918f065fe70a | refs/heads/master | 2021-01-12T10:46:00.227722 | 2016-12-21T09:10:00 | 2016-12-21T09:10:00 | 72,688,565 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,089 | h |
#include <string>
#define ALPHABET "abcdefghijklmnopqrstuvwxyz"
#define ALPHABET_SIZE 26
using namespace std;
double prCharGivenCharOfState(char charGenerated, char charOfTheState, double scaleFactor);
/************************************************************************/
//Calculate and return the probability of charGenerated actually typed
//given charOfTheState as the underlying cognitive state.
/************************************************************************/
void getPrTableForPossibleInitialStates(double prTable[], int sizeOfTable);
/************************************************************************/
//Calculate for each actual cognitive state in a word of sizeOfTable characters,
// the probability of that cognitive state being the actual first cognitive state
// when the user types the word.
//Store these prbabilities in the prTable array.
/************************************************************************/
void getPrTableForPossibleNextStates (double transitionPrTable[], int sizeOfTable, int currentState);
void setParametersSpellingModel();
/************************************************************************/
//Reset the parameters of the spelling model
/************************************************************************/
void displayParametersSpellingModel();
/************************************************************************/
//Display the parameters of the spelling model
/************************************************************************/
void setParametersKbModel();
/************************************************************************/
//Reset the parameters of the keyboard model
/************************************************************************/
void displayParametersKbModel();
/************************************************************************/
//Display the parameters of the keyboard model
/************************************************************************/
int distanceOfLetters(char charOne, char charTwo);
double getScaleFactor(int num);
void testPrOfTypingDocument();
void testgetPrFromDocument();
void testRecoverOriginal();
void testRecoverOriginal2();
void testPrecisionOfRecovered();
int take1SampleFrom1PrSpace(double prTable[], int sizeOfTable);
void getKeyboardProbabilityTable(char charToType, double prTable[]);
char typeOneChar(char charToType);
void typeOneWord(char word[], char output[], bool traceON = false, int maxOutput = 100);
void typeOneArticle(char * corruptedMessageFile, char * sourceArticle, bool trace = false);
double prOf1CharSeriesWhenTyping1Word(char observedString[], char wordString[]);
double logPrOfGettingDocument1WhenTypingDocument2(string document1, string document2);
void getPrFromDocument(string document1, string document2);
void recoverOriginal(string doc1, string doc2, string doc3);
void recoverOriginal2(string doc1, string doc2, string doc3, string doc4);
double getPrecisionOfRecovered(string doc1, string doc2);
| [
"[email protected]"
] | |
6de189689bd52b877076d403e340c95adf1d5e2c | 0c360ce74a4b3f08457dd354a6d1ed70a80a7265 | /src/components/formatters/test/meta_formatter_test.cc | 27f5e70e8fc14c4ed38a2206d1bc1dac74cc78f5 | [] | permissive | APCVSRepo/sdl_implementation_reference | 917ef886c7d053b344740ac4fc3d65f91b474b42 | 19be0eea481a8c05530048c960cce7266a39ccd0 | refs/heads/master | 2021-01-24T07:43:52.766347 | 2017-10-22T14:31:21 | 2017-10-22T14:31:21 | 93,353,314 | 4 | 3 | BSD-3-Clause | 2022-10-09T06:51:42 | 2017-06-05T01:34:12 | C++ | UTF-8 | C++ | false | false | 14,890 | cc | /*
* Copyright (c) 2015, Ford Motor Company
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following
* disclaimer in the documentation and/or other materials provided with the
* distribution.
*
* Neither the name of the Ford Motor Company nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
#include "gtest/gtest.h"
#include "formatters/meta_formatter.h"
#include "formatters/meta_formatter_test_helper.h"
namespace test {
namespace components {
namespace formatters {
TEST_F(CMetaFormatterTestHelper,
inputObjectIdenticalToSchemaWithAndWithoutMandatoryParams) {
Json::Value value;
Json::Reader reader;
CSmartFactory<FunctionIDTest::eType,
MessageTypeTest::eType,
StructIdentifiers::eType> factory_;
SmartObject object1 = factory_.CreateSmartObject(
FunctionIDTest::RegisterAppInterface, MessageTypeTest::request);
SmartObject object2 = factory_.CreateSmartObject(
FunctionIDTest::RegisterAppInterface, MessageTypeTest::request);
SmartObject result_object1;
SmartObject result_object2;
// Get schema
CSmartSchema schema;
schema = initSchemaForMetaFormatter();
FillObjectIdenticalToSchema(object1);
FillObjectIdenticalToSchemaWithoutNoMandatoriesParams(object2);
bool creationresult;
creationresult =
CMetaFormatter::CreateObjectByPattern(object1, schema, result_object1);
EXPECT_TRUE(creationresult);
creationresult =
CMetaFormatter::CreateObjectByPattern(object2, schema, result_object2);
EXPECT_TRUE(creationresult);
// Uncomment code to print objects in console
// std::string formatted_string;
// CFormatterJsonSDLRPCv1::toString(object1, formatted_string);
// printf("object1 %s\n", formatted_string.c_str());
//
// CFormatterJsonSDLRPCv1::toString(result_object1, formatted_string);
// printf("result_object1 %s\n", formatted_string.c_str());
//
// CFormatterJsonSDLRPCv1::toString(object2, formatted_string);
// printf("object2 %s\n", formatted_string.c_str());
//
// CFormatterJsonSDLRPCv1::toString(result_object2, formatted_string);
// printf("result_object2 %s\n", formatted_string.c_str());
CompareObjects(object1, result_object1);
CompareObjects(object2, result_object2);
// Enums must be unapplied (converted to string) in order to be compared
// against strings
result_object1.getSchema().unapplySchema(result_object1);
EXPECT_EQ("request", result_object1[S_PARAMS][S_MESSAGE_TYPE].asString());
EXPECT_EQ("RegisterAppInterface",
result_object1[S_PARAMS][S_FUNCTION_ID].asString());
result_object2.getSchema().unapplySchema(result_object2);
EXPECT_EQ("request", result_object2[S_PARAMS][S_MESSAGE_TYPE].asString());
EXPECT_EQ("RegisterAppInterface",
result_object2[S_PARAMS][S_FUNCTION_ID].asString());
}
TEST_F(CMetaFormatterTestHelper, NormalSchemaWithEmptyObject) {
SmartObject object;
SmartObject result_object;
SmartObject expected_object;
// Get schema
CSmartSchema schema = initSchemaForMetaFormatter();
bool create_object_result =
CMetaFormatter::CreateObjectByPattern(object, schema, result_object);
EXPECT_TRUE(create_object_result);
FillObjectWithDefaultValues(expected_object);
CompareObjects(expected_object, result_object);
// Uncomment code to print objects in console
// std::string str;
// AnyObjectToJsonString(result_object, str);
// printf("result_object(default) %s", str.c_str());
// AnyObjectToJsonString(expected_object, str);
// printf("expected_object %s", str.c_str());
}
TEST_F(CMetaFormatterTestHelper,
NormalSchemaWithObjectWithoutSomeMandatoryFields) {
SmartObject object;
SmartObject result_object;
// Get schema
CSmartSchema schema = initSchemaForMetaFormatter();
FillObjectWithoutSomeMandatoryFields(object);
CMetaFormatter::CreateObjectByPattern(object, schema, result_object);
CompareObjects(object, result_object);
EXPECT_EQ(0, result_object[S_PARAMS][S_CORRELATION_ID].asInt());
EXPECT_EQ(
0, result_object[S_MSG_PARAMS]["syncMsgVersion"]["majorVersion"].asInt());
EXPECT_EQ(
0, result_object[S_MSG_PARAMS]["syncMsgVersion"]["minorVersion"].asInt());
// Uncomment code to print object in console
// std::string str;
// AnyObjectToJsonString(result_object, str);
// printf("result_object %s", str.c_str());
}
TEST_F(CMetaFormatterTestHelper, ObjectWithEmptyMap) {
std::map<std::string, CObjectSchemaItem::SMember> schemaMembersMap;
CSmartSchema map_schema =
CSmartSchema(CObjectSchemaItem::create(schemaMembersMap));
SmartObject object;
SmartObject result_object_empty_map;
SmartObject object_empty_map = SmartObject(SmartType_Map);
CMetaFormatter::CreateObjectByPattern(
object_empty_map, map_schema, result_object_empty_map);
EXPECT_EQ(SmartType_Map, result_object_empty_map.getType())
<< "smartObject is not map type";
EXPECT_EQ(0u, result_object_empty_map.length()) << "non empty map";
CMetaFormatter::CreateObjectByPattern(
object, map_schema, result_object_empty_map);
EXPECT_EQ(SmartType_Map, result_object_empty_map.getType())
<< "smartObject is not map type";
EXPECT_EQ(0u, result_object_empty_map.length()) << "non empty map";
object["field1"] = 0;
object["field2"] = SmartObject();
CMetaFormatter::CreateObjectByPattern(
object, map_schema, result_object_empty_map);
EXPECT_EQ(SmartType_Map, result_object_empty_map.getType())
<< "smartObject is not map type";
EXPECT_EQ(0u, result_object_empty_map.length()) << "non empty map";
// Fill object with any values. Result must be the same
FillObjectIdenticalToSchema(object);
CMetaFormatter::CreateObjectByPattern(
object, map_schema, result_object_empty_map);
EXPECT_EQ(SmartType_Map, result_object_empty_map.getType())
<< "smartObject is not map type";
EXPECT_EQ(0u, result_object_empty_map.length()) << "non empty map";
// Fill object with any values. Result must be the same
FillObjectIdenticalToSchemaWithoutNoMandatoriesParams(object);
CMetaFormatter::CreateObjectByPattern(
object, map_schema, result_object_empty_map);
EXPECT_EQ(SmartType_Map, result_object_empty_map.getType())
<< "smartObject is not map type";
EXPECT_EQ(0u, result_object_empty_map.length()) << "non empty map";
// Uncomment code to print object in console
// std::string str;
// AnyObjectToJsonString(result_object_empty_map, str);
// printf("result_object(empty map) %s", str.c_str());
}
TEST_F(CMetaFormatterTestHelper, ObjectWithEmptyArray) {
SmartObject object;
SmartObject result_object_empty_array;
CSmartSchema array_schema = CSmartSchema(CArraySchemaItem::create());
SmartObject object_empty_aray = SmartObject(SmartType_Array);
CMetaFormatter::CreateObjectByPattern(
object_empty_aray, array_schema, result_object_empty_array);
EXPECT_EQ(SmartType_Array, result_object_empty_array.getType())
<< "smartObject is not array type";
EXPECT_EQ(0u, result_object_empty_array.length()) << "non empty array";
CMetaFormatter::CreateObjectByPattern(
object, array_schema, result_object_empty_array);
EXPECT_EQ(SmartType_Array, result_object_empty_array.getType())
<< "smartObject is not array type";
EXPECT_EQ(0u, result_object_empty_array.length()) << "non empty array";
// Fill object with any values. Result must be the same
FillObjectIdenticalToSchema(object);
CMetaFormatter::CreateObjectByPattern(
object, array_schema, result_object_empty_array);
EXPECT_EQ(SmartType_Array, result_object_empty_array.getType())
<< "smartObject is not array type";
EXPECT_EQ(0u, result_object_empty_array.length()) << "non empty array";
// Fill object with any values. Result must be the same
FillObjectWithoutSomeMandatoryFields(object);
CMetaFormatter::CreateObjectByPattern(
object, array_schema, result_object_empty_array);
EXPECT_EQ(SmartType_Array, result_object_empty_array.getType())
<< "smartObject is not array type";
EXPECT_EQ(0u, result_object_empty_array.length()) << "non empty array";
// Uncomment code to print object in console
// std::string str;
// AnyObjectToJsonString(result_object_empty_array, str);
// printf("result_object(empty array) %s", str.c_str());
}
TEST_F(CMetaFormatterTestHelper,
ObjectWithEmptyArrayAndEmptyMapWithOtherParameters) {
// Arrange
SmartObject result_object;
SmartObject object;
std::map<std::string, CObjectSchemaItem::SMember> paramsMembersMap;
paramsMembersMap[S_FUNCTION_ID] = CObjectSchemaItem::SMember(
TEnumSchemaItem<FunctionIDTest::eType>::create(function_id_items_), true);
paramsMembersMap[S_MESSAGE_TYPE] = CObjectSchemaItem::SMember(
TEnumSchemaItem<MessageTypeTest::eType>::create(message_type_items_),
true);
paramsMembersMap[S_CORRELATION_ID] = CObjectSchemaItem::SMember(
TNumberSchemaItem<int>::create(TSchemaItemParameter<int>(0),
TSchemaItemParameter<int>(100),
TSchemaItemParameter<int>(55)),
true);
paramsMembersMap[S_PROTOCOL_VERSION] = CObjectSchemaItem::SMember(
TNumberSchemaItem<int>::create(TSchemaItemParameter<int>(1),
TSchemaItemParameter<int>(2)),
false);
paramsMembersMap[S_PROTOCOL_TYPE] =
CObjectSchemaItem::SMember(TNumberSchemaItem<int>::create(), false);
std::map<std::string, CObjectSchemaItem::SMember> schemaMembersMap;
schemaMembersMap["mandatory_emptyMap1"] = CObjectSchemaItem::SMember(
CObjectSchemaItem::create(
std::map<std::string, CObjectSchemaItem::SMember>()),
true);
schemaMembersMap["mandatory_emptyMap2"] = CObjectSchemaItem::SMember(
CObjectSchemaItem::create(
std::map<std::string, CObjectSchemaItem::SMember>()),
true);
schemaMembersMap["mandatory_emptyAray"] = CObjectSchemaItem::SMember(
CArraySchemaItem::create(TNumberSchemaItem<int>::create()), true);
schemaMembersMap["non_mandatory_Array"] = CObjectSchemaItem::SMember(
CArraySchemaItem::create(TNumberSchemaItem<int>::create(),
TSchemaItemParameter<size_t>(1),
TSchemaItemParameter<size_t>(2)),
false);
schemaMembersMap["mandatory_string"] = CObjectSchemaItem::SMember(
CStringSchemaItem::create(TSchemaItemParameter<size_t>(0),
TSchemaItemParameter<size_t>(500),
TSchemaItemParameter<std::string>("defValue")),
true);
schemaMembersMap["non_mandatory_string"] = CObjectSchemaItem::SMember(
CStringSchemaItem::create(
TSchemaItemParameter<size_t>(0),
TSchemaItemParameter<size_t>(500),
TSchemaItemParameter<std::string>("ignoredDefValue")),
false);
std::map<std::string, CObjectSchemaItem::SMember> rootMembersMap;
rootMembersMap[S_MSG_PARAMS] = CObjectSchemaItem::SMember(
CObjectSchemaItem::create(schemaMembersMap), true);
rootMembersMap[S_PARAMS] = CObjectSchemaItem::SMember(
CObjectSchemaItem::create(paramsMembersMap), true);
CSmartSchema schema = CSmartSchema(CObjectSchemaItem::create(rootMembersMap));
// Set object value
object[S_PARAMS][S_FUNCTION_ID] = 500;
object[S_PARAMS][S_PROTOCOL_VERSION] = 11;
object[S_PARAMS]["new_field"] = "100500 string";
object[S_MSG_PARAMS]["mandatory_emptyMap1"]["field1"] = 123;
object[S_MSG_PARAMS]["mandatory_emptyMap1"]["field2"][0] = 100;
object[S_MSG_PARAMS]["mandatory_emptyMap1"]["field2"][1] = 200;
object[S_MSG_PARAMS]["non_mandatory_Array"][0] = 100;
object[S_MSG_PARAMS]["non_mandatory_Array"][1] = 200;
object[S_MSG_PARAMS]["non_mandatory_Array"][2] = 300;
object[S_MSG_PARAMS]["non_mandatory_string"] = "some string";
CMetaFormatter::CreateObjectByPattern(object, schema, result_object);
// Uncomment code to print object in console
// std::string str;
// AnyObjectToJsonString(object, str);
// printf("object %s", str.c_str());
// AnyObjectToJsonString(result_object, str);
// printf("result_object %s", str.c_str());
// Assert
EXPECT_EQ(500, result_object[S_PARAMS][S_FUNCTION_ID].asInt());
EXPECT_EQ(-1, result_object[S_PARAMS][S_MESSAGE_TYPE].asInt());
EXPECT_EQ(55, result_object[S_PARAMS][S_CORRELATION_ID].asInt());
EXPECT_EQ(11u, result_object[S_PARAMS][S_PROTOCOL_VERSION].asUInt());
EXPECT_EQ(SmartType_Map,
result_object[S_MSG_PARAMS]["mandatory_emptyMap1"].getType());
EXPECT_EQ(0u, result_object[S_MSG_PARAMS]["mandatory_emptyMap1"].length());
EXPECT_EQ(SmartType_Map,
result_object[S_MSG_PARAMS]["mandatory_emptyMap2"].getType());
EXPECT_EQ(0u, result_object[S_MSG_PARAMS]["mandatory_emptyMap2"].length());
EXPECT_EQ(SmartType_Array,
result_object[S_MSG_PARAMS]["mandatory_emptyAray"].getType());
EXPECT_EQ(0u, result_object[S_MSG_PARAMS]["mandatory_emptyAray"].length());
EXPECT_EQ(100, result_object[S_MSG_PARAMS]["non_mandatory_Array"][0].asInt());
EXPECT_EQ(200, result_object[S_MSG_PARAMS]["non_mandatory_Array"][1].asInt());
EXPECT_EQ(300u,
result_object[S_MSG_PARAMS]["non_mandatory_Array"][2].asUInt());
EXPECT_EQ(std::string("defValue"),
result_object[S_MSG_PARAMS]["mandatory_string"].asString());
EXPECT_EQ(std::string("some string"),
result_object[S_MSG_PARAMS]["non_mandatory_string"].asString());
}
} // namespace formatters
} // namespace components
} // namespace test
| [
"[email protected]"
] | |
2f8c43ab1ac227913ec50732283c0ade03e26899 | bfc88535fa1495c64672f048a5559e8bb6de1ae1 | /UVa/12015.cpp | c506c88fd8e1ab8510057b9bc3225ef9d06feec1 | [] | no_license | famus2310/CP | 59839ffe23cf74019e2f655f49af224390846776 | d8a77572830fb3927de92f1e913ee729d04865e1 | refs/heads/master | 2021-07-05T00:23:31.113026 | 2020-08-07T22:28:24 | 2020-08-07T22:28:24 | 144,426,214 | 1 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 756 | cpp | #include <bits/stdc++.h>
using namespace std;
typedef long long LL;
#define pb push_back
#define debug(x) cout << x << endl
#define fastio ios_base::sync_with_stdio(0), cin.tie(0)
#define PI acos(-1)
#define all(c) c.begin(), c.end()
const int MOD = 1e9 + 7;
const int INF = 1e9;
const LL INF64 = 1e18;
const int N = 1e5 + 5;
struct node{
int ref;
string web;
};
node arr[15];
int main() {
int t;
scanf("%d", &t);
for (int tc = 1; tc <= t; tc++) {
string s;
int val;
int mx = -1;
for (int i = 0; i < 10; i++) {
cin >> s >> val;
arr[i].ref = val;
arr[i].web = s;
mx = max(mx, val);
}
printf("Case #%d:\n", tc);
for (int i = 0; i < 10; i++) {
if (arr[i].ref == mx)
cout << arr[i].web << endl;
}
}
return 0;
}
| [
"[email protected]"
] | |
42c054d9b0cb68407d11de2a79d2b0d008a74b54 | a3dc876f68cbe6a28e764c74b50ba058b83ca0e2 | /projectC++/include/Thread.h | 7c3c044dc7075851eb0a5b0983796ab9c2bed8b8 | [] | no_license | Devilsider/Tencent_Cloud_Backup | 706621d77a29773b3f28ef390ba306d6ed0f1a36 | f04f6f0eba34123bb988fb68008bbfe7ea5bca52 | refs/heads/master | 2020-05-24T14:37:44.915007 | 2019-06-29T07:30:39 | 2019-06-29T07:30:39 | 187,311,445 | 2 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 762 | h | ///
/// @file Thread.h
/// @author lemon([email protected])
/// @date 2019-05-04 09:49:30
///
#ifndef __WD_THREAD_H__
#define __WD_THREAD_H__
#include "Noncopyable.h"
#include <pthread.h>
#include <functional>
#include <string>
using namespace std;
namespace wd
{
extern __thread const char * threadName;
class Thread
: Noncopyable
{
public:
using ThreadCallback = std::function<void()>;
Thread(ThreadCallback && cb,const string & name = string())
:_pthid(0),
_cb(move(cb)),
_isRunning(false),
_name(name)
{}
void start();
void join();
~Thread();
private:
static void * threadFunc(void *);
private:
pthread_t _pthid;
ThreadCallback _cb;
bool _isRunning;
string _name;
};
}//end of namespace wd
#endif
| [
"[email protected]"
] | |
54ba7394269b93fd59d94ba9ac760f91dbb4422d | b83c2b56baddd30e9585fc9bd86c354b4f65af03 | /6120_2020/src/main/include/ctre/Phoenix.h | 0060be72f4706e715cfe0bfa1c39f1dc3a8cc404 | [] | no_license | ShaneSopel/FRC2020 | ca0ff5743c3176efa93f305c852fc7a78022c82e | 7a443e2a39da801313c1174fc19bc5e43bc6cd7c | refs/heads/master | 2020-12-10T03:03:13.117356 | 2020-02-26T22:28:07 | 2020-02-26T22:28:07 | 233,488,301 | 2 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 1,730 | h | #pragma once
#ifndef Phoenix_No_WPI
#define Phoenix_WPI
#include "ctre/phoenix/CANifier.h"
#include "ctre/phoenix/ErrorCode.h"
#include "ctre/phoenix/paramEnum.h"
#include "ctre/phoenix/HsvToRgb.h"
#include "ctre/phoenix/LinearInterpolation.h"
#include "ctre/phoenix/motion/BufferedTrajectoryPointStream.h"
#include "ctre/phoenix/motion/MotionProfileStatus.h"
#include "ctre/phoenix/motion/TrajectoryPoint.h"
#include "ctre/phoenix/motorcontrol/can/TalonSRX.h"
#include "ctre/phoenix/motorcontrol/can/VictorSPX.h"
#include "ctre/phoenix/motorcontrol/DemandType.h"
#include "ctre/phoenix/motorcontrol/Faults.h"
#include "ctre/phoenix/motorcontrol/FollowerType.h"
#include "ctre/phoenix/motorcontrol/IMotorController.h"
#include "ctre/phoenix/motorcontrol/IMotorControllerEnhanced.h"
#include "ctre/phoenix/motorcontrol/InvertType.h"
#include "ctre/phoenix/motorcontrol/SensorCollection.h"
#include "ctre/phoenix/sensors/PigeonIMU.h"
#include "ctre/phoenix/signals/MovingAverage.h"
#include "ctre/phoenix/tasking/Schedulers/ConcurrentScheduler.h"
#include "ctre/phoenix/tasking/ILoopable.h"
#include "ctre/phoenix/tasking/IProcessable.h"
#include "ctre/phoenix/Utilities.h"
#ifdef Phoenix_WPI
#include "ctre/phoenix/motorcontrol/can/WPI_TalonSRX.h"
#include "ctre/phoenix/motorcontrol/can/WPI_VictorSPX.h"
#include "ctre/phoenix/tasking/ButtonMonitor.h"
#endif
using namespace ctre;
using namespace ctre::phoenix;
using namespace ctre::phoenix::motion;
using namespace ctre::phoenix::motorcontrol;
using namespace ctre::phoenix::motorcontrol::can;
using namespace ctre::phoenix::sensors;
using namespace ctre::phoenix::signals;
using namespace ctre::phoenix::tasking;
using namespace ctre::phoenix::tasking::schedulers;
#endif | [
"[email protected]"
] | |
8b1671893e8e65f166899b423c657e3e1465f0c9 | dc1b29c1041ee98d882751a53c49c1044ea272eb | /src/wallet/message_store.h | 57a2fdba907dfc08a01fccd894a2b563b0831356 | [
"BSD-3-Clause"
] | permissive | XtendCash/XtendCash | ed3bcf5fd52eff151821f33f63b47de55792f2ff | f82de0b9e0f0ba4893713dc5021ff87de9943212 | refs/heads/master | 2020-05-05T00:16:17.280894 | 2019-09-15T03:03:13 | 2019-09-15T03:03:13 | 179,569,723 | 3 | 3 | NOASSERTION | 2019-08-25T23:41:29 | 2019-04-04T20:10:26 | C++ | UTF-8 | C++ | false | false | 16,308 | h | // Copyright (c) 2018, The Monero Project
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification, are
// permitted provided that the following conditions are met:
//
// 1. Redistributions of source code must retain the above copyright notice, this list of
// conditions and the following disclaimer.
//
// 2. Redistributions in binary form must reproduce the above copyright notice, this list
// of conditions and the following disclaimer in the documentation and/or other
// materials provided with the distribution.
//
// 3. Neither the name of the copyright holder nor the names of its contributors may be
// used to endorse or promote products derived from this software without specific
// prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
// MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL
// THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
// STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF
// THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#pragma once
#include <cstdlib>
#include <string>
#include <vector>
#include "crypto/hash.h"
#include <boost/serialization/vector.hpp>
#include <boost/program_options/variables_map.hpp>
#include <boost/program_options/options_description.hpp>
#include <boost/optional/optional.hpp>
#include "serialization/serialization.h"
#include "cryptonote_basic/cryptonote_boost_serialization.h"
#include "cryptonote_basic/account_boost_serialization.h"
#include "cryptonote_basic/cryptonote_basic.h"
#include "common/i18n.h"
#include "common/command_line.h"
#include "wipeable_string.h"
#include "message_transporter.h"
#undef XTEND_DEFAULT_LOG_CATEGORY
#define XTEND_DEFAULT_LOG_CATEGORY "wallet.mms"
#define AUTO_CONFIG_TOKEN_BYTES 4
#define AUTO_CONFIG_TOKEN_PREFIX "mms"
namespace mms
{
enum class message_type
{
key_set,
additional_key_set,
multisig_sync_data,
partially_signed_tx,
fully_signed_tx,
note,
signer_config,
auto_config_data
};
enum class message_direction
{
in,
out
};
enum class message_state
{
ready_to_send,
sent,
waiting,
processed,
cancelled
};
enum class message_processing
{
prepare_multisig,
make_multisig,
exchange_multisig_keys,
create_sync_data,
process_sync_data,
sign_tx,
send_tx,
submit_tx,
process_signer_config,
process_auto_config_data
};
struct message
{
uint32_t id;
message_type type;
message_direction direction;
std::string content;
uint64_t created;
uint64_t modified;
uint64_t sent;
uint32_t signer_index;
crypto::hash hash;
message_state state;
uint32_t wallet_height;
uint32_t round;
uint32_t signature_count;
std::string transport_id;
};
// "wallet_height" (for lack of a short name that would describe what it is about)
// is the number of transfers present in the wallet at the time of message
// construction; used to coordinate generation of sync info (which depends
// on the content of the wallet at time of generation)
struct authorized_signer
{
std::string label;
std::string transport_address;
bool monero_address_known;
cryptonote::account_public_address monero_address;
bool me;
uint32_t index;
std::string auto_config_token;
crypto::public_key auto_config_public_key;
crypto::secret_key auto_config_secret_key;
std::string auto_config_transport_address;
bool auto_config_running;
authorized_signer()
{
monero_address_known = false;
memset(&monero_address, 0, sizeof(cryptonote::account_public_address));
me = false;
index = 0;
auto_config_public_key = crypto::null_pkey;
auto_config_secret_key = crypto::null_skey;
auto_config_running = false;
};
};
struct processing_data
{
message_processing processing;
std::vector<uint32_t> message_ids;
uint32_t receiving_signer_index = 0;
};
struct file_transport_message
{
cryptonote::account_public_address sender_address;
crypto::chacha_iv iv;
crypto::public_key encryption_public_key;
message internal_message;
};
struct auto_config_data
{
std::string label;
std::string transport_address;
cryptonote::account_public_address monero_address;
};
// Overal .mms file structure, with the "message_store" object serialized to and
// encrypted in "encrypted_data"
struct file_data
{
std::string magic_string;
uint32_t file_version;
crypto::chacha_iv iv;
std::string encrypted_data;
};
// The following struct provides info about the current state of a "wallet2" object
// at the time of a "message_store" method call that those methods need. See on the
// one hand a first parameter of this type for several of those methods, and on the
// other hand the method "wallet2::get_multisig_wallet_state" which clients like the
// CLI wallet can use to get that info.
//
// Note that in the case of a wallet that is already multisig "address" is NOT the
// multisig address, but the "original" wallet address at creation time. Likewise
// "view_secret_key" is the original view secret key then.
//
// This struct definition is here and not in "wallet2.h" to avoid circular imports.
struct multisig_wallet_state
{
cryptonote::account_public_address address;
cryptonote::network_type nettype;
crypto::secret_key view_secret_key;
bool multisig;
bool multisig_is_ready;
bool has_multisig_partial_key_images;
uint32_t multisig_rounds_passed;
size_t num_transfer_details;
std::string mms_file;
};
class message_store
{
public:
message_store();
// Initialize and start to use the MMS, set the first signer, this wallet itself
// Filename, if not null and not empty, is used to create the ".mms" file
// reset it if already used, with deletion of all signers and messages
void init(const multisig_wallet_state &state, const std::string &own_label,
const std::string &own_transport_address, uint32_t num_authorized_signers, uint32_t num_required_signers);
void set_active(bool active) { m_active = active; };
void set_auto_send(bool auto_send) { m_auto_send = auto_send; };
void set_options(const boost::program_options::variables_map& vm);
void set_options(const std::string &bitmessage_address, const epee::wipeable_string &bitmessage_login);
bool get_active() const { return m_active; };
bool get_auto_send() const { return m_auto_send; };
uint32_t get_num_required_signers() const { return m_num_required_signers; };
uint32_t get_num_authorized_signers() const { return m_num_authorized_signers; };
void set_signer(const multisig_wallet_state &state,
uint32_t index,
const boost::optional<std::string> &label,
const boost::optional<std::string> &transport_address,
const boost::optional<cryptonote::account_public_address> monero_address);
const authorized_signer &get_signer(uint32_t index) const;
bool get_signer_index_by_monero_address(const cryptonote::account_public_address &monero_address, uint32_t &index) const;
bool get_signer_index_by_label(const std::string label, uint32_t &index) const;
const std::vector<authorized_signer> &get_all_signers() const { return m_signers; };
bool signer_config_complete() const;
bool signer_labels_complete() const;
void get_signer_config(std::string &signer_config);
void unpack_signer_config(const multisig_wallet_state &state, const std::string &signer_config,
std::vector<authorized_signer> &signers);
void process_signer_config(const multisig_wallet_state &state, const std::string &signer_config);
void start_auto_config(const multisig_wallet_state &state);
bool check_auto_config_token(const std::string &raw_token,
std::string &adjusted_token) const;
size_t add_auto_config_data_message(const multisig_wallet_state &state,
const std::string &auto_config_token);
void process_auto_config_data_message(uint32_t id);
void stop_auto_config();
// Process data just created by "me" i.e. the own local wallet, e.g. as the result of a "prepare_multisig" command
// Creates the resulting messages to the right signers
void process_wallet_created_data(const multisig_wallet_state &state, message_type type, const std::string &content);
// Go through all the messages, look at the "ready to process" ones, and check whether any single one
// or any group of them can be processed, because they are processable as single messages (like a tx
// that is fully signed and thus ready for submit to the net) or because they form a complete group
// (e.g. key sets from all authorized signers to make the wallet multisig). If there are multiple
// candidates, e.g. in 2/3 multisig sending to one OR the other signer to sign, there will be more
// than 1 element in 'data' for the user to choose. If nothing is ready "false" is returned.
// The method mostly ignores the order in which the messages were received because messages may be delayed
// (e.g. sync data from a signer arrives AFTER a transaction to submit) or because message time stamps
// may be wrong so it's not possible to order them reliably.
// Messages also may be ready by themselves but the wallet not yet ready for them (e.g. sync data already
// arriving when the wallet is not yet multisig because key sets were delayed or were lost altogether.)
// If nothing is ready 'wait_reason' may contain further info about the reason why.
bool get_processable_messages(const multisig_wallet_state &state,
bool force_sync,
std::vector<processing_data> &data_list,
std::string &wait_reason);
void set_messages_processed(const processing_data &data);
size_t add_message(const multisig_wallet_state &state,
uint32_t signer_index, message_type type, message_direction direction,
const std::string &content);
const std::vector<message> &get_all_messages() const { return m_messages; };
bool get_message_by_id(uint32_t id, message &m) const;
message get_message_by_id(uint32_t id) const;
void set_message_processed_or_sent(uint32_t id);
void delete_message(uint32_t id);
void delete_all_messages();
void get_sanitized_message_text(const message &m, std::string &sanitized_text) const;
void send_message(const multisig_wallet_state &state, uint32_t id);
bool check_for_messages(const multisig_wallet_state &state, std::vector<message> &messages);
void stop() { m_run.store(false, std::memory_order_relaxed); m_transporter.stop(); }
void write_to_file(const multisig_wallet_state &state, const std::string &filename);
void read_from_file(const multisig_wallet_state &state, const std::string &filename);
template <class t_archive>
inline void serialize(t_archive &a, const unsigned int ver)
{
a & m_active;
a & m_num_authorized_signers;
a & m_nettype;
a & m_num_required_signers;
a & m_signers;
a & m_messages;
a & m_next_message_id;
a & m_auto_send;
}
static const char* message_type_to_string(message_type type);
static const char* message_direction_to_string(message_direction direction);
static const char* message_state_to_string(message_state state);
std::string signer_to_string(const authorized_signer &signer, uint32_t max_width);
static const char *tr(const char *str) { return i18n_translate(str, "tools::mms"); }
static void init_options(boost::program_options::options_description& desc_params);
private:
bool m_active;
uint32_t m_num_authorized_signers;
uint32_t m_num_required_signers;
bool m_auto_send;
cryptonote::network_type m_nettype;
std::vector<authorized_signer> m_signers;
std::vector<message> m_messages;
uint32_t m_next_message_id;
std::string m_filename;
message_transporter m_transporter;
std::atomic<bool> m_run;
bool get_message_index_by_id(uint32_t id, size_t &index) const;
size_t get_message_index_by_id(uint32_t id) const;
message& get_message_ref_by_id(uint32_t id);
bool any_message_of_type(message_type type, message_direction direction) const;
bool any_message_with_hash(const crypto::hash &hash) const;
size_t get_other_signers_id_count(const std::vector<uint32_t> &ids) const;
bool message_ids_complete(const std::vector<uint32_t> &ids) const;
void encrypt(crypto::public_key public_key, const std::string &plaintext,
std::string &ciphertext, crypto::public_key &encryption_public_key, crypto::chacha_iv &iv);
void decrypt(const std::string &ciphertext, const crypto::public_key &encryption_public_key, const crypto::chacha_iv &iv,
const crypto::secret_key &view_secret_key, std::string &plaintext);
std::string create_auto_config_token();
void setup_signer_for_auto_config(uint32_t index, const std::string token, bool receiving);
void delete_transport_message(uint32_t id);
std::string account_address_to_string(const cryptonote::account_public_address &account_address) const;
void save(const multisig_wallet_state &state);
};
}
BOOST_CLASS_VERSION(mms::file_data, 0)
BOOST_CLASS_VERSION(mms::message_store, 0)
BOOST_CLASS_VERSION(mms::message, 0)
BOOST_CLASS_VERSION(mms::file_transport_message, 0)
BOOST_CLASS_VERSION(mms::authorized_signer, 1)
BOOST_CLASS_VERSION(mms::auto_config_data, 0)
namespace boost
{
namespace serialization
{
template <class Archive>
inline void serialize(Archive &a, mms::file_data &x, const boost::serialization::version_type ver)
{
a & x.magic_string;
a & x.file_version;
a & x.iv;
a & x.encrypted_data;
}
template <class Archive>
inline void serialize(Archive &a, mms::message &x, const boost::serialization::version_type ver)
{
a & x.id;
a & x.type;
a & x.direction;
a & x.content;
a & x.created;
a & x.modified;
a & x.sent;
a & x.signer_index;
a & x.hash;
a & x.state;
a & x.wallet_height;
a & x.round;
a & x.signature_count;
a & x.transport_id;
}
template <class Archive>
inline void serialize(Archive &a, mms::authorized_signer &x, const boost::serialization::version_type ver)
{
a & x.label;
a & x.transport_address;
a & x.monero_address_known;
a & x.monero_address;
a & x.me;
a & x.index;
if (ver < 1)
{
return;
}
a & x.auto_config_token;
a & x.auto_config_public_key;
a & x.auto_config_secret_key;
a & x.auto_config_transport_address;
a & x.auto_config_running;
}
template <class Archive>
inline void serialize(Archive &a, mms::auto_config_data &x, const boost::serialization::version_type ver)
{
a & x.label;
a & x.transport_address;
a & x.monero_address;
}
template <class Archive>
inline void serialize(Archive &a, mms::file_transport_message &x, const boost::serialization::version_type ver)
{
a & x.sender_address;
a & x.iv;
a & x.encryption_public_key;
a & x.internal_message;
}
template <class Archive>
inline void serialize(Archive &a, crypto::chacha_iv &x, const boost::serialization::version_type ver)
{
a & x.data;
}
}
}
| [
"[email protected]"
] | |
1ebacd00d3eaeb25b5457073b7aced08ecdbef96 | c8b749ef111fc87aa24a61c47f743944baec394d | /src/utils/doctest/doctest_runner.cpp | 9c78687ee3c97ee4898e47c96034020b5e0cf426 | [
"MIT"
] | permissive | albertydcy/game | ac9a75b0afecea669c9808e435f373f08dd6ba4b | 08d9f2871bfd5c757d541064b77d38474123592a | refs/heads/master | 2023-06-19T23:00:48.722278 | 2020-12-27T10:58:06 | 2020-12-27T10:58:06 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 60 | cpp | #define DOCTEST_CONFIG_IMPLEMENT
#include "doctest_proxy.h"
| [
"[email protected]"
] | |
38244c5bb2057656d5b965c62c4aeb6ecf1dc8cc | e9749d4e271546fbcdd261edd538d99eb3f7fff8 | /QT/balls/mover.cpp | fcdac40f301646cc7ece694aa7bc4c771945a4f3 | [] | no_license | Xambey/something | 90e4c4823cf553f9c8acc190313fec991b22b44d | 0dc0ecd163e1fc662caea16f7363e166b6687adf | refs/heads/master | 2021-01-10T14:40:09.253969 | 2016-05-09T08:57:50 | 2016-05-09T08:57:50 | 52,145,859 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 514 | cpp | #include "mover.h"
#include "qdebug.h"
Mover::Mover(BallLine* target, float in, float to)
{
this->target = target;
this->in = in;
this->to = to;
invert = false;
}
void Mover::onTick(int)
{
qDebug() << "d'";
if(invert)
{
if(target->angine <= in)
invert = false;
else
target->angine -= 1;
}
else
{
if(target->angine >= to)
invert = true;
else
target->angine += 1;
}
target->update();
}
| [
"[email protected]"
] | |
28133673f0bf25e9fbd09ff04232ac9f9ecb0f0f | 58e34786646a3a46fa8281311cd359361eceeddf | /quanlyNv.cpp | c9d3e951ad2cfde7e23d18852d4e894c1614f996 | [] | no_license | bachlongvu2882001/lithuyet | 0c7412c7642a519118a94d0cf1e0d7ad2290be31 | 6166719c4ca3a9242b88d75017219f18f154a0e1 | refs/heads/master | 2023-02-20T08:21:44.676106 | 2021-01-25T13:52:44 | 2021-01-25T13:52:44 | 272,203,797 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 780 | cpp | #include<iostream>
#include<string>
using namespace std;
class SV{
public:
string lop;
string ht;
void Nhap();
void Xuat();
};
void SV::Nhap(){
cout<<"\nNhap ho ten sinh vien = ";
cin.ignore(1);
getline(cin,ht);
cin.ignore(1);
cout<<"\nNhap lop = ";
getline(cin,lop);
}
void SV::Xuat(){
cout<<"\nTen sinh vien la = "<<ht;
cout<<"\nLop = "<<lop;
}
class SVTC:public SV{
public:
float hocphi;
void Nhap();
void Xuat();
};
void SVTC::Nhap(){
SV::Nhap();
cout<<"\nMuc hoc phi = ";
cin>>hocphi;
}
//Xuat hoc phi
void SVTC::Xuat(){
SV::Xuat();
cout<<"\nHoc phi = "<<hocphi;
}
int main(){
SVTC a;
a.Nhap();
a.Xuat();
system("pause");
return 0;
} | [
"[email protected]"
] | |
91665b67314433e54f06dd74cdf6c3d6b9d7eea7 | 11e97f87deb25babb4a32c80941e7ff4e476c92a | /REC/HRD_220A/Vision/CamUnit_.h | c1da20839220131ea0729e08ecac385c92fc6035 | [] | no_license | xhyangxianjun/Builder6-program | b9d03d98658db5a5a8cf1586210a373bc391dc48 | a12d811d7a5fa3dba6d3e8c05989a41cb89783de | refs/heads/master | 2022-04-03T00:25:47.274355 | 2019-09-19T08:26:56 | 2019-09-19T08:26:56 | null | 0 | 0 | null | null | null | null | UHC | C++ | false | false | 8,787 | h | //---------------------------------------------------------------------------
#ifndef CamUnitH
#define CamUnitH
//#include <Sytems.hpp>
#include <Dialogs.hpp>
#include <ValEdit.hpp>
#include "BaseDefine.h"
#include "BaseClass.h"
//---------------------------------------------------------------------------
enum ETrgMode {
tmSw = 0 ,
tmHw = 1 ,
tmLive = 2 ,
};
enum ECamType {
ctNone = 0 ,
ctImi = 1
};
typedef void (__closure * CamCallbackFunc)(int);
class CCam
{
private:
static int m_iMaxCam ;
public:
static int m_iMaxImi ;
static CCam** m_apCam ;
static int InitCam();
static bool CloseCam();
//상속용.
struct TCamUserPara {
TCamUserPara(){
};
virtual ~TCamUserPara(){
};
};
protected:
int m_iCamNo ;
unsigned char * m_pImgBuf ;
int m_iImgWidth ;
int m_iImgHeight ;
int m_iImgBit ;
double m_dGrabOnTime ;
double m_dGrabTime ;
CamCallbackFunc m_pCallbackFunc ;
ETrgMode m_eTrgMode ;
int GetCamNo(){return m_iCamNo ;}
public:
CCam::CCam(void){
static int iNo = 0 ;
m_iCamNo = iNo;
iNo++;
m_iMaxCam = iNo ;
}
virtual CCam::~CCam(void){}
bool GetTrgMode(){return m_eTrgMode;}
//상속 세트 홍홍홍....
virtual ECamType GetType ( )=0;
virtual bool GetImg (unsigned char *& _pImg, int &_iWidth , int & _iHeight , int & _iBitCnt)=0;
virtual bool Init ( )=0;
virtual bool Close ( )=0;
virtual bool Grab ( )=0;
virtual bool SetTrgMode (ETrgMode _iMode)=0;
virtual void SetGrabFunc (CamCallbackFunc _pFunc)=0;
virtual bool ApplyUserPara (TCamUserPara * _pCamUserPara)=0;
virtual void LoadPara (bool _bLoad , String _sPath )=0;
virtual void UpdateUserPara (bool _bToTable , TValueListEditor * _vePara,TCamUserPara * _pCamUserPara)=0;
virtual void LoadSaveUserPara(bool _bLoad , String _sFilePath,TCamUserPara * _pCamUserPara)=0;
virtual double GetGrabTime ( )=0;
};
#include "ApiImport.h"
class CImi:public CCam //Imi 카메라용용
{
public:
static int m_iMaxCam ;
static bool InitImi();
static bool CloseImi();
private:
static bool m_bDllLoaded ;
int m_iImiCamNo ;
public:
struct TPara { //한번 로딩 하면 바뀔일이 없는 파라.
int iPhysicalNo ;
//이것들은 카메라 스탑 시키고 바꿀수 있다.
int iVideoFormat ;
int iVideoMode ;
int iFrameRate ;
};
/*
struct TUserPara : public CamUserPara{
int iBrightness ;//
int iSharpness ;//
int iGamma ;//
int iExposure ;
int iShutter ;//
int iGain ;//
int iPan ;
int iTilt ;
};
*/
struct TUserPara : public TCamUserPara{
CLinkedList<CValue2*> List ;
DECLARATION(int,iBrightness);
DECLARATION(int,iSharpness );
DECLARATION(int,iGamma );
int iExposure ;//DECLARATION(int,iExposure );
DECLARATION(int,iShutter );
DECLARATION(int,iGain );
int iPan ;//DECLARATION(int,iPan );
int iTilt ;//DECLARATION(int,iTilt );
TUserPara(){
PROPERTY(List , int,iBrightness,"Brightness" , "Brightness");ViBrightness.SetMinMax(0,1023); //0~1023
PROPERTY(List , int,iSharpness ,"Sharpness " , "Sharpness ");ViSharpness .SetMinMax(0,1016); //0~1016
PROPERTY(List , int,iGamma ,"Gamma " , "Gamma ");ViGamma .SetMinMax(4,25 ); //4~25
//PROPERTY(List , int,iExposure ,"Exposure " , "Exposure ");ViExposure .SetMinMax(0,100 ); //0~100
PROPERTY(List , int,iShutter ,"Shutter " , "Shutter ");ViShutter .SetMinMax(1,2000); //1~2000
PROPERTY(List , int,iGain ,"Gain " , "Gain ");ViGain .SetMinMax(0,511 ); //0~511
//PROPERTY(List , int,iPan ,"Pan " , "Pan ");ViPan .SetMinMax(0,1600); //0~1600
//PROPERTY(List , int,iTilt ,"Tilt " , "Tilt ");ViTilt .SetMinMax(0,1230); //0~1230
SetDefault();
}
void SetDefault(){
iBrightness = 0 ;//0~1023
iSharpness = 0 ;//0~1016
iGamma = 4 ;//4~25
iExposure = 0 ;//0~100
iShutter = 400 ;//1~2000
iGain = 0 ;//0~511
iPan = 0 ;//0~1600
iTilt = 0 ;//0~1230
}
virtual ~TUserPara(){
}
};
protected:
TPara Para ;
TUserPara SetUserPara ; //마지막으로 세팅된 유저파라.
unsigned char * m_pImgRGBBuf ;
//멤버변수를 넣지 못하게 되어 있어 Static 선언 카메라가 여러개이고 한번에 그랩하여 들어오면
//병목 있을수 있네... pContext가 imi 포인터라서 데이터 바뀔일은 없음.
static int CALLBACK ImiCallback(PVOID pContext, double SampleTime, BYTE * pBuffer, long lBufferSize);
void SetBuffer (unsigned char * pBuffer, int lBufferSize);
public:
CImi(void);
~CImi(void);
//상속세트 홍홍홍.
ECamType GetType ( );
bool GetImg (unsigned char *& _pImg, int &_iWidth , int & _iHeight , int & _iBitCnt);
bool Init ( );
bool Close ( );
bool Grab ( );
bool SetTrgMode (ETrgMode _iMode);
void SetGrabFunc (CamCallbackFunc _pFunc);
bool ApplyUserPara (TCamUserPara * _pCamUserPara);
void LoadPara (bool _bLoad , String _sPath );
void UpdateUserPara (bool _bToTable , TValueListEditor * _vePara,TCamUserPara * _pCamUserPara);
void LoadSaveUserPara(bool _bLoad , String _sFilePath,TCamUserPara * _pCamUserPara);
double GetGrabTime ( );
};
#endif
//요것들 4개는 일단 쓰지 말자...
//void SetBrightness(int _iVal );
//void SetSharpness (int _iVal );
//void SetGain (int _iVal );
//void SetShutter (int _iVal );
/*
void CImi::SetExposure (int _iTime )
{
IMC_FEATURE_PROPERTY FeatureProp;
bool bRet ;
memset(&FeatureProp, 0, sizeof(IMC_FEATURE_PROPERTY));
FeatureProp.nValue = _iTime ;
bRet = (ImCamSetFeatureValue(Para.iPhysicalNo, IMC_FEATURE_EXPOSURE , &FeatureProp) == IMC_SUCCESS) ;
}
void CImi::SetBrightness(int _iVal )
{
IMC_FEATURE_PROPERTY FeatureProp;
bool bRet ;
memset(&FeatureProp, 0, sizeof(IMC_FEATURE_PROPERTY));
FeatureProp.nValue = _iVal ;
bRet = (ImCamSetFeatureValue(Para.iPhysicalNo, IMC_FEATURE_BRIGHTNESS , &FeatureProp) == IMC_SUCCESS) ;
}
void CImi::SetSharpness (int _iVal )
{
IMC_FEATURE_PROPERTY FeatureProp;
bool bRet ;
memset(&FeatureProp, 0, sizeof(IMC_FEATURE_PROPERTY));
FeatureProp.nValue = _iVal ;
bRet = (ImCamSetFeatureValue(Para.iPhysicalNo, IMC_FEATURE_SHARPNESS , &FeatureProp) == IMC_SUCCESS) ;
}
void CImi::SetGain (int _iVal )
{
IMC_FEATURE_PROPERTY FeatureProp;
bool bRet ;
memset(&FeatureProp, 0, sizeof(IMC_FEATURE_PROPERTY));
FeatureProp.nValue = _iVal ;
bRet = (ImCamSetFeatureValue(Para.iPhysicalNo, IMC_FEATURE_GAIN , &FeatureProp) == IMC_SUCCESS) ;
}
void CImi::SetShutter (int _iVal )
{
IMC_FEATURE_PROPERTY FeatureProp;
bool bRet ;
memset(&FeatureProp, 0, sizeof(IMC_FEATURE_PROPERTY));
FeatureProp.nValue = _iVal ;
bRet = (ImCamSetFeatureValue(Para.iPhysicalNo, IMC_FEATURE_SHUTTER , &FeatureProp) == IMC_SUCCESS) ;
}
*/
| [
"[email protected]"
] | |
73849118cf30d46b1d686e607aa4cc6801c9370e | 40ffa6a10249a2d112e1ced4c4e08d3318301e17 | /TP2/GroupImage.cpp | 2c078eb925a1471077239efb376f0910713fb77b | [] | no_license | julienlegault96/inf1010 | 5bce9504557d812ba38d12b36f20e3c7c3eef97d | 2be2ee15b0cfdc8da57378c05b39e8024fe25e74 | refs/heads/master | 2021-03-24T13:52:52.088043 | 2017-12-19T21:30:06 | 2017-12-19T21:30:06 | 108,063,538 | 0 | 0 | null | null | null | null | ISO-8859-1 | C++ | false | false | 6,167 | cpp | /**************************************************************************
* Fichier: GroupImage.cpp
* Auteur : Arnaud Lebrun et Julien Legault
* Date : 13 sept 2017
* Mise a jour : 02 oct 2017
* Description : Implémentation de la classe GroupImage
****************************************************************************/
#include "GroupImage.h"
#include <iostream>
#include <string>
using namespace std;
/****************************************************************************
* Fonction: GroupImage
* Description: Constructeur par defaut
* Paramètres: -aucun
* Retour: aucun
****************************************************************************/
GroupImage::GroupImage():type_("par defaut") {}
/****************************************************************************
* Fonction: GroupImage
* Description: Destructeur
* Paramètres: -aucun
* Retour: aucun
***************************************************************************/
GroupImage::~GroupImage() {
// Mettre ce destructeur occasionne des problèmes mémoire
//for (unsigned int i = 0; i < Images_.size(); i++) {
// delete Images_[i];
//}
}
/****************************************************************************
* Fonction: GroupImage
* Description: modifierType
* Paramètres: - string type: valeur de type_ (IN)
* Retour: aucun
****************************************************************************/
void GroupImage::modifierType(const string & type) {
type_ = type;
}
/****************************************************************************
* Fonction: GroupImage
* Description: obtenirType
* Paramètres: - aucun
* Retour: (string) la valeur de type_
****************************************************************************/
string GroupImage::obtenirType() const{
return type_;
}
/****************************************************************************
* Fonction: GroupImage
* Description: ajouterImage
* Paramètres: - Image image
* Retour: aucun
****************************************************************************/
void GroupImage::ajouterImage(Image* image) {
bool NomPresent = false;
for (unsigned int i = 0; i < Images_.size(); i++) {
if (image->obtenirNomImage() == Images_[i]->obtenirNomImage()) {
NomPresent = true;
}
}
if (!NomPresent) {
Images_.push_back(image);
}
cout << "L'image " << Images_[Images_.size() - 1 ]->obtenirNomImage() << " a bien ete ajoutee. " << endl ;
}
/****************************************************************************
* Fonction: GroupImage
* Description: retirerImage
* Paramètres: -string : nomImage
* Retour: aucun
****************************************************************************/
void GroupImage::retirerImage(const string & nomImage)
{
for (unsigned int i = 0; i < Images_.size(); i++)
{
if ( (*Images_[i]) == nomImage)
{
for (unsigned int j = i; j < Images_.size() - 1; j++) {
Images_[j] = Images_[j + 1];
}
cout << "L'image " << nomImage << " a bien ete retiree." << endl;
Images_.pop_back();
}
}
}
/****************************************************************************
* Fonction: GroupImage
* Description: afficherImages
* Paramètres: -ostream : sortie
* Retour: aucun
****************************************************************************/
void GroupImage::afficherImages(ostream& sortie) const {
sortie << "*********************************************" << endl;
sortie << "Affichage des images du groupe : ";
sortie << obtenirType() << endl;
sortie << "*********************************************"<< endl;
for (unsigned int i = 0; i <Images_.size(); i++) {
sortie << *Images_[i];
sortie << "---------------------------------------------" << endl;
}
sortie << endl;
}
/****************************************************************************
* Fonction: GroupImage
* Description: obtenirImage
* Paramètres: -unsigned int : indiceImage
* Retour: Image*
****************************************************************************/
Image* GroupImage::obtenirImage(unsigned int indiceImage) const {
return Images_[indiceImage];
}
/****************************************************************************
* Fonction: GroupImage
* Description: doublerTailleImageEnLargeur
* Paramètres: -unsigned int : indiceImage
* Retour: aucun
****************************************************************************/
void GroupImage::doublerTailleImageEnLargeur(unsigned int indiceImage) {
(*Images_[indiceImage]).doublerTailleEnLargeur();
}
/****************************************************************************
* Fonction: GroupImage
* Description: doublerTailleImageEnHauteur
* Paramètres: -unsigned int : indiceImage
* Retour: aucun
****************************************************************************/
void GroupImage::doublerTailleImageEnHauteur(unsigned int indiceImage) {
(*Images_[indiceImage]).doublerTailleEnHauteur();
}
/****************************************************************************
* Fonction: GroupImage
* Description: operateur d'ajout d'images
* Paramètres: -classe Image : image
* Retour: GroupImage
****************************************************************************/
GroupImage & GroupImage::operator += ( Image &image){
Image* pointeur = ℑ
ajouterImage(pointeur);
return *this;
}
/****************************************************************************
* Fonction: GroupImage
* Description: operateur de retrait d'images
* Paramètres: -classe Image : image
* Retour: GroupImage
****************************************************************************/
GroupImage & GroupImage::operator -= (Image &image){
retirerImage(image.obtenirNomImage());
return *this;
}
/****************************************************************************
* Fonction: GroupImage
* Description: Affichage d'image
* Paramètres: -paramètre de sortie
- GroupImage: g
* Retour: paramètre en sortie
****************************************************************************/
ostream& operator << (ostream& sortie, const GroupImage& g){
g.afficherImages(sortie);
return sortie;
} | [
"[email protected]"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.