blob_id
stringlengths 40
40
| directory_id
stringlengths 40
40
| path
stringlengths 4
201
| content_id
stringlengths 40
40
| detected_licenses
listlengths 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
listlengths 1
1
| author
stringlengths 0
119
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
3e1d423a065171e1c2f30f5158c52c106dfa604d | 07e5e3fa89650cf77fe6ca279e8bea11d4a5e227 | /include/score.hpp | 225b72a5f56228f4c5cc74a96c5e0d29d6e4a84e | [] | no_license | jesyspa/4DGo | 812551684ea300604fba83a7c7a0cde25fcdebda | ead53397ac22d92e3b34f25b271179c1ac214153 | refs/heads/master | 2020-05-21T11:41:04.498798 | 2011-04-20T18:32:10 | 2011-04-20T18:32:10 | 1,462,530 | 7 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 205 | hpp | #ifndef FDGO_INCLUDE_SCORE_HPP
#define FDGO_INCLUDE_SCORE_HPP
namespace fdgo {
struct Score {
Score() : black(0), white(0), komi(0.5) {}
unsigned int black, white;
double komi;
};
}
#endif // Guard
| [
"[email protected]"
] | |
c197b869da4b0bc600c986df0b498c47f2c8cd4d | b4f1df8e273ba40f90ac96fdf30c6ec336942aad | /nodeevents.hpp | 3543667ea611b1aec77a317d5742c955d3753eee | [] | no_license | jastadj/stag | 471d8064052329d3455abdd264aca9a79c2f62f6 | eb175df0d797940cd097730af5f28617768560bf | refs/heads/master | 2021-07-18T03:32:46.246484 | 2017-10-26T21:28:19 | 2017-10-26T21:28:19 | 104,498,796 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 298 | hpp | #ifndef _H_NODE_EVENTS
#define _H_NODE_EVENTS
#include "node.hpp"
class NodeEvent: public NodeExecutable
{
private:
public:
NodeEvent();
~NodeEvent();
};
class NodeEventStart: public NodeEvent
{
private:
public:
NodeEventStart();
~NodeEventStart();
};
#endif // NODE_EVENTS
| [
"[email protected]"
] | |
8a9b3eb0e9680f2507c3a296c1b6a79708bdeaf5 | 6d9b1a3f3f46e3767ccaf972b925b4a9cc4862cd | /aa/m3.cpp | 7a03aef44ae8a9172cfe39c547d8ad5614d424f5 | [] | no_license | cool1314520dog/ACM | 011b78a7f3be9b458963ff0539582e08294c6523 | 554f20e834a39ab5a100e0b818f33547127ddc3c | refs/heads/master | 2021-01-25T08:54:41.347832 | 2013-08-25T09:03:19 | 2013-08-25T09:03:19 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,279 | cpp | #include<fstream>
#include<iostream>
#include"filec.h"
using namespace std;
file_op::file_op(string file_name) {
file_path = file_name;
off_set = 0;
details = "";
}
void file_op::back_to_beg() {
off_set = 0;
}
bool file_op::read_file() {
fstream f;
f.open(file_path.c_str(), ios::in);
if(f.bad()) {
cout << "read_file -- file open err" << endl;
return false;
}
f.seekg(off_set, ios::cur);
do {
f >> detalis;
} while (details == "" && !f.eof());
off_set = f.tellg();
if(off_set != -1) {
f.close();
return true;
}
f.close();
return false;
}
void file_op::write_file(string str) {
fstream f;
f.open(file_path.c_str(), ios::app|iios::out);
f << str;
f.close();
}
void file_op::update_file(string old_details, string new_details) {
fstream f, tmp;
f.open(file_path.c_str(), ios::in);
tmp.open("tmp", ios::app|ios::out);
while (!f.eof()) {
f >> details;
if(details == "")
continue;
if(details !=old_details) {
tmp << new_details << endl;
}
else
{
tmp << new_details << endl;
}
}
f.close();
tmp.close();
remove(file_path.c_str());
}
| [
"cooldog@cooldog-SVE14A16ECB.(none)"
] | cooldog@cooldog-SVE14A16ECB.(none) |
a9dc88612a2eefa26c5742d11bc0386ba4512e25 | 43dac644f15d2b05b7de36d16cefeb5638c4cf09 | /Server/GameServer/GameServer.h | 2623a23111ba07649d8ac7905b71e5a417af0166 | [
"MIT"
] | permissive | 724789975/FxLib | 2925470bd6ddad1025417a71b078b3e3299fd59c | 46e5af788d10a411a667b4b61fb3b88fe030b585 | refs/heads/master | 2022-07-09T23:33:22.297506 | 2022-06-29T19:36:11 | 2022-06-29T19:36:11 | 56,384,463 | 37 | 13 | MIT | 2017-12-19T04:11:42 | 2016-04-16T13:16:43 | C | UTF-8 | C++ | false | false | 397 | h | #ifndef __GameServer_H__
#define __GameServer_H__
#include <vector>
#include "singleton.h"
#include "ChatSession.h"
class GameServer : public TSingleton<GameServer>
{
public:
GameServer();
virtual ~GameServer();
//ChatSession& GetChatSession() { return m_oChatSession; }
private:
//ChatSession m_oChatSession;
std::vector<ChatSession> m_vecChatSession;
};
#endif // !__GameServer_H__
| [
"[email protected]"
] | |
9772a0265d5552419220fb908369ce7d73f74611 | 615f8ab10a05daa842e17dd7aac2351df4e292a7 | /CGMF-Version-1.0.7.2/src/cgmFF.cpp | 1e4c1fd1532557bb163213cab031fda0d600235c | [] | no_license | austinlc/YATKE | ebd3b923539f94e56cc28a1885890c0f727ec774 | a82cb9022e6f69b56aef35abeebc21dfd15c3b8c | refs/heads/master | 2020-12-02T19:37:10.589587 | 2017-08-03T22:43:05 | 2017-08-03T22:43:05 | 96,365,573 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 14,901 | cpp | /*
* cgmFF.cpp
* cgm
*
* Created by Ionel Stetcu on 11/4/11.
* Copyright 2011 __MyCompanyName__. All rights reserved.
*
*
* USAGE:
*
* time mpirun -np $NSLOTS ./mpiCGMF -s 1 -m -o 4 -n 128
*
* np: number of processors
* n: number of fission events per processor
*
*/
#include "resultsMC.h"
//#include "cgmFF.h"
#include "FissionFragments.h"
// $Id: cgm.cpp 5 2011-08-09 02:08:58Z kawano $
/******************************************************************************/
/** **/
/** C G M : Cascading Gamma-ray and Multiplicity **/
/** Version 3.4 Sinope (2011) **/
/** T. Kawano **/
/** History **/
/** 1.0 2008 May (Io) Hauser-Feshbach for gamma spectra **/
/** 2.0 2008 Jul. (Europa) Gamma cascade by Monte Carlo **/
/** - 2008 Dec. (Ganymede) CoH3beta branch full Hauser-Feshbach code **/
/** 3.0 2009 Sep. (Amalthea) Backport version from CoH3-Callisto **/
/** 3.1 2010 Feb. (Himalia) Beta decay enhanced **/
/** 3.2 2010 Apr. (Elara) Monte Carlo recovery version **/
/** 3.3 2011 Jan. (Pasiphae) Multiple neutron emission version **/
/** 3.4 2011 Jun. (Sinope) Monte Carlo with neutron emission version **/
/** **/
/** Los Alamos National Laboratory **/
/** **/
/******************************************************************************/
#include <iostream>
#include <fstream>
#include <sstream>
#include <iomanip>
#include <string>
#include <cstdlib>
#include <cmath>
#include <ctime>
#include <netdb.h>
#include <unistd.h>
#include <netinet/in.h> // only needed for section 8
#include <arpa/inet.h> // only needed for section 8
#include <sys/socket.h> // only needed for definition of AF_INET for part 5
using namespace std;
#include "mchf.h"
#include "cgm.h"
#include "global.h"
#include "terminate.h"
#include "config.h"
#include "mt19937ar.h"
#include "ffd.h"
#define CGM_TOPLEVEL
static int cgmCheckRange (int, int, double);
static void cgmOutputOptions (unsigned int);
static void cgmHelp (void);
static void cgmAllocateMemory (void);
static void cgmDeleteAllocated (void);
extern "C" {
void return_bspin2c_( double * , int * , int * ) ;
}
Calculation ctl;
Nucleus *ncl; // 0: parent, 1 - MAX_COMPOUND-1: daughters etc
double *spc[SPECTRA_OUTPUT]; // 0: gamma, 1: neutron, 2: electron, 3: neutrino
ostringstream oserr;
#ifdef HAVE_PRIVATE_ENERGY_GRID
#include GRID_STRUCTURE_FILE
#endif
#define CHOICE 5
#define PARTICLE 0
resultsMC resMC[ 2 ] ; // global variable to store the MC output
bool too_many_gammas = false ;
int irun_times = 0 ;
/**********************************************************/
/* CGM */
/**********************************************************/
int main(int argc, char *argv[])
{
//---------------------------------------
// Command Line Options
// double exciE = 0.0 , exciEh ; // nuclear excitation energy
double initJ = -1.; // initial state spin, J
// double initJh ; // initial state spin, J
// int initP = 0 , initPh ; // initial state parity, -1 or 1
// int targZ = 0 , targZh ; // target Z number
// int targA = 0 , targAh ; // target A number
// int isomr = 0; // isomeric state for beta decay
unsigned long nsim = 0; // number of Monte Carlo sampling
int p , samples=0;
unsigned int o=0xffff,c=0;
// int ifiles , nfiles ;
// char filename[120] , filename_h[ 120 ] ;
// double kin_en , kin_enh ;
int max_nucl, max_nucl_pp ;
// char hostname[120] ;
double spinf = 0.0 ;
resultsMC resMC_store[ 2 ] ;
long t_start , t_start_loop , t_stop_loop , t_io , time0 , time1 , time_ff = 0L ;
int ip , np ;
ifstream data_file , data_file_h ;
MPI_Init (&argc, &argv);
MPI_Comm_rank (MPI_COMM_WORLD, &ip);
MPI_Comm_size (MPI_COMM_WORLD, &np);
double x_clock = 1.0 / CLOCKS_PER_SEC ;
if (ip==0) {
t_start = clock();
cout << "reading data: " << t_start * x_clock << " s" << endl ;
}
MPI_Barrier( MPI_COMM_WORLD ) ;
// initialize here the random number generator
unsigned long init[4]={0x123, 0x234, 0x345, 0x456}, length=4;
if(RAMDOM_SEED_BY_TIME){
for(int i=0 ; i<4 ; i++) init[i] += (unsigned long) (time(NULL) + ip * 3938 * ( 1 + i ) ) ;
}
irun_times = 1 ;
init_by_array(init, length);
for (int i = 0 ; i < 2 ; i++) {
resMC[ i ].ipart = i ;
resMC[ i ].setMPI_info( MPI_COMM_WORLD , ip , np ) ;
resMC_store[ i ].ipart = i ;
resMC_store[ i ].setMPI_info( MPI_COMM_WORLD , ip , np ) ;
}
while((p=getopt(argc,argv,"z:a:e:i:j:p:s:o:mbthn:"))!=-1){
switch(p){
/*
case 'z': targZ = atoi(optarg); break;
case 'a': targA = atoi(optarg); break;
case 'e': exciE = atof(optarg); break;
case 'i': isomr = atoi(optarg); break;
case 'j': initJ = atof(optarg); break;
case 'p': initP = atoi(optarg); break;
*/
case 'o': o = atoi(optarg); break;
case 's': nsim = atoi(optarg); break;
case 'm': c = c | CALC_MC; break;
case 'b': c = c | CALC_BETA; break;
case 't': c = c | CALC_TRAN; break;
case 'h': cgmHelp(); break;
case 'n': max_nucl =atoi(optarg); break;
case ':': cerr << "ERROR :need a value for option" << p << endl;
cgmHelp(); break;
case '?': cerr << "ERROR :unknown optin" << p << endl;
cgmHelp(); break;
}
}
//---------------------------------------
// Output Items and Calc Flow Initialize
cgmOutputOptions(o);
if(c != 0){
ctl.calc_montecarlo = c & CALC_MC;
ctl.calc_betadecay = c & CALC_BETA;
ctl.calc_entrance = c & CALC_TRAN;
}
initJ = 2. ;
if(ctl.calc_betadecay) ctl.init_pop = BETA;
else{
if(initJ >= 0.0) ctl.init_pop = SINGLE;
else{
ctl.init_pop = (ctl.calc_entrance) ? TRANSMISSION : LEVDEN;
}
}
/*** Allocate Memory */
cgmAllocateMemory();
max_nucl_pp = max_nucl ;
cout << " ip = " << ip << " max= " << max_nucl_pp << endl ;
int ZAIDt = 94239;
double incidentEnergy = 2.53e-8; // 0.0 for spontaneous fission! 2.53e-8 for thermal energy
FissionFragments ff(ZAIDt, incidentEnergy);
for (int i=ff.Amin; i<=ff.Amax; i++) {
for (int j=ff.Zmin; j<=ff.Zmax; j++) {
if (ff.YZA2[j][i]!=0.0) cout << i << " " << j << " " << ff.YZA2[j][i] << "\n";
}
}
exit(0);
fissionFragmentType *lightFragment, *heavyFragment;
lightFragment = new fissionFragmentType[max_nucl_pp];
heavyFragment = new fissionFragmentType[max_nucl_pp];
fissionFragmentType lf, hf;
ff.generateInitialFissionFragmentHistories (lightFragment, heavyFragment, max_nucl_pp);
if (ip==0) {
ff.generateInitialFissionFragmentHistories ( "yields", 10000);
ff.checkDistributions ("yields", "yields.out");
// cout << "STOP HERE\n";
// exit(0);
}
for (int i=0; i<2; i++) {
resMC[i].init(ZAIDt, incidentEnergy);
resMC[ i ].geant_init( max_nucl_pp );
resMC_store[ i ] = resMC[ i ];
}
MPI_Barrier (MPI_COMM_WORLD);
t_start_loop = clock() ;
if (ip==0) {
cout << "starting loop: " << t_start_loop * x_clock << " s" << endl ;
cout << "time to read and i/o: " << ( t_start_loop -t_start ) * x_clock << " s" << endl ;
}
MPI_Barrier( MPI_COMM_WORLD ) ;
cout << "ip = " << ip << " max_nucl_pp = " << max_nucl_pp << endl ;
for (samples=0; samples<max_nucl_pp; samples++) {
lf = lightFragment[samples];
hf = heavyFragment[samples];
// light fragment calc.
for (int i=0; i<2; i++) resMC[i].setFragment(lf.A, lf.Z, 0, lf.KE);
ncl[0].za.setZA (lf.Z, lf.A);
ncl[0].max_energy = lf.U;
specMCMain (lf.doubleSpin/2., lf.parity, 0.0, spinf, nsim, spc);
for (int i=0; i<2; i++) resMC[i].update_int();
// heavy fragment calc.
for( int i = 0 ; i < 2 ; i++) resMC[ i ].setFragment(hf.A, hf.Z, 1, hf.KE);
ncl[0].za.setZA( hf.Z, hf.A);
ncl[0].max_energy = hf.U;
specMCMain( hf.doubleSpin / 2. , hf.parity ,0.0,spinf,nsim,spc);
// For now, too_many_gammas ALWAYS SET TO FALSE
if( too_many_gammas ){
for( int i = 0 ; i < 2 ; i++ ) resMC[ i ] = resMC_store[ i ] ;
too_many_gammas = false ;
}
else{
for( int i = 0 ; i < 2 ; i++ ){
resMC[ i ].update() ;
resMC_store[ i ] = resMC[ i ] ;
}
}
// reset fission event
resMC[1].addFissionEvent (lf.A, lf.Z, lf.U, hf.U); // neutrons
resMC[0].addFissionEvent (lf.A, lf.Z, lf.U, hf.U); // gammas
} // end loop over FF samples
MPI_Barrier( MPI_COMM_WORLD ) ;
t_stop_loop = clock() ;
time1 = t_stop_loop - t_start_loop ;
if( ip == 0 ){
cout << "time spent in loop: " << ( t_stop_loop - t_start_loop ) * x_clock << " s" << endl ;
}
MPI_Reduce( &time1 , &time0 , 1 , MPI_LONG , MPI_MIN , 0 , MPI_COMM_WORLD ) ;
MPI_Reduce( &time1 , &time_ff , 1 , MPI_LONG , MPI_MAX , 0 , MPI_COMM_WORLD ) ;
if (ip==0) {
cout << "min time spent in loop: " << time0 * x_clock << " s" << endl ;
cout << "max time spent in loop: " << time_ff * x_clock << " s" << endl ;
}
/*** Print Results */
#ifdef HAVE_PRIVATE_ENERGY_GRID
if(ctl.print_spectrum ) cgmPrintCustomGrid(NUMBER_OF_PRIVATE_GRID,custom_energy_grid,ncl[0].binwidth,spc);
#else
if(ctl.print_spectrum ) cgmPrintSpectra(ctl.calc_betadecay,ncl[0].de,spc);
#endif
// printbspin_inc_() ;
if(ctl.print_spectrum ) cgmPrintSpectra(ctl.calc_betadecay,ncl[0].de,spc);
/*** Free Allocate Memory */
cgmDeleteAllocated();
if( ip == 0 )
remove( "output.txt" ) ;
resMC[ 0 ].printInfo( "test_g" ) ;
resMC[ 1 ].printInfo( "test_n" ) ;
//33 resMC[0].printAllResults ("gammas.CGMF.out");
resMC[1].printAllResults ("neutrons.CGMF.out");
resMC[0].printAllResults ("gammas.CGMF.out");
if (ip==0) {
t_io = clock() ;
cout << "Final i/o time: " << ( t_io - t_stop_loop ) * x_clock << " s" << endl ;
}
delete [] lightFragment ; delete [] heavyFragment ;
MPI_Finalize() ;
return 0;
}
/**********************************************************/
/* Setting Output Options */
/**********************************************************/
void cgmOutputOptions(unsigned int p)
{
ctl.print_spectrum = DEFAULT_CAL & OUT_SPEC;
ctl.print_init_pop = DEFAULT_CAL & OUT_INIPOP;
ctl.print_history = DEFAULT_CAL & OUT_HIST;
ctl.print_indivspec = DEFAULT_CAL & OUT_INDIVSPEC;
if(p != 0xffff){
ctl.print_spectrum = p & OUT_SPEC;
ctl.print_init_pop = p & OUT_INIPOP;
ctl.print_history = p & OUT_HIST;
ctl.print_broadened = p & OUT_BROADENED;
ctl.print_indivspec = p & OUT_INDIVSPEC;
}
if(ctl.print_broadened) ctl.print_spectrum = true;
}
/**********************************************************/
/* Check Z/A/E Range */
/**********************************************************/
int cgmCheckRange(int z, int a, double e)
{
if(z < 6 || z>118){
oserr << "ERROR :Z number " << z << " out of range";
return -1;
}
if(a < 12 || a>300){
oserr << "ERROR :A number " << a << " out of range";
return -1;
}
if(e <= 0.0){
oserr << "ERROR :Excitation energy " << e << " negative or zero";
return -1;
}
double em = 0.0;
#ifdef HAVE_PRIVATE_ENERGY_GRID
em = custom_energy_grid[NUMBER_OF_PRIVATE_GRID-1];
#else
em = (MAX_ENERGY_BIN-1) * ENERGY_BIN;
#endif
return(0);
}
/**********************************************************/
/* Help */
/**********************************************************/
void cgmHelp()
{
cout << "cgm -z Znumber -a Anumber -e Excitation Energy ... " << endl;
cout << "option synopsis" << endl;
cout << " -j J : spin of the excited state" << endl;
cout << " -p P : parity of the excited state" << endl;
cout << " if J and P not given, gaussian dist. is assumed" << endl;
cout << " -t : initial population calculated with neutron Tj (level density, otherwise)" << endl;
cout << " -m : do Monte Carlo (toggle)" << endl;
cout << " -s N : number of simulation" << endl;
cout << " -o N : print control; sum of the following numbers" << endl;
cout << " 1 print energy spectrum" << endl;
cout << " 2 initial population" << endl;
cout << " 4 Monte Carlo history (if -m given)" << endl;
cout << " 8 Gaussian broadening for the output spectrum" << endl;
cout << " 16 print individual spectra from each neutron emission stage" << endl;
exit(-1);
}
/**********************************************************/
/* Memory Allocation */
/**********************************************************/
void cgmAllocateMemory()
{
try{
/*** compound nucleus */
ncl = new Nucleus [MAX_COMPOUND];
/*** calculated results */
for(int i=0 ; i<4 ; i++){
spc[i] = new double[MAX_ENERGY_BIN];
}
}
catch(bad_alloc){
cerr << "ERROR :memory allocation error";
exit(-1);
}
}
/**********************************************************/
/* Free Allocated Memory */
/**********************************************************/
void cgmDeleteAllocated()
{
delete [] ncl;
for(int i=0 ; i<SPECTRA_OUTPUT ; i++) delete [] spc[i];
}
/**********************************************************/
/* Emergency Stop */
/**********************************************************/
int cgmTerminateCode(string msg)
{
/*** Release global storage */
cgmDeleteAllocated();
/*** Exit code */
cerr << "ERROR :" << msg << endl;
exit(-1);
}
int cgmTerminateCode(string msg, int n)
{
/*** Release global storage */
cgmDeleteAllocated();
/*** Exit code */
cerr << "ERROR :" << msg << " : " << n << endl;
exit(-1);
}
int cgmTerminateCode(string msg, double x)
{
/*** Release global storage */
cgmDeleteAllocated();
/*** Exit code */
cerr << "ERROR :" << msg << " : " << x << endl;
exit(-1);
}
| [
"[email protected]"
] | |
dadb9e96010a3568acd39f5a2a71516850c26653 | 4ebca3da4bbf909d27fe2051695ab2e011b81927 | /CCLayerMultiplex/Classes/HelloWorldScene.h | 1a566cbf8ad4ae59192631bb1b77a393bebffdfa | [] | no_license | 980538137/cocos2dx-demo | 7218bbe82d2fe645554cfe65085589917454872f | 51a32b08218bbaf61deafd1c595b976857d1a4d1 | refs/heads/master | 2021-01-17T17:07:20.495360 | 2014-01-02T14:38:10 | 2014-01-02T14:38:10 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 834 | h | #ifndef __HELLOWORLD_SCENE_H__
#define __HELLOWORLD_SCENE_H__
#include "cocos2d.h"
#include "CLayer1.h"
#include "CLayer2.h"
#include "CLayer3.h"
class HelloWorld : public cocos2d::CCLayer
{
public:
HelloWorld(void);
~HelloWorld(void);
CREATE_FUNC(HelloWorld);
// Here's a difference. Method 'init' in cocos2d-x returns bool, instead of returning 'id' in cocos2d-iphone
virtual bool init();
// there's no 'id' in cpp, so we recommend returning the class instance pointer
static cocos2d::CCScene* scene();
// a selector callback
void menuCloseCallback(CCObject* pSender);
// implement the "static node()" method manually
private:
CCLayer1* _layer1;
CCLayer2* _layer2;
CCLayer3* _layer3;
int curLayerPos;
CCLayerMultiplex* _layerMultiplex;
};
#endif // __HELLOWORLD_SCENE_H__
| [
"[email protected]"
] | |
24698759689fdf78ff0dd2296d1a6aef0468d29c | b7f3edb5b7c62174bed808079c3b21fb9ea51d52 | /chrome/browser/extensions/extension_action_storage_manager.h | 6009a9d3d087918a428adf5920f9e970cf59bcae | [
"BSD-3-Clause"
] | permissive | otcshare/chromium-src | 26a7372773b53b236784c51677c566dc0ad839e4 | 64bee65c921db7e78e25d08f1e98da2668b57be5 | refs/heads/webml | 2023-03-21T03:20:15.377034 | 2020-11-16T01:40:14 | 2020-11-16T01:40:14 | 209,262,645 | 18 | 21 | BSD-3-Clause | 2023-03-23T06:20:07 | 2019-09-18T08:52:07 | null | UTF-8 | C++ | false | false | 2,408 | h | // Copyright 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef CHROME_BROWSER_EXTENSIONS_EXTENSION_ACTION_STORAGE_MANAGER_H_
#define CHROME_BROWSER_EXTENSIONS_EXTENSION_ACTION_STORAGE_MANAGER_H_
#include <string>
#include "base/macros.h"
#include "base/memory/weak_ptr.h"
#include "base/scoped_observer.h"
#include "chrome/browser/extensions/api/extension_action/extension_action_api.h"
#include "extensions/browser/extension_action.h"
#include "extensions/browser/extension_registry.h"
#include "extensions/browser/extension_registry_observer.h"
namespace content {
class BrowserContext;
}
namespace extensions {
class StateStore;
// This class manages reading and writing browser action values from storage.
class ExtensionActionStorageManager : public ExtensionActionAPI::Observer,
public ExtensionRegistryObserver {
public:
explicit ExtensionActionStorageManager(content::BrowserContext* context);
~ExtensionActionStorageManager() override;
private:
// ExtensionActionAPI::Observer:
void OnExtensionActionUpdated(
ExtensionAction* extension_action,
content::WebContents* web_contents,
content::BrowserContext* browser_context) override;
void OnExtensionActionAPIShuttingDown() override;
// ExtensionRegistryObserver:
void OnExtensionLoaded(content::BrowserContext* browser_context,
const Extension* extension) override;
// Reads/Writes the ExtensionAction's default values to/from storage.
void WriteToStorage(ExtensionAction* extension_action);
void ReadFromStorage(const std::string& extension_id,
std::unique_ptr<base::Value> value);
// Returns the Extensions StateStore for the |browser_context_|.
// May return NULL.
StateStore* GetStateStore();
content::BrowserContext* browser_context_;
ScopedObserver<ExtensionActionAPI, ExtensionActionAPI::Observer>
extension_action_observer_{this};
ScopedObserver<ExtensionRegistry, ExtensionRegistryObserver>
extension_registry_observer_{this};
base::WeakPtrFactory<ExtensionActionStorageManager> weak_factory_{this};
DISALLOW_COPY_AND_ASSIGN(ExtensionActionStorageManager);
};
} // namespace extensions
#endif // CHROME_BROWSER_EXTENSIONS_EXTENSION_ACTION_STORAGE_MANAGER_H_
| [
"[email protected]"
] | |
1caf0f4533e8ec18c500f29630ffeb8fe5d57236 | 54b413a0789fcfd7feb61d6cc307ee78856953a5 | /HXSpy/stdafx.cpp | dba43ef0b52e72128f496897e0d3e64d873797f2 | [] | no_license | liumorgan/HXHookStudio | 1b8ec80814cf3c58dc3d4911bc2c51b818198dca | 134fbba1b1b037f9fcb03e583437daddd8fad3ad | refs/heads/master | 2023-06-06T03:33:32.107088 | 2021-06-18T03:01:45 | 2021-06-18T03:01:45 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 196 | cpp | // stdafx.cpp : source file that includes just the standard includes
// HXSpy.pch will be the pre-compiled header
// stdafx.obj will contain the pre-compiled type information
#include "stdafx.h"
| [
"[email protected]"
] | |
6e986291f06a6b8780f389db086221bcbc4dafd1 | f5a2f1ecad9d03865587566f7ffa0f8ce94ac50b | /caffe2/operators/reshape_op_gpu_test.cc | 3537ab69d058f03a7a4da06b63038f2ea0a67ffa | [
"BSD-3-Clause",
"LicenseRef-scancode-generic-cla",
"Apache-2.0",
"BSD-2-Clause"
] | permissive | prudvinit/pytorch | 10f82e9220b5005f1ba807c1954eee15c998c463 | 76ab26cc3eff1d7ba822d8db93723f5c9598eead | refs/heads/master | 2020-03-29T13:25:15.298962 | 2018-09-23T04:47:59 | 2018-09-23T04:54:55 | 149,958,168 | 0 | 1 | null | 2018-09-23T07:40:20 | 2018-09-23T07:40:19 | null | UTF-8 | C++ | false | false | 1,455 | cc | #include <iostream>
#include <gtest/gtest.h>
#include "caffe2/core/context.h"
#include "caffe2/core/context_gpu.h"
#include "caffe2/core/flags.h"
#include "caffe2/operators/reshape_op.h"
#include "caffe2/utils/math.h"
CAFFE2_DECLARE_string(caffe_test_root);
namespace caffe2 {
static void AddConstInput(
const vector<int64_t>& shape,
const float value,
const string& name,
Workspace* ws) {
DeviceOption option;
option.set_device_type(PROTO_CUDA);
CUDAContext context(option);
Blob* blob = ws->CreateBlob(name);
auto* tensor = blob->GetMutableTensor(CUDA);
tensor->Resize(shape);
math::Set<float, CUDAContext>(
tensor->size(), value, tensor->template mutable_data<float>(), &context);
return;
}
TEST(ReshapeOpGPUTest, testReshapeWithScalar) {
if (!HasCudaGPU())
return;
Workspace ws;
OperatorDef def;
def.set_name("test_reshape");
def.set_type("Reshape");
def.add_input("X");
def.add_output("XNew");
def.add_output("OldShape");
def.add_arg()->CopyFrom(MakeArgument("shape", vector<int64_t>{1}));
def.mutable_device_option()->set_device_type(PROTO_CUDA);
AddConstInput(vector<int64_t>(), 3.14, "X", &ws);
// execute the op
unique_ptr<OperatorBase> op(CreateOperator(def, &ws));
EXPECT_TRUE(op->Run());
Blob* XNew = ws.GetBlob("XNew");
const Tensor& XNewTensor = XNew->Get<Tensor>();
EXPECT_EQ(1, XNewTensor.ndim());
EXPECT_EQ(1, XNewTensor.size());
}
} // namespace caffe2
| [
"[email protected]"
] | |
84e648a420b207d3209fafd546738500690db8d9 | 5ecc608680acf2a4faccc328f096de071da16293 | /CompisiteDesignPattern/RootNode.cpp | ace28b2019e5937cafc49b605c1c969bcd23200b | [] | no_license | metaliuyong/LearnDesignPatterns | 34240a04ecd62ba76f7d0a0ad2cf952b1a62aebf | ff25792d4168def27a4a4392aedac89d0d942810 | refs/heads/master | 2023-02-28T21:00:28.399646 | 2021-02-09T13:52:58 | 2021-02-09T13:52:58 | 337,407,961 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 447 | cpp | //
// Created by 刘勇 on 2021/2/2.
//
#include "RootNode.h"
#include <iostream>
void RootNode::printInform() {
std::cout << "I am a Root Node." << std::endl;
for(Node* pChildNode : childNodes){
pChildNode->printInform();
}
}
void RootNode::addChildNode(Node* childNode){
childNodes.push_back(childNode);
}
void RootNode::removeChildNode(Node* childNode){
childNodes.remove(childNode);
}
void RootNode::test(){
} | [
"[email protected]"
] | |
974a9022aeb3b5ce95a28e4dc8b9ec7fc577b15e | a689462b89be7da525a7761a573695360a7f2c4c | /curso_prog_professional/P5/A/A.cpp | 31168a70c436415c02f6621767a165dcd187335d | [] | no_license | renanmach/competitive_coding | 6a27e8abac2602e3268b838f7fe17421ffb7aa4f | 48a7498581fbcbcd9763736f66951cdd0dbb05d6 | refs/heads/master | 2020-04-17T11:22:08.263346 | 2018-05-01T23:41:07 | 2018-05-01T23:41:07 | 67,151,508 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 781 | cpp | #include <stdio.h>
#include <iostream>
#include <cstdlib>
#include <cstring>
#include <string>
#define MAXN 1009
using namespace std;
int inline max(int x, int y) {
return x >= y ? x : y;
}
string a;
string b;
int n,m;
int dp[MAXN][MAXN];
int score(int x, int y) {
if(a[x] == b[y]) return 1;
return -1000000;
}
int lcs() {
n = (int)a.size();
m = (int)b.size();
dp[0][0] = 0;
for(int i = 1 ; i <= n; i++) {
dp[0][i] = 0;
}
for(int i = 1 ; i <= m; i++) {
dp[i][0] = 0;
}
for(int i = 1 ; i <= n; i++) {
for(int j = 1 ; j <=m; j++) {
dp[i][j] = max(dp[i-1][j-1]+score(i-1,j-1), max(dp[i-1][j],dp[i][j-1]));
}
}
return dp[n][m];
}
int main(void) {
while(getline(cin, a)) {
getline(cin, b);
cout << lcs() << endl;
}
return 0;
}
| [
"[email protected]"
] | |
630b73e9e08b58bcba5bc13895c3b149f8822573 | 52d2ebd1ddda728cf1bdb311109095edbc911d1f | /Graphics/Shader.cpp | 23eb4b882881162ff576f58280460650fc4f508d | [] | no_license | lazykobolds/cubesource | c46e5a6ac9bcadcb81f11532bce4617cb96c4b49 | d27efe9962622c0596249ead4c90d68f3afcb026 | refs/heads/master | 2020-04-18T04:47:10.595279 | 2016-09-11T02:44:24 | 2016-09-11T02:44:24 | 67,906,305 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 769 | cpp | #include "Shader.h"
#include <stdio.h>
LPD3DXEFFECT LoadEffect( const char * filename, LPDIRECT3DDEVICE9 d3ddev )
{
LPD3DXEFFECT effect = 0;
HRESULT hr;
LPD3DXBUFFER buffer_errors = NULL;
hr = D3DXCreateEffectFromFile( d3ddev,
filename,
NULL,
NULL,
0,
NULL,
&effect,
&buffer_errors );
if( FAILED(hr) && buffer_errors )
{
char* compile_errors = (char*)buffer_errors->GetBufferPointer();
MessageBox(NULL, (const char*)compile_errors, "Fx Compile Error",
MB_OK|MB_ICONEXCLAMATION);
printf("SHADER ERROR:\n");
printf( "%s\n", compile_errors );
}else if( FAILED(hr) )
{
printf("Error number: %i\n", hr );
printf("Failed to create shader: %s\n", filename );
}
return effect;
} | [
"[email protected]"
] | |
01b0ca7c9936a64a40e3b18d7b9ebe7b7691c552 | e6677d0e6deba1821ed6ae8449bc76cb7096348a | /editproduct.cpp | 9934b60fb7614a9eeeb17433ea6610f1535e48ee | [] | no_license | nguloan/Project_ctdl-gt | 5d95fb42b5ded9d89dc205dc498b84d3fe825963 | e2036567654ecdb409f477aee5cc138301e19318 | refs/heads/master | 2022-11-06T17:05:01.466732 | 2020-06-19T14:53:16 | 2020-06-19T14:53:16 | 254,835,636 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,621 | cpp | #include "editproduct.h"
#include "ui_editproduct.h"
EditProduct::EditProduct(std::string str,QWidget *parent) :
QDialog(parent),
ui(new Ui::EditProduct)
{
QWidget* background = new QWidget(this);
background->setStyleSheet("background-color:#F4F6F7;");
background->setGeometry(QRect(0,0,2000,1100));
this->setWindowIcon(QIcon("E:/Project/MyProject/photo/iconTilte.png"));
init(dataPd);
strId = str;
this->setModal(true);
initphlist(dataOrders);
node* ptr = dataPd.getPoiter(str);
ui->setupUi(this);
ui->id->setText(QString::fromStdString(ptr->id)); // setText
ui->id->setEnabled(false);
this->setWindowTitle("Chi tiết sản phẩm về "+ QString::fromStdString(ptr->id));
ui->name->setText(QString::fromStdString(ptr->name));
ui->price->setText(QString::fromStdString(ptr->price));
ui->quanity->setText(QString::number(ptr->quanity));
file = QString("E:/Project/MyProject/photoProducts/%1.png").arg(QString::fromStdString(ptr->id));
if(QFile::exists(file)==false)
{
file = "E:/Project/MyProject/photo/imageNotFound.png";
}
fileTemp = file;
QPixmap photoPd(file);
ui->photo->setPixmap(photoPd.scaled(350,350,Qt::KeepAspectRatio));
for (auto p = dataPd.listCate.getHead();p!=NULL;p=p->next) {
ui->category->addItem(QString::fromStdString(p->name));
}
for (auto p = dataPd.listBrand.getHead();p!=NULL;p=p->next) {
ui->brand->addItem(QString::fromStdString(p->name));
}
for (auto p = dataPd.listMadein.getHead();p!=NULL;p=p->next) {
ui->madein->addItem(QString::fromStdString(p->name));
}
for (auto p = dataPd.listKind.getHead();p!=NULL;p=p->next) {
if(p->idCate==ui->category->currentIndex()) ui->kind->addItem(QString::fromStdString(p->name));
}
if(ptr->disable==1) ui->disable->setChecked(true);
else ui->enable->setChecked(true);
connect(ui->category,&QComboBox::currentTextChanged,this,&EditProduct::Category);
connect(ui->kind,&QComboBox::currentTextChanged,this,&EditProduct::Kind);
connect(ui->brand,&QComboBox::currentTextChanged,this,&EditProduct::Brand);
connect(ui->madein,&QComboBox::currentTextChanged,this,&EditProduct::Madein);
// Category();
ui->category->setCurrentText(QString::fromStdString(ptr->category));
ui->kind->setCurrentText(QString::fromStdString(ptr->kind));
ui->brand->setCurrentText(QString::fromStdString(ptr->brand));
ui->madein->setCurrentText(QString::fromStdString(ptr->madein));
connect(ui->editPhoto,&QPushButton::clicked,this,&EditProduct::EditPhoto);
}
void EditProduct::Category()
{
QString id = ui->id->text();
ui->kind->clear();
for (auto p = dataPd.listKind.getHead();p!=NULL;p=p->next) {
if(p->idCate==ui->category->currentIndex()) ui->kind->addItem(QString::fromStdString(p->name));
}
ui->kind->setCurrentIndex(0);
if(ui->kind->currentText() == "")
{
QMessageBox::information(this,"Thông báo lỗi", "Danh mục chưa có phân loại, vui lòng thêm phân loại cho "+ui->category->currentText());
ui->category->setCurrentIndex(id.left(2).toInt());
return;
}
id = (ui->category->currentIndex() < 10 ? "0":"" ) + QString::number(ui->category->currentIndex()) + id.mid(2,id.length()-2);
ui->id->setText(id);
}
void EditProduct::Brand()
{
std::string id = ui->id->text().toStdString();
id = id.substr(0,4) + (ui->brand->currentIndex() < 10 ? "0":"" ) + std::to_string(ui->brand->currentIndex()) + id.substr(6,id.length()-6);
ui->id->setText(QString::fromStdString(id));
}
void EditProduct::Madein()
{
std::string id = ui->id->text().toStdString();
id = id.substr(0,6) + (ui->madein->currentIndex() < 10 ? "0":"" ) + std::to_string(ui->madein->currentIndex()) + id.substr(8,id.length()-8);
ui->id->setText(QString::fromStdString(id));
}
void EditProduct::Kind()
{
QString id = ui->id->text();
int t = dataPd.listKind.getCode(ui->kind->currentText().toStdString());
id = id.left(2) + (t < 10 ? "0":"" ) + QString::number(t) + id.mid(4,id.length()-4);
ui->id->setText(id);
}
EditProduct::~EditProduct()
{
delete ui;
}
void EditProduct::EditPhoto()
{
QString check = QFileDialog::getOpenFileName(this, tr("Open Image"), "/home", tr("Image Files (*.png *.jpg *.bmp)"));
if(check == "") return;
file = check;
QPixmap photoPd(file);
ui->photo->setPixmap(photoPd.scaled(300,300,Qt::KeepAspectRatio));
}
void EditProduct::on_apply_clicked()
{
if (QMessageBox::information(this,"","Bạn có chắc chắn?",QMessageBox::Yes|QMessageBox::No) == QMessageBox::No) return;
if(ui->name->text()==""){
QMessageBox::warning(this,"","Tên sản phẩm không được để trống");
return;
}
if(ui->price->text()=="")
{
QMessageBox::warning(this,"","Giá sản phẩm không được để trống");
return;
}
std::string price = ui->price->text().toStdString();
for (std::string::iterator it = price.begin(); it != price.end(); ++it) {
if ( isdigit(*it)==false)
{
QMessageBox::warning(this,"","Giá sản phẩm không được có ký tự anphabe");
return;
}
}
fileNew = QString("E:/Project/MyProject/photoProducts/%1.png").arg(ui->id->text());
if(file !="" ) {
QFile::copy(file,fileNew);
}
auto p = dataPd.getPoiter(strId);
p->id = ui->id->text().toStdString();
p->name = ui->name->text().toStdString();
p->price = ui->price->text().toStdString();
p->quanity = ui->quanity->text().toInt();
p->disable = ui->disable->isChecked() ? 1 : 0;
save(dataPd);
this->accept();
return;
}
void EditProduct::on_deletePd_clicked()
{
if (QMessageBox::information(this,"Thông báo","Bạn có chắc chắn?","Có","Không") == 1) return;
if(dataOrders.checkIdProduct(QString::fromStdString(strId)))
{
QMessageBox::warning(this,"Thông báo","Sản phẩm không thể xóa");
return;
}
auto p = dataPd.getPoiter(strId);
dataPd.remove(p);
save(dataPd);
this->accept();
}
| [
"[email protected]"
] | |
e12d180675d8cf19148ecf9dac014402f09538ed | 928aeb62a6f50ff651407fac814b3446ec1957b1 | /src/qt/sendcoinsentry.cpp | de84638293ba9625002f0c607114c074b5b9e787 | [
"MIT"
] | permissive | corefork/astrocoincore | d2218b8b8968a6bf96497468e6fb10d77ec1c466 | 4a297ade044312e0a6b231264ce26f68280065a7 | refs/heads/master | 2021-01-10T20:59:45.000725 | 2014-07-03T05:04:55 | 2014-07-03T05:04:55 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,856 | cpp | // Copyright (c) 2011-2013 The AstroCoin developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "sendcoinsentry.h"
#include "ui_sendcoinsentry.h"
#include "addressbookpage.h"
#include "addresstablemodel.h"
#include "guiutil.h"
#include "optionsmodel.h"
#include "walletmodel.h"
#include <QApplication>
#include <QClipboard>
SendCoinsEntry::SendCoinsEntry(QWidget *parent) :
QStackedWidget(parent),
ui(new Ui::SendCoinsEntry),
model(0)
{
ui->setupUi(this);
setCurrentWidget(ui->SendCoins);
#ifdef Q_OS_MAC
ui->payToLayout->setSpacing(4);
#endif
#if QT_VERSION >= 0x040700
ui->addAsLabel->setPlaceholderText(tr("Enter a label for this address to add it to your address book"));
#endif
// normal astrocoin address field
GUIUtil::setupAddressWidget(ui->payTo, this);
// just a label for displaying astrocoin address(es)
ui->payTo_is->setFont(GUIUtil::astrocoinAddressFont());
}
SendCoinsEntry::~SendCoinsEntry()
{
delete ui;
}
void SendCoinsEntry::on_pasteButton_clicked()
{
// Paste text from clipboard into recipient field
ui->payTo->setText(QApplication::clipboard()->text());
}
void SendCoinsEntry::on_addressBookButton_clicked()
{
if(!model)
return;
AddressBookPage dlg(AddressBookPage::ForSelection, AddressBookPage::SendingTab, this);
dlg.setModel(model->getAddressTableModel());
if(dlg.exec())
{
ui->payTo->setText(dlg.getReturnValue());
ui->payAmount->setFocus();
}
}
void SendCoinsEntry::on_payTo_textChanged(const QString &address)
{
updateLabel(address);
}
void SendCoinsEntry::setModel(WalletModel *model)
{
this->model = model;
if (model && model->getOptionsModel())
connect(model->getOptionsModel(), SIGNAL(displayUnitChanged(int)), this, SLOT(updateDisplayUnit()));
connect(ui->payAmount, SIGNAL(textChanged()), this, SIGNAL(payAmountChanged()));
connect(ui->deleteButton, SIGNAL(clicked()), this, SLOT(deleteClicked()));
connect(ui->deleteButton_is, SIGNAL(clicked()), this, SLOT(deleteClicked()));
connect(ui->deleteButton_s, SIGNAL(clicked()), this, SLOT(deleteClicked()));
clear();
}
void SendCoinsEntry::clear()
{
// clear UI elements for normal payment
ui->payTo->clear();
ui->addAsLabel->clear();
ui->payAmount->clear();
ui->messageTextLabel->clear();
ui->messageTextLabel->hide();
ui->messageLabel->hide();
// clear UI elements for insecure payment request
ui->payTo_is->clear();
ui->memoTextLabel_is->clear();
ui->payAmount_is->clear();
// clear UI elements for secure payment request
ui->payTo_s->clear();
ui->memoTextLabel_s->clear();
ui->payAmount_s->clear();
// update the display unit, to not use the default ("BTC")
updateDisplayUnit();
}
void SendCoinsEntry::deleteClicked()
{
emit removeEntry(this);
}
bool SendCoinsEntry::validate()
{
if (!model)
return false;
// Check input validity
bool retval = true;
// Skip checks for payment request
if (recipient.paymentRequest.IsInitialized())
return retval;
if (!model->validateAddress(ui->payTo->text()))
{
ui->payTo->setValid(false);
retval = false;
}
if (!ui->payAmount->validate())
{
retval = false;
}
// Reject dust outputs:
if (retval && GUIUtil::isDust(ui->payTo->text(), ui->payAmount->value())) {
ui->payAmount->setValid(false);
retval = false;
}
return retval;
}
SendCoinsRecipient SendCoinsEntry::getValue()
{
// Payment request
if (recipient.paymentRequest.IsInitialized())
return recipient;
// Normal payment
recipient.address = ui->payTo->text();
recipient.label = ui->addAsLabel->text();
recipient.amount = ui->payAmount->value();
recipient.message = ui->messageTextLabel->text();
return recipient;
}
QWidget *SendCoinsEntry::setupTabChain(QWidget *prev)
{
QWidget::setTabOrder(prev, ui->payTo);
QWidget::setTabOrder(ui->payTo, ui->addAsLabel);
QWidget *w = ui->payAmount->setupTabChain(ui->addAsLabel);
QWidget::setTabOrder(w, ui->addressBookButton);
QWidget::setTabOrder(ui->addressBookButton, ui->pasteButton);
QWidget::setTabOrder(ui->pasteButton, ui->deleteButton);
return ui->deleteButton;
}
void SendCoinsEntry::setValue(const SendCoinsRecipient &value)
{
recipient = value;
if (recipient.paymentRequest.IsInitialized()) // payment request
{
if (recipient.authenticatedMerchant.isEmpty()) // insecure
{
ui->payTo_is->setText(recipient.address);
ui->memoTextLabel_is->setText(recipient.message);
ui->payAmount_is->setValue(recipient.amount);
ui->payAmount_is->setReadOnly(true);
setCurrentWidget(ui->SendCoins_InsecurePaymentRequest);
}
else // secure
{
ui->payTo_s->setText(recipient.authenticatedMerchant);
ui->memoTextLabel_s->setText(recipient.message);
ui->payAmount_s->setValue(recipient.amount);
ui->payAmount_s->setReadOnly(true);
setCurrentWidget(ui->SendCoins_SecurePaymentRequest);
}
}
else // normal payment
{
// message
ui->messageTextLabel->setText(recipient.message);
ui->messageTextLabel->setVisible(!recipient.message.isEmpty());
ui->messageLabel->setVisible(!recipient.message.isEmpty());
ui->payTo->setText(recipient.address);
ui->addAsLabel->setText(recipient.label);
ui->payAmount->setValue(recipient.amount);
}
}
void SendCoinsEntry::setAddress(const QString &address)
{
ui->payTo->setText(address);
ui->payAmount->setFocus();
}
bool SendCoinsEntry::isClear()
{
return ui->payTo->text().isEmpty() && ui->payTo_is->text().isEmpty() && ui->payTo_s->text().isEmpty();
}
void SendCoinsEntry::setFocus()
{
ui->payTo->setFocus();
}
void SendCoinsEntry::updateDisplayUnit()
{
if(model && model->getOptionsModel())
{
// Update payAmount with the current unit
ui->payAmount->setDisplayUnit(model->getOptionsModel()->getDisplayUnit());
ui->payAmount_is->setDisplayUnit(model->getOptionsModel()->getDisplayUnit());
ui->payAmount_s->setDisplayUnit(model->getOptionsModel()->getDisplayUnit());
}
}
bool SendCoinsEntry::updateLabel(const QString &address)
{
if(!model)
return false;
// Fill in label from address book, if address has an associated label
QString associatedLabel = model->getAddressTableModel()->labelForAddress(address);
if(!associatedLabel.isEmpty())
{
ui->addAsLabel->setText(associatedLabel);
return true;
}
return false;
}
| [
"[email protected]"
] | |
50ff2bf329b0fc3bf58359c47e24162a191f8489 | 51928337483095b12f046eda9ea17ba0b1a81fc0 | /3rdparty/cppwinrt/10.0.15063.0/winrt/Windows.Phone.ApplicationModel.h | 11a0b891fa5d5bd4fc9c0d7244e90929af94ccbc | [
"LicenseRef-scancode-generic-cla",
"MIT"
] | permissive | kingofthebongo2008/geometry_images | 8592aa99e53a16821725a2564313eeafb0462362 | 53109f9bc9ea19d0f119f0fe71762248d5038213 | refs/heads/master | 2021-01-19T03:02:56.996122 | 2017-07-06T13:25:47 | 2017-07-06T13:25:47 | 87,302,727 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,684 | h | // C++ for the Windows Runtime v1.0.170331.7
// Copyright (c) 2017 Microsoft Corporation. All rights reserved.
#pragma once
#include "base.h"
WINRT_WARNING_PUSH
#include "internal/Windows.Phone.ApplicationModel.3.h"
WINRT_EXPORT namespace winrt {
namespace impl {
template <typename D>
struct produce<D, Windows::Phone::ApplicationModel::IApplicationProfileStatics> : produce_base<D, Windows::Phone::ApplicationModel::IApplicationProfileStatics>
{
HRESULT __stdcall get_Modes(Windows::Phone::ApplicationModel::ApplicationProfileModes * value) noexcept override
{
try
{
typename D::abi_guard guard(this->shim());
*value = detach_abi(this->shim().Modes());
return S_OK;
}
catch (...)
{
return impl::to_hresult();
}
}
};
}
namespace Windows::Phone::ApplicationModel {
template <typename D> Windows::Phone::ApplicationModel::ApplicationProfileModes impl_IApplicationProfileStatics<D>::Modes() const
{
Windows::Phone::ApplicationModel::ApplicationProfileModes value {};
check_hresult(WINRT_SHIM(IApplicationProfileStatics)->get_Modes(&value));
return value;
}
inline Windows::Phone::ApplicationModel::ApplicationProfileModes ApplicationProfile::Modes()
{
return get_activation_factory<ApplicationProfile, IApplicationProfileStatics>().Modes();
}
}
}
template<>
struct std::hash<winrt::Windows::Phone::ApplicationModel::IApplicationProfileStatics>
{
size_t operator()(const winrt::Windows::Phone::ApplicationModel::IApplicationProfileStatics & value) const noexcept
{
return winrt::impl::hash_unknown(value);
}
};
WINRT_WARNING_POP
| [
"[email protected]"
] | |
ad92df310fecd2084ed034921be519fa881261cf | ac98ba76e69986859c7d3fa8c403bbc2625aeea0 | /MobilityLayer/src/MyRSUApp.h | f4cbbd7100168edffa2d64034e9ec3e905c4fd62 | [
"MIT"
] | permissive | urbancomp/fogarch | 49088951002250eaaf6f7a5b3dc1c0f8bf4644ae | 1fa6f6d2e699e2c4d915bc393ced74943eb5acdb | refs/heads/main | 2022-12-26T15:16:28.846181 | 2020-10-16T15:08:37 | 2020-10-16T15:08:37 | 304,464,661 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,017 | h |
#ifndef SRC_MYRSUAPP_H_
#define SRC_MYRSUAPP_H_
#include <omnetpp.h>
#include "veins/modules/application/ieee80211p/BaseWaveApplLayer.h"
#include "message/BeaconMessage_m.h"
#include "net/NetworkIntegrate.h"
#include "net/SocketConnection.h"
#include "veins/modules/mobility/traci/TraCIMobility.h"
#include "veins/modules/mobility/traci/TraCICommandInterface.h"
namespace veins_myproject {
class MyRSUApp : public BaseWaveApplLayer {
public:
virtual void initialize(int stage);
//virtual void receiveSignal(cComponent* source, simsignal_t signalID, cObject* obj, cObject* details);
protected:
NetworkIntegrate in;
SocketConnection in2;
virtual void onWSA(WaveServiceAdvertisment* wsa);
virtual void onWSM(WaveShortMessage* wsm);
/*Envio e recebimento de Mensagens*/
virtual void handleLowerMsg(cMessage* msg);
virtual void handleSelfMsg(cMessage* msg);
};
};
#endif
| [
"[email protected]"
] | |
41702b9b6887432b1ea1e2d8d933fe2c03ec06d7 | 87c69454346b1550da7da37f1b7ebfe5468b587c | /protocol/串口通信/串口监视工具/vc62933476624/GUILIB/HEADER/GuiGroupBox.h | 823bba379ade07a16e0e88758ce137b882ea74b0 | [] | no_license | hnlylmlzh/cs | 4305ae18d35d7fe774ae0ece263a68bea882ab6a | b45154053d46c3b3b1e912946d1acaa65e99089b | refs/heads/master | 2022-03-20T17:45:10.202053 | 2019-04-15T08:54:05 | 2019-04-15T08:54:05 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,213 | h | //-----------------------------------------------------------------------//
// This is a part of the GuiLib MFC Extention. //
// Autor : Francisco Campos //
// (C) 2002 Francisco Campos <www.beyondata.com> All rights reserved //
// This code is provided "as is", with absolutely no warranty expressed //
// or implied. Any use is at your own risk. //
// You must obtain the author's consent before you can include this code //
// in a software library. //
// If the source code in this file is used in any application //
// then acknowledgement must be made to the author of this program //
// [email protected] //
//-----------------------------------------------------------------------//
#if !defined(AFX_GUIGROUPBOX_H__C7AAD4CA_1B37_42E8_8F08_AEF18BA77DFD__INCLUDED_)
#define AFX_GUIGROUPBOX_H__C7AAD4CA_1B37_42E8_8F08_AEF18BA77DFD__INCLUDED_
#if _MSC_VER > 1000
#pragma once
#endif // _MSC_VER > 1000
// GuiGroupBox.h : header file
//
/////////////////////////////////////////////////////////////////////////////
// CGuiGroupBox window
#include "GuiLib.h"
/////////////////////////////////////////////////////////////////////////////
// CGuiComboBoxExt window
class GUILIBDLLEXPORT CGuiGroupBox : public CButton
{
// Construction
public:
CGuiGroupBox();
enum Aling{ALING_LEFT=0,ALING_RIGHT=1,ALING_DOWN=2, ALING_UP=3};
// Attributes
public:
void SetStyle(Aling AlingStyle);
void SetCaption(CString Caption);
Aling m_style;
COLORREF m_clrface;
COLORREF m_clrShadow;
CString m_Caption;
// Operations
public:
virtual void PreSubclassWindow();
public:
virtual ~CGuiGroupBox();
// Generated message map functions
protected:
//{{AFX_MSG(CGuiGroupBox)
afx_msg void OnPaint();
afx_msg void OnSysColorChange();
//}}AFX_MSG
DECLARE_MESSAGE_MAP()
};
/////////////////////////////////////////////////////////////////////////////
//{{AFX_INSERT_LOCATION}}
// Microsoft Visual C++ will insert additional declarations immediately before the previous line.
#endif // !defined(AFX_GUIGROUPBOX_H__C7AAD4CA_1B37_42E8_8F08_AEF18BA77DFD__INCLUDED_)
| [
"[email protected]"
] | |
86adf489fa07152752467ac44149227ff490eb96 | 09f50c49816ab87f4e13e53b316ffff4d22d609f | /1203(mod and gcd).cpp | 693058eac7d78d43902ecae1af333cc7a02b784a | [] | no_license | abusomani/UVA | 1168cf25b0cf8fe6296c2088d71c35357c15ad87 | f5c54ff051aea53d134cb8aa9e350fbef31ddcd4 | refs/heads/master | 2020-12-31T05:25:27.325907 | 2016-04-30T22:35:00 | 2016-04-30T22:35:00 | 57,436,587 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 899 | cpp | #include<bits/stdc++.h>
using namespace std;
typedef pair<int,int> ii;
int gcd(int m, int n)
{
int r;
while (n != 0)
{
r = m % n;
m = n;
n = r;
}
return m;
}
int main()
{
cin.sync_with_stdio(0);
cout.sync_with_stdio(0);
int i = 0,n,num,t,k,g,mint;
bool exit;
string str;
vector<ii> v;
mint = 2147483647;
while(1)
{
cin>>str;
if(str=="#") break;
cin>>num>>t;
mint = min(t,mint);
v.push_back(ii(num,t));
i++;
}
cin>>k;
exit = 0;
n = i; g = 0;
sort(v.begin(),v.end());
for(int i=0;i<n;i++)
{
g = gcd(g,v[i].second);
}
n = mint; t = 0;
while(1)
{
for(int i=0;i<v.size();i++)
{
if(n % v[i].second ==0)
{
t++;
cout<<v[i].first<<endl;
if(t==k)
{
exit = 1;
break;
}
}
}
n += g;
if(exit) break;
}
}
| [
"ABHISHEK SOMANI"
] | ABHISHEK SOMANI |
67997ce7d13f7f12fc7f5823ff674315cfbbf13a | d646a142359e832892e7593f8047d9d2fca09a7c | /Qt/Kholkovskii_Konstantin_CW/division.h | 5c690edb4e261deb089860631d84e6733a8fc450 | [] | no_license | gagask/MyCW-s | a481cfe76be07f3d148427125429369162299c94 | bcb7bf81b90c35c52bffc569ffa86d7bbed47269 | refs/heads/master | 2023-03-28T17:47:20.708263 | 2021-03-31T18:17:57 | 2021-03-31T18:17:57 | 353,442,640 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 563 | h | #ifndef DIVISION_H
#define DIVISION_H
#include <QDialog>
#include <QColor>
#include <QColorDialog>
#include <QDir>
#include <QFileDialog>
namespace Ui {
class Division;
}
class Division : public QDialog
{
Q_OBJECT
public:
explicit Division(QWidget *parent = 0);
~Division();
void load(int* n, int* m, QColor* color, int *fatness, bool* flag, QString *path);
private slots:
void on_pushButton_clicked();
void on_pushButton_2_clicked();
private:
Ui::Division *ui;
QColor color;
QString file_path;
};
#endif // DIVISION_H
| [
"[email protected]"
] | |
432c89cf8445ff85e99777b6b1d05dcdfce1eba1 | e1ea9690b62861f53a9933c4e1e1beb92153e422 | /utf8.cpp | 4c0ea21d863ec74dc0028fc62c675f1dbc3f89d1 | [
"MIT"
] | permissive | drcforbin/librw | a5c009fca197c71c61365d726141f042e091d102 | 1f6361efe5594f559ab9ebe25c492aa3047011c1 | refs/heads/master | 2021-06-24T10:14:22.437655 | 2021-05-04T17:44:27 | 2021-05-04T17:44:27 | 222,605,138 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 7,467 | cpp | #include "rw/logging.h"
#include "rw/utf8.h"
#include <array>
#include <cstring>
#include <langinfo.h>
#include <tuple>
#define LOGGER() (rw::logging::get("rwte-main"))
namespace rw::utf8 {
void set_locale() {
// set/check utf8 locale. locale is needed for C funcs
// like wcwidth/wcswidth later
std::setlocale(LC_ALL, "");
{
auto item = nl_langinfo(CODESET);
if (strcmp(item, "UTF-8") != 0) {
LOGGER()->warn("need UTF-8 local (LC_CTYPE) but have {}", item);
}
}
}
} // namespace rw::utf8
// todo: enum classes
enum utf8_result
{
UTF8_RES_CONTINUE,
UTF8_RES_COMPLETE,
UTF8_RES_INVALID
};
enum utf8_state_enum
{
UTF8_GROUND,
UTF8_U3_B2_E0,
UTF8_U3_B2_ED,
UTF8_U4_B3_F0,
UTF8_U4_B3_F4,
UTF8_TAIL1,
UTF8_TAIL2,
UTF8_TAIL3
};
enum utf8_action_enum
{
ACT_NOOP,
ACT_EMIT,
ACT_SET_BYTE1_EMIT,
ACT_SET_BYTE2,
ACT_SET_BYTE3,
ACT_SET_BYTE2_TOP,
ACT_SET_BYTE3_TOP,
ACT_SET_BYTE4_TOP,
ACT_INVALID
};
constexpr unsigned char transition(unsigned char action, unsigned char state)
{
return action << 4 | state;
}
constexpr auto make_transitions()
{
std::array<std::array<unsigned char, 256>, 8> arr{};
unsigned char invalid_val = transition(ACT_INVALID, UTF8_GROUND);
for (int i = 0; i < 256; i++) {
if (0x00 <= i && i <= 0x7F)
arr[UTF8_GROUND][i] = transition(ACT_EMIT, UTF8_GROUND);
else if (0xC2 <= i && i <= 0xDF)
arr[UTF8_GROUND][i] = transition(ACT_SET_BYTE2_TOP, UTF8_TAIL1);
else if (0xE0 <= i && i <= 0xE0)
arr[UTF8_GROUND][i] = transition(ACT_NOOP, UTF8_U3_B2_E0);
else if (0xE1 <= i && i <= 0xEC)
arr[UTF8_GROUND][i] = transition(ACT_SET_BYTE3_TOP, UTF8_TAIL2);
else if (0xED <= i && i <= 0xED)
arr[UTF8_GROUND][i] = transition(ACT_SET_BYTE3_TOP, UTF8_U3_B2_ED);
else if (0xEE <= i && i <= 0xEF)
arr[UTF8_GROUND][i] = transition(ACT_SET_BYTE3_TOP, UTF8_TAIL2);
else if (0xF0 <= i && i <= 0xF0)
arr[UTF8_GROUND][i] = transition(ACT_SET_BYTE4_TOP, UTF8_U4_B3_F0);
else if (0xF1 <= i && i <= 0xF3)
arr[UTF8_GROUND][i] = transition(ACT_SET_BYTE4_TOP, UTF8_TAIL3);
else if (0xF4 <= i && i <= 0xF4)
arr[UTF8_GROUND][i] = transition(ACT_SET_BYTE4_TOP, UTF8_U4_B3_F4);
else
arr[UTF8_GROUND][i] = invalid_val;
if (0xA0 <= i && i <= 0xBF)
arr[UTF8_U3_B2_E0][i] = transition(ACT_SET_BYTE2, UTF8_TAIL1);
else
arr[UTF8_U3_B2_E0][i] = invalid_val;
if (0x80 <= i && i <= 0x9F)
arr[UTF8_U3_B2_ED][i] = transition(ACT_SET_BYTE2, UTF8_TAIL1);
else
arr[UTF8_U3_B2_ED][i] = invalid_val;
if (0x90 <= i && i <= 0xBF)
arr[UTF8_U4_B3_F0][i] = transition(ACT_SET_BYTE3, UTF8_TAIL2);
else
arr[UTF8_U4_B3_F0][i] = invalid_val;
if (0x80 <= i && i <= 0x8F)
arr[UTF8_U4_B3_F4][i] = transition(ACT_SET_BYTE3, UTF8_TAIL2);
else
arr[UTF8_U4_B3_F4][i] = invalid_val;
if (0x80 <= i && i <= 0xBF)
arr[UTF8_TAIL1][i] = transition(ACT_SET_BYTE1_EMIT, UTF8_GROUND);
else
arr[UTF8_TAIL1][i] = invalid_val;
if (0x80 <= i && i <= 0xBF)
arr[UTF8_TAIL2][i] = transition(ACT_SET_BYTE2, UTF8_TAIL1);
else
arr[UTF8_TAIL2][i] = invalid_val;
if (0x80 <= i && i <= 0xBF)
arr[UTF8_TAIL3][i] = transition(ACT_SET_BYTE3, UTF8_TAIL2);
else
arr[UTF8_TAIL3][i] = invalid_val;
}
return arr;
}
constexpr auto UTF8_TRANSITIONS = make_transitions();
class Utf8Decoder
{
public:
constexpr std::pair<utf8_result, char32_t> feed(unsigned char b);
private:
char32_t m_codepoint = 0;
utf8_state_enum m_state = UTF8_GROUND;
};
constexpr std::pair<utf8_result, char32_t> Utf8Decoder::feed(unsigned char b)
{
auto chg = UTF8_TRANSITIONS[m_state][b];
auto action = static_cast<utf8_action_enum>((chg & 0xF0) >> 4);
auto newstate = static_cast<utf8_state_enum>(chg & 0x0F);
auto res = UTF8_RES_CONTINUE;
char32_t cp = 0;
switch (action) {
case ACT_NOOP:
break;
case ACT_EMIT:
res = UTF8_RES_COMPLETE;
cp = b;
m_codepoint = 0;
break;
case ACT_SET_BYTE1_EMIT:
m_codepoint |= static_cast<char32_t>(b & 0b00111111);
res = UTF8_RES_COMPLETE;
cp = m_codepoint;
m_codepoint = 0;
break;
case ACT_SET_BYTE2:
m_codepoint |= (static_cast<char32_t>(b & 0b00111111) << 6);
break;
case ACT_SET_BYTE3:
m_codepoint |= (static_cast<char32_t>(b & 0b00111111) << 12);
break;
case ACT_SET_BYTE2_TOP:
m_codepoint |= (static_cast<char32_t>(b & 0b00011111) << 6);
break;
case ACT_SET_BYTE3_TOP:
m_codepoint |= (static_cast<char32_t>(b & 0b00001111) << 12);
break;
case ACT_SET_BYTE4_TOP:
m_codepoint |= (static_cast<char32_t>(b & 0b00000111) << 18);
break;
case ACT_INVALID:
res = UTF8_RES_INVALID;
cp = utf_invalid;
m_codepoint = 0;
break;
}
m_state = newstate;
return {res, cp};
}
std::size_t utf8encode(char32_t cp, char* c)
{
if (cp <= 0x0000007F) {
// 0xxxxxxx
c[0] = cp & 0b01111111;
return 1;
} else if (cp <= 0x000007FF) {
// 110xxxxx
c[0] = 0b11000000 | (cp >> 6 & 0b00011111);
// 10xxxxxx
c[1] = 0b10000000 | (cp & 0b00111111);
return 2;
} else if (cp <= 0x0000FFFF) {
if (0x0000D800 <= cp && cp <= 0x0000DFFF) {
// excluded range
return 0;
} else {
// 1110xxxx
c[0] = 0b11100000 | (cp >> 12 & 0b00001111);
// 10xxxxxx
c[1] = 0b10000000 | (cp >> 6 & 0b00111111);
// 10xxxxxx
c[2] = 0b10000000 | (cp & 0b00111111);
return 3;
}
} else if (cp <= 0x0010FFFF) {
// 11110xxx
c[0] = 0b11110000 | (cp >> 18 & 0b00000111);
// 10xxxxxx
c[1] = 0b10000000 | (cp >> 12 & 0b00111111);
// 10xxxxxx
c[2] = 0b10000000 | (cp >> 6 & 0b00111111);
// 10xxxxxx
c[3] = 0b10000000 | (cp & 0b00111111);
return 4;
}
return 0;
}
std::size_t utf8size(std::string_view c)
{
auto [sz, cp] = utf8decode(c);
if (cp != utf_invalid) {
return sz;
} else {
return -1;
}
}
std::pair<std::size_t, char32_t> utf8decode(std::string_view c)
{
if (!c.empty()) {
Utf8Decoder dec;
utf8_result state;
std::size_t i = 0;
char32_t cp = utf_invalid;
while (i < c.size()) {
std::tie(state, cp) = dec.feed(c[i]);
if (state == UTF8_RES_CONTINUE)
i++;
else
return {i + 1, cp};
}
}
return {0, utf_invalid};
}
bool utf8contains(std::string_view s, char32_t cp)
{
while (!s.empty()) {
auto [len, curr] = utf8decode(s);
if (!len)
break;
if (curr == cp)
return true;
s = s.substr(len);
}
return false;
}
| [
"[email protected]"
] | |
e11223f3fed4ae40700177c6a52497006e9eb2f6 | b5881a2a068172e356c308ca469b8670e44c3ea6 | /ortools/math_opt/validators/enum_sets.h | 8a1d8ed09167573a1d5f6463ad31d189b3b30b5a | [
"Apache-2.0",
"LicenseRef-scancode-generic-cla",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | bhoeferlin/or-tools | b675fecece9a788cae58ab87f2ba774b9b307728 | dfdcfb58d7228fa0ae6d0182ba9b314c7122519f | refs/heads/master | 2022-02-21T16:38:31.999088 | 2022-02-08T14:27:44 | 2022-02-08T14:27:44 | 141,839,304 | 0 | 0 | Apache-2.0 | 2020-11-06T17:03:34 | 2018-07-21T19:08:59 | C++ | UTF-8 | C++ | false | false | 1,900 | h | // Copyright 2010-2021 Google LLC
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// This header defines sets of enum values that can be used for parametrized
// tests.
#ifndef OR_TOOLS_MATH_OPT_VALIDATORS_ENUM_SETS_H_
#define OR_TOOLS_MATH_OPT_VALIDATORS_ENUM_SETS_H_
#include <string>
#include <tuple>
#include <vector>
#include "gtest/gtest.h"
#include "ortools/math_opt/result.pb.h"
#include "ortools/math_opt/solution.pb.h"
namespace operations_research {
namespace math_opt {
// Returns all valid feasibility statuses (i.e does not include UNSPECIFIED).
std::vector<FeasibilityStatusProto> AllFeasibilityStatuses();
// Returns all valid solution statuses (i.e does not include UNSPECIFIED).
std::vector<SolutionStatusProto> AllSolutionStatuses();
// Printing utilities for parametrized tests.
void PrintTo(const SolutionStatusProto& proto, std::ostream* os);
void PrintTo(const FeasibilityStatusProto& proto, std::ostream* os);
void PrintTo(const std::tuple<SolutionStatusProto, SolutionStatusProto>& proto,
std::ostream* os);
void PrintTo(
const std::tuple<FeasibilityStatusProto, FeasibilityStatusProto>& proto,
std::ostream* os);
void PrintTo(
const std::tuple<SolutionStatusProto, FeasibilityStatusProto>& proto,
std::ostream* os);
} // namespace math_opt
} // namespace operations_research
#endif // OR_TOOLS_MATH_OPT_VALIDATORS_ENUM_SETS_H_
| [
"[email protected]"
] | |
4e32e362f4bef5a0d4a16fa4c115d596dcaf903a | 04040f294a3df9b11d769f51b77d388c3f2047cb | /Engine/src/independent/layers/layerManager.cpp | f2e5a4c8f2827ef8cc6fe7fb5c010271d57ed554 | [] | no_license | DanBullin/LoneWilderness | 1b6c50e05f547bdb94b9a67aaf73cfda7abc0a59 | f5474cbc4ec5d73fa9b641eed47548c9c6422789 | refs/heads/master | 2023-04-10T10:52:10.322151 | 2021-05-07T06:55:09 | 2021-05-07T06:55:09 | 325,267,055 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,577 | cpp | /*! \file layerManager.cpp
*
* \brief A layer manager which manages layers
*
* \author Daniel Bullin
*
*/
#include "independent/layers/layerManager.h"
#include "independent/systems/components/scene.h"
#include "independent/systems/systems/log.h"
#include "independent/systems/systems/resourceManager.h"
namespace Engine
{
//! LayerManager()
/*!
\param scene a Scene* - A pointer to the scene
*/
LayerManager::LayerManager(Scene* scene)
{
m_layers.reserve(ResourceManager::getConfigValue(Config::MaxLayersPerScene));
if (scene)
m_attachedScene = scene;
else
ENGINE_ERROR("[LayerManager::LayerManager] An invalid scene was provided.");
}
//! ~LayerManager()
LayerManager::~LayerManager()
{
if (getParentScene())
{
// Delete all layers
ENGINE_INFO("[LayerManager::~LayerManager] Deleting layer manager attached to {0}.", getParentScene()->getName());
m_attachedScene = nullptr;
}
else
ENGINE_INFO("[LayerManager::~LayerManager] Deleting layer manager which has no scene attached.");
// Go through the list in reverse
for (std::vector<Layer*>::reverse_iterator i = m_layers.rbegin(); i != m_layers.rend(); ++i)
{
// Stop the layer
if ((*i))
{
// Call the onDetach function
(*i)->onDetach();
if ((*i)) delete (*i);
}
else
ENGINE_ERROR("[LayerManager::~LayerManager] Layer is a null pointer.");
}
// All layers have been detached, clear the list
m_layers.clear();
}
//! attachLayer()
/*!
\param newLayer a Layer* - A pointer to the layer
*/
void LayerManager::attachLayer(Layer* newLayer)
{
if (!newLayer)
{
ENGINE_ERROR("[LayerManager::attachLayer] An invalid layer was provided.");
return;
}
// Loop through each layer and check its name, if it exists, just exit out of function
for (auto& layer : m_layers)
{
if (layer)
{
if (layer->getLayerName() == newLayer->getLayerName())
{
ENGINE_ERROR("[LayerManager::attachLayer] Layer name is already taken. Name: {0}.", layer->getLayerName());
return;
}
}
}
// Add layer to the list
m_layers.push_back(newLayer);
// Update the layer's manager
newLayer->setLayerManager(this);
// Call the layer's onAttach function
newLayer->onAttach();
}
//! getLayer()
/*!
\param layerName a const std::string& - The name of the layer
\return a Layer* - A pointer to the layer
*/
Layer* LayerManager::getLayer(const std::string& layerName)
{
// Loop through each layer and check its name
for (auto& layer : m_layers)
{
if (layer)
{
if (layer->getLayerName() == layerName)
return layer;
}
}
ENGINE_ERROR("[LayerManager::getLayer] Could not get layer as layer name could not be found. Name: {0}, Scene: {1}.", layerName, getParentScene()->getName());
return nullptr;
}
//! getLayers()
/*!
\return a std::vector<Layer*>& - A reference to the list of layers
*/
std::vector<Layer*>& LayerManager::getLayers()
{
return m_layers;
}
//! layerExists()
/*!
\param layer a Layer* - A pointer to the layer
\return a bool - Does the layer exist in the layer list
*/
bool LayerManager::layerExists(Layer* layer)
{
// Loop through each layer and check its name
for (auto& layerElement : m_layers)
{
if (layer)
{
if (layerElement->getLayerName() == layer->getLayerName())
return true;
}
else
ENGINE_ERROR("[LayerManager::layerExists] An invalid layer was provided.");
}
return false;
}
//! getParentScene()
/*!
\return a Scene* - The parent scene
*/
Scene* LayerManager::getParentScene()
{
return m_attachedScene;
}
//! onUpdate()
/*!
\param timestep a const float - The timestep
\param totalTime a const float - The total time of the application
*/
void LayerManager::onUpdate(const float timestep, const float totalTime)
{
// Update all layers
for (auto& layer : m_layers)
{
if (layer)
{
if (layer->getActive())
layer->onUpdate(timestep, totalTime);
}
}
}
//! printLayerManagerDetails()
void LayerManager::printLayerManagerDetails()
{
ENGINE_TRACE("Layer Manager Details");
ENGINE_TRACE("============================================");
ENGINE_TRACE("Layer List Size: {0}", m_layers.size());
if(m_attachedScene)
ENGINE_TRACE("Attached to scene: {0}", getParentScene()->getName());
else
ENGINE_TRACE("Attached to scene: NULL");
ENGINE_TRACE("============================================");
}
//! printLayerDetails()
void LayerManager::printLayerDetails()
{
for (auto& layer : m_layers)
{
if(layer) layer->printLayerDetails();
}
}
} | [
"[email protected]"
] | |
d68b6b34510cd94b3c34aee9d1f2cf71b2806c44 | 8372963cc5021f71a3def3a2a540b5d5d4445eb8 | /src/spider/IfengSpider.cpp | 255ed7f1601ad6e3d6ce915db4087f49136b0fb4 | [] | no_license | xdis/sniper | 1a36f193f9e2a683271032c2a79bf30b5a501aae | 13f45a8f37d3cea33502993d65a37b565bf17b22 | refs/heads/master | 2020-07-07T07:23:29.395044 | 2019-08-19T20:08:03 | 2019-08-19T20:08:03 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,667 | cpp | #include "IfengSpider.h"
IfengSpider::IfengSpider(wxString strUrl):StockSpider(strUrl)
{
}
IfengSpider::~IfengSpider()
{
//dtor
}
bool IfengSpider::Run()
{
wxString strUrlBase = _T("http://app.finance.ifeng.com/hq/list.php?type=stock_a&class=");
wxString response;
//沪A
wxString strSH = strUrlBase+_T("ha");
http(strSH,response,wxFONTENCODING_UTF8);
Parse(response,1);
//深A
wxString strSZ = strUrlBase+_T("sa");
http(strSZ,response,wxFONTENCODING_UTF8);
Parse(response,2);
//创业板
wxString strCYB = strUrlBase+_T("gem");
http(strCYB,response,wxFONTENCODING_UTF8);
Parse(response,3);
return true;
}
bool IfengSpider::Parse(wxString& strResponse,short iTag)
{
wxRegEx r(_T("<li>[\\r\\n\\s]*<a\\s+href=\"[^\"]+?\"\\s+target=\"_blank\">"\
"([^(]+?)\\((\\d+)\\)</a>[\\r\\n\\s]*</li>"),wxRE_ADVANCED);
while(r.Matches(strResponse)){
size_t start, len;
r.GetMatch(&start, &len, 0);
wxString code = r.GetMatch(strResponse,1);
wxString name= r.GetMatch(strResponse,2);
std::cout<<"code = "<<code<<std::endl;
std::cout<<"name = "<<name<<std::endl;
std::wcout<<"market = "<<MARKET_NAME_ZH(iTag)<<std::endl;
strResponse = strResponse.Mid(start + len);
}
return true;
}
void IfengSpider::Dump()
{
wxVector<ShareBrief>::const_iterator it;
for(it=m_shares.begin(); it!=m_shares.end();it++){
std::wcout<<"股票代号: "<<it->code<<std::endl;
std::wcout<<"股票名称: "<<it->name<<std::endl;
std::wcout<<"股票市场: "<<MARKET_NAME_ZH(it->market)<<std::endl;
}
}
| [
"[email protected]"
] | |
395ac3d595e5b0a9d5798165d37ca59f2237ed16 | 0eff74b05b60098333ad66cf801bdd93becc9ea4 | /second/download/curl/gumtree/curl_repos_function_2171_last_repos.cpp | 7529e9911562d6da2ec6a0aae115dd3117b67df4 | [] | 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 | 110 | cpp | CURLcode Curl_pp_disconnect(struct pingpong *pp)
{
free(pp->cache);
pp->cache = NULL;
return CURLE_OK;
} | [
"[email protected]"
] | |
b1437c3ad3418598a743fe30a634a1a9faf49f5f | 09bc09a800c069fccb89f36a6aedc1e5c69b822c | /cpp/typeinfo/type_info.h | 6df75511cd02195081137c6dd1d3f4e7efb23a36 | [] | no_license | anonymouss/my-exercises | 8556e880ee8125290f3cfb3787f066b5fb968315 | a30b62ab8f7010eed542d9e945ef617e6815ee01 | refs/heads/master | 2021-06-13T02:48:27.472430 | 2021-05-01T06:34:00 | 2021-05-01T06:34:00 | 162,083,938 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,226 | h | #ifndef __TYPE_INFO_H__
#define __TYPE_INFO_H__
#include <typeinfo>
#include <iostream>
#include <cstdlib>
#include <string>
#include <sstream>
#include <type_traits>
#include <cxxabi.h>
// reference: https://www.cnblogs.com/zfyouxi/p/5060288.html
template <typename T, bool IsBase = false>
struct TypeInfo;
class Output {
public:
explicit Output(std::string &str) : mString(str) {}
Output &operator()() { return (*this); }
template <typename T, typename... Args>
Output &operator()(const T &o, const Args&... args) {
out(o);
return operator()(args...);
}
Output &compact() {
mIsCompact = true;
return (*this);
}
private:
bool mIsCompact = true;
std::string &mString;
template <typename T>
bool isEmpty(const T &) { return false; }
bool isEmpty(const char *str) {
return (!str) || str[0] == 0;
}
template <typename T>
void out(const T &o) {
if (isEmpty(o)) return;
if (!mIsCompact) mString += " ";
using U = std::ostringstream;
mString += (U() << o).str();
mIsCompact = false;
}
};
template <bool>
struct Bracket {
Output &out;
Bracket(Output &o, const char *str = nullptr) : out(o) {
out("(").compact();
}
virtual ~Bracket() {
out.compact()(")");
}
};
template <>
struct Bracket<false> {
Bracket(Output &o, const char *str = nullptr) {
o(str);
}
};
template <std::size_t N = 0>
struct Bound {
Output &out;
Bound(Output &o) : out(o) {}
virtual ~Bound() {
if constexpr(N == 0) {
out("[]");
} else {
out("[").compact()(N).compact()("]");
}
}
};
template <bool, typename... P>
struct Parameter;
template <bool IsStart>
struct Parameter<IsStart> {
Output &out;
Parameter(Output &o) : out(o) {}
virtual ~Parameter() {
Bracket<IsStart>{out};
}
};
template <bool IsStart, typename P1, typename... P>
struct Parameter<IsStart, P1, P...> {
Output out;
Parameter(Output &o) : out(o) {}
virtual ~Parameter() {
[this](Bracket<IsStart>&&) {
TypeInfo<P1> { out };
Parameter<false, P...> { out.compact() };
} (Bracket<IsStart> { out, "," });
}
};
template <typename T, bool IsBase>
struct TypeInfo {
TypeInfo(const Output &o) : out(o) {
char *realName = abi::__cxa_demangle(typeid(T).name(), nullptr, nullptr, nullptr);
out(realName);
std::free(realName);
}
Output out;
};
#define TYPE_INFO__(TYPE) \
template <typename T, bool IsBase> \
struct TypeInfo<T TYPE, IsBase> : TypeInfo<T, true> { \
using base_t = TypeInfo<T, true>; \
using base_t::out; \
TypeInfo(const Output &o) : base_t(o) { out(#TYPE); } \
};
TYPE_INFO__(const)
TYPE_INFO__(volatile)
TYPE_INFO__(const volatile)
TYPE_INFO__(&)
TYPE_INFO__(&&)
TYPE_INFO__(*)
#define TYPE_INFO_ARRAY__(CV, BOUND, ...) \
template <typename T, bool IsBase __VA_ARGS__> \
struct TypeInfo<T CV [BOUND], IsBase> : TypeInfo<T CV, !std::is_array<T>::value> { \
using base_t = TypeInfo<T CV, !std::is_array<T>::value>; \
using base_t::out; \
Bound<BOUND> bound; \
Bracket<IsBase> bracket; \
TypeInfo(const Output &o) : base_t(o), bound(out), bracket(out) {} \
};
#define TYPE_INFO_ARRAY_CV__(BOUND, ...) \
TYPE_INFO_ARRAY__(, BOUND, ,##__VA_ARGS__) \
TYPE_INFO_ARRAY__(const, BOUND, ,##__VA_ARGS__) \
TYPE_INFO_ARRAY__(volatile, BOUND, ,##__VA_ARGS__) \
TYPE_INFO_ARRAY__(const volatile, BOUND, ,##__VA_ARGS__)
#define TYPE_INFO_PLACEHOLDER
TYPE_INFO_ARRAY_CV__(TYPE_INFO_PLACEHOLDER)
TYPE_INFO_ARRAY_CV__(N, std::size_t N)
template <typename T, bool IsBase, typename... P>
struct TypeInfo<T(P...), IsBase> : TypeInfo<T, true> {
using base_t = TypeInfo<T, true>;
using base_t::out;
Parameter<true, P...> parameter;
Bracket<IsBase> bracket;
TypeInfo(const Output &o) : base_t(o), parameter(out), bracket(out) {}
};
/*
template <typename T, bool IsBase, typename C, typename... P>
struct TypeInfo<T(C::*)(P...), IsBase> : TypeInfo<T(P...), true> {
using base_t = TypeInfo<T(P...), true>;
using base_t::out;
TypeInfo(const Out &out) base_t(o) {
TypeInfo<C>{out};
out.compact()("::");
}
};
*/
struct AtDestruct {
Output &out;
const char *str;
AtDestruct(Output &o, const char *s = nullptr) : out(o), str(s) {}
virtual ~AtDestruct() { out(str); }
void setStr(const char *s = nullptr) { str = s; }
};
#define TYPE_INFO_MEM_FUNC__(...) \
template <typename T, bool IsBase, typename C, typename... P> \
struct TypeInfo<T(C::*)(P...) __VA_ARGS__, IsBase> { \
AtDestruct ad; \
TypeInfo<T(P...), true> base; \
Output &out = base.out; \
TypeInfo(const Output &o) : ad(base.out), base(o) { \
ad.setStr(#__VA_ARGS__); \
TypeInfo<C>{out}; \
out.compact()("::"); \
} \
};
TYPE_INFO_MEM_FUNC__()
TYPE_INFO_MEM_FUNC__(const)
TYPE_INFO_MEM_FUNC__(volatile)
TYPE_INFO_MEM_FUNC__(const volatile)
template <typename T>
inline std::string my_type_info() {
std::string str;
TypeInfo<T>{Output(str)};
return str;
}
#endif // __TYPE_INFO_H__ | [
"[email protected]"
] | |
c3a65a9b130a68432123561fc027c50636d0ffea | 6a70b63a2daac5b3cc8fa65b7429c6bd28b16479 | /Assignments/Codes/Filtering/Autofocus/solutions/examples/blur_example.cpp | 3f500eff73b06d0253614af00281e8e838bb1c00 | [] | no_license | mpoullet/NumCSE | 790120fc36643f8f201c9bcfbe7ca7a8e9f66e69 | b03bb0e750c0040329a2df289284a2d680b8e432 | refs/heads/master | 2020-03-30T04:12:25.445889 | 2018-06-15T18:21:34 | 2018-06-15T18:22:28 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 891 | cpp | #include <iostream>
#include <Eigen/Dense>
#include "timer.h"
#include "conv.hpp"
using namespace Eigen;
int main(int argc, char **argv) {
if(argc <= 1) {
MatrixXd A(5,5);
MatrixXd B(3,3);
A << 1,2,3,4,5,
4,5,6,7,8,
7,8,9,10,11,
1,1,1,1,1,
2,2,2,2,2;
B << 0,1,0,
1,2,1,
0,1,1;
std::cout << conv2(A, B);
} else {
unsigned int n = std::stoi(argv[1]);
MatrixXd A = MatrixXd::Random(n, n);
unsigned int m = n;
if(argc > 2) m = std::stoi(argv[2]);
MatrixXd B = MatrixXd::Random(m, m);
Timer t;
t.start();
MatrixXd C = conv2(A,B);
t.stop();
std::cout << "Elapsed:" << t.duration() << "s" << std::endl;
std::cout << "Norm:" << C.norm() << std::endl;
}
}
| [
"[email protected]"
] | |
a07ee7aeee003abfc6889461dbaf0d00b7de0d45 | e2ba7f68252161cfbfb2fb8c62fce134e6836c0a | /Duck.h | c9ff597896b4616e71ac9628e247f2b47aff53e5 | [] | no_license | ShawnJaffe/Duck-Life | 098c207f0f9d6c9dba4d1868afef4cc69222bbe3 | 81aafeb5a630975988f0dd07e7ffcaaec78c8aa7 | refs/heads/main | 2023-03-14T01:58:50.493431 | 2021-03-08T23:20:02 | 2021-03-08T23:20:02 | 345,817,750 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 983 | h | // CS1300 Spring 2020
// Author: Shawn Jaffe
// Recitation: 104 - Dhanendra Soni
// Project3 : Duck Life Game
#include <iostream>
#ifndef Duck_H
#define Duck_H
using namespace std;
class Duck{
private:
string name;
int running;
int swimming;
int flying;
int energy;
int coins;
public:
Duck(); //constructor
Duck(string, int, int, int, int, int); //constructor
int getRunning(); //getter
int getSwimming(); //getter
int getFlying(); //getter
int getEnergy(); //getter
int getCoins(); //getter
string getName(); //getter
void setRunning(int); //setter
void setSwimming(int); //setter
void setFlying(int); //setter
void setEnergy(int); //setter
void setCoins(int); //setter
void setName(string); //setter
void showStats();
string chooseColor();
int shop(int);
};
#endif | [
"[email protected]"
] | |
7ce0d908f753927f291dcacf82af128cdfc589ad | e7d32d176ec4be669f0091c4031c8707ccfcec42 | /DHT/DHT.ino | 6a3627bb20bf7b70354407ceb7e3bb3e5468f065 | [] | no_license | IanMaguithi/Arduino_Sketches | 411117eb1698bed9e3a3be39b4d30519f62c238b | 99d2aed8ab41ef429a15d34d565892d9d32ea336 | refs/heads/main | 2022-12-25T10:24:48.007532 | 2020-10-03T11:08:21 | 2020-10-03T11:08:21 | 294,173,716 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 593 | ino | #include <DHT.h>
#define Type DHT11
int sensePin=2, setTime=500, dt=2000;
DHT HT(sensePin,Type);
float humidity, tempC, tempF;
void setup() {
// put your setup code here, to run once:
Serial.begin(9600);
HT.begin();
delay(setTime);
}
void loop() {
// put your main code here, to run repeatedly:
humidity=HT.readHumidity();
tempC=HT.readTemperature();
tempF=HT.readTemperature(true);
Serial.print("Humidity: ");
Serial.print(humidity);
Serial.print(" Temperature C: ");
Serial.print(tempC);
Serial.print(" Temperature F: ");
Serial.println(tempF);
delay(dt);
}
| [
"[email protected]"
] | |
ff670d21d508198233e466db3ec8665e0d5a9557 | a6ab9fe3c17207d777c1b189d224f89ecb9e0258 | /LEngine/src/model/L3DMesh.cpp | 246d557b616893699263e810854e4c50c0d06026 | [
"MIT"
] | permissive | leafvmaple/LOpenGL | 88f59b38638199b0b0295a55fb160b4f563429bb | 58a696c2115078668ffe463c7d219de5f92c4203 | refs/heads/master | 2020-03-20T05:55:39.239603 | 2019-03-26T09:22:48 | 2019-03-26T09:22:48 | 137,231,545 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 8,985 | cpp | //
// L3DMesh.cpp
// LEngine
//
// Created by LeafMaple on 2018/07/05.
// Copyright © 2018 LeafMaple. All rights reserved.
//
#include <memory.h>
#include "L3DMesh.h"
#include "L3DMaterial.h"
#include "L3DShader.h"
#include "camera/L3DCamera.h"
#include "io/LFileReader.h"
L3DMesh::L3DMesh() :
m_pLMaterial(nullptr),
m_pLShader(nullptr),
m_nVertexArrObj(0),
m_dwNumVertices(0),
m_dwNumFaces(0)
{
m_matTrans = glm::mat4(1.0f);
}
L3DMesh::~L3DMesh()
{
}
const VertexFromatOffsetItem* L3DMesh::GetVertexFormat(GLuint dwFVF)
{
const VertexFromatOffsetItem *pReturn = NULL;
size_t uSize = sizeof(s_VertexFormat) / sizeof(VertexFromatOffsetItem);
size_t i = 0;
for (; i < uSize; i++)
{
if (s_VertexFormat[i].dwFVF == dwFVF)
break;
}
BOOL_ERROR_RETURN(i != uSize);
pReturn = &s_VertexFormat[i];
return pReturn;
}
GLuint L3DMesh::GetVertexStride(GLuint dwFVF)
{
GLuint dwStride = 0;
const VertexFromatOffsetItem *pVertexFromatItem = GetVertexFormat(dwFVF);
BOOL_ERROR_RETURN(pVertexFromatItem);
dwStride = pVertexFromatItem->dwDestOffset[pVertexFromatItem->dwNumElement - 1] +
pVertexFromatItem->dwDestStride[pVertexFromatItem->dwNumElement - 1];
return dwStride;
}
bool L3DMesh::LoadMesh(const char* cszFileName)
{
bool bResult = false;
bool bRetCode = false;
LMESH_DATA MeshData;
bRetCode = LoadMeshData(cszFileName, &MeshData);
BOOL_ERROR_EXIT(bRetCode);
bRetCode = CreateMesh(&MeshData);
BOOL_ERROR_EXIT(bRetCode);
m_pLShader = new L3DShader;
BOOL_ERROR_EXIT(m_pLShader);
bRetCode = m_pLShader->LoadShader("res/shader/default.vs", "res/shader/default.fs");
BOOL_ERROR_EXIT(bRetCode);
bRetCode = m_pLShader->UpdateShader();
BOOL_ERROR_EXIT(bRetCode);
char cszMtl[FILENAME_MAX];
strcpy(cszMtl, cszFileName);
strcpy(cszMtl + strlen(cszMtl) - 5, ".mtl");
if (LFileReader::IsExist(cszMtl))
{
m_pLMaterial = new L3DMaterial;
BOOL_ERROR_EXIT(m_pLMaterial);
bRetCode = m_pLMaterial->LoadLMaterial(cszMtl);
BOOL_ERROR_EXIT(bRetCode);
for (int i = 0; i < m_pLMaterial->GetTextureCount(); i++)
{
char szSLTexture[FILENAME_MAX];
sprintf(szSLTexture, "%s%02d", "slTexture", i + 1);
m_pLShader->SetInt(szSLTexture, i);
}
}
bResult = true;
Exit0:
return bResult;
}
bool L3DMesh::UpdateMesh(GLuint dwSubMesh)
{
if (m_pLMaterial)
m_pLMaterial->UpdateMaterial(dwSubMesh);
if (m_dwNumFaces)
{
glBindVertexArray(m_nVertexArrObj);
glDrawElements(GL_TRIANGLES, m_dwNumFaces, GL_UNSIGNED_SHORT, 0);
}
else
{
glBindVertexArray(m_nVertexArrObj);
glDrawArrays(GL_TRIANGLES, 0, m_dwNumVertices);
}
return true;
}
bool L3DMesh::SetTranslation(glm::mat4 matTrans)
{
m_matTrans = matTrans;
return true;
}
bool L3DMesh::UpdatePosition(L3DCamera *p3DCamera)
{
if (m_pLShader)
{
m_pLShader->SetMatrix("slViewMatrix", p3DCamera->GetViewMatrix());
m_pLShader->SetMatrix("slProjMatrix", p3DCamera->GetProjMatrix());
m_pLShader->SetMatrix("slModelMatrix", m_matTrans);
}
return true;
}
bool L3DMesh::LoadMeshData(const char* cszFileName, LMESH_DATA* pLMeshData)
{
bool bResult = false;
memset(pLMeshData, 0, sizeof(LMESH_DATA));
GLubyte* pbyMesh = NULL;
size_t uMeshLen = 0;
LFileReader::Reader(cszFileName, &pbyMesh, &uMeshLen);
GLubyte* pbyBufferHead = pbyMesh;
_MeshFileHead* pMeshFileHead = NULL;
pbyMesh = LFileReader::Convert(pbyMesh, pMeshFileHead);
BOOL_ERROR_EXIT(pMeshFileHead->dwFileMask == 0x4D455348);
BOOL_ERROR_EXIT(pMeshFileHead->dwVersion == 0);
_MeshHead* pMeshHead = NULL;
pbyMesh = LFileReader::Convert(pbyMesh, pMeshHead);
pLMeshData->dwNumVertices = pMeshHead->dwNumVertices;
pLMeshData->dwNumFaces = pMeshHead->dwNumFaces;
pLMeshData->dwNumSubset = pMeshHead->dwNumSubset;
if (pMeshHead->Blocks.PositionBlock)
{
LFileReader::Convert(pbyBufferHead + pMeshHead->Blocks.PositionBlock, pLMeshData->pPos, pMeshHead->dwNumVertices);
pLMeshData->dwMeshFVF |= L3DFVF_XYZ;
//pLMesh->BoundingBox.AddPosition(pMeshData->pPos, pMeshData->dwNumVertices);
}
if (pMeshHead->Blocks.NormalBlock)
{
LFileReader::Convert(pbyBufferHead + pMeshHead->Blocks.NormalBlock, pLMeshData->pNormals, pMeshHead->dwNumVertices);
pLMeshData->dwMeshFVF |= L3DFVF_NORMAL;
}
if (pMeshHead->Blocks.DiffuseBlock)
{
LFileReader::Convert(pbyBufferHead + pMeshHead->Blocks.DiffuseBlock, pLMeshData->pDiffuse, pMeshHead->dwNumVertices);
pLMeshData->dwMeshFVF |= L3DFVF_DIFFUSE;
}
if (pMeshHead->Blocks.TextureUVW1Block)
{
LFileReader::Convert(pbyBufferHead + pMeshHead->Blocks.TextureUVW1Block, pLMeshData->pUV1, pMeshHead->dwNumVertices);
pLMeshData->dwMeshFVF |= L3DFVF_TEX1;
//计算UVSizeMax
//BBox UVBox;
//UVBox.AddPosition(pMeshData->pUV1, pMeshHead->dwNumVertices);
//pMeshData->pUVSizeMax[0].x = fabs(UVBox.A.x) > fabs(UVBox.B.x) ? fabs(UVBox.A.x) : fabs(UVBox.B.x);
//pMeshData->pUVSizeMax[0].y = fabs(UVBox.A.y) > fabs(UVBox.B.y) ? fabs(UVBox.A.y) : fabs(UVBox.B.y);
}
if (pMeshHead->Blocks.FacesIndexBlock)
{
LFileReader::Convert(pbyBufferHead + pMeshHead->Blocks.FacesIndexBlock, pLMeshData->pFaceIndices, 3 * pMeshHead->dwNumFaces);
}
if (pMeshHead->Blocks.SubsetIndexBlock)
{
LFileReader::Convert(pbyBufferHead + pMeshHead->Blocks.SubsetIndexBlock, pLMeshData->pSubsetIndices, pMeshHead->dwNumFaces);
}
pLMeshData->pbyFileBuffer = pbyBufferHead;
bResult = true;
Exit0:
return bResult;
}
bool L3DMesh::CreateMesh(const LMESH_DATA* pLMeshData)
{
bool bResult = false;
bool bRetCode = false;
do
{
const VertexFromatOffsetItem *pVertexFormat = GetVertexFormat(pLMeshData->dwMeshFVF);
BOOL_ERROR_BREAK(pVertexFormat);
GLuint dwVertexStride = GetVertexStride(pLMeshData->dwMeshFVF);
GLubyte* pbyVertices = new GLubyte[pLMeshData->dwNumVertices * dwVertexStride];
for (GLuint i = 0; i < pLMeshData->dwNumVertices; i++)
{
GLubyte* pCurrentVertexData = pbyVertices + dwVertexStride * i;
for (GLuint j = 0; j < pVertexFormat->dwNumElement; j++)
{
const GLubyte* pCurrentSrc = *(reinterpret_cast<GLubyte* const*>(&pLMeshData->pPos) + pVertexFormat->dwSrcOffset[j]);
memcpy(pCurrentVertexData + pVertexFormat->dwDestOffset[j],
pCurrentSrc + pVertexFormat->dwSrcStride[j] * i,
pVertexFormat->dwDestStride[j]);
if (pVertexFormat->dwElementFVF[j] == L3DFVF_DIFFUSE)
{
const GLuint* pSrcDiffuse = reinterpret_cast<const GLuint*>(
pCurrentSrc + pVertexFormat->dwSrcStride[j] * i);
LCOLOR_RGBA_FLOAT* pDestDiffuse = reinterpret_cast<LCOLOR_RGBA_FLOAT*>(
pCurrentVertexData + pVertexFormat->dwDestOffset[j]);
*pDestDiffuse = L3DARGB_COLOR(*pSrcDiffuse);
}
}
}
glGenVertexArrays(1, &m_nVertexArrObj);
glBindVertexArray(m_nVertexArrObj);
m_dwNumVertices = pLMeshData->dwNumVertices;
GLuint nVertexBufObj = 0;
glGenBuffers(1, &nVertexBufObj);
glBindBuffer(GL_ARRAY_BUFFER, nVertexBufObj);
glBufferData(GL_ARRAY_BUFFER, m_dwNumVertices * dwVertexStride, pbyVertices, GL_STATIC_DRAW);
if (pLMeshData->dwNumFaces)
{
GLushort* pwIndices = new GLushort[pLMeshData->dwNumFaces * 3];
for (GLuint i = 0; i < pLMeshData->dwNumFaces; i++)
{
pwIndices[i * 3] = static_cast<GLushort>(pLMeshData->pFaceIndices[i * 3]);
pwIndices[i * 3 + 1] = static_cast<GLushort>(pLMeshData->pFaceIndices[i * 3 + 1]);
pwIndices[i * 3 + 2] = static_cast<GLushort>(pLMeshData->pFaceIndices[i * 3 + 2]);
}
m_dwNumFaces = pLMeshData->dwNumFaces * 3;
GLuint nElemBufObj = 0;
glGenBuffers(1, &nElemBufObj);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, nElemBufObj);
glBufferData(GL_ELEMENT_ARRAY_BUFFER, m_dwNumFaces * sizeof(GLushort), pwIndices, GL_STATIC_DRAW);
}
for (GLuint i = 0; i < pVertexFormat->dwNumElement; i++)
{
glVertexAttribPointer(i, pVertexFormat->dwDestStride[i] / 4,
GL_FLOAT, GL_FALSE, dwVertexStride,
(void*)pVertexFormat->dwDestOffset[i]);
glEnableVertexAttribArray(i);
}
bResult = true;
} while (0);
return bResult;
}
| [
"[email protected]"
] | |
fb7393419e8463f65a0ef269b953dc938c30c536 | 4269307ea30df5947b22164198789a086e469eca | /OOP_HW01_Template_NET2010/00_StudentWork/00_SimpleInteractiveSystem/mySystem_MonteCarlo.cpp | e5bcec008854fef1e02994c8fbab62c961b6cb54 | [] | no_license | oOIFOo/2016_spring_OOP | 88bd355d48d563753d653dafe4dba3df1de4773f | ff54be474b558384ce4f2493f52ac1c8bdca8de6 | refs/heads/master | 2020-05-09T21:53:12.715209 | 2019-04-15T08:52:31 | 2019-04-15T08:52:31 | 181,448,861 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,107 | cpp | //
// Instructor: Sai-Keung WONG
// Email: [email protected]
// [email protected]
//
// National Chiao Tung University, Taiwan
// Computer Science
// Date: 2016/02/27
//
#include "mySystem_MonteCarlo.h"
#include <iostream>
using namespace std;
#define MAX_SAMPLES 1000000
MONTE_CARLO_SYSTEM::MONTE_CARLO_SYSTEM( )
{
cout.precision(8);
//
mRadius = 5.0f;
mNumSamples = 100000;
computeSamples( );
}
void MONTE_CARLO_SYSTEM::askForInput( )
{
//
//Show the system name
//Ask to input the radius of the circle
//Ask to input the number of sample points
//Call computeSamples( ) to compute the sample points and pi
//
cout << "MONTE CARLO" << endl;
cout<<"input the radius"<<endl;
cout<<"input the number of sample points"<<endl;
computeSamples( );
mX.clear();
mY.clear();
}
void MONTE_CARLO_SYSTEM::computeSamples( )
{
//
//Compute the coordinates of the sample points.
//There are mNumSamples samples.
//Compute pi which is equal to:
// 4*(number of samples inside the circle / total samples)
//
int count , i;
float x , y;
double pi;
cin >> mRadius;
cin >> mNumSamples;
srand(time(NULL));
for(i = 0;i < mNumSamples;i++){
x = (float) ( (mRadius- (-mRadius) ) * (float)rand()/RAND_MAX );
y = (float) ( (mRadius- (-mRadius) ) * (float)rand()/RAND_MAX );
mX.push_back(x);
mY.push_back(y);
getSample( i , x , y);
if( ( (x*x) + (y*y) ) <= (mRadius) * (mRadius) ){
count++;
}
}
pi = (double)4*( (double)count / mNumSamples);
cout<<"pi is "<< pi << endl;
}
double MONTE_CARLO_SYSTEM::getRadius( ) const
{
//Return the radius of the circle
return mRadius;
}
int MONTE_CARLO_SYSTEM::getNumSamples( ) const
{
//Return the number of sample points
return mNumSamples;
}
bool MONTE_CARLO_SYSTEM::getSample(int sampleIndex, float &x, float &y) const
{
//
//Return the sample coordinates in (x, y).
//Return the boolean value indicating whether the sample lying inside the circle.
//
bool flgInside = false;
if( ( (x*x) + (y*y) ) <= (mRadius) * (mRadius) ){
flgInside = true;
}
x = mX[sampleIndex];
y = mY[sampleIndex];
return flgInside;
}
| [
"[email protected]"
] | |
958864004bf1e1fba5c65a8b666a1b351758aff0 | f61c5cbe165b3d37cd93528e70653930895d2144 | /SM/include/mtf/SM/LineTracker.h | 6d328dccd8f925ff8c72449d3566a875806edbb6 | [
"BSD-3-Clause"
] | permissive | huizee/MTF | 5fe26ac651c00ef4de751c8ac6ef40b983ebaf60 | 6e04023844b0f46161a95e0dbaf92769c4dc851f | refs/heads/master | 2021-01-19T13:56:10.512940 | 2017-02-17T05:02:44 | 2017-02-17T05:02:44 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,412 | h | #ifndef MTF_LINE_TRACKER_H
#define MTF_LINE_TRACKER_H
#include "CompositeBase.h"
#include "mtf/Macros/common.h"
#define LINE_GRID_SIZE_X 5
#define LINE_GRID_SIZE_Y 5
#define LINE_PATCH_SIZE 25
#define LINE_USE_CONSTANT_SLOPE false
#define LINE_USE_LS false
#define LINE_INTER_ALPHA_THRESH 0.1
#define LINE_INTRA_ALPHA_THRESH 0.05
#define LINE_RESET_POS false
#define LINE_RESET_TEMPLATE false
#define LINE_DEBUG_MODE false
#define INF_VAL 1e5
#define TINY_VAL 1e-5
#define SMALL_VAL 2
#define PI_RAD 3.14159265358979323846
_MTF_BEGIN_NAMESPACE
struct lineParams {
double m;
double c;
double c_diff;
double theta;
int is_vert;
lineParams(double _m = 0, double _c = 0, double _c_diff=0,
int _is_vert = 0) {
m = _m;
c = _c;
c_diff = _c_diff;
is_vert = _is_vert;
}
};
struct gridPoint {
double x;
double y;
double tracker_x;
double tracker_y;
double xx;
double xy;
double wt;
double wt_y;
double wt_x;
double alpha_wt[2];
double alpha[2];
double inter_alpha_diff[2];
double intra_alpha_diff[2];
int is_successful[2];
};
struct gridLine {
int no_of_pts;
lineParams *params;
gridPoint **pts;
gridPoint *start_pt;
gridPoint *end_pt;
int type;
int inited;
int is_successful;
gridLine();
~gridLine() {
if(inited) {
delete(params);
delete(pts);
}
}
void init(int no_of_pts, int type);
void assignAddrs(gridPoint *start_addr = nullptr, int offset_diff = 1);
void updateParams();
};
struct LineTrackerParams {
int grid_size_x, grid_size_y;
int patch_size;
int use_constant_slope;
int use_ls;
double inter_alpha_thresh;
double intra_alpha_thresh;
int reset_pos;
int reset_template;
int debug_mode;
LineTrackerParams(int grid_size_x, int grid_size_y,
int patch_size, bool use_constant_slope, bool use_ls,
double inter_alpha_thresh, double intra_alpha_thresh,
bool reset_pos, bool reset_template, bool debug_mode);
LineTrackerParams(const LineTrackerParams *params = nullptr);
};
class LineTracker : public CompositeBase {
public:
typedef LineTrackerParams ParamType;
ParamType params;
int corner_tracker_ids[4];
int frame_id;
cv::Point2d *tracker_pos;
cv::Point2d wt_mean_pt;
gridPoint *curr_grid_pts;
gridPoint *prev_grid_pts;
gridLine *curr_vert_lines;
gridLine *curr_horz_lines;
gridLine *prev_vert_lines;
gridLine *prev_horz_lines;
lineParams *mean_horz_params;
lineParams *mean_vert_params;
int is_initialized;
LineTracker(const vector<TrackerBase*> trackers,
const ParamType *line_params = nullptr);
~LineTracker(){}
void initialize(const cv::Mat& cv_corners) override;
void update() override;
void initGridPositions(const cv::Mat& cv_corners);
void updateAlpha(gridLine* curr_lines, gridLine* prev_lines,
int no_of_lines, int line_type);
int updateLineParamsLS(gridLine* curr_lines, gridLine* prev_lines, lineParams *mean_params,
int no_of_lines, int line_type);
int updateLineParamsWeightedLS(gridLine* curr_lines, gridLine* prev_lines, lineParams *mean_params,
int no_of_lines, int line_type);
void resetLineParamsToPrev(gridLine* curr_lines,
gridLine* prev_lines, int no_of_lines);
void resetLineParamsToMean(gridLine* curr_lines, gridLine* prev_lines, lineParams* mean_params,
int no_of_lines, int reset_c = 0);
void updateGridWithLineIntersections();
void updateDistanceWeights();
void resetTrackerStates();
void updateCVCorners();
};
_MTF_END_NAMESPACE
#endif | [
"[email protected]"
] | |
1e9b60bac9f57625e58d8afd15d2471bd6078619 | aa7ef1886eb0f90b5a2c50d2af44504dda1e5b69 | /src/ManualPage.cpp | 05a0d37eb5974b3982ad18978eaacbb373ccfe13 | [] | no_license | RileyMcCarthy/MaD_Firmware | 9314ab1f50c83a55051c4456016e548515e80e29 | 73b8886c68c3b1557c41f4f460742a6fa8c7c918 | refs/heads/master | 2023-03-30T05:51:51.896137 | 2021-04-05T18:22:16 | 2021-04-05T18:22:16 | 344,294,841 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,598 | cpp | #include "MaD.h"
static bool complete;
static MachineState localState;
static bool initialRender;
enum button_names
{
BUTTON_MOTION_MODE,
BUTTON_CONDITION,
BUTTON_NAVIGATION
};
static void buttonHandler(Button b)
{
switch (b.name)
{
case BUTTON_MOTION_MODE:
/* code */
break;
case BUTTON_CONDITION:
/* code */
break;
case BUTTON_NAVIGATION:
complete = true;
break;
default:
break;
}
}
void MAD::runManualPage()
{
complete = false;
initialRender = true;
display.drawSquareFill(0, 0, SCREEN_WIDTH - 1, SCREEN_HEIGHT - 1, BACKCOLOR);
display.setTextParameter1(RA8876_SELECT_INTERNAL_CGROM, RA8876_CHAR_HEIGHT_32, RA8876_SELECT_8859_1);
display.setTextParameter2(RA8876_TEXT_FULL_ALIGN_DISABLE, RA8876_TEXT_CHROMA_KEY_DISABLE, RA8876_TEXT_WIDTH_ENLARGEMENT_X2, RA8876_TEXT_HEIGHT_ENLARGEMENT_X2);
display.textColor(MAINTEXTCOLOR, BACKCOLOR);
char buf[50];
strcpy(buf, "Manual");
int titlex = SCREEN_WIDTH / 2 - strlen(buf) * 16;
int titley = 10;
display.putString(titlex, titley, buf);
display.setTextParameter1(RA8876_SELECT_INTERNAL_CGROM, RA8876_CHAR_HEIGHT_32, RA8876_SELECT_8859_1);
display.setTextParameter2(RA8876_TEXT_FULL_ALIGN_DISABLE, RA8876_TEXT_CHROMA_KEY_DISABLE, RA8876_TEXT_WIDTH_ENLARGEMENT_X1, RA8876_TEXT_HEIGHT_ENLARGEMENT_X1);
display.textColor(MAINTEXTCOLOR, BACKCOLOR);
strcpy(buf, "Information");
titley = 120;
titlex = SCREEN_WIDTH / 6 - strlen(buf) * 8;
display.putString(titlex, titley, buf);
display.drawLine(titlex, titley + 30, titlex + strlen(buf) * 16, titley + 30, MAINTEXTCOLOR);
display.textColor(MAINTEXTCOLOR, BACKCOLOR);
strcpy(buf, "Control");
titley = 300;
titlex = SCREEN_WIDTH / 6 - strlen(buf) * 8;
display.putString(titlex, titley, buf);
display.drawLine(titlex, titley + 30, titlex + strlen(buf) * 16, titley + 30, MAINTEXTCOLOR);
Button buttons[3];
buttons[0].name = BUTTON_MOTION_MODE;
buttons[0].xmin = SCREEN_WIDTH / 6 - 110;
buttons[0].xmax = buttons[0].xmin + 100;
buttons[0].ymin = 350;
buttons[0].ymax = buttons[0].ymin + 50;
buttons[0].onPress = buttonHandler;
buttons[1].name = BUTTON_CONDITION;
buttons[1].xmin = SCREEN_WIDTH / 6 + 10;
buttons[1].xmax = buttons[1].xmin + 100;
buttons[1].ymin = 350;
buttons[1].ymax = buttons[1].ymin + 50;
buttons[1].onPress = buttonHandler;
buttons[2].name = BUTTON_NAVIGATION;
buttons[2].xmin = SCREEN_WIDTH - 100;
buttons[2].xmax = buttons[2].xmin + 100;
buttons[2].ymin = 0;
buttons[2].ymax = buttons[2].ymin + 100;
buttons[2].onPress = buttonHandler;
display.drawSquareFill(buttons[0].xmin, buttons[0].ymin, buttons[0].xmax, buttons[0].ymax, COLOR65K_GREEN);
display.drawSquareFill(buttons[1].xmin, buttons[1].ymin, buttons[1].xmax, buttons[1].ymax, COLOR65K_RED);
display.bteMemoryCopyImage(navigationImg, SCREEN_WIDTH - navigationImg.width - 5, 5);
while (!complete)
{
MachineState currentState = machineState;
display.checkButtons(buttons, 3);
display.setTextParameter1(RA8876_SELECT_INTERNAL_CGROM, RA8876_CHAR_HEIGHT_16, RA8876_SELECT_8859_1);
display.setTextParameter2(RA8876_TEXT_FULL_ALIGN_DISABLE, RA8876_TEXT_CHROMA_KEY_DISABLE, RA8876_TEXT_WIDTH_ENLARGEMENT_X1, RA8876_TEXT_HEIGHT_ENLARGEMENT_X1);
int textcolor = 0;
int backcolor = 0;
int bordercolor = 0;
if ((localState.motion.status != currentState.motion.status) || initialRender)
{
switch (machineState.motion.status)
{
case Motion_Status::STATUS_DISABLED:
strcpy(buf, "DISABLED");
textcolor = COLOR65K_WHITE;
backcolor = COLOR65K_BLACK;
bordercolor = COLOR65K_GREEN;
break;
case Motion_Status::STATUS_ENABLED:
strcpy(buf, "ENABLED");
textcolor = COLOR65K_BLACK;
backcolor = COLOR65K_WHITE;
bordercolor = COLOR65K_GREEN;
break;
case Motion_Status::STATUS_RESTRICTED:
strcpy(buf, "RESTRICTED");
textcolor = COLOR65K_WHITE;
backcolor = COLOR65K_RED;
bordercolor = COLOR65K_DARKRED;
break;
default:
break;
}
display.drawSquareFill(buttons[0].xmin, buttons[0].ymin, buttons[0].xmax, buttons[0].ymax, bordercolor);
display.drawSquareFill(buttons[0].xmin + 5, buttons[0].ymin + 5, buttons[0].xmax - 5, buttons[0].ymax - 5, backcolor);
display.textColor(textcolor, backcolor);
display.putString(buttons[0].xmin + 50 - strlen(buf) * 4, buttons[0].ymin + 25 - 8, buf);
}
display.textColor(MAINTEXTCOLOR, BACKCOLOR);
strcpy(buf, "Relative Position: 0.00");
display.putString(SCREEN_WIDTH / 6 - strlen(buf) * 6, 160, buf);
strcpy(buf, "Relative Force: 0.00");
display.putString(SCREEN_WIDTH / 6 - strlen(buf) * 6, 190, buf);
strcpy(buf, "Absolute Position: 0.00");
display.putString(SCREEN_WIDTH / 6 - strlen(buf) * 6, 230, buf);
strcpy(buf, "Absolute Force: 0.00");
display.putString(SCREEN_WIDTH / 6 - strlen(buf) * 6, 260, buf);
clock.render();
if (initialRender)
{
initialRender = false;
}
localState = currentState;
}
runNavigationPage();
} | [
"[email protected]"
] | |
a4473a0f91221c2fb33e9b1f0ba68e384d81eb19 | 1ed3b78ce9619d3e806e260f62ed38c157088cb9 | /lab04.cpp | eba56d8ff1069986534b0a3b42d09847c3f3d511 | [] | no_license | singhchamp1234/CSE-100---Algorithm-Design-and-Analysis | 5e87cbe5119d354af82cd91d31ccd84d6e1ce738 | 3052dea2147ce3186aa36299bdde7d7b2e9a29a8 | refs/heads/master | 2020-12-03T09:39:20.176115 | 2020-01-01T22:06:31 | 2020-01-01T22:06:31 | 231,268,189 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,629 | cpp | //
// yourid.cpp
// ghghghghg
//
// Created by herman rai on 10/1/19.
// Copyright © 2019 herman rai. All rights reserved.
//
//
// main.cpp
// gggggg
//
// Created by herman rai on 9/29/19.
// Copyright © 2019 herman rai. All rights reserved.
//
#include<iostream>
using namespace std;
//MAX-HEAPIFY.A;i/
// 1 2 3 4 5 6 7 8 9
//10
//l D LEFT.i/
//r D RIGHT.i/
//if l A:heap-size and AŒl > AŒi
//largest D l else largest D i
//if r A:heap-size and AŒr > AŒlargest largest D r
//if largest ¤ i
//exchange AŒi with AŒlargest MAX-HEAPIFY.A;largest/
// pseudocode from page 150-155 of introduction to algorithms 3rd edition
void maxHeap(int array[], int n, int i) { // taking in - array, int n, and variable i
int largest = i; // declaring our largest variable to be equal to i
// now we need to calculate the left and right child of our largest value
int right = 2 * i+ 2; // this is how we would get our right value
int k; // this declaring the temporary value of k
int left = 2 * i + 1; // this is how we would get our left value
while (left < n && array[left] > array[largest]) { // if l is greater then its the largest
largest = left;
}
while (right < n && array[right] > array[largest]) { // if r is greater than its the largest
largest = right;
}
if (largest != i) {
// swapping begins
k = array[i];
array[i] = array[largest];
array[largest] = k;
maxHeap(array, n, largest);
}
}
void heapSort(int array[], int size) { // we are passing in the array and the total number of elements
int temp;
for (int i = size / 2 - 1; i >= 0; i--) // This step for the building process of maxheap
maxHeap(array, size, i);
for (int i = size - 1; i >= 0; i--) { // This step is for deleting element from max heap
// swapping below
temp = array[0];
array[0] = array[i];
array[i] = temp;
maxHeap(array, i, 0);
}
}
int main() {
int size; // declares size to be an integer
int arr[50000]; // declares and allow maximum value
int i; // declares i to be an integer
cin>>size; // takes input for size
for (i = 0; i < size; i++){ // increments one by one based upon the size
cin>>arr[i];
}
heapSort(arr, size); // calls heapSort function
for (i = 0; i < size; ++i)
cout<<arr[i]<<";"; // prints out the sorted array
}
| [
"[email protected]"
] | |
3f74ea58fbf7b0d15b56f842ce23212e704ce6b6 | c2501a3f6998ea7682a7049fa062a0a6c180aafc | /sparsity_driven_detector/src/OptimizationProblemFactory_MultiLayered.cpp | 05fdc1dba4e1b1d57d509455aa96a82d1bc0a767 | [
"MIT"
] | permissive | MatthiasMichael/SparsityDrivenDetector | a46734cd5f1c59105e6f2070ae8c594a82f77b2e | eb50e1e0caf6b097adc4ee670693a6af46f0fc8b | refs/heads/master | 2020-05-25T08:42:57.383415 | 2019-09-25T10:01:56 | 2019-09-25T10:01:56 | 187,718,374 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,272 | cpp | #include "OptimizationProblemFactory_MultiLayered.h"
#include "OptimizationProblem_MultiLayered.h"
OptimizationProblemFactory_MultiLayered::OptimizationProblemFactory_MultiLayered(WrapInDecorators wrap) :
OptimizationProblemFactory(wrap)
{
// empty
}
std::unique_ptr<OptimizationProblemFactory> OptimizationProblemFactory_MultiLayered::clone() const
{
return std::make_unique<OptimizationProblemFactory_MultiLayered>();
}
OptimizationProblemFactory::Parameters OptimizationProblemFactory_MultiLayered::getDefaultParameters() const
{
return Parameters{ 0.1f };
}
std::unique_ptr<IOptimizationProblem> OptimizationProblemFactory_MultiLayered::createProblemImpl(
const Dictionary & dict, const Parameters & param) const
{
return std::make_unique<OptimizationProblem_MultiLayered>(dict, param);
}
std::unique_ptr<OptimizationProblem> OptimizationProblemFactory_MultiLayered::createProblemForLoading() const
{
// Cannot call std::make_unique due to private default ctor
return std::unique_ptr<OptimizationProblem>(new OptimizationProblem_MultiLayered());
}
bool OptimizationProblemFactory_MultiLayered::operator==(const OptimizationProblemFactory & other) const
{
return dynamic_cast<const OptimizationProblemFactory_MultiLayered *>(&other) != nullptr;
}
| [
"[email protected]"
] | |
36b3907a81a5b492dd5f25b08b07722d7ab7a0ef | c776476e9d06b3779d744641e758ac3a2c15cddc | /examples/litmus/c/run-scripts/tmp_1/Z6.4+poreleaserelease+fencembonceonce+poonceacquire.c.cbmc_out.cpp | e014305b6c5985e4fd0fbd1f65f86223a7622740 | [] | no_license | ashutosh0gupta/llvm_bmc | aaac7961c723ba6f7ffd77a39559e0e52432eade | 0287c4fb180244e6b3c599a9902507f05c8a7234 | refs/heads/master | 2023-08-02T17:14:06.178723 | 2023-07-31T10:46:53 | 2023-07-31T10:46:53 | 143,100,825 | 3 | 4 | null | 2023-05-25T05:50:55 | 2018-08-01T03:47:00 | C++ | UTF-8 | C++ | false | false | 41,556 | cpp | // 0:vars:3
// 3:atom_1_X1_0:1
// 4:atom_2_X1_0:1
// 5:thr0:1
// 6:thr1:1
// 7:thr2:1
#define ADDRSIZE 8
#define NPROC 4
#define NCONTEXT 1
#define ASSUME(stmt) __CPROVER_assume(stmt)
#define ASSERT(stmt) __CPROVER_assert(stmt, "error")
#define max(a,b) (a>b?a:b)
char __get_rng();
char get_rng( char from, char to ) {
char ret = __get_rng();
ASSUME(ret >= from && ret <= to);
return ret;
}
char get_rng_th( char from, char to ) {
char ret = __get_rng();
ASSUME(ret >= from && ret <= to);
return ret;
}
int main(int argc, char **argv) {
// declare arrays for intial value version in contexts
int meminit_[ADDRSIZE*NCONTEXT];
#define meminit(x,k) meminit_[(x)*NCONTEXT+k]
int coinit_[ADDRSIZE*NCONTEXT];
#define coinit(x,k) coinit_[(x)*NCONTEXT+k]
int deltainit_[ADDRSIZE*NCONTEXT];
#define deltainit(x,k) deltainit_[(x)*NCONTEXT+k]
// declare arrays for running value version in contexts
int mem_[ADDRSIZE*NCONTEXT];
#define mem(x,k) mem_[(x)*NCONTEXT+k]
int co_[ADDRSIZE*NCONTEXT];
#define co(x,k) co_[(x)*NCONTEXT+k]
int delta_[ADDRSIZE*NCONTEXT];
#define delta(x,k) delta_[(x)*NCONTEXT+k]
// declare arrays for local buffer and observed writes
int buff_[NPROC*ADDRSIZE];
#define buff(x,k) buff_[(x)*ADDRSIZE+k]
int pw_[NPROC*ADDRSIZE];
#define pw(x,k) pw_[(x)*ADDRSIZE+k]
// declare arrays for context stamps
char cr_[NPROC*ADDRSIZE];
#define cr(x,k) cr_[(x)*ADDRSIZE+k]
char iw_[NPROC*ADDRSIZE];
#define iw(x,k) iw_[(x)*ADDRSIZE+k]
char cw_[NPROC*ADDRSIZE];
#define cw(x,k) cw_[(x)*ADDRSIZE+k]
char cx_[NPROC*ADDRSIZE];
#define cx(x,k) cx_[(x)*ADDRSIZE+k]
char is_[NPROC*ADDRSIZE];
#define is(x,k) is_[(x)*ADDRSIZE+k]
char cs_[NPROC*ADDRSIZE];
#define cs(x,k) cs_[(x)*ADDRSIZE+k]
char crmax_[NPROC*ADDRSIZE];
#define crmax(x,k) crmax_[(x)*ADDRSIZE+k]
char sforbid_[ADDRSIZE*NCONTEXT];
#define sforbid(x,k) sforbid_[(x)*NCONTEXT+k]
// declare arrays for synchronizations
int cl[NPROC];
int cdy[NPROC];
int cds[NPROC];
int cdl[NPROC];
int cisb[NPROC];
int caddr[NPROC];
int cctrl[NPROC];
int cstart[NPROC];
int creturn[NPROC];
// declare arrays for contexts activity
int active[NCONTEXT];
int ctx_used[NCONTEXT];
int r0= 0;
char creg_r0;
int r1= 0;
char creg_r1;
int r2= 0;
char creg_r2;
int r3= 0;
char creg_r3;
int r4= 0;
char creg_r4;
int r5= 0;
char creg_r5;
int r6= 0;
char creg_r6;
int r7= 0;
char creg_r7;
int r8= 0;
char creg_r8;
int r9= 0;
char creg_r9;
int r10= 0;
char creg_r10;
int r11= 0;
char creg_r11;
char old_cctrl= 0;
char old_cr= 0;
char old_cdy= 0;
char old_cw= 0;
char new_creg= 0;
buff(0,0) = 0;
pw(0,0) = 0;
cr(0,0) = 0;
iw(0,0) = 0;
cw(0,0) = 0;
cx(0,0) = 0;
is(0,0) = 0;
cs(0,0) = 0;
crmax(0,0) = 0;
buff(0,1) = 0;
pw(0,1) = 0;
cr(0,1) = 0;
iw(0,1) = 0;
cw(0,1) = 0;
cx(0,1) = 0;
is(0,1) = 0;
cs(0,1) = 0;
crmax(0,1) = 0;
buff(0,2) = 0;
pw(0,2) = 0;
cr(0,2) = 0;
iw(0,2) = 0;
cw(0,2) = 0;
cx(0,2) = 0;
is(0,2) = 0;
cs(0,2) = 0;
crmax(0,2) = 0;
buff(0,3) = 0;
pw(0,3) = 0;
cr(0,3) = 0;
iw(0,3) = 0;
cw(0,3) = 0;
cx(0,3) = 0;
is(0,3) = 0;
cs(0,3) = 0;
crmax(0,3) = 0;
buff(0,4) = 0;
pw(0,4) = 0;
cr(0,4) = 0;
iw(0,4) = 0;
cw(0,4) = 0;
cx(0,4) = 0;
is(0,4) = 0;
cs(0,4) = 0;
crmax(0,4) = 0;
buff(0,5) = 0;
pw(0,5) = 0;
cr(0,5) = 0;
iw(0,5) = 0;
cw(0,5) = 0;
cx(0,5) = 0;
is(0,5) = 0;
cs(0,5) = 0;
crmax(0,5) = 0;
buff(0,6) = 0;
pw(0,6) = 0;
cr(0,6) = 0;
iw(0,6) = 0;
cw(0,6) = 0;
cx(0,6) = 0;
is(0,6) = 0;
cs(0,6) = 0;
crmax(0,6) = 0;
buff(0,7) = 0;
pw(0,7) = 0;
cr(0,7) = 0;
iw(0,7) = 0;
cw(0,7) = 0;
cx(0,7) = 0;
is(0,7) = 0;
cs(0,7) = 0;
crmax(0,7) = 0;
cl[0] = 0;
cdy[0] = 0;
cds[0] = 0;
cdl[0] = 0;
cisb[0] = 0;
caddr[0] = 0;
cctrl[0] = 0;
cstart[0] = get_rng(0,NCONTEXT-1);
creturn[0] = get_rng(0,NCONTEXT-1);
buff(1,0) = 0;
pw(1,0) = 0;
cr(1,0) = 0;
iw(1,0) = 0;
cw(1,0) = 0;
cx(1,0) = 0;
is(1,0) = 0;
cs(1,0) = 0;
crmax(1,0) = 0;
buff(1,1) = 0;
pw(1,1) = 0;
cr(1,1) = 0;
iw(1,1) = 0;
cw(1,1) = 0;
cx(1,1) = 0;
is(1,1) = 0;
cs(1,1) = 0;
crmax(1,1) = 0;
buff(1,2) = 0;
pw(1,2) = 0;
cr(1,2) = 0;
iw(1,2) = 0;
cw(1,2) = 0;
cx(1,2) = 0;
is(1,2) = 0;
cs(1,2) = 0;
crmax(1,2) = 0;
buff(1,3) = 0;
pw(1,3) = 0;
cr(1,3) = 0;
iw(1,3) = 0;
cw(1,3) = 0;
cx(1,3) = 0;
is(1,3) = 0;
cs(1,3) = 0;
crmax(1,3) = 0;
buff(1,4) = 0;
pw(1,4) = 0;
cr(1,4) = 0;
iw(1,4) = 0;
cw(1,4) = 0;
cx(1,4) = 0;
is(1,4) = 0;
cs(1,4) = 0;
crmax(1,4) = 0;
buff(1,5) = 0;
pw(1,5) = 0;
cr(1,5) = 0;
iw(1,5) = 0;
cw(1,5) = 0;
cx(1,5) = 0;
is(1,5) = 0;
cs(1,5) = 0;
crmax(1,5) = 0;
buff(1,6) = 0;
pw(1,6) = 0;
cr(1,6) = 0;
iw(1,6) = 0;
cw(1,6) = 0;
cx(1,6) = 0;
is(1,6) = 0;
cs(1,6) = 0;
crmax(1,6) = 0;
buff(1,7) = 0;
pw(1,7) = 0;
cr(1,7) = 0;
iw(1,7) = 0;
cw(1,7) = 0;
cx(1,7) = 0;
is(1,7) = 0;
cs(1,7) = 0;
crmax(1,7) = 0;
cl[1] = 0;
cdy[1] = 0;
cds[1] = 0;
cdl[1] = 0;
cisb[1] = 0;
caddr[1] = 0;
cctrl[1] = 0;
cstart[1] = get_rng(0,NCONTEXT-1);
creturn[1] = get_rng(0,NCONTEXT-1);
buff(2,0) = 0;
pw(2,0) = 0;
cr(2,0) = 0;
iw(2,0) = 0;
cw(2,0) = 0;
cx(2,0) = 0;
is(2,0) = 0;
cs(2,0) = 0;
crmax(2,0) = 0;
buff(2,1) = 0;
pw(2,1) = 0;
cr(2,1) = 0;
iw(2,1) = 0;
cw(2,1) = 0;
cx(2,1) = 0;
is(2,1) = 0;
cs(2,1) = 0;
crmax(2,1) = 0;
buff(2,2) = 0;
pw(2,2) = 0;
cr(2,2) = 0;
iw(2,2) = 0;
cw(2,2) = 0;
cx(2,2) = 0;
is(2,2) = 0;
cs(2,2) = 0;
crmax(2,2) = 0;
buff(2,3) = 0;
pw(2,3) = 0;
cr(2,3) = 0;
iw(2,3) = 0;
cw(2,3) = 0;
cx(2,3) = 0;
is(2,3) = 0;
cs(2,3) = 0;
crmax(2,3) = 0;
buff(2,4) = 0;
pw(2,4) = 0;
cr(2,4) = 0;
iw(2,4) = 0;
cw(2,4) = 0;
cx(2,4) = 0;
is(2,4) = 0;
cs(2,4) = 0;
crmax(2,4) = 0;
buff(2,5) = 0;
pw(2,5) = 0;
cr(2,5) = 0;
iw(2,5) = 0;
cw(2,5) = 0;
cx(2,5) = 0;
is(2,5) = 0;
cs(2,5) = 0;
crmax(2,5) = 0;
buff(2,6) = 0;
pw(2,6) = 0;
cr(2,6) = 0;
iw(2,6) = 0;
cw(2,6) = 0;
cx(2,6) = 0;
is(2,6) = 0;
cs(2,6) = 0;
crmax(2,6) = 0;
buff(2,7) = 0;
pw(2,7) = 0;
cr(2,7) = 0;
iw(2,7) = 0;
cw(2,7) = 0;
cx(2,7) = 0;
is(2,7) = 0;
cs(2,7) = 0;
crmax(2,7) = 0;
cl[2] = 0;
cdy[2] = 0;
cds[2] = 0;
cdl[2] = 0;
cisb[2] = 0;
caddr[2] = 0;
cctrl[2] = 0;
cstart[2] = get_rng(0,NCONTEXT-1);
creturn[2] = get_rng(0,NCONTEXT-1);
buff(3,0) = 0;
pw(3,0) = 0;
cr(3,0) = 0;
iw(3,0) = 0;
cw(3,0) = 0;
cx(3,0) = 0;
is(3,0) = 0;
cs(3,0) = 0;
crmax(3,0) = 0;
buff(3,1) = 0;
pw(3,1) = 0;
cr(3,1) = 0;
iw(3,1) = 0;
cw(3,1) = 0;
cx(3,1) = 0;
is(3,1) = 0;
cs(3,1) = 0;
crmax(3,1) = 0;
buff(3,2) = 0;
pw(3,2) = 0;
cr(3,2) = 0;
iw(3,2) = 0;
cw(3,2) = 0;
cx(3,2) = 0;
is(3,2) = 0;
cs(3,2) = 0;
crmax(3,2) = 0;
buff(3,3) = 0;
pw(3,3) = 0;
cr(3,3) = 0;
iw(3,3) = 0;
cw(3,3) = 0;
cx(3,3) = 0;
is(3,3) = 0;
cs(3,3) = 0;
crmax(3,3) = 0;
buff(3,4) = 0;
pw(3,4) = 0;
cr(3,4) = 0;
iw(3,4) = 0;
cw(3,4) = 0;
cx(3,4) = 0;
is(3,4) = 0;
cs(3,4) = 0;
crmax(3,4) = 0;
buff(3,5) = 0;
pw(3,5) = 0;
cr(3,5) = 0;
iw(3,5) = 0;
cw(3,5) = 0;
cx(3,5) = 0;
is(3,5) = 0;
cs(3,5) = 0;
crmax(3,5) = 0;
buff(3,6) = 0;
pw(3,6) = 0;
cr(3,6) = 0;
iw(3,6) = 0;
cw(3,6) = 0;
cx(3,6) = 0;
is(3,6) = 0;
cs(3,6) = 0;
crmax(3,6) = 0;
buff(3,7) = 0;
pw(3,7) = 0;
cr(3,7) = 0;
iw(3,7) = 0;
cw(3,7) = 0;
cx(3,7) = 0;
is(3,7) = 0;
cs(3,7) = 0;
crmax(3,7) = 0;
cl[3] = 0;
cdy[3] = 0;
cds[3] = 0;
cdl[3] = 0;
cisb[3] = 0;
caddr[3] = 0;
cctrl[3] = 0;
cstart[3] = get_rng(0,NCONTEXT-1);
creturn[3] = get_rng(0,NCONTEXT-1);
// Dumping initializations
mem(0+0,0) = 0;
mem(0+1,0) = 0;
mem(0+2,0) = 0;
mem(3+0,0) = 0;
mem(4+0,0) = 0;
mem(5+0,0) = 0;
mem(6+0,0) = 0;
mem(7+0,0) = 0;
// Dumping context matching equalities
co(0,0) = 0;
delta(0,0) = -1;
co(1,0) = 0;
delta(1,0) = -1;
co(2,0) = 0;
delta(2,0) = -1;
co(3,0) = 0;
delta(3,0) = -1;
co(4,0) = 0;
delta(4,0) = -1;
co(5,0) = 0;
delta(5,0) = -1;
co(6,0) = 0;
delta(6,0) = -1;
co(7,0) = 0;
delta(7,0) = -1;
// Dumping thread 1
int ret_thread_1 = 0;
cdy[1] = get_rng(0,NCONTEXT-1);
ASSUME(cdy[1] >= cstart[1]);
T1BLOCK0:
// call void @llvm.dbg.value(metadata i8* %arg, metadata !35, metadata !DIExpression()), !dbg !44
// br label %label_1, !dbg !45
goto T1BLOCK1;
T1BLOCK1:
// call void @llvm.dbg.label(metadata !43), !dbg !46
// call void @llvm.dbg.value(metadata i64* getelementptr inbounds ([3 x i64], [3 x i64]* @vars, i64 0, i64 1), metadata !36, metadata !DIExpression()), !dbg !47
// call void @llvm.dbg.value(metadata i64 1, metadata !39, metadata !DIExpression()), !dbg !47
// store atomic i64 1, i64* getelementptr inbounds ([3 x i64], [3 x i64]* @vars, i64 0, i64 1) release, align 8, !dbg !48
// ST: Guess
// : Release
iw(1,0+1*1) = get_rng(0,NCONTEXT-1);// 1 ASSIGN STIW
old_cw = cw(1,0+1*1);
cw(1,0+1*1) = get_rng(0,NCONTEXT-1);// 1 ASSIGN STCOM
// Check
ASSUME(active[iw(1,0+1*1)] == 1);
ASSUME(active[cw(1,0+1*1)] == 1);
ASSUME(sforbid(0+1*1,cw(1,0+1*1))== 0);
ASSUME(iw(1,0+1*1) >= 0);
ASSUME(iw(1,0+1*1) >= 0);
ASSUME(cw(1,0+1*1) >= iw(1,0+1*1));
ASSUME(cw(1,0+1*1) >= old_cw);
ASSUME(cw(1,0+1*1) >= cr(1,0+1*1));
ASSUME(cw(1,0+1*1) >= cl[1]);
ASSUME(cw(1,0+1*1) >= cisb[1]);
ASSUME(cw(1,0+1*1) >= cdy[1]);
ASSUME(cw(1,0+1*1) >= cdl[1]);
ASSUME(cw(1,0+1*1) >= cds[1]);
ASSUME(cw(1,0+1*1) >= cctrl[1]);
ASSUME(cw(1,0+1*1) >= caddr[1]);
ASSUME(cw(1,0+1*1) >= cr(1,0+0));
ASSUME(cw(1,0+1*1) >= cr(1,0+1));
ASSUME(cw(1,0+1*1) >= cr(1,0+2));
ASSUME(cw(1,0+1*1) >= cr(1,3+0));
ASSUME(cw(1,0+1*1) >= cr(1,4+0));
ASSUME(cw(1,0+1*1) >= cr(1,5+0));
ASSUME(cw(1,0+1*1) >= cr(1,6+0));
ASSUME(cw(1,0+1*1) >= cr(1,7+0));
ASSUME(cw(1,0+1*1) >= cw(1,0+0));
ASSUME(cw(1,0+1*1) >= cw(1,0+1));
ASSUME(cw(1,0+1*1) >= cw(1,0+2));
ASSUME(cw(1,0+1*1) >= cw(1,3+0));
ASSUME(cw(1,0+1*1) >= cw(1,4+0));
ASSUME(cw(1,0+1*1) >= cw(1,5+0));
ASSUME(cw(1,0+1*1) >= cw(1,6+0));
ASSUME(cw(1,0+1*1) >= cw(1,7+0));
// Update
caddr[1] = max(caddr[1],0);
buff(1,0+1*1) = 1;
mem(0+1*1,cw(1,0+1*1)) = 1;
co(0+1*1,cw(1,0+1*1))+=1;
delta(0+1*1,cw(1,0+1*1)) = -1;
is(1,0+1*1) = iw(1,0+1*1);
cs(1,0+1*1) = cw(1,0+1*1);
ASSUME(creturn[1] >= cw(1,0+1*1));
// call void @llvm.dbg.value(metadata i64* getelementptr inbounds ([3 x i64], [3 x i64]* @vars, i64 0, i64 0), metadata !40, metadata !DIExpression()), !dbg !49
// call void @llvm.dbg.value(metadata i64 1, metadata !42, metadata !DIExpression()), !dbg !49
// store atomic i64 1, i64* getelementptr inbounds ([3 x i64], [3 x i64]* @vars, i64 0, i64 0) release, align 8, !dbg !50
// ST: Guess
// : Release
iw(1,0) = get_rng(0,NCONTEXT-1);// 1 ASSIGN STIW
old_cw = cw(1,0);
cw(1,0) = get_rng(0,NCONTEXT-1);// 1 ASSIGN STCOM
// Check
ASSUME(active[iw(1,0)] == 1);
ASSUME(active[cw(1,0)] == 1);
ASSUME(sforbid(0,cw(1,0))== 0);
ASSUME(iw(1,0) >= 0);
ASSUME(iw(1,0) >= 0);
ASSUME(cw(1,0) >= iw(1,0));
ASSUME(cw(1,0) >= old_cw);
ASSUME(cw(1,0) >= cr(1,0));
ASSUME(cw(1,0) >= cl[1]);
ASSUME(cw(1,0) >= cisb[1]);
ASSUME(cw(1,0) >= cdy[1]);
ASSUME(cw(1,0) >= cdl[1]);
ASSUME(cw(1,0) >= cds[1]);
ASSUME(cw(1,0) >= cctrl[1]);
ASSUME(cw(1,0) >= caddr[1]);
ASSUME(cw(1,0) >= cr(1,0+0));
ASSUME(cw(1,0) >= cr(1,0+1));
ASSUME(cw(1,0) >= cr(1,0+2));
ASSUME(cw(1,0) >= cr(1,3+0));
ASSUME(cw(1,0) >= cr(1,4+0));
ASSUME(cw(1,0) >= cr(1,5+0));
ASSUME(cw(1,0) >= cr(1,6+0));
ASSUME(cw(1,0) >= cr(1,7+0));
ASSUME(cw(1,0) >= cw(1,0+0));
ASSUME(cw(1,0) >= cw(1,0+1));
ASSUME(cw(1,0) >= cw(1,0+2));
ASSUME(cw(1,0) >= cw(1,3+0));
ASSUME(cw(1,0) >= cw(1,4+0));
ASSUME(cw(1,0) >= cw(1,5+0));
ASSUME(cw(1,0) >= cw(1,6+0));
ASSUME(cw(1,0) >= cw(1,7+0));
// Update
caddr[1] = max(caddr[1],0);
buff(1,0) = 1;
mem(0,cw(1,0)) = 1;
co(0,cw(1,0))+=1;
delta(0,cw(1,0)) = -1;
is(1,0) = iw(1,0);
cs(1,0) = cw(1,0);
ASSUME(creturn[1] >= cw(1,0));
// ret i8* null, !dbg !51
ret_thread_1 = (- 1);
// Dumping thread 2
int ret_thread_2 = 0;
cdy[2] = get_rng(0,NCONTEXT-1);
ASSUME(cdy[2] >= cstart[2]);
T2BLOCK0:
// call void @llvm.dbg.value(metadata i8* %arg, metadata !54, metadata !DIExpression()), !dbg !68
// br label %label_2, !dbg !51
goto T2BLOCK1;
T2BLOCK1:
// call void @llvm.dbg.label(metadata !67), !dbg !70
// call void @llvm.dbg.value(metadata i64* getelementptr inbounds ([3 x i64], [3 x i64]* @vars, i64 0, i64 0), metadata !55, metadata !DIExpression()), !dbg !71
// call void @llvm.dbg.value(metadata i64 2, metadata !57, metadata !DIExpression()), !dbg !71
// store atomic i64 2, i64* getelementptr inbounds ([3 x i64], [3 x i64]* @vars, i64 0, i64 0) monotonic, align 8, !dbg !54
// ST: Guess
iw(2,0) = get_rng(0,NCONTEXT-1);// 2 ASSIGN STIW
old_cw = cw(2,0);
cw(2,0) = get_rng(0,NCONTEXT-1);// 2 ASSIGN STCOM
// Check
ASSUME(active[iw(2,0)] == 2);
ASSUME(active[cw(2,0)] == 2);
ASSUME(sforbid(0,cw(2,0))== 0);
ASSUME(iw(2,0) >= 0);
ASSUME(iw(2,0) >= 0);
ASSUME(cw(2,0) >= iw(2,0));
ASSUME(cw(2,0) >= old_cw);
ASSUME(cw(2,0) >= cr(2,0));
ASSUME(cw(2,0) >= cl[2]);
ASSUME(cw(2,0) >= cisb[2]);
ASSUME(cw(2,0) >= cdy[2]);
ASSUME(cw(2,0) >= cdl[2]);
ASSUME(cw(2,0) >= cds[2]);
ASSUME(cw(2,0) >= cctrl[2]);
ASSUME(cw(2,0) >= caddr[2]);
// Update
caddr[2] = max(caddr[2],0);
buff(2,0) = 2;
mem(0,cw(2,0)) = 2;
co(0,cw(2,0))+=1;
delta(0,cw(2,0)) = -1;
ASSUME(creturn[2] >= cw(2,0));
// call void (...) @dmbsy(), !dbg !55
// dumbsy: Guess
old_cdy = cdy[2];
cdy[2] = get_rng(0,NCONTEXT-1);
// Check
ASSUME(cdy[2] >= old_cdy);
ASSUME(cdy[2] >= cisb[2]);
ASSUME(cdy[2] >= cdl[2]);
ASSUME(cdy[2] >= cds[2]);
ASSUME(cdy[2] >= cctrl[2]);
ASSUME(cdy[2] >= cw(2,0+0));
ASSUME(cdy[2] >= cw(2,0+1));
ASSUME(cdy[2] >= cw(2,0+2));
ASSUME(cdy[2] >= cw(2,3+0));
ASSUME(cdy[2] >= cw(2,4+0));
ASSUME(cdy[2] >= cw(2,5+0));
ASSUME(cdy[2] >= cw(2,6+0));
ASSUME(cdy[2] >= cw(2,7+0));
ASSUME(cdy[2] >= cr(2,0+0));
ASSUME(cdy[2] >= cr(2,0+1));
ASSUME(cdy[2] >= cr(2,0+2));
ASSUME(cdy[2] >= cr(2,3+0));
ASSUME(cdy[2] >= cr(2,4+0));
ASSUME(cdy[2] >= cr(2,5+0));
ASSUME(cdy[2] >= cr(2,6+0));
ASSUME(cdy[2] >= cr(2,7+0));
ASSUME(creturn[2] >= cdy[2]);
// call void @llvm.dbg.value(metadata i64* getelementptr inbounds ([3 x i64], [3 x i64]* @vars, i64 0, i64 2), metadata !60, metadata !DIExpression()), !dbg !74
// %0 = load atomic i64, i64* getelementptr inbounds ([3 x i64], [3 x i64]* @vars, i64 0, i64 2) monotonic, align 8, !dbg !57
// LD: Guess
old_cr = cr(2,0+2*1);
cr(2,0+2*1) = get_rng(0,NCONTEXT-1);// 2 ASSIGN LDCOM
// Check
ASSUME(active[cr(2,0+2*1)] == 2);
ASSUME(cr(2,0+2*1) >= iw(2,0+2*1));
ASSUME(cr(2,0+2*1) >= 0);
ASSUME(cr(2,0+2*1) >= cdy[2]);
ASSUME(cr(2,0+2*1) >= cisb[2]);
ASSUME(cr(2,0+2*1) >= cdl[2]);
ASSUME(cr(2,0+2*1) >= cl[2]);
// Update
creg_r0 = cr(2,0+2*1);
crmax(2,0+2*1) = max(crmax(2,0+2*1),cr(2,0+2*1));
caddr[2] = max(caddr[2],0);
if(cr(2,0+2*1) < cw(2,0+2*1)) {
r0 = buff(2,0+2*1);
} else {
if(pw(2,0+2*1) != co(0+2*1,cr(2,0+2*1))) {
ASSUME(cr(2,0+2*1) >= old_cr);
}
pw(2,0+2*1) = co(0+2*1,cr(2,0+2*1));
r0 = mem(0+2*1,cr(2,0+2*1));
}
ASSUME(creturn[2] >= cr(2,0+2*1));
// call void @llvm.dbg.value(metadata i64 %0, metadata !62, metadata !DIExpression()), !dbg !74
// %conv = trunc i64 %0 to i32, !dbg !58
// call void @llvm.dbg.value(metadata i32 %conv, metadata !58, metadata !DIExpression()), !dbg !68
// %cmp = icmp eq i32 %conv, 0, !dbg !59
// %conv1 = zext i1 %cmp to i32, !dbg !59
// call void @llvm.dbg.value(metadata i32 %conv1, metadata !63, metadata !DIExpression()), !dbg !68
// call void @llvm.dbg.value(metadata i64* @atom_1_X1_0, metadata !64, metadata !DIExpression()), !dbg !78
// %1 = zext i32 %conv1 to i64
// call void @llvm.dbg.value(metadata i64 %1, metadata !66, metadata !DIExpression()), !dbg !78
// store atomic i64 %1, i64* @atom_1_X1_0 seq_cst, align 8, !dbg !61
// ST: Guess
iw(2,3) = get_rng(0,NCONTEXT-1);// 2 ASSIGN STIW
old_cw = cw(2,3);
cw(2,3) = get_rng(0,NCONTEXT-1);// 2 ASSIGN STCOM
// Check
ASSUME(active[iw(2,3)] == 2);
ASSUME(active[cw(2,3)] == 2);
ASSUME(sforbid(3,cw(2,3))== 0);
ASSUME(iw(2,3) >= max(creg_r0,0));
ASSUME(iw(2,3) >= 0);
ASSUME(cw(2,3) >= iw(2,3));
ASSUME(cw(2,3) >= old_cw);
ASSUME(cw(2,3) >= cr(2,3));
ASSUME(cw(2,3) >= cl[2]);
ASSUME(cw(2,3) >= cisb[2]);
ASSUME(cw(2,3) >= cdy[2]);
ASSUME(cw(2,3) >= cdl[2]);
ASSUME(cw(2,3) >= cds[2]);
ASSUME(cw(2,3) >= cctrl[2]);
ASSUME(cw(2,3) >= caddr[2]);
// Update
caddr[2] = max(caddr[2],0);
buff(2,3) = (r0==0);
mem(3,cw(2,3)) = (r0==0);
co(3,cw(2,3))+=1;
delta(3,cw(2,3)) = -1;
ASSUME(creturn[2] >= cw(2,3));
// ret i8* null, !dbg !62
ret_thread_2 = (- 1);
// Dumping thread 3
int ret_thread_3 = 0;
cdy[3] = get_rng(0,NCONTEXT-1);
ASSUME(cdy[3] >= cstart[3]);
T3BLOCK0:
// call void @llvm.dbg.value(metadata i8* %arg, metadata !83, metadata !DIExpression()), !dbg !96
// br label %label_3, !dbg !51
goto T3BLOCK1;
T3BLOCK1:
// call void @llvm.dbg.label(metadata !95), !dbg !98
// call void @llvm.dbg.value(metadata i64* getelementptr inbounds ([3 x i64], [3 x i64]* @vars, i64 0, i64 2), metadata !84, metadata !DIExpression()), !dbg !99
// call void @llvm.dbg.value(metadata i64 1, metadata !86, metadata !DIExpression()), !dbg !99
// store atomic i64 1, i64* getelementptr inbounds ([3 x i64], [3 x i64]* @vars, i64 0, i64 2) monotonic, align 8, !dbg !54
// ST: Guess
iw(3,0+2*1) = get_rng(0,NCONTEXT-1);// 3 ASSIGN STIW
old_cw = cw(3,0+2*1);
cw(3,0+2*1) = get_rng(0,NCONTEXT-1);// 3 ASSIGN STCOM
// Check
ASSUME(active[iw(3,0+2*1)] == 3);
ASSUME(active[cw(3,0+2*1)] == 3);
ASSUME(sforbid(0+2*1,cw(3,0+2*1))== 0);
ASSUME(iw(3,0+2*1) >= 0);
ASSUME(iw(3,0+2*1) >= 0);
ASSUME(cw(3,0+2*1) >= iw(3,0+2*1));
ASSUME(cw(3,0+2*1) >= old_cw);
ASSUME(cw(3,0+2*1) >= cr(3,0+2*1));
ASSUME(cw(3,0+2*1) >= cl[3]);
ASSUME(cw(3,0+2*1) >= cisb[3]);
ASSUME(cw(3,0+2*1) >= cdy[3]);
ASSUME(cw(3,0+2*1) >= cdl[3]);
ASSUME(cw(3,0+2*1) >= cds[3]);
ASSUME(cw(3,0+2*1) >= cctrl[3]);
ASSUME(cw(3,0+2*1) >= caddr[3]);
// Update
caddr[3] = max(caddr[3],0);
buff(3,0+2*1) = 1;
mem(0+2*1,cw(3,0+2*1)) = 1;
co(0+2*1,cw(3,0+2*1))+=1;
delta(0+2*1,cw(3,0+2*1)) = -1;
ASSUME(creturn[3] >= cw(3,0+2*1));
// call void @llvm.dbg.value(metadata i64* getelementptr inbounds ([3 x i64], [3 x i64]* @vars, i64 0, i64 1), metadata !88, metadata !DIExpression()), !dbg !101
// %0 = load atomic i64, i64* getelementptr inbounds ([3 x i64], [3 x i64]* @vars, i64 0, i64 1) acquire, align 8, !dbg !56
// LD: Guess
// : Acquire
old_cr = cr(3,0+1*1);
cr(3,0+1*1) = get_rng(0,NCONTEXT-1);// 3 ASSIGN LDCOM
// Check
ASSUME(active[cr(3,0+1*1)] == 3);
ASSUME(cr(3,0+1*1) >= iw(3,0+1*1));
ASSUME(cr(3,0+1*1) >= 0);
ASSUME(cr(3,0+1*1) >= cdy[3]);
ASSUME(cr(3,0+1*1) >= cisb[3]);
ASSUME(cr(3,0+1*1) >= cdl[3]);
ASSUME(cr(3,0+1*1) >= cl[3]);
ASSUME(cr(3,0+1*1) >= cx(3,0+1*1));
ASSUME(cr(3,0+1*1) >= cs(3,0+0));
ASSUME(cr(3,0+1*1) >= cs(3,0+1));
ASSUME(cr(3,0+1*1) >= cs(3,0+2));
ASSUME(cr(3,0+1*1) >= cs(3,3+0));
ASSUME(cr(3,0+1*1) >= cs(3,4+0));
ASSUME(cr(3,0+1*1) >= cs(3,5+0));
ASSUME(cr(3,0+1*1) >= cs(3,6+0));
ASSUME(cr(3,0+1*1) >= cs(3,7+0));
// Update
creg_r1 = cr(3,0+1*1);
crmax(3,0+1*1) = max(crmax(3,0+1*1),cr(3,0+1*1));
caddr[3] = max(caddr[3],0);
if(cr(3,0+1*1) < cw(3,0+1*1)) {
r1 = buff(3,0+1*1);
} else {
if(pw(3,0+1*1) != co(0+1*1,cr(3,0+1*1))) {
ASSUME(cr(3,0+1*1) >= old_cr);
}
pw(3,0+1*1) = co(0+1*1,cr(3,0+1*1));
r1 = mem(0+1*1,cr(3,0+1*1));
}
cl[3] = max(cl[3],cr(3,0+1*1));
ASSUME(creturn[3] >= cr(3,0+1*1));
// call void @llvm.dbg.value(metadata i64 %0, metadata !90, metadata !DIExpression()), !dbg !101
// %conv = trunc i64 %0 to i32, !dbg !57
// call void @llvm.dbg.value(metadata i32 %conv, metadata !87, metadata !DIExpression()), !dbg !96
// %cmp = icmp eq i32 %conv, 0, !dbg !58
// %conv1 = zext i1 %cmp to i32, !dbg !58
// call void @llvm.dbg.value(metadata i32 %conv1, metadata !91, metadata !DIExpression()), !dbg !96
// call void @llvm.dbg.value(metadata i64* @atom_2_X1_0, metadata !92, metadata !DIExpression()), !dbg !105
// %1 = zext i32 %conv1 to i64
// call void @llvm.dbg.value(metadata i64 %1, metadata !94, metadata !DIExpression()), !dbg !105
// store atomic i64 %1, i64* @atom_2_X1_0 seq_cst, align 8, !dbg !60
// ST: Guess
iw(3,4) = get_rng(0,NCONTEXT-1);// 3 ASSIGN STIW
old_cw = cw(3,4);
cw(3,4) = get_rng(0,NCONTEXT-1);// 3 ASSIGN STCOM
// Check
ASSUME(active[iw(3,4)] == 3);
ASSUME(active[cw(3,4)] == 3);
ASSUME(sforbid(4,cw(3,4))== 0);
ASSUME(iw(3,4) >= max(creg_r1,0));
ASSUME(iw(3,4) >= 0);
ASSUME(cw(3,4) >= iw(3,4));
ASSUME(cw(3,4) >= old_cw);
ASSUME(cw(3,4) >= cr(3,4));
ASSUME(cw(3,4) >= cl[3]);
ASSUME(cw(3,4) >= cisb[3]);
ASSUME(cw(3,4) >= cdy[3]);
ASSUME(cw(3,4) >= cdl[3]);
ASSUME(cw(3,4) >= cds[3]);
ASSUME(cw(3,4) >= cctrl[3]);
ASSUME(cw(3,4) >= caddr[3]);
// Update
caddr[3] = max(caddr[3],0);
buff(3,4) = (r1==0);
mem(4,cw(3,4)) = (r1==0);
co(4,cw(3,4))+=1;
delta(4,cw(3,4)) = -1;
ASSUME(creturn[3] >= cw(3,4));
// ret i8* null, !dbg !61
ret_thread_3 = (- 1);
// Dumping thread 0
int ret_thread_0 = 0;
cdy[0] = get_rng(0,NCONTEXT-1);
ASSUME(cdy[0] >= cstart[0]);
T0BLOCK0:
// %thr0 = alloca i64, align 8
// %thr1 = alloca i64, align 8
// %thr2 = alloca i64, align 8
// call void @llvm.dbg.value(metadata i32 %argc, metadata !115, metadata !DIExpression()), !dbg !153
// call void @llvm.dbg.value(metadata i8** %argv, metadata !116, metadata !DIExpression()), !dbg !153
// %0 = bitcast i64* %thr0 to i8*, !dbg !79
// call void @llvm.lifetime.start.p0i8(i64 8, i8* %0) #7, !dbg !79
// call void @llvm.dbg.declare(metadata i64* %thr0, metadata !117, metadata !DIExpression()), !dbg !155
// %1 = bitcast i64* %thr1 to i8*, !dbg !81
// call void @llvm.lifetime.start.p0i8(i64 8, i8* %1) #7, !dbg !81
// call void @llvm.dbg.declare(metadata i64* %thr1, metadata !121, metadata !DIExpression()), !dbg !157
// %2 = bitcast i64* %thr2 to i8*, !dbg !83
// call void @llvm.lifetime.start.p0i8(i64 8, i8* %2) #7, !dbg !83
// call void @llvm.dbg.declare(metadata i64* %thr2, metadata !122, metadata !DIExpression()), !dbg !159
// call void @llvm.dbg.value(metadata i64* getelementptr inbounds ([3 x i64], [3 x i64]* @vars, i64 0, i64 2), metadata !123, metadata !DIExpression()), !dbg !160
// call void @llvm.dbg.value(metadata i64 0, metadata !125, metadata !DIExpression()), !dbg !160
// store atomic i64 0, i64* getelementptr inbounds ([3 x i64], [3 x i64]* @vars, i64 0, i64 2) monotonic, align 8, !dbg !86
// ST: Guess
iw(0,0+2*1) = get_rng(0,NCONTEXT-1);// 0 ASSIGN STIW
old_cw = cw(0,0+2*1);
cw(0,0+2*1) = get_rng(0,NCONTEXT-1);// 0 ASSIGN STCOM
// Check
ASSUME(active[iw(0,0+2*1)] == 0);
ASSUME(active[cw(0,0+2*1)] == 0);
ASSUME(sforbid(0+2*1,cw(0,0+2*1))== 0);
ASSUME(iw(0,0+2*1) >= 0);
ASSUME(iw(0,0+2*1) >= 0);
ASSUME(cw(0,0+2*1) >= iw(0,0+2*1));
ASSUME(cw(0,0+2*1) >= old_cw);
ASSUME(cw(0,0+2*1) >= cr(0,0+2*1));
ASSUME(cw(0,0+2*1) >= cl[0]);
ASSUME(cw(0,0+2*1) >= cisb[0]);
ASSUME(cw(0,0+2*1) >= cdy[0]);
ASSUME(cw(0,0+2*1) >= cdl[0]);
ASSUME(cw(0,0+2*1) >= cds[0]);
ASSUME(cw(0,0+2*1) >= cctrl[0]);
ASSUME(cw(0,0+2*1) >= caddr[0]);
// Update
caddr[0] = max(caddr[0],0);
buff(0,0+2*1) = 0;
mem(0+2*1,cw(0,0+2*1)) = 0;
co(0+2*1,cw(0,0+2*1))+=1;
delta(0+2*1,cw(0,0+2*1)) = -1;
ASSUME(creturn[0] >= cw(0,0+2*1));
// call void @llvm.dbg.value(metadata i64* getelementptr inbounds ([3 x i64], [3 x i64]* @vars, i64 0, i64 1), metadata !126, metadata !DIExpression()), !dbg !162
// call void @llvm.dbg.value(metadata i64 0, metadata !128, metadata !DIExpression()), !dbg !162
// store atomic i64 0, i64* getelementptr inbounds ([3 x i64], [3 x i64]* @vars, i64 0, i64 1) monotonic, align 8, !dbg !88
// ST: Guess
iw(0,0+1*1) = get_rng(0,NCONTEXT-1);// 0 ASSIGN STIW
old_cw = cw(0,0+1*1);
cw(0,0+1*1) = get_rng(0,NCONTEXT-1);// 0 ASSIGN STCOM
// Check
ASSUME(active[iw(0,0+1*1)] == 0);
ASSUME(active[cw(0,0+1*1)] == 0);
ASSUME(sforbid(0+1*1,cw(0,0+1*1))== 0);
ASSUME(iw(0,0+1*1) >= 0);
ASSUME(iw(0,0+1*1) >= 0);
ASSUME(cw(0,0+1*1) >= iw(0,0+1*1));
ASSUME(cw(0,0+1*1) >= old_cw);
ASSUME(cw(0,0+1*1) >= cr(0,0+1*1));
ASSUME(cw(0,0+1*1) >= cl[0]);
ASSUME(cw(0,0+1*1) >= cisb[0]);
ASSUME(cw(0,0+1*1) >= cdy[0]);
ASSUME(cw(0,0+1*1) >= cdl[0]);
ASSUME(cw(0,0+1*1) >= cds[0]);
ASSUME(cw(0,0+1*1) >= cctrl[0]);
ASSUME(cw(0,0+1*1) >= caddr[0]);
// Update
caddr[0] = max(caddr[0],0);
buff(0,0+1*1) = 0;
mem(0+1*1,cw(0,0+1*1)) = 0;
co(0+1*1,cw(0,0+1*1))+=1;
delta(0+1*1,cw(0,0+1*1)) = -1;
ASSUME(creturn[0] >= cw(0,0+1*1));
// call void @llvm.dbg.value(metadata i64* getelementptr inbounds ([3 x i64], [3 x i64]* @vars, i64 0, i64 0), metadata !129, metadata !DIExpression()), !dbg !164
// call void @llvm.dbg.value(metadata i64 0, metadata !131, metadata !DIExpression()), !dbg !164
// store atomic i64 0, i64* getelementptr inbounds ([3 x i64], [3 x i64]* @vars, i64 0, i64 0) monotonic, align 8, !dbg !90
// ST: Guess
iw(0,0) = get_rng(0,NCONTEXT-1);// 0 ASSIGN STIW
old_cw = cw(0,0);
cw(0,0) = get_rng(0,NCONTEXT-1);// 0 ASSIGN STCOM
// Check
ASSUME(active[iw(0,0)] == 0);
ASSUME(active[cw(0,0)] == 0);
ASSUME(sforbid(0,cw(0,0))== 0);
ASSUME(iw(0,0) >= 0);
ASSUME(iw(0,0) >= 0);
ASSUME(cw(0,0) >= iw(0,0));
ASSUME(cw(0,0) >= old_cw);
ASSUME(cw(0,0) >= cr(0,0));
ASSUME(cw(0,0) >= cl[0]);
ASSUME(cw(0,0) >= cisb[0]);
ASSUME(cw(0,0) >= cdy[0]);
ASSUME(cw(0,0) >= cdl[0]);
ASSUME(cw(0,0) >= cds[0]);
ASSUME(cw(0,0) >= cctrl[0]);
ASSUME(cw(0,0) >= caddr[0]);
// Update
caddr[0] = max(caddr[0],0);
buff(0,0) = 0;
mem(0,cw(0,0)) = 0;
co(0,cw(0,0))+=1;
delta(0,cw(0,0)) = -1;
ASSUME(creturn[0] >= cw(0,0));
// call void @llvm.dbg.value(metadata i64* @atom_1_X1_0, metadata !132, metadata !DIExpression()), !dbg !166
// call void @llvm.dbg.value(metadata i64 0, metadata !134, metadata !DIExpression()), !dbg !166
// store atomic i64 0, i64* @atom_1_X1_0 monotonic, align 8, !dbg !92
// ST: Guess
iw(0,3) = get_rng(0,NCONTEXT-1);// 0 ASSIGN STIW
old_cw = cw(0,3);
cw(0,3) = get_rng(0,NCONTEXT-1);// 0 ASSIGN STCOM
// Check
ASSUME(active[iw(0,3)] == 0);
ASSUME(active[cw(0,3)] == 0);
ASSUME(sforbid(3,cw(0,3))== 0);
ASSUME(iw(0,3) >= 0);
ASSUME(iw(0,3) >= 0);
ASSUME(cw(0,3) >= iw(0,3));
ASSUME(cw(0,3) >= old_cw);
ASSUME(cw(0,3) >= cr(0,3));
ASSUME(cw(0,3) >= cl[0]);
ASSUME(cw(0,3) >= cisb[0]);
ASSUME(cw(0,3) >= cdy[0]);
ASSUME(cw(0,3) >= cdl[0]);
ASSUME(cw(0,3) >= cds[0]);
ASSUME(cw(0,3) >= cctrl[0]);
ASSUME(cw(0,3) >= caddr[0]);
// Update
caddr[0] = max(caddr[0],0);
buff(0,3) = 0;
mem(3,cw(0,3)) = 0;
co(3,cw(0,3))+=1;
delta(3,cw(0,3)) = -1;
ASSUME(creturn[0] >= cw(0,3));
// call void @llvm.dbg.value(metadata i64* @atom_2_X1_0, metadata !135, metadata !DIExpression()), !dbg !168
// call void @llvm.dbg.value(metadata i64 0, metadata !137, metadata !DIExpression()), !dbg !168
// store atomic i64 0, i64* @atom_2_X1_0 monotonic, align 8, !dbg !94
// ST: Guess
iw(0,4) = get_rng(0,NCONTEXT-1);// 0 ASSIGN STIW
old_cw = cw(0,4);
cw(0,4) = get_rng(0,NCONTEXT-1);// 0 ASSIGN STCOM
// Check
ASSUME(active[iw(0,4)] == 0);
ASSUME(active[cw(0,4)] == 0);
ASSUME(sforbid(4,cw(0,4))== 0);
ASSUME(iw(0,4) >= 0);
ASSUME(iw(0,4) >= 0);
ASSUME(cw(0,4) >= iw(0,4));
ASSUME(cw(0,4) >= old_cw);
ASSUME(cw(0,4) >= cr(0,4));
ASSUME(cw(0,4) >= cl[0]);
ASSUME(cw(0,4) >= cisb[0]);
ASSUME(cw(0,4) >= cdy[0]);
ASSUME(cw(0,4) >= cdl[0]);
ASSUME(cw(0,4) >= cds[0]);
ASSUME(cw(0,4) >= cctrl[0]);
ASSUME(cw(0,4) >= caddr[0]);
// Update
caddr[0] = max(caddr[0],0);
buff(0,4) = 0;
mem(4,cw(0,4)) = 0;
co(4,cw(0,4))+=1;
delta(4,cw(0,4)) = -1;
ASSUME(creturn[0] >= cw(0,4));
// %call = call i32 @pthread_create(i64* noundef %thr0, %union.pthread_attr_t* noundef null, i8* (i8*)* noundef @t0, i8* noundef null) #7, !dbg !95
// dumbsy: Guess
old_cdy = cdy[0];
cdy[0] = get_rng(0,NCONTEXT-1);
// Check
ASSUME(cdy[0] >= old_cdy);
ASSUME(cdy[0] >= cisb[0]);
ASSUME(cdy[0] >= cdl[0]);
ASSUME(cdy[0] >= cds[0]);
ASSUME(cdy[0] >= cctrl[0]);
ASSUME(cdy[0] >= cw(0,0+0));
ASSUME(cdy[0] >= cw(0,0+1));
ASSUME(cdy[0] >= cw(0,0+2));
ASSUME(cdy[0] >= cw(0,3+0));
ASSUME(cdy[0] >= cw(0,4+0));
ASSUME(cdy[0] >= cw(0,5+0));
ASSUME(cdy[0] >= cw(0,6+0));
ASSUME(cdy[0] >= cw(0,7+0));
ASSUME(cdy[0] >= cr(0,0+0));
ASSUME(cdy[0] >= cr(0,0+1));
ASSUME(cdy[0] >= cr(0,0+2));
ASSUME(cdy[0] >= cr(0,3+0));
ASSUME(cdy[0] >= cr(0,4+0));
ASSUME(cdy[0] >= cr(0,5+0));
ASSUME(cdy[0] >= cr(0,6+0));
ASSUME(cdy[0] >= cr(0,7+0));
ASSUME(creturn[0] >= cdy[0]);
ASSUME(cstart[1] >= cdy[0]);
// %call9 = call i32 @pthread_create(i64* noundef %thr1, %union.pthread_attr_t* noundef null, i8* (i8*)* noundef @t1, i8* noundef null) #7, !dbg !96
// dumbsy: Guess
old_cdy = cdy[0];
cdy[0] = get_rng(0,NCONTEXT-1);
// Check
ASSUME(cdy[0] >= old_cdy);
ASSUME(cdy[0] >= cisb[0]);
ASSUME(cdy[0] >= cdl[0]);
ASSUME(cdy[0] >= cds[0]);
ASSUME(cdy[0] >= cctrl[0]);
ASSUME(cdy[0] >= cw(0,0+0));
ASSUME(cdy[0] >= cw(0,0+1));
ASSUME(cdy[0] >= cw(0,0+2));
ASSUME(cdy[0] >= cw(0,3+0));
ASSUME(cdy[0] >= cw(0,4+0));
ASSUME(cdy[0] >= cw(0,5+0));
ASSUME(cdy[0] >= cw(0,6+0));
ASSUME(cdy[0] >= cw(0,7+0));
ASSUME(cdy[0] >= cr(0,0+0));
ASSUME(cdy[0] >= cr(0,0+1));
ASSUME(cdy[0] >= cr(0,0+2));
ASSUME(cdy[0] >= cr(0,3+0));
ASSUME(cdy[0] >= cr(0,4+0));
ASSUME(cdy[0] >= cr(0,5+0));
ASSUME(cdy[0] >= cr(0,6+0));
ASSUME(cdy[0] >= cr(0,7+0));
ASSUME(creturn[0] >= cdy[0]);
ASSUME(cstart[2] >= cdy[0]);
// %call10 = call i32 @pthread_create(i64* noundef %thr2, %union.pthread_attr_t* noundef null, i8* (i8*)* noundef @t2, i8* noundef null) #7, !dbg !97
// dumbsy: Guess
old_cdy = cdy[0];
cdy[0] = get_rng(0,NCONTEXT-1);
// Check
ASSUME(cdy[0] >= old_cdy);
ASSUME(cdy[0] >= cisb[0]);
ASSUME(cdy[0] >= cdl[0]);
ASSUME(cdy[0] >= cds[0]);
ASSUME(cdy[0] >= cctrl[0]);
ASSUME(cdy[0] >= cw(0,0+0));
ASSUME(cdy[0] >= cw(0,0+1));
ASSUME(cdy[0] >= cw(0,0+2));
ASSUME(cdy[0] >= cw(0,3+0));
ASSUME(cdy[0] >= cw(0,4+0));
ASSUME(cdy[0] >= cw(0,5+0));
ASSUME(cdy[0] >= cw(0,6+0));
ASSUME(cdy[0] >= cw(0,7+0));
ASSUME(cdy[0] >= cr(0,0+0));
ASSUME(cdy[0] >= cr(0,0+1));
ASSUME(cdy[0] >= cr(0,0+2));
ASSUME(cdy[0] >= cr(0,3+0));
ASSUME(cdy[0] >= cr(0,4+0));
ASSUME(cdy[0] >= cr(0,5+0));
ASSUME(cdy[0] >= cr(0,6+0));
ASSUME(cdy[0] >= cr(0,7+0));
ASSUME(creturn[0] >= cdy[0]);
ASSUME(cstart[3] >= cdy[0]);
// %3 = load i64, i64* %thr0, align 8, !dbg !98, !tbaa !99
// LD: Guess
old_cr = cr(0,5);
cr(0,5) = get_rng(0,NCONTEXT-1);// 0 ASSIGN LDCOM
// Check
ASSUME(active[cr(0,5)] == 0);
ASSUME(cr(0,5) >= iw(0,5));
ASSUME(cr(0,5) >= 0);
ASSUME(cr(0,5) >= cdy[0]);
ASSUME(cr(0,5) >= cisb[0]);
ASSUME(cr(0,5) >= cdl[0]);
ASSUME(cr(0,5) >= cl[0]);
// Update
creg_r3 = cr(0,5);
crmax(0,5) = max(crmax(0,5),cr(0,5));
caddr[0] = max(caddr[0],0);
if(cr(0,5) < cw(0,5)) {
r3 = buff(0,5);
} else {
if(pw(0,5) != co(5,cr(0,5))) {
ASSUME(cr(0,5) >= old_cr);
}
pw(0,5) = co(5,cr(0,5));
r3 = mem(5,cr(0,5));
}
ASSUME(creturn[0] >= cr(0,5));
// %call11 = call i32 @pthread_join(i64 noundef %3, i8** noundef null), !dbg !103
// dumbsy: Guess
old_cdy = cdy[0];
cdy[0] = get_rng(0,NCONTEXT-1);
// Check
ASSUME(cdy[0] >= old_cdy);
ASSUME(cdy[0] >= cisb[0]);
ASSUME(cdy[0] >= cdl[0]);
ASSUME(cdy[0] >= cds[0]);
ASSUME(cdy[0] >= cctrl[0]);
ASSUME(cdy[0] >= cw(0,0+0));
ASSUME(cdy[0] >= cw(0,0+1));
ASSUME(cdy[0] >= cw(0,0+2));
ASSUME(cdy[0] >= cw(0,3+0));
ASSUME(cdy[0] >= cw(0,4+0));
ASSUME(cdy[0] >= cw(0,5+0));
ASSUME(cdy[0] >= cw(0,6+0));
ASSUME(cdy[0] >= cw(0,7+0));
ASSUME(cdy[0] >= cr(0,0+0));
ASSUME(cdy[0] >= cr(0,0+1));
ASSUME(cdy[0] >= cr(0,0+2));
ASSUME(cdy[0] >= cr(0,3+0));
ASSUME(cdy[0] >= cr(0,4+0));
ASSUME(cdy[0] >= cr(0,5+0));
ASSUME(cdy[0] >= cr(0,6+0));
ASSUME(cdy[0] >= cr(0,7+0));
ASSUME(creturn[0] >= cdy[0]);
ASSUME(cdy[0] >= creturn[1]);
// %4 = load i64, i64* %thr1, align 8, !dbg !104, !tbaa !99
// LD: Guess
old_cr = cr(0,6);
cr(0,6) = get_rng(0,NCONTEXT-1);// 0 ASSIGN LDCOM
// Check
ASSUME(active[cr(0,6)] == 0);
ASSUME(cr(0,6) >= iw(0,6));
ASSUME(cr(0,6) >= 0);
ASSUME(cr(0,6) >= cdy[0]);
ASSUME(cr(0,6) >= cisb[0]);
ASSUME(cr(0,6) >= cdl[0]);
ASSUME(cr(0,6) >= cl[0]);
// Update
creg_r4 = cr(0,6);
crmax(0,6) = max(crmax(0,6),cr(0,6));
caddr[0] = max(caddr[0],0);
if(cr(0,6) < cw(0,6)) {
r4 = buff(0,6);
} else {
if(pw(0,6) != co(6,cr(0,6))) {
ASSUME(cr(0,6) >= old_cr);
}
pw(0,6) = co(6,cr(0,6));
r4 = mem(6,cr(0,6));
}
ASSUME(creturn[0] >= cr(0,6));
// %call12 = call i32 @pthread_join(i64 noundef %4, i8** noundef null), !dbg !105
// dumbsy: Guess
old_cdy = cdy[0];
cdy[0] = get_rng(0,NCONTEXT-1);
// Check
ASSUME(cdy[0] >= old_cdy);
ASSUME(cdy[0] >= cisb[0]);
ASSUME(cdy[0] >= cdl[0]);
ASSUME(cdy[0] >= cds[0]);
ASSUME(cdy[0] >= cctrl[0]);
ASSUME(cdy[0] >= cw(0,0+0));
ASSUME(cdy[0] >= cw(0,0+1));
ASSUME(cdy[0] >= cw(0,0+2));
ASSUME(cdy[0] >= cw(0,3+0));
ASSUME(cdy[0] >= cw(0,4+0));
ASSUME(cdy[0] >= cw(0,5+0));
ASSUME(cdy[0] >= cw(0,6+0));
ASSUME(cdy[0] >= cw(0,7+0));
ASSUME(cdy[0] >= cr(0,0+0));
ASSUME(cdy[0] >= cr(0,0+1));
ASSUME(cdy[0] >= cr(0,0+2));
ASSUME(cdy[0] >= cr(0,3+0));
ASSUME(cdy[0] >= cr(0,4+0));
ASSUME(cdy[0] >= cr(0,5+0));
ASSUME(cdy[0] >= cr(0,6+0));
ASSUME(cdy[0] >= cr(0,7+0));
ASSUME(creturn[0] >= cdy[0]);
ASSUME(cdy[0] >= creturn[2]);
// %5 = load i64, i64* %thr2, align 8, !dbg !106, !tbaa !99
// LD: Guess
old_cr = cr(0,7);
cr(0,7) = get_rng(0,NCONTEXT-1);// 0 ASSIGN LDCOM
// Check
ASSUME(active[cr(0,7)] == 0);
ASSUME(cr(0,7) >= iw(0,7));
ASSUME(cr(0,7) >= 0);
ASSUME(cr(0,7) >= cdy[0]);
ASSUME(cr(0,7) >= cisb[0]);
ASSUME(cr(0,7) >= cdl[0]);
ASSUME(cr(0,7) >= cl[0]);
// Update
creg_r5 = cr(0,7);
crmax(0,7) = max(crmax(0,7),cr(0,7));
caddr[0] = max(caddr[0],0);
if(cr(0,7) < cw(0,7)) {
r5 = buff(0,7);
} else {
if(pw(0,7) != co(7,cr(0,7))) {
ASSUME(cr(0,7) >= old_cr);
}
pw(0,7) = co(7,cr(0,7));
r5 = mem(7,cr(0,7));
}
ASSUME(creturn[0] >= cr(0,7));
// %call13 = call i32 @pthread_join(i64 noundef %5, i8** noundef null), !dbg !107
// dumbsy: Guess
old_cdy = cdy[0];
cdy[0] = get_rng(0,NCONTEXT-1);
// Check
ASSUME(cdy[0] >= old_cdy);
ASSUME(cdy[0] >= cisb[0]);
ASSUME(cdy[0] >= cdl[0]);
ASSUME(cdy[0] >= cds[0]);
ASSUME(cdy[0] >= cctrl[0]);
ASSUME(cdy[0] >= cw(0,0+0));
ASSUME(cdy[0] >= cw(0,0+1));
ASSUME(cdy[0] >= cw(0,0+2));
ASSUME(cdy[0] >= cw(0,3+0));
ASSUME(cdy[0] >= cw(0,4+0));
ASSUME(cdy[0] >= cw(0,5+0));
ASSUME(cdy[0] >= cw(0,6+0));
ASSUME(cdy[0] >= cw(0,7+0));
ASSUME(cdy[0] >= cr(0,0+0));
ASSUME(cdy[0] >= cr(0,0+1));
ASSUME(cdy[0] >= cr(0,0+2));
ASSUME(cdy[0] >= cr(0,3+0));
ASSUME(cdy[0] >= cr(0,4+0));
ASSUME(cdy[0] >= cr(0,5+0));
ASSUME(cdy[0] >= cr(0,6+0));
ASSUME(cdy[0] >= cr(0,7+0));
ASSUME(creturn[0] >= cdy[0]);
ASSUME(cdy[0] >= creturn[3]);
// call void @llvm.dbg.value(metadata i64* getelementptr inbounds ([3 x i64], [3 x i64]* @vars, i64 0, i64 0), metadata !139, metadata !DIExpression()), !dbg !183
// %6 = load atomic i64, i64* getelementptr inbounds ([3 x i64], [3 x i64]* @vars, i64 0, i64 0) seq_cst, align 8, !dbg !109
// LD: Guess
old_cr = cr(0,0);
cr(0,0) = get_rng(0,NCONTEXT-1);// 0 ASSIGN LDCOM
// Check
ASSUME(active[cr(0,0)] == 0);
ASSUME(cr(0,0) >= iw(0,0));
ASSUME(cr(0,0) >= 0);
ASSUME(cr(0,0) >= cdy[0]);
ASSUME(cr(0,0) >= cisb[0]);
ASSUME(cr(0,0) >= cdl[0]);
ASSUME(cr(0,0) >= cl[0]);
// Update
creg_r6 = cr(0,0);
crmax(0,0) = max(crmax(0,0),cr(0,0));
caddr[0] = max(caddr[0],0);
if(cr(0,0) < cw(0,0)) {
r6 = buff(0,0);
} else {
if(pw(0,0) != co(0,cr(0,0))) {
ASSUME(cr(0,0) >= old_cr);
}
pw(0,0) = co(0,cr(0,0));
r6 = mem(0,cr(0,0));
}
ASSUME(creturn[0] >= cr(0,0));
// call void @llvm.dbg.value(metadata i64 %6, metadata !141, metadata !DIExpression()), !dbg !183
// %conv = trunc i64 %6 to i32, !dbg !110
// call void @llvm.dbg.value(metadata i32 %conv, metadata !138, metadata !DIExpression()), !dbg !153
// %cmp = icmp eq i32 %conv, 2, !dbg !111
// %conv14 = zext i1 %cmp to i32, !dbg !111
// call void @llvm.dbg.value(metadata i32 %conv14, metadata !142, metadata !DIExpression()), !dbg !153
// call void @llvm.dbg.value(metadata i64* @atom_1_X1_0, metadata !144, metadata !DIExpression()), !dbg !187
// %7 = load atomic i64, i64* @atom_1_X1_0 seq_cst, align 8, !dbg !113
// LD: Guess
old_cr = cr(0,3);
cr(0,3) = get_rng(0,NCONTEXT-1);// 0 ASSIGN LDCOM
// Check
ASSUME(active[cr(0,3)] == 0);
ASSUME(cr(0,3) >= iw(0,3));
ASSUME(cr(0,3) >= 0);
ASSUME(cr(0,3) >= cdy[0]);
ASSUME(cr(0,3) >= cisb[0]);
ASSUME(cr(0,3) >= cdl[0]);
ASSUME(cr(0,3) >= cl[0]);
// Update
creg_r7 = cr(0,3);
crmax(0,3) = max(crmax(0,3),cr(0,3));
caddr[0] = max(caddr[0],0);
if(cr(0,3) < cw(0,3)) {
r7 = buff(0,3);
} else {
if(pw(0,3) != co(3,cr(0,3))) {
ASSUME(cr(0,3) >= old_cr);
}
pw(0,3) = co(3,cr(0,3));
r7 = mem(3,cr(0,3));
}
ASSUME(creturn[0] >= cr(0,3));
// call void @llvm.dbg.value(metadata i64 %7, metadata !146, metadata !DIExpression()), !dbg !187
// %conv18 = trunc i64 %7 to i32, !dbg !114
// call void @llvm.dbg.value(metadata i32 %conv18, metadata !143, metadata !DIExpression()), !dbg !153
// call void @llvm.dbg.value(metadata i64* @atom_2_X1_0, metadata !148, metadata !DIExpression()), !dbg !190
// %8 = load atomic i64, i64* @atom_2_X1_0 seq_cst, align 8, !dbg !116
// LD: Guess
old_cr = cr(0,4);
cr(0,4) = get_rng(0,NCONTEXT-1);// 0 ASSIGN LDCOM
// Check
ASSUME(active[cr(0,4)] == 0);
ASSUME(cr(0,4) >= iw(0,4));
ASSUME(cr(0,4) >= 0);
ASSUME(cr(0,4) >= cdy[0]);
ASSUME(cr(0,4) >= cisb[0]);
ASSUME(cr(0,4) >= cdl[0]);
ASSUME(cr(0,4) >= cl[0]);
// Update
creg_r8 = cr(0,4);
crmax(0,4) = max(crmax(0,4),cr(0,4));
caddr[0] = max(caddr[0],0);
if(cr(0,4) < cw(0,4)) {
r8 = buff(0,4);
} else {
if(pw(0,4) != co(4,cr(0,4))) {
ASSUME(cr(0,4) >= old_cr);
}
pw(0,4) = co(4,cr(0,4));
r8 = mem(4,cr(0,4));
}
ASSUME(creturn[0] >= cr(0,4));
// call void @llvm.dbg.value(metadata i64 %8, metadata !150, metadata !DIExpression()), !dbg !190
// %conv22 = trunc i64 %8 to i32, !dbg !117
// call void @llvm.dbg.value(metadata i32 %conv22, metadata !147, metadata !DIExpression()), !dbg !153
// %and = and i32 %conv18, %conv22, !dbg !118
creg_r9 = max(creg_r7,creg_r8);
ASSUME(active[creg_r9] == 0);
r9 = r7 & r8;
// call void @llvm.dbg.value(metadata i32 %and, metadata !151, metadata !DIExpression()), !dbg !153
// %and23 = and i32 %conv14, %and, !dbg !119
creg_r10 = max(max(creg_r6,0),creg_r9);
ASSUME(active[creg_r10] == 0);
r10 = (r6==2) & r9;
// call void @llvm.dbg.value(metadata i32 %and23, metadata !152, metadata !DIExpression()), !dbg !153
// %cmp24 = icmp eq i32 %and23, 1, !dbg !120
// br i1 %cmp24, label %if.then, label %if.end, !dbg !122
old_cctrl = cctrl[0];
cctrl[0] = get_rng(0,NCONTEXT-1);
ASSUME(cctrl[0] >= old_cctrl);
ASSUME(cctrl[0] >= creg_r10);
ASSUME(cctrl[0] >= 0);
if((r10==1)) {
goto T0BLOCK1;
} else {
goto T0BLOCK2;
}
T0BLOCK1:
// call void @__assert_fail(i8* noundef getelementptr inbounds ([2 x i8], [2 x i8]* @.str, i64 0, i64 0), i8* noundef getelementptr inbounds ([136 x i8], [136 x i8]* @.str.1, i64 0, i64 0), i32 noundef 69, i8* noundef getelementptr inbounds ([23 x i8], [23 x i8]* @__PRETTY_FUNCTION__.main, i64 0, i64 0)) #8, !dbg !123
// unreachable, !dbg !123
r11 = 1;
T0BLOCK2:
// %9 = bitcast i64* %thr2 to i8*, !dbg !126
// call void @llvm.lifetime.end.p0i8(i64 8, i8* %9) #7, !dbg !126
// %10 = bitcast i64* %thr1 to i8*, !dbg !126
// call void @llvm.lifetime.end.p0i8(i64 8, i8* %10) #7, !dbg !126
// %11 = bitcast i64* %thr0 to i8*, !dbg !126
// call void @llvm.lifetime.end.p0i8(i64 8, i8* %11) #7, !dbg !126
// ret i32 0, !dbg !127
ret_thread_0 = 0;
ASSERT(r11== 0);
}
| [
"[email protected]"
] | |
5dd401c7ed54f5846d44c4621920ac9df4fe2036 | 005e3a493ad76a918c77e66331a53339bf96ae69 | /dialog2.cpp | cad0a5250d7f4b470e2e78f256e06e208e177eb2 | [] | no_license | Franck-Dernoncourt/HNxVoiceCommand | a2885618b2b762757082aea3151b5c323c308f92 | 2047ecb402ede29924c9de6bb994cdebb20c54f4 | refs/heads/master | 2020-12-31T00:41:56.146597 | 2017-01-02T06:50:43 | 2017-01-02T06:50:43 | 80,546,110 | 1 | 0 | null | 2017-01-31T17:56:56 | 2017-01-31T17:56:56 | null | UTF-8 | C++ | false | false | 1,187 | cpp | #include "dialog2.hpp"
#include "ui_dialog2.h"
Dialog2::Dialog2(QWidget *parent)
: QDialog(parent)
, ui(new Ui::Dialog2)
{
ui->setupUi(this);
}
Dialog2::~Dialog2()
{
delete ui;
}
void Dialog2::on_pushButton_browse_clicked()
{
// open file dialog
}
void Dialog2::on_pushButton_ok_clicked()
{
QVector<QString> qvNew;
qvNew.append(ui->lineEdit_phrase->text());
ui->lineEdit_phrase->setText("");
qvNew.append(ui->lineEdit_prog->text());
ui->lineEdit_prog->setText("");
qvNew.append(ui->lineEdit_param->text());
ui->lineEdit_param->setText("");
emit AddPhraseData(qvNew);
this->accept();
}
void Dialog2::on_pushButton_cancel_clicked()
{
ui->lineEdit_phrase->setText("");
ui->lineEdit_prog->setText("");
ui->lineEdit_param->setText("");
ui->pushButton_ok->setDisabled(true);
this->reject();
}
void Dialog2::on_lineEdit_phrase_textEdited(const QString &arg1)
{
if(!arg1.isEmpty())
{
ui->pushButton_ok->setDisabled(false);
}
}
void Dialog2::on_lineEdit_prog_textEdited(const QString &arg1)
{
if(!arg1.isEmpty())
{
ui->pushButton_ok->setDisabled(false);
}
}
| [
"[email protected]"
] | |
673d16be7835a9682c528ba072468669c465d8f1 | c514746275fc4f8cfebdab2cabbfa7e0d6d67841 | /include/KeyMap.h | 465473645c4f22650d24fc05b3908a570dcaec2d | [] | no_license | teraNybble/nPlayerConnect4 | 37b2525222ba10b9b94a9c4ea1a2f3c4d922ba20 | d1244ea165926313250aa2565b416a3abb8b46fa | refs/heads/master | 2023-04-14T06:04:45.666179 | 2021-04-03T15:23:07 | 2021-04-03T15:23:07 | 274,705,759 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 575 | h | #ifndef GAME2D_KEYMAP_H
#define GAME2D_KEYMAP_H
#include "KeyState.h"
#include <map>
namespace Game2D
{
class KeyMap
{
private:
bool isDown;
bool wasDown;
KeyState::State currentState;
std::map<int, KeyState> map;
public:
KeyMap();
inline void addKey(int id) { map.insert(std::pair<int, KeyState>(id,KeyState())); }
inline bool getDown() const { return isDown; }
inline bool getWasDown() const { return wasDown; }
inline KeyState::State getState() const { return currentState; }
void update(int id, bool keyDown);
};
}
#endif //GAME2D_KEYMAP_H | [
"[email protected]"
] | |
a84ea4dc2c6b420bf91fffc2e6e1bcdbb9eba938 | e28c38584facde5ed74f2a746e2b4f114e686f17 | /PAT1036_ProgrammingWithObama/PAT1036_ProgrammingWithObama/ProgrammingWithObama.cpp | 546918155a65dbd37d2e5bf94b753dfa5134f627 | [] | no_license | mlqcmlmc/PAT_BasicLevel_Practise | 02d54a40d6a475c599005b81a444ead66d63f8d8 | 749b756bcde2972d66f7c30fa541dd29858e7894 | refs/heads/master | 2021-01-10T21:49:48.783896 | 2015-06-15T05:40:43 | 2015-06-15T05:40:43 | 37,369,338 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 347 | cpp | #include<iostream>
#include<string>
using namespace std;
int main()
{
int N;
char C;
cin >> N >> C;
string row(N, C), emptystr(N - 2, ' '), line;
line.push_back(C);
line = line + emptystr;
line.push_back(C);
cout << row << endl;
for (int i = 0; i < int(N/2.0+0.5) - 2; i++)
{
cout << line << endl;
}
cout << row << endl;
return 0;
} | [
"[email protected]"
] | |
4c34180e0dca41cf288a8af878ccc8dcc31fccaf | 37cd7e20852a0a06363cc01b35d8b99945657a2b | /hackerankc++/vectortest.cpp | 8279099dff49c4e11894929df505e0e1e6fede8a | [] | no_license | sunilsarode/allc-programs | 46d7b4fba70409dddacef2fdf9af9dc414dfa822 | 4fdf3077e23ee2a2979b1f76706aef96dc112b7f | refs/heads/master | 2023-05-26T02:37:20.163717 | 2023-05-20T16:32:57 | 2023-05-20T16:32:57 | 215,777,615 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 552 | cpp | #include<bits/stdc++.h>
using namespace std;
int jumpingOnClouds(vector<int> c) {
int n=c.size();
cout<<n<<endl;
int count=0;
for(int i=0;i<n;){
if(i+2<n && c[i+2]==0){
count+=1;
i+=2;
}else if(i+1<n&& c[i+1]==0){
count+=1;
i++;
}else{
i++;
}
}
return count;
}
int main(){
vector<int> vec;
int in=0;
for(int i=0;i<7;i++){
cin>>in;
vec.push_back(in);
}
cout<<vec[0]<<endl;
cout<<vec.size()<<endl;
jumpingOnClouds(vec);
return 0;
}
| [
"[email protected]"
] | |
cc1d6ede25a8e626c3a6b4962b0de743f1d7c3dc | 55eb24ea6b0ea4257046f04aa6d3c18e9a0be29a | /SW_EXPERT_ACADEMY/초콜릿과 건포도/9282_solution.cpp | 868b686801e51a39f9c0066b9f6753e877b9e9e9 | [] | no_license | dwywdo/PS | dbb8b913f46d178783bc4b6ebf2a185a2a66b220 | 05700db6b6a49de93e72848b4d516e2a65da592a | refs/heads/master | 2021-11-28T19:15:11.903267 | 2021-11-22T15:46:01 | 2021-11-22T15:46:01 | 248,372,017 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,757 | cpp | #include <iostream>
#include <cstring>
#define MAX 1000000000
using namespace std;
int dp[51][51][51][51];
int choco[51][51];
int sum[51][51];
int solve(int x, int y, int ex, int ey) {
//초코릿 조각이 한개면 0리턴
if (x == ex && y == ey) return 0;
//이미 최솟값을 구해놨으면 최솟값 바로 리턴
if (dp[x][y][ex][ey] != -1) {
return dp[x][y][ex][ey];
}
//(x, y)부터 (ex, ey)까지의 건포도의 합
int cnt = sum[ex][ey] - sum[x - 1][ey] - sum[ex][y - 1] + sum[x - 1][y - 1];
int rt = MAX;
//가로로 자르는 경우
for (int i = x; i < ex; i++) {
int tmp = solve(x, y, i, ey) + solve(i + 1, y, ex, ey);
if (rt > tmp + cnt) rt = tmp + cnt;
}
//세로로 자르는 경우
for (int i = y; i < ey; i++) {
int tmp = solve(x, y, ex, i) + solve(x, i + 1, ex, ey);
if (rt > tmp + cnt) rt = tmp + cnt;
}
//dp메모하고 리턴
return dp[x][y][ex][ey] = rt;
}
int main() {
ios_base::sync_with_stdio(false);
cin.tie(0);
int T;
cin >> T;
int n, m;
for (int tc = 1; tc <= T; tc++) {
//최솟값 dp배열 -1로 초기화
memset(dp, -1, sizeof(dp));
cin >> n >> m;
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= m; j++) {
cin >> choco[i][j];
}
}
//누적합
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= m; j++) {
sum[i][j] = sum[i - 1][j] + sum[i][j - 1] - sum[i - 1][j - 1] + choco[i][j];
}
}
int ans = solve(1, 1, n, m);
cout << '#' << tc << ' ' << ans << '\n';
}
return 0;
}
| [
"[email protected]"
] | |
af25c26af1d4fbe71442926bc8497d6e70a63ac7 | 5f30caf2617ccb73fb8eebb7fa85cf001025ed0a | /zodiacgraph/plughandle.h | 592b7ccf71505e43b24645dc667379f0a12975c8 | [] | no_license | TheSpecialist4/smili-vp-plugin | a6dc5866183395f35ee1e84d001bcaad53e375bf | 6099cc38a4a50d06ca4163c111df4626d3fcfa86 | refs/heads/master | 2021-01-17T14:14:14.814235 | 2017-05-28T02:49:00 | 2017-05-28T02:49:00 | 68,657,634 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 7,354 | h | //
// ZodiacGraph - A general-purpose, circular node graph UI module.
// Copyright (C) 2015 Clemens Sielaff
//
// This program 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, either version 3 of the License, or
// (at your option) any later version.
//
// 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 Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
//
#ifndef ZODIAC_PLUGHANDLE_H
#define ZODIAC_PLUGHANDLE_H
/// \file plughandle.h
///
/// \brief Contains the definition of the zodiac::PlugHandle class.
///
#include <QObject>
#include <QHash>
namespace zodiac {
class NodeHandle;
class Plug;
class SceneHandle;
///
/// \brief A handle object for a zodiac::Plug.
///
/// Is a thin wrapper around a pointer but with a much nicer, outward facing interface than the real Plug.
///
/// See \ref zodiac::SceneHandle "SceneHandle" for more details on handles.
///
class PlugHandle : public QObject
{
Q_OBJECT
public: // methods
///
/// \brief Constructor.
///
/// \param [in] plug Plug to manage through this handle
///
explicit PlugHandle(Plug* plug = nullptr);
///
/// \brief Copy constructor.
///
/// \param [in] other Other PlugHandle to copy.
///
PlugHandle(const PlugHandle& other)
: PlugHandle(other.data()) {}
///
/// \brief Assignment operator.
///
/// \param [in] other Other PlugHandle to copy from.
///
/// \return This.
///
PlugHandle& operator = (const PlugHandle& other);
///
/// \brief Equality operator.
///
/// \param [in] other Other PlugHandle to test against.
///
/// \return <i>true</i> if both handles handle the same object -- <i>false</i> otherwise.
///
bool operator == (const PlugHandle& other) const {return other.data() == data();}
///
/// \brief Direct pointer access.
///
/// \return The pointer managed by this handle.
///
inline Plug* data() const {return m_plug;}
///
/// \brief Used for testing, whether the handle is still alive or not.
///
/// \return <i>true</i> if the PlugHandle is still managing an existing Plug -- <i>false</i> otherwise.
///
inline bool isValid() const {return m_isValid;}
///
/// \brief Only Plug%s with no connections can be removed.
///
/// \return <i>true</i> if the Plug could be removed -- <i>false</i> otherwise.
///
bool isRemovable() const;
///
/// \brief Removes the managed Plug, if it has no connections.
///
/// \return <i>true</i> if the Plug could be removed -- <i>false</i> otherwise.
///
bool remove();
///
/// \brief Returns the unique name of the managed Plug.
///
/// \return Name of the managed Plug.
///
QString getName() const;
///
/// \brief Changes the direction of a Plug from incoming to outgoing or vice-versa.
///
/// This works only on Plug%s that have no existing connections.
///
/// \return <i>true</i> if the Plug was able to change its direction -- <i>false</i> otherwise.
///
bool toggleDirection();
///
/// \brief Tests, whether the managed Plug is an incoming one.
///
/// \return <i>true</i> if the Plug is incoming -- <i>false</i> if it is an outgoing one.
///
bool isIncoming() const;
///
/// \brief Tests, whether the managed Plug is an outgoing one.
///
/// \return <i>true</i> if the Plug is outgoing -- <i>false</i> if it is an incoming one.
///
bool isOutgoing() const;
///
/// \brief The number of connections of the managed Plug.
///
/// Incoming Plugs have a maximal connection count of 1.
///
/// \return Connection count.
///
int connectionCount() const;
///
/// \brief Returns a list of all Plug%s that are connected to this one.
///
/// \return Handles of all Plugs connected to this one.
///
QList<PlugHandle> getConnectedPlugs() const;
///
/// \brief Creates a new connection between the Plug managed by this handle and another.
///
/// You can only connect incoming Plug%s to outgoing Plug%s and vice versa.
/// Also, incoming Plug%s with an existing connection cannot be connected again until you remove the existing one.
///
/// \param [in] other Handle of the Plug to connect to.
///
/// \return <i>true</i> if the connection was created -- <i>false</i> otherwise.
///
bool connectPlug(PlugHandle other);
///
/// \brief Disconnects the managed Plug from another one.
///
/// This method returns false, if there is no connection from this to the other Plug.
///
/// \param [in] other Plug to disconnect from.
///
/// \return <i>true</i> if a connection was removed -- <i>false</i> otherwise.
///
bool disconnectPlug(PlugHandle other);
///
/// \brief Disconnects all connected edges from this Plug.
///
/// After calling this method, the number of connections to this Plug is always zero.
///
void disconnectAll();
///
/// \brief A handle of the Node of the Plug managed by this.
///
/// \return Handle of the plug's Node.
///
NodeHandle getNode() const;
///
/// \brief Handle of the Scene containing this Plug and its Node.
///
/// \return Scene handle.
///
SceneHandle getScene() const;
public slots:
///
/// \brief Renames this Plug to a new name.
///
/// Name is suffixed with an integer, if the proposed name is not unique in the Node.
///
/// \param [in] name Proposed new name of the plug.
///
/// \return Actual new name of the plug.
///
QString rename(const QString& name);
signals:
///
/// \brief Is emitted, when the plug was renamed.
///
/// \param [out] name New name of the plug.
///
void plugRenamed(const QString& name);
private: // methods
///
/// \brief Connects the handle to its managed object.
///
void connectSignals();
private slots:
///
/// \brief Called, when the mangaged Plug was destroyed.
///
void plugWasDestroyed();
private: // member
///
/// \brief Managed plug.
///
Plug* m_plug;
///
/// \brief Validity flag.
///
bool m_isValid;
};
} // namespace zodiac
///
/// \brief Returns the hash of a PlugHandle instance.
///
/// The hash is calculated by taking the address of the Plug-pointer.
/// This is also, why the pointer adress in the handle is never changed or set to <i>nullptr</i>.
///
/// \param [in] key PlugHandle instance to hash.
///
/// \return Unique identifier of a PlugHandle that can be used to determine equality.
///
inline uint qHash(const zodiac::PlugHandle& key)
{
return qHash(size_t(key.data()));
}
#endif // ZODIAC_PLUGHANDLE_H
| [
"[email protected]"
] | |
456024b259bad5c59712540be9f8f1082219fc2f | df43d79f07900f23ded703421ab27f1faec7d37a | /OpenglSuperBible/Learn1_4Sample3.hpp | b8bd516342287ef4ca8891296f3c4906e87bda0c | [] | no_license | DzmitrySafin/OpenglSuperBible | 78ef6c147ac97de5b91ce046544cd2e6a6f33d3e | 254c736b47a590bd133510ff071445ffaf4fa2ec | refs/heads/master | 2021-01-20T10:28:38.119862 | 2017-08-28T18:11:34 | 2017-08-28T18:11:34 | 101,632,727 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 655 | hpp | //
// Learn1_4Sample3.hpp
// OpenglSuperBible
//
// Created by Dzmitry Safin on 8/19/17.
// Copyright © 2017 Dzmitry Safin. All rights reserved.
//
#ifndef __openglsuperbible__learn1_4sample3_hpp__
#define __openglsuperbible__learn1_4sample3_hpp__
#include "Engine.hpp"
class Learn1_4Sample3 : public CEngine
{
public:
void Initialize() override;
void Render(double time) override;
void Finalize() override;
private:
static GLuint CompileProgram();
private:
GLuint shader_program = 0;
GLuint vertex_array_object = 0;
GLuint vertex_buffer_object = 0;
};
#endif /* __openglsuperbible__learn1_4sample3_hpp__ */
| [
"[email protected]"
] | |
814335f52f48ef859799e55f72c50020cad95cc1 | caf18283b697d51c99eadeb0afbff8473e6bfcdf | /PAT Advanced Level/1084. Broken Keyboard (20).cpp | 784f7ecc69ae37519ba48e1c73f6ee9a06663f67 | [] | no_license | zmh890/ZJU-PAT-Code | 81be4d5478fb7aeaf4e945808b8b8437e01d083a | 65ae5ba7a6e076ba54739adc270221b9b4dba671 | refs/heads/master | 2021-04-26T16:41:13.970695 | 2018-02-12T16:02:51 | 2018-02-12T16:02:51 | 121,266,571 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,066 | cpp | /*
On a broken keyboard, some of the keys are worn out. So when you type some sentences, the characters corresponding to those keys will not appear on screen.
Now given a string that you are supposed to type, and the string that you actually type out, please list those keys which are for sure worn out.
Input Specification:
Each input file contains one test case. For each case, the 1st line contains the original string, and the 2nd line contains the typed-out string. Each string contains no more than 80 characters which are either English letters [A-Z] (case insensitive), digital numbers [0-9], or "_" (representing the space). It is guaranteed that both strings are non-empty.
Output Specification:
For each test case, print in one line the keys that are worn out, in the order of being detected. The English letters must be capitalized. Each worn out key must be printed once only. It is guaranteed that there is at least one worn out key.
Sample Input:
7_This_is_a_test
_hs_s_a_es
Sample Output:
7TI
*/
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
#include <functional>
#include <queue>
#include <stack>
#include <cstring>
#include <cctype>
#include <map>
#include <set>
#include <fstream>
#include <sstream>
using namespace std;
int main()
{
//fstream cin("F://test.txt");
string origin,match;
cin >> origin >> match;
string res;
int i = 0,j = 0;
while(i < origin.size() || j < match.size())//测试点4 match已经比较结束 但是origin还没有结束 origin最后的几个字符没有匹配
{
//cout << i << " " << j << endl;
if(j == match.size())
{
while(i < origin.size())
res += toupper(origin[i]),++i;
break;
}
else
if(origin[i] != match[j])
res += toupper(origin[i]),i++;
else
++i,++j;
}
//cout << "res::" << res << endl;
cout << res[0];
for(i = 1;i < res.size();i++)
{
for(j = 0;j < i;j++)
if(res[j] == res[i])
break;
if(j == i)
cout << res[i];
}
system("pause");
return 0;
} | [
"[email protected]"
] | |
b034cabb3dd70d1f495b35cfc5f78b3b93f808e2 | 469b24a3c35cc72925636ddab30f26ad0cc7fca2 | /src/commonlib/fileio.h | 985c2f4c6c7d220e3e2d745d894e6a120b02d36f | [
"MIT"
] | permissive | on-keyday/easyscript | 20a38999d2c84ba62ebe41d18238f236e433c97b | c6717f88e8b3d3489dbad8f9eb06ff533be1a412 | refs/heads/main | 2023-06-27T16:27:35.167806 | 2021-08-02T16:13:06 | 2021-08-02T16:13:06 | 361,768,880 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 17,669 | h | /*
Copyright (c) 2021 on-keyday
Released under the MIT license
https://opensource.org/licenses/mit-license.php
*/
#pragma once
#include "project_name.h"
#define POSIX_SOURCE 200809L
#include <stddef.h>
#include <stdio.h>
#include <sys/stat.h>
#include <mutex>
#ifdef __EMSCRIPTEN__
#include <iostream>
#endif
#ifdef _WIN32
#include <Windows.h>
#include <io.h>
#elif defined(__linux__) || defined(__APPLE__) || defined(__ANDROID__) || defined(__EMSCRIPTEN__)
#include <fcntl.h>
#include <sys/mman.h>
#include <unistd.h>
#else
#error "unsurpported platform"
#endif
#define COMMONLIB_MSB_FLAG(x) ((x)1 << (sizeof(x) * 8 - 1))
#if defined(_WIN32)
#if defined(__GNUC__)
#define fopen_s(pfp, filename, mode) ((*pfp) = ::fopen(filename, mode))
#define COMMONLIB_FILEIO_STRUCT_STAT struct stat
#define COMMONLIB_FILEIO_FUNC_FSTAT ::fstat
#else
#define COMMONLIB_FILEIO_FUNC_FSTAT ::_fstat64
#define COMMONLIB_FILEIO_STRUCT_STAT struct _stat64
#endif
#define COMMONLIB_FILEIO_FUNC_FSEEK ::_fseeki64
#define COMMONLIB_FILEIO_FSEEK_CAST(x) (long long)(x)
#else
#define fopen_s(pfp, filename, mode) ((*pfp) = fopen(filename, mode))
#define COMMONLIB_FILEIO_STRUCT_STAT struct stat
#define COMMONLIB_FILEIO_FUNC_FSTAT ::fstat
#define COMMONLIB_FILEIO_FUNC_FSEEK ::fseek
#define COMMONLIB_FILEIO_FSEEK_CAST(x) (long)(x)
#define _fileno fileno
#endif
namespace PROJECT_NAME {
inline bool getfilesizebystat(int fd, size_t& size) {
COMMONLIB_FILEIO_STRUCT_STAT status;
if (COMMONLIB_FILEIO_FUNC_FSTAT(fd, &status) == -1) {
return false;
}
size = (size_t)status.st_size;
return true;
}
struct FileInput {
friend struct FileMap;
private:
::FILE* file = nullptr;
size_t size_cache = 0;
mutable size_t prevpos = 0;
mutable char samepos_cache = 0;
void open_file(FILE** pfp, const char* name) {
fopen_s(pfp, name, "rb");
}
#ifdef _WIN32
void open_file(FILE** pfp, const wchar_t* name) {
_wfopen_s(pfp, name, L"rb");
}
#endif
public:
FileInput() {}
FileInput(const FileInput&) = delete;
FileInput(FileInput&& in) noexcept {
file = in.file;
in.file = nullptr;
size_cache = in.size_cache;
in.samepos_cache = 0;
//got_size=in.got_size;
//in.got_size=false;
prevpos = in.prevpos;
in.prevpos = 0;
samepos_cache = in.samepos_cache;
in.samepos_cache = 0;
}
template <class C>
FileInput(C* filename) {
open(filename);
}
~FileInput() {
close();
}
bool set_fp(FILE* fp) {
if (file) {
close();
}
file = fp;
return true;
}
template <class C>
bool open(C* filename) {
if (!filename) return false;
FILE* tmp = nullptr;
open_file(&tmp, filename);
if (!tmp) {
return false;
}
auto fd = _fileno(tmp);
if (!getfilesizebystat(fd, size_cache)) {
fclose(tmp);
return 0;
}
close();
file = tmp;
return true;
}
bool close() {
if (!file) return false;
::fclose(file);
file = nullptr;
size_cache = 0;
//got_size=false;
prevpos = 0;
samepos_cache = 0;
return true;
}
size_t size() const {
if (!file) return 0;
return size_cache;
}
char operator[](size_t p) const {
if (!file) return 0;
if (size_cache <= p) return 0;
if (COMMONLIB_MSB_FLAG(size_t) & p) return 0;
if (prevpos < p) {
if (COMMONLIB_FILEIO_FUNC_FSEEK(file, COMMONLIB_FILEIO_FSEEK_CAST(p - prevpos),
SEEK_CUR) != 0) {
return 0;
}
}
else if (prevpos - 1 == p) {
return samepos_cache;
}
else if (prevpos > p) {
if (COMMONLIB_FILEIO_FUNC_FSEEK(file, COMMONLIB_FILEIO_FSEEK_CAST(p),
SEEK_SET) != 0) {
return 0;
}
}
prevpos = p + 1;
auto c = fgetc(file);
if (c == EOF) {
return 0;
}
samepos_cache = (char)c;
return c;
}
bool is_open() {
return file != nullptr;
}
};
template <class Buf, class Mutex = std::mutex>
struct ThreadSafe {
private:
Buf buf;
mutable Mutex lock;
public:
ThreadSafe()
: buf(Buf()) {}
ThreadSafe(ThreadSafe&& in)
: buf(std::forward<Buf>(in.buf)) {}
ThreadSafe(const Buf&) = delete;
ThreadSafe(Buf&& in)
: buf(std::forward<Buf>(in)) {}
Buf& get() {
lock.lock();
return buf;
}
bool release(Buf& ref) {
if (std::addressof(buf) != std::addressof(ref)) return false;
lock.unlock();
return true;
}
auto operator[](size_t p) const
-> decltype(buf[p]) {
std::scoped_lock<std::mutex> locker(lock);
return buf[p];
}
auto operator[](size_t p)
-> decltype(buf[p]) {
std::scoped_lock<std::mutex> locker(lock);
return buf[p];
}
size_t size() const {
std::scoped_lock<std::mutex> locker(lock);
return buf.size();
}
};
template <class Buf, class Mutex>
struct ThreadSafe<Buf&, Mutex> {
private:
using INBuf = std::remove_reference_t<Buf>;
INBuf& buf;
mutable Mutex lock;
public:
ThreadSafe(ThreadSafe&& in)
: buf(in.buf) {}
ThreadSafe(INBuf& in)
: buf(in) {}
Buf& get() {
lock.lock();
return buf;
}
bool release(Buf& ref) {
if (std::addressof(buf) != std::addressof(ref)) return false;
lock.unlock();
return true;
}
auto operator[](size_t p) const
-> decltype(buf[p]) {
std::scoped_lock<std::mutex> locker(lock);
return buf[p];
}
auto operator[](size_t p)
-> decltype(buf[p]) {
std::scoped_lock<std::mutex> locker(lock);
return buf[p];
}
size_t size() const {
std::scoped_lock<std::mutex> locker(lock);
return buf.size();
}
};
struct FileMap {
private:
FILE* fp = nullptr;
#if defined(_WIN32)
HANDLE file = INVALID_HANDLE_VALUE;
HANDLE maph = nullptr;
int err = 0;
HANDLE fp_to_native(FILE* fp) {
int fd = _fileno(fp);
auto fileh = _get_osfhandle(fd);
return (HANDLE)fileh;
}
HANDLE get_handle(const char* name) {
return CreateFileA(
name,
GENERIC_READ,
FILE_SHARE_READ,
NULL,
OPEN_EXISTING,
FILE_ATTRIBUTE_NORMAL,
NULL);
}
HANDLE get_handle(const wchar_t* name) {
return CreateFileW(
name,
GENERIC_READ,
FILE_SHARE_READ,
NULL,
OPEN_EXISTING,
FILE_ATTRIBUTE_NORMAL,
NULL);
}
bool get_map(HANDLE tmp, size_t tmpsize) {
HANDLE tmpm = CreateFileMappingA(tmp, NULL, PAGE_READONLY, 0, 0, NULL);
if (tmpm == NULL) {
err = GetLastError();
return false;
}
char* rep = (char*)MapViewOfFile(tmpm, FILE_MAP_READ, 0, 0, 0);
if (!rep) {
err = GetLastError();
CloseHandle(tmpm);
return false;
}
close_detail();
file = tmp;
maph = tmpm;
place = rep;
_size = tmpsize;
return true;
}
template <class C>
bool open_detail(const C* in) {
auto tmp = get_handle(in);
if (tmp == INVALID_HANDLE_VALUE) {
return false;
}
DWORD high = 0;
DWORD low = GetFileSize(tmp, &high);
uint64_t tmpsize = ((uint64_t)high << 32) + low;
if (!get_map(tmp, (size_t)tmpsize)) {
CloseHandle(tmp);
return false;
}
return true;
}
bool from_fileinput(FILE* fp, size_t size) {
if (!fp) return false;
auto tmp = fp_to_native(fp);
if (tmp == INVALID_HANDLE_VALUE) {
return false;
}
if (!get_map(tmp, size)) {
return false;
}
this->fp = fp;
return true;
}
bool close_detail() {
if (file == INVALID_HANDLE_VALUE) return false;
UnmapViewOfFile((LPCVOID)place);
CloseHandle(maph);
if (fp) {
::fclose(fp);
fp = nullptr;
}
else {
CloseHandle(file);
}
file = INVALID_HANDLE_VALUE;
maph = nullptr;
place = nullptr;
_size = 0;
return true;
}
bool move_detail(FileMap&& in) {
file = in.file;
in.file = INVALID_HANDLE_VALUE;
maph = in.maph;
in.maph = nullptr;
return true;
}
#elif defined(__linux__) || defined(__APPLE__) || defined(__ANDROID__) || defined(__EMSCRIPTEN__)
int fd = -1;
long maplen = 0;
int fp_to_native(FILE* fp) {
return _fileno(fp);
}
int get_handle(const char* in) {
return ::open(in, O_RDONLY);
}
bool get_map(int tmpfd, long tmpsize) {
long pagesize = ::getpagesize(), mapsize = 0;
mapsize = (tmpsize / pagesize + 1) * pagesize;
char* tmpmap = (char*)mmap(nullptr, mapsize, PROT_READ, MAP_SHARED, tmpfd, 0);
if (tmpmap == MAP_FAILED) {
return false;
}
close_detail();
fd = tmpfd;
_size = tmpsize;
maplen = mapsize;
place = tmpmap;
return true;
}
bool open_detail(const char* in) {
int tmpfd = get_handle(in);
if (tmpfd == -1) {
return false;
}
size_t tmpsize = 0;
if (!getfilesizebystat(tmpfd, tmpsize)) {
::close(fd);
return false;
}
if (!get_map(tmpfd, (long)tmpsize)) {
::close(fd);
return false;
}
return true;
}
bool from_fileinput(FILE* fp, size_t size) {
if (!fp) return false;
auto tmp = fp_to_native(fp);
if (tmp == -1) {
return false;
}
if (!get_map(tmp, size)) {
return false;
}
this->fp = fp;
return true;
}
bool close_detail() {
if (fd == -1) return false;
munmap(place, maplen);
if (fp) {
::fclose(fp);
fp = nullptr;
}
else {
::close(fd);
}
fd = -1;
maplen = 0;
place = nullptr;
_size = 0;
return true;
}
bool move_detail(FileMap&& in) {
fd = in.fd;
in.fd = -1;
return true;
}
#endif
char* place = nullptr;
size_t _size = 0;
bool move_common(FileMap&& in) {
move_detail(std::forward<FileMap>(in));
fp = in.fp;
in.fp = nullptr;
place = in.place;
in.place = nullptr;
_size = in._size;
in._size = 0;
return true;
}
public:
FileMap(const char* name) {
open(name);
}
#ifdef _WIN32
FileMap(const wchar_t* name) {
open(name);
}
#endif
~FileMap() {
close();
}
FileMap(FileMap&& in) noexcept {
move_common(std::forward<FileMap>(in));
}
FileMap(FileInput&& in) {
if (!in.file) {
close();
return;
}
if (!from_fileinput(in.file, in.size_cache)) {
::fclose(in.file);
}
in.file = nullptr;
in.size_cache = 0;
in.samepos_cache = 0;
in.prevpos = 0;
}
bool open(const char* name) {
if (!name) return false;
return open_detail(name);
}
#ifdef _WIN32
bool open(const wchar_t* name) {
if (!name) return false;
return open_detail(name);
}
#endif
bool close() {
return close_detail();
}
size_t size() const {
return _size;
}
char operator[](size_t pos) const {
if (!place || _size <= pos) return char();
return place[pos];
}
const char* c_str() const {
return place;
}
bool is_open() const {
return place != nullptr;
}
};
#ifdef _fileno
#undef _fileno
#endif
struct FileWriter {
private:
FILE* fp = nullptr;
public:
template <class C>
FileWriter(C* path, bool add = false) {
open(path, add);
}
#ifdef _WIN32
bool open(const wchar_t* path, bool add = false) {
FILE* tmp = nullptr;
_wfopen_s(&tmp, path, add ? L"ab" : L"wb");
if (!tmp) {
return false;
}
close();
fp = tmp;
return true;
}
#endif
bool open(const char* path, bool add = false) {
FILE* tmp = nullptr;
fopen_s(&tmp, path, add ? "ab" : "wb");
if (!tmp) {
return false;
}
close();
fp = tmp;
return true;
}
bool close() {
if (fp) {
::fclose(fp);
fp = nullptr;
}
return true;
}
template <class C>
bool write(C* byte, size_t size) {
if (!is_open()) return false;
if (::fwrite(byte, sizeof(C), size, fp) < size) {
return false;
}
return true;
}
template <class T>
bool write(const T& t) {
return write((const char*)&t, sizeof(T));
}
template <class T>
void push_back(const T& t) {
write(t);
}
bool is_open() const {
return fp != nullptr;
}
};
struct FileReader {
FileInput* input = nullptr;
FileMap* map = nullptr;
template <class C>
FileReader(C* in) {
open(in);
}
~FileReader() noexcept {
close();
}
FileReader(FileReader&& in) {
close();
input = in.input;
in.input = nullptr;
map = in.map;
in.map = nullptr;
}
template <class C>
bool open_input(C* name) {
FileInput in = name;
if (!in.is_open()) {
return false;
}
close();
input = new FileInput(std::move(in));
return true;
}
template <class C>
bool open_map(C* name) {
FileMap in = name;
if (!in.is_open()) {
return false;
}
close();
map = new FileMap(std::move(in));
return true;
}
template <class C>
bool open(C* name) {
return open_map(name) || open_input(name);
}
bool close() {
if (input) {
input->close();
delete input;
input = nullptr;
}
else if (map) {
map->close();
delete map;
map = nullptr;
}
return true;
}
char operator[](size_t pos) const {
if (input) {
return input->operator[](pos);
}
else if (map) {
return map->operator[](pos);
}
return char();
}
size_t size() const {
if (input) {
return input->size();
}
else if (map) {
return map->size();
}
return 0;
}
bool is_open() const {
return input || map;
}
bool use_filemap() const {
return map != nullptr;
}
};
} // namespace PROJECT_NAME | [
"[email protected]"
] | |
46ca1e9f61787e610c19eb3665d469bda673acc0 | 8e66b12c31da519ba29accd507756faad7e0001f | /src/types/Venue.cc | 2ae90a6fce7615ddd952c069de5b53168d67bb8e | [
"Zlib"
] | permissive | norbekaiser/yatbcpp | ac698ca3ca509f595a83a9d7a14235272f7154a6 | 7628fe295fb2fd858dc71bebb4805aa3c05ebda4 | refs/heads/master | 2021-01-20T05:15:39.866939 | 2019-01-03T13:09:19 | 2019-01-03T13:09:19 | 100,170,649 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,942 | cc | // Copyright (c) 2017,2018 Norbert Rühl
//
// This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software.
//
// Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions:
//
// 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required.
//
// 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software.
//
// 3. This notice may not be removed or altered from any source distribution.
#include <string>
#if __has_include(<optional>)
#include <optional>
#else
#include <experimental/optional>
#define optional experimental::optional
#endif
#include "types/Venue.h"
using namespace yatbcpp;
using namespace std;
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Constructor Section //
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
Venue::Venue(Location location, std::string title, std::string address):
location(location), title(title), address(address)
{
}
Venue::Venue(const Venue& Venue):
location(Venue.location), title(Venue.title), address(Venue.address)
{
foursquare_id = Venue.foursquare_id;
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Setter Section //
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
void Venue::setFoursquare_id(const optional<string> &foursquare_id) {
Venue::foursquare_id = foursquare_id;
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Getter Section //
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
const Location &Venue::getLocation() const {
return location;
}
const string &Venue::getTitle() const {
return title;
}
const string &Venue::getAddress() const {
return address;
}
const optional<string> &Venue::getFoursquare_id() const {
return foursquare_id;
}
| [
"[email protected]"
] | |
c566087d081809fc854ea91aaa2a7b63d67a2a02 | 46cd3608c7307c3fc140026b901ac2fac87fb418 | /Application/Source/SceneUI.cpp | e8e964ec604003077e4644de552ebf340028e6a0 | [
"Apache-2.0"
] | permissive | zshaqeel/SP2 | d795a2e9a4b7d4b072b0dd84e23a4605c23c1b31 | ff4e0373ef7e5864ae89f46d75037381b16b447e | refs/heads/main | 2023-03-04T21:30:30.307243 | 2021-02-15T01:48:47 | 2021-02-15T01:48:47 | 338,936,808 | 0 | 0 | Apache-2.0 | 2021-02-15T01:02:52 | 2021-02-15T01:02:52 | null | UTF-8 | C++ | false | false | 14,104 | cpp | #include "SceneUI.h"
#include "Utility.h"
#include "LoadTGA.h"
#include <iostream>
SceneUI::SceneUI() {}
SceneUI::~SceneUI() {}
void SceneUI::Init() {
glClearColor(0.4f, 0.4f, 0.4f, 0.0f);
m_programID = LoadShaders("Shader//Texture.vertexshader", "Shader//Text.fragmentshader");
m_parameters[U_MVP] = glGetUniformLocation(m_programID, "MVP");
m_parameters[U_MODELVIEW] = glGetUniformLocation(m_programID, "MV");
m_parameters[U_MODELVIEW_INVERSE_TRANSPOSE] = glGetUniformLocation(m_programID, "MV_inverse_transpose");
m_parameters[U_MATERIAL_AMBIENT] = glGetUniformLocation(m_programID, "material.kAmbient");
m_parameters[U_MATERIAL_DIFFUSE] = glGetUniformLocation(m_programID, "material.kDiffuse");
m_parameters[U_MATERIAL_SPECULAR] = glGetUniformLocation(m_programID, "material.kSpecular");
m_parameters[U_MATERIAL_SHININESS] = glGetUniformLocation(m_programID, "material.kShininess");
m_parameters[U_LIGHT0_POSITION] = glGetUniformLocation(m_programID, "lights[0].position_cameraspace");
m_parameters[U_LIGHT0_COLOR] = glGetUniformLocation(m_programID, "lights[0].color");
m_parameters[U_LIGHT0_POWER] = glGetUniformLocation(m_programID, "lights[0].power");
m_parameters[U_LIGHT0_KC] = glGetUniformLocation(m_programID, "lights[0].kC");
m_parameters[U_LIGHT0_KL] = glGetUniformLocation(m_programID, "lights[0].kL");
m_parameters[U_LIGHT0_KQ] = glGetUniformLocation(m_programID, "lights[0].kQ");
m_parameters[U_LIGHT0_TYPE] = glGetUniformLocation(m_programID, "lights[0].type");
m_parameters[U_LIGHT0_SPOTDIRECTION] = glGetUniformLocation(m_programID, "lights[0].spotDirection");
m_parameters[U_LIGHT0_COSCUTOFF] = glGetUniformLocation(m_programID, "lights[0].cosCutoff");
m_parameters[U_LIGHT0_COSINNER] = glGetUniformLocation(m_programID, "lights[0].cosInner");
m_parameters[U_LIGHT0_EXPONENT] = glGetUniformLocation(m_programID, "lights[0].exponent");
m_parameters[U_LIGHTENABLED] = glGetUniformLocation(m_programID, "lightEnabled");
m_parameters[U_NUMLIGHTS] = glGetUniformLocation(m_programID, "numLights");
m_parameters[U_COLOR_TEXTURE_ENABLED] = glGetUniformLocation(m_programID, "colorTextureEnabled");
m_parameters[U_COLOR_TEXTURE] = glGetUniformLocation(m_programID, "colorTexture");
m_parameters[U_TEXT_ENABLED] = glGetUniformLocation(m_programID, "textEnabled");
m_parameters[U_TEXT_COLOR] = glGetUniformLocation(m_programID, "textColor");
glUseProgram(m_programID);
light[0].type = Light::LIGHT_SPOT;
light[0].position.Set(0, 0, 0);
light[0].color = YELLOW;
light[0].power = 5;
light[0].kC = 1.f;
light[0].kL = 0.01f;
light[0].kQ = 0.001f;
light[0].cosCutoff = cos(Math::DegreeToRadian(45));
light[0].cosInner = cos(Math::DegreeToRadian(30));
light[0].exponent = 3.f;
light[0].spotDirection.Set(0.f, 1.f, 0.f);
lighton = true;
glUniform1i(m_parameters[U_LIGHT0_TYPE], light[0].type);
glUniform3fv(m_parameters[U_LIGHT0_COLOR], 1, &light[0].color.r);
glUniform1f(m_parameters[U_LIGHT0_POWER], light[0].power);
glUniform1f(m_parameters[U_LIGHT0_KC], light[0].kC);
glUniform1f(m_parameters[U_LIGHT0_KL], light[0].kL);
glUniform1f(m_parameters[U_LIGHT0_KQ], light[0].kQ);
glUniform1f(m_parameters[U_LIGHT0_COSCUTOFF], light[0].cosCutoff);
glUniform1f(m_parameters[U_LIGHT0_COSINNER], light[0].cosInner);
glUniform1f(m_parameters[U_LIGHT0_EXPONENT], light[0].exponent);
glUniform1i(m_parameters[U_NUMLIGHTS], 1);
glGenVertexArrays(1, &m_vertexArrayID);
glBindVertexArray(m_vertexArrayID);
meshList[GEO_AXES] = MeshBuilder::GenerateAxes("reference", 100.f, 100.f, 100.f);
meshList[GEO_FRONT] = MeshBuilder::GenerateQuad("front", WHITE, 1.f, 1.f);
meshList[GEO_FRONT]->textureID = LoadTGA("Image//front-space.tga");
meshList[GEO_BACK] = MeshBuilder::GenerateQuad("back", WHITE, 1.f, 1.f);
meshList[GEO_BACK]->textureID = LoadTGA("Image//back-space.tga");
meshList[GEO_LEFT] = MeshBuilder::GenerateQuad("left", WHITE, 1.f, 1.f);
meshList[GEO_LEFT]->textureID = LoadTGA("Image//right-space.tga");
meshList[GEO_RIGHT] = MeshBuilder::GenerateQuad("right", WHITE, 1.f, 1.f);
meshList[GEO_RIGHT]->textureID = LoadTGA("Image//left-space.tga");
meshList[GEO_TOP] = MeshBuilder::GenerateQuad("top", WHITE, 1.f, 1.f);
meshList[GEO_TOP]->textureID = LoadTGA("Image//top-space.tga");
meshList[GEO_BOTTOM] = MeshBuilder::GenerateQuad("bottom", WHITE, 1.f, 1.f);
meshList[GEO_BOTTOM]->textureID = LoadTGA("Image//bottom-space.tga");
meshList[GEO_BUTTON] = MeshBuilder::GenerateQuad("button", WHITE, 1.f, 1.f);
meshList[GEO_BUTTON]->textureID = LoadTGA("Image//button.tga");
meshList[GEO_TEXT] = MeshBuilder::GenerateText("text", 16, 16);
meshList[GEO_TEXT]->textureID = LoadTGA("Image//calibri.tga");
bounds = 300.f;
float fov = 45.f;
camera.Init(Vector3(1, 0, 1), Vector3(0, 0, 0), Vector3(0, 1, 0), fov);
Mtx44 projection;
projection.SetToPerspective(fov, 40.0f / 30.0f, 0.1f, bounds);
projectionStack.LoadMatrix(projection);
Reset();
glEnable(GL_BLEND);
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
glEnable(GL_DEPTH_TEST);
//glEnable(GL_CULL_FACE);
glPolygonMode(GL_FRONT_AND_BACK, GL_FILL);
}
void SceneUI::Update(double dt) {
Mouse mouse;
this->Update(dt, mouse);
}
void SceneUI::Update(double dt, Mouse mouse) {
float fps = (1.f / dt);
if (Application::IsKeyPressed('1')) {
glEnable(GL_CULL_FACE);
}
if (Application::IsKeyPressed('2')) {
glDisable(GL_CULL_FACE);
}
if (Application::IsKeyPressed('3')) {
glPolygonMode(GL_FRONT_AND_BACK, GL_FILL);
}
if (Application::IsKeyPressed('4')) {
glPolygonMode(GL_FRONT_AND_BACK, GL_LINE);
}
if (Application::IsKeyPressed('5')) {
light[0].type = Light::LIGHT_POINT;
glUniform1i(m_parameters[U_LIGHT0_TYPE], light[0].type);
}
if (Application::IsKeyPressed('6')) {
light[0].type = Light::LIGHT_DIRECTIONAL;
glUniform1i(m_parameters[U_LIGHT0_TYPE], light[0].type);
}
if (Application::IsKeyPressed('7')) {
light[0].type = Light::LIGHT_SPOT;
glUniform1i(m_parameters[U_LIGHT0_TYPE], light[0].type);
}
if (Application::IsKeyPressed('0')) {
lighton = false;
}
if (Application::IsKeyPressed('9')) {
lighton = true;
}
if (Application::IsKeyPressed('R')) {
Reset();
}
if (Application::IsKeyPressed('C')) {
dt *= 2.0f;
}
unsigned LSPEED = 10.f;
light[0].position.x = camera.position.x;
light[0].position.y = camera.position.y;
light[0].position.z = camera.position.z;
//camera.Update(dt, mouse);
Mtx44 projection;
projection.SetToPerspective(camera.fov, 40.0f / 30.0f, 0.1f, bounds);
projectionStack.LoadMatrix(projection);
Render();
RenderTextOnScreen(meshList[GEO_TEXT], "SP2 - Group 2", WHITE, 4, 5, 55);
RenderImageOnScreen(meshList[GEO_BUTTON], 10, 40, 40);
RenderTextOnScreen(meshList[GEO_TEXT], "Play", BLACK, 4, 38, 38);
RenderImageOnScreen(meshList[GEO_BUTTON], 10, 40, 10);
RenderTextOnScreen(meshList[GEO_TEXT], "Quit", BLACK, 4, 38, 8);
//RenderImageOnScreen(meshList[GEO_CROSSHAIR], 4, 40, 30);
}
void SceneUI::RenderMesh(Mesh* mesh, bool enableLight) {
Mtx44 MVP, modelView, modelView_inverse_transpose;
MVP = projectionStack.Top() * viewStack.Top() * modelStack.Top();
glUniformMatrix4fv(m_parameters[U_MVP], 1, GL_FALSE, &MVP.a[0]);
modelView = viewStack.Top() * modelStack.Top();
glUniformMatrix4fv(m_parameters[U_MODELVIEW], 1, GL_FALSE, &modelView.a[0]);
if (enableLight && lighton) {
glUniform1i(m_parameters[U_LIGHTENABLED], 1);
modelView_inverse_transpose = modelView.GetInverse().GetTranspose();
glUniformMatrix4fv(m_parameters[U_MODELVIEW_INVERSE_TRANSPOSE], 1, GL_FALSE, &modelView_inverse_transpose.a[0]);
glUniform3fv(m_parameters[U_MATERIAL_AMBIENT], 1, &mesh->material.kAmbient.r);
glUniform3fv(m_parameters[U_MATERIAL_DIFFUSE], 1, &mesh->material.kDiffuse.r);
glUniform3fv(m_parameters[U_MATERIAL_SPECULAR], 1, &mesh->material.kSpecular.r);
glUniform1f(m_parameters[U_MATERIAL_SHININESS], mesh->material.kShininess);
} else {
glUniform1i(m_parameters[U_LIGHTENABLED], 0);
}
if (mesh->textureID > 0) {
glUniform1i(m_parameters[U_COLOR_TEXTURE_ENABLED], 1);
glActiveTexture(GL_TEXTURE0);
glBindTexture(GL_TEXTURE_2D, mesh->textureID);
glUniform1i(m_parameters[U_COLOR_TEXTURE], 0);
}
else {
glUniform1i(m_parameters[U_COLOR_TEXTURE_ENABLED], 0);
}
mesh->Render();
if (mesh->textureID > 0) {
glBindTexture(GL_TEXTURE_2D, 0);
}
}
void SceneUI::RenderText(Mesh* mesh, std::string text, Color color) {
if (!mesh || mesh->textureID <= 0) //Proper error check
return;
//glDisable(GL_DEPTH_TEST);
glUniform1i(m_parameters[U_TEXT_ENABLED], 1);
glUniform3fv(m_parameters[U_TEXT_COLOR], 1, &color.r);
glUniform1i(m_parameters[U_LIGHTENABLED], 0);
glUniform1i(m_parameters[U_COLOR_TEXTURE_ENABLED], 1);
glActiveTexture(GL_TEXTURE0);
glBindTexture(GL_TEXTURE_2D, mesh->textureID);
glUniform1i(m_parameters[U_COLOR_TEXTURE], 0);
for (unsigned i = 0; i < text.length(); ++i) {
Mtx44 characterSpacing;
characterSpacing.SetToTranslation(i * 0.1f, 0, 0); //1.0f is the spacing of each character, you may change this value
Mtx44 MVP = projectionStack.Top() * viewStack.Top() * modelStack.Top() * characterSpacing;
glUniformMatrix4fv(m_parameters[U_MVP], 1, GL_FALSE, &MVP.a[0]);
mesh->Render((unsigned)text[i] * 6, 6);
}
glBindTexture(GL_TEXTURE_2D, 0);
glUniform1i(m_parameters[U_TEXT_ENABLED], 0);
//glEnable(GL_DEPTH_TEST);
}
void SceneUI::RenderTextOnScreen(Mesh* mesh, std::string text, Color color, float size, float x, float y) {
if (!mesh || mesh->textureID <= 0) //Proper error check
return;
glDisable(GL_DEPTH_TEST);
Mtx44 ortho;
ortho.SetToOrtho(0, 80, 0, 60, -10, 10); //size of screen UI
projectionStack.PushMatrix();
projectionStack.LoadMatrix(ortho);
viewStack.PushMatrix();
viewStack.LoadIdentity(); //No need camera for ortho mode
modelStack.PushMatrix();
modelStack.LoadIdentity(); //Reset modelStack
modelStack.Translate(x, y, 0);
modelStack.Scale(size, size, size);
glUniform1i(m_parameters[U_TEXT_ENABLED], 1);
glUniform3fv(m_parameters[U_TEXT_COLOR], 1, &color.r);
glUniform1i(m_parameters[U_LIGHTENABLED], 0);
glUniform1i(m_parameters[U_COLOR_TEXTURE_ENABLED], 1);
glActiveTexture(GL_TEXTURE0);
glBindTexture(GL_TEXTURE_2D, mesh->textureID);
glUniform1i(m_parameters[U_COLOR_TEXTURE], 0);
for (unsigned i = 0; i < text.length(); ++i) {
Mtx44 characterSpacing;
characterSpacing.SetToTranslation(i * 0.5f, 0.5f, 0);
Mtx44 MVP = projectionStack.Top() * viewStack.Top() * modelStack.Top() * characterSpacing;
glUniformMatrix4fv(m_parameters[U_MVP], 1, GL_FALSE, &MVP.a[0]);
mesh->Render((unsigned)text[i] * 6, 6);
}
glBindTexture(GL_TEXTURE_2D, 0);
glUniform1i(m_parameters[U_TEXT_ENABLED], 0);
projectionStack.PopMatrix();
viewStack.PopMatrix();
modelStack.PopMatrix();
glEnable(GL_DEPTH_TEST);
}
void SceneUI::RenderImageOnScreen(Mesh* mesh, float size, float x, float y) {
if (!mesh || mesh->textureID <= 0) //Proper error check
return;
glDisable(GL_DEPTH_TEST);
Mtx44 ortho;
ortho.SetToOrtho(0, 80, 0, 60, -10, 10); //size of screen UI
projectionStack.PushMatrix();
projectionStack.LoadMatrix(ortho);
viewStack.PushMatrix();
viewStack.LoadIdentity(); //No need camera for ortho mode
modelStack.PushMatrix();
modelStack.LoadIdentity(); //Reset modelStack
modelStack.Translate(x, y, 0);
modelStack.Scale(size, size, size);
RenderMesh(mesh, false);
projectionStack.PopMatrix();
viewStack.PopMatrix();
modelStack.PopMatrix();
glEnable(GL_DEPTH_TEST);
}
void SceneUI::RenderSkybox() {
float translate = 40;
float scaleVal = (translate*2)+(translate*0.01f);
modelStack.PushMatrix();
modelStack.Translate(0, translate, 0);
modelStack.Rotate(90, 1, 0, 0);
modelStack.Rotate(270, 0, 0, 1);
modelStack.Scale(scaleVal, scaleVal, scaleVal);
RenderMesh(meshList[GEO_TOP], false);
modelStack.PopMatrix();
modelStack.PushMatrix();
modelStack.Translate(0, -translate, 0);
modelStack.Rotate(-90, 1, 0, 0);
modelStack.Rotate(90, 0, 0, 1);
modelStack.Scale(scaleVal, scaleVal, scaleVal);
RenderMesh(meshList[GEO_BOTTOM], false);
modelStack.PopMatrix();
modelStack.PushMatrix();
modelStack.Translate(0, 0, -translate);
modelStack.Scale(scaleVal, scaleVal, scaleVal);
RenderMesh(meshList[GEO_FRONT], false);
modelStack.PopMatrix();
modelStack.PushMatrix();
modelStack.Translate(0, 0, translate);
modelStack.Rotate(180, 0, 1, 0);
modelStack.Scale(scaleVal, scaleVal, scaleVal);
RenderMesh(meshList[GEO_BACK], false);
modelStack.PopMatrix();
modelStack.PushMatrix();
modelStack.Translate(translate, 0, 0);
modelStack.Rotate(-90, 0, 1, 0);
modelStack.Scale(scaleVal, scaleVal, scaleVal);
RenderMesh(meshList[GEO_RIGHT], false);
modelStack.PopMatrix();
modelStack.PushMatrix();
modelStack.Translate(-translate, 0, 0);
modelStack.Rotate(90, 0, 1, 0);
modelStack.Scale(scaleVal, scaleVal, scaleVal);
RenderMesh(meshList[GEO_LEFT], false);
modelStack.PopMatrix();
}
void SceneUI::Render() {
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
viewStack.LoadIdentity();
viewStack.LookAt(
1, 0, 1,
0, 0, 0,
0, 1, 0
);
modelStack.LoadIdentity();
if (light[0].type == Light::LIGHT_DIRECTIONAL) {
Vector3 lightDir(light[0].position.x, light[0].position.y, light[0].position.z);
Vector3 lightDirection_cameraspace = viewStack.Top() * lightDir;
glUniform3fv(m_parameters[U_LIGHT0_POSITION], 1, &lightDirection_cameraspace.x);
} else if (light[0].type == Light::LIGHT_SPOT) {
Position lightPosition_cameraspace = viewStack.Top() * light[0].position;
glUniform3fv(m_parameters[U_LIGHT0_POSITION], 1, &lightPosition_cameraspace.x);
Vector3 spotDirection_cameraspace = viewStack.Top() * light[0].spotDirection;
glUniform3fv(m_parameters[U_LIGHT0_SPOTDIRECTION], 1, &spotDirection_cameraspace.x);
} else {
Position lightPosition_cameraspace = viewStack.Top() * light[0].position;
glUniform3fv(m_parameters[U_LIGHT0_POSITION], 1, &lightPosition_cameraspace.x);
}
RenderSkybox();
}
void SceneUI::Exit() {
for (unsigned i = 0; i < NUM_GEOMETRY; i++) {
if (meshList[i]) delete meshList[i];
}
glDeleteProgram(m_programID);
}
void SceneUI::Reset() {
camera.Reset();
} | [
"[email protected]"
] | |
98f42772722108b16aa30c4754dfe5867f5315ff | 4bab98acf65c4625a8b3c757327a8a386f90dd32 | /ros2-windows/include/sensor_msgs/msg/nav_sat_status__rosidl_typesupport_connext_cpp.hpp | 38bd798ffe339ec71ff7c0e822f47f9d379d87ae | [] | no_license | maojoejoe/Peach-Thinning-GTRI-Agricultural-Robotics-VIP | e2afb08b8d7b3ac075e071e063229f76b25f883a | 8ed707edb72692698f270317113eb215b57ae9f9 | refs/heads/master | 2023-01-15T06:00:22.844468 | 2020-11-25T04:16:15 | 2020-11-25T04:16:15 | 289,108,482 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,444 | hpp | // generated from rosidl_typesupport_connext_cpp/resource/idl__rosidl_typesupport_connext_cpp.hpp.em
// with input from sensor_msgs:msg\NavSatStatus.idl
// generated code does not contain a copyright notice
#ifndef SENSOR_MSGS__MSG__NAV_SAT_STATUS__ROSIDL_TYPESUPPORT_CONNEXT_CPP_HPP_
#define SENSOR_MSGS__MSG__NAV_SAT_STATUS__ROSIDL_TYPESUPPORT_CONNEXT_CPP_HPP_
#include "rosidl_runtime_c/message_type_support_struct.h"
#include "rosidl_typesupport_interface/macros.h"
#include "sensor_msgs/msg/rosidl_typesupport_connext_cpp__visibility_control.h"
#include "sensor_msgs/msg/detail/nav_sat_status__struct.hpp"
#ifndef _WIN32
# pragma GCC diagnostic push
# pragma GCC diagnostic ignored "-Wunused-parameter"
# ifdef __clang__
# pragma clang diagnostic ignored "-Wdeprecated-register"
# pragma clang diagnostic ignored "-Wreturn-type-c-linkage"
# endif
#endif
#include "sensor_msgs/msg/dds_connext/NavSatStatus_Support.h"
#include "sensor_msgs/msg/dds_connext/NavSatStatus_Plugin.h"
#include "ndds/ndds_cpp.h"
#ifndef _WIN32
# pragma GCC diagnostic pop
#endif
// forward declaration of internal CDR Stream
struct ConnextStaticCDRStream;
// forward declaration of DDS types
class DDSDomainParticipant;
class DDSDataWriter;
class DDSDataReader;
namespace sensor_msgs
{
namespace msg
{
namespace typesupport_connext_cpp
{
DDS_TypeCode *
get_type_code__NavSatStatus();
bool
ROSIDL_TYPESUPPORT_CONNEXT_CPP_PUBLIC_sensor_msgs
convert_ros_message_to_dds(
const sensor_msgs::msg::NavSatStatus & ros_message,
sensor_msgs::msg::dds_::NavSatStatus_ & dds_message);
bool
ROSIDL_TYPESUPPORT_CONNEXT_CPP_PUBLIC_sensor_msgs
convert_dds_message_to_ros(
const sensor_msgs::msg::dds_::NavSatStatus_ & dds_message,
sensor_msgs::msg::NavSatStatus & ros_message);
bool
to_cdr_stream__NavSatStatus(
const void * untyped_ros_message,
ConnextStaticCDRStream * cdr_stream);
bool
to_message__NavSatStatus(
const ConnextStaticCDRStream * cdr_stream,
void * untyped_ros_message);
} // namespace typesupport_connext_cpp
} // namespace msg
} // namespace sensor_msgs
#ifdef __cplusplus
extern "C"
{
#endif
ROSIDL_TYPESUPPORT_CONNEXT_CPP_PUBLIC_sensor_msgs
const rosidl_message_type_support_t *
ROSIDL_TYPESUPPORT_INTERFACE__MESSAGE_SYMBOL_NAME(
rosidl_typesupport_connext_cpp,
sensor_msgs, msg,
NavSatStatus)();
#ifdef __cplusplus
}
#endif
#endif // SENSOR_MSGS__MSG__NAV_SAT_STATUS__ROSIDL_TYPESUPPORT_CONNEXT_CPP_HPP_
| [
"[email protected]"
] | |
a19391252e070f6e6574e49e4aea0e5274de2f9a | ec7a0f82cb3271da72eb38978b0110284f52e155 | /Projects/funciones/funciones/stdafx.cpp | 0bd29e71af25b369ea3fc656f8c9f032a0916697 | [] | no_license | vicsanjinez/reversing101 | b1fa0c5c0ce2e99afd2c83eb9a7241c5343096c3 | 57253153539e33addbd69a9e73c0a9b86c1aeaa6 | refs/heads/master | 2020-03-30T06:28:04.880735 | 2018-09-28T15:15:45 | 2018-09-28T15:15:45 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 296 | cpp | // stdafx.cpp : source file that includes just the standard includes
// funciones.pch will be the pre-compiled header
// stdafx.obj will contain the pre-compiled type information
#include "stdafx.h"
// TODO: reference any additional headers you need in STDAFX.H
// and not in this file
| [
"[email protected]"
] | |
95b25d88c0de5aec5d1f48a43069654248d6acae | 50a7d625dc134715f0316685f81cd3746a36f66c | /src/main.cpp | 1849295a026cf2286d78085c149b0db97ce1d847 | [] | no_license | xt1zer/sorts | fb290799c33f3b23bba974cb1e918ccb3dc7fdcb | c231685700fb1916c62d9544886af7adf62dc036 | refs/heads/master | 2023-08-19T04:52:45.037992 | 2020-10-02T21:55:31 | 2020-10-02T21:55:31 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 111 | cpp | #include "DynArray.h"
#include "Menu.h"
int main() {
DynArray arr;
menu(arr);
return 0;
} | [
"[email protected]"
] | |
90057c626fb5dcdb0b051c6ba063457dc7bd1c5b | e12376aadfc081042c5df6eeb9954091b8801493 | /vcf/src/thirdparty/win32/comet/registry.h | 5f5aa229190ffd1396a22284ae684cd13d6dd74d | [] | no_license | jimcrafton/visualcomponentframework | 65d5c4a72309884477089ce102ebc44f3eb28e27 | 87d7f44ad15bbf42fac6c8cd5fba3c6ecc51eb45 | refs/heads/master | 2022-11-30T05:44:27.210513 | 2022-11-19T01:29:35 | 2022-11-19T01:29:35 | 181,391,567 | 0 | 0 | null | null | null | null | WINDOWS-1252 | C++ | false | false | 32,538 | h | /** \file
* Windows Registry iteration and manipulation functions.
*/
/*
* Copyright © 2000, 2001 Paul Hollingsworth
*
* This material is provided "as is", with absolutely no warranty
* expressed or implied. Any use is at your own risk. Permission to
* use or copy this software for any purpose is hereby granted without
* fee, provided the above notices are retained on all copies.
* Permission to modify the code and to distribute modified code is
* granted, provided the above notices are retained, and a notice that
* the code was modified is included with the above copyright notice.
*
* This header is part of comet.
* http://www.lambdasoft.dk/comet
*/
#ifndef COMET_REGISTRY_H
#define COMET_REGISTRY_H
#include <windows.h>
#include <comet/reference_count.h>
#include <comet/assert.h>
#include <comet/tstring.h>
#ifdef __BORLANDC__
#define COMET_ITERATOR_VOID(tag) std::iterator<tag, void, void, void *, void >
#else
#ifndef __SGI_STL
#ifdef __MINGW32__
#define COMET_ITERATOR_VOID(tag) std::forward_iterator<tag, void>
#else
#ifdef _CPPLIB_VER
#define COMET_ITERATOR_VOID(tag) std::iterator<tag, void, void, void, void>
#else
#define COMET_ITERATOR_VOID(tag) std::iterator<tag, void, void>
#endif
#endif
#else
#define COMET_ITERATOR_VOID(tag) std::iterator<tag, void, void, void, void>
#endif
#endif
namespace comet {
/** Contains implementation of registry classes.
*/
namespace registry {
/// Unicode compatible string class used in registry operations.
// typedef std::basic_string<TCHAR> tstring;
namespace impl {
// Only when an iterator is dereferenced
// do we want to go about reading the value
// from the registry. This requires us to create
// a temporary object. But in order to overload
// operator->, our temporary object must overload
// operator-> - and often it doesn't.
// Proxy is here to effectively overload operator-> for the temporary
// object.
template<typename T>
class proxy
{
T t_;
public:
proxy(const T &t) : t_(t) {}
T *operator->()
{
return &t_;
}
const T *operator->() const
{
return &t_;
}
};
class key_base
{
HKEY key_;
mutable reference_count rc_;
static bool valid_key_(HKEY key) {
return key != 0;
}
void close_() {
if(valid_key_(key_) && (--rc_ == 0)) {
LONG errcode = ::RegCloseKey(key_);
COMET_ASSERT(ERROR_SUCCESS == errcode);
/* C4189 */ errcode;
}
key_ = 0; // invalidate key handle
}
public:
key_base(const key_base &rhs)
: key_(rhs.key_) {
if(valid_key_(key_))
++rhs.rc_;
rc_ = rhs.rc_;
}
key_base(HKEY key = 0) : key_(key) {
}
~key_base() throw() {
close_();
}
key_base &operator=(const key_base &rhs)
{
key_base tmp(rhs);
swap(tmp);
return *this;
}
void swap(key_base &rhs) throw() {
std::swap(key_, rhs.key_);
std::swap(rc_, rhs.rc_);
}
LONG open(const tstring &subkey,
REGSAM sam_desired,
HKEY *childkey) const {
*childkey = 0;
return ::RegOpenKeyEx(key_,
subkey.c_str(),
0,
sam_desired,
childkey);
}
HKEY open_nothrow(const tstring &subkey,
REGSAM sam_desired,
LONG *errcode) const {
HKEY childkey_ = 0;
LONG errcode_ = open(subkey,
sam_desired,
&childkey_);
if(errcode) *errcode = errcode_;
return childkey_;
}
LONG create(const tstring &subkey,
DWORD options,
REGSAM sam_desired,
LPSECURITY_ATTRIBUTES security_attributes,
LPDWORD disposition,
HKEY *childkey) const {
return ::RegCreateKeyEx(key_,
subkey.c_str(),
0,
REG_NONE,
options,
sam_desired,
security_attributes,
childkey,
disposition);
}
HKEY create_nothrow(const tstring &subkey,
DWORD options,
REGSAM sam_desired,
LPSECURITY_ATTRIBUTES security_attributes,
LPDWORD disposition,
LONG *errcode) const {
HKEY childkey = 0;
LONG errcode_ = create(subkey,
options,
sam_desired,
security_attributes,
disposition,
&childkey);
if(errcode) *errcode = errcode_;
return childkey;
}
LONG flush_nothrow() const {
return ::RegFlushKey(key_);
}
LONG delete_subkey_nothrow(const tstring &subkey) const {
return ::RegDeleteKey(key_, subkey.c_str());
}
LONG delete_value_nothrow(const tstring &value_name) const {
return ::RegDeleteValue(key_, value_name.c_str());
}
void close() {
close_();
}
HKEY get() const {
return key_;
}
bool is_valid() const throw()
{
return key_ ? true : false;
}
operator const void *() const throw()
{
return is_valid() ? this : 0;
}
}; // class key_base
// Enumerating through keys or values is
// very similar. These two class encapsulate
// all that is different between the two algorithms.
struct next_value
{
static LONG perform(HKEY key,
DWORD dwIndex,
LPTSTR lpName,
LPDWORD lpcName)
{
return ::RegEnumValue(key, dwIndex, lpName, lpcName, 0, 0, 0, 0);
}
};
struct next_key
{
static LONG perform(HKEY key,
DWORD dwIndex,
LPTSTR lpName,
LPDWORD lpcName)
{
return ::RegEnumKeyEx(key, dwIndex, lpName, lpcName, 0, 0, 0, 0);
}
};
} // namespace impl
/** \struct name_iterator registry.h comet/registry.h
* Iterates through a list of names. The names might be either key
* names or value names, depending on get_next.
*/
template<class error_policy, class get_next>
struct name_iterator : public COMET_ITERATOR_VOID(std::forward_iterator_tag)
{
// key_ is the only assignment that can fail. So
// we make it the first member, so that
// default assignment is exception safe.
impl::key_base key_;
DWORD index_;
DWORD buf_size_;
DWORD num_values_;
static void check_exception_(LONG errcode)
{
if(ERROR_SUCCESS != errcode)
error_policy::on_error(errcode);
}
// Is this iterator an end iterator?
bool is_end() const
{
return key_ ? false : true;
}
// Make this iterator an end
// iterator
void make_end()
{
key_.close();
}
public:
typedef tstring value_type;
name_iterator(const impl::key_base &key,
DWORD num_values,
DWORD buf_size)
: key_(key),
num_values_(num_values),
buf_size_(buf_size),
index_(0)
{
if(0 == num_values)
make_end();
}
void swap(name_iterator &rhs)
{
key_.swap(rhs.key_);
std::swap(index_, rhs.index_);
std::swap(buf_size_, rhs.buf_size_);
std::swap(num_values_, rhs.num_values_);
}
name_iterator &operator=(const name_iterator &rhs)
{
key_ = rhs.key_;
index_ = rhs.index_;
buf_size_ = rhs.buf_size_;
num_values_ = rhs.num_values_;
return *this;
}
impl::key_base key() const
{
return key_;
}
name_iterator()
{
make_end();
}
value_type operator*() const
{
tstring::value_type *buf = static_cast<tstring::value_type *>(_alloca(buf_size_));
DWORD dummy = buf_size_;
check_exception_(get_next::perform(key_.get(),
index_,
buf,
&dummy));
return buf;
}
impl::proxy<value_type> operator->() const
{
return **this;
}
name_iterator &operator++()
{
++index_;
if(index_ == num_values_)
make_end();
return *this;
}
name_iterator operator++(int) const
{
name_iterator retval = *this;
++(*this);
return retval;
}
bool operator==(const name_iterator &rhs) const
{
if(is_end()) return rhs.is_end();
if(rhs.is_end()) return is_end();
return index_ == rhs.index_;
}
bool operator!=(const name_iterator &rhs) const
{
return !(*this == rhs);
}
};
/** \class value registry.h comet/registry.h
* A pseudo-reference to a value in the registry.
* Assign to instances of this object to make changes to the corresponding registry value
* Read from this object to read values from the registry.
*/
template<class error_policy>
class value
{
impl::key_base key_;
tstring value_name_;
static void check_exception_(LONG errcode)
{
if(ERROR_SUCCESS != errcode)
error_policy::on_error(errcode);
}
static void type_mismatch()
{
error_policy::on_typemismatch();
}
LONG get_value_(DWORD *type,
BYTE *buffer,
DWORD *number_bytes) const
{
return ::RegQueryValueEx(key_.get(),
value_name_.c_str(),
0,
type,
buffer,
number_bytes);
}
void get_value(DWORD *type,
BYTE *buffer,
DWORD *number_bytes) const {
check_exception_(
get_value_(type,
buffer,
number_bytes)
);
}
LONG set_value_(DWORD type,
const BYTE *data,
DWORD number_bytes)
{
return ::RegSetValueEx(key_.get(),
value_name_.c_str(),
0,
type,
data,
number_bytes);
}
void set_value(DWORD type,
const BYTE *data,
DWORD number_bytes)
{
check_exception_(
set_value_(type,
data,
number_bytes));
}
tstring name() const
{
return value_name_;
}
public:
//! This can be used to query if a value exists.
/*!
For example:
\code
string get_thread_model(const regkey &clsid_key)
{
regkey::value_type t = clsid_key.open("InprocServer32", KEY_READ)["ThreadingModel"];
if(t.exists())
return t.str();
else
return "Single";
}
\endcode
*/
bool exists() const
{
return ERROR_SUCCESS == get_value_(0, 0, 0);
}
value(const impl::key_base &key,
const tstring &value_name)
: key_(key),
value_name_(value_name)
{
}
//! Non throwing swap
/*! This is for efficiency only.
operator= is overloaded to have a different
meaning (copying one part of the
registry to another part of the registry).
*/
void swap(value &rhs)
{
key_.swap(rhs.key_);
value_name_.swap(rhs.value_name_);
}
//! Get a value of any type. The arguments are passed directly to RegQueryValueEx
/*!
\param type Pointer to the type - can be 0
\param buffer Pointer to a buffer - can be 0
\param number_bytes Indicates size of the buffer - can be 0 if buffer is 0
*/
void get(DWORD *type,
BYTE *buffer,
DWORD *number_bytes) const
{
get_value(type,
buffer,
number_bytes);
}
//! Get a value - return errcode
/*!
\param type Pointer to the type - can be 0
\param buffer Pointer to a buffer - can be 0
\param number_bytes Indicates size of the buffer - can be 0 if buffer is 0
*/
LONG get_nothrow(DWORD *type,
BYTE *buffer,
DWORD *number_bytes) const
{
return get_value_(type, buffer, number_bytes);
}
//! Set a value arbitrarily. The arguments are passed directly to RegSetValueEx
/*!
\param type Type to set it to (e.g. REG_SZ)
\param buffer Pointer to a buffer
\param number_bytes Indicates size of the buffer
*/
void set(DWORD type,
const BYTE *buffer,
DWORD number_bytes)
{
set_value(type,
buffer,
number_bytes);
}
//! Set a value - return errcode
/*!
\param type Type to set it to (e.g. REG_SZ)
\param buffer Pointer to a buffer
\param number_bytes Indicates size of the buffer
*/
LONG set_nothrow(DWORD type,
const BYTE *buffer,
DWORD number_bytes)
{
return set_value_(type, buffer, bytes);
}
//! Interpret value as a string
/*!
\exception com_error If the type is not REG_SZ or REG_EXPAND_SZ (using standard error_policy)
*/
tstring str() const
{
DWORD number_bytes = 0;
DWORD type;
get_value(&type,
0,
&number_bytes);
if( (REG_SZ != type) && (REG_EXPAND_SZ != type))
type_mismatch();
BYTE *buffer = static_cast<BYTE *>(_alloca(number_bytes));
get_value(0,
buffer,
&number_bytes);
return tstring(reinterpret_cast<const tstring::value_type *>(buffer),
(number_bytes/sizeof(tstring::value_type)) - 1);
}
tstring str(const tstring& default_val) const
{
DWORD number_bytes = 0;
DWORD type;
if (get_value_(&type,
0,
&number_bytes) != ERROR_SUCCESS) return default_val;
if( (REG_SZ != type) && (REG_EXPAND_SZ != type))
type_mismatch();
BYTE *buffer = static_cast<BYTE *>(_alloca(number_bytes));
get_value(0,
buffer,
&number_bytes);
return tstring(reinterpret_cast<const tstring::value_type *>(buffer),
(number_bytes/sizeof(tstring::value_type)) - 1);
}
//! Implicit conversion to string.
operator tstring() const
{
return str();
}
//! Implicit conversion to unsigned int
operator DWORD() const
{
return dword();
}
//! Interpret value as a DWORD
/*!
\exception com_error If the type is not REG_DWORD or REG_DWORD_LITTLE_ENDIAN (using standard error_policy)
*/
DWORD dword() const
{
DWORD number_bytes = sizeof( DWORD );
DWORD type;
DWORD retval;
get_value(&type,
reinterpret_cast<BYTE *>(&retval),
&number_bytes);
if( (REG_DWORD != type) && (REG_DWORD_LITTLE_ENDIAN != type) )
type_mismatch();
return retval;
}
DWORD dword(DWORD default_val) const
{
DWORD number_bytes = sizeof( DWORD );
DWORD type;
DWORD retval;
if (get_value_(&type,
reinterpret_cast<BYTE *>(&retval),
&number_bytes) != ERROR_SUCCESS) return default_val;
if( (REG_DWORD != type) && (REG_DWORD_LITTLE_ENDIAN != type) )
type_mismatch();
return retval;
}
// These two operators are currently useless
// because VC++ 6.0 appears to have a bug -
// it claims that no conversion to pair<string,string>
// exists even though it clearly does here.
// However, it's possible these would be
// useful on other compilers (or future compilers).
operator std::pair<tstring, tstring>() const
{
return std::make_pair(name(), str());
}
operator std::pair<tstring, DWORD>() const
{
return std::make_pair(name(), dword());
}
//! Assign a string value and set the type to REG_SZ
value &operator=(const tstring &rhs)
{
set_value(REG_SZ,
reinterpret_cast<const BYTE *>(rhs.c_str()),
(rhs.length() + 1) * sizeof ( tstring::value_type));
return *this;
}
//! Assign a DWORD value and set the type to REG_DWORD
value &operator=(const DWORD &rhs)
{
set_value(REG_DWORD,
reinterpret_cast<const BYTE *>(&rhs),
sizeof (DWORD) );
return *this;
}
//! Assign an integer value - sets type to REG_DWORD
value &operator=(int rhs)
{
return *this = DWORD(rhs);
}
//! Assign value from another registry value
/*!
Because value objects always refer to a part of the registry,
this effectively copies a registry value
from somewhere else in the registry.
*/
value &operator=(const value &rhs)
{
DWORD type;
DWORD size;
rhs.get_value(&type,
0,
&size);
BYTE *buffer = static_cast<BYTE *>(_alloca(size));
rhs.get_value_(0,
buffer,
&size);
set_value(type,
buffer,
size);
return *this;
}
}; // class value
/** \class const_value_iterator registry.h comet/registry.h
* Forward const iterator over registry values.
*/
template<typename error_policy>
class const_value_iterator : public COMET_ITERATOR_VOID(std::forward_iterator_tag)
{
typedef const value<error_policy> second_type;
typedef std::pair<const tstring, second_type > value_type_;
value_type_ get_value() const
{
tstring name = *index_;
return std::make_pair(name, second_type(index_.key(), name) );
}
protected:
name_iterator<error_policy, impl::next_value> index_;
public:
typedef value_type_ value_type;
const_value_iterator(const impl::key_base &key,
DWORD num_values,
DWORD buf_size)
: index_(key, num_values, buf_size)
{
}
const_value_iterator() {}
void swap(const_value_iterator &rhs)
{
index_.swap(rhs.index_);
}
value_type operator*() const
{
return get_value();
}
const_value_iterator &operator++()
{
++index_;
return *this;
}
const_value_iterator operator++(int)
{
const_value_iterator retval(*this);
++(*this);
return retval;
}
impl::proxy<value_type> operator->()
{
return **this;
}
bool operator==(const const_value_iterator &rhs) const
{
return index_ == rhs.index_;
}
bool operator!=(const const_value_iterator &rhs) const
{
return index_ != rhs.index_;
}
};
/** \class value_iterator registry.h comet/registry.h
* Forward iterator over registry values.
*/
template<typename error_policy>
class value_iterator : public const_value_iterator<error_policy>
{
typedef value<error_policy> second_type;
typedef std::pair<const tstring, second_type> value_type_;
typedef const_value_iterator<error_policy> base;
value_type_ get_value() const
{
tstring name = *index_;
return std::make_pair(name, second_type(index_.key(), name) );
}
public:
typedef value_type_ value_type;
value_iterator(const impl::key_base &key,
DWORD num_values,
DWORD buf_size)
: base(key, num_values, buf_size) {}
value_iterator() {}
value_type operator*() const
{
return get_value();
}
value_iterator &operator++()
{
base::operator++();
return *this;
}
value_iterator operator++(int)
{
value_iterator retval(*this);
++(*this);
return retval;
}
impl::proxy<value_type> operator->()
{
return get_value();
}
bool operator==(const value_iterator &rhs) const
{
return index_ == rhs.index_;
}
bool operator!=(const value_iterator &rhs) const
{
return index_ != rhs.index_;
}
};
/** \struct collection registry.h comet/registry.h
* STL style container class for various types of registry based
* aggregations.
*/
template<typename error_policy,
typename iterator_,
typename const_iterator_ = iterator_>
struct collection
{
impl::key_base key_;
DWORD num_values_;
DWORD buf_size_;
public:
collection(const impl::key_base &key,
DWORD num_values,
DWORD buf_size)
: key_(key),
num_values_(num_values),
buf_size_(buf_size)
{
}
typedef iterator_ iterator;
typedef const_iterator_ const_iterator;
typedef typename iterator_::value_type value_type;
typedef size_t size_type;
//! Number of elements in the collection
size_type size() const { return num_values_; }
//! Exception safe swap
void swap(collection &rhs)
{
key_.swap(rhs.key_);
std::swap(num_values_, rhs.num_values_);
std::swap(buf_size_, rhs.buf_size_);
}
//! Get the first iterator
iterator begin()
{
return iterator(key_, num_values_, buf_size_);
}
//! Signature iterator marking the end of the sequence
iterator end()
{
return iterator();
}
const_iterator begin() const
{
return const_iterator(key_, num_values_, buf_size_);
}
const_iterator end() const
{
return const_iterator();
}
};
/** \class info registry.h comet/registry.h
* Structure returned by regkey.enumerate()
*/
template<typename error_policy>
class info
{
// Make key_ the first member - this
// ensures exception safe assignment.
impl::key_base key_;
// Number of values
DWORD num_values_;
// Maximum length of a value name
DWORD value_name_tchars_;
// Number of sub keys
DWORD num_subkeys_;
// Maximum length of a sub key name
DWORD subkey_name_tchars_;
static void check_exception_(LONG errcode)
{
if(ERROR_SUCCESS != errcode)
error_policy::on_error(errcode);
}
static DWORD bytes(DWORD tchars)
{
return (tchars + 1) * sizeof( tstring::value_type);
}
public:
info(const impl::key_base &key)
: key_(key)
{
check_exception_(::RegQueryInfoKey(key_.get(),
0, // lpClass - reserved
0, // lpcClass - reserved
0, // lpReserved
&num_subkeys_,
&subkey_name_tchars_,
0, // lpcMaxClassLen - I think this is also reserved
&num_values_,
&value_name_tchars_,
0, // lpcMaxValueLen - not necessary for us
0, // lpcbSecurityDescriptor
0)); // lpftLastWriteTime
}
//! Exception safe swap
void swap(info &rhs)
{
key_.swap(rhs.key_);
std::swap(num_subkeys_, rhs.num_subkeys_);
std::swap(subkey_name_tchars_, rhs.subkey_name_tchars_);
std::swap(value_name_tchars_, rhs.value_name_tchars_);
std::swap(num_values_, rhs.num_values_);
}
//! Type returned by values()
typedef collection<error_policy, value_iterator<error_policy>, const_value_iterator<error_policy> > values_type;
//! Type returned by value_names()
typedef collection<error_policy, name_iterator<error_policy, impl::next_value> > value_names_type;
//! Type returned by subkeys()
typedef collection<error_policy, name_iterator<error_policy, impl::next_key> > subkeys_type;
//! Number of values under this key (excluding the default value)
size_t num_values() const
{
return num_values_;
}
//! Number of subkeys under this key
size_t num_subkeys() const
{
return num_subkeys_;
}
//! Length of the longest value_name under this key (in TCHARs)
size_t max_value_name() const
{
return value_name_tchars_;
}
//! Length of the longest subkey name under this key (in TCHARs)
size_t max_subkey_name() const
{
return subkey_name_tchars_;
}
//! Return the collection of values
/*!
The value_type of the collection is std::pair<const std::basic_string<TCHAR>, regkey::mapped_type>
regkey::mapped_type has implicit conversions to unsigned int and std::basic_string however.
Example - copy all value-name/value pairs into a map
\code
typedef std::basic_string<TCHAR> tstring;
regkey::info_type info(regkey(HKEY_LOCAL_MACHINE).enumerate());
map<tstring, regkey::mapped_type> values_map;
copy(info.values().begin(), info.values().end(), inserter(values_map, values_map.end()));
\endcode
Example - copy all value-name/value pairs into a string map - exception will
be thrown if a non string value is encountered.
\code
typedef std::basic_string<TCHAR> tstring;
regkey::info_type info(regkey(HKEY_LOCAL_MACHINE).enumerate());
map<bstr_t, bstr_t> values_map;
copy(info.values().begin(), info.values().end(), inserter(values_map, values_map.end()));
\endcode
Example - copy all value-name/value pairs into a string/int map - exception will
be thrown if a non string value is encountered.
\code
typedef std::basic_string<TCHAR> tstring;
regkey::info_type info(regkey(HKEY_LOCAL_MACHINE).enumerate());
map<bstr_t, int> values_map;
copy(info.values().begin(), info.values().end(), inserter(values_map, values_map.end()));
\endcode
*/
values_type values() const
{
return values_type(key_, num_values_, bytes(value_name_tchars_));
}
//! Returns the collection of value names
/*! The value_type of the collection is std::basic_string<TCHAR>.
Example - copy all value names of HKEY_LOCAL_MACHINE into a list
\code
regkey::info_type info(regkey(HKEY_LOCAL_MACHINE).enumerate());
vector<string> value_names;
copy(info.value_names().begin(), info.value_names().end(), back_inserter(value_names));
\endcode
*/
value_names_type value_names() const
{
return value_names_type(key_, num_values_, bytes(value_name_tchars_));
}
//! Returns the collection of subkey names
/*! The value_type of the collection is std::basic_string<TCHAR>.
Example - copy all subkeys of HKEY_LOCAL_MACHINE into a list
\code
regkey::info_type info(regkey(HKEY_LOCAL_MACHINE).enumerate());
vector<string> subkey_names;
copy(info.subkeys().begin(), info.subkeys().end(), back_inserter(subkey_names));
\endcode
*/
subkeys_type subkeys() const
{
return subkeys_type(key_, num_subkeys_, bytes(subkey_name_tchars_));
}
};
#ifdef __BORLANDC__
using impl::key_base;
#endif
/** \class key registry.h comet/registry.h
* Registry key wrapper.
Because an HKEY cannot be duplicated in a platform independent way,
reference counting is used to enable copying of key objects.
Methods with the _nothrow suffix do not throw exceptions other than
std::bad_alloc.
Key instances can be used as output iterators for std::pair
assignments. The second argument of each pair must be assignable to
an instance of regkey::mapped_type. Currently, this means that the
second member of each pair must be convertable to either an int,
unsigned int, or std::basic_string<TCHAR>.
Example:
\code
regkey the_key = regkey(HKEY_LOCAL_MACHINE).open("Software\\Comet");
map<string,string> names;
names["one"] = "one";
names["two"] = "two";
copy(names.begin(), names.end(), the_key);
map<string,int> values;
values["three"] = 3;
values["four"] = 4;
copy(values.begin(), values.end(), the_key);
\endcode
*/
template<class error_policy>
class key : private impl::key_base {
private:
static void check_exception_(LONG errcode)
{
if(ERROR_SUCCESS != errcode)
error_policy::on_error(errcode);
}
public:
key(HKEY key_handle = 0) : key_base(key_handle) {}
//! Copy a key.
/*! In reality this
only increments a reference count.
We have to use reference counting
because ::DuplicateHandle does not
work for registry keys on windows 95/98.
*/
key(const key &rhs)
: key_base(rhs) {
}
//! Copy a key.
/*! This is useful for attaching to keys from a name iterator.
*/
key( const impl::key_base &rhs)
: key_base(rhs) {
}
void swap(key &rhs)
{
key_base::swap(rhs);
}
//! Operator overload to allow you to put key instances in a conditional.
/*! This operator allows you to write code like this:
\code
if(subkey = key(HKEY_LOCAL_MACHINE).open_nothrow(_T("Software")))
{
...
};
\endcode
const void * is used instead of the more obvious "bool" to disable
implicit conversions to int and the like.
Example:
\code
int success = key(HKEY_LOCAL_MACHINE).open_nothrow(_T("Software")); // Won't compile fortunately!!
\endcode
*/
operator const void *() const throw()
{
return is_valid() ? this : 0;
}
//! Open a subkey
key open(const tstring &subkey,
REGSAM sam_desired = KEY_ALL_ACCESS) const {
HKEY childkey_ = 0;
check_exception_(
key_base::open(subkey,
sam_desired,
&childkey_)
);
return childkey_;
}
//! Open a subkey, no exceptions
key open_nothrow(const tstring &subkey,
REGSAM sam_desired = KEY_ALL_ACCESS,
LONG *errcode = 0) const {
return key_base::open_nothrow(subkey,
sam_desired, errcode);
}
//! Create a subkey
key create(const tstring &subkey,
DWORD options = REG_OPTION_NON_VOLATILE,
REGSAM sam_desired = KEY_ALL_ACCESS,
LPSECURITY_ATTRIBUTES security_attributes = 0,
LPDWORD disposition = 0) const {
HKEY childkey_ = 0;
check_exception_(
key_base::create(subkey,
options,
sam_desired,
security_attributes,
disposition,
&childkey_)
);
return childkey_;
}
//! Create a subkey - no exceptions
key create_nothrow(const tstring &subkey,
DWORD options = REG_OPTION_NON_VOLATILE,
REGSAM sam_desired = KEY_ALL_ACCESS,
LPSECURITY_ATTRIBUTES security_attributes = 0,
LPDWORD disposition = 0,
LONG *errcode = 0) const {
return key_base::create_nothrow(subkey,
options,
sam_desired,
security_attributes,
disposition,
errcode);
}
//! Call RegFlushKey with the contained key
void flush() const {
check_exception_(
flush_nothrow()
);
}
//! Call RegFlushKey with the contained key - no exceptions
LONG flush_nothrow() const {
return key_base::flush_nothrow();
}
//! Delete the subkey
/*! Warning - the behaviour is different
between WinNT and Win95/98 if
sub keys are present.
See documentation for ::RegDeleteKey for
more information.
*/
void delete_subkey(const tstring &subkey) const {
check_exception_(
delete_subkey_nothrow(subkey.c_str())
);
}
//! Delete the subkey
/*! Warning - the behaviour is different
between WinNT and Win95/98 if
sub keys are present.
See documentation for ::RegDeleteKey for
more information.
*/
LONG delete_subkey_nothrow(const tstring &subkey) const {
return key_base::delete_subkey_nothrow(subkey);
}
//! delete a value
void delete_value(const tstring &value_name) const {
check_exception_(
delete_value_nothrow(value_name)
);
}
//! delete a value - no exceptions
LONG delete_value_nothrow(const tstring &value_name) const {
return key_base::delete_value_nothrow(value_name);
}
//! Release reference to the key.
/*! Note that this will only call ::RegCloseKey
if this was the last reference to the outstanding key.
This method is implicitly called by the destructor.
*/
void close() {
key_base::close();
}
//! Get access to the raw key without releasing ownership
HKEY get() const {
return key_base::get();
}
typedef value<error_policy> mapped_type;
// All of these methods are const because I figured
// it was more useful. It allows you to create
// temporary regkey objects for the purposes of
// updating.
//! Get a reference to a value in the registry.
/*! The returned value can be used on both sides of an assignment. Example:
\code
key.get_value("Name") = "Paul";
string name = key.get_value("Name");
cout << key.get_value("Name").str() << endl;
\endcode
*/
mapped_type get_value(const tstring &value_name = _T("")) const
{
return mapped_type(*this, value_name);
}
//! Subscript operator overload - syntactic sugar for get_value().
/*! Example:
\code
key["Name"] = "Paul";
string name = key["Name"];
cout << key["Name"].str() << endl;
\endcode
*/
mapped_type operator[](const tstring &value_name) const
{
return get_value(value_name);
}
//! Type returned by enumerate()
typedef info<error_policy> info_type;
//! Type returned by enumerate().subkeys()
typedef typename info_type::subkeys_type subkeys_type;
//! Type returned by enumerate().values()
typedef typename info_type::values_type values_type;
//! Type returned by enumerate().value_names()
typedef typename info_type::value_names_type value_names_type;
//! Enumerate the subkeys, values or value_names, or obtain other information about the key. See also info.
/*!
The enumerate() method effectively calls RegQueryInfoKey, so you should
minimize the number of calls to enumerate() if efficiency is
a concern. e.g.
The following
\code
regkey::info_type info = key.enumerate();
copy(info.values().begin(), info.values().end(), inserter(value_map, value_map.end()));
\endcode
is more efficient than
\code
copy(key.enumerate().values().begin(), key.enumerate().values().end(), inserter(value_map, value_map.end()));
\endcode
The second version will end up calling RegQueryInfoKey twice.
*/
info_type enumerate() const
{
return info_type(*this);
}
//! Part of making key into an output iterator
key &operator*()
{
return *this;
}
//! Assignment. This is designed to work with 'std::pair's - the value type of map classes
template<typename T>
key &operator=(const T &val)
{
get_value(val.first) = val.second;
return *this;
}
//! Exception safe assignment operator.
//! Can still throw std::bad_alloc due
//! to reference counting.
//template<>
key &operator=(const key &rhs)
{
key_base::operator=(rhs);
return *this;
}
//! Noop increment
key &operator++() { return *this; }
//! Noop decrement
key &operator++(int) { return *this; }
}; // class key
} // namespace registry
} // namespace comet
#endif // COMET_REGISTRY_H
| [
"ddiego@cccfda39-7811-0410-ae5f-bc4b32ab4073"
] | ddiego@cccfda39-7811-0410-ae5f-bc4b32ab4073 |
90f53818fec1b692b2ce8ba0bd293cd00a5b67e7 | 3f368f90e28b0084c3971c706f46b1e34c8a9aa1 | /src/test/key_tests.cpp | 3fd6d70a610aebd684457d27b605ddc7cc8c4a29 | [
"MIT"
] | permissive | AaronWashington/SIN-core | f3043ee4e561e97144e2b7695d22f011ccd16d64 | ec78b3b1d94457b2c3a521143d7bf68f474de189 | refs/heads/master | 2020-12-11T15:55:26.882477 | 2020-01-08T17:04:22 | 2020-01-08T17:04:22 | 233,890,392 | 1 | 0 | MIT | 2020-01-14T16:54:54 | 2020-01-14T16:54:53 | null | UTF-8 | C++ | false | false | 8,101 | cpp | // Copyright (c) 2012-2018 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include <key.h>
#include <key_io.h>
#include <script/script.h>
#include <uint256.h>
#include <util.h>
#include <utilstrencodings.h>
#include <test/test_sin.h>
#include <string>
#include <vector>
#include <boost/test/unit_test.hpp>
static const std::string strSecret1 = "5HxWvvfubhXpYYpS3tJkw6fq9jE9j18THftkZjHHfmFiWtmAbrj";
static const std::string strSecret2 = "5KC4ejrDjv152FGwP386VD1i2NYc5KkfSMyv1nGy1VGDxGHqVY3";
static const std::string strSecret1C = "Kwr371tjA9u2rFSMZjTNun2PXXP3WPZu2afRHTcta6KxEUdm1vEw";
static const std::string strSecret2C = "L3Hq7a8FEQwJkW1M2GNKDW28546Vp5miewcCzSqUD9kCAXrJdS3g";
static const std::string addr1 = "1QFqqMUD55ZV3PJEJZtaKCsQmjLT6JkjvJ";
static const std::string addr2 = "1F5y5E5FMc5YzdJtB9hLaUe43GDxEKXENJ";
static const std::string addr1C = "1NoJrossxPBKfCHuJXT4HadJrXRE9Fxiqs";
static const std::string addr2C = "1CRj2HyM1CXWzHAXLQtiGLyggNT9WQqsDs";
static const std::string strAddressBad = "1HV9Lc3sNHZxwj4Zk6fB38tEmBryq2cBiF";
BOOST_FIXTURE_TEST_SUITE(key_tests, BasicTestingSetup)
BOOST_AUTO_TEST_CASE(key_test1)
{
CKey key1 = DecodeSecret(strSecret1);
BOOST_CHECK(key1.IsValid() && !key1.IsCompressed());
CKey key2 = DecodeSecret(strSecret2);
BOOST_CHECK(key2.IsValid() && !key2.IsCompressed());
CKey key1C = DecodeSecret(strSecret1C);
BOOST_CHECK(key1C.IsValid() && key1C.IsCompressed());
CKey key2C = DecodeSecret(strSecret2C);
BOOST_CHECK(key2C.IsValid() && key2C.IsCompressed());
CKey bad_key = DecodeSecret(strAddressBad);
BOOST_CHECK(!bad_key.IsValid());
CPubKey pubkey1 = key1. GetPubKey();
CPubKey pubkey2 = key2. GetPubKey();
CPubKey pubkey1C = key1C.GetPubKey();
CPubKey pubkey2C = key2C.GetPubKey();
BOOST_CHECK(key1.VerifyPubKey(pubkey1));
BOOST_CHECK(!key1.VerifyPubKey(pubkey1C));
BOOST_CHECK(!key1.VerifyPubKey(pubkey2));
BOOST_CHECK(!key1.VerifyPubKey(pubkey2C));
BOOST_CHECK(!key1C.VerifyPubKey(pubkey1));
BOOST_CHECK(key1C.VerifyPubKey(pubkey1C));
BOOST_CHECK(!key1C.VerifyPubKey(pubkey2));
BOOST_CHECK(!key1C.VerifyPubKey(pubkey2C));
BOOST_CHECK(!key2.VerifyPubKey(pubkey1));
BOOST_CHECK(!key2.VerifyPubKey(pubkey1C));
BOOST_CHECK(key2.VerifyPubKey(pubkey2));
BOOST_CHECK(!key2.VerifyPubKey(pubkey2C));
BOOST_CHECK(!key2C.VerifyPubKey(pubkey1));
BOOST_CHECK(!key2C.VerifyPubKey(pubkey1C));
BOOST_CHECK(!key2C.VerifyPubKey(pubkey2));
BOOST_CHECK(key2C.VerifyPubKey(pubkey2C));
BOOST_CHECK(DecodeDestination(addr1) == CTxDestination(pubkey1.GetID()));
BOOST_CHECK(DecodeDestination(addr2) == CTxDestination(pubkey2.GetID()));
BOOST_CHECK(DecodeDestination(addr1C) == CTxDestination(pubkey1C.GetID()));
BOOST_CHECK(DecodeDestination(addr2C) == CTxDestination(pubkey2C.GetID()));
for (int n=0; n<16; n++)
{
std::string strMsg = strprintf("Very secret message %i: 11", n);
uint256 hashMsg = Hash(strMsg.begin(), strMsg.end());
// normal signatures
std::vector<unsigned char> sign1, sign2, sign1C, sign2C;
BOOST_CHECK(key1.Sign (hashMsg, sign1));
BOOST_CHECK(key2.Sign (hashMsg, sign2));
BOOST_CHECK(key1C.Sign(hashMsg, sign1C));
BOOST_CHECK(key2C.Sign(hashMsg, sign2C));
BOOST_CHECK( pubkey1.Verify(hashMsg, sign1));
BOOST_CHECK(!pubkey1.Verify(hashMsg, sign2));
BOOST_CHECK( pubkey1.Verify(hashMsg, sign1C));
BOOST_CHECK(!pubkey1.Verify(hashMsg, sign2C));
BOOST_CHECK(!pubkey2.Verify(hashMsg, sign1));
BOOST_CHECK( pubkey2.Verify(hashMsg, sign2));
BOOST_CHECK(!pubkey2.Verify(hashMsg, sign1C));
BOOST_CHECK( pubkey2.Verify(hashMsg, sign2C));
BOOST_CHECK( pubkey1C.Verify(hashMsg, sign1));
BOOST_CHECK(!pubkey1C.Verify(hashMsg, sign2));
BOOST_CHECK( pubkey1C.Verify(hashMsg, sign1C));
BOOST_CHECK(!pubkey1C.Verify(hashMsg, sign2C));
BOOST_CHECK(!pubkey2C.Verify(hashMsg, sign1));
BOOST_CHECK( pubkey2C.Verify(hashMsg, sign2));
BOOST_CHECK(!pubkey2C.Verify(hashMsg, sign1C));
BOOST_CHECK( pubkey2C.Verify(hashMsg, sign2C));
// compact signatures (with key recovery)
std::vector<unsigned char> csign1, csign2, csign1C, csign2C;
BOOST_CHECK(key1.SignCompact (hashMsg, csign1));
BOOST_CHECK(key2.SignCompact (hashMsg, csign2));
BOOST_CHECK(key1C.SignCompact(hashMsg, csign1C));
BOOST_CHECK(key2C.SignCompact(hashMsg, csign2C));
CPubKey rkey1, rkey2, rkey1C, rkey2C;
BOOST_CHECK(rkey1.RecoverCompact (hashMsg, csign1));
BOOST_CHECK(rkey2.RecoverCompact (hashMsg, csign2));
BOOST_CHECK(rkey1C.RecoverCompact(hashMsg, csign1C));
BOOST_CHECK(rkey2C.RecoverCompact(hashMsg, csign2C));
BOOST_CHECK(rkey1 == pubkey1);
BOOST_CHECK(rkey2 == pubkey2);
BOOST_CHECK(rkey1C == pubkey1C);
BOOST_CHECK(rkey2C == pubkey2C);
}
// test deterministic signing
std::vector<unsigned char> detsig, detsigc;
std::string strMsg = "Very deterministic message";
uint256 hashMsg = Hash(strMsg.begin(), strMsg.end());
BOOST_CHECK(key1.Sign(hashMsg, detsig));
BOOST_CHECK(key1C.Sign(hashMsg, detsigc));
BOOST_CHECK(detsig == detsigc);
BOOST_CHECK(detsig == ParseHex("304402205dbbddda71772d95ce91cd2d14b592cfbc1dd0aabd6a394b6c2d377bbe59d31d022014ddda21494a4e221f0824f0b8b924c43fa43c0ad57dccdaa11f81a6bd4582f6"));
BOOST_CHECK(key2.Sign(hashMsg, detsig));
BOOST_CHECK(key2C.Sign(hashMsg, detsigc));
BOOST_CHECK(detsig == detsigc);
BOOST_CHECK(detsig == ParseHex("3044022052d8a32079c11e79db95af63bb9600c5b04f21a9ca33dc129c2bfa8ac9dc1cd5022061d8ae5e0f6c1a16bde3719c64c2fd70e404b6428ab9a69566962e8771b5944d"));
BOOST_CHECK(key1.SignCompact(hashMsg, detsig));
BOOST_CHECK(key1C.SignCompact(hashMsg, detsigc));
BOOST_CHECK(detsig == ParseHex("1c5dbbddda71772d95ce91cd2d14b592cfbc1dd0aabd6a394b6c2d377bbe59d31d14ddda21494a4e221f0824f0b8b924c43fa43c0ad57dccdaa11f81a6bd4582f6"));
BOOST_CHECK(detsigc == ParseHex("205dbbddda71772d95ce91cd2d14b592cfbc1dd0aabd6a394b6c2d377bbe59d31d14ddda21494a4e221f0824f0b8b924c43fa43c0ad57dccdaa11f81a6bd4582f6"));
BOOST_CHECK(key2.SignCompact(hashMsg, detsig));
BOOST_CHECK(key2C.SignCompact(hashMsg, detsigc));
BOOST_CHECK(detsig == ParseHex("1c52d8a32079c11e79db95af63bb9600c5b04f21a9ca33dc129c2bfa8ac9dc1cd561d8ae5e0f6c1a16bde3719c64c2fd70e404b6428ab9a69566962e8771b5944d"));
BOOST_CHECK(detsigc == ParseHex("2052d8a32079c11e79db95af63bb9600c5b04f21a9ca33dc129c2bfa8ac9dc1cd561d8ae5e0f6c1a16bde3719c64c2fd70e404b6428ab9a69566962e8771b5944d"));
}
BOOST_AUTO_TEST_CASE(key_signature_tests)
{
// When entropy is specified, we should see at least one high R signature within 20 signatures
CKey key = DecodeSecret(strSecret1);
std::string msg = "A message to be signed";
uint256 msg_hash = Hash(msg.begin(), msg.end());
std::vector<unsigned char> sig;
bool found = false;
for (int i = 1; i <=20; ++i) {
sig.clear();
key.Sign(msg_hash, sig, false, i);
found = sig[3] == 0x21 && sig[4] == 0x00;
if (found) {
break;
}
}
BOOST_CHECK(found);
// When entropy is not specified, we should always see low R signatures that are less than 70 bytes in 256 tries
// We should see at least one signature that is less than 70 bytes.
found = true;
bool found_small = false;
for (int i = 0; i < 256; ++i) {
sig.clear();
std::string msg = "A message to be signed" + std::to_string(i);
msg_hash = Hash(msg.begin(), msg.end());
key.Sign(msg_hash, sig);
found = sig[3] == 0x20;
BOOST_CHECK(sig.size() <= 70);
found_small |= sig.size() < 70;
}
BOOST_CHECK(found);
BOOST_CHECK(found_small);
}
BOOST_AUTO_TEST_SUITE_END()
| [
"[email protected]"
] | |
754e6da51c624af94cf2ebdc46908a0db673d70a | 1711ba6906fcfbebe0f5e6b91c5a388bf694f88f | /Server/common/SerManager.h | 855e8e5d9930745830c84ff73e91065fe2c4b5d4 | [] | no_license | killvxk/remotectrl-1 | 00a19b6aeb006eb587d6b225e26bf8d5cf56a491 | c17fb3961918b624262e76f14a7cfb8ba226a311 | refs/heads/master | 2021-05-27T15:41:38.169865 | 2014-06-20T14:12:47 | 2014-06-20T14:12:47 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 912 | h | // SerManager.h: interface for the CSerManager class.
//
//////////////////////////////////////////////////////////////////////
#if !defined(AFX_SerManager_H__26C71561_C37D_44F2_B69C_DAF907C04CBE__INCLUDED_)
#define AFX_SerManager_H__26C71561_C37D_44F2_B69C_DAF907C04CBE__INCLUDED_
#if _MSC_VER > 1000
#pragma once
#endif // _MSC_VER > 1000
#include "Manager.h"
class CSerManager : public CManager
{
public:
CSerManager(CClientSocket *pClient);
virtual ~CSerManager();
virtual void OnReceive(LPBYTE lpBuffer, UINT nSize);
private:
LPBYTE getServerList();
void SendServicesList();
void StartStopService(LPBYTE lpBuffer, UINT nSize ,BOOL strp);
// void CreatService(LPBYTE lpBuffer, UINT nSize);
void DeleteService(LPBYTE lpBuffer, UINT nSize);
void DisableService(LPBYTE lpBuffer, UINT nSize, UCHAR strn);
};
#endif // !defined(AFX_SerManager_H__26C71561_C37D_44F2_B69C_DAF907C04CBE__INCLUDED_)
| [
"[email protected]"
] | |
e943646cada366c08e913120032e0b8165cd583e | 1a218c67ad04f99e52c37425fdb933b053af6244 | /Ch06/exercise6.12.cpp | 8931fb58dd0cdc94d0818a796f630edc48c83424 | [] | no_license | xiaonengmiao/Cpp_Primer | 5a91cd223c9b0870f4ab9a45c6f679333a98fa20 | be20a29b49be19f6959b7873077ea698da940bf6 | refs/heads/master | 2020-12-25T14:23:58.976008 | 2020-06-18T07:54:43 | 2020-06-18T07:54:43 | 66,343,361 | 1 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 274 | cpp | #include <iostream>
void swap(int &i, int &j)
{
int k = i;
i = j;
j = k;
}
int main()
{
for (int i, j; std::cout << "enter two ints:\n", std::cin >> i >> j; )
{
swap(i,j);
std::cout << i << " " << j << std::endl;
}
return 0;
}
| [
"[email protected]"
] | |
45a43f3c89905d88bc6bdcac6c671870e9e1d908 | 7e82040f3fbe2e67f16d188e7cd7c203c9984229 | /June 6/June 6 Solution.cpp | 38d995b1b8f1b484282a07d2c0791d01e5eb0830 | [] | no_license | Sanjays2402/LeetCode-June-Challenge | 2f888c855e3c1a1349cad33d95d8557141cb3f6e | f26584e8deff0f20a651948dbd2adffe7d0b1b0e | refs/heads/master | 2022-11-07T05:22:09.861640 | 2020-06-29T18:14:10 | 2020-06-29T18:14:10 | 268,486,362 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 420 | cpp | vector<pair<int, int>> reconstructQueue(vector<pair<int, int>>& people) {
auto comp = [](const pair<int, int>& p1, const pair<int, int>& p2)
{ return p1.first > p2.first || (p1.first == p2.first && p1.second < p2.second); };
sort(people.begin(), people.end(), comp);
vector<pair<int, int>> res;
for (auto& p : people)
res.insert(res.begin() + p.second, p);
return res;
}
| [
"[email protected]"
] | |
783bd834cf10cb377cd1f24d60eb0c89a3948846 | d21f797f3128c053d35dec1e8b3023677af6d8d4 | /1052.cpp | 3f6b7629e7698c5374ea16d1cd8f831885c58333 | [] | no_license | AmrMaghraby/uri | 4c1939e1cf63831ceb7aba6accf917ce16c42afe | 2b8fb2881227fea43fe6e4f8892703250f739f13 | refs/heads/master | 2021-01-13T00:51:54.760112 | 2016-05-04T15:03:55 | 2016-05-04T15:03:55 | 51,157,337 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 564 | cpp | #include<stdio.h>
#include<conio.h>
int main(){
int x;
scanf("%d",&x);
switch(x){
case 1 :printf("January\n");break;
case 2 :printf("February\n");break;
case 3 :printf("March\n");break;
case 4 :printf("April\n");break;
case 5 :printf("May\n");break;
case 6 :printf("June\n");break;
case 7 :printf("July\n");break;
case 8 :printf("August\n");break;
case 9 :printf("September\n");break;
case 10:printf("October\n");break;
case 11:printf("November\n");break;
case 12:printf("December\n");break;
}
getch();
}
| [
"[email protected]"
] | |
0ebc13514cbbc2b304ba791d4b0fd3bbff4dd22f | 9b1d9a6396433288ba60fab4198ed25f8ca494c8 | /imread/lib/_png.h | db2da34f6fe297b45347ef7f3a91bf3c6c507a70 | [
"MIT"
] | permissive | buratono/imread | 24fc4e473399b30e24f7537ea30543f605b78f39 | b197de415bf27ee7e44bafe8f40750729479a680 | refs/heads/master | 2021-01-16T19:01:59.360471 | 2014-06-16T18:17:58 | 2014-06-16T18:17:58 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 613 | h | // Copyright 2012 Luis Pedro Coelho <[email protected]>
// License: MIT (see COPYING.MIT file)
#ifndef LPC_PNG_H_INCLUDE_GUARD_WED_FEB__1_16_34_50_WET_2012
#define LPC_PNG_H_INCLUDE_GUARD_WED_FEB__1_16_34_50_WET_2012
class PNGFormat : public ImageFormat {
public:
bool can_read() const { return true; }
bool can_write() const { return true; }
std::auto_ptr<Image> read(byte_source* src, ImageFactory* factory, const options_map& opts);
void write(Image* input, byte_sink* output, const options_map& opts);
};
#endif // LPC_PNG_H_INCLUDE_GUARD_WED_FEB__1_16_34_50_WET_2012
| [
"[email protected]"
] | |
63dbb8bb29973b419bd8f1a84a476cae4c3f261d | 0e44257aa418a506b1bb2f76c715e403cb893f13 | /NWNXLib/API/Mac/API/unknown_sqlite_int64.hpp | a7334198dbc83cc8a6314b3751fec66669c8b08d | [
"MIT"
] | permissive | Silvard/nwnxee | 58bdfa023348edcc88f9d3cfd9ff77fdd6194058 | 0989acb86e4d2b2bdcf25f6eabc16df7a72fb315 | refs/heads/master | 2020-04-15T22:04:43.925619 | 2019-10-10T14:18:53 | 2019-10-10T14:18:53 | 165,058,523 | 0 | 0 | MIT | 2019-10-10T14:18:57 | 2019-01-10T12:44:36 | C++ | UTF-8 | C++ | false | false | 82 | hpp | #pragma once
namespace NWNXLib {
namespace API {
class sqlite_int64 { };
}
}
| [
"[email protected]"
] | |
ffa358543aaa7116c61ab182e5cbf8579ae38c0f | 2bec5a52ce1fb3266e72f8fbeb5226b025584a16 | /multdyn/inst/testfiles/dlmLplCpp/dlmLplCpp_DeepState_TestHarness.cpp | 3157e43e4e931f950c1499bce8fd1aebb02c2633 | [] | no_license | akhikolla/InformationHouse | 4e45b11df18dee47519e917fcf0a869a77661fce | c0daab1e3f2827fd08aa5c31127fadae3f001948 | refs/heads/master | 2023-02-12T19:00:20.752555 | 2020-12-31T20:59:23 | 2020-12-31T20:59:23 | 325,589,503 | 9 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 2,526 | cpp | // AUTOMATICALLY GENERATED BY RCPPDEEPSTATE PLEASE DO NOT EDIT BY HAND, INSTEAD EDIT
// dlmLplCpp_DeepState_TestHarness_generation.cpp and dlmLplCpp_DeepState_TestHarness_checks.cpp
#include <fstream>
#include <RInside.h>
#include <iostream>
#include <RcppDeepState.h>
#include <qs.h>
#include <DeepState.hpp>
arma::rowvec dlmLplCpp(NumericVector Yt_, NumericMatrix Ft_, double delta, double m0_, double CS0_, double n0, double d0);
TEST(multdyn_deepstate_test,dlmLplCpp_test){
RInside R;
std::cout << "input starts" << std::endl;
NumericVector Yt_ = RcppDeepState_NumericVector();
qs::c_qsave(Yt_,"/home/akhila/fuzzer_packages/fuzzedpackages/multdyn/inst/testfiles/dlmLplCpp/inputs/Yt_.qs",
"high", "zstd", 1, 15, true, 1);
std::cout << "Yt_ values: "<< Yt_ << std::endl;
NumericMatrix Ft_ = RcppDeepState_NumericMatrix();
qs::c_qsave(Ft_,"/home/akhila/fuzzer_packages/fuzzedpackages/multdyn/inst/testfiles/dlmLplCpp/inputs/Ft_.qs",
"high", "zstd", 1, 15, true, 1);
std::cout << "Ft_ values: "<< Ft_ << std::endl;
NumericVector delta(1);
delta[0] = RcppDeepState_double();
qs::c_qsave(delta,"/home/akhila/fuzzer_packages/fuzzedpackages/multdyn/inst/testfiles/dlmLplCpp/inputs/delta.qs",
"high", "zstd", 1, 15, true, 1);
std::cout << "delta values: "<< delta << std::endl;
NumericVector m0_(1);
m0_[0] = RcppDeepState_double();
qs::c_qsave(m0_,"/home/akhila/fuzzer_packages/fuzzedpackages/multdyn/inst/testfiles/dlmLplCpp/inputs/m0_.qs",
"high", "zstd", 1, 15, true, 1);
std::cout << "m0_ values: "<< m0_ << std::endl;
NumericVector CS0_(1);
CS0_[0] = RcppDeepState_double();
qs::c_qsave(CS0_,"/home/akhila/fuzzer_packages/fuzzedpackages/multdyn/inst/testfiles/dlmLplCpp/inputs/CS0_.qs",
"high", "zstd", 1, 15, true, 1);
std::cout << "CS0_ values: "<< CS0_ << std::endl;
NumericVector n0(1);
n0[0] = RcppDeepState_double();
qs::c_qsave(n0,"/home/akhila/fuzzer_packages/fuzzedpackages/multdyn/inst/testfiles/dlmLplCpp/inputs/n0.qs",
"high", "zstd", 1, 15, true, 1);
std::cout << "n0 values: "<< n0 << std::endl;
NumericVector d0(1);
d0[0] = RcppDeepState_double();
qs::c_qsave(d0,"/home/akhila/fuzzer_packages/fuzzedpackages/multdyn/inst/testfiles/dlmLplCpp/inputs/d0.qs",
"high", "zstd", 1, 15, true, 1);
std::cout << "d0 values: "<< d0 << std::endl;
std::cout << "input ends" << std::endl;
try{
dlmLplCpp(Yt_,Ft_,delta[0],m0_[0],CS0_[0],n0[0],d0[0]);
}
catch(Rcpp::exception& e){
std::cout<<"Exception Handled"<<std::endl;
}
}
| [
"[email protected]"
] | |
97751bfa207db0147ab385582c2db42dd9a5450e | 67a46851a67f0a93d7312c5a9a89c942e37b73eb | /algorithm/HDU-ACM/ambition0109/1197.cpp | b9dbbfea5ecd76c3f6682b8f339bed658b5828f9 | [] | no_license | zhangwj0101/codestudy | e8c0a0c55b0ee556c217dc58273711a18e4194c9 | 06ce3bb9f9d9f977e0e4dc7687c561ab74f1980b | refs/heads/master | 2021-01-15T09:28:32.054331 | 2016-09-17T11:11:06 | 2016-09-17T11:11:06 | 44,471,951 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,541 | cpp | ////////////////////System Comment////////////////////
////Welcome to Hangzhou Dianzi University Online Judge
////http://acm.hdu.edu.cn
//////////////////////////////////////////////////////
////Username: ambition0109
////Nickname: Ambition
////Run ID:
////Submit time: 2010-07-10 19:55:47
////Compiler: Visual C++
//////////////////////////////////////////////////////
////Problem ID: 1197
////Problem Title:
////Run result: Accept
////Run time:0MS
////Run memory:180KB
//////////////////System Comment End//////////////////
/*
* 1197.cpp
*
* Created on: 2010-7-10
* Author: ambition
*/
#include<cstdio>
#include<cstdlib>
using namespace std;
char T[16]={'0','1','2','3','4','5','6','7','8','9','a','b','c','d','e','f'};
int main()
{
int num,sum,temp,i,j;
char str[10];
for(num=2992;num<10000;num++)
{
itoa(num,str,10);
for(i=0,sum=0;str[i]!='\0';i++)
{
for(j=0;j<10;j++)
if(str[i]==T[j])
{sum+=j;break;}
}
itoa(num,str,12);
for(i=0,temp=0;str[i]!='\0';i++)
{
for(j=0;j<12;j++)
if(str[i]==T[j])
{temp+=j;break;}
}
if(temp!=sum) continue;
itoa(num,str,16);
for(i=0,temp=0;str[i]!='\0';i++)
{
for(j=0;j<16;j++)
if(str[i]==T[j])
{temp+=j;break;}
}
if(temp!=sum) continue;
printf("%d\n",num);
}
}
| [
"[email protected]"
] | |
66bd94a3eefde161747cbb42f55d04075fe88da7 | 28292986abd1db0806b9ff9e741053fbc0f7f306 | /ESP8266/libraries/Adapter/Adapter.cpp | 885482afeb3fcb259a2f547ae959edbfac45e88d | [] | no_license | toastedcode/ShopSense | 41726d4ce9c016ecf55c17b7b9ba01e4a3fc1c13 | a65c76ff82d97859f9c23fccc9a5e7afcd9761dd | refs/heads/master | 2021-01-10T02:44:10.956544 | 2018-05-31T18:59:22 | 2018-05-31T18:59:22 | 43,096,547 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 514 | cpp | // *****************************************************************************
// *****************************************************************************
// Adapter.cpp
//
// Author: Jason Tost
// Date: 11.2.2015
//
// *****************************************************************************
// *****************************************************************************
#include "Adapter.h"
Adapter::Adapter(
const String& id)
{
this->id = id;
protocol = 0;
}
Adapter::~Adapter()
{
}
| [
"[email protected]"
] | |
c715dde4c58753af06ccaa39aeee346663d1221f | 3fa3540923e616da6789e2d48fe7aa8ce58dd38b | /Coding Ninjas/A17/A17-1.cpp | 0903ef8a39ce66496890dfeb97189af9fedf0787 | [] | no_license | ib13/Coding-Practice | c0ad8e51e6fb7901d16415f1f1a62432bf6d78d3 | d5eea327b94d23c4e3287e4e05067e9be235a15b | refs/heads/master | 2020-05-09T08:48:49.449972 | 2019-09-13T12:05:27 | 2019-09-13T12:05:27 | 180,995,930 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,169 | cpp | #include <iostream>
#include <queue>
template <typename T>
class BinaryTreeNode
{
public:
T data;
BinaryTreeNode<T> *left;
BinaryTreeNode<T> *right;
BinaryTreeNode(T data)
{
this->data = data;
left = NULL;
right = NULL;
}
~BinaryTreeNode()
{
if (left)
delete left;
if (right)
delete right;
}
};
using namespace std;
///////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////
BinaryTreeNode<int> *searchInBST(BinaryTreeNode<int> *root, int k)
{
if (root == NULL)
return root;
if (root->data == k)
return root;
else if (k < root->data)
return searchInBST(root->left, k);
else
return searchInBST(root->right, k);
}
///////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////
BinaryTreeNode<int> *takeInput()
{
int rootData;
cin >> rootData;
if (rootData == -1)
{
return NULL;
}
BinaryTreeNode<int> *root = new BinaryTreeNode<int>(rootData);
queue<BinaryTreeNode<int> *> q;
q.push(root);
while (!q.empty())
{
BinaryTreeNode<int> *currentNode = q.front();
q.pop();
int leftChild, rightChild;
cin >> leftChild;
if (leftChild != -1)
{
BinaryTreeNode<int> *leftNode = new BinaryTreeNode<int>(leftChild);
currentNode->left = leftNode;
q.push(leftNode);
}
cin >> rightChild;
if (rightChild != -1)
{
BinaryTreeNode<int> *rightNode = new BinaryTreeNode<int>(rightChild);
currentNode->right = rightNode;
q.push(rightNode);
}
}
return root;
}
int main()
{
BinaryTreeNode<int> *root = takeInput();
int k;
cin >> k;
BinaryTreeNode<int> *ans = searchInBST(root, k);
if (ans != NULL)
{
cout << ans->data << endl;
}
delete root;
}
| [
"[email protected]"
] | |
e61166a921d0bdd82ac3ea91309163311a0af6e0 | 97cd58c8198dbb8016a78cb1fa7f658986a99a10 | /widget.hpp | 3ae9e2088b45046fd7a0742cae21cc054c03f552 | [] | no_license | bullk/albizzia | 434484f0f7da18af08181baed987fa3f3ffc23f3 | d82cd1ef47f351f0f37ce4662666b3bb60d0a00c | refs/heads/master | 2021-01-01T18:04:47.991745 | 2017-09-21T17:04:19 | 2017-09-21T17:04:19 | 98,239,536 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,066 | hpp | /*
*/
#ifndef WIDGET_H
#define WIDGET_H
//#include <stdlib.h>
#include <cairo/cairo.h>
#define COLOR_BG GRAY(0.2)
#define COLOR_WBG GRAY(0.0)
#define COLOR_BOR GRAY(0.4)
#define COLOR_TEXT GRAY(0.8)
#define ORANGE cairo_set_source_rgb (cr, 1.0, 0.7, 0.0)
#define GREEN cairo_set_source_rgb (cr, 0.5, 1.0, 0.2)
#define GRAY(f) cairo_set_source_rgb (cr, f, f, f)
class Widget
{
public:
Widget(int x, int y, int w, int h):
x_(x), y_(y), w_(w), h_(h),
mouse_pressed_(false), mouse_over_(false)
{
fprintf(stderr, "creating widget %d %d, %d %d \n", x_, y_, w_, h_);
}
~Widget()
{}
virtual void draw (cairo_t*)=0;
bool touches (double x, double y)
{
return (x >= x_ && x <= x_ + w_ && y >= y_ && y <= y_ + h_);
}
bool pressed () { return mouse_pressed_; }
virtual void press (unsigned int, unsigned int) { mouse_pressed_ = true; }
virtual void release () { mouse_pressed_ = false; }
virtual void highlight(double x, double y)
{
mouse_over_ = touches(x, y);
}
protected:
int x_, y_, w_, h_;
bool mouse_pressed_;
bool mouse_over_;
};
#endif
| [
"[email protected]"
] | |
b4bdbf215cebbfcbde4f3cf3e61754bd4258ea64 | 011006ca59cfe75fb3dd84a50b6c0ef6427a7dc3 | /codeChef/CCOOK.cpp | df30997831d3d45418c905dd8dfee2ed873103a4 | [] | no_license | ay2306/Competitive-Programming | 34f35367de2e8623da0006135cf21ba6aec34049 | 8cc9d953b09212ab32b513acf874dba4fa1d2848 | refs/heads/master | 2021-06-26T16:46:28.179504 | 2021-01-24T15:32:57 | 2021-01-24T15:32:57 | 205,185,905 | 5 | 3 | null | null | null | null | UTF-8 | C++ | false | false | 585 | cpp | #include<bits/stdc++.h>
#define ll unsigned long long int
#define mod 1000000007
using namespace std;
int main(){
ios_base::sync_with_stdio(false);
cin.tie(0);
cout.tie(0);
int t;
cin >> t;
while(t--){
int k = 0;
int a;
for(int i = 0; i < 5; ++i){
cin >> a;
if(a==1)k++;
}
switch(k){
case 0: cout << "Beginner\n";break;
case 1: cout << "Junior Developer\n";break;
case 2: cout << "Middle Developer\n";break;
case 3: cout << "Senior Developer\n";break;
case 4: cout << "Hacker\n";break;
case 5: cout << "Jeff Dean\n";break;
}
}
return 0;
}
| [
"[email protected]"
] | |
fd41928d22e53d28fe2196690ae9059d0f5bae55 | b53617ccf68a284d3d69b3202572e03a0668c311 | /TermProject/TermProject/GateClass.h | ebfb7c82dbb3df077085cfd321ebb73cf5ef89f0 | [] | no_license | ndavis98/CS1220TermProject | 6ce7efaf5a6f6163a99f65890221c042fac84b08 | 8dc26886834adbb81b900061319cd672a7c3727f | refs/heads/master | 2020-03-09T21:14:07.671420 | 2018-04-10T20:56:02 | 2018-04-10T20:56:02 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 635 | h | // Author: Alex McNeil
// Date: 4/10/2018
// Purpose: Header file for Gate class
#include <string>
#include "WireClass.h"
#ifndef Gate_H
#define Gate_H
using namespace std;
class Gate {
public:
Gate();//default constructor
Gate(string name, int Delay, Wire In1, Wire In2, Wire outPut); //specified constructor
string setName(const string name);
int setDelay(const int delay);
char setIn1(const char in1);
char setIn2(const char in1);
char setOutPut(const char outPut);
protected:
private:
string type;
int delay;
Wire in1;
Wire in2;
Wire outPut;
};
#endif //Gate_H
| [
"[email protected]"
] | |
73145ac266e2da42f2849fe993ff791198cdaa3e | 50b07ae70fe269dadfd9c433a14ff44182f77ee0 | /Old Contest and Practice Problems/ZOMCAV.cpp | 0909842aec74c097cd764c5eaa2f3aaca652d152 | [] | no_license | PrakharUniyal/CompiArchives | 393d72695dcf393500d7dd95d8980f9005139385 | d89d53ae06f47cd2e144aa1df2a255d4e67218a2 | refs/heads/master | 2022-11-24T15:26:35.536346 | 2020-07-30T16:55:40 | 2020-07-30T16:55:40 | 258,544,798 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 790 | cpp | #include <bits/stdc++.h>
using namespace std;
#define li long long
int main()
{
li t;
cin>>t;
while(t--)
{
li n;
cin>>n;
vector<li> c(n),h(n),chg(n+2),p(n);
for(int i=0;i<n;i++)
{
cin>>c[i];
chg[max(i+1-c[i],1LL)]++;chg[min(i+1+c[i]+1,n+1)]--;
}
for(int i=0;i<n;i++){cin>>h[i];}
li m=0;
for(int i=0;i<n;i++){m+=chg[i+1];p[i]=m;}
sort(p.begin(),p.end());
sort(h.begin(),h.end());
bool flag=false;
for(int i=0;i<n;i++)
{
if(p[i]!=h[i]) {flag=true; break;}
}
if(flag) cout<<"NO"<<endl;
else cout<<"YES"<<endl;
}
} | [
"[email protected]"
] | |
d04d5059c040f20b7720e5a2d9b01bbea0e7f17b | ece30e7058d8bd42bc13c54560228bd7add50358 | /DataCollector/mozilla/xulrunner-sdk/include/mozilla/dom/UnionConversions.h | 0bae2d65f823c876cd9f712ac922c3527f3590eb | [
"Apache-2.0"
] | permissive | andrasigneczi/TravelOptimizer | b0fe4d53f6494d40ba4e8b98cc293cb5451542ee | b08805f97f0823fd28975a36db67193386aceb22 | refs/heads/master | 2022-07-22T02:07:32.619451 | 2018-12-03T13:58:21 | 2018-12-03T13:58:21 | 53,926,539 | 1 | 0 | Apache-2.0 | 2022-07-06T20:05:38 | 2016-03-15T08:16:59 | C++ | UTF-8 | C++ | false | false | 112,261 | h | #ifndef mozilla_dom_UnionConversions_h
#define mozilla_dom_UnionConversions_h
#include "AudioTrackBinding.h"
#include "BlobBinding.h"
#include "CanvasRenderingContext2DBinding.h"
#include "ClientBinding.h"
#include "ConsoleBinding.h"
#include "ConstraintsBinding.h"
#include "ContactsBinding.h"
#include "DOMMobileMessageErrorBinding.h"
#include "DataStoreBinding.h"
#include "DirectoryBinding.h"
#include "DocumentBinding.h"
#include "ElementBinding.h"
#include "EventBinding.h"
#include "EventHandlerBinding.h"
#include "ExternalBinding.h"
#include "FetchBinding.h"
#include "FetchEventBinding.h"
#include "FileBinding.h"
#include "FontFaceBinding.h"
#include "FormDataBinding.h"
#include "GeometryUtilsBinding.h"
#include "HTMLAllCollectionBinding.h"
#include "HTMLCanvasElementBinding.h"
#include "HTMLCollectionBinding.h"
#include "HTMLElementBinding.h"
#include "HTMLFormControlsCollectionBinding.h"
#include "HTMLImageElementBinding.h"
#include "HTMLOptGroupElementBinding.h"
#include "HTMLOptionElementBinding.h"
#include "HTMLVideoElementBinding.h"
#include "HeadersBinding.h"
#include "IDBCursorBinding.h"
#include "IDBIndexBinding.h"
#include "IDBObjectStoreBinding.h"
#include "IDBRequestBinding.h"
#include "InstallTriggerBinding.h"
#include "MediaStreamBinding.h"
#include "MediaStreamTrackBinding.h"
#include "MediaTrackConstraintSetBinding.h"
#include "MessageEventBinding.h"
#include "MessagePortBinding.h"
#include "MozIccBinding.h"
#include "MozIccInfoBinding.h"
#include "MozMobileConnectionBinding.h"
#include "MozMobileMessageManagerBinding.h"
#include "NavigatorBinding.h"
#include "NodeBinding.h"
#include "PromiseBinding.h"
#include "RadioNodeListBinding.h"
#include "RequestBinding.h"
#include "ResourceStatsBinding.h"
#include "ResponseBinding.h"
#include "SubtleCryptoBinding.h"
#include "TelephonyBinding.h"
#include "TelephonyCallBinding.h"
#include "TelephonyCallGroupBinding.h"
#include "TextBinding.h"
#include "TextTrackBinding.h"
#include "TrackEventBinding.h"
#include "URLSearchParamsBinding.h"
#include "VTTCueBinding.h"
#include "VideoTrackBinding.h"
#include "WebGL2RenderingContextBinding.h"
#include "WebGLRenderingContextBinding.h"
#include "WindowBinding.h"
#include "jsfriendapi.h"
#include "mozilla/dom/MozMap.h"
#include "mozilla/dom/PrimitiveConversions.h"
#include "mozilla/dom/TypedArray.h"
#include "mozilla/dom/UnionTypes.h"
#include "nsDebug.h"
#include "nsIDOMMozMmsMessage.h"
#include "nsIDOMMozSmsMessage.h"
#include "nsIDOMWindow.h"
namespace mozilla {
namespace dom {
class ArrayBufferOrArrayBufferViewOrBlobOrFormDataOrUSVStringOrURLSearchParamsArgument
{
ArrayBufferOrArrayBufferViewOrBlobOrFormDataOrUSVStringOrURLSearchParams& mUnion;
ArrayBufferOrArrayBufferViewOrBlobOrFormDataOrUSVStringOrURLSearchParamsArgument(const ArrayBufferOrArrayBufferViewOrBlobOrFormDataOrUSVStringOrURLSearchParamsArgument&) = delete;
void operator=(const ArrayBufferOrArrayBufferViewOrBlobOrFormDataOrUSVStringOrURLSearchParamsArgument) = delete;
public:
explicit inline ArrayBufferOrArrayBufferViewOrBlobOrFormDataOrUSVStringOrURLSearchParamsArgument(const ArrayBufferOrArrayBufferViewOrBlobOrFormDataOrUSVStringOrURLSearchParams& aUnion)
: mUnion(const_cast<ArrayBufferOrArrayBufferViewOrBlobOrFormDataOrUSVStringOrURLSearchParams&>(aUnion))
{
}
inline bool
TrySetToArrayBuffer(JSContext* cx, JS::Handle<JS::Value> value, bool& tryNext, bool passedToJSImpl = false)
{
tryNext = false;
{ // scope for memberSlot
RootedTypedArray<ArrayBuffer>& memberSlot = RawSetAsArrayBuffer(cx);
if (!memberSlot.Init(&value.toObject())) {
mUnion.DestroyArrayBuffer();
tryNext = true;
return true;
}
}
return true;
}
inline bool
TrySetToArrayBufferView(JSContext* cx, JS::Handle<JS::Value> value, bool& tryNext, bool passedToJSImpl = false)
{
tryNext = false;
{ // scope for memberSlot
RootedTypedArray<ArrayBufferView>& memberSlot = RawSetAsArrayBufferView(cx);
if (!memberSlot.Init(&value.toObject())) {
mUnion.DestroyArrayBufferView();
tryNext = true;
return true;
}
}
return true;
}
inline bool
TrySetToBlob(JSContext* cx, JS::Handle<JS::Value> value, bool& tryNext, bool passedToJSImpl = false)
{
tryNext = false;
{ // scope for memberSlot
NonNull<mozilla::dom::Blob>& memberSlot = RawSetAsBlob();
{
nsresult rv = UnwrapObject<prototypes::id::Blob, mozilla::dom::Blob>(&value.toObject(), memberSlot);
if (NS_FAILED(rv)) {
mUnion.DestroyBlob();
tryNext = true;
return true;
}
}
}
return true;
}
inline bool
TrySetToFormData(JSContext* cx, JS::Handle<JS::Value> value, bool& tryNext, bool passedToJSImpl = false)
{
tryNext = false;
{ // scope for memberSlot
NonNull<nsFormData>& memberSlot = RawSetAsFormData();
{
nsresult rv = UnwrapObject<prototypes::id::FormData, nsFormData>(&value.toObject(), memberSlot);
if (NS_FAILED(rv)) {
mUnion.DestroyFormData();
tryNext = true;
return true;
}
}
}
return true;
}
inline bool
TrySetToUSVString(JSContext* cx, JS::Handle<JS::Value> value, bool& tryNext, bool passedToJSImpl = false)
{
tryNext = false;
{ // scope for memberSlot
binding_detail::FakeString& memberSlot = RawSetAsUSVString();
if (!ConvertJSValueToString(cx, value, eStringify, eStringify, memberSlot)) {
return false;
}
NormalizeUSVString(cx, memberSlot);
}
return true;
}
inline void
SetStringData(const nsDependentString::char_type* aData, nsDependentString::size_type aLength)
{
RawSetAsUSVString().Rebind(aData, aLength);
}
inline bool
TrySetToURLSearchParams(JSContext* cx, JS::Handle<JS::Value> value, bool& tryNext, bool passedToJSImpl = false)
{
tryNext = false;
{ // scope for memberSlot
NonNull<mozilla::dom::URLSearchParams>& memberSlot = RawSetAsURLSearchParams();
{
nsresult rv = UnwrapObject<prototypes::id::URLSearchParams, mozilla::dom::URLSearchParams>(&value.toObject(), memberSlot);
if (NS_FAILED(rv)) {
mUnion.DestroyURLSearchParams();
tryNext = true;
return true;
}
}
}
return true;
}
private:
inline RootedTypedArray<ArrayBuffer>&
RawSetAsArrayBuffer(JSContext* cx)
{
MOZ_ASSERT(mUnion.mType == mUnion.eUninitialized);
mUnion.mType = mUnion.eArrayBuffer;
return mUnion.mValue.mArrayBuffer.SetValue(cx);
}
inline RootedTypedArray<ArrayBufferView>&
RawSetAsArrayBufferView(JSContext* cx)
{
MOZ_ASSERT(mUnion.mType == mUnion.eUninitialized);
mUnion.mType = mUnion.eArrayBufferView;
return mUnion.mValue.mArrayBufferView.SetValue(cx);
}
inline NonNull<mozilla::dom::Blob>&
RawSetAsBlob()
{
MOZ_ASSERT(mUnion.mType == mUnion.eUninitialized);
mUnion.mType = mUnion.eBlob;
return mUnion.mValue.mBlob.SetValue();
}
inline NonNull<nsFormData>&
RawSetAsFormData()
{
MOZ_ASSERT(mUnion.mType == mUnion.eUninitialized);
mUnion.mType = mUnion.eFormData;
return mUnion.mValue.mFormData.SetValue();
}
inline binding_detail::FakeString&
RawSetAsUSVString()
{
MOZ_ASSERT(mUnion.mType == mUnion.eUninitialized);
mUnion.mType = mUnion.eUSVString;
return mUnion.mValue.mUSVString.SetValue();
}
inline NonNull<mozilla::dom::URLSearchParams>&
RawSetAsURLSearchParams()
{
MOZ_ASSERT(mUnion.mType == mUnion.eUninitialized);
mUnion.mType = mUnion.eURLSearchParams;
return mUnion.mValue.mURLSearchParams.SetValue();
}
};
class ArrayBufferOrArrayBufferViewOrBlobOrStringArgument
{
ArrayBufferOrArrayBufferViewOrBlobOrString& mUnion;
ArrayBufferOrArrayBufferViewOrBlobOrStringArgument(const ArrayBufferOrArrayBufferViewOrBlobOrStringArgument&) = delete;
void operator=(const ArrayBufferOrArrayBufferViewOrBlobOrStringArgument) = delete;
public:
explicit inline ArrayBufferOrArrayBufferViewOrBlobOrStringArgument(const ArrayBufferOrArrayBufferViewOrBlobOrString& aUnion)
: mUnion(const_cast<ArrayBufferOrArrayBufferViewOrBlobOrString&>(aUnion))
{
}
inline bool
TrySetToArrayBuffer(JSContext* cx, JS::Handle<JS::Value> value, bool& tryNext, bool passedToJSImpl = false)
{
tryNext = false;
{ // scope for memberSlot
RootedTypedArray<ArrayBuffer>& memberSlot = RawSetAsArrayBuffer(cx);
if (!memberSlot.Init(&value.toObject())) {
mUnion.DestroyArrayBuffer();
tryNext = true;
return true;
}
}
return true;
}
inline bool
TrySetToArrayBufferView(JSContext* cx, JS::Handle<JS::Value> value, bool& tryNext, bool passedToJSImpl = false)
{
tryNext = false;
{ // scope for memberSlot
RootedTypedArray<ArrayBufferView>& memberSlot = RawSetAsArrayBufferView(cx);
if (!memberSlot.Init(&value.toObject())) {
mUnion.DestroyArrayBufferView();
tryNext = true;
return true;
}
}
return true;
}
inline bool
TrySetToBlob(JSContext* cx, JS::Handle<JS::Value> value, bool& tryNext, bool passedToJSImpl = false)
{
tryNext = false;
{ // scope for memberSlot
NonNull<mozilla::dom::Blob>& memberSlot = RawSetAsBlob();
{
nsresult rv = UnwrapObject<prototypes::id::Blob, mozilla::dom::Blob>(&value.toObject(), memberSlot);
if (NS_FAILED(rv)) {
mUnion.DestroyBlob();
tryNext = true;
return true;
}
}
}
return true;
}
inline bool
TrySetToString(JSContext* cx, JS::Handle<JS::Value> value, bool& tryNext, bool passedToJSImpl = false)
{
tryNext = false;
{ // scope for memberSlot
binding_detail::FakeString& memberSlot = RawSetAsString();
if (!ConvertJSValueToString(cx, value, eStringify, eStringify, memberSlot)) {
return false;
}
}
return true;
}
inline void
SetStringData(const nsDependentString::char_type* aData, nsDependentString::size_type aLength)
{
RawSetAsString().Rebind(aData, aLength);
}
private:
inline RootedTypedArray<ArrayBuffer>&
RawSetAsArrayBuffer(JSContext* cx)
{
MOZ_ASSERT(mUnion.mType == mUnion.eUninitialized);
mUnion.mType = mUnion.eArrayBuffer;
return mUnion.mValue.mArrayBuffer.SetValue(cx);
}
inline RootedTypedArray<ArrayBufferView>&
RawSetAsArrayBufferView(JSContext* cx)
{
MOZ_ASSERT(mUnion.mType == mUnion.eUninitialized);
mUnion.mType = mUnion.eArrayBufferView;
return mUnion.mValue.mArrayBufferView.SetValue(cx);
}
inline NonNull<mozilla::dom::Blob>&
RawSetAsBlob()
{
MOZ_ASSERT(mUnion.mType == mUnion.eUninitialized);
mUnion.mType = mUnion.eBlob;
return mUnion.mValue.mBlob.SetValue();
}
inline binding_detail::FakeString&
RawSetAsString()
{
MOZ_ASSERT(mUnion.mType == mUnion.eUninitialized);
mUnion.mType = mUnion.eString;
return mUnion.mValue.mString.SetValue();
}
};
class ArrayBufferViewOrArrayBufferArgument
{
ArrayBufferViewOrArrayBuffer& mUnion;
ArrayBufferViewOrArrayBufferArgument(const ArrayBufferViewOrArrayBufferArgument&) = delete;
void operator=(const ArrayBufferViewOrArrayBufferArgument) = delete;
public:
explicit inline ArrayBufferViewOrArrayBufferArgument(const ArrayBufferViewOrArrayBuffer& aUnion)
: mUnion(const_cast<ArrayBufferViewOrArrayBuffer&>(aUnion))
{
}
inline bool
TrySetToArrayBufferView(JSContext* cx, JS::Handle<JS::Value> value, bool& tryNext, bool passedToJSImpl = false)
{
tryNext = false;
{ // scope for memberSlot
RootedTypedArray<ArrayBufferView>& memberSlot = RawSetAsArrayBufferView(cx);
if (!memberSlot.Init(&value.toObject())) {
mUnion.DestroyArrayBufferView();
tryNext = true;
return true;
}
}
return true;
}
inline bool
TrySetToArrayBuffer(JSContext* cx, JS::Handle<JS::Value> value, bool& tryNext, bool passedToJSImpl = false)
{
tryNext = false;
{ // scope for memberSlot
RootedTypedArray<ArrayBuffer>& memberSlot = RawSetAsArrayBuffer(cx);
if (!memberSlot.Init(&value.toObject())) {
mUnion.DestroyArrayBuffer();
tryNext = true;
return true;
}
}
return true;
}
private:
inline RootedTypedArray<ArrayBufferView>&
RawSetAsArrayBufferView(JSContext* cx)
{
MOZ_ASSERT(mUnion.mType == mUnion.eUninitialized);
mUnion.mType = mUnion.eArrayBufferView;
return mUnion.mValue.mArrayBufferView.SetValue(cx);
}
inline RootedTypedArray<ArrayBuffer>&
RawSetAsArrayBuffer(JSContext* cx)
{
MOZ_ASSERT(mUnion.mType == mUnion.eUninitialized);
mUnion.mType = mUnion.eArrayBuffer;
return mUnion.mValue.mArrayBuffer.SetValue(cx);
}
};
class ArrayBufferViewOrBlobOrStringOrFormDataArgument
{
ArrayBufferViewOrBlobOrStringOrFormData& mUnion;
ArrayBufferViewOrBlobOrStringOrFormDataArgument(const ArrayBufferViewOrBlobOrStringOrFormDataArgument&) = delete;
void operator=(const ArrayBufferViewOrBlobOrStringOrFormDataArgument) = delete;
public:
explicit inline ArrayBufferViewOrBlobOrStringOrFormDataArgument(const ArrayBufferViewOrBlobOrStringOrFormData& aUnion)
: mUnion(const_cast<ArrayBufferViewOrBlobOrStringOrFormData&>(aUnion))
{
}
inline bool
TrySetToArrayBufferView(JSContext* cx, JS::Handle<JS::Value> value, bool& tryNext, bool passedToJSImpl = false)
{
tryNext = false;
{ // scope for memberSlot
RootedTypedArray<ArrayBufferView>& memberSlot = RawSetAsArrayBufferView(cx);
if (!memberSlot.Init(&value.toObject())) {
mUnion.DestroyArrayBufferView();
tryNext = true;
return true;
}
}
return true;
}
inline bool
TrySetToBlob(JSContext* cx, JS::Handle<JS::Value> value, bool& tryNext, bool passedToJSImpl = false)
{
tryNext = false;
{ // scope for memberSlot
NonNull<mozilla::dom::Blob>& memberSlot = RawSetAsBlob();
{
nsresult rv = UnwrapObject<prototypes::id::Blob, mozilla::dom::Blob>(&value.toObject(), memberSlot);
if (NS_FAILED(rv)) {
mUnion.DestroyBlob();
tryNext = true;
return true;
}
}
}
return true;
}
inline bool
TrySetToString(JSContext* cx, JS::Handle<JS::Value> value, bool& tryNext, bool passedToJSImpl = false)
{
tryNext = false;
{ // scope for memberSlot
binding_detail::FakeString& memberSlot = RawSetAsString();
if (!ConvertJSValueToString(cx, value, eStringify, eStringify, memberSlot)) {
return false;
}
}
return true;
}
inline void
SetStringData(const nsDependentString::char_type* aData, nsDependentString::size_type aLength)
{
RawSetAsString().Rebind(aData, aLength);
}
inline bool
TrySetToFormData(JSContext* cx, JS::Handle<JS::Value> value, bool& tryNext, bool passedToJSImpl = false)
{
tryNext = false;
{ // scope for memberSlot
NonNull<nsFormData>& memberSlot = RawSetAsFormData();
{
nsresult rv = UnwrapObject<prototypes::id::FormData, nsFormData>(&value.toObject(), memberSlot);
if (NS_FAILED(rv)) {
mUnion.DestroyFormData();
tryNext = true;
return true;
}
}
}
return true;
}
private:
inline RootedTypedArray<ArrayBufferView>&
RawSetAsArrayBufferView(JSContext* cx)
{
MOZ_ASSERT(mUnion.mType == mUnion.eUninitialized);
mUnion.mType = mUnion.eArrayBufferView;
return mUnion.mValue.mArrayBufferView.SetValue(cx);
}
inline NonNull<mozilla::dom::Blob>&
RawSetAsBlob()
{
MOZ_ASSERT(mUnion.mType == mUnion.eUninitialized);
mUnion.mType = mUnion.eBlob;
return mUnion.mValue.mBlob.SetValue();
}
inline binding_detail::FakeString&
RawSetAsString()
{
MOZ_ASSERT(mUnion.mType == mUnion.eUninitialized);
mUnion.mType = mUnion.eString;
return mUnion.mValue.mString.SetValue();
}
inline NonNull<nsFormData>&
RawSetAsFormData()
{
MOZ_ASSERT(mUnion.mType == mUnion.eUninitialized);
mUnion.mType = mUnion.eFormData;
return mUnion.mValue.mFormData.SetValue();
}
};
class BooleanOrMediaTrackConstraintsArgument
{
BooleanOrMediaTrackConstraints& mUnion;
BooleanOrMediaTrackConstraintsArgument(const BooleanOrMediaTrackConstraintsArgument&) = delete;
void operator=(const BooleanOrMediaTrackConstraintsArgument) = delete;
public:
explicit inline BooleanOrMediaTrackConstraintsArgument(const BooleanOrMediaTrackConstraints& aUnion)
: mUnion(const_cast<BooleanOrMediaTrackConstraints&>(aUnion))
{
}
inline bool
TrySetToBoolean(JSContext* cx, JS::Handle<JS::Value> value, bool& tryNext, bool passedToJSImpl = false)
{
tryNext = false;
{ // scope for memberSlot
bool& memberSlot = RawSetAsBoolean();
if (!ValueToPrimitive<bool, eDefault>(cx, value, &memberSlot)) {
return false;
}
}
return true;
}
inline bool
TrySetToMediaTrackConstraints(JSContext* cx, JS::Handle<JS::Value> value, bool& tryNext, bool passedToJSImpl = false)
{
tryNext = false;
{ // scope for memberSlot
binding_detail::FastMediaTrackConstraints& memberSlot = RawSetAsMediaTrackConstraints();
if (!IsConvertibleToDictionary(cx, value)) {
mUnion.DestroyMediaTrackConstraints();
tryNext = true;
return true;
}
if (!memberSlot.Init(cx, value, "Member of BooleanOrMediaTrackConstraints", passedToJSImpl)) {
return false;
}
}
return true;
}
private:
inline bool&
RawSetAsBoolean()
{
MOZ_ASSERT(mUnion.mType == mUnion.eUninitialized);
mUnion.mType = mUnion.eBoolean;
return mUnion.mValue.mBoolean.SetValue();
}
inline binding_detail::FastMediaTrackConstraints&
RawSetAsMediaTrackConstraints()
{
MOZ_ASSERT(mUnion.mType == mUnion.eUninitialized);
mUnion.mType = mUnion.eMediaTrackConstraints;
return mUnion.mValue.mMediaTrackConstraints.SetValue();
}
};
class DoubleOrConstrainDoubleRangeArgument
{
DoubleOrConstrainDoubleRange& mUnion;
DoubleOrConstrainDoubleRangeArgument(const DoubleOrConstrainDoubleRangeArgument&) = delete;
void operator=(const DoubleOrConstrainDoubleRangeArgument) = delete;
public:
explicit inline DoubleOrConstrainDoubleRangeArgument(const DoubleOrConstrainDoubleRange& aUnion)
: mUnion(const_cast<DoubleOrConstrainDoubleRange&>(aUnion))
{
}
inline bool
TrySetToDouble(JSContext* cx, JS::Handle<JS::Value> value, bool& tryNext, bool passedToJSImpl = false)
{
tryNext = false;
{ // scope for memberSlot
double& memberSlot = RawSetAsDouble();
if (!ValueToPrimitive<double, eDefault>(cx, value, &memberSlot)) {
return false;
} else if (!mozilla::IsFinite(memberSlot)) {
// Note: mozilla::IsFinite will do the right thing
// when passed a non-finite float too.
ThrowErrorMessage(cx, MSG_NOT_FINITE, "Member of DoubleOrConstrainDoubleRange");
return false;
}
}
return true;
}
inline bool
TrySetToConstrainDoubleRange(JSContext* cx, JS::Handle<JS::Value> value, bool& tryNext, bool passedToJSImpl = false)
{
tryNext = false;
{ // scope for memberSlot
binding_detail::FastConstrainDoubleRange& memberSlot = RawSetAsConstrainDoubleRange();
if (!IsConvertibleToDictionary(cx, value)) {
mUnion.DestroyConstrainDoubleRange();
tryNext = true;
return true;
}
if (!memberSlot.Init(cx, value, "Member of DoubleOrConstrainDoubleRange", passedToJSImpl)) {
return false;
}
}
return true;
}
private:
inline double&
RawSetAsDouble()
{
MOZ_ASSERT(mUnion.mType == mUnion.eUninitialized);
mUnion.mType = mUnion.eDouble;
return mUnion.mValue.mDouble.SetValue();
}
inline binding_detail::FastConstrainDoubleRange&
RawSetAsConstrainDoubleRange()
{
MOZ_ASSERT(mUnion.mType == mUnion.eUninitialized);
mUnion.mType = mUnion.eConstrainDoubleRange;
return mUnion.mValue.mConstrainDoubleRange.SetValue();
}
};
class EventOrStringArgument
{
EventOrString& mUnion;
EventOrStringArgument(const EventOrStringArgument&) = delete;
void operator=(const EventOrStringArgument) = delete;
public:
explicit inline EventOrStringArgument(const EventOrString& aUnion)
: mUnion(const_cast<EventOrString&>(aUnion))
{
}
inline bool
TrySetToEvent(JSContext* cx, JS::Handle<JS::Value> value, bool& tryNext, bool passedToJSImpl = false)
{
tryNext = false;
{ // scope for memberSlot
NonNull<mozilla::dom::Event>& memberSlot = RawSetAsEvent();
{
nsresult rv = UnwrapObject<prototypes::id::Event, mozilla::dom::Event>(&value.toObject(), memberSlot);
if (NS_FAILED(rv)) {
mUnion.DestroyEvent();
tryNext = true;
return true;
}
}
}
return true;
}
inline bool
TrySetToString(JSContext* cx, JS::Handle<JS::Value> value, bool& tryNext, bool passedToJSImpl = false)
{
tryNext = false;
{ // scope for memberSlot
binding_detail::FakeString& memberSlot = RawSetAsString();
if (!ConvertJSValueToString(cx, value, eStringify, eStringify, memberSlot)) {
return false;
}
}
return true;
}
inline void
SetStringData(const nsDependentString::char_type* aData, nsDependentString::size_type aLength)
{
RawSetAsString().Rebind(aData, aLength);
}
private:
inline NonNull<mozilla::dom::Event>&
RawSetAsEvent()
{
MOZ_ASSERT(mUnion.mType == mUnion.eUninitialized);
mUnion.mType = mUnion.eEvent;
return mUnion.mValue.mEvent.SetValue();
}
inline binding_detail::FakeString&
RawSetAsString()
{
MOZ_ASSERT(mUnion.mType == mUnion.eUninitialized);
mUnion.mType = mUnion.eString;
return mUnion.mValue.mString.SetValue();
}
};
class ExternalOrWindowProxyArgument
{
ExternalOrWindowProxy& mUnion;
Maybe<nsRefPtr<nsIDOMWindow>> mWindowProxyHolder;
ExternalOrWindowProxyArgument(const ExternalOrWindowProxyArgument&) = delete;
void operator=(const ExternalOrWindowProxyArgument) = delete;
public:
explicit inline ExternalOrWindowProxyArgument(const ExternalOrWindowProxy& aUnion)
: mUnion(const_cast<ExternalOrWindowProxy&>(aUnion))
{
}
inline bool
TrySetToExternal(JSContext* cx, JS::Handle<JS::Value> value, bool& tryNext, bool passedToJSImpl = false)
{
tryNext = false;
{ // scope for memberSlot
NonNull<mozilla::dom::External>& memberSlot = RawSetAsExternal();
{
nsresult rv = UnwrapObject<prototypes::id::External, mozilla::dom::External>(&value.toObject(), memberSlot);
if (NS_FAILED(rv)) {
mUnion.DestroyExternal();
tryNext = true;
return true;
}
}
}
return true;
}
inline bool
TrySetToWindowProxy(JSContext* cx, JS::Handle<JS::Value> value, bool& tryNext, bool passedToJSImpl = false)
{
tryNext = false;
{ // scope for memberSlot
nsIDOMWindow*& memberSlot = RawSetAsWindowProxy();
mWindowProxyHolder.emplace();
JS::Rooted<JSObject*> source(cx, &value.toObject());
if (NS_FAILED(UnwrapArg<nsIDOMWindow>(source, getter_AddRefs(mWindowProxyHolder.ref())))) {
mWindowProxyHolder.reset();
mUnion.DestroyWindowProxy();
tryNext = true;
return true;
}
MOZ_ASSERT(mWindowProxyHolder.ref());
memberSlot = mWindowProxyHolder.ref();
}
return true;
}
private:
inline NonNull<mozilla::dom::External>&
RawSetAsExternal()
{
MOZ_ASSERT(mUnion.mType == mUnion.eUninitialized);
mUnion.mType = mUnion.eExternal;
return mUnion.mValue.mExternal.SetValue();
}
inline nsIDOMWindow*&
RawSetAsWindowProxy()
{
MOZ_ASSERT(mUnion.mType == mUnion.eUninitialized);
mUnion.mType = mUnion.eWindowProxy;
return mUnion.mValue.mWindowProxy.SetValue();
}
};
class FileOrUSVStringArgument
{
FileOrUSVString& mUnion;
FileOrUSVStringArgument(const FileOrUSVStringArgument&) = delete;
void operator=(const FileOrUSVStringArgument) = delete;
public:
explicit inline FileOrUSVStringArgument(const FileOrUSVString& aUnion)
: mUnion(const_cast<FileOrUSVString&>(aUnion))
{
}
inline bool
TrySetToFile(JSContext* cx, JS::Handle<JS::Value> value, bool& tryNext, bool passedToJSImpl = false)
{
tryNext = false;
{ // scope for memberSlot
NonNull<mozilla::dom::File>& memberSlot = RawSetAsFile();
{
nsresult rv = UnwrapObject<prototypes::id::File, mozilla::dom::File>(&value.toObject(), memberSlot);
if (NS_FAILED(rv)) {
mUnion.DestroyFile();
tryNext = true;
return true;
}
}
}
return true;
}
inline bool
TrySetToUSVString(JSContext* cx, JS::Handle<JS::Value> value, bool& tryNext, bool passedToJSImpl = false)
{
tryNext = false;
{ // scope for memberSlot
binding_detail::FakeString& memberSlot = RawSetAsUSVString();
if (!ConvertJSValueToString(cx, value, eStringify, eStringify, memberSlot)) {
return false;
}
NormalizeUSVString(cx, memberSlot);
}
return true;
}
inline void
SetStringData(const nsDependentString::char_type* aData, nsDependentString::size_type aLength)
{
RawSetAsUSVString().Rebind(aData, aLength);
}
private:
inline NonNull<mozilla::dom::File>&
RawSetAsFile()
{
MOZ_ASSERT(mUnion.mType == mUnion.eUninitialized);
mUnion.mType = mUnion.eFile;
return mUnion.mValue.mFile.SetValue();
}
inline binding_detail::FakeString&
RawSetAsUSVString()
{
MOZ_ASSERT(mUnion.mType == mUnion.eUninitialized);
mUnion.mType = mUnion.eUSVString;
return mUnion.mValue.mUSVString.SetValue();
}
};
class HTMLElementOrLongArgument
{
HTMLElementOrLong& mUnion;
HTMLElementOrLongArgument(const HTMLElementOrLongArgument&) = delete;
void operator=(const HTMLElementOrLongArgument) = delete;
public:
explicit inline HTMLElementOrLongArgument(const HTMLElementOrLong& aUnion)
: mUnion(const_cast<HTMLElementOrLong&>(aUnion))
{
}
inline bool
TrySetToHTMLElement(JSContext* cx, JS::Handle<JS::Value> value, bool& tryNext, bool passedToJSImpl = false)
{
tryNext = false;
{ // scope for memberSlot
NonNull<nsGenericHTMLElement>& memberSlot = RawSetAsHTMLElement();
{
nsresult rv = UnwrapObject<prototypes::id::HTMLElement, nsGenericHTMLElement>(&value.toObject(), memberSlot);
if (NS_FAILED(rv)) {
mUnion.DestroyHTMLElement();
tryNext = true;
return true;
}
}
}
return true;
}
inline bool
TrySetToLong(JSContext* cx, JS::Handle<JS::Value> value, bool& tryNext, bool passedToJSImpl = false)
{
tryNext = false;
{ // scope for memberSlot
int32_t& memberSlot = RawSetAsLong();
if (!ValueToPrimitive<int32_t, eDefault>(cx, value, &memberSlot)) {
return false;
}
}
return true;
}
private:
inline NonNull<nsGenericHTMLElement>&
RawSetAsHTMLElement()
{
MOZ_ASSERT(mUnion.mType == mUnion.eUninitialized);
mUnion.mType = mUnion.eHTMLElement;
return mUnion.mValue.mHTMLElement.SetValue();
}
inline int32_t&
RawSetAsLong()
{
MOZ_ASSERT(mUnion.mType == mUnion.eUninitialized);
mUnion.mType = mUnion.eLong;
return mUnion.mValue.mLong.SetValue();
}
};
class HTMLImageElementOrHTMLCanvasElementOrHTMLVideoElementArgument
{
HTMLImageElementOrHTMLCanvasElementOrHTMLVideoElement& mUnion;
HTMLImageElementOrHTMLCanvasElementOrHTMLVideoElementArgument(const HTMLImageElementOrHTMLCanvasElementOrHTMLVideoElementArgument&) = delete;
void operator=(const HTMLImageElementOrHTMLCanvasElementOrHTMLVideoElementArgument) = delete;
public:
explicit inline HTMLImageElementOrHTMLCanvasElementOrHTMLVideoElementArgument(const HTMLImageElementOrHTMLCanvasElementOrHTMLVideoElement& aUnion)
: mUnion(const_cast<HTMLImageElementOrHTMLCanvasElementOrHTMLVideoElement&>(aUnion))
{
}
inline bool
TrySetToHTMLImageElement(JSContext* cx, JS::Handle<JS::Value> value, bool& tryNext, bool passedToJSImpl = false)
{
tryNext = false;
{ // scope for memberSlot
NonNull<mozilla::dom::HTMLImageElement>& memberSlot = RawSetAsHTMLImageElement();
{
nsresult rv = UnwrapObject<prototypes::id::HTMLImageElement, mozilla::dom::HTMLImageElement>(&value.toObject(), memberSlot);
if (NS_FAILED(rv)) {
mUnion.DestroyHTMLImageElement();
tryNext = true;
return true;
}
}
}
return true;
}
inline bool
TrySetToHTMLCanvasElement(JSContext* cx, JS::Handle<JS::Value> value, bool& tryNext, bool passedToJSImpl = false)
{
tryNext = false;
{ // scope for memberSlot
NonNull<mozilla::dom::HTMLCanvasElement>& memberSlot = RawSetAsHTMLCanvasElement();
{
nsresult rv = UnwrapObject<prototypes::id::HTMLCanvasElement, mozilla::dom::HTMLCanvasElement>(&value.toObject(), memberSlot);
if (NS_FAILED(rv)) {
mUnion.DestroyHTMLCanvasElement();
tryNext = true;
return true;
}
}
}
return true;
}
inline bool
TrySetToHTMLVideoElement(JSContext* cx, JS::Handle<JS::Value> value, bool& tryNext, bool passedToJSImpl = false)
{
tryNext = false;
{ // scope for memberSlot
NonNull<mozilla::dom::HTMLVideoElement>& memberSlot = RawSetAsHTMLVideoElement();
{
nsresult rv = UnwrapObject<prototypes::id::HTMLVideoElement, mozilla::dom::HTMLVideoElement>(&value.toObject(), memberSlot);
if (NS_FAILED(rv)) {
mUnion.DestroyHTMLVideoElement();
tryNext = true;
return true;
}
}
}
return true;
}
private:
inline NonNull<mozilla::dom::HTMLImageElement>&
RawSetAsHTMLImageElement()
{
MOZ_ASSERT(mUnion.mType == mUnion.eUninitialized);
mUnion.mType = mUnion.eHTMLImageElement;
return mUnion.mValue.mHTMLImageElement.SetValue();
}
inline NonNull<mozilla::dom::HTMLCanvasElement>&
RawSetAsHTMLCanvasElement()
{
MOZ_ASSERT(mUnion.mType == mUnion.eUninitialized);
mUnion.mType = mUnion.eHTMLCanvasElement;
return mUnion.mValue.mHTMLCanvasElement.SetValue();
}
inline NonNull<mozilla::dom::HTMLVideoElement>&
RawSetAsHTMLVideoElement()
{
MOZ_ASSERT(mUnion.mType == mUnion.eUninitialized);
mUnion.mType = mUnion.eHTMLVideoElement;
return mUnion.mValue.mHTMLVideoElement.SetValue();
}
};
class HTMLOptionElementOrHTMLOptGroupElementArgument
{
HTMLOptionElementOrHTMLOptGroupElement& mUnion;
HTMLOptionElementOrHTMLOptGroupElementArgument(const HTMLOptionElementOrHTMLOptGroupElementArgument&) = delete;
void operator=(const HTMLOptionElementOrHTMLOptGroupElementArgument) = delete;
public:
explicit inline HTMLOptionElementOrHTMLOptGroupElementArgument(const HTMLOptionElementOrHTMLOptGroupElement& aUnion)
: mUnion(const_cast<HTMLOptionElementOrHTMLOptGroupElement&>(aUnion))
{
}
inline bool
TrySetToHTMLOptionElement(JSContext* cx, JS::Handle<JS::Value> value, bool& tryNext, bool passedToJSImpl = false)
{
tryNext = false;
{ // scope for memberSlot
NonNull<mozilla::dom::HTMLOptionElement>& memberSlot = RawSetAsHTMLOptionElement();
{
nsresult rv = UnwrapObject<prototypes::id::HTMLOptionElement, mozilla::dom::HTMLOptionElement>(&value.toObject(), memberSlot);
if (NS_FAILED(rv)) {
mUnion.DestroyHTMLOptionElement();
tryNext = true;
return true;
}
}
}
return true;
}
inline bool
TrySetToHTMLOptGroupElement(JSContext* cx, JS::Handle<JS::Value> value, bool& tryNext, bool passedToJSImpl = false)
{
tryNext = false;
{ // scope for memberSlot
NonNull<mozilla::dom::HTMLOptGroupElement>& memberSlot = RawSetAsHTMLOptGroupElement();
{
nsresult rv = UnwrapObject<prototypes::id::HTMLOptGroupElement, mozilla::dom::HTMLOptGroupElement>(&value.toObject(), memberSlot);
if (NS_FAILED(rv)) {
mUnion.DestroyHTMLOptGroupElement();
tryNext = true;
return true;
}
}
}
return true;
}
private:
inline NonNull<mozilla::dom::HTMLOptionElement>&
RawSetAsHTMLOptionElement()
{
MOZ_ASSERT(mUnion.mType == mUnion.eUninitialized);
mUnion.mType = mUnion.eHTMLOptionElement;
return mUnion.mValue.mHTMLOptionElement.SetValue();
}
inline NonNull<mozilla::dom::HTMLOptGroupElement>&
RawSetAsHTMLOptGroupElement()
{
MOZ_ASSERT(mUnion.mType == mUnion.eUninitialized);
mUnion.mType = mUnion.eHTMLOptGroupElement;
return mUnion.mValue.mHTMLOptGroupElement.SetValue();
}
};
class HeadersOrByteStringSequenceSequenceOrByteStringMozMapArgument
{
HeadersOrByteStringSequenceSequenceOrByteStringMozMap& mUnion;
HeadersOrByteStringSequenceSequenceOrByteStringMozMapArgument(const HeadersOrByteStringSequenceSequenceOrByteStringMozMapArgument&) = delete;
void operator=(const HeadersOrByteStringSequenceSequenceOrByteStringMozMapArgument) = delete;
public:
explicit inline HeadersOrByteStringSequenceSequenceOrByteStringMozMapArgument(const HeadersOrByteStringSequenceSequenceOrByteStringMozMap& aUnion)
: mUnion(const_cast<HeadersOrByteStringSequenceSequenceOrByteStringMozMap&>(aUnion))
{
}
inline bool
TrySetToHeaders(JSContext* cx, JS::Handle<JS::Value> value, bool& tryNext, bool passedToJSImpl = false)
{
tryNext = false;
{ // scope for memberSlot
NonNull<mozilla::dom::Headers>& memberSlot = RawSetAsHeaders();
{
nsresult rv = UnwrapObject<prototypes::id::Headers, mozilla::dom::Headers>(&value.toObject(), memberSlot);
if (NS_FAILED(rv)) {
mUnion.DestroyHeaders();
tryNext = true;
return true;
}
}
}
return true;
}
inline bool
TrySetToByteStringSequenceSequence(JSContext* cx, JS::Handle<JS::Value> value, bool& tryNext, bool passedToJSImpl = false)
{
tryNext = false;
{ // scope for memberSlot
binding_detail::AutoSequence<Sequence<nsCString>>& memberSlot = RawSetAsByteStringSequenceSequence();
JS::ForOfIterator iter(cx);
if (!iter.init(value, JS::ForOfIterator::AllowNonIterable)) {
return false;
}
if (!iter.valueIsIterable()) {
mUnion.DestroyByteStringSequenceSequence();
tryNext = true;
return true;
}
binding_detail::AutoSequence<Sequence<nsCString>> &arr = memberSlot;
JS::Rooted<JS::Value> temp(cx);
while (true) {
bool done;
if (!iter.next(&temp, &done)) {
return false;
}
if (done) {
break;
}
Sequence<nsCString>* slotPtr = arr.AppendElement(mozilla::fallible);
if (!slotPtr) {
JS_ReportOutOfMemory(cx);
return false;
}
Sequence<nsCString>& slot = *slotPtr;
if (temp.isObject()) {
JS::ForOfIterator iter1(cx);
if (!iter1.init(temp, JS::ForOfIterator::AllowNonIterable)) {
return false;
}
if (!iter1.valueIsIterable()) {
ThrowErrorMessage(cx, MSG_NOT_SEQUENCE, "Element of member of HeadersOrByteStringSequenceSequenceOrByteStringMozMap");
return false;
}
Sequence<nsCString> &arr1 = slot;
JS::Rooted<JS::Value> temp1(cx);
while (true) {
bool done1;
if (!iter1.next(&temp1, &done1)) {
return false;
}
if (done1) {
break;
}
nsCString* slotPtr1 = arr1.AppendElement(mozilla::fallible);
if (!slotPtr1) {
JS_ReportOutOfMemory(cx);
return false;
}
nsCString& slot1 = *slotPtr1;
if (!ConvertJSValueToByteString(cx, temp1, false, slot1)) {
return false;
}
}
} else {
ThrowErrorMessage(cx, MSG_NOT_SEQUENCE, "Element of member of HeadersOrByteStringSequenceSequenceOrByteStringMozMap");
return false;
}
}
}
return true;
}
inline bool
TrySetToByteStringMozMap(JSContext* cx, JS::Handle<JS::Value> value, bool& tryNext, bool passedToJSImpl = false)
{
tryNext = false;
{ // scope for memberSlot
MozMap<nsCString>& memberSlot = RawSetAsByteStringMozMap();
MozMap<nsCString> &mozMap = memberSlot;
JS::Rooted<JSObject*> mozMapObj(cx, &value.toObject());
JS::AutoIdArray ids(cx, JS_Enumerate(cx, mozMapObj));
if (!ids) {
return false;
}
JS::Rooted<JS::Value> propNameValue(cx);
JS::Rooted<JS::Value> temp(cx);
JS::Rooted<jsid> curId(cx);
for (size_t i = 0; i < ids.length(); ++i) {
// Make sure we get the value before converting the name, since
// getting the value can trigger GC but our name is a dependent
// string.
curId = ids[i];
binding_detail::FakeString propName;
bool isSymbol;
if (!ConvertIdToString(cx, curId, propName, isSymbol) ||
(!isSymbol && !JS_GetPropertyById(cx, mozMapObj, curId, &temp))) {
return false;
}
if (isSymbol) {
continue;
}
nsCString* slotPtr = mozMap.AddEntry(propName);
if (!slotPtr) {
JS_ReportOutOfMemory(cx);
return false;
}
nsCString& slot = *slotPtr;
if (!ConvertJSValueToByteString(cx, temp, false, slot)) {
return false;
}
}
}
return true;
}
private:
inline NonNull<mozilla::dom::Headers>&
RawSetAsHeaders()
{
MOZ_ASSERT(mUnion.mType == mUnion.eUninitialized);
mUnion.mType = mUnion.eHeaders;
return mUnion.mValue.mHeaders.SetValue();
}
inline binding_detail::AutoSequence<Sequence<nsCString>>&
RawSetAsByteStringSequenceSequence()
{
MOZ_ASSERT(mUnion.mType == mUnion.eUninitialized);
mUnion.mType = mUnion.eByteStringSequenceSequence;
return mUnion.mValue.mByteStringSequenceSequence.SetValue();
}
inline MozMap<nsCString>&
RawSetAsByteStringMozMap()
{
MOZ_ASSERT(mUnion.mType == mUnion.eUninitialized);
mUnion.mType = mUnion.eByteStringMozMap;
return mUnion.mValue.mByteStringMozMap.SetValue();
}
};
class IDBObjectStoreOrIDBIndexArgument
{
IDBObjectStoreOrIDBIndex& mUnion;
IDBObjectStoreOrIDBIndexArgument(const IDBObjectStoreOrIDBIndexArgument&) = delete;
void operator=(const IDBObjectStoreOrIDBIndexArgument) = delete;
public:
explicit inline IDBObjectStoreOrIDBIndexArgument(const IDBObjectStoreOrIDBIndex& aUnion)
: mUnion(const_cast<IDBObjectStoreOrIDBIndex&>(aUnion))
{
}
inline bool
TrySetToIDBObjectStore(JSContext* cx, JS::Handle<JS::Value> value, bool& tryNext, bool passedToJSImpl = false)
{
tryNext = false;
{ // scope for memberSlot
NonNull<mozilla::dom::indexedDB::IDBObjectStore>& memberSlot = RawSetAsIDBObjectStore();
{
nsresult rv = UnwrapObject<prototypes::id::IDBObjectStore, mozilla::dom::indexedDB::IDBObjectStore>(&value.toObject(), memberSlot);
if (NS_FAILED(rv)) {
mUnion.DestroyIDBObjectStore();
tryNext = true;
return true;
}
}
}
return true;
}
inline bool
TrySetToIDBIndex(JSContext* cx, JS::Handle<JS::Value> value, bool& tryNext, bool passedToJSImpl = false)
{
tryNext = false;
{ // scope for memberSlot
NonNull<mozilla::dom::indexedDB::IDBIndex>& memberSlot = RawSetAsIDBIndex();
{
nsresult rv = UnwrapObject<prototypes::id::IDBIndex, mozilla::dom::indexedDB::IDBIndex>(&value.toObject(), memberSlot);
if (NS_FAILED(rv)) {
mUnion.DestroyIDBIndex();
tryNext = true;
return true;
}
}
}
return true;
}
private:
inline NonNull<mozilla::dom::indexedDB::IDBObjectStore>&
RawSetAsIDBObjectStore()
{
MOZ_ASSERT(mUnion.mType == mUnion.eUninitialized);
mUnion.mType = mUnion.eIDBObjectStore;
return mUnion.mValue.mIDBObjectStore.SetValue();
}
inline NonNull<mozilla::dom::indexedDB::IDBIndex>&
RawSetAsIDBIndex()
{
MOZ_ASSERT(mUnion.mType == mUnion.eUninitialized);
mUnion.mType = mUnion.eIDBIndex;
return mUnion.mValue.mIDBIndex.SetValue();
}
};
class IDBObjectStoreOrIDBIndexOrIDBCursorArgument
{
IDBObjectStoreOrIDBIndexOrIDBCursor& mUnion;
IDBObjectStoreOrIDBIndexOrIDBCursorArgument(const IDBObjectStoreOrIDBIndexOrIDBCursorArgument&) = delete;
void operator=(const IDBObjectStoreOrIDBIndexOrIDBCursorArgument) = delete;
public:
explicit inline IDBObjectStoreOrIDBIndexOrIDBCursorArgument(const IDBObjectStoreOrIDBIndexOrIDBCursor& aUnion)
: mUnion(const_cast<IDBObjectStoreOrIDBIndexOrIDBCursor&>(aUnion))
{
}
inline bool
TrySetToIDBObjectStore(JSContext* cx, JS::Handle<JS::Value> value, bool& tryNext, bool passedToJSImpl = false)
{
tryNext = false;
{ // scope for memberSlot
NonNull<mozilla::dom::indexedDB::IDBObjectStore>& memberSlot = RawSetAsIDBObjectStore();
{
nsresult rv = UnwrapObject<prototypes::id::IDBObjectStore, mozilla::dom::indexedDB::IDBObjectStore>(&value.toObject(), memberSlot);
if (NS_FAILED(rv)) {
mUnion.DestroyIDBObjectStore();
tryNext = true;
return true;
}
}
}
return true;
}
inline bool
TrySetToIDBIndex(JSContext* cx, JS::Handle<JS::Value> value, bool& tryNext, bool passedToJSImpl = false)
{
tryNext = false;
{ // scope for memberSlot
NonNull<mozilla::dom::indexedDB::IDBIndex>& memberSlot = RawSetAsIDBIndex();
{
nsresult rv = UnwrapObject<prototypes::id::IDBIndex, mozilla::dom::indexedDB::IDBIndex>(&value.toObject(), memberSlot);
if (NS_FAILED(rv)) {
mUnion.DestroyIDBIndex();
tryNext = true;
return true;
}
}
}
return true;
}
inline bool
TrySetToIDBCursor(JSContext* cx, JS::Handle<JS::Value> value, bool& tryNext, bool passedToJSImpl = false)
{
tryNext = false;
{ // scope for memberSlot
NonNull<mozilla::dom::indexedDB::IDBCursor>& memberSlot = RawSetAsIDBCursor();
{
nsresult rv = UnwrapObject<prototypes::id::IDBCursor, mozilla::dom::indexedDB::IDBCursor>(&value.toObject(), memberSlot);
if (NS_FAILED(rv)) {
mUnion.DestroyIDBCursor();
tryNext = true;
return true;
}
}
}
return true;
}
private:
inline NonNull<mozilla::dom::indexedDB::IDBObjectStore>&
RawSetAsIDBObjectStore()
{
MOZ_ASSERT(mUnion.mType == mUnion.eUninitialized);
mUnion.mType = mUnion.eIDBObjectStore;
return mUnion.mValue.mIDBObjectStore.SetValue();
}
inline NonNull<mozilla::dom::indexedDB::IDBIndex>&
RawSetAsIDBIndex()
{
MOZ_ASSERT(mUnion.mType == mUnion.eUninitialized);
mUnion.mType = mUnion.eIDBIndex;
return mUnion.mValue.mIDBIndex.SetValue();
}
inline NonNull<mozilla::dom::indexedDB::IDBCursor>&
RawSetAsIDBCursor()
{
MOZ_ASSERT(mUnion.mType == mUnion.eUninitialized);
mUnion.mType = mUnion.eIDBCursor;
return mUnion.mValue.mIDBCursor.SetValue();
}
};
class LongOrAutoKeywordArgument
{
LongOrAutoKeyword& mUnion;
LongOrAutoKeywordArgument(const LongOrAutoKeywordArgument&) = delete;
void operator=(const LongOrAutoKeywordArgument) = delete;
public:
explicit inline LongOrAutoKeywordArgument(const LongOrAutoKeyword& aUnion)
: mUnion(const_cast<LongOrAutoKeyword&>(aUnion))
{
}
inline bool
TrySetToLong(JSContext* cx, JS::Handle<JS::Value> value, bool& tryNext, bool passedToJSImpl = false)
{
tryNext = false;
{ // scope for memberSlot
int32_t& memberSlot = RawSetAsLong();
if (!ValueToPrimitive<int32_t, eDefault>(cx, value, &memberSlot)) {
return false;
}
}
return true;
}
inline bool
TrySetToAutoKeyword(JSContext* cx, JS::Handle<JS::Value> value, bool& tryNext, bool passedToJSImpl = false)
{
tryNext = false;
{ // scope for memberSlot
AutoKeyword& memberSlot = RawSetAsAutoKeyword();
{
bool ok;
int index = FindEnumStringIndex<true>(cx, value, AutoKeywordValues::strings, "AutoKeyword", "Member of LongOrAutoKeyword", &ok);
if (!ok) {
return false;
}
MOZ_ASSERT(index >= 0);
memberSlot = static_cast<AutoKeyword>(index);
}
}
return true;
}
private:
inline int32_t&
RawSetAsLong()
{
MOZ_ASSERT(mUnion.mType == mUnion.eUninitialized);
mUnion.mType = mUnion.eLong;
return mUnion.mValue.mLong.SetValue();
}
inline AutoKeyword&
RawSetAsAutoKeyword()
{
MOZ_ASSERT(mUnion.mType == mUnion.eUninitialized);
mUnion.mType = mUnion.eAutoKeyword;
return mUnion.mValue.mAutoKeyword.SetValue();
}
};
class LongOrConstrainLongRangeArgument
{
LongOrConstrainLongRange& mUnion;
LongOrConstrainLongRangeArgument(const LongOrConstrainLongRangeArgument&) = delete;
void operator=(const LongOrConstrainLongRangeArgument) = delete;
public:
explicit inline LongOrConstrainLongRangeArgument(const LongOrConstrainLongRange& aUnion)
: mUnion(const_cast<LongOrConstrainLongRange&>(aUnion))
{
}
inline bool
TrySetToLong(JSContext* cx, JS::Handle<JS::Value> value, bool& tryNext, bool passedToJSImpl = false)
{
tryNext = false;
{ // scope for memberSlot
int32_t& memberSlot = RawSetAsLong();
if (!ValueToPrimitive<int32_t, eDefault>(cx, value, &memberSlot)) {
return false;
}
}
return true;
}
inline bool
TrySetToConstrainLongRange(JSContext* cx, JS::Handle<JS::Value> value, bool& tryNext, bool passedToJSImpl = false)
{
tryNext = false;
{ // scope for memberSlot
binding_detail::FastConstrainLongRange& memberSlot = RawSetAsConstrainLongRange();
if (!IsConvertibleToDictionary(cx, value)) {
mUnion.DestroyConstrainLongRange();
tryNext = true;
return true;
}
if (!memberSlot.Init(cx, value, "Member of LongOrConstrainLongRange", passedToJSImpl)) {
return false;
}
}
return true;
}
private:
inline int32_t&
RawSetAsLong()
{
MOZ_ASSERT(mUnion.mType == mUnion.eUninitialized);
mUnion.mType = mUnion.eLong;
return mUnion.mValue.mLong.SetValue();
}
inline binding_detail::FastConstrainLongRange&
RawSetAsConstrainLongRange()
{
MOZ_ASSERT(mUnion.mType == mUnion.eUninitialized);
mUnion.mType = mUnion.eConstrainLongRange;
return mUnion.mValue.mConstrainLongRange.SetValue();
}
};
class LongOrMozSmsMessageOrMozMmsMessageArgument
{
LongOrMozSmsMessageOrMozMmsMessage& mUnion;
Maybe<nsRefPtr<nsIDOMMozSmsMessage>> mMozSmsMessageHolder;
Maybe<nsRefPtr<nsIDOMMozMmsMessage>> mMozMmsMessageHolder;
LongOrMozSmsMessageOrMozMmsMessageArgument(const LongOrMozSmsMessageOrMozMmsMessageArgument&) = delete;
void operator=(const LongOrMozSmsMessageOrMozMmsMessageArgument) = delete;
public:
explicit inline LongOrMozSmsMessageOrMozMmsMessageArgument(const LongOrMozSmsMessageOrMozMmsMessage& aUnion)
: mUnion(const_cast<LongOrMozSmsMessageOrMozMmsMessage&>(aUnion))
{
}
inline bool
TrySetToLong(JSContext* cx, JS::Handle<JS::Value> value, bool& tryNext, bool passedToJSImpl = false)
{
tryNext = false;
{ // scope for memberSlot
int32_t& memberSlot = RawSetAsLong();
if (!ValueToPrimitive<int32_t, eDefault>(cx, value, &memberSlot)) {
return false;
}
}
return true;
}
inline bool
TrySetToMozSmsMessage(JSContext* cx, JS::Handle<JS::Value> value, bool& tryNext, bool passedToJSImpl = false)
{
tryNext = false;
{ // scope for memberSlot
nsIDOMMozSmsMessage*& memberSlot = RawSetAsMozSmsMessage();
mMozSmsMessageHolder.emplace();
JS::Rooted<JSObject*> source(cx, &value.toObject());
if (NS_FAILED(UnwrapArg<nsIDOMMozSmsMessage>(source, getter_AddRefs(mMozSmsMessageHolder.ref())))) {
mMozSmsMessageHolder.reset();
mUnion.DestroyMozSmsMessage();
tryNext = true;
return true;
}
MOZ_ASSERT(mMozSmsMessageHolder.ref());
memberSlot = mMozSmsMessageHolder.ref();
}
return true;
}
inline bool
TrySetToMozMmsMessage(JSContext* cx, JS::Handle<JS::Value> value, bool& tryNext, bool passedToJSImpl = false)
{
tryNext = false;
{ // scope for memberSlot
nsIDOMMozMmsMessage*& memberSlot = RawSetAsMozMmsMessage();
mMozMmsMessageHolder.emplace();
JS::Rooted<JSObject*> source(cx, &value.toObject());
if (NS_FAILED(UnwrapArg<nsIDOMMozMmsMessage>(source, getter_AddRefs(mMozMmsMessageHolder.ref())))) {
mMozMmsMessageHolder.reset();
mUnion.DestroyMozMmsMessage();
tryNext = true;
return true;
}
MOZ_ASSERT(mMozMmsMessageHolder.ref());
memberSlot = mMozMmsMessageHolder.ref();
}
return true;
}
private:
inline int32_t&
RawSetAsLong()
{
MOZ_ASSERT(mUnion.mType == mUnion.eUninitialized);
mUnion.mType = mUnion.eLong;
return mUnion.mValue.mLong.SetValue();
}
inline nsIDOMMozSmsMessage*&
RawSetAsMozSmsMessage()
{
MOZ_ASSERT(mUnion.mType == mUnion.eUninitialized);
mUnion.mType = mUnion.eMozSmsMessage;
return mUnion.mValue.mMozSmsMessage.SetValue();
}
inline nsIDOMMozMmsMessage*&
RawSetAsMozMmsMessage()
{
MOZ_ASSERT(mUnion.mType == mUnion.eUninitialized);
mUnion.mType = mUnion.eMozMmsMessage;
return mUnion.mValue.mMozMmsMessage.SetValue();
}
};
class MozIccInfoOrMozGsmIccInfoOrMozCdmaIccInfoArgument
{
MozIccInfoOrMozGsmIccInfoOrMozCdmaIccInfo& mUnion;
MozIccInfoOrMozGsmIccInfoOrMozCdmaIccInfoArgument(const MozIccInfoOrMozGsmIccInfoOrMozCdmaIccInfoArgument&) = delete;
void operator=(const MozIccInfoOrMozGsmIccInfoOrMozCdmaIccInfoArgument) = delete;
public:
explicit inline MozIccInfoOrMozGsmIccInfoOrMozCdmaIccInfoArgument(const MozIccInfoOrMozGsmIccInfoOrMozCdmaIccInfo& aUnion)
: mUnion(const_cast<MozIccInfoOrMozGsmIccInfoOrMozCdmaIccInfo&>(aUnion))
{
}
inline bool
TrySetToMozIccInfo(JSContext* cx, JS::Handle<JS::Value> value, bool& tryNext, bool passedToJSImpl = false)
{
tryNext = false;
{ // scope for memberSlot
NonNull<mozilla::dom::IccInfo>& memberSlot = RawSetAsMozIccInfo();
{
nsresult rv = UnwrapObject<prototypes::id::MozIccInfo, mozilla::dom::IccInfo>(&value.toObject(), memberSlot);
if (NS_FAILED(rv)) {
mUnion.DestroyMozIccInfo();
tryNext = true;
return true;
}
}
}
return true;
}
inline bool
TrySetToMozGsmIccInfo(JSContext* cx, JS::Handle<JS::Value> value, bool& tryNext, bool passedToJSImpl = false)
{
tryNext = false;
{ // scope for memberSlot
NonNull<mozilla::dom::GsmIccInfo>& memberSlot = RawSetAsMozGsmIccInfo();
{
nsresult rv = UnwrapObject<prototypes::id::MozGsmIccInfo, mozilla::dom::GsmIccInfo>(&value.toObject(), memberSlot);
if (NS_FAILED(rv)) {
mUnion.DestroyMozGsmIccInfo();
tryNext = true;
return true;
}
}
}
return true;
}
inline bool
TrySetToMozCdmaIccInfo(JSContext* cx, JS::Handle<JS::Value> value, bool& tryNext, bool passedToJSImpl = false)
{
tryNext = false;
{ // scope for memberSlot
NonNull<mozilla::dom::CdmaIccInfo>& memberSlot = RawSetAsMozCdmaIccInfo();
{
nsresult rv = UnwrapObject<prototypes::id::MozCdmaIccInfo, mozilla::dom::CdmaIccInfo>(&value.toObject(), memberSlot);
if (NS_FAILED(rv)) {
mUnion.DestroyMozCdmaIccInfo();
tryNext = true;
return true;
}
}
}
return true;
}
private:
inline NonNull<mozilla::dom::IccInfo>&
RawSetAsMozIccInfo()
{
MOZ_ASSERT(mUnion.mType == mUnion.eUninitialized);
mUnion.mType = mUnion.eMozIccInfo;
return mUnion.mValue.mMozIccInfo.SetValue();
}
inline NonNull<mozilla::dom::GsmIccInfo>&
RawSetAsMozGsmIccInfo()
{
MOZ_ASSERT(mUnion.mType == mUnion.eUninitialized);
mUnion.mType = mUnion.eMozGsmIccInfo;
return mUnion.mValue.mMozGsmIccInfo.SetValue();
}
inline NonNull<mozilla::dom::CdmaIccInfo>&
RawSetAsMozCdmaIccInfo()
{
MOZ_ASSERT(mUnion.mType == mUnion.eUninitialized);
mUnion.mType = mUnion.eMozCdmaIccInfo;
return mUnion.mValue.mMozCdmaIccInfo.SetValue();
}
};
class MozSmsMessageOrMozMmsMessageArgument
{
MozSmsMessageOrMozMmsMessage& mUnion;
Maybe<nsRefPtr<nsIDOMMozSmsMessage>> mMozSmsMessageHolder;
Maybe<nsRefPtr<nsIDOMMozMmsMessage>> mMozMmsMessageHolder;
MozSmsMessageOrMozMmsMessageArgument(const MozSmsMessageOrMozMmsMessageArgument&) = delete;
void operator=(const MozSmsMessageOrMozMmsMessageArgument) = delete;
public:
explicit inline MozSmsMessageOrMozMmsMessageArgument(const MozSmsMessageOrMozMmsMessage& aUnion)
: mUnion(const_cast<MozSmsMessageOrMozMmsMessage&>(aUnion))
{
}
inline bool
TrySetToMozSmsMessage(JSContext* cx, JS::Handle<JS::Value> value, bool& tryNext, bool passedToJSImpl = false)
{
tryNext = false;
{ // scope for memberSlot
nsIDOMMozSmsMessage*& memberSlot = RawSetAsMozSmsMessage();
mMozSmsMessageHolder.emplace();
JS::Rooted<JSObject*> source(cx, &value.toObject());
if (NS_FAILED(UnwrapArg<nsIDOMMozSmsMessage>(source, getter_AddRefs(mMozSmsMessageHolder.ref())))) {
mMozSmsMessageHolder.reset();
mUnion.DestroyMozSmsMessage();
tryNext = true;
return true;
}
MOZ_ASSERT(mMozSmsMessageHolder.ref());
memberSlot = mMozSmsMessageHolder.ref();
}
return true;
}
inline bool
TrySetToMozMmsMessage(JSContext* cx, JS::Handle<JS::Value> value, bool& tryNext, bool passedToJSImpl = false)
{
tryNext = false;
{ // scope for memberSlot
nsIDOMMozMmsMessage*& memberSlot = RawSetAsMozMmsMessage();
mMozMmsMessageHolder.emplace();
JS::Rooted<JSObject*> source(cx, &value.toObject());
if (NS_FAILED(UnwrapArg<nsIDOMMozMmsMessage>(source, getter_AddRefs(mMozMmsMessageHolder.ref())))) {
mMozMmsMessageHolder.reset();
mUnion.DestroyMozMmsMessage();
tryNext = true;
return true;
}
MOZ_ASSERT(mMozMmsMessageHolder.ref());
memberSlot = mMozMmsMessageHolder.ref();
}
return true;
}
private:
inline nsIDOMMozSmsMessage*&
RawSetAsMozSmsMessage()
{
MOZ_ASSERT(mUnion.mType == mUnion.eUninitialized);
mUnion.mType = mUnion.eMozSmsMessage;
return mUnion.mValue.mMozSmsMessage.SetValue();
}
inline nsIDOMMozMmsMessage*&
RawSetAsMozMmsMessage()
{
MOZ_ASSERT(mUnion.mType == mUnion.eUninitialized);
mUnion.mType = mUnion.eMozMmsMessage;
return mUnion.mValue.mMozMmsMessage.SetValue();
}
};
class NetworkStatsDataOrPowerStatsDataArgument
{
NetworkStatsDataOrPowerStatsData& mUnion;
NetworkStatsDataOrPowerStatsDataArgument(const NetworkStatsDataOrPowerStatsDataArgument&) = delete;
void operator=(const NetworkStatsDataOrPowerStatsDataArgument) = delete;
public:
explicit inline NetworkStatsDataOrPowerStatsDataArgument(const NetworkStatsDataOrPowerStatsData& aUnion)
: mUnion(const_cast<NetworkStatsDataOrPowerStatsData&>(aUnion))
{
}
inline bool
TrySetToNetworkStatsData(JSContext* cx, JS::Handle<JS::Value> value, bool& tryNext, bool passedToJSImpl = false)
{
tryNext = false;
{ // scope for memberSlot
NonNull<mozilla::dom::NetworkStatsData>& memberSlot = RawSetAsNetworkStatsData();
{
nsresult rv = UnwrapObject<prototypes::id::NetworkStatsData, mozilla::dom::NetworkStatsData>(&value.toObject(), memberSlot);
if (NS_FAILED(rv)) {
mUnion.DestroyNetworkStatsData();
tryNext = true;
return true;
}
}
}
return true;
}
inline bool
TrySetToPowerStatsData(JSContext* cx, JS::Handle<JS::Value> value, bool& tryNext, bool passedToJSImpl = false)
{
tryNext = false;
{ // scope for memberSlot
NonNull<mozilla::dom::PowerStatsData>& memberSlot = RawSetAsPowerStatsData();
{
nsresult rv = UnwrapObject<prototypes::id::PowerStatsData, mozilla::dom::PowerStatsData>(&value.toObject(), memberSlot);
if (NS_FAILED(rv)) {
mUnion.DestroyPowerStatsData();
tryNext = true;
return true;
}
}
}
return true;
}
private:
inline NonNull<mozilla::dom::NetworkStatsData>&
RawSetAsNetworkStatsData()
{
MOZ_ASSERT(mUnion.mType == mUnion.eUninitialized);
mUnion.mType = mUnion.eNetworkStatsData;
return mUnion.mValue.mNetworkStatsData.SetValue();
}
inline NonNull<mozilla::dom::PowerStatsData>&
RawSetAsPowerStatsData()
{
MOZ_ASSERT(mUnion.mType == mUnion.eUninitialized);
mUnion.mType = mUnion.ePowerStatsData;
return mUnion.mValue.mPowerStatsData.SetValue();
}
};
class NodeOrHTMLCollectionArgument
{
NodeOrHTMLCollection& mUnion;
NodeOrHTMLCollectionArgument(const NodeOrHTMLCollectionArgument&) = delete;
void operator=(const NodeOrHTMLCollectionArgument) = delete;
public:
explicit inline NodeOrHTMLCollectionArgument(const NodeOrHTMLCollection& aUnion)
: mUnion(const_cast<NodeOrHTMLCollection&>(aUnion))
{
}
inline bool
TrySetToNode(JSContext* cx, JS::Handle<JS::Value> value, bool& tryNext, bool passedToJSImpl = false)
{
tryNext = false;
{ // scope for memberSlot
NonNull<nsINode>& memberSlot = RawSetAsNode();
{
nsresult rv = UnwrapObject<prototypes::id::Node, nsINode>(&value.toObject(), memberSlot);
if (NS_FAILED(rv)) {
mUnion.DestroyNode();
tryNext = true;
return true;
}
}
}
return true;
}
inline bool
TrySetToHTMLCollection(JSContext* cx, JS::Handle<JS::Value> value, bool& tryNext, bool passedToJSImpl = false)
{
tryNext = false;
{ // scope for memberSlot
NonNull<nsIHTMLCollection>& memberSlot = RawSetAsHTMLCollection();
{
nsresult rv = UnwrapObject<prototypes::id::HTMLCollection, nsIHTMLCollection>(&value.toObject(), memberSlot);
if (NS_FAILED(rv)) {
mUnion.DestroyHTMLCollection();
tryNext = true;
return true;
}
}
}
return true;
}
private:
inline NonNull<nsINode>&
RawSetAsNode()
{
MOZ_ASSERT(mUnion.mType == mUnion.eUninitialized);
mUnion.mType = mUnion.eNode;
return mUnion.mValue.mNode.SetValue();
}
inline NonNull<nsIHTMLCollection>&
RawSetAsHTMLCollection()
{
MOZ_ASSERT(mUnion.mType == mUnion.eUninitialized);
mUnion.mType = mUnion.eHTMLCollection;
return mUnion.mValue.mHTMLCollection.SetValue();
}
};
class ObjectOrStringArgument
{
ObjectOrString& mUnion;
ObjectOrStringArgument(const ObjectOrStringArgument&) = delete;
void operator=(const ObjectOrStringArgument) = delete;
public:
explicit inline ObjectOrStringArgument(const ObjectOrString& aUnion)
: mUnion(const_cast<ObjectOrString&>(aUnion))
{
}
inline bool
SetToObject(JSContext* cx, JSObject* obj, bool passedToJSImpl = false)
{
MOZ_ASSERT(mUnion.mType == mUnion.eUninitialized);
mUnion.mValue.mObject.SetValue(cx, obj);
mUnion.mType = mUnion.eObject;
if (passedToJSImpl && !CallerSubsumes(obj)) {
ThrowErrorMessage(cx, MSG_PERMISSION_DENIED_TO_PASS_ARG, "%s");
return false;
}
return true;
}
inline bool
TrySetToString(JSContext* cx, JS::Handle<JS::Value> value, bool& tryNext, bool passedToJSImpl = false)
{
tryNext = false;
{ // scope for memberSlot
binding_detail::FakeString& memberSlot = RawSetAsString();
if (!ConvertJSValueToString(cx, value, eStringify, eStringify, memberSlot)) {
return false;
}
}
return true;
}
inline void
SetStringData(const nsDependentString::char_type* aData, nsDependentString::size_type aLength)
{
RawSetAsString().Rebind(aData, aLength);
}
private:
inline binding_detail::FakeString&
RawSetAsString()
{
MOZ_ASSERT(mUnion.mType == mUnion.eUninitialized);
mUnion.mType = mUnion.eString;
return mUnion.mValue.mString.SetValue();
}
};
class RadioNodeListOrElementArgument
{
RadioNodeListOrElement& mUnion;
RadioNodeListOrElementArgument(const RadioNodeListOrElementArgument&) = delete;
void operator=(const RadioNodeListOrElementArgument) = delete;
public:
explicit inline RadioNodeListOrElementArgument(const RadioNodeListOrElement& aUnion)
: mUnion(const_cast<RadioNodeListOrElement&>(aUnion))
{
}
inline bool
TrySetToRadioNodeList(JSContext* cx, JS::Handle<JS::Value> value, bool& tryNext, bool passedToJSImpl = false)
{
tryNext = false;
{ // scope for memberSlot
NonNull<mozilla::dom::RadioNodeList>& memberSlot = RawSetAsRadioNodeList();
{
nsresult rv = UnwrapObject<prototypes::id::RadioNodeList, mozilla::dom::RadioNodeList>(&value.toObject(), memberSlot);
if (NS_FAILED(rv)) {
mUnion.DestroyRadioNodeList();
tryNext = true;
return true;
}
}
}
return true;
}
inline bool
TrySetToElement(JSContext* cx, JS::Handle<JS::Value> value, bool& tryNext, bool passedToJSImpl = false)
{
tryNext = false;
{ // scope for memberSlot
NonNull<mozilla::dom::Element>& memberSlot = RawSetAsElement();
{
nsresult rv = UnwrapObject<prototypes::id::Element, mozilla::dom::Element>(&value.toObject(), memberSlot);
if (NS_FAILED(rv)) {
mUnion.DestroyElement();
tryNext = true;
return true;
}
}
}
return true;
}
private:
inline NonNull<mozilla::dom::RadioNodeList>&
RawSetAsRadioNodeList()
{
MOZ_ASSERT(mUnion.mType == mUnion.eUninitialized);
mUnion.mType = mUnion.eRadioNodeList;
return mUnion.mValue.mRadioNodeList.SetValue();
}
inline NonNull<mozilla::dom::Element>&
RawSetAsElement()
{
MOZ_ASSERT(mUnion.mType == mUnion.eUninitialized);
mUnion.mType = mUnion.eElement;
return mUnion.mValue.mElement.SetValue();
}
};
class RequestOrUSVStringArgument
{
RequestOrUSVString& mUnion;
RequestOrUSVStringArgument(const RequestOrUSVStringArgument&) = delete;
void operator=(const RequestOrUSVStringArgument) = delete;
public:
explicit inline RequestOrUSVStringArgument(const RequestOrUSVString& aUnion)
: mUnion(const_cast<RequestOrUSVString&>(aUnion))
{
}
inline bool
TrySetToRequest(JSContext* cx, JS::Handle<JS::Value> value, bool& tryNext, bool passedToJSImpl = false)
{
tryNext = false;
{ // scope for memberSlot
NonNull<mozilla::dom::Request>& memberSlot = RawSetAsRequest();
{
nsresult rv = UnwrapObject<prototypes::id::Request, mozilla::dom::Request>(&value.toObject(), memberSlot);
if (NS_FAILED(rv)) {
mUnion.DestroyRequest();
tryNext = true;
return true;
}
}
}
return true;
}
inline bool
TrySetToUSVString(JSContext* cx, JS::Handle<JS::Value> value, bool& tryNext, bool passedToJSImpl = false)
{
tryNext = false;
{ // scope for memberSlot
binding_detail::FakeString& memberSlot = RawSetAsUSVString();
if (!ConvertJSValueToString(cx, value, eStringify, eStringify, memberSlot)) {
return false;
}
NormalizeUSVString(cx, memberSlot);
}
return true;
}
inline void
SetStringData(const nsDependentString::char_type* aData, nsDependentString::size_type aLength)
{
RawSetAsUSVString().Rebind(aData, aLength);
}
private:
inline NonNull<mozilla::dom::Request>&
RawSetAsRequest()
{
MOZ_ASSERT(mUnion.mType == mUnion.eUninitialized);
mUnion.mType = mUnion.eRequest;
return mUnion.mValue.mRequest.SetValue();
}
inline binding_detail::FakeString&
RawSetAsUSVString()
{
MOZ_ASSERT(mUnion.mType == mUnion.eUninitialized);
mUnion.mType = mUnion.eUSVString;
return mUnion.mValue.mUSVString.SetValue();
}
};
class ResponseOrPromiseArgument
{
ResponseOrPromise& mUnion;
ResponseOrPromiseArgument(const ResponseOrPromiseArgument&) = delete;
void operator=(const ResponseOrPromiseArgument) = delete;
public:
explicit inline ResponseOrPromiseArgument(const ResponseOrPromise& aUnion)
: mUnion(const_cast<ResponseOrPromise&>(aUnion))
{
}
inline bool
TrySetToResponse(JSContext* cx, JS::Handle<JS::Value> value, bool& tryNext, bool passedToJSImpl = false)
{
tryNext = false;
{ // scope for memberSlot
NonNull<mozilla::dom::Response>& memberSlot = RawSetAsResponse();
{
nsresult rv = UnwrapObject<prototypes::id::Response, mozilla::dom::Response>(&value.toObject(), memberSlot);
if (NS_FAILED(rv)) {
mUnion.DestroyResponse();
tryNext = true;
return true;
}
}
}
return true;
}
inline bool
TrySetToPromise(JSContext* cx, JS::Handle<JS::Value> value, bool& tryNext, bool passedToJSImpl = false)
{
tryNext = false;
{ // scope for memberSlot
NonNull<mozilla::dom::Promise>& memberSlot = RawSetAsPromise();
{
nsresult rv = UnwrapObject<prototypes::id::Promise, mozilla::dom::Promise>(&value.toObject(), memberSlot);
if (NS_FAILED(rv)) {
mUnion.DestroyPromise();
tryNext = true;
return true;
}
}
}
return true;
}
private:
inline NonNull<mozilla::dom::Response>&
RawSetAsResponse()
{
MOZ_ASSERT(mUnion.mType == mUnion.eUninitialized);
mUnion.mType = mUnion.eResponse;
return mUnion.mValue.mResponse.SetValue();
}
inline NonNull<mozilla::dom::Promise>&
RawSetAsPromise()
{
MOZ_ASSERT(mUnion.mType == mUnion.eUninitialized);
mUnion.mType = mUnion.ePromise;
return mUnion.mValue.mPromise.SetValue();
}
};
class StringOrArrayBufferOrArrayBufferViewArgument
{
StringOrArrayBufferOrArrayBufferView& mUnion;
StringOrArrayBufferOrArrayBufferViewArgument(const StringOrArrayBufferOrArrayBufferViewArgument&) = delete;
void operator=(const StringOrArrayBufferOrArrayBufferViewArgument) = delete;
public:
explicit inline StringOrArrayBufferOrArrayBufferViewArgument(const StringOrArrayBufferOrArrayBufferView& aUnion)
: mUnion(const_cast<StringOrArrayBufferOrArrayBufferView&>(aUnion))
{
}
inline bool
TrySetToString(JSContext* cx, JS::Handle<JS::Value> value, bool& tryNext, bool passedToJSImpl = false)
{
tryNext = false;
{ // scope for memberSlot
binding_detail::FakeString& memberSlot = RawSetAsString();
if (!ConvertJSValueToString(cx, value, eStringify, eStringify, memberSlot)) {
return false;
}
}
return true;
}
inline void
SetStringData(const nsDependentString::char_type* aData, nsDependentString::size_type aLength)
{
RawSetAsString().Rebind(aData, aLength);
}
inline bool
TrySetToArrayBuffer(JSContext* cx, JS::Handle<JS::Value> value, bool& tryNext, bool passedToJSImpl = false)
{
tryNext = false;
{ // scope for memberSlot
RootedTypedArray<ArrayBuffer>& memberSlot = RawSetAsArrayBuffer(cx);
if (!memberSlot.Init(&value.toObject())) {
mUnion.DestroyArrayBuffer();
tryNext = true;
return true;
}
}
return true;
}
inline bool
TrySetToArrayBufferView(JSContext* cx, JS::Handle<JS::Value> value, bool& tryNext, bool passedToJSImpl = false)
{
tryNext = false;
{ // scope for memberSlot
RootedTypedArray<ArrayBufferView>& memberSlot = RawSetAsArrayBufferView(cx);
if (!memberSlot.Init(&value.toObject())) {
mUnion.DestroyArrayBufferView();
tryNext = true;
return true;
}
}
return true;
}
private:
inline binding_detail::FakeString&
RawSetAsString()
{
MOZ_ASSERT(mUnion.mType == mUnion.eUninitialized);
mUnion.mType = mUnion.eString;
return mUnion.mValue.mString.SetValue();
}
inline RootedTypedArray<ArrayBuffer>&
RawSetAsArrayBuffer(JSContext* cx)
{
MOZ_ASSERT(mUnion.mType == mUnion.eUninitialized);
mUnion.mType = mUnion.eArrayBuffer;
return mUnion.mValue.mArrayBuffer.SetValue(cx);
}
inline RootedTypedArray<ArrayBufferView>&
RawSetAsArrayBufferView(JSContext* cx)
{
MOZ_ASSERT(mUnion.mType == mUnion.eUninitialized);
mUnion.mType = mUnion.eArrayBufferView;
return mUnion.mValue.mArrayBufferView.SetValue(cx);
}
};
class StringOrBlobOrArrayBufferOrArrayBufferViewArgument
{
StringOrBlobOrArrayBufferOrArrayBufferView& mUnion;
StringOrBlobOrArrayBufferOrArrayBufferViewArgument(const StringOrBlobOrArrayBufferOrArrayBufferViewArgument&) = delete;
void operator=(const StringOrBlobOrArrayBufferOrArrayBufferViewArgument) = delete;
public:
explicit inline StringOrBlobOrArrayBufferOrArrayBufferViewArgument(const StringOrBlobOrArrayBufferOrArrayBufferView& aUnion)
: mUnion(const_cast<StringOrBlobOrArrayBufferOrArrayBufferView&>(aUnion))
{
}
inline bool
TrySetToString(JSContext* cx, JS::Handle<JS::Value> value, bool& tryNext, bool passedToJSImpl = false)
{
tryNext = false;
{ // scope for memberSlot
binding_detail::FakeString& memberSlot = RawSetAsString();
if (!ConvertJSValueToString(cx, value, eStringify, eStringify, memberSlot)) {
return false;
}
}
return true;
}
inline void
SetStringData(const nsDependentString::char_type* aData, nsDependentString::size_type aLength)
{
RawSetAsString().Rebind(aData, aLength);
}
inline bool
TrySetToBlob(JSContext* cx, JS::Handle<JS::Value> value, bool& tryNext, bool passedToJSImpl = false)
{
tryNext = false;
{ // scope for memberSlot
NonNull<mozilla::dom::Blob>& memberSlot = RawSetAsBlob();
{
nsresult rv = UnwrapObject<prototypes::id::Blob, mozilla::dom::Blob>(&value.toObject(), memberSlot);
if (NS_FAILED(rv)) {
mUnion.DestroyBlob();
tryNext = true;
return true;
}
}
}
return true;
}
inline bool
TrySetToArrayBuffer(JSContext* cx, JS::Handle<JS::Value> value, bool& tryNext, bool passedToJSImpl = false)
{
tryNext = false;
{ // scope for memberSlot
RootedTypedArray<ArrayBuffer>& memberSlot = RawSetAsArrayBuffer(cx);
if (!memberSlot.Init(&value.toObject())) {
mUnion.DestroyArrayBuffer();
tryNext = true;
return true;
}
}
return true;
}
inline bool
TrySetToArrayBufferView(JSContext* cx, JS::Handle<JS::Value> value, bool& tryNext, bool passedToJSImpl = false)
{
tryNext = false;
{ // scope for memberSlot
RootedTypedArray<ArrayBufferView>& memberSlot = RawSetAsArrayBufferView(cx);
if (!memberSlot.Init(&value.toObject())) {
mUnion.DestroyArrayBufferView();
tryNext = true;
return true;
}
}
return true;
}
private:
inline binding_detail::FakeString&
RawSetAsString()
{
MOZ_ASSERT(mUnion.mType == mUnion.eUninitialized);
mUnion.mType = mUnion.eString;
return mUnion.mValue.mString.SetValue();
}
inline NonNull<mozilla::dom::Blob>&
RawSetAsBlob()
{
MOZ_ASSERT(mUnion.mType == mUnion.eUninitialized);
mUnion.mType = mUnion.eBlob;
return mUnion.mValue.mBlob.SetValue();
}
inline RootedTypedArray<ArrayBuffer>&
RawSetAsArrayBuffer(JSContext* cx)
{
MOZ_ASSERT(mUnion.mType == mUnion.eUninitialized);
mUnion.mType = mUnion.eArrayBuffer;
return mUnion.mValue.mArrayBuffer.SetValue(cx);
}
inline RootedTypedArray<ArrayBufferView>&
RawSetAsArrayBufferView(JSContext* cx)
{
MOZ_ASSERT(mUnion.mType == mUnion.eUninitialized);
mUnion.mType = mUnion.eArrayBufferView;
return mUnion.mValue.mArrayBufferView.SetValue(cx);
}
};
class StringOrCanvasGradientOrCanvasPatternArgument
{
StringOrCanvasGradientOrCanvasPattern& mUnion;
StringOrCanvasGradientOrCanvasPatternArgument(const StringOrCanvasGradientOrCanvasPatternArgument&) = delete;
void operator=(const StringOrCanvasGradientOrCanvasPatternArgument) = delete;
public:
explicit inline StringOrCanvasGradientOrCanvasPatternArgument(const StringOrCanvasGradientOrCanvasPattern& aUnion)
: mUnion(const_cast<StringOrCanvasGradientOrCanvasPattern&>(aUnion))
{
}
inline bool
TrySetToString(JSContext* cx, JS::Handle<JS::Value> value, bool& tryNext, bool passedToJSImpl = false)
{
tryNext = false;
{ // scope for memberSlot
binding_detail::FakeString& memberSlot = RawSetAsString();
if (!ConvertJSValueToString(cx, value, eStringify, eStringify, memberSlot)) {
return false;
}
}
return true;
}
inline void
SetStringData(const nsDependentString::char_type* aData, nsDependentString::size_type aLength)
{
RawSetAsString().Rebind(aData, aLength);
}
inline bool
TrySetToCanvasGradient(JSContext* cx, JS::Handle<JS::Value> value, bool& tryNext, bool passedToJSImpl = false)
{
tryNext = false;
{ // scope for memberSlot
NonNull<mozilla::dom::CanvasGradient>& memberSlot = RawSetAsCanvasGradient();
{
nsresult rv = UnwrapObject<prototypes::id::CanvasGradient, mozilla::dom::CanvasGradient>(&value.toObject(), memberSlot);
if (NS_FAILED(rv)) {
mUnion.DestroyCanvasGradient();
tryNext = true;
return true;
}
}
}
return true;
}
inline bool
TrySetToCanvasPattern(JSContext* cx, JS::Handle<JS::Value> value, bool& tryNext, bool passedToJSImpl = false)
{
tryNext = false;
{ // scope for memberSlot
NonNull<mozilla::dom::CanvasPattern>& memberSlot = RawSetAsCanvasPattern();
{
nsresult rv = UnwrapObject<prototypes::id::CanvasPattern, mozilla::dom::CanvasPattern>(&value.toObject(), memberSlot);
if (NS_FAILED(rv)) {
mUnion.DestroyCanvasPattern();
tryNext = true;
return true;
}
}
}
return true;
}
private:
inline binding_detail::FakeString&
RawSetAsString()
{
MOZ_ASSERT(mUnion.mType == mUnion.eUninitialized);
mUnion.mType = mUnion.eString;
return mUnion.mValue.mString.SetValue();
}
inline NonNull<mozilla::dom::CanvasGradient>&
RawSetAsCanvasGradient()
{
MOZ_ASSERT(mUnion.mType == mUnion.eUninitialized);
mUnion.mType = mUnion.eCanvasGradient;
return mUnion.mValue.mCanvasGradient.SetValue();
}
inline NonNull<mozilla::dom::CanvasPattern>&
RawSetAsCanvasPattern()
{
MOZ_ASSERT(mUnion.mType == mUnion.eUninitialized);
mUnion.mType = mUnion.eCanvasPattern;
return mUnion.mValue.mCanvasPattern.SetValue();
}
};
class StringOrFileOrDirectoryArgument
{
StringOrFileOrDirectory& mUnion;
StringOrFileOrDirectoryArgument(const StringOrFileOrDirectoryArgument&) = delete;
void operator=(const StringOrFileOrDirectoryArgument) = delete;
public:
explicit inline StringOrFileOrDirectoryArgument(const StringOrFileOrDirectory& aUnion)
: mUnion(const_cast<StringOrFileOrDirectory&>(aUnion))
{
}
inline bool
TrySetToString(JSContext* cx, JS::Handle<JS::Value> value, bool& tryNext, bool passedToJSImpl = false)
{
tryNext = false;
{ // scope for memberSlot
binding_detail::FakeString& memberSlot = RawSetAsString();
if (!ConvertJSValueToString(cx, value, eStringify, eStringify, memberSlot)) {
return false;
}
}
return true;
}
inline void
SetStringData(const nsDependentString::char_type* aData, nsDependentString::size_type aLength)
{
RawSetAsString().Rebind(aData, aLength);
}
inline bool
TrySetToFile(JSContext* cx, JS::Handle<JS::Value> value, bool& tryNext, bool passedToJSImpl = false)
{
tryNext = false;
{ // scope for memberSlot
NonNull<mozilla::dom::File>& memberSlot = RawSetAsFile();
{
nsresult rv = UnwrapObject<prototypes::id::File, mozilla::dom::File>(&value.toObject(), memberSlot);
if (NS_FAILED(rv)) {
mUnion.DestroyFile();
tryNext = true;
return true;
}
}
}
return true;
}
inline bool
TrySetToDirectory(JSContext* cx, JS::Handle<JS::Value> value, bool& tryNext, bool passedToJSImpl = false)
{
tryNext = false;
{ // scope for memberSlot
NonNull<mozilla::dom::Directory>& memberSlot = RawSetAsDirectory();
{
nsresult rv = UnwrapObject<prototypes::id::Directory, mozilla::dom::Directory>(&value.toObject(), memberSlot);
if (NS_FAILED(rv)) {
mUnion.DestroyDirectory();
tryNext = true;
return true;
}
}
}
return true;
}
private:
inline binding_detail::FakeString&
RawSetAsString()
{
MOZ_ASSERT(mUnion.mType == mUnion.eUninitialized);
mUnion.mType = mUnion.eString;
return mUnion.mValue.mString.SetValue();
}
inline NonNull<mozilla::dom::File>&
RawSetAsFile()
{
MOZ_ASSERT(mUnion.mType == mUnion.eUninitialized);
mUnion.mType = mUnion.eFile;
return mUnion.mValue.mFile.SetValue();
}
inline NonNull<mozilla::dom::Directory>&
RawSetAsDirectory()
{
MOZ_ASSERT(mUnion.mType == mUnion.eUninitialized);
mUnion.mType = mUnion.eDirectory;
return mUnion.mValue.mDirectory.SetValue();
}
};
class StringOrInstallTriggerDataArgument
{
StringOrInstallTriggerData& mUnion;
StringOrInstallTriggerDataArgument(const StringOrInstallTriggerDataArgument&) = delete;
void operator=(const StringOrInstallTriggerDataArgument) = delete;
public:
explicit inline StringOrInstallTriggerDataArgument(const StringOrInstallTriggerData& aUnion)
: mUnion(const_cast<StringOrInstallTriggerData&>(aUnion))
{
}
inline bool
TrySetToString(JSContext* cx, JS::Handle<JS::Value> value, bool& tryNext, bool passedToJSImpl = false)
{
tryNext = false;
{ // scope for memberSlot
binding_detail::FakeString& memberSlot = RawSetAsString();
if (!ConvertJSValueToString(cx, value, eStringify, eStringify, memberSlot)) {
return false;
}
}
return true;
}
inline void
SetStringData(const nsDependentString::char_type* aData, nsDependentString::size_type aLength)
{
RawSetAsString().Rebind(aData, aLength);
}
inline bool
TrySetToInstallTriggerData(JSContext* cx, JS::Handle<JS::Value> value, bool& tryNext, bool passedToJSImpl = false)
{
tryNext = false;
{ // scope for memberSlot
binding_detail::FastInstallTriggerData& memberSlot = RawSetAsInstallTriggerData();
if (!IsConvertibleToDictionary(cx, value)) {
mUnion.DestroyInstallTriggerData();
tryNext = true;
return true;
}
if (!memberSlot.Init(cx, value, "Member of StringOrInstallTriggerData", passedToJSImpl)) {
return false;
}
}
return true;
}
private:
inline binding_detail::FakeString&
RawSetAsString()
{
MOZ_ASSERT(mUnion.mType == mUnion.eUninitialized);
mUnion.mType = mUnion.eString;
return mUnion.mValue.mString.SetValue();
}
inline binding_detail::FastInstallTriggerData&
RawSetAsInstallTriggerData()
{
MOZ_ASSERT(mUnion.mType == mUnion.eUninitialized);
mUnion.mType = mUnion.eInstallTriggerData;
return mUnion.mValue.mInstallTriggerData.SetValue();
}
};
class StringOrStringSequenceArgument
{
StringOrStringSequence& mUnion;
StringOrStringSequenceArgument(const StringOrStringSequenceArgument&) = delete;
void operator=(const StringOrStringSequenceArgument) = delete;
public:
explicit inline StringOrStringSequenceArgument(const StringOrStringSequence& aUnion)
: mUnion(const_cast<StringOrStringSequence&>(aUnion))
{
}
inline bool
TrySetToString(JSContext* cx, JS::Handle<JS::Value> value, bool& tryNext, bool passedToJSImpl = false)
{
tryNext = false;
{ // scope for memberSlot
binding_detail::FakeString& memberSlot = RawSetAsString();
if (!ConvertJSValueToString(cx, value, eStringify, eStringify, memberSlot)) {
return false;
}
}
return true;
}
inline void
SetStringData(const nsDependentString::char_type* aData, nsDependentString::size_type aLength)
{
RawSetAsString().Rebind(aData, aLength);
}
inline bool
TrySetToStringSequence(JSContext* cx, JS::Handle<JS::Value> value, bool& tryNext, bool passedToJSImpl = false)
{
tryNext = false;
{ // scope for memberSlot
binding_detail::AutoSequence<nsString>& memberSlot = RawSetAsStringSequence();
JS::ForOfIterator iter(cx);
if (!iter.init(value, JS::ForOfIterator::AllowNonIterable)) {
return false;
}
if (!iter.valueIsIterable()) {
mUnion.DestroyStringSequence();
tryNext = true;
return true;
}
binding_detail::AutoSequence<nsString> &arr = memberSlot;
JS::Rooted<JS::Value> temp(cx);
while (true) {
bool done;
if (!iter.next(&temp, &done)) {
return false;
}
if (done) {
break;
}
nsString* slotPtr = arr.AppendElement(mozilla::fallible);
if (!slotPtr) {
JS_ReportOutOfMemory(cx);
return false;
}
nsString& slot = *slotPtr;
if (!ConvertJSValueToString(cx, temp, eStringify, eStringify, slot)) {
return false;
}
}
}
return true;
}
private:
inline binding_detail::FakeString&
RawSetAsString()
{
MOZ_ASSERT(mUnion.mType == mUnion.eUninitialized);
mUnion.mType = mUnion.eString;
return mUnion.mValue.mString.SetValue();
}
inline binding_detail::AutoSequence<nsString>&
RawSetAsStringSequence()
{
MOZ_ASSERT(mUnion.mType == mUnion.eUninitialized);
mUnion.mType = mUnion.eStringSequence;
return mUnion.mValue.mStringSequence.SetValue();
}
};
class StringOrStringSequenceOrConstrainDOMStringParametersArgument
{
StringOrStringSequenceOrConstrainDOMStringParameters& mUnion;
StringOrStringSequenceOrConstrainDOMStringParametersArgument(const StringOrStringSequenceOrConstrainDOMStringParametersArgument&) = delete;
void operator=(const StringOrStringSequenceOrConstrainDOMStringParametersArgument) = delete;
public:
explicit inline StringOrStringSequenceOrConstrainDOMStringParametersArgument(const StringOrStringSequenceOrConstrainDOMStringParameters& aUnion)
: mUnion(const_cast<StringOrStringSequenceOrConstrainDOMStringParameters&>(aUnion))
{
}
inline bool
TrySetToString(JSContext* cx, JS::Handle<JS::Value> value, bool& tryNext, bool passedToJSImpl = false)
{
tryNext = false;
{ // scope for memberSlot
binding_detail::FakeString& memberSlot = RawSetAsString();
if (!ConvertJSValueToString(cx, value, eStringify, eStringify, memberSlot)) {
return false;
}
}
return true;
}
inline void
SetStringData(const nsDependentString::char_type* aData, nsDependentString::size_type aLength)
{
RawSetAsString().Rebind(aData, aLength);
}
inline bool
TrySetToStringSequence(JSContext* cx, JS::Handle<JS::Value> value, bool& tryNext, bool passedToJSImpl = false)
{
tryNext = false;
{ // scope for memberSlot
binding_detail::AutoSequence<nsString>& memberSlot = RawSetAsStringSequence();
JS::ForOfIterator iter(cx);
if (!iter.init(value, JS::ForOfIterator::AllowNonIterable)) {
return false;
}
if (!iter.valueIsIterable()) {
mUnion.DestroyStringSequence();
tryNext = true;
return true;
}
binding_detail::AutoSequence<nsString> &arr = memberSlot;
JS::Rooted<JS::Value> temp(cx);
while (true) {
bool done;
if (!iter.next(&temp, &done)) {
return false;
}
if (done) {
break;
}
nsString* slotPtr = arr.AppendElement(mozilla::fallible);
if (!slotPtr) {
JS_ReportOutOfMemory(cx);
return false;
}
nsString& slot = *slotPtr;
if (!ConvertJSValueToString(cx, temp, eStringify, eStringify, slot)) {
return false;
}
}
}
return true;
}
inline bool
TrySetToConstrainDOMStringParameters(JSContext* cx, JS::Handle<JS::Value> value, bool& tryNext, bool passedToJSImpl = false)
{
tryNext = false;
{ // scope for memberSlot
binding_detail::FastConstrainDOMStringParameters& memberSlot = RawSetAsConstrainDOMStringParameters();
if (!IsConvertibleToDictionary(cx, value)) {
mUnion.DestroyConstrainDOMStringParameters();
tryNext = true;
return true;
}
if (!memberSlot.Init(cx, value, "Member of StringOrStringSequenceOrConstrainDOMStringParameters", passedToJSImpl)) {
return false;
}
}
return true;
}
private:
inline binding_detail::FakeString&
RawSetAsString()
{
MOZ_ASSERT(mUnion.mType == mUnion.eUninitialized);
mUnion.mType = mUnion.eString;
return mUnion.mValue.mString.SetValue();
}
inline binding_detail::AutoSequence<nsString>&
RawSetAsStringSequence()
{
MOZ_ASSERT(mUnion.mType == mUnion.eUninitialized);
mUnion.mType = mUnion.eStringSequence;
return mUnion.mValue.mStringSequence.SetValue();
}
inline binding_detail::FastConstrainDOMStringParameters&
RawSetAsConstrainDOMStringParameters()
{
MOZ_ASSERT(mUnion.mType == mUnion.eUninitialized);
mUnion.mType = mUnion.eConstrainDOMStringParameters;
return mUnion.mValue.mConstrainDOMStringParameters.SetValue();
}
};
class StringOrUnsignedLongArgument
{
StringOrUnsignedLong& mUnion;
StringOrUnsignedLongArgument(const StringOrUnsignedLongArgument&) = delete;
void operator=(const StringOrUnsignedLongArgument) = delete;
public:
explicit inline StringOrUnsignedLongArgument(const StringOrUnsignedLong& aUnion)
: mUnion(const_cast<StringOrUnsignedLong&>(aUnion))
{
}
inline bool
TrySetToString(JSContext* cx, JS::Handle<JS::Value> value, bool& tryNext, bool passedToJSImpl = false)
{
tryNext = false;
{ // scope for memberSlot
binding_detail::FakeString& memberSlot = RawSetAsString();
if (!ConvertJSValueToString(cx, value, eStringify, eStringify, memberSlot)) {
return false;
}
}
return true;
}
inline void
SetStringData(const nsDependentString::char_type* aData, nsDependentString::size_type aLength)
{
RawSetAsString().Rebind(aData, aLength);
}
inline bool
TrySetToUnsignedLong(JSContext* cx, JS::Handle<JS::Value> value, bool& tryNext, bool passedToJSImpl = false)
{
tryNext = false;
{ // scope for memberSlot
uint32_t& memberSlot = RawSetAsUnsignedLong();
if (!ValueToPrimitive<uint32_t, eDefault>(cx, value, &memberSlot)) {
return false;
}
}
return true;
}
private:
inline binding_detail::FakeString&
RawSetAsString()
{
MOZ_ASSERT(mUnion.mType == mUnion.eUninitialized);
mUnion.mType = mUnion.eString;
return mUnion.mValue.mString.SetValue();
}
inline uint32_t&
RawSetAsUnsignedLong()
{
MOZ_ASSERT(mUnion.mType == mUnion.eUninitialized);
mUnion.mType = mUnion.eUnsignedLong;
return mUnion.mValue.mUnsignedLong.SetValue();
}
};
class TelephonyCallOrTelephonyCallGroupArgument
{
TelephonyCallOrTelephonyCallGroup& mUnion;
TelephonyCallOrTelephonyCallGroupArgument(const TelephonyCallOrTelephonyCallGroupArgument&) = delete;
void operator=(const TelephonyCallOrTelephonyCallGroupArgument) = delete;
public:
explicit inline TelephonyCallOrTelephonyCallGroupArgument(const TelephonyCallOrTelephonyCallGroup& aUnion)
: mUnion(const_cast<TelephonyCallOrTelephonyCallGroup&>(aUnion))
{
}
inline bool
TrySetToTelephonyCall(JSContext* cx, JS::Handle<JS::Value> value, bool& tryNext, bool passedToJSImpl = false)
{
tryNext = false;
{ // scope for memberSlot
NonNull<mozilla::dom::TelephonyCall>& memberSlot = RawSetAsTelephonyCall();
{
nsresult rv = UnwrapObject<prototypes::id::TelephonyCall, mozilla::dom::TelephonyCall>(&value.toObject(), memberSlot);
if (NS_FAILED(rv)) {
mUnion.DestroyTelephonyCall();
tryNext = true;
return true;
}
}
}
return true;
}
inline bool
TrySetToTelephonyCallGroup(JSContext* cx, JS::Handle<JS::Value> value, bool& tryNext, bool passedToJSImpl = false)
{
tryNext = false;
{ // scope for memberSlot
NonNull<mozilla::dom::TelephonyCallGroup>& memberSlot = RawSetAsTelephonyCallGroup();
{
nsresult rv = UnwrapObject<prototypes::id::TelephonyCallGroup, mozilla::dom::TelephonyCallGroup>(&value.toObject(), memberSlot);
if (NS_FAILED(rv)) {
mUnion.DestroyTelephonyCallGroup();
tryNext = true;
return true;
}
}
}
return true;
}
private:
inline NonNull<mozilla::dom::TelephonyCall>&
RawSetAsTelephonyCall()
{
MOZ_ASSERT(mUnion.mType == mUnion.eUninitialized);
mUnion.mType = mUnion.eTelephonyCall;
return mUnion.mValue.mTelephonyCall.SetValue();
}
inline NonNull<mozilla::dom::TelephonyCallGroup>&
RawSetAsTelephonyCallGroup()
{
MOZ_ASSERT(mUnion.mType == mUnion.eUninitialized);
mUnion.mType = mUnion.eTelephonyCallGroup;
return mUnion.mValue.mTelephonyCallGroup.SetValue();
}
};
class TextOrElementOrDocumentArgument
{
TextOrElementOrDocument& mUnion;
TextOrElementOrDocumentArgument(const TextOrElementOrDocumentArgument&) = delete;
void operator=(const TextOrElementOrDocumentArgument) = delete;
public:
explicit inline TextOrElementOrDocumentArgument(const TextOrElementOrDocument& aUnion)
: mUnion(const_cast<TextOrElementOrDocument&>(aUnion))
{
}
inline bool
TrySetToText(JSContext* cx, JS::Handle<JS::Value> value, bool& tryNext, bool passedToJSImpl = false)
{
tryNext = false;
{ // scope for memberSlot
NonNull<mozilla::dom::Text>& memberSlot = RawSetAsText();
{
nsresult rv = UnwrapObject<prototypes::id::Text, mozilla::dom::Text>(&value.toObject(), memberSlot);
if (NS_FAILED(rv)) {
mUnion.DestroyText();
tryNext = true;
return true;
}
}
}
return true;
}
inline bool
TrySetToElement(JSContext* cx, JS::Handle<JS::Value> value, bool& tryNext, bool passedToJSImpl = false)
{
tryNext = false;
{ // scope for memberSlot
NonNull<mozilla::dom::Element>& memberSlot = RawSetAsElement();
{
nsresult rv = UnwrapObject<prototypes::id::Element, mozilla::dom::Element>(&value.toObject(), memberSlot);
if (NS_FAILED(rv)) {
mUnion.DestroyElement();
tryNext = true;
return true;
}
}
}
return true;
}
inline bool
TrySetToDocument(JSContext* cx, JS::Handle<JS::Value> value, bool& tryNext, bool passedToJSImpl = false)
{
tryNext = false;
{ // scope for memberSlot
NonNull<nsIDocument>& memberSlot = RawSetAsDocument();
{
nsresult rv = UnwrapObject<prototypes::id::Document, nsIDocument>(&value.toObject(), memberSlot);
if (NS_FAILED(rv)) {
mUnion.DestroyDocument();
tryNext = true;
return true;
}
}
}
return true;
}
private:
inline NonNull<mozilla::dom::Text>&
RawSetAsText()
{
MOZ_ASSERT(mUnion.mType == mUnion.eUninitialized);
mUnion.mType = mUnion.eText;
return mUnion.mValue.mText.SetValue();
}
inline NonNull<mozilla::dom::Element>&
RawSetAsElement()
{
MOZ_ASSERT(mUnion.mType == mUnion.eUninitialized);
mUnion.mType = mUnion.eElement;
return mUnion.mValue.mElement.SetValue();
}
inline NonNull<nsIDocument>&
RawSetAsDocument()
{
MOZ_ASSERT(mUnion.mType == mUnion.eUninitialized);
mUnion.mType = mUnion.eDocument;
return mUnion.mValue.mDocument.SetValue();
}
};
class UnsignedLongLongOrStringArgument
{
UnsignedLongLongOrString& mUnion;
UnsignedLongLongOrStringArgument(const UnsignedLongLongOrStringArgument&) = delete;
void operator=(const UnsignedLongLongOrStringArgument) = delete;
public:
explicit inline UnsignedLongLongOrStringArgument(const UnsignedLongLongOrString& aUnion)
: mUnion(const_cast<UnsignedLongLongOrString&>(aUnion))
{
}
inline bool
TrySetToUnsignedLongLong(JSContext* cx, JS::Handle<JS::Value> value, bool& tryNext, bool passedToJSImpl = false)
{
tryNext = false;
{ // scope for memberSlot
uint64_t& memberSlot = RawSetAsUnsignedLongLong();
if (!ValueToPrimitive<uint64_t, eDefault>(cx, value, &memberSlot)) {
return false;
}
}
return true;
}
inline bool
TrySetToString(JSContext* cx, JS::Handle<JS::Value> value, bool& tryNext, bool passedToJSImpl = false)
{
tryNext = false;
{ // scope for memberSlot
binding_detail::FakeString& memberSlot = RawSetAsString();
if (!ConvertJSValueToString(cx, value, eStringify, eStringify, memberSlot)) {
return false;
}
}
return true;
}
inline void
SetStringData(const nsDependentString::char_type* aData, nsDependentString::size_type aLength)
{
RawSetAsString().Rebind(aData, aLength);
}
private:
inline uint64_t&
RawSetAsUnsignedLongLong()
{
MOZ_ASSERT(mUnion.mType == mUnion.eUninitialized);
mUnion.mType = mUnion.eUnsignedLongLong;
return mUnion.mValue.mUnsignedLongLong.SetValue();
}
inline binding_detail::FakeString&
RawSetAsString()
{
MOZ_ASSERT(mUnion.mType == mUnion.eUninitialized);
mUnion.mType = mUnion.eString;
return mUnion.mValue.mString.SetValue();
}
};
class UnsignedLongOrUint32ArrayOrBooleanArgument
{
UnsignedLongOrUint32ArrayOrBoolean& mUnion;
UnsignedLongOrUint32ArrayOrBooleanArgument(const UnsignedLongOrUint32ArrayOrBooleanArgument&) = delete;
void operator=(const UnsignedLongOrUint32ArrayOrBooleanArgument) = delete;
public:
explicit inline UnsignedLongOrUint32ArrayOrBooleanArgument(const UnsignedLongOrUint32ArrayOrBoolean& aUnion)
: mUnion(const_cast<UnsignedLongOrUint32ArrayOrBoolean&>(aUnion))
{
}
inline bool
TrySetToUnsignedLong(JSContext* cx, JS::Handle<JS::Value> value, bool& tryNext, bool passedToJSImpl = false)
{
tryNext = false;
{ // scope for memberSlot
uint32_t& memberSlot = RawSetAsUnsignedLong();
if (!ValueToPrimitive<uint32_t, eDefault>(cx, value, &memberSlot)) {
return false;
}
}
return true;
}
inline bool
TrySetToUint32Array(JSContext* cx, JS::Handle<JS::Value> value, bool& tryNext, bool passedToJSImpl = false)
{
tryNext = false;
{ // scope for memberSlot
RootedTypedArray<Uint32Array>& memberSlot = RawSetAsUint32Array(cx);
if (!memberSlot.Init(&value.toObject())) {
mUnion.DestroyUint32Array();
tryNext = true;
return true;
}
}
return true;
}
inline bool
TrySetToBoolean(JSContext* cx, JS::Handle<JS::Value> value, bool& tryNext, bool passedToJSImpl = false)
{
tryNext = false;
{ // scope for memberSlot
bool& memberSlot = RawSetAsBoolean();
if (!ValueToPrimitive<bool, eDefault>(cx, value, &memberSlot)) {
return false;
}
}
return true;
}
private:
inline uint32_t&
RawSetAsUnsignedLong()
{
MOZ_ASSERT(mUnion.mType == mUnion.eUninitialized);
mUnion.mType = mUnion.eUnsignedLong;
return mUnion.mValue.mUnsignedLong.SetValue();
}
inline RootedTypedArray<Uint32Array>&
RawSetAsUint32Array(JSContext* cx)
{
MOZ_ASSERT(mUnion.mType == mUnion.eUninitialized);
mUnion.mType = mUnion.eUint32Array;
return mUnion.mValue.mUint32Array.SetValue(cx);
}
inline bool&
RawSetAsBoolean()
{
MOZ_ASSERT(mUnion.mType == mUnion.eUninitialized);
mUnion.mType = mUnion.eBoolean;
return mUnion.mValue.mBoolean.SetValue();
}
};
class UnsignedShortOrObjectArgument
{
UnsignedShortOrObject& mUnion;
UnsignedShortOrObjectArgument(const UnsignedShortOrObjectArgument&) = delete;
void operator=(const UnsignedShortOrObjectArgument) = delete;
public:
explicit inline UnsignedShortOrObjectArgument(const UnsignedShortOrObject& aUnion)
: mUnion(const_cast<UnsignedShortOrObject&>(aUnion))
{
}
inline bool
TrySetToUnsignedShort(JSContext* cx, JS::Handle<JS::Value> value, bool& tryNext, bool passedToJSImpl = false)
{
tryNext = false;
{ // scope for memberSlot
uint16_t& memberSlot = RawSetAsUnsignedShort();
if (!ValueToPrimitive<uint16_t, eDefault>(cx, value, &memberSlot)) {
return false;
}
}
return true;
}
inline bool
SetToObject(JSContext* cx, JSObject* obj, bool passedToJSImpl = false)
{
MOZ_ASSERT(mUnion.mType == mUnion.eUninitialized);
mUnion.mValue.mObject.SetValue(cx, obj);
mUnion.mType = mUnion.eObject;
if (passedToJSImpl && !CallerSubsumes(obj)) {
ThrowErrorMessage(cx, MSG_PERMISSION_DENIED_TO_PASS_ARG, "%s");
return false;
}
return true;
}
private:
inline uint16_t&
RawSetAsUnsignedShort()
{
MOZ_ASSERT(mUnion.mType == mUnion.eUninitialized);
mUnion.mType = mUnion.eUnsignedShort;
return mUnion.mValue.mUnsignedShort.SetValue();
}
};
class VideoTrackOrAudioTrackOrTextTrackArgument
{
VideoTrackOrAudioTrackOrTextTrack& mUnion;
VideoTrackOrAudioTrackOrTextTrackArgument(const VideoTrackOrAudioTrackOrTextTrackArgument&) = delete;
void operator=(const VideoTrackOrAudioTrackOrTextTrackArgument) = delete;
public:
explicit inline VideoTrackOrAudioTrackOrTextTrackArgument(const VideoTrackOrAudioTrackOrTextTrack& aUnion)
: mUnion(const_cast<VideoTrackOrAudioTrackOrTextTrack&>(aUnion))
{
}
inline bool
TrySetToVideoTrack(JSContext* cx, JS::Handle<JS::Value> value, bool& tryNext, bool passedToJSImpl = false)
{
tryNext = false;
{ // scope for memberSlot
NonNull<mozilla::dom::VideoTrack>& memberSlot = RawSetAsVideoTrack();
{
nsresult rv = UnwrapObject<prototypes::id::VideoTrack, mozilla::dom::VideoTrack>(&value.toObject(), memberSlot);
if (NS_FAILED(rv)) {
mUnion.DestroyVideoTrack();
tryNext = true;
return true;
}
}
}
return true;
}
inline bool
TrySetToAudioTrack(JSContext* cx, JS::Handle<JS::Value> value, bool& tryNext, bool passedToJSImpl = false)
{
tryNext = false;
{ // scope for memberSlot
NonNull<mozilla::dom::AudioTrack>& memberSlot = RawSetAsAudioTrack();
{
nsresult rv = UnwrapObject<prototypes::id::AudioTrack, mozilla::dom::AudioTrack>(&value.toObject(), memberSlot);
if (NS_FAILED(rv)) {
mUnion.DestroyAudioTrack();
tryNext = true;
return true;
}
}
}
return true;
}
inline bool
TrySetToTextTrack(JSContext* cx, JS::Handle<JS::Value> value, bool& tryNext, bool passedToJSImpl = false)
{
tryNext = false;
{ // scope for memberSlot
NonNull<mozilla::dom::TextTrack>& memberSlot = RawSetAsTextTrack();
{
nsresult rv = UnwrapObject<prototypes::id::TextTrack, mozilla::dom::TextTrack>(&value.toObject(), memberSlot);
if (NS_FAILED(rv)) {
mUnion.DestroyTextTrack();
tryNext = true;
return true;
}
}
}
return true;
}
private:
inline NonNull<mozilla::dom::VideoTrack>&
RawSetAsVideoTrack()
{
MOZ_ASSERT(mUnion.mType == mUnion.eUninitialized);
mUnion.mType = mUnion.eVideoTrack;
return mUnion.mValue.mVideoTrack.SetValue();
}
inline NonNull<mozilla::dom::AudioTrack>&
RawSetAsAudioTrack()
{
MOZ_ASSERT(mUnion.mType == mUnion.eUninitialized);
mUnion.mType = mUnion.eAudioTrack;
return mUnion.mValue.mAudioTrack.SetValue();
}
inline NonNull<mozilla::dom::TextTrack>&
RawSetAsTextTrack()
{
MOZ_ASSERT(mUnion.mType == mUnion.eUninitialized);
mUnion.mType = mUnion.eTextTrack;
return mUnion.mValue.mTextTrack.SetValue();
}
};
class WebGLBufferOrLongLongArgument
{
WebGLBufferOrLongLong& mUnion;
WebGLBufferOrLongLongArgument(const WebGLBufferOrLongLongArgument&) = delete;
void operator=(const WebGLBufferOrLongLongArgument) = delete;
public:
explicit inline WebGLBufferOrLongLongArgument(const WebGLBufferOrLongLong& aUnion)
: mUnion(const_cast<WebGLBufferOrLongLong&>(aUnion))
{
}
inline bool
TrySetToWebGLBuffer(JSContext* cx, JS::Handle<JS::Value> value, bool& tryNext, bool passedToJSImpl = false)
{
tryNext = false;
{ // scope for memberSlot
NonNull<mozilla::WebGLBuffer>& memberSlot = RawSetAsWebGLBuffer();
{
nsresult rv = UnwrapObject<prototypes::id::WebGLBuffer, mozilla::WebGLBuffer>(&value.toObject(), memberSlot);
if (NS_FAILED(rv)) {
mUnion.DestroyWebGLBuffer();
tryNext = true;
return true;
}
}
}
return true;
}
inline bool
TrySetToLongLong(JSContext* cx, JS::Handle<JS::Value> value, bool& tryNext, bool passedToJSImpl = false)
{
tryNext = false;
{ // scope for memberSlot
int64_t& memberSlot = RawSetAsLongLong();
if (!ValueToPrimitive<int64_t, eDefault>(cx, value, &memberSlot)) {
return false;
}
}
return true;
}
private:
inline NonNull<mozilla::WebGLBuffer>&
RawSetAsWebGLBuffer()
{
MOZ_ASSERT(mUnion.mType == mUnion.eUninitialized);
mUnion.mType = mUnion.eWebGLBuffer;
return mUnion.mValue.mWebGLBuffer.SetValue();
}
inline int64_t&
RawSetAsLongLong()
{
MOZ_ASSERT(mUnion.mType == mUnion.eUninitialized);
mUnion.mType = mUnion.eLongLong;
return mUnion.mValue.mLongLong.SetValue();
}
};
class WindowOrMessagePortArgument
{
WindowOrMessagePort& mUnion;
WindowOrMessagePortArgument(const WindowOrMessagePortArgument&) = delete;
void operator=(const WindowOrMessagePortArgument) = delete;
public:
explicit inline WindowOrMessagePortArgument(const WindowOrMessagePort& aUnion)
: mUnion(const_cast<WindowOrMessagePort&>(aUnion))
{
}
inline bool
TrySetToWindow(JSContext* cx, JS::Handle<JS::Value> value, bool& tryNext, bool passedToJSImpl = false)
{
tryNext = false;
{ // scope for memberSlot
NonNull<nsGlobalWindow>& memberSlot = RawSetAsWindow();
{
nsresult rv = UnwrapObject<prototypes::id::Window, nsGlobalWindow>(&value.toObject(), memberSlot);
if (NS_FAILED(rv)) {
mUnion.DestroyWindow();
tryNext = true;
return true;
}
}
}
return true;
}
inline bool
TrySetToMessagePort(JSContext* cx, JS::Handle<JS::Value> value, bool& tryNext, bool passedToJSImpl = false)
{
tryNext = false;
{ // scope for memberSlot
NonNull<mozilla::dom::MessagePortBase>& memberSlot = RawSetAsMessagePort();
{
nsresult rv = UnwrapObject<prototypes::id::MessagePort, mozilla::dom::MessagePortBase>(&value.toObject(), memberSlot);
if (NS_FAILED(rv)) {
mUnion.DestroyMessagePort();
tryNext = true;
return true;
}
}
}
return true;
}
private:
inline NonNull<nsGlobalWindow>&
RawSetAsWindow()
{
MOZ_ASSERT(mUnion.mType == mUnion.eUninitialized);
mUnion.mType = mUnion.eWindow;
return mUnion.mValue.mWindow.SetValue();
}
inline NonNull<mozilla::dom::MessagePortBase>&
RawSetAsMessagePort()
{
MOZ_ASSERT(mUnion.mType == mUnion.eUninitialized);
mUnion.mType = mUnion.eMessagePort;
return mUnion.mValue.mMessagePort.SetValue();
}
};
class WindowProxyOrMessagePortOrClientArgument
{
WindowProxyOrMessagePortOrClient& mUnion;
Maybe<nsRefPtr<nsIDOMWindow>> mWindowProxyHolder;
WindowProxyOrMessagePortOrClientArgument(const WindowProxyOrMessagePortOrClientArgument&) = delete;
void operator=(const WindowProxyOrMessagePortOrClientArgument) = delete;
public:
explicit inline WindowProxyOrMessagePortOrClientArgument(const WindowProxyOrMessagePortOrClient& aUnion)
: mUnion(const_cast<WindowProxyOrMessagePortOrClient&>(aUnion))
{
}
inline bool
TrySetToWindowProxy(JSContext* cx, JS::Handle<JS::Value> value, bool& tryNext, bool passedToJSImpl = false)
{
tryNext = false;
{ // scope for memberSlot
nsIDOMWindow*& memberSlot = RawSetAsWindowProxy();
mWindowProxyHolder.emplace();
JS::Rooted<JSObject*> source(cx, &value.toObject());
if (NS_FAILED(UnwrapArg<nsIDOMWindow>(source, getter_AddRefs(mWindowProxyHolder.ref())))) {
mWindowProxyHolder.reset();
mUnion.DestroyWindowProxy();
tryNext = true;
return true;
}
MOZ_ASSERT(mWindowProxyHolder.ref());
memberSlot = mWindowProxyHolder.ref();
}
return true;
}
inline bool
TrySetToMessagePort(JSContext* cx, JS::Handle<JS::Value> value, bool& tryNext, bool passedToJSImpl = false)
{
tryNext = false;
{ // scope for memberSlot
NonNull<mozilla::dom::MessagePortBase>& memberSlot = RawSetAsMessagePort();
{
nsresult rv = UnwrapObject<prototypes::id::MessagePort, mozilla::dom::MessagePortBase>(&value.toObject(), memberSlot);
if (NS_FAILED(rv)) {
mUnion.DestroyMessagePort();
tryNext = true;
return true;
}
}
}
return true;
}
inline bool
TrySetToClient(JSContext* cx, JS::Handle<JS::Value> value, bool& tryNext, bool passedToJSImpl = false)
{
tryNext = false;
{ // scope for memberSlot
NonNull<mozilla::dom::workers::ServiceWorkerClient>& memberSlot = RawSetAsClient();
{
nsresult rv = UnwrapObject<prototypes::id::Client, mozilla::dom::workers::ServiceWorkerClient>(&value.toObject(), memberSlot);
if (NS_FAILED(rv)) {
mUnion.DestroyClient();
tryNext = true;
return true;
}
}
}
return true;
}
private:
inline nsIDOMWindow*&
RawSetAsWindowProxy()
{
MOZ_ASSERT(mUnion.mType == mUnion.eUninitialized);
mUnion.mType = mUnion.eWindowProxy;
return mUnion.mValue.mWindowProxy.SetValue();
}
inline NonNull<mozilla::dom::MessagePortBase>&
RawSetAsMessagePort()
{
MOZ_ASSERT(mUnion.mType == mUnion.eUninitialized);
mUnion.mType = mUnion.eMessagePort;
return mUnion.mValue.mMessagePort.SetValue();
}
inline NonNull<mozilla::dom::workers::ServiceWorkerClient>&
RawSetAsClient()
{
MOZ_ASSERT(mUnion.mType == mUnion.eUninitialized);
mUnion.mType = mUnion.eClient;
return mUnion.mValue.mClient.SetValue();
}
};
class mozContactOrStringArgument
{
mozContactOrString& mUnion;
mozContactOrStringArgument(const mozContactOrStringArgument&) = delete;
void operator=(const mozContactOrStringArgument) = delete;
public:
explicit inline mozContactOrStringArgument(const mozContactOrString& aUnion)
: mUnion(const_cast<mozContactOrString&>(aUnion))
{
}
inline bool
TrySetTomozContact(JSContext* cx, JS::Handle<JS::Value> value, bool& tryNext, bool passedToJSImpl = false)
{
tryNext = false;
{ // scope for memberSlot
NonNull<mozilla::dom::mozContact>& memberSlot = RawSetAsmozContact();
{
nsresult rv = UnwrapObject<prototypes::id::mozContact, mozilla::dom::mozContact>(&value.toObject(), memberSlot);
if (NS_FAILED(rv)) {
mUnion.DestroymozContact();
tryNext = true;
return true;
}
}
}
return true;
}
inline bool
TrySetToString(JSContext* cx, JS::Handle<JS::Value> value, bool& tryNext, bool passedToJSImpl = false)
{
tryNext = false;
{ // scope for memberSlot
binding_detail::FakeString& memberSlot = RawSetAsString();
if (!ConvertJSValueToString(cx, value, eStringify, eStringify, memberSlot)) {
return false;
}
}
return true;
}
inline void
SetStringData(const nsDependentString::char_type* aData, nsDependentString::size_type aLength)
{
RawSetAsString().Rebind(aData, aLength);
}
private:
inline NonNull<mozilla::dom::mozContact>&
RawSetAsmozContact()
{
MOZ_ASSERT(mUnion.mType == mUnion.eUninitialized);
mUnion.mType = mUnion.emozContact;
return mUnion.mValue.mmozContact.SetValue();
}
inline binding_detail::FakeString&
RawSetAsString()
{
MOZ_ASSERT(mUnion.mType == mUnion.eUninitialized);
mUnion.mType = mUnion.eString;
return mUnion.mValue.mString.SetValue();
}
};
} // namespace dom
} // namespace mozilla
#endif // mozilla_dom_UnionConversions_h
| [
"[email protected]"
] | |
e2c256eac7dba04077b2942737dca7561689e210 | ba4db75b9d1f08c6334bf7b621783759cd3209c7 | /src_main/dmserializers/importsfmv4.cpp | 1dc8ecea2b4781f4dae16077c7fbca2591130ec3 | [] | no_license | equalent/source-2007 | a27326c6eb1e63899e3b77da57f23b79637060c0 | d07be8d02519ff5c902e1eb6430e028e1b302c8b | refs/heads/master | 2020-03-28T22:46:44.606988 | 2017-03-27T18:05:57 | 2017-03-27T18:05:57 | 149,257,460 | 2 | 0 | null | 2018-09-18T08:52:10 | 2018-09-18T08:52:09 | null | WINDOWS-1252 | C++ | false | false | 3,725 | cpp | //====== Copyright © 1996-2006, Valve Corporation, All rights reserved. =======
//
// Purpose:
//
//=============================================================================
#include "dmserializers.h"
#include "dmebaseimporter.h"
#include "datamodel/idatamodel.h"
#include "datamodel/dmelement.h"
#include "tier1/KeyValues.h"
#include "tier1/utlbuffer.h"
#include "tier1/utlmap.h"
#include <limits.h>
//-----------------------------------------------------------------------------
// Format converter
//-----------------------------------------------------------------------------
class CImportSFMV4 : public CSFMBaseImporter
{
typedef CSFMBaseImporter BaseClass;
public:
CImportSFMV4( char const *formatName, char const *nextFormatName );
private:
virtual bool DoFixup( CDmElement *pSourceRoot );
void FixupElement( CDmElement *pElement );
// Fixes up all elements
void BuildList( CDmElement *pElement, CUtlRBTree< CDmElement *, int >& list );
};
//-----------------------------------------------------------------------------
// Singleton instance
//-----------------------------------------------------------------------------
static CImportSFMV4 s_ImportSFMV4( "sfm_v4", "sfm_v5" );
void InstallSFMV4Importer( IDataModel *pFactory )
{
pFactory->AddLegacyUpdater( &s_ImportSFMV4 );
}
//-----------------------------------------------------------------------------
// Constructor
//-----------------------------------------------------------------------------
CImportSFMV4::CImportSFMV4( char const *formatName, char const *nextFormatName ) :
BaseClass( formatName, nextFormatName )
{
}
// Fixes up all elements
//-----------------------------------------------------------------------------
void CImportSFMV4::FixupElement( CDmElement *pElement )
{
if ( !pElement )
return;
const char *pType = pElement->GetTypeString();
if ( !V_stricmp( pType, "DmeCamera" ) )
{
CDmAttribute *pOldToneMapScaleAttr = pElement->GetAttribute( "toneMapScale" );
float fNewBloomScale = pOldToneMapScaleAttr->GetValue<float>( );
Assert( !pElement->HasAttribute("bloomScale") );
CDmAttribute *pNewBloomScaleAttr = pElement->AddAttribute( "bloomScale", AT_FLOAT );
pNewBloomScaleAttr->SetValue( fNewBloomScale );
pOldToneMapScaleAttr->SetValue( 1.0f );
}
}
// Fixes up all elements
//-----------------------------------------------------------------------------
void CImportSFMV4::BuildList( CDmElement *pElement, CUtlRBTree< CDmElement *, int >& list )
{
if ( !pElement )
return;
if ( list.Find( pElement ) != list.InvalidIndex() )
return;
list.Insert( pElement );
// Descend to bottom of tree, then do fixup coming back up the tree
for ( CDmAttribute *pAttribute = pElement->FirstAttribute(); pAttribute; pAttribute = pAttribute->NextAttribute() )
{
if ( pAttribute->GetType() == AT_ELEMENT )
{
CDmElement *pElement = pAttribute->GetValueElement<CDmElement>( );
BuildList( pElement, list );
continue;
}
if ( pAttribute->GetType() == AT_ELEMENT_ARRAY )
{
CDmrElementArray<> array( pAttribute );
int nCount = array.Count();
for ( int i = 0; i < nCount; ++i )
{
CDmElement *pChild = array[ i ];
BuildList( pChild, list );
}
continue;
}
}
}
bool CImportSFMV4::DoFixup( CDmElement *pSourceRoot )
{
CUtlRBTree< CDmElement *, int > fixlist( 0, 0, DefLessFunc( CDmElement * ) );
BuildList( pSourceRoot, fixlist );
for ( int i = fixlist.FirstInorder(); i != fixlist.InvalidIndex() ; i = fixlist.NextInorder( i ) )
{
// Search and replace in the entire tree!
FixupElement( fixlist[ i ] );
}
return true;
}
| [
"[email protected]"
] | |
6d5c3503979b50b480b8d6cd816495d64d80ce1e | 8750513879cb6f24648d43ae16b21ba34a6c78bd | /StackAsLinkedList.CPP | 95dd418242bf91e1511185ae6ad9f07cf210d5db | [] | no_license | NamanArora/Cpp-Algorithms | 83fc9ca4cf60af527afe012a34f0c82f56795c3e | 510c22d795f80dbded1bbc97f66b14365154302b | refs/heads/master | 2021-05-04T10:18:13.582458 | 2018-06-30T14:12:19 | 2018-06-30T14:12:19 | 43,776,797 | 2 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 701 | cpp | #include<iostream.h>
#include<conio.h>
#include<stdio.h>
#include<stdlib.h>
#include<dos.h>
#include<fstream.h>
struct node
{
int data;
node *next;
};
class stack
{
node *top;
public:
stack()
{
top=NULL;
}
void push(int item)
{
node *p=new node;
if(p==NULL)
{
cout << "Stack full";
}
else
{
p->data=item;
p->next=top;
top=p;
cout << "Data entered: " << top->data << endl;
}
}
void pop()
{
if(top==NULL)
cout << "Stack is empty" << endl;
else{
node *t=top;
cout << t;
cout << "Delete data: " << top->data << endl;
top=t->next;
delete t;
}
}
};
void main()
{
stack obj;
obj.push(10);
obj.push(11);
obj.pop();
obj.pop();
obj.pop();
getch();
}
| [
"[email protected]"
] | |
9bb6bcfb7a2b844d2e156f3955f6ef07a205551e | 29211fecff372e7957c7657c222058773d396388 | /GameClient/ClientNet.cpp | 0ef945009e9822e97a2c889517bdadf263a165f3 | [] | no_license | Kiridmit/mysamples | 40c5754fcaaab223892f9d93c4d390d492992fd1 | 9f8c64f2dfce9d4ded61726d7ac4807553ab1baa | refs/heads/master | 2021-07-04T14:52:26.994102 | 2017-09-26T10:46:06 | 2017-09-26T10:46:06 | 104,870,654 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 955 | cpp | #include "ClientNet.h"
void ClientNet::Start(std::string ip, std::string port) {
slots.connect(netGameClient.sig_connected(), this, &ClientNet::OnConnect);
slots.connect(netGameClient.sig_disconnected(), this, &ClientNet::OnDisconnect);
slots.connect(netGameClient.sig_event_received(), this, &ClientNet::OnEvent);
netGameClient.connect(ip, port);
}
void ClientNet::Stop() {
netGameClient.disconnect();
}
void ClientNet::Request(const clan::NetGameEvent &e) {
netGameClient.send_event(e);
}
clan::Signal_v1<const clan::NetGameEvent&> &ClientNet::SigResponse() {
return sigResponse;
}
void ClientNet::OnConnect() {
sigResponse.invoke(clan::NetGameEvent("connect"));
}
void ClientNet::OnDisconnect() {
sigResponse.invoke(clan::NetGameEvent("disconnect"));
}
void ClientNet::OnEvent(const clan::NetGameEvent &e) {
std::string command = e.get_name();
if (command != "connect" && command != "disconnect") {
sigResponse.invoke(e);
}
}
| [
"[email protected]"
] | |
a49145aa72da43dece42ded3691e1b791d618057 | a06515f4697a3dbcbae4e3c05de2f8632f8d5f46 | /corpus/taken_from_cppcheck_tests/stolen_13153.cpp | 93e266e2290a2c6c9ae6884427a051a517f32d74 | [] | no_license | pauldreik/fuzzcppcheck | 12d9c11bcc182cc1f1bb4893e0925dc05fcaf711 | 794ba352af45971ff1f76d665b52adeb42dcab5f | refs/heads/master | 2020-05-01T01:55:04.280076 | 2019-03-22T21:05:28 | 2019-03-22T21:05:28 | 177,206,313 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 10 | cpp | ;0xFFFFFF; | [
"[email protected]"
] | |
773b9519e22162c7dd6618b5c0d91163e1499698 | a62342d6359a88b0aee911e549a4973fa38de9ea | /0.6.0.3/External/SDK/DE_UpdateWorkByNPCID_functions.cpp | b0e54c0ce87b5fc5d2c7c5001d1f13525467df82 | [] | no_license | zanzo420/Medieval-Dynasty-SDK | d020ad634328ee8ee612ba4bd7e36b36dab740ce | d720e49ae1505e087790b2743506921afb28fc18 | refs/heads/main | 2023-06-20T03:00:17.986041 | 2021-07-15T04:51:34 | 2021-07-15T04:51:34 | 386,165,085 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,308 | cpp | // Name: Medieval Dynasty, Version: 0.6.0.3
#include "../pch.h"
/*!!DEFINE!!*/
/*!!HELPER_DEF!!*/
/*!!HELPER_INC!!*/
#ifdef _MSC_VER
#pragma pack(push, 0x01)
#endif
namespace CG
{
//---------------------------------------------------------------------------
// Functions
//---------------------------------------------------------------------------
// Function DE_UpdateWorkByNPCID.DE_UpdateWorkByNPCID_C.RecieveEventTriggered
// (Event, Public, BlueprintCallable, BlueprintEvent)
// Parameters:
// class APlayerController* ConsideringPlayer (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash)
// class AActor* NPCActor (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash)
void UDE_UpdateWorkByNPCID_C::RecieveEventTriggered(class APlayerController* ConsideringPlayer, class AActor* NPCActor)
{
static auto fn = UObject::FindObject<UFunction>("Function DE_UpdateWorkByNPCID.DE_UpdateWorkByNPCID_C.RecieveEventTriggered");
UDE_UpdateWorkByNPCID_C_RecieveEventTriggered_Params params;
params.ConsideringPlayer = ConsideringPlayer;
params.NPCActor = NPCActor;
auto flags = fn->FunctionFlags;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
}
// Function DE_UpdateWorkByNPCID.DE_UpdateWorkByNPCID_C.ExecuteUbergraph_DE_UpdateWorkByNPCID
// (Final)
// Parameters:
// int EntryPoint (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash)
void UDE_UpdateWorkByNPCID_C::ExecuteUbergraph_DE_UpdateWorkByNPCID(int EntryPoint)
{
static auto fn = UObject::FindObject<UFunction>("Function DE_UpdateWorkByNPCID.DE_UpdateWorkByNPCID_C.ExecuteUbergraph_DE_UpdateWorkByNPCID");
UDE_UpdateWorkByNPCID_C_ExecuteUbergraph_DE_UpdateWorkByNPCID_Params params;
params.EntryPoint = EntryPoint;
auto flags = fn->FunctionFlags;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
}
void UDE_UpdateWorkByNPCID_C::AfterRead()
{
UDialogueEvents::AfterRead();
}
void UDE_UpdateWorkByNPCID_C::BeforeDelete()
{
UDialogueEvents::BeforeDelete();
}
}
#ifdef _MSC_VER
#pragma pack(pop)
#endif
| [
"[email protected]"
] | |
02257dba726f96aca19d30fa6af6344a81897661 | 996b75d54e9bdda308a078f93028d2aed667db94 | /Engine/EngineDeps/Deps/third_party/Imgui/imgui_draw.cpp | b23b29d5913b5ca1a516609b294f5413ca08a9a6 | [] | no_license | sravankaruturi/Vermin | f3227c7b4cba85a6b6f877338896bb8c0537bbd3 | 996cca1b9773b2168751f7049623d60c47dbd5c1 | refs/heads/master | 2020-04-05T02:16:16.562568 | 2018-12-04T18:14:41 | 2018-12-04T18:14:41 | 156,470,355 | 2 | 0 | null | 2018-11-21T19:40:36 | 2018-11-07T01:04:14 | C++ | UTF-8 | C++ | false | false | 162,197 | cpp | // dear imgui, v1.62
// (drawing and font code)
// Contains implementation for
// - Default styles
// - ImDrawList
// - ImDrawData
// - ImFontAtlas
// - ImFont
// - Default font data
#if defined(_MSC_VER) && !defined(_CRT_SECURE_NO_WARNINGS)
#define _CRT_SECURE_NO_WARNINGS
#endif
#include "imgui.h"
#define IMGUI_DEFINE_MATH_OPERATORS
#include "imgui_internal.h"
#if !defined(alloca)
#ifdef _WIN32
#include <malloc.h> // alloca
#if !defined(alloca)
#define alloca _alloca // for clang with MS Codegen
#endif
#elif defined(__GLIBC__) || defined(__sun)
#include <alloca.h> // alloca
#else
#include <stdlib.h> // alloca
#endif
#endif
#ifdef _MSC_VER
#pragma warning (disable: 4505) // unreferenced local function has been removed (stb stuff)
#pragma warning (disable: 4996) // 'This function or variable may be unsafe': strcpy, strdup, sprintf, vsnprintf, sscanf, fopen
#endif
#ifdef __clang__
#pragma clang diagnostic ignored "-Wold-style-cast" // warning : use of old-style cast // yes, they are more terse.
#pragma clang diagnostic ignored "-Wfloat-equal" // warning : comparing floating point with == or != is unsafe // storing and comparing against same constants ok.
#pragma clang diagnostic ignored "-Wglobal-constructors" // warning : declaration requires a global destructor // similar to above, not sure what the exact difference it.
#pragma clang diagnostic ignored "-Wsign-conversion" // warning : implicit conversion changes signedness //
#if __has_warning("-Wcomma")
#pragma clang diagnostic ignored "-Wcomma" // warning : possible misuse of comma operator here //
#endif
#if __has_warning("-Wreserved-id-macro")
#pragma clang diagnostic ignored "-Wreserved-id-macro" // warning : macro name is a reserved identifier //
#endif
#if __has_warning("-Wdouble-promotion")
#pragma clang diagnostic ignored "-Wdouble-promotion" // warning: implicit conversion from 'float' to 'double' when passing argument to function
#endif
#elif defined(__GNUC__)
#pragma GCC diagnostic ignored "-Wunused-function" // warning: 'xxxx' defined but not used
#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
#if __GNUC__ >= 8
#pragma GCC diagnostic ignored "-Wclass-memaccess" // warning: 'memset/memcpy' clearing/writing an object of type 'xxxx' with no trivial copy-assignment; use assignment or value-initialization instead
#endif
#endif
//-------------------------------------------------------------------------
// STB libraries implementation
//-------------------------------------------------------------------------
// Compile time options:
//#define IMGUI_STB_NAMESPACE ImGuiStb
//#define IMGUI_STB_TRUETYPE_FILENAME "my_folder/stb_truetype.h"
//#define IMGUI_STB_RECT_PACK_FILENAME "my_folder/stb_rect_pack.h"
//#define IMGUI_DISABLE_STB_TRUETYPE_IMPLEMENTATION
//#define IMGUI_DISABLE_STB_RECT_PACK_IMPLEMENTATION
#ifdef IMGUI_STB_NAMESPACE
namespace IMGUI_STB_NAMESPACE
{
#endif
#ifdef _MSC_VER
#pragma warning (push)
#pragma warning (disable: 4456) // declaration of 'xx' hides previous local declaration
#endif
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wunused-function"
#pragma clang diagnostic ignored "-Wmissing-prototypes"
#pragma clang diagnostic ignored "-Wimplicit-fallthrough"
#pragma clang diagnostic ignored "-Wcast-qual" // warning : cast from 'const xxxx *' to 'xxx *' drops const qualifier //
#endif
#ifdef __GNUC__
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wtype-limits" // warning: comparison is always true due to limited range of data type [-Wtype-limits]
#pragma GCC diagnostic ignored "-Wcast-qual" // warning: cast from type 'const xxxx *' to type 'xxxx *' casts away qualifiers
#endif
#ifndef STB_RECT_PACK_IMPLEMENTATION // in case the user already have an implementation in the _same_ compilation unit (e.g. unity builds)
#ifndef IMGUI_DISABLE_STB_RECT_PACK_IMPLEMENTATION
#define STBRP_STATIC
#define STBRP_ASSERT(x) IM_ASSERT(x)
#define STB_RECT_PACK_IMPLEMENTATION
#endif
#ifdef IMGUI_STB_RECT_PACK_FILENAME
#include IMGUI_STB_RECT_PACK_FILENAME
#else
#include "stb_rect_pack.h"
#endif
#endif
#ifndef STB_TRUETYPE_IMPLEMENTATION // in case the user already have an implementation in the _same_ compilation unit (e.g. unity builds)
#ifndef IMGUI_DISABLE_STB_TRUETYPE_IMPLEMENTATION
#define STBTT_malloc(x, u) ((void)(u), ImGui::MemAlloc(x))
#define STBTT_free(x, u) ((void)(u), ImGui::MemFree(x))
#define STBTT_assert(x) IM_ASSERT(x)
#define STBTT_fmod(x, y) ImFmod(x,y)
#define STBTT_sqrt(x) ImSqrt(x)
#define STBTT_pow(x, y) ImPow(x,y)
#define STBTT_fabs(x) ImFabs(x)
#define STBTT_ifloor(x) ((int)ImFloorStd(x))
#define STBTT_iceil(x) ((int)ImCeil(x))
#define STBTT_STATIC
#define STB_TRUETYPE_IMPLEMENTATION
#else
#define STBTT_DEF extern
#endif
#ifdef IMGUI_STB_TRUETYPE_FILENAME
#include IMGUI_STB_TRUETYPE_FILENAME
#else
#include "stb_truetype.h"
#endif
#endif
#ifdef __GNUC__
#pragma GCC diagnostic pop
#endif
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#ifdef _MSC_VER
#pragma warning (pop)
#endif
#ifdef IMGUI_STB_NAMESPACE
} // namespace ImGuiStb
using namespace IMGUI_STB_NAMESPACE;
#endif
//-----------------------------------------------------------------------------
// Style functions
//-----------------------------------------------------------------------------
void ImGui::StyleColorsDark(ImGuiStyle *dst) {
ImGuiStyle *style = dst ? dst : &ImGui::GetStyle();
ImVec4 *colors = style->Colors;
colors[ImGuiCol_Text] = ImVec4(1.00f, 1.00f, 1.00f, 1.00f);
colors[ImGuiCol_TextDisabled] = ImVec4(0.50f, 0.50f, 0.50f, 1.00f);
colors[ImGuiCol_WindowBg] = ImVec4(0.06f, 0.06f, 0.06f, 0.94f);
colors[ImGuiCol_ChildBg] = ImVec4(1.00f, 1.00f, 1.00f, 0.00f);
colors[ImGuiCol_PopupBg] = ImVec4(0.08f, 0.08f, 0.08f, 0.94f);
colors[ImGuiCol_Border] = ImVec4(0.43f, 0.43f, 0.50f, 0.50f);
colors[ImGuiCol_BorderShadow] = ImVec4(0.00f, 0.00f, 0.00f, 0.00f);
colors[ImGuiCol_FrameBg] = ImVec4(0.16f, 0.29f, 0.48f, 0.54f);
colors[ImGuiCol_FrameBgHovered] = ImVec4(0.26f, 0.59f, 0.98f, 0.40f);
colors[ImGuiCol_FrameBgActive] = ImVec4(0.26f, 0.59f, 0.98f, 0.67f);
colors[ImGuiCol_TitleBg] = ImVec4(0.04f, 0.04f, 0.04f, 1.00f);
colors[ImGuiCol_TitleBgActive] = ImVec4(0.16f, 0.29f, 0.48f, 1.00f);
colors[ImGuiCol_TitleBgCollapsed] = ImVec4(0.00f, 0.00f, 0.00f, 0.51f);
colors[ImGuiCol_MenuBarBg] = ImVec4(0.14f, 0.14f, 0.14f, 1.00f);
colors[ImGuiCol_ScrollbarBg] = ImVec4(0.02f, 0.02f, 0.02f, 0.53f);
colors[ImGuiCol_ScrollbarGrab] = ImVec4(0.31f, 0.31f, 0.31f, 1.00f);
colors[ImGuiCol_ScrollbarGrabHovered] = ImVec4(0.41f, 0.41f, 0.41f, 1.00f);
colors[ImGuiCol_ScrollbarGrabActive] = ImVec4(0.51f, 0.51f, 0.51f, 1.00f);
colors[ImGuiCol_CheckMark] = ImVec4(0.26f, 0.59f, 0.98f, 1.00f);
colors[ImGuiCol_SliderGrab] = ImVec4(0.24f, 0.52f, 0.88f, 1.00f);
colors[ImGuiCol_SliderGrabActive] = ImVec4(0.26f, 0.59f, 0.98f, 1.00f);
colors[ImGuiCol_Button] = ImVec4(0.26f, 0.59f, 0.98f, 0.40f);
colors[ImGuiCol_ButtonHovered] = ImVec4(0.26f, 0.59f, 0.98f, 1.00f);
colors[ImGuiCol_ButtonActive] = ImVec4(0.06f, 0.53f, 0.98f, 1.00f);
colors[ImGuiCol_Header] = ImVec4(0.26f, 0.59f, 0.98f, 0.31f);
colors[ImGuiCol_HeaderHovered] = ImVec4(0.26f, 0.59f, 0.98f, 0.80f);
colors[ImGuiCol_HeaderActive] = ImVec4(0.26f, 0.59f, 0.98f, 1.00f);
colors[ImGuiCol_Separator] = colors[ImGuiCol_Border];
colors[ImGuiCol_SeparatorHovered] = ImVec4(0.10f, 0.40f, 0.75f, 0.78f);
colors[ImGuiCol_SeparatorActive] = ImVec4(0.10f, 0.40f, 0.75f, 1.00f);
colors[ImGuiCol_ResizeGrip] = ImVec4(0.26f, 0.59f, 0.98f, 0.25f);
colors[ImGuiCol_ResizeGripHovered] = ImVec4(0.26f, 0.59f, 0.98f, 0.67f);
colors[ImGuiCol_ResizeGripActive] = ImVec4(0.26f, 0.59f, 0.98f, 0.95f);
colors[ImGuiCol_PlotLines] = ImVec4(0.61f, 0.61f, 0.61f, 1.00f);
colors[ImGuiCol_PlotLinesHovered] = ImVec4(1.00f, 0.43f, 0.35f, 1.00f);
colors[ImGuiCol_PlotHistogram] = ImVec4(0.90f, 0.70f, 0.00f, 1.00f);
colors[ImGuiCol_PlotHistogramHovered] = ImVec4(1.00f, 0.60f, 0.00f, 1.00f);
colors[ImGuiCol_TextSelectedBg] = ImVec4(0.26f, 0.59f, 0.98f, 0.35f);
colors[ImGuiCol_ModalWindowDarkening] = ImVec4(0.80f, 0.80f, 0.80f, 0.35f);
colors[ImGuiCol_DragDropTarget] = ImVec4(1.00f, 1.00f, 0.00f, 0.90f);
colors[ImGuiCol_NavHighlight] = ImVec4(0.26f, 0.59f, 0.98f, 1.00f);
colors[ImGuiCol_NavWindowingHighlight] = ImVec4(1.00f, 1.00f, 1.00f, 0.70f);
}
void ImGui::StyleColorsClassic(ImGuiStyle *dst) {
ImGuiStyle *style = dst ? dst : &ImGui::GetStyle();
ImVec4 *colors = style->Colors;
colors[ImGuiCol_Text] = ImVec4(0.90f, 0.90f, 0.90f, 1.00f);
colors[ImGuiCol_TextDisabled] = ImVec4(0.60f, 0.60f, 0.60f, 1.00f);
colors[ImGuiCol_WindowBg] = ImVec4(0.00f, 0.00f, 0.00f, 0.70f);
colors[ImGuiCol_ChildBg] = ImVec4(0.00f, 0.00f, 0.00f, 0.00f);
colors[ImGuiCol_PopupBg] = ImVec4(0.11f, 0.11f, 0.14f, 0.92f);
colors[ImGuiCol_Border] = ImVec4(0.50f, 0.50f, 0.50f, 0.50f);
colors[ImGuiCol_BorderShadow] = ImVec4(0.00f, 0.00f, 0.00f, 0.00f);
colors[ImGuiCol_FrameBg] = ImVec4(0.43f, 0.43f, 0.43f, 0.39f);
colors[ImGuiCol_FrameBgHovered] = ImVec4(0.47f, 0.47f, 0.69f, 0.40f);
colors[ImGuiCol_FrameBgActive] = ImVec4(0.42f, 0.41f, 0.64f, 0.69f);
colors[ImGuiCol_TitleBg] = ImVec4(0.27f, 0.27f, 0.54f, 0.83f);
colors[ImGuiCol_TitleBgActive] = ImVec4(0.32f, 0.32f, 0.63f, 0.87f);
colors[ImGuiCol_TitleBgCollapsed] = ImVec4(0.40f, 0.40f, 0.80f, 0.20f);
colors[ImGuiCol_MenuBarBg] = ImVec4(0.40f, 0.40f, 0.55f, 0.80f);
colors[ImGuiCol_ScrollbarBg] = ImVec4(0.20f, 0.25f, 0.30f, 0.60f);
colors[ImGuiCol_ScrollbarGrab] = ImVec4(0.40f, 0.40f, 0.80f, 0.30f);
colors[ImGuiCol_ScrollbarGrabHovered] = ImVec4(0.40f, 0.40f, 0.80f, 0.40f);
colors[ImGuiCol_ScrollbarGrabActive] = ImVec4(0.41f, 0.39f, 0.80f, 0.60f);
colors[ImGuiCol_CheckMark] = ImVec4(0.90f, 0.90f, 0.90f, 0.50f);
colors[ImGuiCol_SliderGrab] = ImVec4(1.00f, 1.00f, 1.00f, 0.30f);
colors[ImGuiCol_SliderGrabActive] = ImVec4(0.41f, 0.39f, 0.80f, 0.60f);
colors[ImGuiCol_Button] = ImVec4(0.35f, 0.40f, 0.61f, 0.62f);
colors[ImGuiCol_ButtonHovered] = ImVec4(0.40f, 0.48f, 0.71f, 0.79f);
colors[ImGuiCol_ButtonActive] = ImVec4(0.46f, 0.54f, 0.80f, 1.00f);
colors[ImGuiCol_Header] = ImVec4(0.40f, 0.40f, 0.90f, 0.45f);
colors[ImGuiCol_HeaderHovered] = ImVec4(0.45f, 0.45f, 0.90f, 0.80f);
colors[ImGuiCol_HeaderActive] = ImVec4(0.53f, 0.53f, 0.87f, 0.80f);
colors[ImGuiCol_Separator] = ImVec4(0.50f, 0.50f, 0.50f, 1.00f);
colors[ImGuiCol_SeparatorHovered] = ImVec4(0.60f, 0.60f, 0.70f, 1.00f);
colors[ImGuiCol_SeparatorActive] = ImVec4(0.70f, 0.70f, 0.90f, 1.00f);
colors[ImGuiCol_ResizeGrip] = ImVec4(1.00f, 1.00f, 1.00f, 0.16f);
colors[ImGuiCol_ResizeGripHovered] = ImVec4(0.78f, 0.82f, 1.00f, 0.60f);
colors[ImGuiCol_ResizeGripActive] = ImVec4(0.78f, 0.82f, 1.00f, 0.90f);
colors[ImGuiCol_PlotLines] = ImVec4(1.00f, 1.00f, 1.00f, 1.00f);
colors[ImGuiCol_PlotLinesHovered] = ImVec4(0.90f, 0.70f, 0.00f, 1.00f);
colors[ImGuiCol_PlotHistogram] = ImVec4(0.90f, 0.70f, 0.00f, 1.00f);
colors[ImGuiCol_PlotHistogramHovered] = ImVec4(1.00f, 0.60f, 0.00f, 1.00f);
colors[ImGuiCol_TextSelectedBg] = ImVec4(0.00f, 0.00f, 1.00f, 0.35f);
colors[ImGuiCol_ModalWindowDarkening] = ImVec4(0.20f, 0.20f, 0.20f, 0.35f);
colors[ImGuiCol_DragDropTarget] = ImVec4(1.00f, 1.00f, 0.00f, 0.90f);
colors[ImGuiCol_NavHighlight] = colors[ImGuiCol_HeaderHovered];
colors[ImGuiCol_NavWindowingHighlight] = ImVec4(1.00f, 1.00f, 1.00f, 0.70f);
}
// Those light colors are better suited with a thicker font than the default one + FrameBorder
void ImGui::StyleColorsLight(ImGuiStyle *dst) {
ImGuiStyle *style = dst ? dst : &ImGui::GetStyle();
ImVec4 *colors = style->Colors;
colors[ImGuiCol_Text] = ImVec4(0.00f, 0.00f, 0.00f, 1.00f);
colors[ImGuiCol_TextDisabled] = ImVec4(0.60f, 0.60f, 0.60f, 1.00f);
colors[ImGuiCol_WindowBg] = ImVec4(0.94f, 0.94f, 0.94f, 1.00f);
colors[ImGuiCol_ChildBg] = ImVec4(0.00f, 0.00f, 0.00f, 0.00f);
colors[ImGuiCol_PopupBg] = ImVec4(1.00f, 1.00f, 1.00f, 0.98f);
colors[ImGuiCol_Border] = ImVec4(0.00f, 0.00f, 0.00f, 0.30f);
colors[ImGuiCol_BorderShadow] = ImVec4(0.00f, 0.00f, 0.00f, 0.00f);
colors[ImGuiCol_FrameBg] = ImVec4(1.00f, 1.00f, 1.00f, 1.00f);
colors[ImGuiCol_FrameBgHovered] = ImVec4(0.26f, 0.59f, 0.98f, 0.40f);
colors[ImGuiCol_FrameBgActive] = ImVec4(0.26f, 0.59f, 0.98f, 0.67f);
colors[ImGuiCol_TitleBg] = ImVec4(0.96f, 0.96f, 0.96f, 1.00f);
colors[ImGuiCol_TitleBgActive] = ImVec4(0.82f, 0.82f, 0.82f, 1.00f);
colors[ImGuiCol_TitleBgCollapsed] = ImVec4(1.00f, 1.00f, 1.00f, 0.51f);
colors[ImGuiCol_MenuBarBg] = ImVec4(0.86f, 0.86f, 0.86f, 1.00f);
colors[ImGuiCol_ScrollbarBg] = ImVec4(0.98f, 0.98f, 0.98f, 0.53f);
colors[ImGuiCol_ScrollbarGrab] = ImVec4(0.69f, 0.69f, 0.69f, 0.80f);
colors[ImGuiCol_ScrollbarGrabHovered] = ImVec4(0.49f, 0.49f, 0.49f, 0.80f);
colors[ImGuiCol_ScrollbarGrabActive] = ImVec4(0.49f, 0.49f, 0.49f, 1.00f);
colors[ImGuiCol_CheckMark] = ImVec4(0.26f, 0.59f, 0.98f, 1.00f);
colors[ImGuiCol_SliderGrab] = ImVec4(0.26f, 0.59f, 0.98f, 0.78f);
colors[ImGuiCol_SliderGrabActive] = ImVec4(0.46f, 0.54f, 0.80f, 0.60f);
colors[ImGuiCol_Button] = ImVec4(0.26f, 0.59f, 0.98f, 0.40f);
colors[ImGuiCol_ButtonHovered] = ImVec4(0.26f, 0.59f, 0.98f, 1.00f);
colors[ImGuiCol_ButtonActive] = ImVec4(0.06f, 0.53f, 0.98f, 1.00f);
colors[ImGuiCol_Header] = ImVec4(0.26f, 0.59f, 0.98f, 0.31f);
colors[ImGuiCol_HeaderHovered] = ImVec4(0.26f, 0.59f, 0.98f, 0.80f);
colors[ImGuiCol_HeaderActive] = ImVec4(0.26f, 0.59f, 0.98f, 1.00f);
colors[ImGuiCol_Separator] = ImVec4(0.39f, 0.39f, 0.39f, 1.00f);
colors[ImGuiCol_SeparatorHovered] = ImVec4(0.14f, 0.44f, 0.80f, 0.78f);
colors[ImGuiCol_SeparatorActive] = ImVec4(0.14f, 0.44f, 0.80f, 1.00f);
colors[ImGuiCol_ResizeGrip] = ImVec4(0.80f, 0.80f, 0.80f, 0.56f);
colors[ImGuiCol_ResizeGripHovered] = ImVec4(0.26f, 0.59f, 0.98f, 0.67f);
colors[ImGuiCol_ResizeGripActive] = ImVec4(0.26f, 0.59f, 0.98f, 0.95f);
colors[ImGuiCol_PlotLines] = ImVec4(0.39f, 0.39f, 0.39f, 1.00f);
colors[ImGuiCol_PlotLinesHovered] = ImVec4(1.00f, 0.43f, 0.35f, 1.00f);
colors[ImGuiCol_PlotHistogram] = ImVec4(0.90f, 0.70f, 0.00f, 1.00f);
colors[ImGuiCol_PlotHistogramHovered] = ImVec4(1.00f, 0.45f, 0.00f, 1.00f);
colors[ImGuiCol_TextSelectedBg] = ImVec4(0.26f, 0.59f, 0.98f, 0.35f);
colors[ImGuiCol_ModalWindowDarkening] = ImVec4(0.20f, 0.20f, 0.20f, 0.35f);
colors[ImGuiCol_DragDropTarget] = ImVec4(0.26f, 0.59f, 0.98f, 0.95f);
colors[ImGuiCol_NavHighlight] = colors[ImGuiCol_HeaderHovered];
colors[ImGuiCol_NavWindowingHighlight] = ImVec4(0.70f, 0.70f, 0.70f, 0.70f);
}
//-----------------------------------------------------------------------------
// ImDrawListData
//-----------------------------------------------------------------------------
ImDrawListSharedData::ImDrawListSharedData() {
Font = NULL;
FontSize = 0.0f;
CurveTessellationTol = 0.0f;
ClipRectFullscreen = ImVec4(-8192.0f, -8192.0f, +8192.0f, +8192.0f);
// Const data
for (int i = 0; i < IM_ARRAYSIZE(CircleVtx12); i++) {
const float a = ((float) i * 2 * IM_PI) / (float) IM_ARRAYSIZE(CircleVtx12);
CircleVtx12[i] = ImVec2(ImCos(a), ImSin(a));
}
}
//-----------------------------------------------------------------------------
// ImDrawList
//-----------------------------------------------------------------------------
void ImDrawList::Clear() {
CmdBuffer.resize(0);
IdxBuffer.resize(0);
VtxBuffer.resize(0);
Flags = ImDrawListFlags_AntiAliasedLines | ImDrawListFlags_AntiAliasedFill;
_VtxCurrentIdx = 0;
_VtxWritePtr = NULL;
_IdxWritePtr = NULL;
_ClipRectStack.resize(0);
_TextureIdStack.resize(0);
_Path.resize(0);
_ChannelsCurrent = 0;
_ChannelsCount = 1;
// NB: Do not clear channels so our allocations are re-used after the first frame.
}
void ImDrawList::ClearFreeMemory() {
CmdBuffer.clear();
IdxBuffer.clear();
VtxBuffer.clear();
_VtxCurrentIdx = 0;
_VtxWritePtr = NULL;
_IdxWritePtr = NULL;
_ClipRectStack.clear();
_TextureIdStack.clear();
_Path.clear();
_ChannelsCurrent = 0;
_ChannelsCount = 1;
for (int i = 0; i < _Channels.Size; i++) {
if (i == 0)
memset(&_Channels[0], 0,
sizeof(_Channels[0])); // channel 0 is a copy of CmdBuffer/IdxBuffer, don't destruct again
_Channels[i].CmdBuffer.clear();
_Channels[i].IdxBuffer.clear();
}
_Channels.clear();
}
ImDrawList *ImDrawList::CloneOutput() const {
ImDrawList *dst = IM_NEW(ImDrawList(NULL));
dst->CmdBuffer = CmdBuffer;
dst->IdxBuffer = IdxBuffer;
dst->VtxBuffer = VtxBuffer;
dst->Flags = Flags;
return dst;
}
// Using macros because C++ is a terrible language, we want guaranteed inline, no code in header, and no overhead in Debug builds
#define GetCurrentClipRect() (_ClipRectStack.Size ? _ClipRectStack.Data[_ClipRectStack.Size-1] : _Data->ClipRectFullscreen)
#define GetCurrentTextureId() (_TextureIdStack.Size ? _TextureIdStack.Data[_TextureIdStack.Size-1] : NULL)
void ImDrawList::AddDrawCmd() {
ImDrawCmd draw_cmd;
draw_cmd.ClipRect = GetCurrentClipRect();
draw_cmd.TextureId = GetCurrentTextureId();
IM_ASSERT(draw_cmd.ClipRect.x <= draw_cmd.ClipRect.z && draw_cmd.ClipRect.y <= draw_cmd.ClipRect.w);
CmdBuffer.push_back(draw_cmd);
}
void ImDrawList::AddCallback(ImDrawCallback callback, void *callback_data) {
ImDrawCmd *current_cmd = CmdBuffer.Size ? &CmdBuffer.back() : NULL;
if (!current_cmd || current_cmd->ElemCount != 0 || current_cmd->UserCallback != NULL) {
AddDrawCmd();
current_cmd = &CmdBuffer.back();
}
current_cmd->UserCallback = callback;
current_cmd->UserCallbackData = callback_data;
AddDrawCmd(); // Force a new command after us (see comment below)
}
// Our scheme may appears a bit unusual, basically we want the most-common calls AddLine AddRect etc. to not have to perform any check so we always have a command ready in the stack.
// The cost of figuring out if a new command has to be added or if we can merge is paid in those Update** functions only.
void ImDrawList::UpdateClipRect() {
// If current command is used with different settings we need to add a new command
const ImVec4 curr_clip_rect = GetCurrentClipRect();
ImDrawCmd *curr_cmd = CmdBuffer.Size > 0 ? &CmdBuffer.Data[CmdBuffer.Size - 1] : NULL;
if (!curr_cmd || (curr_cmd->ElemCount != 0 && memcmp(&curr_cmd->ClipRect, &curr_clip_rect, sizeof(ImVec4)) != 0) ||
curr_cmd->UserCallback != NULL) {
AddDrawCmd();
return;
}
// Try to merge with previous command if it matches, else use current command
ImDrawCmd *prev_cmd = CmdBuffer.Size > 1 ? curr_cmd - 1 : NULL;
if (curr_cmd->ElemCount == 0 && prev_cmd && memcmp(&prev_cmd->ClipRect, &curr_clip_rect, sizeof(ImVec4)) == 0 &&
prev_cmd->TextureId == GetCurrentTextureId() && prev_cmd->UserCallback == NULL)
CmdBuffer.pop_back();
else
curr_cmd->ClipRect = curr_clip_rect;
}
void ImDrawList::UpdateTextureID() {
// If current command is used with different settings we need to add a new command
const ImTextureID curr_texture_id = GetCurrentTextureId();
ImDrawCmd *curr_cmd = CmdBuffer.Size ? &CmdBuffer.back() : NULL;
if (!curr_cmd || (curr_cmd->ElemCount != 0 && curr_cmd->TextureId != curr_texture_id) ||
curr_cmd->UserCallback != NULL) {
AddDrawCmd();
return;
}
// Try to merge with previous command if it matches, else use current command
ImDrawCmd *prev_cmd = CmdBuffer.Size > 1 ? curr_cmd - 1 : NULL;
if (curr_cmd->ElemCount == 0 && prev_cmd && prev_cmd->TextureId == curr_texture_id &&
memcmp(&prev_cmd->ClipRect, &GetCurrentClipRect(), sizeof(ImVec4)) == 0 && prev_cmd->UserCallback == NULL)
CmdBuffer.pop_back();
else
curr_cmd->TextureId = curr_texture_id;
}
#undef GetCurrentClipRect
#undef GetCurrentTextureId
// Render-level scissoring. This is passed down to your render function but not used for CPU-side coarse clipping. Prefer using higher-level ImGui::PushClipRect() to affect logic (hit-testing and widget culling)
void ImDrawList::PushClipRect(ImVec2 cr_min, ImVec2 cr_max, bool intersect_with_current_clip_rect) {
ImVec4 cr(cr_min.x, cr_min.y, cr_max.x, cr_max.y);
if (intersect_with_current_clip_rect && _ClipRectStack.Size) {
ImVec4 current = _ClipRectStack.Data[_ClipRectStack.Size - 1];
if (cr.x < current.x) cr.x = current.x;
if (cr.y < current.y) cr.y = current.y;
if (cr.z > current.z) cr.z = current.z;
if (cr.w > current.w) cr.w = current.w;
}
cr.z = ImMax(cr.x, cr.z);
cr.w = ImMax(cr.y, cr.w);
_ClipRectStack.push_back(cr);
UpdateClipRect();
}
void ImDrawList::PushClipRectFullScreen() {
PushClipRect(ImVec2(_Data->ClipRectFullscreen.x, _Data->ClipRectFullscreen.y),
ImVec2(_Data->ClipRectFullscreen.z, _Data->ClipRectFullscreen.w));
}
void ImDrawList::PopClipRect() {
IM_ASSERT(_ClipRectStack.Size > 0);
_ClipRectStack.pop_back();
UpdateClipRect();
}
void ImDrawList::PushTextureID(ImTextureID texture_id) {
_TextureIdStack.push_back(texture_id);
UpdateTextureID();
}
void ImDrawList::PopTextureID() {
IM_ASSERT(_TextureIdStack.Size > 0);
_TextureIdStack.pop_back();
UpdateTextureID();
}
void ImDrawList::ChannelsSplit(int channels_count) {
IM_ASSERT(_ChannelsCurrent == 0 && _ChannelsCount == 1);
int old_channels_count = _Channels.Size;
if (old_channels_count < channels_count)
_Channels.resize(channels_count);
_ChannelsCount = channels_count;
// _Channels[] (24/32 bytes each) hold storage that we'll swap with this->_CmdBuffer/_IdxBuffer
// The content of _Channels[0] at this point doesn't matter. We clear it to make state tidy in a debugger but we don't strictly need to.
// When we switch to the next channel, we'll copy _CmdBuffer/_IdxBuffer into _Channels[0] and then _Channels[1] into _CmdBuffer/_IdxBuffer
memset(&_Channels[0], 0, sizeof(ImDrawChannel));
for (int i = 1; i < channels_count; i++) {
if (i >= old_channels_count) {
IM_PLACEMENT_NEW(&_Channels[i]) ImDrawChannel();
} else {
_Channels[i].CmdBuffer.resize(0);
_Channels[i].IdxBuffer.resize(0);
}
if (_Channels[i].CmdBuffer.Size == 0) {
ImDrawCmd draw_cmd;
draw_cmd.ClipRect = _ClipRectStack.back();
draw_cmd.TextureId = _TextureIdStack.back();
_Channels[i].CmdBuffer.push_back(draw_cmd);
}
}
}
void ImDrawList::ChannelsMerge() {
// Note that we never use or rely on channels.Size because it is merely a buffer that we never shrink back to 0 to keep all sub-buffers ready for use.
if (_ChannelsCount <= 1)
return;
ChannelsSetCurrent(0);
if (CmdBuffer.Size && CmdBuffer.back().ElemCount == 0)
CmdBuffer.pop_back();
int new_cmd_buffer_count = 0, new_idx_buffer_count = 0;
for (int i = 1; i < _ChannelsCount; i++) {
ImDrawChannel &ch = _Channels[i];
if (ch.CmdBuffer.Size && ch.CmdBuffer.back().ElemCount == 0)
ch.CmdBuffer.pop_back();
new_cmd_buffer_count += ch.CmdBuffer.Size;
new_idx_buffer_count += ch.IdxBuffer.Size;
}
CmdBuffer.resize(CmdBuffer.Size + new_cmd_buffer_count);
IdxBuffer.resize(IdxBuffer.Size + new_idx_buffer_count);
ImDrawCmd *cmd_write = CmdBuffer.Data + CmdBuffer.Size - new_cmd_buffer_count;
_IdxWritePtr = IdxBuffer.Data + IdxBuffer.Size - new_idx_buffer_count;
for (int i = 1; i < _ChannelsCount; i++) {
ImDrawChannel &ch = _Channels[i];
if (int sz = ch.CmdBuffer.Size) {
memcpy(cmd_write, ch.CmdBuffer.Data, sz * sizeof(ImDrawCmd));
cmd_write += sz;
}
if (int sz = ch.IdxBuffer.Size) {
memcpy(_IdxWritePtr, ch.IdxBuffer.Data, sz * sizeof(ImDrawIdx));
_IdxWritePtr += sz;
}
}
UpdateClipRect(); // We call this instead of AddDrawCmd(), so that empty channels won't produce an extra draw call.
_ChannelsCount = 1;
}
void ImDrawList::ChannelsSetCurrent(int idx) {
IM_ASSERT(idx < _ChannelsCount);
if (_ChannelsCurrent == idx) return;
memcpy(&_Channels.Data[_ChannelsCurrent].CmdBuffer, &CmdBuffer, sizeof(CmdBuffer)); // copy 12 bytes, four times
memcpy(&_Channels.Data[_ChannelsCurrent].IdxBuffer, &IdxBuffer, sizeof(IdxBuffer));
_ChannelsCurrent = idx;
memcpy(&CmdBuffer, &_Channels.Data[_ChannelsCurrent].CmdBuffer, sizeof(CmdBuffer));
memcpy(&IdxBuffer, &_Channels.Data[_ChannelsCurrent].IdxBuffer, sizeof(IdxBuffer));
_IdxWritePtr = IdxBuffer.Data + IdxBuffer.Size;
}
// NB: this can be called with negative count for removing primitives (as long as the result does not underflow)
void ImDrawList::PrimReserve(int idx_count, int vtx_count) {
ImDrawCmd &draw_cmd = CmdBuffer.Data[CmdBuffer.Size - 1];
draw_cmd.ElemCount += idx_count;
int vtx_buffer_old_size = VtxBuffer.Size;
VtxBuffer.resize(vtx_buffer_old_size + vtx_count);
_VtxWritePtr = VtxBuffer.Data + vtx_buffer_old_size;
int idx_buffer_old_size = IdxBuffer.Size;
IdxBuffer.resize(idx_buffer_old_size + idx_count);
_IdxWritePtr = IdxBuffer.Data + idx_buffer_old_size;
}
// Fully unrolled with inline call to keep our debug builds decently fast.
void ImDrawList::PrimRect(const ImVec2 &a, const ImVec2 &c, ImU32 col) {
ImVec2 b(c.x, a.y), d(a.x, c.y), uv(_Data->TexUvWhitePixel);
ImDrawIdx idx = (ImDrawIdx) _VtxCurrentIdx;
_IdxWritePtr[0] = idx;
_IdxWritePtr[1] = (ImDrawIdx) (idx + 1);
_IdxWritePtr[2] = (ImDrawIdx) (idx + 2);
_IdxWritePtr[3] = idx;
_IdxWritePtr[4] = (ImDrawIdx) (idx + 2);
_IdxWritePtr[5] = (ImDrawIdx) (idx + 3);
_VtxWritePtr[0].pos = a;
_VtxWritePtr[0].uv = uv;
_VtxWritePtr[0].col = col;
_VtxWritePtr[1].pos = b;
_VtxWritePtr[1].uv = uv;
_VtxWritePtr[1].col = col;
_VtxWritePtr[2].pos = c;
_VtxWritePtr[2].uv = uv;
_VtxWritePtr[2].col = col;
_VtxWritePtr[3].pos = d;
_VtxWritePtr[3].uv = uv;
_VtxWritePtr[3].col = col;
_VtxWritePtr += 4;
_VtxCurrentIdx += 4;
_IdxWritePtr += 6;
}
void ImDrawList::PrimRectUV(const ImVec2 &a, const ImVec2 &c, const ImVec2 &uv_a, const ImVec2 &uv_c, ImU32 col) {
ImVec2 b(c.x, a.y), d(a.x, c.y), uv_b(uv_c.x, uv_a.y), uv_d(uv_a.x, uv_c.y);
ImDrawIdx idx = (ImDrawIdx) _VtxCurrentIdx;
_IdxWritePtr[0] = idx;
_IdxWritePtr[1] = (ImDrawIdx) (idx + 1);
_IdxWritePtr[2] = (ImDrawIdx) (idx + 2);
_IdxWritePtr[3] = idx;
_IdxWritePtr[4] = (ImDrawIdx) (idx + 2);
_IdxWritePtr[5] = (ImDrawIdx) (idx + 3);
_VtxWritePtr[0].pos = a;
_VtxWritePtr[0].uv = uv_a;
_VtxWritePtr[0].col = col;
_VtxWritePtr[1].pos = b;
_VtxWritePtr[1].uv = uv_b;
_VtxWritePtr[1].col = col;
_VtxWritePtr[2].pos = c;
_VtxWritePtr[2].uv = uv_c;
_VtxWritePtr[2].col = col;
_VtxWritePtr[3].pos = d;
_VtxWritePtr[3].uv = uv_d;
_VtxWritePtr[3].col = col;
_VtxWritePtr += 4;
_VtxCurrentIdx += 4;
_IdxWritePtr += 6;
}
void ImDrawList::PrimQuadUV(const ImVec2 &a, const ImVec2 &b, const ImVec2 &c, const ImVec2 &d, const ImVec2 &uv_a,
const ImVec2 &uv_b, const ImVec2 &uv_c, const ImVec2 &uv_d, ImU32 col) {
ImDrawIdx idx = (ImDrawIdx) _VtxCurrentIdx;
_IdxWritePtr[0] = idx;
_IdxWritePtr[1] = (ImDrawIdx) (idx + 1);
_IdxWritePtr[2] = (ImDrawIdx) (idx + 2);
_IdxWritePtr[3] = idx;
_IdxWritePtr[4] = (ImDrawIdx) (idx + 2);
_IdxWritePtr[5] = (ImDrawIdx) (idx + 3);
_VtxWritePtr[0].pos = a;
_VtxWritePtr[0].uv = uv_a;
_VtxWritePtr[0].col = col;
_VtxWritePtr[1].pos = b;
_VtxWritePtr[1].uv = uv_b;
_VtxWritePtr[1].col = col;
_VtxWritePtr[2].pos = c;
_VtxWritePtr[2].uv = uv_c;
_VtxWritePtr[2].col = col;
_VtxWritePtr[3].pos = d;
_VtxWritePtr[3].uv = uv_d;
_VtxWritePtr[3].col = col;
_VtxWritePtr += 4;
_VtxCurrentIdx += 4;
_IdxWritePtr += 6;
}
// TODO: Thickness anti-aliased lines cap are missing their AA fringe.
void ImDrawList::AddPolyline(const ImVec2 *points, const int points_count, ImU32 col, bool closed, float thickness) {
if (points_count < 2)
return;
const ImVec2 uv = _Data->TexUvWhitePixel;
int count = points_count;
if (!closed)
count = points_count - 1;
const bool thick_line = thickness > 1.0f;
if (Flags & ImDrawListFlags_AntiAliasedLines) {
// Anti-aliased stroke
const float AA_SIZE = 1.0f;
const ImU32 col_trans = col & ~IM_COL32_A_MASK;
const int idx_count = thick_line ? count * 18 : count * 12;
const int vtx_count = thick_line ? points_count * 4 : points_count * 3;
PrimReserve(idx_count, vtx_count);
// Temporary buffer
ImVec2 *temp_normals = (ImVec2 *) alloca(points_count * (thick_line ? 5 : 3) * sizeof(ImVec2));
ImVec2 *temp_points = temp_normals + points_count;
for (int i1 = 0; i1 < count; i1++) {
const int i2 = (i1 + 1) == points_count ? 0 : i1 + 1;
ImVec2 diff = points[i2] - points[i1];
diff *= ImInvLength(diff, 1.0f);
temp_normals[i1].x = diff.y;
temp_normals[i1].y = -diff.x;
}
if (!closed)
temp_normals[points_count - 1] = temp_normals[points_count - 2];
if (!thick_line) {
if (!closed) {
temp_points[0] = points[0] + temp_normals[0] * AA_SIZE;
temp_points[1] = points[0] - temp_normals[0] * AA_SIZE;
temp_points[(points_count - 1) * 2 + 0] =
points[points_count - 1] + temp_normals[points_count - 1] * AA_SIZE;
temp_points[(points_count - 1) * 2 + 1] =
points[points_count - 1] - temp_normals[points_count - 1] * AA_SIZE;
}
// FIXME-OPT: Merge the different loops, possibly remove the temporary buffer.
unsigned int idx1 = _VtxCurrentIdx;
for (int i1 = 0; i1 < count; i1++) {
const int i2 = (i1 + 1) == points_count ? 0 : i1 + 1;
unsigned int idx2 = (i1 + 1) == points_count ? _VtxCurrentIdx : idx1 + 3;
// Average normals
ImVec2 dm = (temp_normals[i1] + temp_normals[i2]) * 0.5f;
float dmr2 = dm.x * dm.x + dm.y * dm.y;
if (dmr2 > 0.000001f) {
float scale = 1.0f / dmr2;
if (scale > 100.0f) scale = 100.0f;
dm *= scale;
}
dm *= AA_SIZE;
temp_points[i2 * 2 + 0] = points[i2] + dm;
temp_points[i2 * 2 + 1] = points[i2] - dm;
// Add indexes
_IdxWritePtr[0] = (ImDrawIdx) (idx2 + 0);
_IdxWritePtr[1] = (ImDrawIdx) (idx1 + 0);
_IdxWritePtr[2] = (ImDrawIdx) (idx1 + 2);
_IdxWritePtr[3] = (ImDrawIdx) (idx1 + 2);
_IdxWritePtr[4] = (ImDrawIdx) (idx2 + 2);
_IdxWritePtr[5] = (ImDrawIdx) (idx2 + 0);
_IdxWritePtr[6] = (ImDrawIdx) (idx2 + 1);
_IdxWritePtr[7] = (ImDrawIdx) (idx1 + 1);
_IdxWritePtr[8] = (ImDrawIdx) (idx1 + 0);
_IdxWritePtr[9] = (ImDrawIdx) (idx1 + 0);
_IdxWritePtr[10] = (ImDrawIdx) (idx2 + 0);
_IdxWritePtr[11] = (ImDrawIdx) (idx2 + 1);
_IdxWritePtr += 12;
idx1 = idx2;
}
// Add vertexes
for (int i = 0; i < points_count; i++) {
_VtxWritePtr[0].pos = points[i];
_VtxWritePtr[0].uv = uv;
_VtxWritePtr[0].col = col;
_VtxWritePtr[1].pos = temp_points[i * 2 + 0];
_VtxWritePtr[1].uv = uv;
_VtxWritePtr[1].col = col_trans;
_VtxWritePtr[2].pos = temp_points[i * 2 + 1];
_VtxWritePtr[2].uv = uv;
_VtxWritePtr[2].col = col_trans;
_VtxWritePtr += 3;
}
} else {
const float half_inner_thickness = (thickness - AA_SIZE) * 0.5f;
if (!closed) {
temp_points[0] = points[0] + temp_normals[0] * (half_inner_thickness + AA_SIZE);
temp_points[1] = points[0] + temp_normals[0] * (half_inner_thickness);
temp_points[2] = points[0] - temp_normals[0] * (half_inner_thickness);
temp_points[3] = points[0] - temp_normals[0] * (half_inner_thickness + AA_SIZE);
temp_points[(points_count - 1) * 4 + 0] =
points[points_count - 1] + temp_normals[points_count - 1] * (half_inner_thickness + AA_SIZE);
temp_points[(points_count - 1) * 4 + 1] =
points[points_count - 1] + temp_normals[points_count - 1] * (half_inner_thickness);
temp_points[(points_count - 1) * 4 + 2] =
points[points_count - 1] - temp_normals[points_count - 1] * (half_inner_thickness);
temp_points[(points_count - 1) * 4 + 3] =
points[points_count - 1] - temp_normals[points_count - 1] * (half_inner_thickness + AA_SIZE);
}
// FIXME-OPT: Merge the different loops, possibly remove the temporary buffer.
unsigned int idx1 = _VtxCurrentIdx;
for (int i1 = 0; i1 < count; i1++) {
const int i2 = (i1 + 1) == points_count ? 0 : i1 + 1;
unsigned int idx2 = (i1 + 1) == points_count ? _VtxCurrentIdx : idx1 + 4;
// Average normals
ImVec2 dm = (temp_normals[i1] + temp_normals[i2]) * 0.5f;
float dmr2 = dm.x * dm.x + dm.y * dm.y;
if (dmr2 > 0.000001f) {
float scale = 1.0f / dmr2;
if (scale > 100.0f) scale = 100.0f;
dm *= scale;
}
ImVec2 dm_out = dm * (half_inner_thickness + AA_SIZE);
ImVec2 dm_in = dm * half_inner_thickness;
temp_points[i2 * 4 + 0] = points[i2] + dm_out;
temp_points[i2 * 4 + 1] = points[i2] + dm_in;
temp_points[i2 * 4 + 2] = points[i2] - dm_in;
temp_points[i2 * 4 + 3] = points[i2] - dm_out;
// Add indexes
_IdxWritePtr[0] = (ImDrawIdx) (idx2 + 1);
_IdxWritePtr[1] = (ImDrawIdx) (idx1 + 1);
_IdxWritePtr[2] = (ImDrawIdx) (idx1 + 2);
_IdxWritePtr[3] = (ImDrawIdx) (idx1 + 2);
_IdxWritePtr[4] = (ImDrawIdx) (idx2 + 2);
_IdxWritePtr[5] = (ImDrawIdx) (idx2 + 1);
_IdxWritePtr[6] = (ImDrawIdx) (idx2 + 1);
_IdxWritePtr[7] = (ImDrawIdx) (idx1 + 1);
_IdxWritePtr[8] = (ImDrawIdx) (idx1 + 0);
_IdxWritePtr[9] = (ImDrawIdx) (idx1 + 0);
_IdxWritePtr[10] = (ImDrawIdx) (idx2 + 0);
_IdxWritePtr[11] = (ImDrawIdx) (idx2 + 1);
_IdxWritePtr[12] = (ImDrawIdx) (idx2 + 2);
_IdxWritePtr[13] = (ImDrawIdx) (idx1 + 2);
_IdxWritePtr[14] = (ImDrawIdx) (idx1 + 3);
_IdxWritePtr[15] = (ImDrawIdx) (idx1 + 3);
_IdxWritePtr[16] = (ImDrawIdx) (idx2 + 3);
_IdxWritePtr[17] = (ImDrawIdx) (idx2 + 2);
_IdxWritePtr += 18;
idx1 = idx2;
}
// Add vertexes
for (int i = 0; i < points_count; i++) {
_VtxWritePtr[0].pos = temp_points[i * 4 + 0];
_VtxWritePtr[0].uv = uv;
_VtxWritePtr[0].col = col_trans;
_VtxWritePtr[1].pos = temp_points[i * 4 + 1];
_VtxWritePtr[1].uv = uv;
_VtxWritePtr[1].col = col;
_VtxWritePtr[2].pos = temp_points[i * 4 + 2];
_VtxWritePtr[2].uv = uv;
_VtxWritePtr[2].col = col;
_VtxWritePtr[3].pos = temp_points[i * 4 + 3];
_VtxWritePtr[3].uv = uv;
_VtxWritePtr[3].col = col_trans;
_VtxWritePtr += 4;
}
}
_VtxCurrentIdx += (ImDrawIdx) vtx_count;
} else {
// Non Anti-aliased Stroke
const int idx_count = count * 6;
const int vtx_count = count * 4; // FIXME-OPT: Not sharing edges
PrimReserve(idx_count, vtx_count);
for (int i1 = 0; i1 < count; i1++) {
const int i2 = (i1 + 1) == points_count ? 0 : i1 + 1;
const ImVec2 &p1 = points[i1];
const ImVec2 &p2 = points[i2];
ImVec2 diff = p2 - p1;
diff *= ImInvLength(diff, 1.0f);
const float dx = diff.x * (thickness * 0.5f);
const float dy = diff.y * (thickness * 0.5f);
_VtxWritePtr[0].pos.x = p1.x + dy;
_VtxWritePtr[0].pos.y = p1.y - dx;
_VtxWritePtr[0].uv = uv;
_VtxWritePtr[0].col = col;
_VtxWritePtr[1].pos.x = p2.x + dy;
_VtxWritePtr[1].pos.y = p2.y - dx;
_VtxWritePtr[1].uv = uv;
_VtxWritePtr[1].col = col;
_VtxWritePtr[2].pos.x = p2.x - dy;
_VtxWritePtr[2].pos.y = p2.y + dx;
_VtxWritePtr[2].uv = uv;
_VtxWritePtr[2].col = col;
_VtxWritePtr[3].pos.x = p1.x - dy;
_VtxWritePtr[3].pos.y = p1.y + dx;
_VtxWritePtr[3].uv = uv;
_VtxWritePtr[3].col = col;
_VtxWritePtr += 4;
_IdxWritePtr[0] = (ImDrawIdx) (_VtxCurrentIdx);
_IdxWritePtr[1] = (ImDrawIdx) (_VtxCurrentIdx + 1);
_IdxWritePtr[2] = (ImDrawIdx) (_VtxCurrentIdx + 2);
_IdxWritePtr[3] = (ImDrawIdx) (_VtxCurrentIdx);
_IdxWritePtr[4] = (ImDrawIdx) (_VtxCurrentIdx + 2);
_IdxWritePtr[5] = (ImDrawIdx) (_VtxCurrentIdx + 3);
_IdxWritePtr += 6;
_VtxCurrentIdx += 4;
}
}
}
void ImDrawList::AddConvexPolyFilled(const ImVec2 *points, const int points_count, ImU32 col) {
const ImVec2 uv = _Data->TexUvWhitePixel;
if (Flags & ImDrawListFlags_AntiAliasedFill) {
// Anti-aliased Fill
const float AA_SIZE = 1.0f;
const ImU32 col_trans = col & ~IM_COL32_A_MASK;
const int idx_count = (points_count - 2) * 3 + points_count * 6;
const int vtx_count = (points_count * 2);
PrimReserve(idx_count, vtx_count);
// Add indexes for fill
unsigned int vtx_inner_idx = _VtxCurrentIdx;
unsigned int vtx_outer_idx = _VtxCurrentIdx + 1;
for (int i = 2; i < points_count; i++) {
_IdxWritePtr[0] = (ImDrawIdx) (vtx_inner_idx);
_IdxWritePtr[1] = (ImDrawIdx) (vtx_inner_idx + ((i - 1) << 1));
_IdxWritePtr[2] = (ImDrawIdx) (vtx_inner_idx + (i << 1));
_IdxWritePtr += 3;
}
// Compute normals
ImVec2 *temp_normals = (ImVec2 *) alloca(points_count * sizeof(ImVec2));
for (int i0 = points_count - 1, i1 = 0; i1 < points_count; i0 = i1++) {
const ImVec2 &p0 = points[i0];
const ImVec2 &p1 = points[i1];
ImVec2 diff = p1 - p0;
diff *= ImInvLength(diff, 1.0f);
temp_normals[i0].x = diff.y;
temp_normals[i0].y = -diff.x;
}
for (int i0 = points_count - 1, i1 = 0; i1 < points_count; i0 = i1++) {
// Average normals
const ImVec2 &n0 = temp_normals[i0];
const ImVec2 &n1 = temp_normals[i1];
ImVec2 dm = (n0 + n1) * 0.5f;
float dmr2 = dm.x * dm.x + dm.y * dm.y;
if (dmr2 > 0.000001f) {
float scale = 1.0f / dmr2;
if (scale > 100.0f) scale = 100.0f;
dm *= scale;
}
dm *= AA_SIZE * 0.5f;
// Add vertices
_VtxWritePtr[0].pos = (points[i1] - dm);
_VtxWritePtr[0].uv = uv;
_VtxWritePtr[0].col = col; // Inner
_VtxWritePtr[1].pos = (points[i1] + dm);
_VtxWritePtr[1].uv = uv;
_VtxWritePtr[1].col = col_trans; // Outer
_VtxWritePtr += 2;
// Add indexes for fringes
_IdxWritePtr[0] = (ImDrawIdx) (vtx_inner_idx + (i1 << 1));
_IdxWritePtr[1] = (ImDrawIdx) (vtx_inner_idx + (i0 << 1));
_IdxWritePtr[2] = (ImDrawIdx) (vtx_outer_idx + (i0 << 1));
_IdxWritePtr[3] = (ImDrawIdx) (vtx_outer_idx + (i0 << 1));
_IdxWritePtr[4] = (ImDrawIdx) (vtx_outer_idx + (i1 << 1));
_IdxWritePtr[5] = (ImDrawIdx) (vtx_inner_idx + (i1 << 1));
_IdxWritePtr += 6;
}
_VtxCurrentIdx += (ImDrawIdx) vtx_count;
} else {
// Non Anti-aliased Fill
const int idx_count = (points_count - 2) * 3;
const int vtx_count = points_count;
PrimReserve(idx_count, vtx_count);
for (int i = 0; i < vtx_count; i++) {
_VtxWritePtr[0].pos = points[i];
_VtxWritePtr[0].uv = uv;
_VtxWritePtr[0].col = col;
_VtxWritePtr++;
}
for (int i = 2; i < points_count; i++) {
_IdxWritePtr[0] = (ImDrawIdx) (_VtxCurrentIdx);
_IdxWritePtr[1] = (ImDrawIdx) (_VtxCurrentIdx + i - 1);
_IdxWritePtr[2] = (ImDrawIdx) (_VtxCurrentIdx + i);
_IdxWritePtr += 3;
}
_VtxCurrentIdx += (ImDrawIdx) vtx_count;
}
}
void ImDrawList::PathArcToFast(const ImVec2 ¢re, float radius, int a_min_of_12, int a_max_of_12) {
if (radius == 0.0f || a_min_of_12 > a_max_of_12) {
_Path.push_back(centre);
return;
}
_Path.reserve(_Path.Size + (a_max_of_12 - a_min_of_12 + 1));
for (int a = a_min_of_12; a <= a_max_of_12; a++) {
const ImVec2 &c = _Data->CircleVtx12[a % IM_ARRAYSIZE(_Data->CircleVtx12)];
_Path.push_back(ImVec2(centre.x + c.x * radius, centre.y + c.y * radius));
}
}
void ImDrawList::PathArcTo(const ImVec2 ¢re, float radius, float a_min, float a_max, int num_segments) {
if (radius == 0.0f) {
_Path.push_back(centre);
return;
}
_Path.reserve(_Path.Size + (num_segments + 1));
for (int i = 0; i <= num_segments; i++) {
const float a = a_min + ((float) i / (float) num_segments) * (a_max - a_min);
_Path.push_back(ImVec2(centre.x + ImCos(a) * radius, centre.y + ImSin(a) * radius));
}
}
static void
PathBezierToCasteljau(ImVector<ImVec2> *path, 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)) {
path->push_back(ImVec2(x4, y4));
} 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;
PathBezierToCasteljau(path, x1, y1, x12, y12, x123, y123, x1234, y1234, tess_tol, level + 1);
PathBezierToCasteljau(path, x1234, y1234, x234, y234, x34, y34, x4, y4, tess_tol, level + 1);
}
}
void ImDrawList::PathBezierCurveTo(const ImVec2 &p2, const ImVec2 &p3, const ImVec2 &p4, int num_segments) {
ImVec2 p1 = _Path.back();
if (num_segments == 0) {
// Auto-tessellated
PathBezierToCasteljau(&_Path, p1.x, p1.y, p2.x, p2.y, p3.x, p3.y, p4.x, p4.y, _Data->CurveTessellationTol, 0);
} else {
float t_step = 1.0f / (float) num_segments;
for (int i_step = 1; i_step <= num_segments; i_step++) {
float t = t_step * i_step;
float u = 1.0f - t;
float w1 = u * u * u;
float w2 = 3 * u * u * t;
float w3 = 3 * u * t * t;
float w4 = t * t * t;
_Path.push_back(ImVec2(w1 * p1.x + w2 * p2.x + w3 * p3.x + w4 * p4.x,
w1 * p1.y + w2 * p2.y + w3 * p3.y + w4 * p4.y));
}
}
}
void ImDrawList::PathRect(const ImVec2 &a, const ImVec2 &b, float rounding, int rounding_corners) {
rounding = ImMin(rounding, ImFabs(b.x - a.x) *
(((rounding_corners & ImDrawCornerFlags_Top) == ImDrawCornerFlags_Top) ||
((rounding_corners & ImDrawCornerFlags_Bot) == ImDrawCornerFlags_Bot) ? 0.5f : 1.0f) -
1.0f);
rounding = ImMin(rounding, ImFabs(b.y - a.y) *
(((rounding_corners & ImDrawCornerFlags_Left) == ImDrawCornerFlags_Left) ||
((rounding_corners & ImDrawCornerFlags_Right) == ImDrawCornerFlags_Right) ? 0.5f
: 1.0f) -
1.0f);
if (rounding <= 0.0f || rounding_corners == 0) {
PathLineTo(a);
PathLineTo(ImVec2(b.x, a.y));
PathLineTo(b);
PathLineTo(ImVec2(a.x, b.y));
} else {
const float rounding_tl = (rounding_corners & ImDrawCornerFlags_TopLeft) ? rounding : 0.0f;
const float rounding_tr = (rounding_corners & ImDrawCornerFlags_TopRight) ? rounding : 0.0f;
const float rounding_br = (rounding_corners & ImDrawCornerFlags_BotRight) ? rounding : 0.0f;
const float rounding_bl = (rounding_corners & ImDrawCornerFlags_BotLeft) ? rounding : 0.0f;
PathArcToFast(ImVec2(a.x + rounding_tl, a.y + rounding_tl), rounding_tl, 6, 9);
PathArcToFast(ImVec2(b.x - rounding_tr, a.y + rounding_tr), rounding_tr, 9, 12);
PathArcToFast(ImVec2(b.x - rounding_br, b.y - rounding_br), rounding_br, 0, 3);
PathArcToFast(ImVec2(a.x + rounding_bl, b.y - rounding_bl), rounding_bl, 3, 6);
}
}
void ImDrawList::AddLine(const ImVec2 &a, const ImVec2 &b, ImU32 col, float thickness) {
if ((col & IM_COL32_A_MASK) == 0)
return;
PathLineTo(a + ImVec2(0.5f, 0.5f));
PathLineTo(b + ImVec2(0.5f, 0.5f));
PathStroke(col, false, thickness);
}
// a: upper-left, b: lower-right. we don't render 1 px sized rectangles properly.
void ImDrawList::AddRect(const ImVec2 &a, const ImVec2 &b, ImU32 col, float rounding, int rounding_corners_flags,
float thickness) {
if ((col & IM_COL32_A_MASK) == 0)
return;
if (Flags & ImDrawListFlags_AntiAliasedLines)
PathRect(a + ImVec2(0.5f, 0.5f), b - ImVec2(0.50f, 0.50f), rounding, rounding_corners_flags);
else
PathRect(a + ImVec2(0.5f, 0.5f), b - ImVec2(0.49f, 0.49f), rounding,
rounding_corners_flags); // Better looking lower-right corner and rounded non-AA shapes.
PathStroke(col, true, thickness);
}
void
ImDrawList::AddRectFilled(const ImVec2 &a, const ImVec2 &b, ImU32 col, float rounding, int rounding_corners_flags) {
if ((col & IM_COL32_A_MASK) == 0)
return;
if (rounding > 0.0f) {
PathRect(a, b, rounding, rounding_corners_flags);
PathFillConvex(col);
} else {
PrimReserve(6, 4);
PrimRect(a, b, col);
}
}
void ImDrawList::AddRectFilledMultiColor(const ImVec2 &a, const ImVec2 &c, ImU32 col_upr_left, ImU32 col_upr_right,
ImU32 col_bot_right, ImU32 col_bot_left) {
if (((col_upr_left | col_upr_right | col_bot_right | col_bot_left) & IM_COL32_A_MASK) == 0)
return;
const ImVec2 uv = _Data->TexUvWhitePixel;
PrimReserve(6, 4);
PrimWriteIdx((ImDrawIdx) (_VtxCurrentIdx));
PrimWriteIdx((ImDrawIdx) (_VtxCurrentIdx + 1));
PrimWriteIdx((ImDrawIdx) (_VtxCurrentIdx + 2));
PrimWriteIdx((ImDrawIdx) (_VtxCurrentIdx));
PrimWriteIdx((ImDrawIdx) (_VtxCurrentIdx + 2));
PrimWriteIdx((ImDrawIdx) (_VtxCurrentIdx + 3));
PrimWriteVtx(a, uv, col_upr_left);
PrimWriteVtx(ImVec2(c.x, a.y), uv, col_upr_right);
PrimWriteVtx(c, uv, col_bot_right);
PrimWriteVtx(ImVec2(a.x, c.y), uv, col_bot_left);
}
void
ImDrawList::AddQuad(const ImVec2 &a, const ImVec2 &b, const ImVec2 &c, const ImVec2 &d, ImU32 col, float thickness) {
if ((col & IM_COL32_A_MASK) == 0)
return;
PathLineTo(a);
PathLineTo(b);
PathLineTo(c);
PathLineTo(d);
PathStroke(col, true, thickness);
}
void ImDrawList::AddQuadFilled(const ImVec2 &a, const ImVec2 &b, const ImVec2 &c, const ImVec2 &d, ImU32 col) {
if ((col & IM_COL32_A_MASK) == 0)
return;
PathLineTo(a);
PathLineTo(b);
PathLineTo(c);
PathLineTo(d);
PathFillConvex(col);
}
void ImDrawList::AddTriangle(const ImVec2 &a, const ImVec2 &b, const ImVec2 &c, ImU32 col, float thickness) {
if ((col & IM_COL32_A_MASK) == 0)
return;
PathLineTo(a);
PathLineTo(b);
PathLineTo(c);
PathStroke(col, true, thickness);
}
void ImDrawList::AddTriangleFilled(const ImVec2 &a, const ImVec2 &b, const ImVec2 &c, ImU32 col) {
if ((col & IM_COL32_A_MASK) == 0)
return;
PathLineTo(a);
PathLineTo(b);
PathLineTo(c);
PathFillConvex(col);
}
void ImDrawList::AddCircle(const ImVec2 ¢re, float radius, ImU32 col, int num_segments, float thickness) {
if ((col & IM_COL32_A_MASK) == 0)
return;
const float a_max = IM_PI * 2.0f * ((float) num_segments - 1.0f) / (float) num_segments;
PathArcTo(centre, radius - 0.5f, 0.0f, a_max, num_segments);
PathStroke(col, true, thickness);
}
void ImDrawList::AddCircleFilled(const ImVec2 ¢re, float radius, ImU32 col, int num_segments) {
if ((col & IM_COL32_A_MASK) == 0)
return;
const float a_max = IM_PI * 2.0f * ((float) num_segments - 1.0f) / (float) num_segments;
PathArcTo(centre, radius, 0.0f, a_max, num_segments);
PathFillConvex(col);
}
void ImDrawList::AddBezierCurve(const ImVec2 &pos0, const ImVec2 &cp0, const ImVec2 &cp1, const ImVec2 &pos1, ImU32 col,
float thickness, int num_segments) {
if ((col & IM_COL32_A_MASK) == 0)
return;
PathLineTo(pos0);
PathBezierCurveTo(cp0, cp1, pos1, num_segments);
PathStroke(col, false, thickness);
}
void ImDrawList::AddText(const ImFont *font, float font_size, const ImVec2 &pos, ImU32 col, const char *text_begin,
const char *text_end, float wrap_width, const ImVec4 *cpu_fine_clip_rect) {
if ((col & IM_COL32_A_MASK) == 0)
return;
if (text_end == NULL)
text_end = text_begin + strlen(text_begin);
if (text_begin == text_end)
return;
// Pull default font/size from the shared ImDrawListSharedData instance
if (font == NULL)
font = _Data->Font;
if (font_size == 0.0f)
font_size = _Data->FontSize;
IM_ASSERT(font->ContainerAtlas->TexID ==
_TextureIdStack.back()); // Use high-level ImGui::PushFont() or low-level ImDrawList::PushTextureId() to change font.
ImVec4 clip_rect = _ClipRectStack.back();
if (cpu_fine_clip_rect) {
clip_rect.x = ImMax(clip_rect.x, cpu_fine_clip_rect->x);
clip_rect.y = ImMax(clip_rect.y, cpu_fine_clip_rect->y);
clip_rect.z = ImMin(clip_rect.z, cpu_fine_clip_rect->z);
clip_rect.w = ImMin(clip_rect.w, cpu_fine_clip_rect->w);
}
font->RenderText(this, font_size, pos, col, clip_rect, text_begin, text_end, wrap_width,
cpu_fine_clip_rect != NULL);
}
void ImDrawList::AddText(const ImVec2 &pos, ImU32 col, const char *text_begin, const char *text_end) {
AddText(NULL, 0.0f, pos, col, text_begin, text_end);
}
void ImDrawList::AddImage(ImTextureID user_texture_id, const ImVec2 &a, const ImVec2 &b, const ImVec2 &uv_a,
const ImVec2 &uv_b, ImU32 col) {
if ((col & IM_COL32_A_MASK) == 0)
return;
const bool push_texture_id = _TextureIdStack.empty() || user_texture_id != _TextureIdStack.back();
if (push_texture_id)
PushTextureID(user_texture_id);
PrimReserve(6, 4);
PrimRectUV(a, b, uv_a, uv_b, col);
if (push_texture_id)
PopTextureID();
}
void ImDrawList::AddImageQuad(ImTextureID user_texture_id, const ImVec2 &a, const ImVec2 &b, const ImVec2 &c,
const ImVec2 &d, const ImVec2 &uv_a, const ImVec2 &uv_b, const ImVec2 &uv_c,
const ImVec2 &uv_d, ImU32 col) {
if ((col & IM_COL32_A_MASK) == 0)
return;
const bool push_texture_id = _TextureIdStack.empty() || user_texture_id != _TextureIdStack.back();
if (push_texture_id)
PushTextureID(user_texture_id);
PrimReserve(6, 4);
PrimQuadUV(a, b, c, d, uv_a, uv_b, uv_c, uv_d, col);
if (push_texture_id)
PopTextureID();
}
void ImDrawList::AddImageRounded(ImTextureID user_texture_id, const ImVec2 &a, const ImVec2 &b, const ImVec2 &uv_a,
const ImVec2 &uv_b, ImU32 col, float rounding, int rounding_corners) {
if ((col & IM_COL32_A_MASK) == 0)
return;
if (rounding <= 0.0f || (rounding_corners & ImDrawCornerFlags_All) == 0) {
AddImage(user_texture_id, a, b, uv_a, uv_b, col);
return;
}
const bool push_texture_id = _TextureIdStack.empty() || user_texture_id != _TextureIdStack.back();
if (push_texture_id)
PushTextureID(user_texture_id);
int vert_start_idx = VtxBuffer.Size;
PathRect(a, b, rounding, rounding_corners);
PathFillConvex(col);
int vert_end_idx = VtxBuffer.Size;
ImGui::ShadeVertsLinearUV(VtxBuffer.Data + vert_start_idx, VtxBuffer.Data + vert_end_idx, a, b, uv_a, uv_b, true);
if (push_texture_id)
PopTextureID();
}
//-----------------------------------------------------------------------------
// ImDrawData
//-----------------------------------------------------------------------------
// For backward compatibility: convert all buffers from indexed to de-indexed, in case you cannot render indexed. Note: this is slow and most likely a waste of resources. Always prefer indexed rendering!
void ImDrawData::DeIndexAllBuffers() {
ImVector<ImDrawVert> new_vtx_buffer;
TotalVtxCount = TotalIdxCount = 0;
for (int i = 0; i < CmdListsCount; i++) {
ImDrawList *cmd_list = CmdLists[i];
if (cmd_list->IdxBuffer.empty())
continue;
new_vtx_buffer.resize(cmd_list->IdxBuffer.Size);
for (int j = 0; j < cmd_list->IdxBuffer.Size; j++)
new_vtx_buffer[j] = cmd_list->VtxBuffer[cmd_list->IdxBuffer[j]];
cmd_list->VtxBuffer.swap(new_vtx_buffer);
cmd_list->IdxBuffer.resize(0);
TotalVtxCount += cmd_list->VtxBuffer.Size;
}
}
// Helper to scale the ClipRect field of each ImDrawCmd. Use if your final output buffer is at a different scale than ImGui expects, or if there is a difference between your window resolution and framebuffer resolution.
void ImDrawData::ScaleClipRects(const ImVec2 &scale) {
for (int i = 0; i < CmdListsCount; i++) {
ImDrawList *cmd_list = CmdLists[i];
for (int cmd_i = 0; cmd_i < cmd_list->CmdBuffer.Size; cmd_i++) {
ImDrawCmd *cmd = &cmd_list->CmdBuffer[cmd_i];
cmd->ClipRect = ImVec4(cmd->ClipRect.x * scale.x, cmd->ClipRect.y * scale.y, cmd->ClipRect.z * scale.x,
cmd->ClipRect.w * scale.y);
}
}
}
//-----------------------------------------------------------------------------
// Shade functions
//-----------------------------------------------------------------------------
// Generic linear color gradient, write to RGB fields, leave A untouched.
void ImGui::ShadeVertsLinearColorGradientKeepAlpha(ImDrawVert *vert_start, ImDrawVert *vert_end, ImVec2 gradient_p0,
ImVec2 gradient_p1, ImU32 col0, ImU32 col1) {
ImVec2 gradient_extent = gradient_p1 - gradient_p0;
float gradient_inv_length2 = 1.0f / ImLengthSqr(gradient_extent);
for (ImDrawVert *vert = vert_start; vert < vert_end; vert++) {
float d = ImDot(vert->pos - gradient_p0, gradient_extent);
float t = ImClamp(d * gradient_inv_length2, 0.0f, 1.0f);
int r = ImLerp((int) (col0 >> IM_COL32_R_SHIFT) & 0xFF, (int) (col1 >> IM_COL32_R_SHIFT) & 0xFF, t);
int g = ImLerp((int) (col0 >> IM_COL32_G_SHIFT) & 0xFF, (int) (col1 >> IM_COL32_G_SHIFT) & 0xFF, t);
int b = ImLerp((int) (col0 >> IM_COL32_B_SHIFT) & 0xFF, (int) (col1 >> IM_COL32_B_SHIFT) & 0xFF, t);
vert->col = (r << IM_COL32_R_SHIFT) | (g << IM_COL32_G_SHIFT) | (b << IM_COL32_B_SHIFT) |
(vert->col & IM_COL32_A_MASK);
}
}
// Scan and shade backward from the end of given vertices. Assume vertices are text only (= vert_start..vert_end going left to right) so we can break as soon as we are out the gradient bounds.
void ImGui::ShadeVertsLinearAlphaGradientForLeftToRightText(ImDrawVert *vert_start, ImDrawVert *vert_end,
float gradient_p0_x, float gradient_p1_x) {
float gradient_extent_x = gradient_p1_x - gradient_p0_x;
float gradient_inv_length2 = 1.0f / (gradient_extent_x * gradient_extent_x);
int full_alpha_count = 0;
for (ImDrawVert *vert = vert_end - 1; vert >= vert_start; vert--) {
float d = (vert->pos.x - gradient_p0_x) * (gradient_extent_x);
float alpha_mul = 1.0f - ImClamp(d * gradient_inv_length2, 0.0f, 1.0f);
if (alpha_mul >= 1.0f && ++full_alpha_count > 2)
return; // Early out
int a = (int) (((vert->col >> IM_COL32_A_SHIFT) & 0xFF) * alpha_mul);
vert->col = (vert->col & ~IM_COL32_A_MASK) | (a << IM_COL32_A_SHIFT);
}
}
// Distribute UV over (a, b) rectangle
void ImGui::ShadeVertsLinearUV(ImDrawVert *vert_start, ImDrawVert *vert_end, const ImVec2 &a, const ImVec2 &b,
const ImVec2 &uv_a, const ImVec2 &uv_b, bool clamp) {
const ImVec2 size = b - a;
const ImVec2 uv_size = uv_b - uv_a;
const ImVec2 scale = ImVec2(
size.x != 0.0f ? (uv_size.x / size.x) : 0.0f,
size.y != 0.0f ? (uv_size.y / size.y) : 0.0f);
if (clamp) {
const ImVec2 min = ImMin(uv_a, uv_b);
const ImVec2 max = ImMax(uv_a, uv_b);
for (ImDrawVert *vertex = vert_start; vertex < vert_end; ++vertex)
vertex->uv = ImClamp(uv_a + ImMul(ImVec2(vertex->pos.x, vertex->pos.y) - a, scale), min, max);
} else {
for (ImDrawVert *vertex = vert_start; vertex < vert_end; ++vertex)
vertex->uv = uv_a + ImMul(ImVec2(vertex->pos.x, vertex->pos.y) - a, scale);
}
}
//-----------------------------------------------------------------------------
// ImFontConfig
//-----------------------------------------------------------------------------
ImFontConfig::ImFontConfig() {
FontData = NULL;
FontDataSize = 0;
FontDataOwnedByAtlas = true;
FontNo = 0;
SizePixels = 0.0f;
OversampleH = 3;
OversampleV = 1;
PixelSnapH = false;
GlyphExtraSpacing = ImVec2(0.0f, 0.0f);
GlyphOffset = ImVec2(0.0f, 0.0f);
GlyphRanges = NULL;
GlyphMinAdvanceX = 0.0f;
GlyphMaxAdvanceX = FLT_MAX;
MergeMode = false;
RasterizerFlags = 0x00;
RasterizerMultiply = 1.0f;
memset(Name, 0, sizeof(Name));
DstFont = NULL;
}
//-----------------------------------------------------------------------------
// ImFontAtlas
//-----------------------------------------------------------------------------
// A work of art lies ahead! (. = white layer, X = black layer, others are blank)
// The white texels on the top left are the ones we'll use everywhere in ImGui to render filled shapes.
const int FONT_ATLAS_DEFAULT_TEX_DATA_W_HALF = 90;
const int FONT_ATLAS_DEFAULT_TEX_DATA_H = 27;
const unsigned int FONT_ATLAS_DEFAULT_TEX_DATA_ID = 0x80000000;
static const char FONT_ATLAS_DEFAULT_TEX_DATA_PIXELS[
FONT_ATLAS_DEFAULT_TEX_DATA_W_HALF * FONT_ATLAS_DEFAULT_TEX_DATA_H + 1] =
{
"..- -XXXXXXX- X - X -XXXXXXX - XXXXXXX"
"..- -X.....X- X.X - X.X -X.....X - X.....X"
"--- -XXX.XXX- X...X - X...X -X....X - X....X"
"X - X.X - X.....X - X.....X -X...X - X...X"
"XX - X.X -X.......X- X.......X -X..X.X - X.X..X"
"X.X - X.X -XXXX.XXXX- XXXX.XXXX -X.X X.X - X.X X.X"
"X..X - X.X - X.X - X.X -XX X.X - X.X XX"
"X...X - X.X - X.X - XX X.X XX - X.X - X.X "
"X....X - X.X - X.X - X.X X.X X.X - X.X - X.X "
"X.....X - X.X - X.X - X..X X.X X..X - X.X - X.X "
"X......X - X.X - X.X - X...XXXXXX.XXXXXX...X - X.X XX-XX X.X "
"X.......X - X.X - X.X -X.....................X- X.X X.X-X.X X.X "
"X........X - X.X - X.X - X...XXXXXX.XXXXXX...X - X.X..X-X..X.X "
"X.........X -XXX.XXX- X.X - X..X X.X X..X - X...X-X...X "
"X..........X-X.....X- X.X - X.X X.X X.X - X....X-X....X "
"X......XXXXX-XXXXXXX- X.X - XX X.X XX - X.....X-X.....X "
"X...X..X --------- X.X - X.X - XXXXXXX-XXXXXXX "
"X..X X..X - -XXXX.XXXX- XXXX.XXXX ------------------------------------"
"X.X X..X - -X.......X- X.......X - XX XX - "
"XX X..X - - X.....X - X.....X - X.X X.X - "
" X..X - X...X - X...X - X..X X..X - "
" XX - X.X - X.X - X...XXXXXXXXXXXXX...X - "
"------------ - X - X -X.....................X- "
" ----------------------------------- X...XXXXXXXXXXXXX...X - "
" - X..X X..X - "
" - X.X X.X - "
" - XX XX - "
};
static const ImVec2 FONT_ATLAS_DEFAULT_TEX_CURSOR_DATA[ImGuiMouseCursor_COUNT][3] =
{
// Pos ........ Size ......... Offset ......
{ImVec2(0, 3), ImVec2(12, 19), ImVec2(0, 0)}, // ImGuiMouseCursor_Arrow
{ImVec2(13, 0), ImVec2(7, 16), ImVec2(4, 8)}, // ImGuiMouseCursor_TextInput
{ImVec2(31, 0), ImVec2(23, 23), ImVec2(11, 11)}, // ImGuiMouseCursor_ResizeAll
{ImVec2(21, 0), ImVec2(9, 23), ImVec2(5, 11)}, // ImGuiMouseCursor_ResizeNS
{ImVec2(55, 18), ImVec2(23, 9), ImVec2(11, 5)}, // ImGuiMouseCursor_ResizeEW
{ImVec2(73, 0), ImVec2(17, 17), ImVec2(9, 9)}, // ImGuiMouseCursor_ResizeNESW
{ImVec2(55, 0), ImVec2(17, 17), ImVec2(9, 9)}, // ImGuiMouseCursor_ResizeNWSE
};
ImFontAtlas::ImFontAtlas() {
Flags = 0x00;
TexID = NULL;
TexDesiredWidth = 0;
TexGlyphPadding = 1;
TexPixelsAlpha8 = NULL;
TexPixelsRGBA32 = NULL;
TexWidth = TexHeight = 0;
TexUvScale = ImVec2(0.0f, 0.0f);
TexUvWhitePixel = ImVec2(0.0f, 0.0f);
for (int n = 0; n < IM_ARRAYSIZE(CustomRectIds); n++)
CustomRectIds[n] = -1;
}
ImFontAtlas::~ImFontAtlas() {
Clear();
}
void ImFontAtlas::ClearInputData() {
for (int i = 0; i < ConfigData.Size; i++)
if (ConfigData[i].FontData && ConfigData[i].FontDataOwnedByAtlas) {
ImGui::MemFree(ConfigData[i].FontData);
ConfigData[i].FontData = NULL;
}
// When clearing this we lose access to the font name and other information used to build the font.
for (int i = 0; i < Fonts.Size; i++)
if (Fonts[i]->ConfigData >= ConfigData.Data && Fonts[i]->ConfigData < ConfigData.Data + ConfigData.Size) {
Fonts[i]->ConfigData = NULL;
Fonts[i]->ConfigDataCount = 0;
}
ConfigData.clear();
CustomRects.clear();
for (int n = 0; n < IM_ARRAYSIZE(CustomRectIds); n++)
CustomRectIds[n] = -1;
}
void ImFontAtlas::ClearTexData() {
if (TexPixelsAlpha8)
ImGui::MemFree(TexPixelsAlpha8);
if (TexPixelsRGBA32)
ImGui::MemFree(TexPixelsRGBA32);
TexPixelsAlpha8 = NULL;
TexPixelsRGBA32 = NULL;
}
void ImFontAtlas::ClearFonts() {
for (int i = 0; i < Fonts.Size; i++)
IM_DELETE(Fonts[i]);
Fonts.clear();
}
void ImFontAtlas::Clear() {
ClearInputData();
ClearTexData();
ClearFonts();
}
void
ImFontAtlas::GetTexDataAsAlpha8(unsigned char **out_pixels, int *out_width, int *out_height, int *out_bytes_per_pixel) {
// Build atlas on demand
if (TexPixelsAlpha8 == NULL) {
if (ConfigData.empty())
AddFontDefault();
Build();
}
*out_pixels = TexPixelsAlpha8;
if (out_width) *out_width = TexWidth;
if (out_height) *out_height = TexHeight;
if (out_bytes_per_pixel) *out_bytes_per_pixel = 1;
}
void
ImFontAtlas::GetTexDataAsRGBA32(unsigned char **out_pixels, int *out_width, int *out_height, int *out_bytes_per_pixel) {
// Convert to RGBA32 format on demand
// Although it is likely to be the most commonly used format, our font rendering is 1 channel / 8 bpp
if (!TexPixelsRGBA32) {
unsigned char *pixels = NULL;
GetTexDataAsAlpha8(&pixels, NULL, NULL);
if (pixels) {
TexPixelsRGBA32 = (unsigned int *) ImGui::MemAlloc((size_t) (TexWidth * TexHeight * 4));
const unsigned char *src = pixels;
unsigned int *dst = TexPixelsRGBA32;
for (int n = TexWidth * TexHeight; n > 0; n--)
*dst++ = IM_COL32(255, 255, 255, (unsigned int) (*src++));
}
}
*out_pixels = (unsigned char *) TexPixelsRGBA32;
if (out_width) *out_width = TexWidth;
if (out_height) *out_height = TexHeight;
if (out_bytes_per_pixel) *out_bytes_per_pixel = 4;
}
ImFont *ImFontAtlas::AddFont(const ImFontConfig *font_cfg) {
IM_ASSERT(font_cfg->FontData != NULL && font_cfg->FontDataSize > 0);
IM_ASSERT(font_cfg->SizePixels > 0.0f);
// Create new font
if (!font_cfg->MergeMode)
Fonts.push_back(IM_NEW(ImFont));
else
IM_ASSERT(
!Fonts.empty()); // When using MergeMode make sure that a font has already been added before. You can use ImGui::GetIO().Fonts->AddFontDefault() to add the default imgui font.
ConfigData.push_back(*font_cfg);
ImFontConfig &new_font_cfg = ConfigData.back();
if (!new_font_cfg.DstFont)
new_font_cfg.DstFont = Fonts.back();
if (!new_font_cfg.FontDataOwnedByAtlas) {
new_font_cfg.FontData = ImGui::MemAlloc(new_font_cfg.FontDataSize);
new_font_cfg.FontDataOwnedByAtlas = true;
memcpy(new_font_cfg.FontData, font_cfg->FontData, (size_t) new_font_cfg.FontDataSize);
}
// Invalidate texture
ClearTexData();
return new_font_cfg.DstFont;
}
// Default font TTF is compressed with stb_compress then base85 encoded (see misc/fonts/binary_to_compressed_c.cpp for encoder)
static unsigned int stb_decompress_length(const unsigned char *input);
static unsigned int stb_decompress(unsigned char *output, const unsigned char *input, unsigned int length);
static const char *GetDefaultCompressedFontDataTTFBase85();
static unsigned int Decode85Byte(char c) { return c >= '\\' ? c - 36 : c - 35; }
static void Decode85(const unsigned char *src, unsigned char *dst) {
while (*src) {
unsigned int tmp = Decode85Byte(src[0]) + 85 * (Decode85Byte(src[1]) + 85 * (Decode85Byte(src[2]) + 85 *
(Decode85Byte(
src[3]) +
85 *
Decode85Byte(
src[4]))));
dst[0] = ((tmp >> 0) & 0xFF);
dst[1] = ((tmp >> 8) & 0xFF);
dst[2] = ((tmp >> 16) & 0xFF);
dst[3] = ((tmp >> 24) & 0xFF); // We can't assume little-endianness.
src += 5;
dst += 4;
}
}
// Load embedded ProggyClean.ttf at size 13, disable oversampling
ImFont *ImFontAtlas::AddFontDefault(const ImFontConfig *font_cfg_template) {
ImFontConfig font_cfg = font_cfg_template ? *font_cfg_template : ImFontConfig();
if (!font_cfg_template) {
font_cfg.OversampleH = font_cfg.OversampleV = 1;
font_cfg.PixelSnapH = true;
}
if (font_cfg.Name[0] == '\0') strcpy(font_cfg.Name, "ProggyClean.ttf, 13px");
if (font_cfg.SizePixels <= 0.0f) font_cfg.SizePixels = 13.0f;
const char *ttf_compressed_base85 = GetDefaultCompressedFontDataTTFBase85();
ImFont *font = AddFontFromMemoryCompressedBase85TTF(ttf_compressed_base85, font_cfg.SizePixels, &font_cfg,
GetGlyphRangesDefault());
font->DisplayOffset.y = 1.0f;
return font;
}
ImFont *ImFontAtlas::AddFontFromFileTTF(const char *filename, float size_pixels, const ImFontConfig *font_cfg_template,
const ImWchar *glyph_ranges) {
size_t data_size = 0;
void *data = ImFileLoadToMemory(filename, "rb", &data_size, 0);
if (!data) {
IM_ASSERT(0); // Could not load file.
return NULL;
}
ImFontConfig font_cfg = font_cfg_template ? *font_cfg_template : ImFontConfig();
if (font_cfg.Name[0] == '\0') {
// Store a short copy of filename into into the font name for convenience
const char *p;
for (p = filename + strlen(filename); p > filename && p[-1] != '/' && p[-1] != '\\'; p--) {}
ImFormatString(font_cfg.Name, IM_ARRAYSIZE(font_cfg.Name), "%s, %.0fpx", p, size_pixels);
}
return AddFontFromMemoryTTF(data, (int) data_size, size_pixels, &font_cfg, glyph_ranges);
}
// NB: Transfer ownership of 'ttf_data' to ImFontAtlas, unless font_cfg_template->FontDataOwnedByAtlas == false. Owned TTF buffer will be deleted after Build().
ImFont *ImFontAtlas::AddFontFromMemoryTTF(void *ttf_data, int ttf_size, float size_pixels,
const ImFontConfig *font_cfg_template, const ImWchar *glyph_ranges) {
ImFontConfig font_cfg = font_cfg_template ? *font_cfg_template : ImFontConfig();
IM_ASSERT(font_cfg.FontData == NULL);
font_cfg.FontData = ttf_data;
font_cfg.FontDataSize = ttf_size;
font_cfg.SizePixels = size_pixels;
if (glyph_ranges)
font_cfg.GlyphRanges = glyph_ranges;
return AddFont(&font_cfg);
}
ImFont *
ImFontAtlas::AddFontFromMemoryCompressedTTF(const void *compressed_ttf_data, int compressed_ttf_size, float size_pixels,
const ImFontConfig *font_cfg_template, const ImWchar *glyph_ranges) {
const unsigned int buf_decompressed_size = stb_decompress_length((const unsigned char *) compressed_ttf_data);
unsigned char *buf_decompressed_data = (unsigned char *) ImGui::MemAlloc(buf_decompressed_size);
stb_decompress(buf_decompressed_data, (const unsigned char *) compressed_ttf_data,
(unsigned int) compressed_ttf_size);
ImFontConfig font_cfg = font_cfg_template ? *font_cfg_template : ImFontConfig();
IM_ASSERT(font_cfg.FontData == NULL);
font_cfg.FontDataOwnedByAtlas = true;
return AddFontFromMemoryTTF(buf_decompressed_data, (int) buf_decompressed_size, size_pixels, &font_cfg,
glyph_ranges);
}
ImFont *ImFontAtlas::AddFontFromMemoryCompressedBase85TTF(const char *compressed_ttf_data_base85, float size_pixels,
const ImFontConfig *font_cfg, const ImWchar *glyph_ranges) {
int compressed_ttf_size = (((int) strlen(compressed_ttf_data_base85) + 4) / 5) * 4;
void *compressed_ttf = ImGui::MemAlloc((size_t) compressed_ttf_size);
Decode85((const unsigned char *) compressed_ttf_data_base85, (unsigned char *) compressed_ttf);
ImFont *font = AddFontFromMemoryCompressedTTF(compressed_ttf, compressed_ttf_size, size_pixels, font_cfg,
glyph_ranges);
ImGui::MemFree(compressed_ttf);
return font;
}
int ImFontAtlas::AddCustomRectRegular(unsigned int id, int width, int height) {
IM_ASSERT(id >= 0x10000);
IM_ASSERT(width > 0 && width <= 0xFFFF);
IM_ASSERT(height > 0 && height <= 0xFFFF);
CustomRect r;
r.ID = id;
r.Width = (unsigned short) width;
r.Height = (unsigned short) height;
CustomRects.push_back(r);
return CustomRects.Size - 1; // Return index
}
int ImFontAtlas::AddCustomRectFontGlyph(ImFont *font, ImWchar id, int width, int height, float advance_x,
const ImVec2 &offset) {
IM_ASSERT(font != NULL);
IM_ASSERT(width > 0 && width <= 0xFFFF);
IM_ASSERT(height > 0 && height <= 0xFFFF);
CustomRect r;
r.ID = id;
r.Width = (unsigned short) width;
r.Height = (unsigned short) height;
r.GlyphAdvanceX = advance_x;
r.GlyphOffset = offset;
r.Font = font;
CustomRects.push_back(r);
return CustomRects.Size - 1; // Return index
}
void ImFontAtlas::CalcCustomRectUV(const CustomRect *rect, ImVec2 *out_uv_min, ImVec2 *out_uv_max) {
IM_ASSERT(TexWidth > 0 && TexHeight > 0); // Font atlas needs to be built before we can calculate UV coordinates
IM_ASSERT(rect->IsPacked()); // Make sure the rectangle has been packed
*out_uv_min = ImVec2((float) rect->X * TexUvScale.x, (float) rect->Y * TexUvScale.y);
*out_uv_max = ImVec2((float) (rect->X + rect->Width) * TexUvScale.x,
(float) (rect->Y + rect->Height) * TexUvScale.y);
}
bool ImFontAtlas::GetMouseCursorTexData(ImGuiMouseCursor cursor_type, ImVec2 *out_offset, ImVec2 *out_size,
ImVec2 out_uv_border[2], ImVec2 out_uv_fill[2]) {
if (cursor_type <= ImGuiMouseCursor_None || cursor_type >= ImGuiMouseCursor_COUNT)
return false;
if (Flags & ImFontAtlasFlags_NoMouseCursors)
return false;
IM_ASSERT(CustomRectIds[0] != -1);
ImFontAtlas::CustomRect &r = CustomRects[CustomRectIds[0]];
IM_ASSERT(r.ID == FONT_ATLAS_DEFAULT_TEX_DATA_ID);
ImVec2 pos = FONT_ATLAS_DEFAULT_TEX_CURSOR_DATA[cursor_type][0] + ImVec2((float) r.X, (float) r.Y);
ImVec2 size = FONT_ATLAS_DEFAULT_TEX_CURSOR_DATA[cursor_type][1];
*out_size = size;
*out_offset = FONT_ATLAS_DEFAULT_TEX_CURSOR_DATA[cursor_type][2];
out_uv_border[0] = (pos) * TexUvScale;
out_uv_border[1] = (pos + size) * TexUvScale;
pos.x += FONT_ATLAS_DEFAULT_TEX_DATA_W_HALF + 1;
out_uv_fill[0] = (pos) * TexUvScale;
out_uv_fill[1] = (pos + size) * TexUvScale;
return true;
}
bool ImFontAtlas::Build() {
return ImFontAtlasBuildWithStbTruetype(this);
}
void ImFontAtlasBuildMultiplyCalcLookupTable(unsigned char out_table[256], float in_brighten_factor) {
for (unsigned int i = 0; i < 256; i++) {
unsigned int value = (unsigned int) (i * in_brighten_factor);
out_table[i] = value > 255 ? 255 : (value & 0xFF);
}
}
void
ImFontAtlasBuildMultiplyRectAlpha8(const unsigned char table[256], unsigned char *pixels, int x, int y, int w, int h,
int stride) {
unsigned char *data = pixels + x + y * stride;
for (int j = h; j > 0; j--, data += stride)
for (int i = 0; i < w; i++)
data[i] = table[data[i]];
}
bool ImFontAtlasBuildWithStbTruetype(ImFontAtlas *atlas) {
IM_ASSERT(atlas->ConfigData.Size > 0);
ImFontAtlasBuildRegisterDefaultCustomRects(atlas);
atlas->TexID = NULL;
atlas->TexWidth = atlas->TexHeight = 0;
atlas->TexUvScale = ImVec2(0.0f, 0.0f);
atlas->TexUvWhitePixel = ImVec2(0.0f, 0.0f);
atlas->ClearTexData();
// Count glyphs/ranges
int total_glyphs_count = 0;
int total_ranges_count = 0;
for (int input_i = 0; input_i < atlas->ConfigData.Size; input_i++) {
ImFontConfig &cfg = atlas->ConfigData[input_i];
if (!cfg.GlyphRanges)
cfg.GlyphRanges = atlas->GetGlyphRangesDefault();
for (const ImWchar *in_range = cfg.GlyphRanges; in_range[0] && in_range[1]; in_range += 2, total_ranges_count++)
total_glyphs_count += (in_range[1] - in_range[0]) + 1;
}
// We need a width for the skyline algorithm. Using a dumb heuristic here to decide of width. User can override TexDesiredWidth and TexGlyphPadding if they wish.
// Width doesn't really matter much, but some API/GPU have texture size limitations and increasing width can decrease height.
atlas->TexWidth = (atlas->TexDesiredWidth > 0) ? atlas->TexDesiredWidth : (total_glyphs_count > 4000) ? 4096
: (total_glyphs_count >
2000)
? 2048
: (total_glyphs_count >
1000)
? 1024
: 512;
atlas->TexHeight = 0;
// Start packing
const int max_tex_height = 1024 * 32;
stbtt_pack_context spc = {};
if (!stbtt_PackBegin(&spc, NULL, atlas->TexWidth, max_tex_height, 0, atlas->TexGlyphPadding, NULL))
return false;
stbtt_PackSetOversampling(&spc, 1, 1);
// Pack our extra data rectangles first, so it will be on the upper-left corner of our texture (UV will have small values).
ImFontAtlasBuildPackCustomRects(atlas, spc.pack_info);
// Initialize font information (so we can error without any cleanup)
struct ImFontTempBuildData {
stbtt_fontinfo FontInfo;
stbrp_rect *Rects;
int RectsCount;
stbtt_pack_range *Ranges;
int RangesCount;
};
ImFontTempBuildData *tmp_array = (ImFontTempBuildData *) ImGui::MemAlloc(
(size_t) atlas->ConfigData.Size * sizeof(ImFontTempBuildData));
for (int input_i = 0; input_i < atlas->ConfigData.Size; input_i++) {
ImFontConfig &cfg = atlas->ConfigData[input_i];
ImFontTempBuildData &tmp = tmp_array[input_i];
IM_ASSERT(cfg.DstFont && (!cfg.DstFont->IsLoaded() || cfg.DstFont->ContainerAtlas == atlas));
const int font_offset = stbtt_GetFontOffsetForIndex((unsigned char *) cfg.FontData, cfg.FontNo);
IM_ASSERT(font_offset >= 0 && "FontData is incorrect, or FontNo cannot be found.");
if (!stbtt_InitFont(&tmp.FontInfo, (unsigned char *) cfg.FontData, font_offset)) {
atlas->TexWidth = atlas->TexHeight = 0; // Reset output on failure
ImGui::MemFree(tmp_array);
return false;
}
}
// Allocate packing character data and flag packed characters buffer as non-packed (x0=y0=x1=y1=0)
int buf_packedchars_n = 0, buf_rects_n = 0, buf_ranges_n = 0;
stbtt_packedchar *buf_packedchars = (stbtt_packedchar *) ImGui::MemAlloc(
total_glyphs_count * sizeof(stbtt_packedchar));
stbrp_rect *buf_rects = (stbrp_rect *) ImGui::MemAlloc(total_glyphs_count * sizeof(stbrp_rect));
stbtt_pack_range *buf_ranges = (stbtt_pack_range *) ImGui::MemAlloc(total_ranges_count * sizeof(stbtt_pack_range));
memset(buf_packedchars, 0, total_glyphs_count * sizeof(stbtt_packedchar));
memset(buf_rects, 0, total_glyphs_count *
sizeof(stbrp_rect)); // Unnecessary but let's clear this for the sake of sanity.
memset(buf_ranges, 0, total_ranges_count * sizeof(stbtt_pack_range));
// First font pass: pack all glyphs (no rendering at this point, we are working with rectangles in an infinitely tall texture at this point)
for (int input_i = 0; input_i < atlas->ConfigData.Size; input_i++) {
ImFontConfig &cfg = atlas->ConfigData[input_i];
ImFontTempBuildData &tmp = tmp_array[input_i];
// Setup ranges
int font_glyphs_count = 0;
int font_ranges_count = 0;
for (const ImWchar *in_range = cfg.GlyphRanges; in_range[0] && in_range[1]; in_range += 2, font_ranges_count++)
font_glyphs_count += (in_range[1] - in_range[0]) + 1;
tmp.Ranges = buf_ranges + buf_ranges_n;
tmp.RangesCount = font_ranges_count;
buf_ranges_n += font_ranges_count;
for (int i = 0; i < font_ranges_count; i++) {
const ImWchar *in_range = &cfg.GlyphRanges[i * 2];
stbtt_pack_range &range = tmp.Ranges[i];
range.font_size = cfg.SizePixels;
range.first_unicode_codepoint_in_range = in_range[0];
range.num_chars = (in_range[1] - in_range[0]) + 1;
range.chardata_for_range = buf_packedchars + buf_packedchars_n;
buf_packedchars_n += range.num_chars;
}
// Gather the sizes of all rectangle we need
tmp.Rects = buf_rects + buf_rects_n;
tmp.RectsCount = font_glyphs_count;
buf_rects_n += font_glyphs_count;
stbtt_PackSetOversampling(&spc, cfg.OversampleH, cfg.OversampleV);
int n = stbtt_PackFontRangesGatherRects(&spc, &tmp.FontInfo, tmp.Ranges, tmp.RangesCount, tmp.Rects);
IM_ASSERT(n == font_glyphs_count);
// Detect missing glyphs and replace them with a zero-sized box instead of relying on the default glyphs
// This allows us merging overlapping icon fonts more easily.
int rect_i = 0;
for (int range_i = 0; range_i < tmp.RangesCount; range_i++)
for (int char_i = 0; char_i < tmp.Ranges[range_i].num_chars; char_i++, rect_i++)
if (stbtt_FindGlyphIndex(&tmp.FontInfo,
tmp.Ranges[range_i].first_unicode_codepoint_in_range + char_i) == 0)
tmp.Rects[rect_i].w = tmp.Rects[rect_i].h = 0;
// Pack
stbrp_pack_rects((stbrp_context *) spc.pack_info, tmp.Rects, n);
// Extend texture height
// Also mark missing glyphs as non-packed so we don't attempt to render into them
for (int i = 0; i < n; i++) {
if (tmp.Rects[i].w == 0 && tmp.Rects[i].h == 0)
tmp.Rects[i].was_packed = 0;
if (tmp.Rects[i].was_packed)
atlas->TexHeight = ImMax(atlas->TexHeight, tmp.Rects[i].y + tmp.Rects[i].h);
}
}
IM_ASSERT(buf_rects_n == total_glyphs_count);
IM_ASSERT(buf_packedchars_n == total_glyphs_count);
IM_ASSERT(buf_ranges_n == total_ranges_count);
// Create texture
atlas->TexHeight = (atlas->Flags & ImFontAtlasFlags_NoPowerOfTwoHeight) ? (atlas->TexHeight + 1)
: ImUpperPowerOfTwo(atlas->TexHeight);
atlas->TexUvScale = ImVec2(1.0f / atlas->TexWidth, 1.0f / atlas->TexHeight);
atlas->TexPixelsAlpha8 = (unsigned char *) ImGui::MemAlloc(atlas->TexWidth * atlas->TexHeight);
memset(atlas->TexPixelsAlpha8, 0, atlas->TexWidth * atlas->TexHeight);
spc.pixels = atlas->TexPixelsAlpha8;
spc.height = atlas->TexHeight;
// Second pass: render font characters
for (int input_i = 0; input_i < atlas->ConfigData.Size; input_i++) {
ImFontConfig &cfg = atlas->ConfigData[input_i];
ImFontTempBuildData &tmp = tmp_array[input_i];
stbtt_PackSetOversampling(&spc, cfg.OversampleH, cfg.OversampleV);
stbtt_PackFontRangesRenderIntoRects(&spc, &tmp.FontInfo, tmp.Ranges, tmp.RangesCount, tmp.Rects);
if (cfg.RasterizerMultiply != 1.0f) {
unsigned char multiply_table[256];
ImFontAtlasBuildMultiplyCalcLookupTable(multiply_table, cfg.RasterizerMultiply);
for (const stbrp_rect *r = tmp.Rects; r != tmp.Rects + tmp.RectsCount; r++)
if (r->was_packed)
ImFontAtlasBuildMultiplyRectAlpha8(multiply_table, spc.pixels, r->x, r->y, r->w, r->h,
spc.stride_in_bytes);
}
tmp.Rects = NULL;
}
// End packing
stbtt_PackEnd(&spc);
ImGui::MemFree(buf_rects);
buf_rects = NULL;
// Third pass: setup ImFont and glyphs for runtime
for (int input_i = 0; input_i < atlas->ConfigData.Size; input_i++) {
ImFontConfig &cfg = atlas->ConfigData[input_i];
ImFontTempBuildData &tmp = tmp_array[input_i];
ImFont *dst_font = cfg.DstFont; // We can have multiple input fonts writing into a same destination font (when using MergeMode=true)
if (cfg.MergeMode)
dst_font->BuildLookupTable();
const float font_scale = stbtt_ScaleForPixelHeight(&tmp.FontInfo, cfg.SizePixels);
int unscaled_ascent, unscaled_descent, unscaled_line_gap;
stbtt_GetFontVMetrics(&tmp.FontInfo, &unscaled_ascent, &unscaled_descent, &unscaled_line_gap);
const float ascent = ImFloor(unscaled_ascent * font_scale + ((unscaled_ascent > 0.0f) ? +1 : -1));
const float descent = ImFloor(unscaled_descent * font_scale + ((unscaled_descent > 0.0f) ? +1 : -1));
ImFontAtlasBuildSetupFont(atlas, dst_font, &cfg, ascent, descent);
const float font_off_x = cfg.GlyphOffset.x;
const float font_off_y = cfg.GlyphOffset.y + (float) (int) (dst_font->Ascent + 0.5f);
for (int i = 0; i < tmp.RangesCount; i++) {
stbtt_pack_range &range = tmp.Ranges[i];
for (int char_idx = 0; char_idx < range.num_chars; char_idx += 1) {
const stbtt_packedchar &pc = range.chardata_for_range[char_idx];
if (!pc.x0 && !pc.x1 && !pc.y0 && !pc.y1)
continue;
const int codepoint = range.first_unicode_codepoint_in_range + char_idx;
if (cfg.MergeMode && dst_font->FindGlyphNoFallback((unsigned short) codepoint))
continue;
float char_advance_x_org = pc.xadvance;
float char_advance_x_mod = ImClamp(char_advance_x_org, cfg.GlyphMinAdvanceX, cfg.GlyphMaxAdvanceX);
float char_off_x = font_off_x;
if (char_advance_x_org != char_advance_x_mod)
char_off_x += cfg.PixelSnapH ? (float) (int) ((char_advance_x_mod - char_advance_x_org) * 0.5f) :
(char_advance_x_mod - char_advance_x_org) * 0.5f;
stbtt_aligned_quad q;
float dummy_x = 0.0f, dummy_y = 0.0f;
stbtt_GetPackedQuad(range.chardata_for_range, atlas->TexWidth, atlas->TexHeight, char_idx, &dummy_x,
&dummy_y, &q, 0);
dst_font->AddGlyph((ImWchar) codepoint, q.x0 + char_off_x, q.y0 + font_off_y, q.x1 + char_off_x,
q.y1 + font_off_y, q.s0, q.t0, q.s1, q.t1, char_advance_x_mod);
}
}
}
// Cleanup temporaries
ImGui::MemFree(buf_packedchars);
ImGui::MemFree(buf_ranges);
ImGui::MemFree(tmp_array);
ImFontAtlasBuildFinish(atlas);
return true;
}
void ImFontAtlasBuildRegisterDefaultCustomRects(ImFontAtlas *atlas) {
if (atlas->CustomRectIds[0] >= 0)
return;
if (!(atlas->Flags & ImFontAtlasFlags_NoMouseCursors))
atlas->CustomRectIds[0] = atlas->AddCustomRectRegular(FONT_ATLAS_DEFAULT_TEX_DATA_ID,
FONT_ATLAS_DEFAULT_TEX_DATA_W_HALF * 2 + 1,
FONT_ATLAS_DEFAULT_TEX_DATA_H);
else
atlas->CustomRectIds[0] = atlas->AddCustomRectRegular(FONT_ATLAS_DEFAULT_TEX_DATA_ID, 2, 2);
}
void
ImFontAtlasBuildSetupFont(ImFontAtlas *atlas, ImFont *font, ImFontConfig *font_config, float ascent, float descent) {
if (!font_config->MergeMode) {
font->ClearOutputData();
font->FontSize = font_config->SizePixels;
font->ConfigData = font_config;
font->ContainerAtlas = atlas;
font->Ascent = ascent;
font->Descent = descent;
}
font->ConfigDataCount++;
}
void ImFontAtlasBuildPackCustomRects(ImFontAtlas *atlas, void *pack_context_opaque) {
stbrp_context *pack_context = (stbrp_context *) pack_context_opaque;
ImVector<ImFontAtlas::CustomRect> &user_rects = atlas->CustomRects;
IM_ASSERT(user_rects.Size >=
1); // We expect at least the default custom rects to be registered, else something went wrong.
ImVector<stbrp_rect> pack_rects;
pack_rects.resize(user_rects.Size);
memset(pack_rects.Data, 0, sizeof(stbrp_rect) * user_rects.Size);
for (int i = 0; i < user_rects.Size; i++) {
pack_rects[i].w = user_rects[i].Width;
pack_rects[i].h = user_rects[i].Height;
}
stbrp_pack_rects(pack_context, &pack_rects[0], pack_rects.Size);
for (int i = 0; i < pack_rects.Size; i++)
if (pack_rects[i].was_packed) {
user_rects[i].X = pack_rects[i].x;
user_rects[i].Y = pack_rects[i].y;
IM_ASSERT(pack_rects[i].w == user_rects[i].Width && pack_rects[i].h == user_rects[i].Height);
atlas->TexHeight = ImMax(atlas->TexHeight, pack_rects[i].y + pack_rects[i].h);
}
}
static void ImFontAtlasBuildRenderDefaultTexData(ImFontAtlas *atlas) {
IM_ASSERT(atlas->CustomRectIds[0] >= 0);
IM_ASSERT(atlas->TexPixelsAlpha8 != NULL);
ImFontAtlas::CustomRect &r = atlas->CustomRects[atlas->CustomRectIds[0]];
IM_ASSERT(r.ID == FONT_ATLAS_DEFAULT_TEX_DATA_ID);
IM_ASSERT(r.IsPacked());
const int w = atlas->TexWidth;
if (!(atlas->Flags & ImFontAtlasFlags_NoMouseCursors)) {
// Render/copy pixels
IM_ASSERT(r.Width == FONT_ATLAS_DEFAULT_TEX_DATA_W_HALF * 2 + 1 && r.Height == FONT_ATLAS_DEFAULT_TEX_DATA_H);
for (int y = 0, n = 0; y < FONT_ATLAS_DEFAULT_TEX_DATA_H; y++)
for (int x = 0; x < FONT_ATLAS_DEFAULT_TEX_DATA_W_HALF; x++, n++) {
const int offset0 = (int) (r.X + x) + (int) (r.Y + y) * w;
const int offset1 = offset0 + FONT_ATLAS_DEFAULT_TEX_DATA_W_HALF + 1;
atlas->TexPixelsAlpha8[offset0] = FONT_ATLAS_DEFAULT_TEX_DATA_PIXELS[n] == '.' ? 0xFF : 0x00;
atlas->TexPixelsAlpha8[offset1] = FONT_ATLAS_DEFAULT_TEX_DATA_PIXELS[n] == 'X' ? 0xFF : 0x00;
}
} else {
IM_ASSERT(r.Width == 2 && r.Height == 2);
const int offset = (int) (r.X) + (int) (r.Y) * w;
atlas->TexPixelsAlpha8[offset] = atlas->TexPixelsAlpha8[offset + 1] = atlas->TexPixelsAlpha8[offset +
w] = atlas->TexPixelsAlpha8[
offset + w + 1] = 0xFF;
}
atlas->TexUvWhitePixel = ImVec2((r.X + 0.5f) * atlas->TexUvScale.x, (r.Y + 0.5f) * atlas->TexUvScale.y);
}
void ImFontAtlasBuildFinish(ImFontAtlas *atlas) {
// Render into our custom data block
ImFontAtlasBuildRenderDefaultTexData(atlas);
// Register custom rectangle glyphs
for (int i = 0; i < atlas->CustomRects.Size; i++) {
const ImFontAtlas::CustomRect &r = atlas->CustomRects[i];
if (r.Font == NULL || r.ID > 0x10000)
continue;
IM_ASSERT(r.Font->ContainerAtlas == atlas);
ImVec2 uv0, uv1;
atlas->CalcCustomRectUV(&r, &uv0, &uv1);
r.Font->AddGlyph((ImWchar) r.ID, r.GlyphOffset.x, r.GlyphOffset.y, r.GlyphOffset.x + r.Width,
r.GlyphOffset.y + r.Height, uv0.x, uv0.y, uv1.x, uv1.y, r.GlyphAdvanceX);
}
// Build all fonts lookup tables
for (int i = 0; i < atlas->Fonts.Size; i++)
if (atlas->Fonts[i]->DirtyLookupTables)
atlas->Fonts[i]->BuildLookupTable();
}
// Retrieve list of range (2 int per range, values are inclusive)
const ImWchar *ImFontAtlas::GetGlyphRangesDefault() {
static const ImWchar ranges[] =
{
0x0020, 0x00FF, // Basic Latin + Latin Supplement
0,
};
return &ranges[0];
}
const ImWchar *ImFontAtlas::GetGlyphRangesKorean() {
static const ImWchar ranges[] =
{
0x0020, 0x00FF, // Basic Latin + Latin Supplement
0x3131, 0x3163, // Korean alphabets
0xAC00, 0xD79D, // Korean characters
0,
};
return &ranges[0];
}
const ImWchar *ImFontAtlas::GetGlyphRangesChineseFull() {
static const ImWchar ranges[] =
{
0x0020, 0x00FF, // Basic Latin + Latin Supplement
0x3000, 0x30FF, // Punctuations, Hiragana, Katakana
0x31F0, 0x31FF, // Katakana Phonetic Extensions
0xFF00, 0xFFEF, // Half-width characters
0x4e00, 0x9FAF, // CJK Ideograms
0,
};
return &ranges[0];
}
static void UnpackAccumulativeOffsetsIntoRanges(int base_codepoint, const short *accumulative_offsets,
int accumulative_offsets_count, ImWchar *out_ranges) {
for (int n = 0; n < accumulative_offsets_count; n++, out_ranges += 2) {
out_ranges[0] = out_ranges[1] = (ImWchar) (base_codepoint + accumulative_offsets[n]);
base_codepoint += accumulative_offsets[n];
}
out_ranges[0] = 0;
}
const ImWchar *ImFontAtlas::GetGlyphRangesChineseSimplifiedCommon() {
// Store 2500 regularly used characters for Simplified Chinese.
// Sourced from https://zh.wiktionary.org/wiki/%E9%99%84%E5%BD%95:%E7%8E%B0%E4%BB%A3%E6%B1%89%E8%AF%AD%E5%B8%B8%E7%94%A8%E5%AD%97%E8%A1%A8
// This table covers 97.97% of all characters used during the month in July, 1987.
// You can use ImFontAtlas::GlyphRangesBuilder to create your own ranges derived from this, by merging existing ranges or adding new characters.
// (Stored as accumulative offsets from the initial unicode codepoint 0x4E00. This encoding is designed to helps us compact the source code size.)
static const short accumulative_offsets_from_0x4E00[] =
{
0, 1, 2, 4, 1, 1, 1, 1, 2, 1, 3, 2, 1, 2, 2, 1, 1, 1, 1, 1, 5, 2, 1, 2, 3, 3, 3, 2, 2, 4, 1, 1, 1,
2, 1, 5, 2, 3, 1, 2, 1, 2, 1, 1, 2, 1, 1, 2, 2, 1, 4, 1, 1, 1, 1, 5, 10, 1, 2, 19, 2, 1, 2, 1, 2, 1,
2, 1, 2,
1, 5, 1, 6, 3, 2, 1, 2, 2, 1, 1, 1, 4, 8, 5, 1, 1, 4, 1, 1, 3, 1, 2, 1, 5, 1, 2, 1, 1, 1, 10, 1, 1,
5, 2, 4, 6, 1, 4, 2, 2, 2, 12, 2, 1, 1, 6, 1, 1, 1, 4, 1, 1, 4, 6, 5, 1, 4, 2, 2, 4, 10, 7, 1, 1, 4,
2, 4,
2, 1, 4, 3, 6, 10, 12, 5, 7, 2, 14, 2, 9, 1, 1, 6, 7, 10, 4, 7, 13, 1, 5, 4, 8, 4, 1, 1, 2, 28, 5,
6, 1, 1, 5, 2, 5, 20, 2, 2, 9, 8, 11, 2, 9, 17, 1, 8, 6, 8, 27, 4, 6, 9, 20, 11, 27, 6, 68, 2, 2, 1,
1,
1, 2, 1, 2, 2, 7, 6, 11, 3, 3, 1, 1, 3, 1, 2, 1, 1, 1, 1, 1, 3, 1, 1, 8, 3, 4, 1, 5, 7, 2, 1, 4, 4,
8, 4, 2, 1, 2, 1, 1, 4, 5, 6, 3, 6, 2, 12, 3, 1, 3, 9, 2, 4, 3, 4, 1, 5, 3, 3, 1, 3, 7, 1, 5, 1, 1,
1, 1, 2,
3, 4, 5, 2, 3, 2, 6, 1, 1, 2, 1, 7, 1, 7, 3, 4, 5, 15, 2, 2, 1, 5, 3, 22, 19, 2, 1, 1, 1, 1, 2, 5,
1, 1, 1, 6, 1, 1, 12, 8, 2, 9, 18, 22, 4, 1, 1, 5, 1, 16, 1, 2, 7, 10, 15, 1, 1, 6, 2, 4, 1, 2, 4,
1, 6,
1, 1, 3, 2, 4, 1, 6, 4, 5, 1, 2, 1, 1, 2, 1, 10, 3, 1, 3, 2, 1, 9, 3, 2, 5, 7, 2, 19, 4, 3, 6, 1, 1,
1, 1, 1, 4, 3, 2, 1, 1, 1, 2, 5, 3, 1, 1, 1, 2, 2, 1, 1, 2, 1, 1, 2, 1, 3, 1, 1, 1, 3, 7, 1, 4, 1,
1, 2, 1,
1, 2, 1, 2, 4, 4, 3, 8, 1, 1, 1, 2, 1, 3, 5, 1, 3, 1, 3, 4, 6, 2, 2, 14, 4, 6, 6, 11, 9, 1, 15, 3,
1, 28, 5, 2, 5, 5, 3, 1, 3, 4, 5, 4, 6, 14, 3, 2, 3, 5, 21, 2, 7, 20, 10, 1, 2, 19, 2, 4, 28, 28, 2,
3,
2, 1, 14, 4, 1, 26, 28, 42, 12, 40, 3, 52, 79, 5, 14, 17, 3, 2, 2, 11, 3, 4, 6, 3, 1, 8, 2, 23, 4,
5, 8, 10, 4, 2, 7, 3, 5, 1, 1, 6, 3, 1, 2, 2, 2, 5, 28, 1, 1, 7, 7, 20, 5, 3, 29, 3, 17, 26, 1, 8,
4,
27, 3, 6, 11, 23, 5, 3, 4, 6, 13, 24, 16, 6, 5, 10, 25, 35, 7, 3, 2, 3, 3, 14, 3, 6, 2, 6, 1, 4, 2,
3, 8, 2, 1, 1, 3, 3, 3, 4, 1, 1, 13, 2, 2, 4, 5, 2, 1, 14, 14, 1, 2, 2, 1, 4, 5, 2, 3, 1, 14, 3, 12,
3, 17, 2, 16, 5, 1, 2, 1, 8, 9, 3, 19, 4, 2, 2, 4, 17, 25, 21, 20, 28, 75, 1, 10, 29, 103, 4, 1, 2,
1, 1, 4, 2, 4, 1, 2, 3, 24, 2, 2, 2, 1, 1, 2, 1, 3, 8, 1, 1, 1, 2, 1, 1, 3, 1, 1, 1, 6, 1, 5, 3, 1,
1,
1, 3, 4, 1, 1, 5, 2, 1, 5, 6, 13, 9, 16, 1, 1, 1, 1, 3, 2, 3, 2, 4, 5, 2, 5, 2, 2, 3, 7, 13, 7, 2,
2, 1, 1, 1, 1, 2, 3, 3, 2, 1, 6, 4, 9, 2, 1, 14, 2, 14, 2, 1, 18, 3, 4, 14, 4, 11, 41, 15, 23, 15,
23,
176, 1, 3, 4, 1, 1, 1, 1, 5, 3, 1, 2, 3, 7, 3, 1, 1, 2, 1, 2, 4, 4, 6, 2, 4, 1, 9, 7, 1, 10, 5, 8,
16, 29, 1, 1, 2, 2, 3, 1, 3, 5, 2, 4, 5, 4, 1, 1, 2, 2, 3, 3, 7, 1, 6, 10, 1, 17, 1, 44, 4, 6, 2, 1,
1, 6,
5, 4, 2, 10, 1, 6, 9, 2, 8, 1, 24, 1, 2, 13, 7, 8, 8, 2, 1, 4, 1, 3, 1, 3, 3, 5, 2, 5, 10, 9, 4, 9,
12, 2, 1, 6, 1, 10, 1, 1, 7, 7, 4, 10, 8, 3, 1, 13, 4, 3, 1, 6, 1, 3, 5, 2, 1, 2, 17, 16, 5, 2, 16,
6,
1, 4, 2, 1, 3, 3, 6, 8, 5, 11, 11, 1, 3, 3, 2, 4, 6, 10, 9, 5, 7, 4, 7, 4, 7, 1, 1, 4, 2, 1, 3, 6,
8, 7, 1, 6, 11, 5, 5, 3, 24, 9, 4, 2, 7, 13, 5, 1, 8, 82, 16, 61, 1, 1, 1, 4, 2, 2, 16, 10, 3, 8, 1,
1,
6, 4, 2, 1, 3, 1, 1, 1, 4, 3, 8, 4, 2, 2, 1, 1, 1, 1, 1, 6, 3, 5, 1, 1, 4, 6, 9, 2, 1, 1, 1, 2, 1,
7, 2, 1, 6, 1, 5, 4, 4, 3, 1, 8, 1, 3, 3, 1, 3, 2, 2, 2, 2, 3, 1, 6, 1, 2, 1, 2, 1, 3, 7, 1, 8, 2,
1, 2, 1, 5,
2, 5, 3, 5, 10, 1, 2, 1, 1, 3, 2, 5, 11, 3, 9, 3, 5, 1, 1, 5, 9, 1, 2, 1, 5, 7, 9, 9, 8, 1, 3, 3, 3,
6, 8, 2, 3, 2, 1, 1, 32, 6, 1, 2, 15, 9, 3, 7, 13, 1, 3, 10, 13, 2, 14, 1, 13, 10, 2, 1, 3, 10, 4,
15,
2, 15, 15, 10, 1, 3, 9, 6, 9, 32, 25, 26, 47, 7, 3, 2, 3, 1, 6, 3, 4, 3, 2, 8, 5, 4, 1, 9, 4, 2, 2,
19, 10, 6, 2, 3, 8, 1, 2, 2, 4, 2, 1, 9, 4, 4, 4, 6, 4, 8, 9, 2, 3, 1, 1, 1, 1, 3, 5, 5, 1, 3, 8, 4,
6,
2, 1, 4, 12, 1, 5, 3, 7, 13, 2, 5, 8, 1, 6, 1, 2, 5, 14, 6, 1, 5, 2, 4, 8, 15, 5, 1, 23, 6, 62, 2,
10, 1, 1, 8, 1, 2, 2, 10, 4, 2, 2, 9, 2, 1, 1, 3, 2, 3, 1, 5, 3, 3, 2, 1, 3, 8, 1, 1, 1, 11, 3, 1,
1, 4,
3, 7, 1, 14, 1, 2, 3, 12, 5, 2, 5, 1, 6, 7, 5, 7, 14, 11, 1, 3, 1, 8, 9, 12, 2, 1, 11, 8, 4, 4, 2,
6, 10, 9, 13, 1, 1, 3, 1, 5, 1, 3, 2, 4, 4, 1, 18, 2, 3, 14, 11, 4, 29, 4, 2, 7, 1, 3, 13, 9, 2, 2,
5,
3, 5, 20, 7, 16, 8, 5, 72, 34, 6, 4, 22, 12, 12, 28, 45, 36, 9, 7, 39, 9, 191, 1, 1, 1, 4, 11, 8, 4,
9, 2, 3, 22, 1, 1, 1, 1, 4, 17, 1, 7, 7, 1, 11, 31, 10, 2, 4, 8, 2, 3, 2, 1, 4, 2, 16, 4, 32, 2,
3, 19, 13, 4, 9, 1, 5, 2, 14, 8, 1, 1, 3, 6, 19, 6, 5, 1, 16, 6, 2, 10, 8, 5, 1, 2, 3, 1, 5, 5, 1,
11, 6, 6, 1, 3, 3, 2, 6, 3, 8, 1, 1, 4, 10, 7, 5, 7, 7, 5, 8, 9, 2, 1, 3, 4, 1, 1, 3, 1, 3, 3, 2, 6,
16,
1, 4, 6, 3, 1, 10, 6, 1, 3, 15, 2, 9, 2, 10, 25, 13, 9, 16, 6, 2, 2, 10, 11, 4, 3, 9, 1, 2, 6, 6, 5,
4, 30, 40, 1, 10, 7, 12, 14, 33, 6, 3, 6, 7, 3, 1, 3, 1, 11, 14, 4, 9, 5, 12, 11, 49, 18, 51, 31,
140, 31, 2, 2, 1, 5, 1, 8, 1, 10, 1, 4, 4, 3, 24, 1, 10, 1, 3, 6, 6, 16, 3, 4, 5, 2, 1, 4, 2, 57,
10, 6, 22, 2, 22, 3, 7, 22, 6, 10, 11, 36, 18, 16, 33, 36, 2, 5, 5, 1, 1, 1, 4, 10, 1, 4, 13, 2, 7,
5, 2, 9, 3, 4, 1, 7, 43, 3, 7, 3, 9, 14, 7, 9, 1, 11, 1, 1, 3, 7, 4, 18, 13, 1, 14, 1, 3, 6, 10, 73,
2, 2, 30, 6, 1, 11, 18, 19, 13, 22, 3, 46, 42, 37, 89, 7, 3, 16, 34, 2, 2, 3, 9, 1, 7, 1, 1, 1, 2,
2, 4, 10, 7, 3, 10, 3, 9, 5, 28, 9, 2, 6, 13, 7, 3, 1, 3, 10, 2, 7, 2, 11, 3, 6, 21, 54, 85, 2, 1,
4, 2, 2, 1, 39, 3, 21, 2, 2, 5, 1, 1, 1, 4, 1, 1, 3, 4, 15, 1, 3, 2, 4, 4, 2, 3, 8, 2, 20, 1, 8, 7,
13,
4, 1, 26, 6, 2, 9, 34, 4, 21, 52, 10, 4, 4, 1, 5, 12, 2, 11, 1, 7, 2, 30, 12, 44, 2, 30, 1, 1, 3, 6,
16, 9, 17, 39, 82, 2, 2, 24, 7, 1, 7, 3, 16, 9, 14, 44, 2, 1, 2, 1, 2, 3, 5, 2, 4, 1, 6, 7, 5, 3,
2, 6, 1, 11, 5, 11, 2, 1, 18, 19, 8, 1, 3, 24, 29, 2, 1, 3, 5, 2, 2, 1, 13, 6, 5, 1, 46, 11, 3, 5,
1, 1, 5, 8, 2, 10, 6, 12, 6, 3, 7, 11, 2, 4, 16, 13, 2, 5, 1, 1, 2, 2, 5, 2, 28, 5, 2, 23, 10, 8, 4,
4, 22, 39, 95, 38, 8, 14, 9, 5, 1, 13, 5, 4, 3, 13, 12, 11, 1, 9, 1, 27, 37, 2, 5, 4, 4, 63, 211,
95, 2, 2, 2, 1, 3, 5, 2, 1, 1, 2, 2, 1, 1, 1, 3, 2, 4, 1, 2, 1, 1, 5, 2, 2, 1, 1, 2, 3, 1, 3, 1, 1,
1,
3, 1, 4, 2, 1, 3, 6, 1, 1, 3, 7, 15, 5, 3, 2, 5, 3, 9, 11, 4, 2, 22, 1, 6, 3, 8, 7, 1, 4, 28, 4, 16,
3, 3, 25, 4, 4, 27, 27, 1, 4, 1, 2, 2, 7, 1, 3, 5, 2, 28, 8, 2, 14, 1, 8, 6, 16, 25, 3, 3, 3, 14, 3,
3, 1, 1, 2, 1, 4, 6, 3, 8, 4, 1, 1, 1, 2, 3, 6, 10, 6, 2, 3, 18, 3, 2, 5, 5, 4, 3, 1, 5, 2, 5, 4,
23, 7, 6, 12, 6, 4, 17, 11, 9, 5, 1, 1, 10, 5, 12, 1, 1, 11, 26, 33, 7, 3, 6, 1, 17, 7, 1, 5, 12, 1,
11,
2, 4, 1, 8, 14, 17, 23, 1, 2, 1, 7, 8, 16, 11, 9, 6, 5, 2, 6, 4, 16, 2, 8, 14, 1, 11, 8, 9, 1, 1, 1,
9, 25, 4, 11, 19, 7, 2, 15, 2, 12, 8, 52, 7, 5, 19, 2, 16, 4, 36, 8, 1, 16, 8, 24, 26, 4, 6, 2, 9,
5, 4, 36, 3, 28, 12, 25, 15, 37, 27, 17, 12, 59, 38, 5, 32, 127, 1, 2, 9, 17, 14, 4, 1, 2, 1, 1, 8,
11, 50, 4, 14, 2, 19, 16, 4, 17, 5, 4, 5, 26, 12, 45, 2, 23, 45, 104, 30, 12, 8, 3, 10, 2, 2,
3, 3, 1, 4, 20, 7, 2, 9, 6, 15, 2, 20, 1, 3, 16, 4, 11, 15, 6, 134, 2, 5, 59, 1, 2, 2, 2, 1, 9, 17,
3, 26, 137, 10, 211, 59, 1, 2, 4, 1, 4, 1, 1, 1, 2, 6, 2, 3, 1, 1, 2, 3, 2, 3, 1, 3, 4, 4, 2, 3, 3,
1, 4, 3, 1, 7, 2, 2, 3, 1, 2, 1, 3, 3, 3, 2, 2, 3, 2, 1, 3, 14, 6, 1, 3, 2, 9, 6, 15, 27, 9, 34,
145, 1, 1, 2, 1, 1, 1, 1, 2, 1, 1, 1, 1, 2, 2, 2, 3, 1, 2, 1, 1, 1, 2, 3, 5, 8, 3, 5, 2, 4, 1, 3, 2,
2, 2, 12,
4, 1, 1, 1, 10, 4, 5, 1, 20, 4, 16, 1, 15, 9, 5, 12, 2, 9, 2, 5, 4, 2, 26, 19, 7, 1, 26, 4, 30, 12,
15, 42, 1, 6, 8, 172, 1, 1, 4, 2, 1, 1, 11, 2, 2, 4, 2, 1, 2, 1, 10, 8, 1, 2, 1, 4, 5, 1, 2, 5, 1,
8,
4, 1, 3, 4, 2, 1, 6, 2, 1, 3, 4, 1, 2, 1, 1, 1, 1, 12, 5, 7, 2, 4, 3, 1, 1, 1, 3, 3, 6, 1, 2, 2, 3,
3, 3, 2, 1, 2, 12, 14, 11, 6, 6, 4, 12, 2, 8, 1, 7, 10, 1, 35, 7, 4, 13, 15, 4, 3, 23, 21, 28, 52,
5,
26, 5, 6, 1, 7, 10, 2, 7, 53, 3, 2, 1, 1, 1, 2, 163, 532, 1, 10, 11, 1, 3, 3, 4, 8, 2, 8, 6, 2, 2,
23, 22, 4, 2, 2, 4, 2, 1, 3, 1, 3, 3, 5, 9, 8, 2, 1, 2, 8, 1, 10, 2, 12, 21, 20, 15, 105, 2, 3, 1,
1,
3, 2, 3, 1, 1, 2, 5, 1, 4, 15, 11, 19, 1, 1, 1, 1, 5, 4, 5, 1, 1, 2, 5, 3, 5, 12, 1, 2, 5, 1, 11, 1,
1, 15, 9, 1, 4, 5, 3, 26, 8, 2, 1, 3, 1, 1, 15, 19, 2, 12, 1, 2, 5, 2, 7, 2, 19, 2, 20, 6, 26, 7, 5,
2, 2, 7, 34, 21, 13, 70, 2, 128, 1, 1, 2, 1, 1, 2, 1, 1, 3, 2, 2, 2, 15, 1, 4, 1, 3, 4, 42, 10, 6,
1, 49, 85, 8, 1, 2, 1, 1, 4, 4, 2, 3, 6, 1, 5, 7, 4, 3, 211, 4, 1, 2, 1, 2, 5, 1, 2, 4, 2, 2, 6, 5,
6,
10, 3, 4, 48, 100, 6, 2, 16, 296, 5, 27, 387, 2, 2, 3, 7, 16, 8, 5, 38, 15, 39, 21, 9, 10, 3, 7, 59,
13, 27, 21, 47, 5, 21, 6
};
static ImWchar base_ranges[] = // not zero-terminated
{
0x0020, 0x00FF, // Basic Latin + Latin Supplement
0x3000, 0x30FF, // Punctuations, Hiragana, Katakana
0x31F0, 0x31FF, // Katakana Phonetic Extensions
0xFF00, 0xFFEF, // Half-width characters
};
static ImWchar full_ranges[
IM_ARRAYSIZE(base_ranges) + IM_ARRAYSIZE(accumulative_offsets_from_0x4E00) * 2 + 1] = {0};
if (!full_ranges[0]) {
memcpy(full_ranges, base_ranges, sizeof(base_ranges));
UnpackAccumulativeOffsetsIntoRanges(0x4E00, accumulative_offsets_from_0x4E00,
IM_ARRAYSIZE(accumulative_offsets_from_0x4E00),
full_ranges + IM_ARRAYSIZE(base_ranges));
}
return &full_ranges[0];
}
const ImWchar *ImFontAtlas::GetGlyphRangesJapanese() {
// 1946 common ideograms code points for Japanese
// Sourced from http://theinstructionlimit.com/common-kanji-character-ranges-for-xna-spritefont-rendering
// FIXME: Source a list of the revised 2136 Joyo Kanji list from 2010 and rebuild this.
// You can use ImFontAtlas::GlyphRangesBuilder to create your own ranges derived from this, by merging existing ranges or adding new characters.
// (Stored as accumulative offsets from the initial unicode codepoint 0x4E00. This encoding is designed to helps us compact the source code size.)
static const short accumulative_offsets_from_0x4E00[] =
{
0, 1, 2, 4, 1, 1, 1, 1, 2, 1, 6, 2, 2, 1, 8, 5, 7, 11, 1, 2, 10, 10, 8, 2, 4, 20, 2, 11, 8, 2, 1, 2,
1, 6, 2, 1, 7, 5, 3, 7, 1, 1, 13, 7, 9, 1, 4, 6, 1, 2, 1, 10, 1, 1, 9, 2, 2, 4, 5, 6, 14, 1, 1, 9,
3, 18,
5, 4, 2, 2, 10, 7, 1, 1, 1, 3, 2, 4, 3, 23, 2, 10, 12, 2, 14, 2, 4, 13, 1, 6, 10, 3, 1, 7, 13, 6, 4,
13, 5, 2, 3, 17, 2, 2, 5, 7, 6, 4, 1, 7, 14, 16, 6, 13, 9, 15, 1, 1, 7, 16, 4, 7, 1, 19, 9, 2, 7,
15,
2, 6, 5, 13, 25, 4, 14, 13, 11, 25, 1, 1, 1, 2, 1, 2, 2, 3, 10, 11, 3, 3, 1, 1, 4, 4, 2, 1, 4, 9, 1,
4, 3, 5, 5, 2, 7, 12, 11, 15, 7, 16, 4, 5, 16, 2, 1, 1, 6, 3, 3, 1, 1, 2, 7, 6, 6, 7, 1, 4, 7, 6, 1,
1,
2, 1, 12, 3, 3, 9, 5, 8, 1, 11, 1, 2, 3, 18, 20, 4, 1, 3, 6, 1, 7, 3, 5, 5, 7, 2, 2, 12, 3, 1, 4, 2,
3, 2, 3, 11, 8, 7, 4, 17, 1, 9, 25, 1, 1, 4, 2, 2, 4, 1, 2, 7, 1, 1, 1, 3, 1, 2, 6, 16, 1, 2, 1, 1,
3, 12,
20, 2, 5, 20, 8, 7, 6, 2, 1, 1, 1, 1, 6, 2, 1, 2, 10, 1, 1, 6, 1, 3, 1, 2, 1, 4, 1, 12, 4, 1, 3, 1,
1, 1, 1, 1, 10, 4, 7, 5, 13, 1, 15, 1, 1, 30, 11, 9, 1, 15, 38, 14, 1, 32, 17, 20, 1, 9, 31, 2, 21,
9,
4, 49, 22, 2, 1, 13, 1, 11, 45, 35, 43, 55, 12, 19, 83, 1, 3, 2, 3, 13, 2, 1, 7, 3, 18, 3, 13, 8, 1,
8, 18, 5, 3, 7, 25, 24, 9, 24, 40, 3, 17, 24, 2, 1, 6, 2, 3, 16, 15, 6, 7, 3, 12, 1, 9, 7, 3, 3,
3, 15, 21, 5, 16, 4, 5, 12, 11, 11, 3, 6, 3, 2, 31, 3, 2, 1, 1, 23, 6, 6, 1, 4, 2, 6, 5, 2, 1, 1, 3,
3, 22, 2, 6, 2, 3, 17, 3, 2, 4, 5, 1, 9, 5, 1, 1, 6, 15, 12, 3, 17, 2, 14, 2, 8, 1, 23, 16, 4, 2,
23,
8, 15, 23, 20, 12, 25, 19, 47, 11, 21, 65, 46, 4, 3, 1, 5, 6, 1, 2, 5, 26, 2, 1, 1, 3, 11, 1, 1, 1,
2, 1, 2, 3, 1, 1, 10, 2, 3, 1, 1, 1, 3, 6, 3, 2, 2, 6, 6, 9, 2, 2, 2, 6, 2, 5, 10, 2, 4, 1, 2, 1, 2,
2,
3, 1, 1, 3, 1, 2, 9, 23, 9, 2, 1, 1, 1, 1, 5, 3, 2, 1, 10, 9, 6, 1, 10, 2, 31, 25, 3, 7, 5, 40, 1,
15, 6, 17, 7, 27, 180, 1, 3, 2, 2, 1, 1, 1, 6, 3, 10, 7, 1, 3, 6, 17, 8, 6, 2, 2, 1, 3, 5, 5, 8, 16,
14,
15, 1, 1, 4, 1, 2, 1, 1, 1, 3, 2, 7, 5, 6, 2, 5, 10, 1, 4, 2, 9, 1, 1, 11, 6, 1, 44, 1, 3, 7, 9, 5,
1, 3, 1, 1, 10, 7, 1, 10, 4, 2, 7, 21, 15, 7, 2, 5, 1, 8, 3, 4, 1, 3, 1, 6, 1, 4, 2, 1, 4, 10, 8, 1,
4, 5,
1, 5, 10, 2, 7, 1, 10, 1, 1, 3, 4, 11, 10, 29, 4, 7, 3, 5, 2, 3, 33, 5, 2, 19, 3, 1, 4, 2, 6, 31,
11, 1, 3, 3, 3, 1, 8, 10, 9, 12, 11, 12, 8, 3, 14, 8, 6, 11, 1, 4, 41, 3, 1, 2, 7, 13, 1, 5, 6, 2,
6, 12,
12, 22, 5, 9, 4, 8, 9, 9, 34, 6, 24, 1, 1, 20, 9, 9, 3, 4, 1, 7, 2, 2, 2, 6, 2, 28, 5, 3, 6, 1, 4,
6, 7, 4, 2, 1, 4, 2, 13, 6, 4, 4, 3, 1, 8, 8, 3, 2, 1, 5, 1, 2, 2, 3, 1, 11, 11, 7, 3, 6, 10, 8, 6,
16, 16,
22, 7, 12, 6, 21, 5, 4, 6, 6, 3, 6, 1, 3, 2, 1, 2, 8, 29, 1, 10, 1, 6, 13, 6, 6, 19, 31, 1, 13, 4,
4, 22, 17, 26, 33, 10, 4, 15, 12, 25, 6, 67, 10, 2, 3, 1, 6, 10, 2, 6, 2, 9, 1, 9, 4, 4, 1, 2, 16,
2,
5, 9, 2, 3, 8, 1, 8, 3, 9, 4, 8, 6, 4, 8, 11, 3, 2, 1, 1, 3, 26, 1, 7, 5, 1, 11, 1, 5, 3, 5, 2, 13,
6, 39, 5, 1, 5, 2, 11, 6, 10, 5, 1, 15, 5, 3, 6, 19, 21, 22, 2, 4, 1, 6, 1, 8, 1, 4, 8, 2, 4, 2, 2,
9, 2,
1, 1, 1, 4, 3, 6, 3, 12, 7, 1, 14, 2, 4, 10, 2, 13, 1, 17, 7, 3, 2, 1, 3, 2, 13, 7, 14, 12, 3, 1,
29, 2, 8, 9, 15, 14, 9, 14, 1, 3, 1, 6, 5, 9, 11, 3, 38, 43, 20, 7, 7, 8, 5, 15, 12, 19, 15, 81, 8,
7,
1, 5, 73, 13, 37, 28, 8, 8, 1, 15, 18, 20, 165, 28, 1, 6, 11, 8, 4, 14, 7, 15, 1, 3, 3, 6, 4, 1, 7,
14, 1, 1, 11, 30, 1, 5, 1, 4, 14, 1, 4, 2, 7, 52, 2, 6, 29, 3, 1, 9, 1, 21, 3, 5, 1, 26, 3, 11, 14,
11, 1, 17, 5, 1, 2, 1, 3, 2, 8, 1, 2, 9, 12, 1, 1, 2, 3, 8, 3, 24, 12, 7, 7, 5, 17, 3, 3, 3, 1, 23,
10, 4, 4, 6, 3, 1, 16, 17, 22, 3, 10, 21, 16, 16, 6, 4, 10, 2, 1, 1, 2, 8, 8, 6, 5, 3, 3, 3, 39, 25,
15, 1, 1, 16, 6, 7, 25, 15, 6, 6, 12, 1, 22, 13, 1, 4, 9, 5, 12, 2, 9, 1, 12, 28, 8, 3, 5, 10, 22,
60, 1, 2, 40, 4, 61, 63, 4, 1, 13, 12, 1, 4, 31, 12, 1, 14, 89, 5, 16, 6, 29, 14, 2, 5, 49, 18, 18,
5, 29, 33, 47, 1, 17, 1, 19, 12, 2, 9, 7, 39, 12, 3, 7, 12, 39, 3, 1, 46, 4, 12, 3, 8, 9, 5, 31, 15,
18, 3, 2, 2, 66, 19, 13, 17, 5, 3, 46, 124, 13, 57, 34, 2, 5, 4, 5, 8, 1, 1, 1, 4, 3, 1, 17, 5,
3, 5, 3, 1, 8, 5, 6, 3, 27, 3, 26, 7, 12, 7, 2, 17, 3, 7, 18, 78, 16, 4, 36, 1, 2, 1, 6, 2, 1, 39,
17, 7, 4, 13, 4, 4, 4, 1, 10, 4, 2, 4, 6, 3, 10, 1, 19, 1, 26, 2, 4, 33, 2, 73, 47, 7, 3, 8, 2, 4,
15,
18, 1, 29, 2, 41, 14, 1, 21, 16, 41, 7, 39, 25, 13, 44, 2, 2, 10, 1, 13, 7, 1, 7, 3, 5, 20, 4, 8, 2,
49, 1, 10, 6, 1, 6, 7, 10, 7, 11, 16, 3, 12, 20, 4, 10, 3, 1, 2, 11, 2, 28, 9, 2, 4, 7, 2, 15, 1,
27, 1, 28, 17, 4, 5, 10, 7, 3, 24, 10, 11, 6, 26, 3, 2, 7, 2, 2, 49, 16, 10, 16, 15, 4, 5, 27, 61,
30, 14, 38, 22, 2, 7, 5, 1, 3, 12, 23, 24, 17, 17, 3, 3, 2, 4, 1, 6, 2, 7, 5, 1, 1, 5, 1, 1, 9, 4,
1, 3, 6, 1, 8, 2, 8, 4, 14, 3, 5, 11, 4, 1, 3, 32, 1, 19, 4, 1, 13, 11, 5, 2, 1, 8, 6, 8, 1, 6, 5,
13, 3, 23, 11, 5, 3, 16, 3, 9, 10, 1, 24, 3, 198, 52, 4, 2, 2, 5, 14, 5, 4, 22, 5, 20, 4, 11, 6, 41,
1, 5, 2, 2, 11, 5, 2, 28, 35, 8, 22, 3, 18, 3, 10, 7, 5, 3, 4, 1, 5, 3, 8, 9, 3, 6, 2, 16, 22, 4, 5,
5, 3, 3, 18, 23, 2, 6, 23, 5, 27, 8, 1, 33, 2, 12, 43, 16, 5, 2, 3, 6, 1, 20, 4, 2, 9, 7, 1, 11, 2,
10, 3, 14, 31, 9, 3, 25, 18, 20, 2, 5, 5, 26, 14, 1, 11, 17, 12, 40, 19, 9, 6, 31, 83, 2, 7, 9, 19,
78, 12, 14, 21, 76, 12, 113, 79, 34, 4, 1, 1, 61, 18, 85, 10, 2, 2, 13, 31, 11, 50, 6, 33, 159,
179, 6, 6, 7, 4, 4, 2, 4, 2, 5, 8, 7, 20, 32, 22, 1, 3, 10, 6, 7, 28, 5, 10, 9, 2, 77, 19, 13, 2, 5,
1, 4, 4, 7, 4, 13, 3, 9, 31, 17, 3, 26, 2, 6, 6, 5, 4, 1, 7, 11, 3, 4, 2, 1, 6, 2, 20, 4, 1, 9, 2,
6,
3, 7, 1, 1, 1, 20, 2, 3, 1, 6, 2, 3, 6, 2, 4, 8, 1, 5, 13, 8, 4, 11, 23, 1, 10, 6, 2, 1, 3, 21, 2,
2, 4, 24, 31, 4, 10, 10, 2, 5, 192, 15, 4, 16, 7, 9, 51, 1, 2, 1, 1, 5, 1, 1, 2, 1, 3, 5, 3, 1, 3,
4, 1,
3, 1, 3, 3, 9, 8, 1, 2, 2, 2, 4, 4, 18, 12, 92, 2, 10, 4, 3, 14, 5, 25, 16, 42, 4, 14, 4, 2, 21, 5,
126, 30, 31, 2, 1, 5, 13, 3, 22, 5, 6, 6, 20, 12, 1, 14, 12, 87, 3, 19, 1, 8, 2, 9, 9, 3, 3, 23, 2,
3, 7, 6, 3, 1, 2, 3, 9, 1, 3, 1, 6, 3, 2, 1, 3, 11, 3, 1, 6, 10, 3, 2, 3, 1, 2, 1, 5, 1, 1, 11, 3,
6, 4, 1, 7, 2, 1, 2, 5, 5, 34, 4, 14, 18, 4, 19, 7, 5, 8, 2, 6, 79, 1, 5, 2, 14, 8, 2, 9, 2, 1, 36,
28, 16,
4, 1, 1, 1, 2, 12, 6, 42, 39, 16, 23, 7, 15, 15, 3, 2, 12, 7, 21, 64, 6, 9, 28, 8, 12, 3, 3, 41, 59,
24, 51, 55, 57, 294, 9, 9, 2, 6, 2, 15, 1, 2, 13, 38, 90, 9, 9, 9, 3, 11, 7, 1, 1, 1, 5, 6, 3, 2,
1, 2, 2, 3, 8, 1, 4, 4, 1, 5, 7, 1, 4, 3, 20, 4, 9, 1, 1, 1, 5, 5, 17, 1, 5, 2, 6, 2, 4, 1, 4, 5, 7,
3, 18, 11, 11, 32, 7, 5, 4, 7, 11, 127, 8, 4, 3, 3, 1, 10, 1, 1, 6, 21, 14, 1, 16, 1, 7, 1, 3, 6, 9,
65,
51, 4, 3, 13, 3, 10, 1, 1, 12, 9, 21, 110, 3, 19, 24, 1, 1, 10, 62, 4, 1, 29, 42, 78, 28, 20, 18,
82, 6, 3, 15, 6, 84, 58, 253, 15, 155, 264, 15, 21, 9, 14, 7, 58, 40, 39,
};
static ImWchar base_ranges[] = // not zero-terminated
{
0x0020, 0x00FF, // Basic Latin + Latin Supplement
0x3000, 0x30FF, // Punctuations, Hiragana, Katakana
0x31F0, 0x31FF, // Katakana Phonetic Extensions
0xFF00, 0xFFEF, // Half-width characters
};
static ImWchar full_ranges[
IM_ARRAYSIZE(base_ranges) + IM_ARRAYSIZE(accumulative_offsets_from_0x4E00) * 2 + 1] = {0};
if (!full_ranges[0]) {
memcpy(full_ranges, base_ranges, sizeof(base_ranges));
UnpackAccumulativeOffsetsIntoRanges(0x4E00, accumulative_offsets_from_0x4E00,
IM_ARRAYSIZE(accumulative_offsets_from_0x4E00),
full_ranges + IM_ARRAYSIZE(base_ranges));
}
return &full_ranges[0];
}
const ImWchar *ImFontAtlas::GetGlyphRangesCyrillic() {
static const ImWchar ranges[] =
{
0x0020, 0x00FF, // Basic Latin + Latin Supplement
0x0400, 0x052F, // Cyrillic + Cyrillic Supplement
0x2DE0, 0x2DFF, // Cyrillic Extended-A
0xA640, 0xA69F, // Cyrillic Extended-B
0,
};
return &ranges[0];
}
const ImWchar *ImFontAtlas::GetGlyphRangesThai() {
static const ImWchar ranges[] =
{
0x0020, 0x00FF, // Basic Latin
0x2010, 0x205E, // Punctuations
0x0E00, 0x0E7F, // Thai
0,
};
return &ranges[0];
}
//-----------------------------------------------------------------------------
// ImFontAtlas::GlyphRangesBuilder
//-----------------------------------------------------------------------------
void ImFontAtlas::GlyphRangesBuilder::AddText(const char *text, const char *text_end) {
while (text_end ? (text < text_end) : *text) {
unsigned int c = 0;
int c_len = ImTextCharFromUtf8(&c, text, text_end);
text += c_len;
if (c_len == 0)
break;
if (c < 0x10000)
AddChar((ImWchar) c);
}
}
void ImFontAtlas::GlyphRangesBuilder::AddRanges(const ImWchar *ranges) {
for (; ranges[0]; ranges += 2)
for (ImWchar c = ranges[0]; c <= ranges[1]; c++)
AddChar(c);
}
void ImFontAtlas::GlyphRangesBuilder::BuildRanges(ImVector<ImWchar> *out_ranges) {
for (int n = 0; n < 0x10000; n++)
if (GetBit(n)) {
out_ranges->push_back((ImWchar) n);
while (n < 0x10000 && GetBit(n + 1))
n++;
out_ranges->push_back((ImWchar) n);
}
out_ranges->push_back(0);
}
//-----------------------------------------------------------------------------
// ImFont
//-----------------------------------------------------------------------------
ImFont::ImFont() {
Scale = 1.0f;
FallbackChar = (ImWchar) '?';
DisplayOffset = ImVec2(0.0f, 0.0f);
ClearOutputData();
}
ImFont::~ImFont() {
// Invalidate active font so that the user gets a clear crash instead of a dangling pointer.
// If you want to delete fonts you need to do it between Render() and NewFrame().
// FIXME-CLEANUP
/*
ImGuiContext& g = *GImGui;
if (g.Font == this)
g.Font = NULL;
*/
ClearOutputData();
}
void ImFont::ClearOutputData() {
FontSize = 0.0f;
Glyphs.clear();
IndexAdvanceX.clear();
IndexLookup.clear();
FallbackGlyph = NULL;
FallbackAdvanceX = 0.0f;
ConfigDataCount = 0;
ConfigData = NULL;
ContainerAtlas = NULL;
Ascent = Descent = 0.0f;
DirtyLookupTables = true;
MetricsTotalSurface = 0;
}
void ImFont::BuildLookupTable() {
int max_codepoint = 0;
for (int i = 0; i != Glyphs.Size; i++)
max_codepoint = ImMax(max_codepoint, (int) Glyphs[i].Codepoint);
IM_ASSERT(Glyphs.Size < 0xFFFF); // -1 is reserved
IndexAdvanceX.clear();
IndexLookup.clear();
DirtyLookupTables = false;
GrowIndex(max_codepoint + 1);
for (int i = 0; i < Glyphs.Size; i++) {
int codepoint = (int) Glyphs[i].Codepoint;
IndexAdvanceX[codepoint] = Glyphs[i].AdvanceX;
IndexLookup[codepoint] = (unsigned short) i;
}
// Create a glyph to handle TAB
// FIXME: Needs proper TAB handling but it needs to be contextualized (or we could arbitrary say that each string starts at "column 0" ?)
if (FindGlyph((unsigned short) ' ')) {
if (Glyphs.back().Codepoint != '\t') // So we can call this function multiple times
Glyphs.resize(Glyphs.Size + 1);
ImFontGlyph &tab_glyph = Glyphs.back();
tab_glyph = *FindGlyph((unsigned short) ' ');
tab_glyph.Codepoint = '\t';
tab_glyph.AdvanceX *= 4;
IndexAdvanceX[(int) tab_glyph.Codepoint] = (float) tab_glyph.AdvanceX;
IndexLookup[(int) tab_glyph.Codepoint] = (unsigned short) (Glyphs.Size - 1);
}
FallbackGlyph = FindGlyphNoFallback(FallbackChar);
FallbackAdvanceX = FallbackGlyph ? FallbackGlyph->AdvanceX : 0.0f;
for (int i = 0; i < max_codepoint + 1; i++)
if (IndexAdvanceX[i] < 0.0f)
IndexAdvanceX[i] = FallbackAdvanceX;
}
void ImFont::SetFallbackChar(ImWchar c) {
FallbackChar = c;
BuildLookupTable();
}
void ImFont::GrowIndex(int new_size) {
IM_ASSERT(IndexAdvanceX.Size == IndexLookup.Size);
if (new_size <= IndexLookup.Size)
return;
IndexAdvanceX.resize(new_size, -1.0f);
IndexLookup.resize(new_size, (unsigned short) -1);
}
void ImFont::AddGlyph(ImWchar codepoint, float x0, float y0, float x1, float y1, float u0, float v0, float u1, float v1,
float advance_x) {
Glyphs.resize(Glyphs.Size + 1);
ImFontGlyph &glyph = Glyphs.back();
glyph.Codepoint = (ImWchar) codepoint;
glyph.X0 = x0;
glyph.Y0 = y0;
glyph.X1 = x1;
glyph.Y1 = y1;
glyph.U0 = u0;
glyph.V0 = v0;
glyph.U1 = u1;
glyph.V1 = v1;
glyph.AdvanceX = advance_x + ConfigData->GlyphExtraSpacing.x; // Bake spacing into AdvanceX
if (ConfigData->PixelSnapH)
glyph.AdvanceX = (float) (int) (glyph.AdvanceX + 0.5f);
// Compute rough surface usage metrics (+1 to account for average padding, +0.99 to round)
DirtyLookupTables = true;
MetricsTotalSurface += (int) ((glyph.U1 - glyph.U0) * ContainerAtlas->TexWidth + 1.99f) *
(int) ((glyph.V1 - glyph.V0) * ContainerAtlas->TexHeight + 1.99f);
}
void ImFont::AddRemapChar(ImWchar dst, ImWchar src, bool overwrite_dst) {
IM_ASSERT(IndexLookup.Size >
0); // Currently this can only be called AFTER the font has been built, aka after calling ImFontAtlas::GetTexDataAs*() function.
int index_size = IndexLookup.Size;
if (dst < index_size && IndexLookup.Data[dst] == (unsigned short) -1 && !overwrite_dst) // 'dst' already exists
return;
if (src >= index_size && dst >= index_size) // both 'dst' and 'src' don't exist -> no-op
return;
GrowIndex(dst + 1);
IndexLookup[dst] = (src < index_size) ? IndexLookup.Data[src] : (unsigned short) -1;
IndexAdvanceX[dst] = (src < index_size) ? IndexAdvanceX.Data[src] : 1.0f;
}
const ImFontGlyph *ImFont::FindGlyph(ImWchar c) const {
if (c >= IndexLookup.Size)
return FallbackGlyph;
const unsigned short i = IndexLookup[c];
if (i == (unsigned short) -1)
return FallbackGlyph;
return &Glyphs.Data[i];
}
const ImFontGlyph *ImFont::FindGlyphNoFallback(ImWchar c) const {
if (c >= IndexLookup.Size)
return NULL;
const unsigned short i = IndexLookup[c];
if (i == (unsigned short) -1)
return NULL;
return &Glyphs.Data[i];
}
const char *ImFont::CalcWordWrapPositionA(float scale, const char *text, const char *text_end, float wrap_width) const {
// Simple word-wrapping for English, not full-featured. Please submit failing cases!
// FIXME: Much possible improvements (don't cut things like "word !", "word!!!" but cut within "word,,,,", more sensible support for punctuations, support for Unicode punctuations, etc.)
// For references, possible wrap point marked with ^
// "aaa bbb, ccc,ddd. eee fff. ggg!"
// ^ ^ ^ ^ ^__ ^ ^
// List of hardcoded separators: .,;!?'"
// Skip extra blanks after a line returns (that includes not counting them in width computation)
// e.g. "Hello world" --> "Hello" "World"
// Cut words that cannot possibly fit within one line.
// e.g.: "The tropical fish" with ~5 characters worth of width --> "The tr" "opical" "fish"
float line_width = 0.0f;
float word_width = 0.0f;
float blank_width = 0.0f;
wrap_width /= scale; // We work with unscaled widths to avoid scaling every characters
const char *word_end = text;
const char *prev_word_end = NULL;
bool inside_word = true;
const char *s = text;
while (s < text_end) {
unsigned int c = (unsigned int) *s;
const char *next_s;
if (c < 0x80)
next_s = s + 1;
else
next_s = s + ImTextCharFromUtf8(&c, s, text_end);
if (c == 0)
break;
if (c < 32) {
if (c == '\n') {
line_width = word_width = blank_width = 0.0f;
inside_word = true;
s = next_s;
continue;
}
if (c == '\r') {
s = next_s;
continue;
}
}
const float char_width = ((int) c < IndexAdvanceX.Size ? IndexAdvanceX[(int) c] : FallbackAdvanceX);
if (ImCharIsBlankW(c)) {
if (inside_word) {
line_width += blank_width;
blank_width = 0.0f;
word_end = s;
}
blank_width += char_width;
inside_word = false;
} else {
word_width += char_width;
if (inside_word) {
word_end = next_s;
} else {
prev_word_end = word_end;
line_width += word_width + blank_width;
word_width = blank_width = 0.0f;
}
// Allow wrapping after punctuation.
inside_word = !(c == '.' || c == ',' || c == ';' || c == '!' || c == '?' || c == '\"');
}
// We ignore blank width at the end of the line (they can be skipped)
if (line_width + word_width >= wrap_width) {
// Words that cannot possibly fit within an entire line will be cut anywhere.
if (word_width < wrap_width)
s = prev_word_end ? prev_word_end : word_end;
break;
}
s = next_s;
}
return s;
}
ImVec2
ImFont::CalcTextSizeA(float size, float max_width, float wrap_width, const char *text_begin, const char *text_end,
const char **remaining) const {
if (!text_end)
text_end = text_begin + strlen(text_begin); // FIXME-OPT: Need to avoid this.
const float line_height = size;
const float scale = size / FontSize;
ImVec2 text_size = ImVec2(0, 0);
float line_width = 0.0f;
const bool word_wrap_enabled = (wrap_width > 0.0f);
const char *word_wrap_eol = NULL;
const char *s = text_begin;
while (s < text_end) {
if (word_wrap_enabled) {
// Calculate how far we can render. Requires two passes on the string data but keeps the code simple and not intrusive for what's essentially an uncommon feature.
if (!word_wrap_eol) {
word_wrap_eol = CalcWordWrapPositionA(scale, s, text_end, wrap_width - line_width);
if (word_wrap_eol ==
s) // Wrap_width is too small to fit anything. Force displaying 1 character to minimize the height discontinuity.
word_wrap_eol++; // +1 may not be a character start point in UTF-8 but it's ok because we use s >= word_wrap_eol below
}
if (s >= word_wrap_eol) {
if (text_size.x < line_width)
text_size.x = line_width;
text_size.y += line_height;
line_width = 0.0f;
word_wrap_eol = NULL;
// Wrapping skips upcoming blanks
while (s < text_end) {
const char c = *s;
if (ImCharIsBlankA(c)) { s++; }
else if (c == '\n') {
s++;
break;
}
else { break; }
}
continue;
}
}
// Decode and advance source
const char *prev_s = s;
unsigned int c = (unsigned int) *s;
if (c < 0x80) {
s += 1;
} else {
s += ImTextCharFromUtf8(&c, s, text_end);
if (c == 0) // Malformed UTF-8?
break;
}
if (c < 32) {
if (c == '\n') {
text_size.x = ImMax(text_size.x, line_width);
text_size.y += line_height;
line_width = 0.0f;
continue;
}
if (c == '\r')
continue;
}
const float char_width = ((int) c < IndexAdvanceX.Size ? IndexAdvanceX[(int) c] : FallbackAdvanceX) * scale;
if (line_width + char_width >= max_width) {
s = prev_s;
break;
}
line_width += char_width;
}
if (text_size.x < line_width)
text_size.x = line_width;
if (line_width > 0 || text_size.y == 0.0f)
text_size.y += line_height;
if (remaining)
*remaining = s;
return text_size;
}
void ImFont::RenderChar(ImDrawList *draw_list, float size, ImVec2 pos, ImU32 col, unsigned short c) const {
if (c == ' ' || c == '\t' || c == '\n' ||
c == '\r') // Match behavior of RenderText(), those 4 codepoints are hard-coded.
return;
if (const ImFontGlyph *glyph = FindGlyph(c)) {
float scale = (size >= 0.0f) ? (size / FontSize) : 1.0f;
pos.x = (float) (int) pos.x + DisplayOffset.x;
pos.y = (float) (int) pos.y + DisplayOffset.y;
draw_list->PrimReserve(6, 4);
draw_list->PrimRectUV(ImVec2(pos.x + glyph->X0 * scale, pos.y + glyph->Y0 * scale),
ImVec2(pos.x + glyph->X1 * scale, pos.y + glyph->Y1 * scale),
ImVec2(glyph->U0, glyph->V0), ImVec2(glyph->U1, glyph->V1), col);
}
}
void ImFont::RenderText(ImDrawList *draw_list, float size, ImVec2 pos, ImU32 col, const ImVec4 &clip_rect,
const char *text_begin, const char *text_end, float wrap_width, bool cpu_fine_clip) const {
if (!text_end)
text_end = text_begin +
strlen(text_begin); // ImGui functions generally already provides a valid text_end, so this is merely to handle direct calls.
// Align to be pixel perfect
pos.x = (float) (int) pos.x + DisplayOffset.x;
pos.y = (float) (int) pos.y + DisplayOffset.y;
float x = pos.x;
float y = pos.y;
if (y > clip_rect.w)
return;
const float scale = size / FontSize;
const float line_height = FontSize * scale;
const bool word_wrap_enabled = (wrap_width > 0.0f);
const char *word_wrap_eol = NULL;
// Skip non-visible lines
const char *s = text_begin;
if (!word_wrap_enabled && y + line_height < clip_rect.y)
while (s < text_end && *s != '\n') // Fast-forward to next line
s++;
// Reserve vertices for remaining worse case (over-reserving is useful and easily amortized)
const int vtx_count_max = (int) (text_end - s) * 4;
const int idx_count_max = (int) (text_end - s) * 6;
const int idx_expected_size = draw_list->IdxBuffer.Size + idx_count_max;
draw_list->PrimReserve(idx_count_max, vtx_count_max);
ImDrawVert *vtx_write = draw_list->_VtxWritePtr;
ImDrawIdx *idx_write = draw_list->_IdxWritePtr;
unsigned int vtx_current_idx = draw_list->_VtxCurrentIdx;
while (s < text_end) {
if (word_wrap_enabled) {
// Calculate how far we can render. Requires two passes on the string data but keeps the code simple and not intrusive for what's essentially an uncommon feature.
if (!word_wrap_eol) {
word_wrap_eol = CalcWordWrapPositionA(scale, s, text_end, wrap_width - (x - pos.x));
if (word_wrap_eol ==
s) // Wrap_width is too small to fit anything. Force displaying 1 character to minimize the height discontinuity.
word_wrap_eol++; // +1 may not be a character start point in UTF-8 but it's ok because we use s >= word_wrap_eol below
}
if (s >= word_wrap_eol) {
x = pos.x;
y += line_height;
word_wrap_eol = NULL;
// Wrapping skips upcoming blanks
while (s < text_end) {
const char c = *s;
if (ImCharIsBlankA(c)) { s++; }
else if (c == '\n') {
s++;
break;
}
else { break; }
}
continue;
}
}
// Decode and advance source
unsigned int c = (unsigned int) *s;
if (c < 0x80) {
s += 1;
} else {
s += ImTextCharFromUtf8(&c, s, text_end);
if (c == 0) // Malformed UTF-8?
break;
}
if (c < 32) {
if (c == '\n') {
x = pos.x;
y += line_height;
if (y > clip_rect.w)
break;
if (!word_wrap_enabled && y + line_height < clip_rect.y)
while (s < text_end && *s != '\n') // Fast-forward to next line
s++;
continue;
}
if (c == '\r')
continue;
}
float char_width = 0.0f;
if (const ImFontGlyph *glyph = FindGlyph((unsigned short) c)) {
char_width = glyph->AdvanceX * scale;
// Arbitrarily assume that both space and tabs are empty glyphs as an optimization
if (c != ' ' && c != '\t') {
// We don't do a second finer clipping test on the Y axis as we've already skipped anything before clip_rect.y and exit once we pass clip_rect.w
float x1 = x + glyph->X0 * scale;
float x2 = x + glyph->X1 * scale;
float y1 = y + glyph->Y0 * scale;
float y2 = y + glyph->Y1 * scale;
if (x1 <= clip_rect.z && x2 >= clip_rect.x) {
// Render a character
float u1 = glyph->U0;
float v1 = glyph->V0;
float u2 = glyph->U1;
float v2 = glyph->V1;
// CPU side clipping used to fit text in their frame when the frame is too small. Only does clipping for axis aligned quads.
if (cpu_fine_clip) {
if (x1 < clip_rect.x) {
u1 = u1 + (1.0f - (x2 - clip_rect.x) / (x2 - x1)) * (u2 - u1);
x1 = clip_rect.x;
}
if (y1 < clip_rect.y) {
v1 = v1 + (1.0f - (y2 - clip_rect.y) / (y2 - y1)) * (v2 - v1);
y1 = clip_rect.y;
}
if (x2 > clip_rect.z) {
u2 = u1 + ((clip_rect.z - x1) / (x2 - x1)) * (u2 - u1);
x2 = clip_rect.z;
}
if (y2 > clip_rect.w) {
v2 = v1 + ((clip_rect.w - y1) / (y2 - y1)) * (v2 - v1);
y2 = clip_rect.w;
}
if (y1 >= y2) {
x += char_width;
continue;
}
}
// We are NOT calling PrimRectUV() here because non-inlined causes too much overhead in a debug builds. Inlined here:
{
idx_write[0] = (ImDrawIdx) (vtx_current_idx);
idx_write[1] = (ImDrawIdx) (vtx_current_idx + 1);
idx_write[2] = (ImDrawIdx) (vtx_current_idx + 2);
idx_write[3] = (ImDrawIdx) (vtx_current_idx);
idx_write[4] = (ImDrawIdx) (vtx_current_idx + 2);
idx_write[5] = (ImDrawIdx) (vtx_current_idx + 3);
vtx_write[0].pos.x = x1;
vtx_write[0].pos.y = y1;
vtx_write[0].col = col;
vtx_write[0].uv.x = u1;
vtx_write[0].uv.y = v1;
vtx_write[1].pos.x = x2;
vtx_write[1].pos.y = y1;
vtx_write[1].col = col;
vtx_write[1].uv.x = u2;
vtx_write[1].uv.y = v1;
vtx_write[2].pos.x = x2;
vtx_write[2].pos.y = y2;
vtx_write[2].col = col;
vtx_write[2].uv.x = u2;
vtx_write[2].uv.y = v2;
vtx_write[3].pos.x = x1;
vtx_write[3].pos.y = y2;
vtx_write[3].col = col;
vtx_write[3].uv.x = u1;
vtx_write[3].uv.y = v2;
vtx_write += 4;
vtx_current_idx += 4;
idx_write += 6;
}
}
}
}
x += char_width;
}
// Give back unused vertices
draw_list->VtxBuffer.resize((int) (vtx_write - draw_list->VtxBuffer.Data));
draw_list->IdxBuffer.resize((int) (idx_write - draw_list->IdxBuffer.Data));
draw_list->CmdBuffer[draw_list->CmdBuffer.Size - 1].ElemCount -= (idx_expected_size - draw_list->IdxBuffer.Size);
draw_list->_VtxWritePtr = vtx_write;
draw_list->_IdxWritePtr = idx_write;
draw_list->_VtxCurrentIdx = (unsigned int) draw_list->VtxBuffer.Size;
}
//-----------------------------------------------------------------------------
// Internals Drawing Helpers
//-----------------------------------------------------------------------------
static inline float ImAcos01(float x) {
if (x <= 0.0f) return IM_PI * 0.5f;
if (x >= 1.0f) return 0.0f;
return ImAcos(x);
//return (-0.69813170079773212f * x * x - 0.87266462599716477f) * x + 1.5707963267948966f; // Cheap approximation, may be enough for what we do.
}
// FIXME: Cleanup and move code to ImDrawList.
void ImGui::RenderRectFilledRangeH(ImDrawList *draw_list, const ImRect &rect, ImU32 col, float x_start_norm,
float x_end_norm, float rounding) {
if (x_end_norm == x_start_norm)
return;
if (x_start_norm > x_end_norm)
ImSwap(x_start_norm, x_end_norm);
ImVec2 p0 = ImVec2(ImLerp(rect.Min.x, rect.Max.x, x_start_norm), rect.Min.y);
ImVec2 p1 = ImVec2(ImLerp(rect.Min.x, rect.Max.x, x_end_norm), rect.Max.y);
if (rounding == 0.0f) {
draw_list->AddRectFilled(p0, p1, col, 0.0f);
return;
}
rounding = ImClamp(ImMin((rect.Max.x - rect.Min.x) * 0.5f, (rect.Max.y - rect.Min.y) * 0.5f) - 1.0f, 0.0f,
rounding);
const float inv_rounding = 1.0f / rounding;
const float arc0_b = ImAcos01(1.0f - (p0.x - rect.Min.x) * inv_rounding);
const float arc0_e = ImAcos01(1.0f - (p1.x - rect.Min.x) * inv_rounding);
const float x0 = ImMax(p0.x, rect.Min.x + rounding);
if (arc0_b == arc0_e) {
draw_list->PathLineTo(ImVec2(x0, p1.y));
draw_list->PathLineTo(ImVec2(x0, p0.y));
} else if (arc0_b == 0.0f && arc0_e == IM_PI * 0.5f) {
draw_list->PathArcToFast(ImVec2(x0, p1.y - rounding), rounding, 3, 6); // BL
draw_list->PathArcToFast(ImVec2(x0, p0.y + rounding), rounding, 6, 9); // TR
} else {
draw_list->PathArcTo(ImVec2(x0, p1.y - rounding), rounding, IM_PI - arc0_e, IM_PI - arc0_b, 3); // BL
draw_list->PathArcTo(ImVec2(x0, p0.y + rounding), rounding, IM_PI + arc0_b, IM_PI + arc0_e, 3); // TR
}
if (p1.x > rect.Min.x + rounding) {
const float arc1_b = ImAcos01(1.0f - (rect.Max.x - p1.x) * inv_rounding);
const float arc1_e = ImAcos01(1.0f - (rect.Max.x - p0.x) * inv_rounding);
const float x1 = ImMin(p1.x, rect.Max.x - rounding);
if (arc1_b == arc1_e) {
draw_list->PathLineTo(ImVec2(x1, p0.y));
draw_list->PathLineTo(ImVec2(x1, p1.y));
} else if (arc1_b == 0.0f && arc1_e == IM_PI * 0.5f) {
draw_list->PathArcToFast(ImVec2(x1, p0.y + rounding), rounding, 9, 12); // TR
draw_list->PathArcToFast(ImVec2(x1, p1.y - rounding), rounding, 0, 3); // BR
} else {
draw_list->PathArcTo(ImVec2(x1, p0.y + rounding), rounding, -arc1_e, -arc1_b, 3); // TR
draw_list->PathArcTo(ImVec2(x1, p1.y - rounding), rounding, +arc1_b, +arc1_e, 3); // BR
}
}
draw_list->PathFillConvex(col);
}
//-----------------------------------------------------------------------------
// DEFAULT FONT DATA
//-----------------------------------------------------------------------------
// Compressed with stb_compress() then converted to a C array.
// Use the program in misc/fonts/binary_to_compressed_c.cpp to create the array from a TTF file.
// Decompression from stb.h (public domain) by Sean Barrett https://github.com/nothings/stb/blob/master/stb.h
//-----------------------------------------------------------------------------
static unsigned int stb_decompress_length(const unsigned char *input) {
return (input[8] << 24) + (input[9] << 16) + (input[10] << 8) + input[11];
}
static unsigned char *stb__barrier_out_e, *stb__barrier_out_b;
static const unsigned char *stb__barrier_in_b;
static unsigned char *stb__dout;
static void stb__match(const unsigned char *data, unsigned int length) {
// INVERSE of memmove... write each byte before copying the next...
IM_ASSERT(stb__dout + length <= stb__barrier_out_e);
if (stb__dout + length > stb__barrier_out_e) {
stb__dout += length;
return;
}
if (data < stb__barrier_out_b) {
stb__dout = stb__barrier_out_e + 1;
return;
}
while (length--) *stb__dout++ = *data++;
}
static void stb__lit(const unsigned char *data, unsigned int length) {
IM_ASSERT(stb__dout + length <= stb__barrier_out_e);
if (stb__dout + length > stb__barrier_out_e) {
stb__dout += length;
return;
}
if (data < stb__barrier_in_b) {
stb__dout = stb__barrier_out_e + 1;
return;
}
memcpy(stb__dout, data, length);
stb__dout += length;
}
#define stb__in2(x) ((i[x] << 8) + i[(x)+1])
#define stb__in3(x) ((i[x] << 16) + stb__in2((x)+1))
#define stb__in4(x) ((i[x] << 24) + stb__in3((x)+1))
static const unsigned char *stb_decompress_token(const unsigned char *i) {
if (*i >= 0x20) { // use fewer if's for cases that expand small
if (*i >= 0x80) stb__match(stb__dout - i[1] - 1, i[0] - 0x80 + 1), i += 2;
else if (*i >= 0x40) stb__match(stb__dout - (stb__in2(0) - 0x4000 + 1), i[2] + 1), i += 3;
else /* *i >= 0x20 */ stb__lit(i + 1, i[0] - 0x20 + 1), i += 1 + (i[0] - 0x20 + 1);
} else { // more ifs for cases that expand large, since overhead is amortized
if (*i >= 0x18) stb__match(stb__dout - (stb__in3(0) - 0x180000 + 1), i[3] + 1), i += 4;
else if (*i >= 0x10) stb__match(stb__dout - (stb__in3(0) - 0x100000 + 1), stb__in2(3) + 1), i += 5;
else if (*i >= 0x08) stb__lit(i + 2, stb__in2(0) - 0x0800 + 1), i += 2 + (stb__in2(0) - 0x0800 + 1);
else if (*i == 0x07) stb__lit(i + 3, stb__in2(1) + 1), i += 3 + (stb__in2(1) + 1);
else if (*i == 0x06) stb__match(stb__dout - (stb__in3(1) + 1), i[4] + 1), i += 5;
else if (*i == 0x04) stb__match(stb__dout - (stb__in3(1) + 1), stb__in2(4) + 1), i += 6;
}
return i;
}
static unsigned int stb_adler32(unsigned int adler32, unsigned char *buffer, unsigned int buflen) {
const unsigned long ADLER_MOD = 65521;
unsigned long s1 = adler32 & 0xffff, s2 = adler32 >> 16;
unsigned long blocklen, i;
blocklen = buflen % 5552;
while (buflen) {
for (i = 0; i + 7 < blocklen; i += 8) {
s1 += buffer[0], s2 += s1;
s1 += buffer[1], s2 += s1;
s1 += buffer[2], s2 += s1;
s1 += buffer[3], s2 += s1;
s1 += buffer[4], s2 += s1;
s1 += buffer[5], s2 += s1;
s1 += buffer[6], s2 += s1;
s1 += buffer[7], s2 += s1;
buffer += 8;
}
for (; i < blocklen; ++i)
s1 += *buffer++, s2 += s1;
s1 %= ADLER_MOD, s2 %= ADLER_MOD;
buflen -= blocklen;
blocklen = 5552;
}
return (unsigned int) (s2 << 16) + (unsigned int) s1;
}
static unsigned int stb_decompress(unsigned char *output, const unsigned char *i, unsigned int /*length*/) {
unsigned int olen;
if (stb__in4(0) != 0x57bC0000) return 0;
if (stb__in4(4) != 0) return 0; // error! stream is > 4GB
olen = stb_decompress_length(i);
stb__barrier_in_b = i;
stb__barrier_out_e = output + olen;
stb__barrier_out_b = output;
i += 16;
stb__dout = output;
for (;;) {
const unsigned char *old_i = i;
i = stb_decompress_token(i);
if (i == old_i) {
if (*i == 0x05 && i[1] == 0xfa) {
IM_ASSERT(stb__dout == output + olen);
if (stb__dout != output + olen) return 0;
if (stb_adler32(1, output, olen) != (unsigned int) stb__in4(2))
return 0;
return olen;
} else {
IM_ASSERT(0); /* NOTREACHED */
return 0;
}
}
IM_ASSERT(stb__dout <= output + olen);
if (stb__dout > output + olen)
return 0;
}
}
//-----------------------------------------------------------------------------
// ProggyClean.ttf
// Copyright (c) 2004, 2005 Tristan Grimmer
// MIT license (see License.txt in http://www.upperbounds.net/download/ProggyClean.ttf.zip)
// Download and more information at http://upperbounds.net
//-----------------------------------------------------------------------------
// File: 'ProggyClean.ttf' (41208 bytes)
// Exported using binary_to_compressed_c.cpp
//-----------------------------------------------------------------------------
static const char proggy_clean_ttf_compressed_data_base85[11980 + 1] =
"7])#######hV0qs'/###[),##/l:$#Q6>##5[n42>c-TH`->>#/e>11NNV=Bv(*:.F?uu#(gRU.o0XGH`$vhLG1hxt9?W`#,5LsCp#-i>.r$<$6pD>Lb';9Crc6tgXmKVeU2cD4Eo3R/"
"2*>]b(MC;$jPfY.;h^`IWM9<Lh2TlS+f-s$o6Q<BWH`YiU.xfLq$N;$0iR/GX:U(jcW2p/W*q?-qmnUCI;jHSAiFWM.R*kU@C=GH?a9wp8f$e.-4^Qg1)Q-GL(lf(r/7GrRgwV%MS=C#"
"`8ND>Qo#t'X#(v#Y9w0#1D$CIf;W'#pWUPXOuxXuU(H9M(1<q-UE31#^-V'8IRUo7Qf./L>=Ke$$'5F%)]0^#[email protected]<r:QLtFsLcL6##lOj)#.Y5<-R&KgLwqJfLgN&;Q?gI^#DY2uL"
"i@^rMl9t=cWq6##weg>$FBjVQTSDgEKnIS7EM9>ZY9w0#L;>>#Mx&4Mvt//L[MkA#[email protected]'[0#7RL_&#w+F%HtG9M#XL`N&.,GM4Pg;-<nLENhvx>-VsM.M0rJfLH2eTM`*oJMHRC`N"
"kfimM2J,W-jXS:)r0wK#@Fge$U>`w'N7G#$#fB#$E^$#:9:hk+eOe--6x)F7*E%?76%^GMHePW-Z5l'&GiF#$956:rS?dA#fiK:)Yr+`�j@'DbG&#^$PG.Ll+DNa<XCMKEV*N)LN/N"
"*b=%Q6pia-Xg8I$<MR&,VdJe$<(7G;Ckl'&hF;;$<_=X(b.RS%%)###MPBuuE1V:v&cXm#(&cV]`k9OhLMbn%s$G2,B$BfD3X*sp5#l,$R#]x_X1xKX%b5U*[r5iMfUo9U`N99hG)"
"tm+/Us9pG)XPu`<0s-)WTt(gCRxIg(%6sfh=ktMKn3j)<6<b5Sk_/0(^]AaN#(p/L>&VZ>1i%h1S9u5o@YaaW$e+b<TWFn/Z:Oh(Cx2$lNEoN^e)#CFY@@I;BOQ*sRwZtZxRcU7uW6CX"
"ow0i(?$Q[cjOd[P4d)]>ROPOpxTO7Stwi1::iB1q)C_=dV26J;2,]7op$]uQr@_V7$q^%lQwtuHY]=DX,n3L#0PHDO4f9>dC@O>HBuKPpP*E,N+b3L#lpR/MrTEH.IAQk.a>D[.e;mc."
"x]Ip.PH^'/aqUO/$1WxLoW0[iLA<QT;5HKD+@qQ'NQ(3_PLhE48R.qAPSwQ0/WK?Z,[x?-J;jQTWA0X@KJ(_Y8N-:/M74:/-ZpKrUss?d#dZq]DAbkU*JqkL+nwX@@47`5>w=4h(9.`G"
"CRUxHPeR`5Mjol(dUWxZa(>STrPkrJiWx`5U7F#.g*jrohGg`cg:lSTvEY/EV_7H4Q9[Z%cnv;JQYZ5q.l7Zeas:HOIZOB?G<Nald$qs]@]L<J7bR*>gv:[7MI2k).'2($5FNP&EQ(,)"
"U]W]+fh18.vsai00);D3@4ku5P?DP8aJt+;qUM]=+b'8@;mViBKx0DE[-auGl8:PJ&Dj+M6OC]O^((##]`0i)drT;-7X`=-H3[igUnPG-NZlo.#k@h#=Ork$m>a>$-?Tm$UV(?#P6YY#"
"'/###xe7q.73rI3*pP/$1>s9)W,JrM7SN]'/4C#v$U`0#V.[0>xQsH$fEmPMgY2u7Kh(G%siIfLSoS+MK2eTM$=5,M8p`A.;_R%#u[K#$x4AG8.kK/HSB==-'Ie/QTtG?-.*^N-4B/ZM"
"_3YlQC7(p7q)&](`6_c)$/*JL(L-^(]$wIM`dPtOdGA,U3:w2M-0<q-]L_?^)1vw'.,MRsqVr.L;aN&#/EgJ)PBc[-f>+WomX2u7lqM2iEumMTcsF?-aT=Z-97UEnXglEn1K-bnEO`gu"
"Ft(c%=;Am_Qs@jLooI&NX;]0#j4#F14;gl8-GQpgwhrq8'=l_f-b49'UOqkLu7-##oDY2L(te+Mch&gLYtJ,MEtJfLh'x'M=$CS-ZZ%P]8bZ>#S?YY#%Q&q'3^Fw&?D)UDNrocM3A76/"
"/oL?#h7gl85[qW/NDOk%16ij;+:1a'iNIdb-ou8.P*w,v5#EI$TWS>Pot-R*H'-SEpA:g)f+O$%%`kA#G=8RMmG1&O`>to8bC]T&$,n.LoO>29sp3dt-52U%VM#q7'DHpg+#Z9%H[K<L"
"%a2E-grWVM3@2=-k22tL]4$##6We'8UJCKE[d_=%wI;'6X-GsLX4j^SgJ$##R*w,vP3wK#iiW&#*h^D&R?jp7+/u&#(AP##XU8c$fSYW-J95_-Dp[g9wcO&#M-h1OcJlc-*vpw0xUX&#"
"OQFKNX@QI'IoPp7nb,QU//MQ&ZDkKP)X<WSVL(68uVl&#c'[0#(s1X&xm$Y%B7*K:eDA323j998GXbA#pwMs-jgD$9QISB-A_(aN4xoFM^@C58D0+Q+q3n0#3U1InDjF682-SjMXJK)("
"h$hxua_K]ul92%'BOU&#BRRh-slg8KDlr:%L71Ka:.A;%YULjDPmL<LYs8i#XwJOYaKPKc1h:'9Ke,g)b),78=I39B;xiY$bgGw-&.Zi9InXDuYa%G*f2Bq7mn9^#p1vv%#(Wi-;/Z5h"
"o;#2:;%d	v68C5g?ntX0X)pT`;%pB3q7mgGN)3%(P8nTd5L7GeA-GL@+%J3u2:(Yf>et`e;)f#Km8&+DC$I46>#Kr]]u-[=99tts1.qb#q72g1WJO81q+eN'03'eM>&1XxY-caEnO"
"j%2n8)),?ILR5^.Ibn<-X-Mq7[a82Lq:F&#ce+S9wsCK*x`569E8ew'He]h:sI[2LM$[guka3ZRd6:t%IG:;$%YiJ:Nq=?eAw;/:nnDq0(CYcMpG)qLN4$##&J<j$UpK<Q4a1]MupW^-"
"sj_$%[HK%'F####QRZJ::Y3EGl4'@%FkiAOg#p[##O`gukTfBHagL<LHw%q&OV0##F=6/:chIm0@eCP8X]:kFI%hl8hgO@RcBhS-@Qb$%+m=hPDLg*%K8ln(wcf3/'DW-$.lR?n[nCH-"
"eXOONTJlh:.RYF%3'p6sq:UIMA945&^HFS87@$EP2iG<-lCO$%c`uKGD3rC$x0BL8aFn--`ke%#HMP'vh1/R&O_J9'um,.<tx[@%wsJk&bUT2`0uMv7gg#qp/ij.L56'hl;.s5CUrxjO"
"M7-##.l+Au'A&O:-T72L]P`&=;ctp'XScX*rU.>-XTt,%OVU4)S1+R-#dg0/Nn?Ku1^0f$B*P:Rowwm-`0PKjYDDM'3]d39VZHEl4,.j']Pk-M.h^&:0FACm$maq-&sgw0t7/6(^xtk%"
"LuH88Fj-ekm>GA#_>568x6(OFRl-IZp`&b,_P'$M<Jnq79VsJW/mWS*PUiq76;]/NM_>hLbxfc$mj`,O;&%W2m`Zh:/)Uetw:aJ%]K9h:TcF]u_-Sj9,VK3M.*'&0D[Ca]J9gp8,kAW]"
"%(?A%R$f<->Zts'^kn=-^@c4%-pY6qI%J%1IGxfLU9CP8cbPlXv);C=b),<2mOvP8up,UVf3839acAWAW-W?#ao/^#%KYo8fRULNd2.>%m]UK:n%r$'sw]J;5pAoO_#2mO3n,'=H5(et"
"Hg*`+RLgv>=4U8guD$I%D:W>-r5V*%j*W:Kvej.Lp$<M-SGZ':+Q_k+uvOSLiEo(<aD/K<CCc`'Lx>'?;++O'>()jLR-^u68PHm8ZFWe+ej8h:9r6L*0//c&iH&R8pRbA#Kjm%upV1g:"
"a_#Ur7FuA#(tRh#.Y5K+@?3<-8m0$PEn;J:rh6?I6uG<-`wMU'ircp0LaE_OtlMb&1#6T.#FDKu#1Lw%u%+GM+X'e?YLfjM[VO0MbuFp7;>Q&#WIo)0@F%q7c#4XAXN-U&VB<HFF*qL("
"$/V,;(kXZejWO`<[5?\?ewY(*9=%wDc;,u<'9t3W-(H1th3+G]ucQ]kLs7df($/*JL]@*t7Bu_G3_7mp7<[email protected];x3B0lqp7Hf,^Ze7-##@/c58Mo(3;knp0%)A7?-W+eI'o8)b<"
"nKnw'Ho8C=Y>pqB>0ie&jhZ[?iLR@@_AvA-iQC(=ksRZRVp7`.=+NpBC%rh&3]R:8XDmE5^V8O(x<<aG/1N$#FX$0V5Y6x'aErI3I$7x%E`v<-BY,)%-?Psf*l?%C3.mM(=/M0:JxG'?"
"7WhH%o'a<-80g0NBxoO(GH<dM]n.+%q@jH?f.UsJ2Ggs&4<-e47&Kl+f//9@`b+?.TeN_&B8Ss?v;^Trk;f#YvJkl&w$]>-+k?'(<S:68tq*WoDfZu';mM?8X[ma8W%*`-=;D.(nc7/;"
")g:T1=^J$&BRV(-lTmNB6xqB[@0*o.erM*<SWF]u2=st-*(6v>^](H.aREZSi,#1:[IXaZFOm<-ui#qUq2$##Ri;u75OK#(RtaW-K-F`S+cF]uN`-KMQ%rP/Xri.LRcB##=YL3BgM/3M"
"D?@f&1'BW-)Ju<L25gl8uhVm1hL$##*8###'A3/LkKW+(^rWX?5W_8g)a(m&K8P>#bmmWCMkk&#TR`C,5d>g)F;t,4:@_l8G/5h4vUd%&%950:VXD'QdWoY-F$BtUwmfe$YqL'8(PWX("
"P?^@Po3$##`MSs?DWBZ/S>+4%>fX,VWv/w'KD`LP5IbH;rTV>n3cEK8U#bX]l-/V+^lj3;vlMb&[5YQ8#pekX9JP3XUC72L,,?+Ni&co7ApnO*5NK,((W-i:$,kp'UDAO(G0Sq7MVjJs"
"bIu)'Z,*[>br5fX^:FPAWr-m2KgL<LUN098kTF&#lvo58=/vjDo;.;)Ka*hLR#/k=rKbxuV`>Q_nN6'8uTGT5g)uLv:873UpTLgH+#FgpH'_o1780Ph8KmxQJ8#H72L4@768@Tm&Q"
"h4CB/5OvmA&,Q&QbUoi$a_%3M01H)4x7I^&KQVgtFnV+;[Pc>[m4k//,]1?#`VY[Jr*3&&slRfLiVZJ:]?=K3Sw=[$=uRB?3xk48@aeg<Z'<$#4H)6,>e0jT6'N#(q%.O=?2S]u*(m<-"
"V8J'(1)G][68hW$5'q[GC&5j`TE?m'esFGNRM)j,ffZ?-qx8;->g4t*:CIP/[Qap7/9'#(1sao7w-.qNUdkJ)tCF&#B^;[email protected]$m%#QvQS8U@)2Z+3K:AKM5i"
"sZ88+dKQ)W6>J%CL<KE>`.d*(B`-n8D9oK<Up]c$X$(,)M8Zt7/[rdkqTgl-0cuGMv'?>-XV1q['-5k'cAZ69e;D_?$ZPP&s^+7])$*$#@QYi9,5P	r+$%CE=68>K8r0=dSC%%(@p7"
".m7jilQ02'0-VWAg<a/''3u.=4L$Y)6k/K:_[3=&jvL<L0C/2'v:^;-DIBW,B4E68:kZ;%?8(Q8BH=kO65BW?xSG&#@uU,DS*,?.+(o(#1vCS8#CHF>TlGW'b)Tq7VT9q^*^$$.:&N@@"
"$&)WHtPm*5_rO0&e%K&#-30j(E4#'Zb.o/(Tpm$>K'f@[PvFl,hfINTNU6u'0pao7%XUp9]5.>%h`8_=VYbxuel.NTSsJfLacFu3B'lQSu/m6-Oqem8T+oE--$0a/k]uj9EwsG>%veR*"
"hv^BFpQj:K'#SJ,sB-'#](j.Lg92rTw-*n%@/;39rrJF,l#qV%OrtBeC6/,;qB3ebNW[?,Hqj2L.1NP&GjUR=1D8QaS3Up&@*9wP?+lo7b?@%'k4`p0Z$22%K3+iCZj?XJN4Nm&+YF]u"
"@-W$U%VEQ/,,>>#)D<h#`)h0:<Q6909ua+&VU%n2:cG3FJ-%@Bj-DgLr`Hw&HAKjKjseK</xKT*)B,N9X3]krc12t'pgTV(Lv-tL[xg_%=M_q7a^x?7Ubd>#%8cY#YZ?=,`Wdxu/ae&#"
"w6)R89tI#6@s'(6Bf7a&?S=^ZI_kS&ai`&=tE72L_D,;^R)7[$s<Eh#c&)q.MXI%#v9ROa5FZO%sF7q7Nwb&#ptUJ:aqJe$Sl68%.D###EC><?-aF&#RNQv>o8lKN%5/$(vdfq7+ebA#"
"u1p]ovUKW&Y%q]'>$1@-[xfn$7ZTp7mM,G,Ko7a&Gu%G[RMxJs[0MM%wci.LFDK)(<c`Q8N)jEIF*+?P2a8g%)$q]o2aH8C&<SibC/q,(e:v;-b#6[$NtDZ84Je2KNvB#$P5?tQ3nt(0"
"d=j.LQf./Ll33+(;q3L-w=8dX$#WF&uIJ@-bfI>%:_i2B5CsR8&9Z&#=mPEnm0f`<&c)QL5uJ#%u%lJj+D-r;BoFDoS97h5g)E#o:&S4weDF,9^Hoe`h*L+_a*NrLW-1pG_&2UdB8"
"6e%B/:=>)N4xeW.*wft-;$'58-ESqr<b?UI(_%@[P46>#U`'6AQ]m&6/`Z>#S?YY#Vc;r7U2&326d=w&H####?TZ`*4?&.MK?LP8Vxg>$[QXc%QJv92.(Db*B)gb*BM9dM*hJMAo*c&#"
"b0v=Pjer]$gG&JXDf->'StvU7505l9$AFvgYRI^&<^b68?j#q9QX4SM'RO#&sL1IM.rJfLUAj221]d##DW=m83u5;'bYx,*Sl0hL(W;;$doB&O/TQ:(Z^xBdLjL<Lni;''X.`$#8+1GD"
":k$YUWsbn8ogh6rxZ2Z9]%nd+>V#*8U_72Lh+2Q8Cj0i:6hp&$C/:p(HK>T8Y[gHQ4`4)'$Ab(Nof%V'8hL&#<NEdtg(n'=S1A(Q1/I&4([%dM`,Iu'1:_hL>SfD07&6D<fp8dHM7/g+"
"tlPN9J*rKaPct&?'uBCem^jn%9_K)<,C5K3s=5g&GmJb*[SYq7K;TRLGCsM-$$;S%:Y@r7AK0pprpL<Lrh,q7e/%KWK:50I^+m'vi`3?%Zp+<-d+$L-Sv:@.o19n$s0&39;kn;S%BSq*"
"$3WoJSCLweV[aZ'MQIjO<7;X-X;&+dMLvu#^UsGEC9WEc[X(wI7#2.(F0jV*eZf<-Qv3J-c+J5AlrB#$p(H68LvEA'q3n0#m,[`*8Ft)FcYgEud]CWfm68,(aLA$@EFTgLXoBq/UPlp7"
":d[/;r_ix=:TF`S5H-b<LI&HY(K=h#)]Lk$K14lVfm:x$H<3^Ql<M`$OhapBnkup'D#L$Pb_`N*g]2e;X/Dtg,bsj&K#2[-:iYr'_wgH)NUIR8a1n#S?Yej'h8^58UbZd+^FKD*T@;6A"
"7aQC[K8d-(v6GI$x:T<&'Gp5Uf>@M.*J:;$-rv29'M]8qMv-tLp,'886iaC=Hb*YJoKJ,(j%K=H`K.v9HggqBIiZu'QvBT.#=)0ukruV&.)3=(^1`o*Pj4<-<aN((^7('#Z0wK#5GX@7"
"u][`*S^43933A4rl][`*O4CgLEl]v$1Q3AeF37dbXk,.)vj#x'd`;qgbQR%FW,2(?LO=s%Sc68%NP'##Aotl8x=BE#j1UD([3$M(]UI2LX3RpKN@;/#f'f/&_mt&F)XdF<9t4)Qa.*kT"
"LwQ'(TTB9.xH'>#MJ+gLq9-##@HuZPN0]u:h7.T..G:;$/Usj(T7`Q8tT72LnYl<-qx8;-HV7Q-&Xdx%1a,hC=0u+HlsV>nuIQL-5<N?)NBS)QN*_I,?&)2'IM%L3I)X((e/dl2&8'<M"
":^#M*Q+[T.Xri.LYS3v%fF`68h;b-X[/En'CR.q7E)p'/kle2HM,u;^%OKC-N+Ll%F9CF<Nf'^#t2L,;27W:0O@6##U6W7:$rJfLWHj$#)woqBefIZ.PK<b*t7ed;p*_m;4ExK#h@&]>"
"_>@kXQtMacfD.m-VAb8;IReM3$wf0''hra*so568'Ip&vRs849'MRYSp%:t:h5qSgwpEr$B>Q,;s(C#$)`svQuF$##-D,##,g68@2[T;.XSdN9Qe)rpt._K-#5wF)sP'##p#C0c%-Gb%"
"hd+<-j'Ai*x&&HMkT]C'OSl##5RG[JXaHN;d'uA#x._U;.`PU@(Z3dt4r152@:v,'R.Sj'w#0<-;kPI)FfJ&#AYJ&#//)>-k=m=*XnK$>=)72L]0I%>.G690a:$##<,);?;72#?x9+d;"
"^V'9;jY@;)br#q^YQpx:X#Te$Z^'=-=bGhLf:D6&bNwZ9-ZD#n^9HhLMr5G;']d&6'wYmTFmL<LD)F^%[tC'8;+9E#C$g%#5Y>q9wI>P(9mI[>kC-ekLC/R&CH+s'B;K-M6$EB%is00:"
"+A4[7xks.LrNk0&E)wILYF@2L'0Nb$+pv<(2.768/FrY&h$^3i&@+G%JT'<-,v`3;_)I9M^AE]CN?Cl2AZg+%4iTpT3<n-&%H%b<FDj2M<hH=&Eh<2Len$b*aTX=-8QxN)k11IM1c^j%"
"9s<L<NFSo)B?+<-(GxsF,^-Eh@$4dXhN$+#rxK8'je'D7k`e;)2pYwPA'_p9&@^18ml1^[@g4t*[JOa*[=Qp7(qJ_oOL^('7fB&Hq-:sf,sNj8xq^>$U4O]GKx'm9)b@p7YsvK3w^YR-"
"CdQ*:Ir<($u&)#(&?L9Rg3H)4fiEp^iI9O8KnTj,]H?D*r7'M;PwZ9K0E^k&-cpI;.p/6_vwoFMV<->#%Xi.LxVnrU(4&8/P+:hLSKj$#U%]49t'I:rgMi'FL@a:0Y-uA[39',(vbma*"
"hU%<-SRF`Tt:542R_VV$p@[p8DV[A,?1839FWdF<TddF<9Ah-6&9tWoDlh]&1SpGMq>Ti1O*H&#(AL8[_P%.M>v^-))qOT*F5Cq0`Ye%+$B6i:7@0IX<N+T+0MlMBPQ*Vj>SsD<U4JHY"
"8kD2)2fU/M#$e.)T4,_=8hLim[&);?UkK'-x?'(:siIfL<$pFM`i<?%W(mGDHM%>iWP,##P`%/L<eXi:@Z9C.7o=@(pXdAO/NLQ8lPl+HPOQa8wD8=^GlPa8TKI1CjhsCTSLJM'/Wl>-"
"S(qw%sf/@%#B6;/U7K]uZbi^Oc^2n<bhPmUkMw>%t<)'mEVE''n`WnJra$^TKvX5B>;_aSEK',(hwa0:i4G?.Bci.(X[?b*($,=-n<.Q%`(X=?+@Am*Js0&=3bh8K]mL<LoNs'6,'85`"
"0?t/'_U59@]ddF<#LdF<eWdF<OuN/45rY<-L@&#+fm>69=Lb,OcZV/);TTm8VI;?%OtJ<(b4mq7M6:u?KRdF<gR@2L=FNU-<b[(9c/ML3m;Z[$oF3g)GAWqpARc=<ROu7cL5l;-[A]%/"
"+fsd;l#SafT/f*W]0=O'$(Tb<[)*@e775R-:Yob%g*>l*:xP?Yb.5)%w_I?7uk5JC+FS(m#i'k.'a0i)9<7b'fs'59hq$*5Uhv##pi^8+hIEBF`nvo`;'l0.^S1<-wUK2/Coh58KKhLj"
"M=SO*rfO`+qC`W-On.=AJ56>>i2@2LH6A:&5q`?9I3@@'04&p2/LVa*T-4<-i3;M9UvZd+N7>b*eIwg:CC)c<>nO&#<IGe;__.thjZl<%w(Wk2xmp4Q@I#I9,DF]u7-P=.-_:YJ]aS@V"
"?6*C()dOp7:WL,b&3Rg/.cmM9&r^>$(>.Z-I&J(Q0Hd5Q%7Co-b`-c<N(6r@ip+AurK<m86QIth*#v;-OBqi+L7wDE-Ir8K['m+DDSLwK&/.?-V%U_%3:qKNu$_b*B-kp7NaD'QdWQPK"
"Yq[@>P)hI;*_F]u`Rb[.j8_Q/<&>uu+VsH$sM9TA%?)(vmJ80),P7E>)tjD%2L=-t#fK[%`v=Q8<FfNkgg^oIbah*#8/Qt$F&:K*-(N/'+1vMB,u()-a.VUU*#[e%gAAO(S>WlA2);Sa"
">gXm8YB`1d@K#n]76-a$U,mF<fX]idqd)<3,]J7JmW4`6]uks=4-72L(jEk+:bJ0M^q-8Dm_Z?0olP1C9Sa&H[d&c$ooQUj]Exd*3ZM@-WGW2%s',B-_M%>%Ul:#/'xoFM9QX-$.QN'>"
"[%$Z$uF6pA6Ki2O5:8w*vP1<-1`[G,)-m#>0`P&#eb#.3i)rtB61(o'$?X3B</R90;eZ]%Ncq;-Tl]#F>2Qft^ae_5tKL9MUe9b*sLEQ95C&`=G?@Mj=wh*'3E>=-<)Gt*Iw)'QG:`@I"
"wOf7&]1i'S01B+Ev/Nac#9S;=;YQpg_6U`*kVY39xK,[/6Aj7:'1Bm-_1EYfa1+o&o4hp7KN_Q(OlIo@S%;jVdn0'1<Vc52=u`3^o-n1'g4v58Hj&6_t7$##?M)c<$bgQ_'SY((-xkA#"
"Y(,p'H9rIVY-b,'%bCPF7.J<Up^,(dU1VY*5#WkTU>h19w,WQhLI)3S#f$2(eb,jr*b;3Vw]*7NH%$c4Vs,eD9>XW8?N]o+(*pgC%/72LV-u<Hp,3@e^9UB1J+ak9-TN/mhKPg+AJYd$"
"MlvAF_jCK*.O-^(63adMT->W%iewS8W6m2rtCpo'RS1R84=@paTKt)>=%&1[)*vp'u+x,VrwN;&]kuO9JDbg=pO$J*.jVe;u'm0dr9l,<*wMK*Oe=g8lV_KEBFkO'oU]^=[-792#ok,)"
"i]lR8qQ2oA8wcRCZ^7w/Njh;?.stX?Q1>S1q4Bn$)K1<-rGdO'$Wr.Lc.CG)$/*JL4tNR/,SVO3,aUw'DJN:)Ss;wGn9A32ijw%FL+Z0Fn.U9;reSq)bmI32U==5ALuG&#Vf1398/pVo"
"1*c-(aY168o<`JsSbk-,1N;$>0:OUas(3:8Z972LSfF8eb=c-;>SPw7.6hn3m`9^Xkn(r.qS[0;T%&Qc=+STRxX'q1BNk3&*eu2;&8q$&x>Q#Q7^Tf+6<(d%ZVmj2bDi%.3L2n+4W'$P"
"iDDG)g,r%+?,$@?uou5tSe2aN_AQU*<h`e-GI7)?OK2A.d7_c)?wQ5AS@DL3r#7fSkgl6-++D:'A,uq7SvlB$pcpH'q3n0#_%dY#xCpr-l<F0NR@-##FEV6NTF6##$l84N1w?AO>'IAO"
"URQ##V^Fv-XFbGM7Fl(N<3DhLGF%q.1rC$#:T__&Pi68%0xi_&[qFJ(77j_&JWoF.V735&T,[R*:xFR*K5>>#`bW-?4Ne_&6Ne_&6Ne_&n`kr-#GJcM6X;uM6X;uM(.a..^2TkL%oR(#"
";u.T%fAr%4tJ8&><1=GHZ_+m9/#H1F^R#SC#*N=BA9(D?v[UiFY>>^8p,KKF.W]L29uLkLlu/+4T<XoIB&hx=T1PcDaB&;HH+-AFr?(m9HZV)FKS8JCw;SD=6[^/DZUL`EUDf]GGlG&>"
"w$)F./^n3+rlo+DB;5sIYGNk+i1t-69Jg--0pao7Sm#K)pdHW&;LuDNH@H>#/X-TI(;P>#,Gc>#0Su>#4`1?#8lC?#<xU?#@.i?#D:%@#HF7@#LRI@#P_[@#Tkn@#Xw*A#]-=A#a9OA#"
"d<F&#*;G##.GY##2Sl##6`($#:l:$#>xL$#B.`$#F:r$#JF.%#NR@%#R_R%#Vke%#Zww%#_-4^Rh%Sflr-k'MS.o?.5/sWel/wpEM0%3'/1)K^f1-d>G21&v(35>V`39V7A4=onx4"
"A1OY5EI0;6Ibgr6M$HS7Q<)58C5w,;WoA*#[%T*#`1g*#d=#+#hI5+#lUG+#pbY+#tnl+#x$),#&1;,#*=M,#.I`,#2Ur,#6b.-#;w[H#iQtA#m^0B#qjBB#uvTB##-hB#'9$C#+E6C#"
"/QHC#3^ZC#7jmC#;v)D#?,<D#C8ND#GDaD#KPsD#O]/E#g1A5#KA*1#gC17#MGd;#8(02#L-d3#rWM4#Hga1#,<w0#T.j<#O#'2#CYN1#qa^:#_4m3#o@/=#eG8=#t8J5#`+78#4uI-#"
"m3B2#SB[8#Q0@8#i[*9#iOn8#1Nm;#^sN9#qh<9#:=x-#P;K2#$%X9#bC+.#Rg;<#mN=.#MTF.#RZO.#2?)4#Y#(/#[)1/#b;L/#dAU/#0Sv;#lY$0#n`-0#sf60#(F24#wrH0#%/e0#"
"TmD<#%JSMFove:CTBEXI:<eh2g)B,3h2^G3i;#d3jD>)4kMYD4lVu`4m`:&5niUA5@(A5BA1]PBB:xlBCC=2CDLXMCEUtiCf&0g2'tN?PGT4CPGT4CPGT4CPGT4CPGT4CPGT4CPGT4CP"
"GT4CPGT4CPGT4CPGT4CPGT4CPGT4CP-qekC`.9kEg^+F$kwViFJTB&5KTB&5KTB&5KTB&5KTB&5KTB&5KTB&5KTB&5KTB&5KTB&5KTB&5KTB&5KTB&5KTB&5KTB&5o,^<-28ZI'O?;xp"
"O?;xpO?;xpO?;xpO?;xpO?;xpO?;xpO?;xpO?;xpO?;xpO?;xpO?;xpO?;xpO?;xp;7q-#lLYI:xvD=#";
static const char *GetDefaultCompressedFontDataTTFBase85() {
return proggy_clean_ttf_compressed_data_base85;
}
| [
"[email protected]"
] | |
73226c7b42cf769c97539d9086a3747632dcd022 | 46890d2bfb9fb8d0ffae136a210c671c6ae3c3c4 | /FunctionTemplates/main.cpp | c9f964f9ae6b04a3e8ada29f8663c849c053aac2 | [] | no_license | AKQuaternion/Fall2019CS202 | b29ac0603a699912918c95befb9ea08c8ba2f1e8 | 1b877dd85317befcfa44a24148533004537a7abd | refs/heads/master | 2020-07-27T14:55:07.728969 | 2019-11-26T19:01:25 | 2019-11-26T19:01:25 | 209,131,869 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 708 | cpp | #include <iostream>
using std::cout;
using std::endl;
#include <string>
using std::string;
template <typename T, typename U>
void printTwo(const T & t, const U & u) {
cout << t << " " << u;
}
int square(int x) {return x*x;}
int thirteen(int x) {return 13;}
template <typename Func>
void functionCaller(Func f) {
cout << f(2) << f(3) << endl;
}
template<typename T>
void printTwice(const T&t) {
cout << t << t << endl;
}
void printTwice(int x) {
cout << "int" << x << x << endl;
}
int main() {
// functionCaller(square);
// functionCaller(thirteen);
printTwice(2);
printTwice(string("hello"));
// auto x=3;
//// cout << x << endl;
// printTwo<int,string>(2.2,string("hello"));
return 0;
} | [
"[email protected]"
] | |
15903067b1ac8bfe11f3ec2b3c47c77c8914cec5 | 2cae3c65a40a43aa1376fe8f6302ae84b2185b68 | /Analysis/Simulation/.sl64_gcc447/include/fastjet/NestedDefsPlugin.hh | b0f15e88554f4f650553b6cd5a5a3892da03f7fa | [] | no_license | mckinziebrandon/STAR | a7039b28e4ea6367a8e4752abb8036a26722593a | e1626b9f0795cb2e8d339e42fc86b7e4cd9b2d47 | refs/heads/master | 2020-04-25T18:43:53.617355 | 2015-09-30T18:53:20 | 2015-09-30T18:53:20 | 33,167,069 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,883 | hh | //STARTHEADER
// $Id: NestedDefsPlugin.hh 2577 2011-09-13 15:11:38Z salam $
//
// Copyright (c) 2007-2011, Matteo Cacciari, Gavin P. Salam and Gregory Soyez
//
//----------------------------------------------------------------------
// This file is part of FastJet.
//
// FastJet is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation; either version 2 of the License, or
// (at your option) any later version.
//
// The algorithms that underlie FastJet have required considerable
// development and are described in hep-ph/0512210. If you use
// FastJet as part of work towards a scientific publication, please
// include a citation to the FastJet paper.
//
// FastJet 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 FastJet. If not, see <http://www.gnu.org/licenses/>.
//----------------------------------------------------------------------
//ENDHEADER
#ifndef __NESTEDALGSPLUGIN_HH__
#define __NESTEDALGSPLUGIN_HH__
#include "fastjet/JetDefinition.hh"
#include <list>
#include <memory>
#include <cmath>
// questionable whether this should be in fastjet namespace or not...
namespace fastjet { // defined in fastjet/internal/base.hh
// another forward declaration to reduce includes
class PseudoJet;
//----------------------------------------------------------------------
//
/// @ingroup plugins
/// \class NestedDefsPlugin
/// Plugin to run multiple jet definitions successively (plugin for fastjet v2.4 upwards)
///
/// NestedAglsPlugin is a plugin for fastjet (v2.4 upwards) that, given
/// a list of jet definitions, performs the clustering by feeding the
/// particles to the first algorithm and then, successively feeding the
/// output to the next algorithm in the list.
//
class NestedDefsPlugin : public JetDefinition::Plugin {
public:
/// Main constructor for the NestedDefs Plugin class.
///
/// The argument is an initialised list of jet algorithms
NestedDefsPlugin (std::list<JetDefinition> &defs) :
_defs(defs){}
/// copy constructor
NestedDefsPlugin (const NestedDefsPlugin & plugin) {
*this = plugin;
}
// the things that are required by base class
virtual std::string description () const;
virtual void run_clustering(ClusterSequence &) const;
/// the plugin mechanism's standard way of accessing the jet radius
/// here we return the R of the last alg in the list
virtual double R() const {return _defs.rbegin()->R();}
private:
std::list<JetDefinition> _defs;
};
} // fastjet namespace
#endif // __SISCONEPLUGIN_HH__
| [
"[email protected]"
] | |
24aa0000cbc11cac25f77aa37b954327edfd7649 | de7e771699065ec21a340ada1060a3cf0bec3091 | /analysis/common/src/java/org/apache/lucene/analysis/miscellaneous/KeywordMarkerFilter.cpp | 8451c9e6d2b9241b7524377e69d170f82fe96f51 | [] | no_license | sraihan73/Lucene- | 0d7290bacba05c33b8d5762e0a2a30c1ec8cf110 | 1fe2b48428dcbd1feb3e10202ec991a5ca0d54f3 | refs/heads/master | 2020-03-31T07:23:46.505891 | 2018-12-08T14:57:54 | 2018-12-08T14:57:54 | 152,020,180 | 7 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 929 | cpp | using namespace std;
#include "KeywordMarkerFilter.h"
#include "../../../../../../../../../core/src/java/org/apache/lucene/analysis/TokenStream.h"
#include "../../../../../../../../../core/src/java/org/apache/lucene/analysis/tokenattributes/KeywordAttribute.h"
namespace org::apache::lucene::analysis::miscellaneous
{
using TokenFilter = org::apache::lucene::analysis::TokenFilter;
using TokenStream = org::apache::lucene::analysis::TokenStream;
using KeywordAttribute =
org::apache::lucene::analysis::tokenattributes::KeywordAttribute;
KeywordMarkerFilter::KeywordMarkerFilter(shared_ptr<TokenStream> in_)
: org::apache::lucene::analysis::TokenFilter(in_)
{
}
bool KeywordMarkerFilter::incrementToken()
{
if (input->incrementToken()) {
if (isKeyword()) {
keywordAttr->setKeyword(true);
}
return true;
} else {
return false;
}
}
} // namespace org::apache::lucene::analysis::miscellaneous | [
"[email protected]"
] | |
32eb57e5a4bf412891e30b665e96ddb00c232e01 | 197e2a8233a57be2abf4b6908c5abc7f72e3a11a | /subroutines/pirr_pfree_ratio_ps.cpp | 8eb157e807f45a4e82ec83fa51a10293ebc9567a | [] | no_license | mjohn218/FPR_simulator | 59a35e94bcbae8524e226b17a9a1530608e3cdef | 73a1e1be915a7943f5022a250729b0904cb397fb | refs/heads/master | 2021-01-01T16:32:15.384775 | 2017-08-10T03:10:53 | 2017-08-10T03:10:53 | 97,852,538 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,948 | cpp | #include "GF_calls.h"
#include "Faddeeva.hh"
#include "rand_gsl.h"
double pirr_pfree_ratio_ps(double rcurr, double r0, double tcurr, double Dtot, double bindrad, double alpha, double ps_prev, double rtol) {
//double pirr=pirrev_value(rcurr, r0, deltat, Dtot, bindrad, alpha_irr);
//double pfree=pfree_value(rcurr, r0, deltat, Dtot, bindrad, alpha_irr, prevpassoc);
double fDt = 4.0 * Dtot * tcurr;
double sq_fDt = sqrt(fDt);
double f1 = 1.0 / (sqrt(4.0 * M_PI * tcurr));
double f2 = 1.0 / (4.0 * M_PI * r0 * sqrt(Dtot));
double sep, dist;
double sqrt_t = sqrt(tcurr);
double a2 = alpha * alpha;
double r1, term1, term2, e1, ef1, sum;
r1 = rcurr;
sep = r1 + r0 - 2.0 * bindrad;
dist = r1 - r0;
term1 = f1 * (exp(-dist * dist / fDt) + exp(-sep * sep / fDt));
e1 = 2.0 * sep / sq_fDt * sqrt_t * alpha + a2 * tcurr;
ef1 = sep / sq_fDt + alpha * sqrt_t;
term2 = alpha * exp(e1) * erfc(ef1);
sum = term1 - term2;
sum *= f2 / r1;
double pirr = sum;
/*Normalization for no diffusion inside binding radius!*/
double cof = f1 * f2; //equal to 1/( 8pir_0 sqrt(piDt))
double c1 = 4.0 * M_PI * cof;
double ndist = bindrad - r0;
double nadist = bindrad + r0;
double sq_P = sqrt(M_PI);
term1 = -0.5 * fDt * exp(-ndist * ndist / fDt) - 0.5 * sq_fDt * sq_P * r0 * erf(-ndist / sq_fDt);
term2 = 0.5 * fDt * exp(-nadist * nadist / fDt) + 0.5 * sq_fDt * sq_P * r0 * erf(nadist / sq_fDt);
double pnorm = 1.0 - c1 * (term1 + term2); //this is then the normlization from sigma->inf
// cout <<"Normlization: integratl from sigma to infinity: "<<pnorm<<endl;
double adist = r1 + r0;
term1 = exp(-dist * dist / fDt) - exp(-adist * adist / fDt);
double pfree = cof / r1 * term1 / pnorm; //NORMALIZES TO ONE
double ratio;
if (abs(pirr - pfree * ps_prev) < rtol)
ratio = 1.0;
else {
ratio = pirr / (pfree * ps_prev);
// cout <<"pirr: "<<pirr<<" pfree*ps: "<<pfree*ps_prev<<" ratio: "<<ratio<<endl;
}
return ratio;
}
| [
"[email protected]"
] | |
1d579f8145fd21154ba9864ac9332a7313daf443 | f8a1624b062ff53cc4ee592587ec341bc77bf21a | /newExpression.h | bdfb1d44d437cf3121ad94502b2c36027488a95c | [] | no_license | kylegwilliam/Project1_Lexer | 8efd6dff52acb4e1a4edaa9ad590092bb6cdc224 | baf514e7ac6d6f230d8cff0e49d00e0019a65cb1 | refs/heads/master | 2023-03-22T03:59:50.734092 | 2021-03-10T02:53:52 | 2021-03-10T02:53:52 | 337,579,715 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 726 | h | //
// Created by Kyle Gwilliam on 2/26/21.
//
#ifndef PROJECT1_LEXER_NEWEXPRESSION_H
#define PROJECT1_LEXER_NEWEXPRESSION_H
#include "Parameter.h"
class newExpression : public Parameter {
private:
public:
string operatorAddMult;
Parameter* leftParam;
Parameter* rightParam;
string toString();
void setParam(Parameter* outputParam) {
if (leftParam == nullptr) {
leftParam = outputParam;
}
else {
rightParam = outputParam;
}
}
void setOpp(string outputOpp) {
operatorAddMult = outputOpp;
}
newExpression(){
leftParam = nullptr;
rightParam = nullptr;
}
};
#endif //PROJECT1_LEXER_NEWEXPRESSION_H
| [
"[email protected]"
] | |
4d95ce11aee2a605110d63c5e1a8abd5c589871f | 66257fa9bf3025d4398d11d01f19e559a350ee5b | /SDA/Module/DB/Mappers/DataTypeMapper.h | 9b1c053f3edc7ffc9b8c468007e586a445e53112 | [] | no_license | Fleynaro/MultiPlayer | 79a7e3e646ef23f5851d5ecc257ad0d77adc6ca1 | eb4310e0c61ab7126b3e3e31b322add999cef44b | refs/heads/master | 2023-06-12T16:00:53.713952 | 2021-05-14T14:14:15 | 2021-05-14T14:14:15 | 233,058,852 | 6 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,064 | h | #pragma once
#include <DB/AbstractMapper.h>
#include <Code/Type/AbstractType.h>
namespace CE {
class TypeManager;
};
namespace DB
{
class EnumTypeMapper;
class StructureTypeMapper;
class ClassTypeMapper;
class TypedefTypeMapper;
class SignatureTypeMapper;
class DataTypeMapper : public AbstractMapper
{
public:
EnumTypeMapper* m_enumTypeMapper;
StructureTypeMapper* m_structureTypeMapper;
ClassTypeMapper* m_classTypeMapper;
TypedefTypeMapper* m_typedefTypeMapper;
SignatureTypeMapper* m_signatureTypeMapper;
DataTypeMapper(IRepository* repository);
void loadBefore();
void loadAfter();
Id getNextId() override;
CE::TypeManager* getManager();
protected:
IDomainObject* doLoad(Database* db, SQLite::Statement& query) override;
void doInsert(TransactionContext* ctx, IDomainObject* obj) override;
void doUpdate(TransactionContext* ctx, IDomainObject* obj) override;
void doRemove(TransactionContext* ctx, IDomainObject* obj) override;
private:
void bind(SQLite::Statement& query, CE::DataType::Type& type);
};
}; | [
"[email protected]"
] | |
b6fe0e0525f7a3e8f58aeca9a3eca2b50ab90e13 | 45ca744b94418fe1ce3860048b071cc0ae4a3c62 | /xunlei1/myclass.h | 6dbaf595002f40b99287bfab3a8770f998c00823 | [] | no_license | squirrelClare/OnlineWrittenExamination | ec25937460d8b67495f9ec1784bb2691c4869d8a | 04213b0efa949f2ea68923cad4db3efcf305acff | refs/heads/master | 2021-01-10T03:39:03.776954 | 2015-10-21T13:36:25 | 2015-10-21T13:36:25 | 44,678,676 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 220 | h | #ifndef MYCLASS_H
#define MYCLASS_H
class MyClass
{
public:
MyClass();
// int a;
~MyClass();
int show(){
return 13;
}
private:
virtual int get(){
return 2;
}
};
#endif // MYCLASS_H
| [
"[email protected]"
] | |
fdd07c7aafeefaf2f382689ccc818c7e3e477337 | be6601674657294784b9ef455c1773d73ad657d9 | /PandoraSDK/src/Objects/ParticleFlowObject.cc | c30a17fb9e584fbd16a5f709c51b91ed65ce35d2 | [] | no_license | cms-externals/pandora | 0a7a7eaec6596f57bec89f28e72ac4eb04a68eb7 | 41abc90c25109c5bc91896079546e53a8586c057 | refs/heads/master | 2016-09-05T13:13:39.703922 | 2015-03-12T09:48:17 | 2015-03-12T09:48:17 | 31,168,496 | 0 | 1 | null | 2015-03-12T09:48:20 | 2015-02-22T16:01:51 | C++ | UTF-8 | C++ | false | false | 6,724 | cc | /**
* @file PandoraSDK/src/Objects/ParticleFlowObject.cc
*
* @brief Implementation of the particle flow object class.
*
* $Log: $
*/
#include "Objects/Cluster.h"
#include "Objects/OrderedCaloHitList.h"
#include "Objects/ParticleFlowObject.h"
#include "Objects/Track.h"
namespace pandora
{
ParticleFlowObject::ParticleFlowObject(const PandoraContentApi::ParticleFlowObject::Parameters ¶meters) :
m_particleId(parameters.m_particleId.Get()),
m_charge(parameters.m_charge.Get()),
m_mass(parameters.m_mass.Get()),
m_energy(parameters.m_energy.Get()),
m_momentum(parameters.m_momentum.Get()),
m_trackList(parameters.m_trackList),
m_clusterList(parameters.m_clusterList),
m_vertexList(parameters.m_vertexList)
{
}
//------------------------------------------------------------------------------------------------------------------------------------------
StatusCode ParticleFlowObject::AlterMetadata(const PandoraContentApi::ParticleFlowObject::Metadata &metadata)
{
if (metadata.m_particleId.IsInitialized())
m_particleId = metadata.m_particleId.Get();
if (metadata.m_charge.IsInitialized())
m_charge = metadata.m_charge.Get();
if (metadata.m_mass.IsInitialized())
m_mass = metadata.m_mass.Get();
if (metadata.m_energy.IsInitialized())
m_energy = metadata.m_energy.Get();
if (metadata.m_momentum.IsInitialized())
m_momentum = metadata.m_momentum.Get();
return STATUS_CODE_SUCCESS;
}
//------------------------------------------------------------------------------------------------------------------------------------------
TrackAddressList ParticleFlowObject::GetTrackAddressList() const
{
TrackAddressList trackAddressList;
for (TrackList::const_iterator iter = m_trackList.begin(), iterEnd = m_trackList.end(); iter != iterEnd; ++iter)
{
trackAddressList.push_back((*iter)->GetParentTrackAddress());
}
return trackAddressList;
}
//------------------------------------------------------------------------------------------------------------------------------------------
ClusterAddressList ParticleFlowObject::GetClusterAddressList() const
{
ClusterAddressList clusterAddressList;
for (ClusterList::const_iterator iter = m_clusterList.begin(), iterEnd = m_clusterList.end(); iter != iterEnd; ++iter)
{
CaloHitAddressList caloHitAddressList;
OrderedCaloHitList orderedCaloHitList((*iter)->GetOrderedCaloHitList());
PANDORA_THROW_RESULT_IF(STATUS_CODE_SUCCESS, !=, orderedCaloHitList.Add((*iter)->GetIsolatedCaloHitList()));
for (OrderedCaloHitList::const_iterator layerIter = orderedCaloHitList.begin(), layerIterEnd = orderedCaloHitList.end();
layerIter != layerIterEnd; ++layerIter)
{
for (CaloHitList::const_iterator hitIter = layerIter->second->begin(), hitIterEnd = layerIter->second->end();
hitIter != hitIterEnd; ++hitIter)
{
caloHitAddressList.push_back((*hitIter)->GetParentCaloHitAddress());
}
}
clusterAddressList.push_back(caloHitAddressList);
}
return clusterAddressList;
}
//------------------------------------------------------------------------------------------------------------------------------------------
template <>
StatusCode ParticleFlowObject::AddToPfo(const Cluster *const pCluster)
{
if (!m_clusterList.insert(pCluster).second)
return STATUS_CODE_ALREADY_PRESENT;
return STATUS_CODE_SUCCESS;
}
template <>
StatusCode ParticleFlowObject::AddToPfo(const Track *const pTrack)
{
if (!m_trackList.insert(pTrack).second)
return STATUS_CODE_ALREADY_PRESENT;
return STATUS_CODE_SUCCESS;
}
template <>
StatusCode ParticleFlowObject::AddToPfo(const Vertex *const pVertex)
{
if (!m_vertexList.insert(pVertex).second)
return STATUS_CODE_ALREADY_PRESENT;
return STATUS_CODE_SUCCESS;
}
//------------------------------------------------------------------------------------------------------------------------------------------
template <>
StatusCode ParticleFlowObject::RemoveFromPfo(const Cluster *const pCluster)
{
ClusterList::iterator iter = m_clusterList.find(pCluster);
if (m_clusterList.end() == iter)
return STATUS_CODE_NOT_FOUND;
m_clusterList.erase(iter);
return STATUS_CODE_SUCCESS;
}
template <>
StatusCode ParticleFlowObject::RemoveFromPfo(const Track *const pTrack)
{
TrackList::iterator iter = m_trackList.find(pTrack);
if (m_trackList.end() == iter)
return STATUS_CODE_NOT_FOUND;
m_trackList.erase(iter);
return STATUS_CODE_SUCCESS;
}
template <>
StatusCode ParticleFlowObject::RemoveFromPfo(const Vertex *const pVertex)
{
VertexList::iterator iter = m_vertexList.find(pVertex);
if (m_vertexList.end() == iter)
return STATUS_CODE_NOT_FOUND;
m_vertexList.erase(iter);
return STATUS_CODE_SUCCESS;
}
//------------------------------------------------------------------------------------------------------------------------------------------
StatusCode ParticleFlowObject::AddParent(const ParticleFlowObject *const pPfo)
{
if (NULL == pPfo)
return STATUS_CODE_INVALID_PARAMETER;
if (!m_parentPfoList.insert(pPfo).second)
return STATUS_CODE_ALREADY_PRESENT;
return STATUS_CODE_SUCCESS;
}
//------------------------------------------------------------------------------------------------------------------------------------------
StatusCode ParticleFlowObject::AddDaughter(const ParticleFlowObject *const pPfo)
{
if (NULL == pPfo)
return STATUS_CODE_INVALID_PARAMETER;
if (!m_daughterPfoList.insert(pPfo).second)
return STATUS_CODE_ALREADY_PRESENT;
return STATUS_CODE_SUCCESS;
}
//------------------------------------------------------------------------------------------------------------------------------------------
StatusCode ParticleFlowObject::RemoveParent(const ParticleFlowObject *const pPfo)
{
PfoList::const_iterator iter = m_parentPfoList.find(pPfo);
if (m_parentPfoList.end() == iter)
return STATUS_CODE_NOT_FOUND;
m_parentPfoList.erase(iter);
return STATUS_CODE_SUCCESS;
}
//------------------------------------------------------------------------------------------------------------------------------------------
StatusCode ParticleFlowObject::RemoveDaughter(const ParticleFlowObject *const pPfo)
{
PfoList::const_iterator iter = m_daughterPfoList.find(pPfo);
if (m_daughterPfoList.end() == iter)
return STATUS_CODE_NOT_FOUND;
m_daughterPfoList.erase(iter);
return STATUS_CODE_SUCCESS;
}
} // namespace pandora
| [
"[email protected]"
] | |
145af177e8b3ad1f3e95b29f9c84e8d79906e425 | 7d9ba9adeb3673c09c73e68da71861e83888df67 | /main/blind.h | bd66e59e57912359a6f903e712a4b0f1ad23ac9b | [] | no_license | apexskier/blind-minder | efe696b12b45999717316558ef1ac4e635d981bc | 6df67604e157ddc7ce41a72799432916a2615b0d | refs/heads/master | 2020-12-24T11:24:37.970828 | 2016-12-06T17:00:14 | 2016-12-06T17:00:14 | 73,033,999 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 769 | h | #include <Servo.h>
typedef int (*read_servo_val_func) ();
enum ServoStatus { positive, negative, stopped };
class Blind {
public:
int target_angle; // flat, 90 deg => up, -90 deg => down. won't ever go all the way
bool obstruction_detected;
ServoStatus status;
Blind();
Blind(int servo_pin, read_servo_val_func read_func);
Blind(int servo_pin, read_servo_val_func read_func, int max_read, int min_read, int max_pos, int min_pos);
String get_status();
void loop();
bool seek(int degrees);
void stop();
int read();
private:
Servo servo;
int write_servo_pin;
read_servo_val_func read_func;
int max_read;
int min_read;
int max_pos;
int min_pos;
void calibrate();
void print_status();
};
| [
"[email protected]"
] | |
abdbebaf35b4c8bcde4f7c04037af5b91ff8ebe2 | 5b511602ee4165fa95a5d178c573f67a34c0563a | /examples/common/CommonEvents.cpp | 93c8f8b594a48aa36df33025939f3621e95d5faa | [
"Apache-2.0"
] | permissive | savageking-io/evelengine | ca88d00dc6375181248a7131a721afe72750b1ee | f4f31419077e3467db271e82b05164eafa521eb7 | refs/heads/master | 2023-03-01T23:39:47.842808 | 2021-02-09T13:36:36 | 2021-02-09T13:36:36 | 261,850,906 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 274 | cpp | #include "CommonEvents.hpp"
CommonEvents::CommonEvents(const std::string& id) : EvelEngine::EventBase(id)
{
}
CommonEvents::~CommonEvents()
{
}
void CommonEvents::handleKeyUp(SDL_Keycode key)
{
if (key == SDLK_F3)
{
_engine->log()->debug("F3");
}
}
| [
"[email protected]"
] | |
70def3834686ce3adf8ececbdeb7703ae125ac60 | ca780c75c1e7339ee2cc8802b18c48cf70f10172 | /re2c/src/re/empty_class_policy.h | caf60a410c42d7250d4491d474346c6dfc816e1f | [
"LicenseRef-scancode-warranty-disclaimer",
"LicenseRef-scancode-public-domain"
] | permissive | gkantsidis/re2c | b8f793c727dc4cb96ef12d862e687afdeb9fc3b3 | 8a82ee027744a3a21ae45c70ace0d5076cf591a8 | refs/heads/master | 2021-05-04T13:25:42.903156 | 2018-02-06T14:34:06 | 2018-02-06T14:34:06 | 120,313,604 | 1 | 0 | null | 2018-02-05T14:12:48 | 2018-02-05T14:12:48 | null | UTF-8 | C++ | false | false | 330 | h | #ifndef _RE2C_RE_EMPTY_CLASS_POLICY_
#define _RE2C_RE_EMPTY_CLASS_POLICY_
namespace re2c {
enum empty_class_policy_t
{
EMPTY_CLASS_MATCH_EMPTY, // match on empty input
EMPTY_CLASS_MATCH_NONE, // fail to match on any input
EMPTY_CLASS_ERROR // compilation error
};
} // namespace re2c
#endif // _RE2C_RE_EMPTY_CLASS_POLICY_
| [
"[email protected]"
] | |
2027c75a4451dfa017cea0c1a9e23cd071ff8ee5 | afbd1dc4af29236c2bacbae09cbb0743827aae2c | /src/ADTs/interfaces/Stack.h | 7ae2b01dfd50767aa97d2f40deab6994274599e3 | [
"MIT"
] | permissive | StrayDragon/DataStructure-Algorithm-Cpp | b6ce185640f3a5a9c52cca31596e506e7798ca34 | 276b6ca9df54f2425732f7c9c9e9dd60c59033d1 | refs/heads/master | 2020-04-01T00:46:08.540197 | 2019-12-09T05:04:31 | 2019-12-09T05:04:31 | 152,712,671 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,073 | h | //
// Created by straydragon on 18-10-13.
//
#ifndef DATASTRUCTURE_ALGORITHM_CPP_STACK_H
#define DATASTRUCTURE_ALGORITHM_CPP_STACK_H
/**
* @brief 栈(Stack) 接口声明
*
* @tparam E 元素声明
*/
template <typename E>
class Stack {
public:
/**
* @brief 判断栈是否为空
*
* @return true 栈为空
* @return false 栈不为空
*/
virtual bool isEmpty() const = 0;
/**
* @brief 将元素 e 推进堆栈
*
* @param e 待推入元素
* @post 如果成功,元素 e 位于栈顶
* @return true 推入成功
* @return false 推入失败
*/
virtual bool push(const E& e) = 0;
/**
* @brief 将栈顶元素弹出(删除)
*
* @post 如果成功,栈顶元素已经被移除
* @return true 移除成功
* @return false 移除失败
*/
virtual bool pop() = 0;
/**
* @brief 返回栈顶元素
* @pre isEmpty() == false
* @post 栈顶元素已经返回,但栈内部状态不改变
* @return E 栈顶元素
*/
virtual E top() const = 0;
};
#endif // DATASTRUCTURE_ALGORITHM_CPP_STACK_H
| [
"[email protected]"
] | |
e081c5ac492b1f6d6444d02d61ed0c24fbe6beb5 | 395d1860e82bc75ccc04b91c4b9a8fa46276d9bb | /Source/Geometry/Collide/DataStructures/Planar/Solid/hkcdPlanarSolid.inl | 965adac666f1f4a449ed8495ba3ef207e03043e6 | [] | no_license | Hakhyun-Kim/projectanarchy | 28ba7370050000a12e4305faa11d5deb77c330a1 | ccea719afcb03967a68a169730b59e8a8a6c45f8 | refs/heads/master | 2021-06-03T04:41:22.814866 | 2013-11-07T07:21:03 | 2013-11-07T07:21:03 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 9,005 | inl | /*
*
* Confidential Information of Telekinesys Research Limited (t/a Havok). Not for disclosure or distribution without Havok's
* prior written consent. This software contains code, techniques and know-how which is confidential and proprietary to Havok.
* Product and Trade Secret source code contains trade secrets of Havok. Havok Software (C) Copyright 1999-2013 Telekinesys Research Limited t/a Havok. All Rights Reserved. Use of this software is subject to the terms of an end user license agreement.
*
*/
//
// Gets the node having the given Id.
HK_FORCE_INLINE const hkcdPlanarSolid::Node& hkcdPlanarSolid::getNode(NodeId nodeId) const { return (*m_nodes)[nodeId]; }
HK_FORCE_INLINE hkcdPlanarSolid::Node& hkcdPlanarSolid::accessNode(NodeId nodeId) { return (*m_nodes)[nodeId]; }
//
// Returns the nodes
HK_FORCE_INLINE const hkcdPlanarSolid::NodeStorage* hkcdPlanarSolid::getNodes() const
{
return m_nodes;
}
HK_FORCE_INLINE hkcdPlanarSolid::NodeStorage* hkcdPlanarSolid::accessNodes()
{
return m_nodes;
}
//
// Returns the collection of planes used by this solid
HK_FORCE_INLINE hkcdPlanarGeometryPlanesCollection* hkcdPlanarSolid::accessPlanesCollection() { return const_cast<hkcdPlanarGeometryPlanesCollection*>(m_planes.val()); }
HK_FORCE_INLINE const hkcdPlanarGeometryPlanesCollection* hkcdPlanarSolid::getPlanesCollection() const { return m_planes; }
//
// Returns true if the tree is valid
HK_FORCE_INLINE bool hkcdPlanarSolid::isValid() const
{
return m_rootNodeId.isValid();
}
//
// Returns true if the tree represent the empty set
HK_FORCE_INLINE bool hkcdPlanarSolid::isEmpty() const
{
return (isValid() && getNodeLabel(m_rootNodeId) == NODE_TYPE_OUT);
}
//
// Returns true if the given node is internal
HK_FORCE_INLINE bool hkcdPlanarSolid::isInternal(NodeId nodeId) const
{
if ( nodeId.isValid() )
{
const Node& node = getNode(nodeId);
return node.isAllocated() && (node.m_typeAndFlags == NODE_TYPE_INTERNAL);
}
return false;
}
//
// Returns the Id of the root node
HK_FORCE_INLINE const hkcdPlanarSolid::NodeId hkcdPlanarSolid::getRootNodeId() const
{
return m_rootNodeId;
}
//
// Returns the label of a given leaf node
HK_FORCE_INLINE hkcdPlanarSolid::NodeTypes hkcdPlanarSolid::getNodeLabel(NodeId nodeId) const
{
const Node& node = getNode(nodeId);
return (hkcdPlanarSolid::NodeTypes)node.m_typeAndFlags;
}
//
// Creates a new internal node
HK_FORCE_INLINE hkcdPlanarSolid::NodeId hkcdPlanarSolid::createNode(PlaneId splitPlaneId, NodeId leftChild, NodeId rightChild)
{
const NodeId nodeId = m_nodes->allocate();
Node& node = accessNode(nodeId);
node.m_planeId = splitPlaneId;
node.m_left = leftChild;
node.m_right = rightChild;
node.m_typeAndFlags = NODE_TYPE_INTERNAL;
node.m_data = 0;
return nodeId;
}
//
// Default nodes accessors
HK_FORCE_INLINE hkcdPlanarSolid::NodeId hkcdPlanarSolid::createInsideNode(NodeId parentId)
{
NodeId inNodeId = m_nodes->allocate();
Node& nodeIn = (*m_nodes)[inNodeId];
nodeIn.m_left = NodeId::invalid();
nodeIn.m_right = NodeId::invalid();
nodeIn.m_typeAndFlags = NODE_TYPE_IN;
nodeIn.m_planeId = PlaneId::invalid();
nodeIn.m_parent = parentId;
nodeIn.m_data = 0;
return inNodeId;
}
HK_FORCE_INLINE hkcdPlanarSolid::NodeId hkcdPlanarSolid::createOutsideNode(NodeId parentId)
{
NodeId outNodeId = m_nodes->allocate();
Node& nodeOut = (*m_nodes)[outNodeId];
nodeOut.m_left = NodeId::invalid();
nodeOut.m_right = NodeId::invalid();
nodeOut.m_typeAndFlags = NODE_TYPE_OUT;
nodeOut.m_planeId = PlaneId::invalid();
nodeOut.m_parent = parentId;
nodeOut.m_data = 0;
return outNodeId;
}
HK_FORCE_INLINE hkcdPlanarSolid::NodeId hkcdPlanarSolid::createUnknownNode(NodeId parentId)
{
NodeId unknownNodeId = m_nodes->allocate();
Node& nodeUnknown = (*m_nodes)[unknownNodeId];
nodeUnknown.m_left = NodeId::invalid();
nodeUnknown.m_right = NodeId::invalid();
nodeUnknown.m_typeAndFlags = NODE_TYPE_UNKNOWN;
nodeUnknown.m_planeId = PlaneId::invalid();
nodeUnknown.m_parent = parentId;
nodeUnknown.m_data = 0;
return unknownNodeId;
}
//
// Sets the root node
HK_FORCE_INLINE void hkcdPlanarSolid::setRootNode(NodeId rootNodeId)
{
m_rootNodeId = rootNodeId;
}
//
// Returns true if the given node can be collapsed to its parent
HK_FORCE_INLINE bool hkcdPlanarSolid::canCollapse(NodeId nodeId) const
{
if ( !nodeId.isValid() ) return false;
const Node& node = getNode(nodeId);
const Node& nodeLeft = getNode(node.m_left);
const Node& nodeRight = getNode(node.m_right);
return (nodeLeft.m_typeAndFlags == nodeRight.m_typeAndFlags) &&
((nodeLeft.m_typeAndFlags == hkcdPlanarSolid::NODE_TYPE_IN) || (nodeLeft.m_typeAndFlags == hkcdPlanarSolid::NODE_TYPE_OUT));
}
//
// Returns true if the triangle is allocated
HK_FORCE_INLINE bool hkcdPlanarSolid::Node::isAllocated() const
{
return m_typeAndFlags != NODE_TYPE_FREE;
}
//
// Marks this node as not-allocated
HK_FORCE_INLINE void hkcdPlanarSolid::Node::clear()
{
m_typeAndFlags = NODE_TYPE_FREE;
}
//
// Called by the free-list to initialize an unallocated entry
HK_FORCE_INLINE void hkcdPlanarSolid::Node::setEmpty(Node& element, hkUint32 next)
{
(hkUint32&)element = next; element.clear();
}
//
// Returns the index of the next free element. Will be called only with empty elements
HK_FORCE_INLINE hkUint32 hkcdPlanarSolid::Node::getNext(const Node& element)
{
return (hkUint32&)element;
}
//
// Sets the given child id
HK_FORCE_INLINE void hkcdPlanarSolid::Node::setChildId(int childIdx, NodeId childNodeId)
{
(&m_left)[childIdx] = childNodeId;
}
//
// Classifies the polygons into inside, boundary, and outside parts
HK_FORCE_INLINE void hkcdPlanarSolid::classifyPolygons( hkcdPlanarGeometry& polySoup, const hkArray<PolygonId>& polygonsIn,
hkArray<PolygonId>& insidePieces, hkArray<PolygonId>& boundaryPieces, hkArray<PolygonId>& outsidePieces, ArrayMgr* arrayMgr) const
{
if ( arrayMgr == HK_NULL )
{
ArrayMgr localArrayMgr;
classifyPolygons(polySoup, getRootNodeId(), polygonsIn, insidePieces, boundaryPieces, outsidePieces, localArrayMgr);
}
else
{
classifyPolygons(polySoup, getRootNodeId(), polygonsIn, insidePieces, boundaryPieces, outsidePieces, *arrayMgr);
}
}
//
// Constructor
HK_FORCE_INLINE hkcdPlanarSolid::ArrayMgr::ArrayMgr()
{
clear();
}
//
// Allocates an array slot. The storage for the array is not yet allocated
HK_FORCE_INLINE hkcdPlanarSolid::ArrayId hkcdPlanarSolid::ArrayMgr::allocArraySlot()
{
const ArrayId aid = m_arrays.allocate();
ArraySlot& slot = m_arrays[aid];
slot.m_offset = 0;
slot.m_size = 0;
return aid;
}
//
// Returns the array slot at the given Id
HK_FORCE_INLINE hkcdPlanarSolid::ArraySlot& hkcdPlanarSolid::ArrayMgr::getArraySlot(ArrayId aid)
{
return m_arrays[aid];
}
//
// Returns the array storage for the given Id
HK_FORCE_INLINE hkcdPlanarSolid::PolygonId hkcdPlanarSolid::ArrayMgr::getPolygonId(ArrayId aid, int k)
{
return PolygonId(m_storage[getArraySlot(aid).m_offset + k] & PAYLOAD_MASK);
}
//
// Allocates storage for numPolygons in the array at the given slot
HK_FORCE_INLINE void hkcdPlanarSolid::ArrayMgr::allocArrayStorage(ArrayId arraySlot, const PolygonId* HK_RESTRICT srcPolyIds, int numPolygons)
{
// Allocate polygons
ArraySlot& arrayElement = m_arrays[arraySlot];
hkUint32 allocSize = hkMath::max2<hkUint32>(MIN_BLOCK_SIZE, numPolygons);
arrayElement.m_offset = blockAlloc(allocSize);
arrayElement.m_size = numPolygons;
// Copy
int* ptr = &m_storage[arrayElement.m_offset];
for (int k = numPolygons - 1; k >= 0; k--)
{
ptr[k] = (ptr[k] & BLOCK_FLAGS_MASK) | (srcPolyIds[k].value() & PAYLOAD_MASK);
}
ptr[numPolygons - 1] |= END_PAYLOAD_FLAG;
}
HK_FORCE_INLINE void hkcdPlanarSolid::ArrayMgr::allocArrayStorage(ArrayId arraySlot, const hkArray<PolygonId>& srcPolyIds)
{
HK_ASSERT(0x2bc0d8cd, srcPolyIds.getSize());
allocArrayStorage(arraySlot, srcPolyIds.begin(), srcPolyIds.getSize());
}
HK_FORCE_INLINE void hkcdPlanarSolid::ArrayMgr::freeArray(ArrayId arraySlot)
{
ArraySlot& arrayElement = m_arrays[arraySlot];
if ( arrayElement.m_offset )
{
blockFree(arrayElement.m_offset, arrayElement.m_size);
}
m_arrays.release(arraySlot);
}
//
// Resets the manager for a new use
HK_FORCE_INLINE void hkcdPlanarSolid::ArrayMgr::reset()
{
clear();
m_arrays.clear();
}
/*
* Havok SDK - Base file, BUILD(#20131019)
*
* Confidential Information of Havok. (C) Copyright 1999-2013
* Telekinesys Research Limited t/a Havok. All Rights Reserved. The Havok
* Logo, and the Havok buzzsaw logo are trademarks of Havok. Title, ownership
* rights, and intellectual property rights in the Havok software remain in
* Havok and/or its suppliers.
*
* Use of this software for evaluation purposes is subject to and indicates
* acceptance of the End User licence Agreement for this product. A copy of
* the license is included with this software and is also available from [email protected].
*
*/
| [
"[email protected]"
] | |
45213d036033333b387bd380826270f5a41f3119 | 3540dc1216642b1e678de18bca58c1c172cefcf0 | /w7_Scope_LifeCycle/Scope.h | 0a3e3a8cf08ff171a0134bcdfa1b04e957dee184 | [] | no_license | Sudouble/TheBeautyOfCompiling | 5588e8bc185b61de7a8aee2cffc8ed25a20ce9a0 | 7f1e36d07cfcf05a9bd578a75fb8086da514d41a | refs/heads/master | 2022-03-26T21:55:48.281125 | 2019-11-13T10:07:33 | 2019-11-13T10:07:33 | 210,384,357 | 3 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 130 | h | #pragma once
#include "Symbol.h"
#include <vector>
using std::vector;
class Symbol;
class Scope
{
vector<Symbol> symbols;
};
| [
"[email protected]"
] | |
87f99c84af72e28f450c9294e17f9bdc2e9c35f8 | 76e33c5c200d1672a282dc719c3bc369c59befdb | /binary-search/search-in-rotated-sorted-array-ii.cpp | 75ffa8e8d8465a9fc14bb69a71f33230cf15f02f | [] | no_license | sankalpkotewar/algorithms-1 | cdc851a4695e0dd6d9aee360923c7af06dea837f | 22a8a2e1d29d60ee6b5070f32d5d9c30cd5f9780 | refs/heads/master | 2022-11-11T17:48:19.366022 | 2020-07-09T10:31:20 | 2020-07-09T10:31:20 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 657 | cpp | #include "binary-search.h"
/*
* Suppose an array sorted in ascending order is rotated at some pivot unknown to you beforehand.
(i.e., [0,0,1,2,2,5,6] might become [2,5,6,0,0,1,2]).
You are given a target value to search. If found in the array return true, otherwise return false.
Example 1:
Input: nums = [2,5,6,0,0,1,2], target = 0
Output: true
Example 2:
Input: nums = [2,5,6,0,0,1,2], target = 3
Output: false
Follow up:
This is a follow up problem to Search in Rotated Sorted Array, where nums may contain duplicates.
Would this affect the run-time complexity? How and why?
*/
bool searchII(vector<int>& nums, int target) {
return false;
} | [
"[email protected]"
] | |
b1526e7591e69ab01f93ea16f7ec633c114cc8cf | c690f08338fd6fdd365bdd55e01348655dd5bc9c | /include/room.h | c2535efd7a728c26db223d9d508ba034e3c4c79e | [] | no_license | dustin-ward/Text-Based-Adventure-Game | 927af00559048b67459acc21eb6b81e9f2794e20 | 10f5c26cdae5004934265fbb2c21ad59d246a686 | refs/heads/master | 2020-09-25T12:52:42.382656 | 2019-12-05T03:41:21 | 2019-12-05T03:41:21 | 226,008,386 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,155 | h | /*
* Copyright 2019 Team Electra
* @author Dustin Ward, <[email protected]>
@author Jared Sisco, <[email protected]>
* @date 2019-11
*/
#ifndef INCLUDE_ROOM_H_
#define INCLUDE_ROOM_H_
/**
* A class used to implement all rooms
*/
#include <vector>
#include <string>
#include "./NPC.h"
/**
* An enum to identify each room
*/
enum Room_Type { RN_NULL, RN_Closet_A, RN_Closet_B, RN_Bridge, RN_Mech_Storage,
RN_Engine, RN_Corridor_A, RN_Corridor_B, RN_Corridor_C,
RN_Captain, RN_Lunch, RN_Empty_A, RN_Empty_B, RN_Cargo
};
/**
* A struct that is used to initialize the room
*/
struct Room_Properties {
std::string Friendly_Name;
Room_Type Room_Typing;
std::string Description;
std::string Examine_Text;
std::string Locked_Text;
std::vector<Room_Type> Connections = {};
Room_Properties() {}
Room_Properties(const std::string &RN, Room_Type RT, const std::string &Desc,
const std::vector<Room_Type> &Conn, const std::string &EX,
const std::string <XT) :
Friendly_Name(RN), Room_Typing(RT), Description(Desc),
Connections(Conn), Examine_Text(EX), Locked_Text(LTXT) {}
};
class Room {
public:
/**
* Default Constructor
* @param Room_N A completed Room_Type that loads all values
*/
Room(Room_Type Room_N, bool From_Load);
/**
* Default destructor
*/
virtual ~Room();
/**
* Access the name of the room
* @return The name of the room as a string
*/
std::string getName() const;
/**
* Access the description of the room
* @return The description of the room as a string
*/
std::string getDescription() const;
/**
* Access the exanination text of the room
* @return The exanination text of the room as a string
*/
std::string getExamine() const;
/**
* Access the locked message of the room
* @return The locked message of the room as a string
*/
std::string getLockText() const;
/**
* Access the items that are contained in the room
* @return A pointer to an inventory that contains all of the room's items
*/
class Inventory* getInventory() const;
/**
* Access the NPC's that exist in the room
* @return A pointer to a vector of NPC pointers
*/
std::vector<NPC*>* getCharacters() const;
/**
* Access the type of the room
* @return The type of the room
*/
Room_Type getType() const;
/**
* Access the first NPC of type in a room
* @param reqName The name of the NPC to be returned
* @return A pointer to the requested NPC
*/
NPC* getCharacter(Character_Type reqName) const;
/**
* Access a specific NPC index in a room
* @param reqName The room slot num of the NPC to be returned
* @return A pointer to the requested NPC
*/
NPC* getCharacter(int Slot_Num) const;
/**
* Access the connected rooms
* @return A vector of connected rooms
*/
std::vector<Room_Type> getConnected() const;
/**
* Remove an NPC from a room
* @param reqNPC A pointer to the NPC to be removed
*/
void removeCharacter(NPC* reqNPC);
/**
* Access the Room_Properties of the room
* @param Needed_Room What room data to load
* @return The completed Room_Properties
*/
Room_Properties Obtain_Room_Properties(Room_Type Needed_Room);
/**
* Obtain a list of all the available items in the room
* @return A list of all available items as a string
*/
std::string listItems();
/**
* Obtain a list of all the available npcs in the room
* @return A list of all available npcs as a string
*/
std::string listNPC();
/**
* Loading NPC data from file
* @return A bool value based on if the load was successful
*/
bool load(const std::string &fileName);
/**
* Loading specific details into the class
* @param Needed_Type The details to be added
* @return Completed Room_Properties
*/
static Room_Properties loadDetails(Room_Type Needed_Type);
/**
* Filling rooms with their required items
* @param Needed_Type Room identifier
*/
void New_Data_Creation(Room_Type Needed_Type);
/**
* Fill rooms with their required characters
* @param Needed_Type Room identifier
*/
void NPC_Creation(Room_Type Needed_Type);
/**
* Check if the condition of the room is complete
* @return bool based on completion of the room
*/
bool checkCondition();
/**
* Flips the room codition upon completion of a task
* @param New_Condition A value to set the room to
*/
void setCondition(bool New_Condition);
/**
* Save room status to file
* @param Output_File Filename to write to
*/
void Save_Room(std::ofstream& Output_File);
/**
* Load room status from file
* @param Input_File Filename to read from
*/
void Load_Room(std::ifstream& Input_File);
bool Room_Flag = false;
bool Lock_Flag = false;
protected:
Room_Properties Contained_Properties;
class Inventory* items;
std::vector<NPC*>* characters;
};
#endif // INCLUDE_ROOM_H_
| [
"[email protected]"
] | |
1cd7bd607c38b3c16b679f65484440e3a5eec7ec | 54c11990f08dfdf4abca67aa6d7c6a30588c8db8 | /EjercicioROMPECABEZAS/main.cpp | 87f68df5d87c2868ccc8d01b0c4dd548191eb298 | [] | no_license | rafaelcanoguitton/CCOMP2 | 1951e57844febf58b7777c74a0e1a4d07fac694c | 8f26ccdb122f13efdf6771773ad6a3ac1e7ed161 | refs/heads/master | 2021-01-19T12:42:16.103709 | 2017-10-21T15:06:02 | 2017-10-21T15:06:02 | 100,798,739 | 1 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 366 | cpp | #include <iostream>
using namespace std;
void impr(int (*p)[4])
{
for (int i=0;i<4;i++)
{
cout<<**p;
}
cout<<endl;
}
int main()
{
int m[4][4]={{1,2,3,4},{5,6,7,8},{9,10,11,12},{13,14,15,16}};
int *p=m[0];
int (*a)[4]=m;
impr(a);
a++;
impr(a);
return 0;
}
//*(b[i]+j)
//cout<<(sizeof(m)/sizeof(m[0]))<<endl;
| [
"[email protected]"
] | |
2f9ea35033681d44fce08315192d78533eb2acc8 | 8f9ea3f14bdf2187de759939b2bbc87fe68ccfc0 | /tensorflow/core/common_runtime/lower_if_op.cc | b5fee36ff43e0808ee4128d55dcbcf2935889f0d | [
"Apache-2.0"
] | permissive | davidstanke/bazel-mvn-demo | 4ea43f0ba293a28b916a27eab5f0812e9b753c2c | cff14dddce15ea7152988da576673bd15bab6c6e | refs/heads/master | 2022-10-20T07:52:29.651851 | 2018-11-22T13:17:51 | 2018-11-22T13:17:51 | 157,782,756 | 2 | 0 | Apache-2.0 | 2022-10-04T23:47:05 | 2018-11-15T22:54:09 | C++ | UTF-8 | C++ | false | false | 9,943 | cc | /* Copyright 2018 The TensorFlow Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
#include "tensorflow/core/common_runtime/lower_if_op.h"
#include "tensorflow/core/common_runtime/function.h"
#include "tensorflow/core/framework/node_def_builder.h"
#include "tensorflow/core/graph/graph.h"
#include "tensorflow/core/graph/node_builder.h"
namespace tensorflow {
// TODO(jpienaar): Consider making it a public attribute.
const char* const LowerIfOpPass::kLowerUsingSwitchMergeAttr =
"_lower_using_switch_merge";
namespace {
using NodeOut = NodeBuilder::NodeOut;
// Convenience builder to make it easy to construct a conditional with a single
// function call in the then and else branch. This first converts the if node
// into switches (for inputs) and merges (for outputs) around a function call
// per branch, then inlines the function calls.
class CondBuilder {
public:
enum Branch { kElseBranch = 0, kThenBranch = 1 };
// Create a CondBuilder to create the lowering of If op. that has then and
// else functions named `then_fn_name` and `else_fn_name` respectively in the
// given graph.
CondBuilder(Node* if_op, const string& then_fn_name,
const string& else_fn_name, Graph* graph);
// Constructs the basic conditional control flow using switch and merge nodes.
Status CreatePivotNodes();
// Adds the inputs from the if node to the merge nodes of the lowered if.
Status AddInputs();
// Adds the outputs from the if node to the merge nodes of the lowered if.
// Note: no inputs can be added once outputs are added as the then and else
// nodes are finalized while adding outputs.
Status AddOutputs();
// Builds an identity node with the same outputs as If.
Status BuildLoweredIfOutput();
// Inline call nodes for then and else.
Status InlineCallNodes();
private:
// Returns unique name containing the name of the If op being rewritten
// (name_), infix and a suffix to ensure it is unique within the graph.
string NewName(const string& infix);
// Adds input to both the then and else nodes from src:src_output.
Status AddInput(Node* src, int src_output);
// The merged outputs of the then and else nodes.
std::vector<NodeOut> outputs_;
// The node that dominates all execution of the then and else body nodes.
Node* control_predecessor_;
// The original If op.
Node* if_op_;
// The identity node with the same outputs as the original If op.
Node* lowered_if_output_;
// The predicate of the conditional.
Node* pred_;
// Node corresponding to pivot_f branch of predicate switch which is
// the pivot node that dominates all nodes in the false/else branch.
Node* pivot_f_;
// Node corresponding to pivot_t branch of predicate switch which is
// the pivot node that dominates all nodes in the true/then branch.
Node* pivot_t_;
Node* then_call_node_;
Node* else_call_node_;
Graph* graph_;
string name_;
NodeBuilder then_call_builder_;
NodeBuilder else_call_builder_;
};
CondBuilder::CondBuilder(Node* if_op, const string& then_fn_name,
const string& else_fn_name, Graph* graph)
: if_op_(if_op),
graph_(graph),
name_(if_op->name()),
then_call_builder_(NewName("then"), then_fn_name, graph->op_registry()),
else_call_builder_(NewName("else"), else_fn_name, graph->op_registry()) {
TF_CHECK_OK(if_op_->input_node(0, &pred_));
}
Status CondBuilder::CreatePivotNodes() {
// Construct the basic cond body (consisting of feeding in the predicate to
// create pivot nodes).
Node* switch_pred;
TF_RETURN_IF_ERROR(
NodeBuilder(NewName("switch_pred"), "Switch", graph_->op_registry())
.Input(NodeOut(pred_, 0))
.Input(NodeOut(pred_, 0))
.Finalize(graph_, &switch_pred));
control_predecessor_ = switch_pred;
TF_RETURN_IF_ERROR(
NodeBuilder(NewName("pivot_f"), "Identity", graph_->op_registry())
.Input(switch_pred, kElseBranch)
.Finalize(graph_, &pivot_f_));
TF_RETURN_IF_ERROR(
NodeBuilder(NewName("pivot_t"), "Identity", graph_->op_registry())
.Input(switch_pred, kThenBranch)
.Finalize(graph_, &pivot_t_));
return Status::OK();
}
string CondBuilder::NewName(const string& infix) {
return graph_->NewName(strings::StrCat(name_, "/", infix));
}
Status CondBuilder::AddInput(Node* src, int src_output) {
Node* input;
TF_RETURN_IF_ERROR(
NodeBuilder(NewName(src->name()), "Switch", graph_->op_registry())
.Input(src, src_output)
.Input(pred_, 0)
.Finalize(graph_, &input));
then_call_builder_.Input(input, kThenBranch);
else_call_builder_.Input(input, kElseBranch);
return Status::OK();
}
Status CondBuilder::AddInputs() {
// Add input data edges.
std::vector<const Edge*> edges;
TF_RETURN_IF_ERROR(if_op_->input_edges(&edges));
// Start at index 1 as the first input is the predicate.
for (int i = 1; i < edges.size(); ++i) {
const Edge* e = edges[i];
TF_RETURN_IF_ERROR(AddInput(e->src(), e->src_output()));
}
// Add input control edges.
for (const Edge* e : if_op_->in_edges()) {
if (e->IsControlEdge()) {
graph_->AddControlEdge(e->src(), control_predecessor_);
}
}
return Status::OK();
}
Status CondBuilder::AddOutputs() {
// Construct the then and else nodes.
TF_RETURN_IF_ERROR(then_call_builder_.Finalize(graph_, &then_call_node_));
graph_->AddControlEdge(pivot_t_, then_call_node_);
TF_RETURN_IF_ERROR(else_call_builder_.Finalize(graph_, &else_call_node_));
graph_->AddControlEdge(pivot_f_, else_call_node_);
// Merge the outputs from the two branches.
std::vector<Node*> merges(then_call_node_->num_outputs());
outputs_.resize(merges.size());
for (int i = 0; i < then_call_node_->num_outputs(); ++i) {
TF_RETURN_IF_ERROR(
NodeBuilder(graph_->NewName("merge"), "Merge", graph_->op_registry())
.Input({NodeOut(then_call_node_, i), NodeOut(else_call_node_, i)})
.Finalize(graph_, &merges[i]));
outputs_[i] = NodeOut(merges[i], 0);
}
TF_RETURN_IF_ERROR(BuildLoweredIfOutput());
// Add outputs.
for (const Edge* e : if_op_->out_edges()) {
if (e->IsControlEdge()) {
graph_->AddControlEdge(lowered_if_output_, e->dst());
} else {
// Feed the outputs directly from the merge nodes so that downstream ops
// can start before all the outputs have been computed.
graph_->AddEdge(merges[e->src_output()], e->src_output(), e->dst(),
e->dst_input());
}
}
return Status::OK();
}
Status InlineCallInGraph(Node* n, Graph* g) {
const auto& lib = g->flib_def();
const FunctionDef* fdef = lib.Find(n->type_string());
CHECK(fdef != nullptr);
FunctionBody* fbody;
TF_RETURN_IF_ERROR(
FunctionDefToBodyHelper(*fdef, n->attrs(), &lib,
[&lib](const string& op, const OpDef** sig) {
return lib.LookUpOpDef(op, sig);
},
&fbody));
// TODO(jpienaar): Improve this interface to make the need to delete it
// explicit.
InlineFunctionBody(g->flib_def(), g, n, fbody);
delete fbody;
return Status::OK();
}
Status CondBuilder::BuildLoweredIfOutput() {
// Build the identity node output.
NodeBuilder ib(name_, "IdentityN");
ib.Input(outputs_);
return ib.Finalize(graph_, &lowered_if_output_);
}
Status CondBuilder::InlineCallNodes() {
TF_RETURN_IF_ERROR(InlineCallInGraph(then_call_node_, graph_));
TF_RETURN_IF_ERROR(InlineCallInGraph(else_call_node_, graph_));
return Status::OK();
}
} // namespace
Status LowerIfOpPass::Run(const GraphOptimizationPassOptions& options) {
if (options.partition_graphs != nullptr) {
return errors::Internal(
"Lowering If op should happen before partitioning.");
}
if (options.graph == nullptr) {
return Status::OK();
}
Graph* g = options.graph->get();
if (g == nullptr) {
return errors::Internal("Lowering If op requires a graph to be available.");
}
// Match all the nodes that need to be rewritten.
gtl::InlinedVector<Node*, 2> matches;
for (Node* n : g->op_nodes()) {
if (n->type_string() == "If") {
// Only rewrite if the If op is marked as needing to be lowered.
bool match;
Status s = GetNodeAttr(n->attrs(), kLowerUsingSwitchMergeAttr, &match);
if (s.ok() && match) matches.push_back(n);
}
}
for (Node* n : matches) {
TF_RETURN_IF_ERROR(RewriteNode(n, g));
}
return Status::OK();
}
Status LowerIfOpPass::RewriteNode(Node* n, Graph* g) {
const AttrValue* then_attr = n->attrs().Find("then_branch");
if (then_attr == nullptr) {
return errors::InvalidArgument("Then branch function missing");
}
const AttrValue* else_attr = n->attrs().Find("else_branch");
if (else_attr == nullptr) {
return errors::InvalidArgument("Else branch function missing");
}
CondBuilder cb(n, then_attr->func().name(), else_attr->func().name(), g);
TF_RETURN_IF_ERROR(cb.CreatePivotNodes());
TF_RETURN_IF_ERROR(cb.AddInputs());
TF_RETURN_IF_ERROR(cb.AddOutputs());
TF_RETURN_IF_ERROR(cb.InlineCallNodes());
g->RemoveNode(n);
return Status::OK();
}
REGISTER_OPTIMIZATION(OptimizationPassRegistry::PRE_PLACEMENT, 0,
LowerIfOpPass);
} // namespace tensorflow
| [
"[email protected]"
] | |
ee5de7d3ce5dbe7b88500ddd966b21ff6ccac8f9 | 46999d9c4258959d251c3356beb027f69ea12275 | /Tree/tree.cpp | 5c067120f5221f6b6a9d115991c63f2f3765da94 | [] | no_license | GauravTanwar15/Data-Structures-practice | 9611d2658ea88675b0db021bb8983e1d5bd68cf1 | b85f9f35ab823e86c0eb39f2ca6a4394f40564fd | refs/heads/master | 2023-04-09T21:38:18.132038 | 2021-04-28T14:19:19 | 2021-04-28T14:19:19 | 346,328,604 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,216 | cpp | #include <stdio.h>
#include <stdlib.h>
#include "Queue.h"
struct Node *root=NULL;
void Treecreate()
{
struct Node *p,*t;
int x;
struct Queue q;
create(&q,100);
printf("Eneter root value ");
scanf("%d",&x);
root=(struct Node *)malloc(sizeof(struct Node));
root->data=x;
root->lchild=root->rchild=NULL;
enqueue(&q,root);
while(!isEmpty(q))
{
p=dequeue(&q);
printf("eneter left child of %d ",p->data);
scanf("%d",&x);
if(x!=-1)
{
t=(struct Node *)malloc(sizeof(struct
Node));
t->data=x;
t->lchild=t->rchild=NULL;
p->lchild=t;
enqueue(&q,t);
}
printf("eneter right child of %d ",p->data);
scanf("%d",&x); if(x!=-1)
{
t=(struct Node *)malloc(sizeof(struct
Node));
t->data=x;
t->lchild=t->rchild=NULL;
p->rchild=t;
enqueue(&q,t);
}
}
}
void Preorder(struct Node *p)
{
if(p)
{
printf("%d ",p->data);
Preorder(p->lchild);
Preorder(p->rchild);
}
}
void Inorder(struct Node *p)
{
if(p)
{
Inorder(p->lchild);
printf("%d ",p->data);
Inorder(p->rchild);
}
}
void Postorder(struct Node *p)
{
if(p)
{
Postorder(p->lchild);
Postorder(p->rchild);
printf("%d ",p->data);
}
}int main()
{
Treecreate();
Preorder(root);
printf("\nPost Order ");
Postorder(root);
return 0;
};
| [
"[email protected]"
] | |
dc7a54f7b0ab896b4653a779269a2554f84384c1 | 8aee93ee0dc09c6cf9df91a215713fa957fa883b | /test/config/autogen/fill_style_r.re | f843a5947bbb14d1f52bd46a6926e00616d35dbc | [
"LicenseRef-scancode-warranty-disclaimer",
"LicenseRef-scancode-public-domain"
] | permissive | trofi/re2c | 7bbe5a3ffa6398c69d3e48886fcd2c38f88296c6 | 51c3d5f5acd18da6aea9d3deebc855776344fe8f | refs/heads/master | 2022-07-11T21:33:43.253548 | 2022-07-03T08:24:37 | 2022-07-03T08:24:37 | 270,314,465 | 0 | 0 | NOASSERTION | 2020-06-07T13:25:47 | 2020-06-07T13:25:46 | null | UTF-8 | C++ | false | false | 3,834 | re | // re2c $INPUT -o $OUTPUT -ri
/*!rules:re2c
[a] { a }
* { x }
*/
/*!use:re2c
*/
// re2c:api:style = free-form;
/*!use:re2c
re2c:api:style = free-form;
*/
// re2c:api:style = functions;
/*!use:re2c
re2c:api:style = functions;
*/
// re2c:yyfill:parameter = 0;
/*!use:re2c
re2c:yyfill:parameter = 0;
*/
// re2c:yyfill:parameter = 0;
// re2c:api:style = free-form;
/*!use:re2c
re2c:yyfill:parameter = 0;
re2c:api:style = free-form;
*/
// re2c:yyfill:parameter = 0;
// re2c:api:style = functions;
/*!use:re2c
re2c:yyfill:parameter = 0;
re2c:api:style = functions;
*/
// re2c:yyfill:parameter = 1;
/*!use:re2c
re2c:yyfill:parameter = 1;
*/
// re2c:yyfill:parameter = 1;
// re2c:api:style = free-form;
/*!use:re2c
re2c:yyfill:parameter = 1;
re2c:api:style = free-form;
*/
// re2c:yyfill:parameter = 1;
// re2c:api:style = functions;
/*!use:re2c
re2c:yyfill:parameter = 1;
re2c:api:style = functions;
*/
// re2c:define:YYFILL:naked = 0;
/*!use:re2c
re2c:define:YYFILL:naked = 0;
*/
// re2c:define:YYFILL:naked = 0;
// re2c:api:style = free-form;
/*!use:re2c
re2c:define:YYFILL:naked = 0;
re2c:api:style = free-form;
*/
// re2c:define:YYFILL:naked = 0;
// re2c:api:style = functions;
/*!use:re2c
re2c:define:YYFILL:naked = 0;
re2c:api:style = functions;
*/
// re2c:define:YYFILL:naked = 0;
// re2c:yyfill:parameter = 0;
/*!use:re2c
re2c:define:YYFILL:naked = 0;
re2c:yyfill:parameter = 0;
*/
// re2c:define:YYFILL:naked = 0;
// re2c:yyfill:parameter = 0;
// re2c:api:style = free-form;
/*!use:re2c
re2c:define:YYFILL:naked = 0;
re2c:yyfill:parameter = 0;
re2c:api:style = free-form;
*/
// re2c:define:YYFILL:naked = 0;
// re2c:yyfill:parameter = 0;
// re2c:api:style = functions;
/*!use:re2c
re2c:define:YYFILL:naked = 0;
re2c:yyfill:parameter = 0;
re2c:api:style = functions;
*/
// re2c:define:YYFILL:naked = 0;
// re2c:yyfill:parameter = 1;
/*!use:re2c
re2c:define:YYFILL:naked = 0;
re2c:yyfill:parameter = 1;
*/
// re2c:define:YYFILL:naked = 0;
// re2c:yyfill:parameter = 1;
// re2c:api:style = free-form;
/*!use:re2c
re2c:define:YYFILL:naked = 0;
re2c:yyfill:parameter = 1;
re2c:api:style = free-form;
*/
// re2c:define:YYFILL:naked = 0;
// re2c:yyfill:parameter = 1;
// re2c:api:style = functions;
/*!use:re2c
re2c:define:YYFILL:naked = 0;
re2c:yyfill:parameter = 1;
re2c:api:style = functions;
*/
// re2c:define:YYFILL:naked = 1;
/*!use:re2c
re2c:define:YYFILL:naked = 1;
*/
// re2c:define:YYFILL:naked = 1;
// re2c:api:style = free-form;
/*!use:re2c
re2c:define:YYFILL:naked = 1;
re2c:api:style = free-form;
*/
// re2c:define:YYFILL:naked = 1;
// re2c:api:style = functions;
/*!use:re2c
re2c:define:YYFILL:naked = 1;
re2c:api:style = functions;
*/
// re2c:define:YYFILL:naked = 1;
// re2c:yyfill:parameter = 0;
/*!use:re2c
re2c:define:YYFILL:naked = 1;
re2c:yyfill:parameter = 0;
*/
// re2c:define:YYFILL:naked = 1;
// re2c:yyfill:parameter = 0;
// re2c:api:style = free-form;
/*!use:re2c
re2c:define:YYFILL:naked = 1;
re2c:yyfill:parameter = 0;
re2c:api:style = free-form;
*/
// re2c:define:YYFILL:naked = 1;
// re2c:yyfill:parameter = 0;
// re2c:api:style = functions;
/*!use:re2c
re2c:define:YYFILL:naked = 1;
re2c:yyfill:parameter = 0;
re2c:api:style = functions;
*/
// re2c:define:YYFILL:naked = 1;
// re2c:yyfill:parameter = 1;
/*!use:re2c
re2c:define:YYFILL:naked = 1;
re2c:yyfill:parameter = 1;
*/
// re2c:define:YYFILL:naked = 1;
// re2c:yyfill:parameter = 1;
// re2c:api:style = free-form;
/*!use:re2c
re2c:define:YYFILL:naked = 1;
re2c:yyfill:parameter = 1;
re2c:api:style = free-form;
*/
// re2c:define:YYFILL:naked = 1;
// re2c:yyfill:parameter = 1;
// re2c:api:style = functions;
/*!use:re2c
re2c:define:YYFILL:naked = 1;
re2c:yyfill:parameter = 1;
re2c:api:style = functions;
*/
| [
"[email protected]"
] | |
319f1362d4f6a0ba0dca77fd262907e8cbb69e9c | 839dcaa6cae01eb243d3a1be3754249a5018112f | /Practica_2/include/Thread_Structure.h | 619d7f17b3c0512ecafeb586c38614b53e92022f | [] | no_license | ERV501/SSOOII_P2 | 2ad5d91f0ce62635f0cc448fc8b212d2e9b6df48 | 42b47876cadfd121b88f45858ca1f3e29d21dd91 | refs/heads/main | 2023-02-27T08:33:25.039903 | 2021-02-02T21:48:14 | 2021-02-02T21:48:14 | 335,444,268 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 693 | h | #pragma once
#include "../include/Result_Structure.h"
#include "../include/definitions.h"
#include <iostream>
#include <fstream>
#include <thread>
#include <list>
#include <string>
using namespace std;
class Thread_Structure{
private:
int task_begin;
int task_end;
int n_thread;
string task_word;
string file_name;
list <Result_Structure> result_list;
public:
Thread_Structure(int task_begin, int task_end,string task_word,string file_name,int n_thread);
~Thread_Structure();
int getTask_begin();
int getTask_end();
string getTask_word();
string getFile_name();
void pushResult_list(Result_Structure result_s);
void toString();
}; | [
"[email protected]"
] | |
cb54a5b8dc3aa498eea8164e53efd0d9c2f2d9bb | d70ad481a9fd1f2feb968afd1af272cfa001cdd7 | /AMod/MolTopo.h | b38fbb09b4259d752e5d86598a730a5647d28082 | [] | no_license | hoang6/2D-materials | 1f34346a97c84e510867569376315defcb3d5fb7 | d0946a119e0e0b9a273f9196b336fbe53e23e2a7 | refs/heads/master | 2021-01-01T05:15:48.811837 | 2016-05-12T20:08:29 | 2016-05-12T20:08:29 | 58,672,222 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,219 | h | #ifndef _AMOD_MOL_TOPO_H
#define _AMOD_MOL_TOPO_H
#include "MolService.h"
#include "Atom.h"
#include "Trans.h"
#include "../Util/Accessors.h"
#include "../Util/PtrCont.h"
#include "../Util/Array2D.h"
#include <map>
#include <list>
#include <vector>
namespace AMod {
class Molecule;
typedef enum {MODE_NULL = 0, MODE_FREEZE, MODE_CELL} MolTopoMode;
typedef enum {CASE_AXES = 0, CASE_LONELY, CASE_BRUTAL, CASE_GENERAL,
CASE_CHANGE_MODE, CASE_ROTATION, CASE_TRANSLATION } MolTopoCase;
class MolTopo: public MolServ {
public:
MolTopo();
MolTopo(Molecule& _mol);
MolTopo(const MolTopo& molTopo);
MolTopo& operator= (const MolTopo& molTopo);
void reset();
void clear();
/********** sync & update **********/
void sync(); //will not change existing topology
void update(MolTopoCase _case); //update for global changes
/********** new/del/move atom **********/
Atom& newAtom(int _atomID, Atom::Data& _atomData);
void deleteAtom(int _atomID);
Atom& moveAtom(int _atomID);
/********** make/new/move lonely atom **********/
Atom& newLonelyAtom(int _atomID, Atom::Data& _atomData);
Atom& moveLonelyAtom(int _atomID);
Atom& makeLonelyAtom(int _atomID);
/********** new/del bond **********/
Bond& newBond(int _atomID1, int _atomID2);
Bond& newBond(int _atomID1, int _atomID2, const int* _n);
void deleteBond(int _bondID);
/********** metric **********/
double distance(int _atomID, const double _x[3]) const;
double distance(int _atomID1, int _atomID2) const;
void displacement(int _atomID1, int _atomID2, double* _dx) const;
/********** utilities **********/
bool bondok(int _bondID) const; //is bondRange().ok?
int bondID(int _atomID1, int _atomID2) const;
int atomID(const double* _x) const;
int atomID(const double* _x, double& _rmin) const;
void around(const double* _x, int _atomID);
void around(const double* _x);
/********** set & get **********/
int natoms() const;
int nbonds() const;
Atom& atom(int _atomID);
Bond& bond(int _bondID);
const Atom& atom(int _atomID) const;
const Bond& bond(int _bondID) const;
const Trans& trans() const;
Util::Accessors<MolTopoMode> mode;
Util::Accessors<BondRange> bondRange;
Util::Accessors<double> cellLength;
protected:
struct Cell;
struct A2CLink;
typedef std::list<Atom*> AtomPtrList;
typedef std::map<Cell,AtomPtrList> C2ALinks;
typedef Util::PtrCont<A2CLink> A2CLinks;
typedef Util::Array2D<double,3,3> Axes;
friend class MolChecker; //for debug
/********** clone topology **********/
void clone(const MolTopo& molTopo);
/********** manage cell **********/
void setupTrans();
void setupCells(double _cellLength);
void clearCells();
void whatCell(const double* _x, Cell& _cell) const;
void updateCellsNewAtom(int _atomID);
void updateCellsDeleteAtom(int _atomID);
void updateCellsMoveAtom(int _atomID);
void updateSoftConnection(int _bondID);
void updateHardConnection(int _atomID, bool _single);
bool newHardBond(int _atomID1, int _atomID2);
/********** connect atoms **********/
void setupAxes();
void setupConnection();
void updateConnection(MolTopoMode _mode);
void updateConnection(MolTopoMode _mode, int _atomID);
void clearConnection();
void clearConnection(int _atomID);
Trans tr, ctr;
Axes cellAxes;
int ncell[3];
C2ALinks c2aLinks;
A2CLinks a2cLinks;
Util::Accessors<Atoms> atoms;
Util::Accessors<Bonds> bonds;
struct Cell {
int x[3];
bool operator== (const Cell& rhs) const;
bool operator< (const Cell& rhs) const;
};
struct A2CLink {
Cell cell;
Util::PtrCont<A2CLink>::ID id;
};
};
/************************************************************/
inline int MolTopo::natoms() const { return atoms().size(); }
inline int MolTopo::nbonds() const { return bonds().size(); }
inline Atom& MolTopo::atom(int _atomID) { return atoms()[_atomID]; }
inline Bond& MolTopo::bond(int _bondID) { return bonds()[_bondID]; }
inline const Atom& MolTopo::atom(int _atomID) const { return atoms()[_atomID]; }
inline const Bond& MolTopo::bond(int _bondID) const { return bonds()[_bondID]; }
inline const Trans& MolTopo::trans() const { return tr; }
}/* AMod */
#endif
| [
"[email protected]"
] | |
13b385cab0642aedb9f3acdd15d5af8af7681073 | d2a12d935fb1d6cf1798cb4595c5652151f92714 | /examples/lock-app/esp32/main/DeviceCallbacks.cpp | 408a25a82e506286524f95a2dacbd4461970caac | [
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | RunnerL/connectedhomeip | eafe2b70561483f19e10a0fa3de3077dbfc53f99 | ebd9e0a2b1a00d71918b2bd223e1da1ae120466e | refs/heads/master | 2023-05-21T11:32:41.864533 | 2021-05-26T02:51:24 | 2021-05-26T02:51:24 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,042 | cpp | /*
*
* Copyright (c) 2020 Project CHIP Authors
* All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* @file DeviceCallbacks.cpp
*
* Implements all the callbacks to the application from the CHIP Stack
*
**/
#include "DeviceCallbacks.h"
#include "esp_heap_caps.h"
#include "esp_log.h"
#include <app/common/gen/attribute-id.h>
#include <app/common/gen/cluster-id.h>
#include <support/CodeUtils.h>
static const char * TAG = "lock-devicecallbacks";
using namespace ::chip;
using namespace ::chip::Inet;
using namespace ::chip::System;
using namespace ::chip::DeviceLayer;
void DeviceCallbacks::DeviceEventCallback(const ChipDeviceEvent * event, intptr_t arg)
{
switch (event->Type)
{
case DeviceEventType::kInternetConnectivityChange:
OnInternetConnectivityChange(event);
break;
case DeviceEventType::kSessionEstablished:
OnSessionEstablished(event);
break;
}
ESP_LOGI(TAG, "Current free heap: %d\n", heap_caps_get_free_size(MALLOC_CAP_8BIT));
}
void DeviceCallbacks::PostAttributeChangeCallback(EndpointId endpointId, ClusterId clusterId, AttributeId attributeId, uint8_t mask,
uint16_t manufacturerCode, uint8_t type, uint16_t size, uint8_t * value)
{
ESP_LOGI(TAG, "PostAttributeChangeCallback - Cluster ID: '0x%04x', EndPoint ID: '0x%02x', Attribute ID: '0x%04x'", clusterId,
endpointId, attributeId);
ESP_LOGI(TAG, "Unhandled cluster ID: %d", clusterId);
ESP_LOGI(TAG, "Current free heap: %d\n", heap_caps_get_free_size(MALLOC_CAP_8BIT));
}
void DeviceCallbacks::OnInternetConnectivityChange(const ChipDeviceEvent * event)
{
if (event->InternetConnectivityChange.IPv4 == kConnectivity_Established)
{
ESP_LOGI(TAG, "Server ready at: %s:%d", event->InternetConnectivityChange.address, CHIP_PORT);
}
else if (event->InternetConnectivityChange.IPv4 == kConnectivity_Lost)
{
ESP_LOGE(TAG, "Lost IPv4 connectivity...");
}
if (event->InternetConnectivityChange.IPv6 == kConnectivity_Established)
{
ESP_LOGI(TAG, "IPv6 Server ready...");
}
else if (event->InternetConnectivityChange.IPv6 == kConnectivity_Lost)
{
ESP_LOGE(TAG, "Lost IPv6 connectivity...");
}
}
void DeviceCallbacks::OnSessionEstablished(const ChipDeviceEvent * event)
{
if (event->SessionEstablished.IsCommissioner)
{
ESP_LOGI(TAG, "Commissioner detected!");
}
}
| [
"[email protected]"
] | |
9ff618b3182a81cc87114c43a98014792f8c033c | f5340054536ff4f68736f51b1347b52c88880aab | /vcl/shape/mesh/mesh_primitive/mesh_primitive.cpp | 452de27a9d01e3f4660e2bc2b8d6f5f66a62b491 | [] | no_license | aliciafmachado/minecraft-clone | 0e853b2f8fb0855511d705723f32aee1299aee54 | 126a45fa1180839112a17681372ced909e1fa379 | refs/heads/master | 2023-01-22T13:08:10.981919 | 2020-12-07T17:47:07 | 2020-12-07T17:47:07 | 265,665,442 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 14,053 | cpp | #include "mesh_primitive.hpp"
#include "vcl/math/math.hpp"
namespace vcl
{
std::vector<uint3> connectivity_grid(size_t Nu, size_t Nv, bool periodic_u, bool periodic_v)
{
std::vector<std::array<unsigned int,3> > triangle_index;
for(size_t ku=0; ku<Nu-1; ++ku) {
for( size_t kv=0; kv<Nv-1; ++kv) {
const unsigned int u00 = static_cast<unsigned int>( kv + Nv*ku );
const unsigned int u10 = static_cast<unsigned int>( kv+1 + Nv*ku );
const unsigned int u01 = static_cast<unsigned int>( kv + Nv*(ku+1) );
const unsigned int u11 = static_cast<unsigned int>( kv+1 + Nv*(ku+1) );
triangle_index.push_back({u00,u10,u11});
triangle_index.push_back({u11,u01,u00});
}
}
if( periodic_u==true ) {
for( size_t kv=0; kv<Nv-1; ++kv ) {
const unsigned int u00 = static_cast<unsigned int>( kv + Nv*(Nu-1) );
const unsigned int u10 = static_cast<unsigned int>( kv+1 + Nv*(Nu-1) );
const unsigned int u01 = static_cast<unsigned int>( kv + Nv*0 );
const unsigned int u11 = static_cast<unsigned int>( kv+1 + Nv*0 );
triangle_index.push_back({u00,u10,u11});
triangle_index.push_back({u11,u01,u00});
}
}
if( periodic_v==true ) {
for( size_t ku=0; ku<Nu-1; ++ku ) {
const unsigned int u00 = static_cast<unsigned int>( Nv-1 + Nv*ku );
const unsigned int u10 = static_cast<unsigned int>( 0 + Nv*ku );
const unsigned int u01 = static_cast<unsigned int>( Nv-1 + Nv*(ku+1) );
const unsigned int u11 = static_cast<unsigned int>( 0 + Nv*(ku+1) );
triangle_index.push_back({u00,u10,u11});
triangle_index.push_back({u11,u01,u00});
}
}
if( periodic_u==true && periodic_v==true )
{
const unsigned int u00 = static_cast<unsigned int>( Nv-1 + Nv*(Nu-1) );
const unsigned int u10 = static_cast<unsigned int>( 0 + Nv*(Nu-1) );
const unsigned int u01 = static_cast<unsigned int>( Nv-1 + Nv*0 );
const unsigned int u11 = static_cast<unsigned int>( 0 + Nv*0 );
triangle_index.push_back({u00,u10,u11});
triangle_index.push_back({u11,u01,u00});
}
return triangle_index;
}
mesh mesh_primitive_ellipsoid(float radius0, float radius1, float radius2, const vec3& center, size_t Nu, size_t Nv)
{
mesh shape;
for( size_t ku=0; ku<Nu; ++ku ) {
for( size_t kv=0; kv<Nv; ++kv ) {
const float u = static_cast<float>(ku)/static_cast<float>(Nu-1);
const float v = static_cast<float>(kv)/static_cast<float>(Nv);
const float theta = static_cast<float>( 3.14159f*u );
const float phi = static_cast<float>( 2*3.14159f*v );
const float x = radius0 * std::sin(theta) * std::cos(phi);
const float y = radius1 * std::sin(theta) * std::sin(phi);
const float z = radius2 * std::cos(theta);
const vec3 p = {x,y,z};
const vec3 n = normalize(p);
shape.position.push_back( p+center );
shape.normal.push_back( n );
}
}
shape.connectivity = connectivity_grid(Nu, Nv, false, true);
return shape;
}
mesh mesh_primitive_sphere(float radius, const vec3& p0, size_t Nu, size_t Nv)
{
assert(Nu>=4);
assert(Nv>=4);
mesh shape;
for( size_t ku=0; ku<Nu; ++ku ) {
for( size_t kv=0; kv<Nv; ++kv ) {
// Parametric coordinates
const float u = static_cast<float>(ku)/static_cast<float>(Nu-1);
const float v = static_cast<float>(kv)/static_cast<float>(Nv-1);
// Angles
const float theta = static_cast<float>( 3.14159f*v );
const float phi = static_cast<float>( 2*3.14159f*u );
// Spherical coordinates
const float x = radius * std::sin(theta) * std::cos(phi);
const float y = radius * std::sin(theta) * std::sin(phi);
const float z = radius * std::cos(theta);
const vec3 p = {x,y,z}; // Position (centered)
const vec3 n = normalize(p); // Normal
const vec2 uv = {v,u}; // Texture-coordinates
shape.position.push_back( p+p0 ); // Add new position (with translation of the center)
shape.normal.push_back( n );
shape.texture_uv.push_back(uv);
}
}
shape.connectivity = connectivity_grid(Nu, Nv, false, false);
return shape;
}
mesh mesh_primitive_cylinder(float radius, const vec3& p1, const vec3& p2, size_t Nu, size_t Nv, bool is_border_duplicated)
{
const vec3 p12 = p2-p1;
const float L = norm(p12);
const vec3 dir = p12/L;
const mat3 R = rotation_between_vector_mat3({0,0,1}, dir);
mesh shape;
float const Nu_interval = is_border_duplicated? float(Nu) : float(Nu-1);
for( size_t ku=0; ku<Nu; ++ku ) {
for( size_t kv=0; kv<Nv; ++kv ) {
const float u = static_cast<float>(ku)/Nu_interval;
const float v = static_cast<float>(kv)/static_cast<float>(Nv-1);
const float theta = static_cast<float>( 2* 3.14159f * u );
const float x = radius * std::sin(theta);
const float y = radius * std::cos(theta);
const float z = L * v;
const vec3 p0 = {x,y,z};
const vec3 p = R*p0+p1;
const vec3 n = normalize(R*vec3{x,y,0.0f});
const vec2 uv = {u,v};
shape.position.push_back( p );
shape.normal.push_back( n );
shape.texture_uv.push_back(uv);
}
}
shape.connectivity = connectivity_grid(Nu, Nv, is_border_duplicated, false);
return shape;
}
mesh mesh_primitive_torus(float R, float r, const vec3& center, const vec3& axis_direction, size_t Nu, size_t Nv, bool is_border_duplicated)
{
const mat3 Rotation = rotation_between_vector_mat3({0,0,1},axis_direction);
mesh shape;
float const Nu_interval = is_border_duplicated? float(Nu) : float(Nu-1);
float const Nv_interval = is_border_duplicated? float(Nv) : float(Nv-1);
for( size_t ku=0; ku<Nu; ++ku ) {
for( size_t kv=0; kv<Nv; ++kv ) {
const float u = static_cast<float>(ku)/Nu_interval;
const float v = static_cast<float>(kv)/Nv_interval;
const float theta = static_cast<float>( 2* 3.14159f * u );
const float phi = static_cast<float>( 2* 3.14159f * v );
const vec3 p0 = {(R+r*std::cos(theta)) * std::cos(phi),
(R+r*std::cos(theta)) * std::sin(phi),
r*std::sin(theta) };
const vec3 d_theta = {-r*std::sin(theta)*std::cos(phi), -r*std::sin(theta)*std::sin(phi), r*std::cos(theta)};
const vec3 d_phi = {-(R+r*std::cos(theta))*std::sin(phi), (R+r*std::cos(theta))*std::cos(phi), 0};
const vec3 n = normalize(cross(d_theta,d_phi));
const vec2 uv = {u,v};
shape.position.push_back( Rotation*p0+center );
shape.normal.push_back( n );
shape.texture_uv.push_back(uv);
}
}
shape.connectivity = connectivity_grid(Nu, Nv, is_border_duplicated, is_border_duplicated);
return shape;
}
mesh mesh_primitive_cone(float radius, const vec3& p1, const vec3& p2, size_t Nu, size_t Nv)
{
const vec3 p12 = p2-p1;
const float L = norm(p12);
const vec3 dir = p12/L;
const mat3 R = rotation_between_vector_mat3({0,0,1},dir);
mesh shape;
for( size_t ku=0; ku<Nu; ++ku ) {
for( size_t kv=0; kv<Nv; ++kv ) {
const float u = static_cast<float>(ku)/static_cast<float>(Nu);
const float v = static_cast<float>(kv)/static_cast<float>(Nv-1);
const float theta = static_cast<float>( 2* 3.14159f * u );
const float alpha = 1.0f-v;
const float x = alpha*radius * std::sin(theta);
const float y = alpha*radius * std::cos(theta);
const float z = L * v;
const vec3 p0 = {x,y,z};
const vec3 p = R*p0+p1;
const vec3 normal_d = R*vec3{x,y,0.0f};
const float normal_n = norm(normal_d);
vec3 n = normal_d;
if( normal_n>1e-6f )
n /= normal_n;
else
n = {0,0,1};
shape.position.push_back( p );
shape.normal.push_back( n );
}
}
shape.connectivity = connectivity_grid(Nu, Nv, true, false);
return shape;
}
mesh mesh_primitive_frame(float sphere_radius, float cylinder_radius, float cone_radius, float cone_length)
{
mesh sphere = mesh_primitive_sphere(sphere_radius); sphere.fill_color_uniform({1,1,1});
mesh cylinder_x = mesh_primitive_cylinder(cylinder_radius,{0,0,0},{1.0f-cone_length,0,0}); cylinder_x.fill_color_uniform({1,0,0});
mesh cylinder_y = mesh_primitive_cylinder(cylinder_radius,{0,0,0},{0,1.0f-cone_length,0}); cylinder_y.fill_color_uniform({0,1,0});
mesh cylinder_z = mesh_primitive_cylinder(cylinder_radius,{0,0,0},{0,0,1.0f-cone_length}); cylinder_z.fill_color_uniform({0,0,1});
mesh cone_x = mesh_primitive_cone(cone_radius,{1.0f-cone_length,0,0},{1.0f,0,0}); cone_x.fill_color_uniform({1,0,0});
mesh cone_y = mesh_primitive_cone(cone_radius,{0,1.0f-cone_length,0},{0,1.0f,0}); cone_y.fill_color_uniform({0,1,0});
mesh cone_z = mesh_primitive_cone(cone_radius,{0,0,1.0f-cone_length},{0,0,1.0f}); cone_z.fill_color_uniform({0,0,1});
mesh m;
m.push_back(sphere);
m.push_back(cylinder_x);
m.push_back(cylinder_y);
m.push_back(cylinder_z);
m.push_back(cone_x);
m.push_back(cone_y);
m.push_back(cone_z);
return m;
}
mesh mesh_primitive_quad(const vec3& p00, const vec3& p10, const vec3& p11, const vec3& p01)
{
// Compute normal of the quadrangle (orthogonal to the two basis vectors p00->p01 and p00->p10)
const vec3 n = normalize(cross(normalize(p10-p00), normalize(p01-p00)));
// Fill per-vertex buffers
mesh quad;
quad.position = {p00, p10, p11, p01}; // 3D-coordinates
quad.normal = {n,n,n,n}; // same normal for all vertices
quad.texture_uv = {{0,0}, {1,0}, {1,1}, {0,1}}; // 2D (u,v) - texture coordinates
quad.connectivity = {{0,1,2}, {0,2,3}}; // Quadrangle made up of two triangles
return quad;
}
mesh mesh_primitive_disc(float radius, const vec3& p0, const vec3& n, size_t N)
{
mesh disc;
mat3 R = rotation_between_vector_mat3({0,0,1},n);
for(size_t k=0; k<N; ++k)
{
const float u = static_cast<float>(k)/(static_cast<float>(N)-1.0f);
const float theta = 2*static_cast<float>(3.14159f)*u;
const vec3 p = R*vec3(radius*std::cos(theta),radius*std::sin(theta),0.0f);
disc.position.push_back(p0+p);
disc.normal.push_back(n);
disc.connectivity.push_back( {static_cast<unsigned int>( k ),
static_cast<unsigned int>((k+1)%N),
static_cast<unsigned int>( N )});
}
// add central point
disc.position.push_back(p0);
disc.normal.push_back(n);
return disc;
}
mesh mesh_primitive_grid(size_t Nu, size_t Nv, const vec3& p0, const vec3& direction_u, const vec3& direction_v)
{
mesh shape;
for( size_t kv=0; kv<Nv; ++kv ) {
for( size_t ku=0; ku<Nu; ++ku ) {
const float u = static_cast<float>(ku)/static_cast<float>(Nu-1);
const float v = static_cast<float>(kv)/static_cast<float>(Nv-1);
const vec3 position = u*direction_u + v*direction_v + p0;
const vec3 normal = normalize(cross(direction_u, direction_v));
shape.position.push_back( position );
shape.normal.push_back( normal );
shape.texture_uv.push_back({u,1.0f-v});
}
}
shape.connectivity = connectivity_grid(Nv, Nu, false, false);
return shape;
}
mesh mesh_primitive_parallelepiped(const vec3& p0, const vec3& u1, const vec3& u2, const vec3& u3)
{
const vec3 p000 = p0;
const vec3 p100 = p0+u1;
const vec3 p010 = p0+u2;
const vec3 p001 = p0+u3;
const vec3 p110 = p0+u1+u2;
const vec3 p101 = p0+u1+u3;
const vec3 p011 = p0+u2+u3;
const vec3 p111 = p0+u1+u2+u3;
mesh shape;
shape.position = {p000, p100, p110, p010,
p100, p101, p111, p110,
p110, p111, p011, p010,
p000, p001, p011, p010,
p000, p001, p101, p100,
p101, p001, p011, p111};
const vec3 n1 = normalize(u1);
const vec3 n2 = normalize(u2);
const vec3 n3 = normalize(u3);
shape.normal = {-n3, -n3, -n3, -n3,
n1, n1, n1, n1,
n2, n2, n2, n2,
-n1, -n1, -n1, -n1,
-n2, -n2, -n2, -n2,
n3, n3, n3, n3};
shape.connectivity = {{0,1,2}, {0,2,3},
{4,5,6}, {4,6,7},
{8,9,10}, {8,10,11},
{12,13,14}, {12,14,15},
{16,17,18}, {16,18,19},
{20,21,22}, {20,22,23}};
return shape;
}
mesh mesh_primitive_bar_grid(int Nu, int Nv , int Nw, const vec3& p0, const vec3& direction_u, const vec3& direction_v, const vec3& direction_w)
{
const vec3 p1 = p0 + direction_u+direction_v+direction_w;
mesh shape = mesh_primitive_grid(Nv,Nu, p0, direction_v, direction_u);
shape.push_back(mesh_primitive_grid(Nu,Nw, p0, direction_u, direction_w));
shape.push_back(mesh_primitive_grid(Nw,Nv, p0, direction_w, direction_v));
shape.push_back(mesh_primitive_grid(Nu,Nv, p1, -direction_u, -direction_v));
shape.push_back(mesh_primitive_grid(Nw,Nu, p1, -direction_w, -direction_u));
shape.push_back(mesh_primitive_grid(Nv,Nw, p1, -direction_v, -direction_w));
return shape;
}
}
| [
"[email protected]"
] | |
1afa50159a980bbea8a6a19a3ddfcd473eeb66cf | 3366bb6ef42307f64db392fc84f01c39ca627489 | /example/example.cpp | c15c7357895747f2d96d0d24a2c6a03e6e49089e | [
"MIT"
] | permissive | psigen/rules_debian | 0d6cce7204931dc7fbe8af6a5314a838135179f8 | e374e319b864d5bd251407565eebc8ddf0e6597f | refs/heads/master | 2023-03-06T22:54:05.907490 | 2023-02-20T23:39:17 | 2023-02-20T23:39:17 | 260,598,751 | 2 | 3 | MIT | 2023-02-20T23:25:52 | 2020-05-02T02:25:54 | Starlark | UTF-8 | C++ | false | false | 567 | cpp | ///
/// Adapted from The Boost C++ Libraries: Boost.System, Example 55.5
/// See: https://theboostcpplibraries.com/boost.system
///
#include <boost/system/error_code.hpp>
#include <boost/system/system_error.hpp>
#include <iostream>
using namespace boost::system;
void fail()
{
throw system_error{errc::make_error_code(errc::not_supported)};
}
int main()
{
try
{
fail();
}
catch (system_error &e)
{
error_code ec = e.code();
std::cerr << ec.value() << '\n';
std::cerr << ec.category().name() << '\n';
}
}
| [
"[email protected]"
] | |
71267d30a01898053aa4b2d1a80d6bf4bb8c94b5 | 48298469e7d828ab1aa54a419701c23afeeadce1 | /Client/OGRE/PlugIns/BSPSceneManager/src/OgreBspNode.cpp | 7ec6a2287fe211cb7ed7eca9ef43ff9ca2927626 | [] | no_license | brock7/TianLong | c39fccb3fd2aa0ad42c9c4183d67a843ab2ce9c2 | 8142f9ccb118e76a5cd0a8b168bcf25e58e0be8b | refs/heads/master | 2021-01-10T14:19:19.850859 | 2016-02-20T13:58:55 | 2016-02-20T13:58:55 | 52,155,393 | 5 | 3 | null | null | null | null | UTF-8 | C++ | false | false | 6,516 | cpp | /*
-----------------------------------------------------------------------------
This source file is part of OGRE
(Object-oriented Graphics Rendering Engine)
For the latest info, see http://www.ogre3d.org/
Copyright (c) 2000-2005 The OGRE Team
Also see acknowledgements in Readme.html
This program 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; either version 2 of the License, or (at your option) any later
version.
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 Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License along with
this program; if not, write to the Free Software Foundation, Inc., 59 Temple
Place - Suite 330, Boston, MA 02111-1307, USA, or go to
http://www.gnu.org/copyleft/lesser.txt.
-----------------------------------------------------------------------------
*/
#include "OgreBspNode.h"
#include "OgreBspLevel.h"
#include "OgreException.h"
#include "OgreLogManager.h"
namespace Ogre {
//-----------------------------------------------------------------------
BspNode::BspNode(BspLevel* owner, bool isLeaf)
{
mOwner = owner;
mIsLeaf = isLeaf;
}
//-----------------------------------------------------------------------
BspNode::BspNode()
{
}
//-----------------------------------------------------------------------
BspNode::~BspNode()
{
}
//-----------------------------------------------------------------------
bool BspNode::isLeaf(void) const
{
return mIsLeaf;
}
//-----------------------------------------------------------------------
BspNode* BspNode::getFront(void) const
{
if (mIsLeaf)
OGRE_EXCEPT(Exception::ERR_INVALIDPARAMS,
"This method is not valid on a leaf node.",
"BspNode::getFront");
return mFront;
}
//-----------------------------------------------------------------------
BspNode* BspNode::getBack(void) const
{
if (mIsLeaf)
OGRE_EXCEPT(Exception::ERR_INVALIDPARAMS,
"This method is not valid on a leaf node.",
"BspNode::getBack");
return mBack;
}
//-----------------------------------------------------------------------
const Plane& BspNode::getSplitPlane(void) const
{
if (mIsLeaf)
OGRE_EXCEPT(Exception::ERR_INVALIDPARAMS,
"This method is not valid on a leaf node.",
"BspNode::getSplitPlane");
return mSplitPlane;
}
//-----------------------------------------------------------------------
const AxisAlignedBox& BspNode::getBoundingBox(void) const
{
if (!mIsLeaf)
OGRE_EXCEPT(Exception::ERR_INVALIDPARAMS,
"This method is only valid on a leaf node.",
"BspNode::getBoundingBox");
return mBounds;
}
//-----------------------------------------------------------------------
int BspNode::getNumFaceGroups(void) const
{
if (!mIsLeaf)
OGRE_EXCEPT(Exception::ERR_INVALIDPARAMS,
"This method is only valid on a leaf node.",
"BspNode::getNumFaces");
return mNumFaceGroups;
}
//-----------------------------------------------------------------------
int BspNode::getFaceGroupStart(void) const
{
if (!mIsLeaf)
OGRE_EXCEPT(Exception::ERR_INVALIDPARAMS,
"This method is only valid on a leaf node.",
"BspNode::getFaces");
return mFaceGroupStart;
}
//-----------------------------------------------------------------------
bool BspNode::isLeafVisible(const BspNode* leaf) const
{
return mOwner->isLeafVisible(this, leaf);
}
//-----------------------------------------------------------------------
Plane::Side BspNode::getSide (const Vector3& point) const
{
if (mIsLeaf)
OGRE_EXCEPT(Exception::ERR_INVALIDPARAMS,
"This method is not valid on a leaf node.",
"BspNode::getSide");
return mSplitPlane.getSide(point);
}
//-----------------------------------------------------------------------
BspNode* BspNode::getNextNode(const Vector3& point) const
{
if (mIsLeaf)
OGRE_EXCEPT(Exception::ERR_INVALIDPARAMS,
"This method is not valid on a leaf node.",
"BspNode::getNextNode");
Plane::Side sd = getSide(point);
if (sd == Plane::NEGATIVE_SIDE)
{
//LogManager::getSingleton().logMessage("back");
return getBack();
}
else
{
//LogManager::getSingleton().logMessage("front");
return getFront();
}
}
//-----------------------------------------------------------------------
void BspNode::_addMovable(const MovableObject* mov)
{
mMovables.insert(mov);
}
//-----------------------------------------------------------------------
void BspNode::_removeMovable(const MovableObject* mov)
{
mMovables.erase(mov);
}
//-----------------------------------------------------------------------
Real BspNode::getDistance(const Vector3& pos) const
{
if (mIsLeaf)
OGRE_EXCEPT(Exception::ERR_INVALIDPARAMS,
"This method is not valid on a leaf node.",
"BspNode::getSide");
return mSplitPlane.getDistance(pos);
}
//-----------------------------------------------------------------------
const BspNode::NodeBrushList& BspNode::getSolidBrushes(void) const
{
return mSolidBrushes;
}
//-----------------------------------------------------------------------
std::ostream& operator<< (std::ostream& o, BspNode& n)
{
o << "BspNode(";
if (n.mIsLeaf)
{
o << "leaf, bbox=" << n.mBounds << ", cluster=" << n.mVisCluster;
o << ", faceGrps=" << n.mNumFaceGroups << ", faceStart=" << n.mFaceGroupStart << ")";
}
else
{
o << "splitter, plane=" << n.mSplitPlane << ")";
}
return o;
}
}
| [
"[email protected]"
] | |
8415d6ed9a6358e2f3071d0cf59d39f222b9fc8f | 93925ac586cd1d70b2bf6efe7ac43498877a17b8 | /HackerRank/Algorithms/Warmup/Simple Array Sum.cpp | b7ed07c61ffeada96cb8c9a06d7fbdea7bbd048e | [] | no_license | LeeSongA/Coding | 10bbb734d9bac157fdebbd184f1d2c2e904e1d1b | f261e885f998a0aa37206bab36409626a0b88ce9 | refs/heads/master | 2022-01-15T16:03:37.102635 | 2019-06-05T05:50:10 | 2019-06-05T05:50:10 | 113,270,930 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,611 | cpp | #include <bits/stdc++.h>
using namespace std;
vector<string> split_string(string);
/*
* Complete the simpleArraySum function below.
*/
int simpleArraySum(vector<int> ar) {
int sum = 0;
for (int ar_itr = 0; ar_itr < ar.size(); ar_itr++) {
sum += ar[ar_itr];
}
return sum;
}
int main()
{
ofstream fout(getenv("OUTPUT_PATH"));
int ar_count;
cin >> ar_count;
cin.ignore(numeric_limits<streamsize>::max(), '\n');
string ar_temp_temp;
getline(cin, ar_temp_temp);
vector<string> ar_temp = split_string(ar_temp_temp);
vector<int> ar(ar_count);
for (int ar_itr = 0; ar_itr < ar_count; ar_itr++) {
int ar_item = stoi(ar_temp[ar_itr]);
ar[ar_itr] = ar_item;
}
int result = simpleArraySum(ar);
fout << result << "\n";
fout.close();
return 0;
}
vector<string> split_string(string input_string) {
string::iterator new_end = unique(input_string.begin(), input_string.end(), [] (const char &x, const char &y) {
return x == y and x == ' ';
});
input_string.erase(new_end, input_string.end());
while (input_string[input_string.length() - 1] == ' ') {
input_string.pop_back();
}
vector<string> splits;
char delimiter = ' ';
size_t i = 0;
size_t pos = input_string.find(delimiter);
while (pos != string::npos) {
splits.push_back(input_string.substr(i, pos - i));
i = pos + 1;
pos = input_string.find(delimiter, i);
}
splits.push_back(input_string.substr(i, min(pos, input_string.length()) - i + 1));
return splits;
} | [
"[email protected]"
] | |
8a84c85b5f2a0129f433573a602530eed04e0dd5 | 23695d2dc657907d97607d2fd9ff8a62dcb42ee9 | /water/logs/flush_thread.hpp | af72ef16b3de6613b75ab4ea2b46d4c82b13c1b8 | [
"MIT"
] | permissive | watercpp/water | 3833e1c6e5d86f5dbebc154f733c0955ef71f7e4 | 446af3faf96e2a4daecdb65121b8c9fd0d891df9 | refs/heads/master | 2023-08-22T21:07:42.894764 | 2023-08-20T13:43:28 | 2023-08-20T13:43:28 | 86,233,011 | 7 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,274 | hpp | // Copyright 2023 Johan Paulsson
// This file is part of the Water C++ Library. It is licensed under the MIT License.
// See the license.txt file in this distribution or https://watercpp.com/license.txt
//\_/\_/\_/\_/\_/\_/\_/\_/\_/\_/\_/\_/\_/\_/\_/\_/\_/\_/\_/\_/\_/\_/\_/\_/\_/\_/\_/\_
#ifndef WATER_LOGS_FLUSH_THREAD_HPP
#define WATER_LOGS_FLUSH_THREAD_HPP
#include <water/logs/bits.hpp>
#if defined(WATER_NO_STD) || defined(WATER_USE_WATER_THREADS)
#include <water/logs/flush_thread_water.hpp>
#else
#include <water/logs/flush_thread_std.hpp>
#endif
namespace water { namespace logs {
/*
Use like this:
water::logs::buffer<...> log;
void main() {
water::logs::flush_thread flush{log};
log("hello world");
}
Or call start and stop manually:
water::logs::buffer<...> log;
void main() {
water::logs::flush_thread flush;
flush.start(log);
log("hello world");
flush.stop();
flush.start(log);
log("hello world");
flush.stop();
}
Never call start() while another thread is calling stop().
*/
#if defined(WATER_NO_STD) || defined(WATER_USE_WATER_THREADS)
using flush_thread = flush_thread_water;
#else
using flush_thread = flush_thread_std;
#endif
}}
#endif
| [
"[email protected]"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.