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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
d2a45c5fdf382808d1617c2f8c8d09cb09a68f8e | e74079830f86a791279b72cca438d529eebd028a | /lua/5.1/clibs/plplot-install/share/plplot5.9.6/examples/c++/x09.cc | 790d8d0d71cba957e1b0357a4c766d86679d78c5 | [
"MIT"
] | permissive | black13/lua-graphing | 5deaf6d311bd1e057a9fa56362bae730315e766e | c0ffdd899113a843105d27b900e2fb53010d8bc6 | refs/heads/master | 2020-04-28T01:45:36.971487 | 2014-10-07T20:36:20 | 2014-10-07T20:36:20 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 15,249 | cc | //---------------------------------------------------------------------------//
// $Id: x09.cc 10785 2010-01-31 20:05:17Z hezekiahcarty $
//---------------------------------------------------------------------------//
//
//---------------------------------------------------------------------------//
// Copyright (C) 2004 Andrew Ross <andrewr@coriolis.greenend.org.uk>
// Copyright (C) 2004 Alan W. Irwin
//
// This file is part of PLplot.
//
// PLplot is free software; you can redistribute it and/or modify
// it under the terms of the GNU Library General Public License as published by
// the Free Software Foundation; version 2 of the License.
//
// PLplot 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 Library General Public License for more details.
//
// You should have received a copy of the GNU Library General Public License
// along with PLplot; if not, write to the Free Software
// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
//---------------------------------------------------------------------------//
//
//---------------------------------------------------------------------------//
// Implementation of PLplot example 09 in C++.
//---------------------------------------------------------------------------//
#include "plc++demos.h"
#ifdef PL_USE_NAMESPACE
using namespace std;
#endif
class x09 {
public:
x09( int, const char** );
void polar();
const void potential();
private:
plstream *pls;
static const int XPTS;
static const int YPTS;
// polar plot data
static const int PERIMETERPTS;
static const int RPTS;
static const int THETAPTS;
// potential plot data
static const int PPERIMETERPTS;
static const int PRPTS;
static const int PTHETAPTS;
static const int PNLEVEL;
static PLFLT clevel[];
// Transformation function
// static const PLFLT tr[];
public:
static const PLFLT XSPA;
static const PLFLT YSPA;
};
const int x09:: XPTS = 35;
const int x09:: YPTS = 46;
const PLFLT x09::XSPA = 2. / ( XPTS - 1 );
const PLFLT x09::YSPA = 2. / ( YPTS - 1 );
// polar plot data
const int x09::PERIMETERPTS = 100;
const int x09::RPTS = 40;
const int x09::THETAPTS = 40;
// potential plot data
const int x09::PPERIMETERPTS = 100;
const int x09::PRPTS = 40;
const int x09::PTHETAPTS = 64;
const int x09::PNLEVEL = 20;
PLFLT x09:: clevel[] = { -1., -.8, -.6, -.4, -.2, 0, .2, .4, .6, .8, 1. };
// Transformation function
//const PLFLT x09::tr[] = {XSPA, 0.0, -1.0, 0.0, YSPA, -1.0};
static const PLFLT tr[] = { x09::XSPA, 0.0, -1.0, 0.0, x09::YSPA, -1.0 };
static void mypltr( PLFLT x, PLFLT y, PLFLT *tx, PLFLT *ty, void *pltr_data )
{
*tx = tr[0] * x + tr[1] * y + tr[2];
*ty = tr[3] * x + tr[4] * y + tr[5];
}
// Does a large series of unlabelled and labelled contour plots.
x09::x09( int argc, const char **argv )
{
int i, j;
PLFLT *xg1 = new PLFLT[XPTS];
PLFLT *yg1 = new PLFLT[YPTS];
PLcGrid cgrid1;
PLcGrid2 cgrid2;
PLFLT **z;
PLFLT **w;
PLFLT xx, yy, argx, argy, distort;
static PLINT mark = 1500;
static PLINT space = 1500;
pls = new plstream();
// Parse and process command line arguments.
pls->parseopts( &argc, argv, PL_PARSE_FULL );
/* Initialize plplot */
pls->init();
pls->Alloc2dGrid( &z, XPTS, YPTS );
pls->Alloc2dGrid( &w, XPTS, YPTS );
/* Set up function arrays */
for ( i = 0; i < XPTS; i++ )
{
xx = (PLFLT) ( i - ( XPTS / 2 ) ) / (PLFLT) ( XPTS / 2 );
for ( j = 0; j < YPTS; j++ )
{
yy = (PLFLT) ( j - ( YPTS / 2 ) ) / (PLFLT) ( YPTS / 2 ) - 1.0;
z[i][j] = xx * xx - yy * yy;
w[i][j] = 2 * xx * yy;
}
}
/* Set up grids */
cgrid1.xg = xg1;
cgrid1.yg = yg1;
cgrid1.nx = XPTS;
cgrid1.ny = YPTS;
pls->Alloc2dGrid( &cgrid2.xg, XPTS, YPTS );
pls->Alloc2dGrid( &cgrid2.yg, XPTS, YPTS );
cgrid2.nx = XPTS;
cgrid2.ny = YPTS;
for ( i = 0; i < XPTS; i++ )
{
for ( j = 0; j < YPTS; j++ )
{
mypltr( (PLFLT) i, (PLFLT) j, &xx, &yy, NULL );
argx = xx * M_PI / 2;
argy = yy * M_PI / 2;
distort = 0.4;
cgrid1.xg[i] = xx + distort * cos( argx );
cgrid1.yg[j] = yy - distort * cos( argy );
cgrid2.xg[i][j] = xx + distort * cos( argx ) * cos( argy );
cgrid2.yg[i][j] = yy - distort * cos( argx ) * cos( argy );
}
}
// Plot using scaled identity transform used to create xg0 and yg0
/* pls->_setcontlabelparam(0.006, 0.3, 0.1, 0);
* pls->env(-1.0, 1.0, -1.0, 1.0, 0, 0);
* pls->col0(2);
* pls->cont( z, XPTS, YPTS, 1, XPTS, 1, YPTS, clevel, 11, mypltr, NULL );
* pls->styl(1, &mark, &space);
* pls->col0(3);
* pls->cont(w, XPTS, YPTS, 1, XPTS, 1, YPTS, clevel, 11, mypltr, NULL );
* pls->styl(0, &mark, &space);
* pls->col0(1);
* pls->lab("X Coordinate", "Y Coordinate", "Streamlines of flow");
*/
pls->setcontlabelformat( 4, 3 );
pls->setcontlabelparam( 0.006, 0.3, 0.1, 1 );
pls->env( -1.0, 1.0, -1.0, 1.0, 0, 0 );
pls->col0( 2 );
pls->cont( z, XPTS, YPTS, 1, XPTS, 1, YPTS, clevel, 11, mypltr, NULL );
pls->styl( 1, &mark, &space );
pls->col0( 3 );
pls->cont( w, XPTS, YPTS, 1, XPTS, 1, YPTS, clevel, 11, mypltr, NULL );
pls->styl( 0, &mark, &space );
pls->col0( 1 );
pls->lab( "X Coordinate", "Y Coordinate", "Streamlines of flow" );
pls->setcontlabelparam( 0.006, 0.3, 0.1, 0 );
// Plot using 1d coordinate transform
pls->env( -1.0, 1.0, -1.0, 1.0, 0, 0 );
pls->col0( 2 );
pls->cont( z, XPTS, YPTS, 1, XPTS, 1, YPTS, clevel, 11,
plstream::tr1, (void *) &cgrid1 );
pls->styl( 1, &mark, &space );
pls->col0( 3 );
pls->cont( w, XPTS, YPTS, 1, XPTS, 1, YPTS, clevel, 11,
plstream::tr1, (void *) &cgrid1 );
pls->styl( 0, NULL, NULL );
pls->col0( 1 );
pls->lab( "X Coordinate", "Y Coordinate", "Streamlines of flow" );
/* pls->_setcontlabelparam(0.006, 0.3, 0.1, 1);
* pls->env(-1.0, 1.0, -1.0, 1.0, 0, 0);
* pls->col0(2);
* pls->cont(z, XPTS, YPTS, 1, XPTS, 1, YPTS, clevel, 11,
* pltr1, (void *) &cgrid1 );
* pls->styl(2, &mark, &space);
* pls->col0(3);
* pls->cont(w, XPTS, YPTS, 1, XPTS, 1, YPTS, clevel, 11,
* pltr1, (void *) &cgrid1 );
* pls->styl(0, &mark, &space);
* pls->col0(1);
* pls->lab("X Coordinate", "Y Coordinate", "Streamlines of flow");
* pls->_setcontlabelparam(0.006, 0.3, 0.1, 0);
*/
// Plot using 2d coordinate transform
pls->env( -1.0, 1.0, -1.0, 1.0, 0, 0 );
pls->col0( 2 );
pls->cont( z, XPTS, YPTS, 1, XPTS, 1, YPTS, clevel, 11,
plstream::tr2, (void *) &cgrid2 );
pls->styl( 1, &mark, &space );
pls->col0( 3 );
pls->cont( w, XPTS, YPTS, 1, XPTS, 1, YPTS, clevel, 11,
plstream::tr2, (void *) &cgrid2 );
pls->styl( 0, &mark, &space );
pls->col0( 1 );
pls->lab( "X Coordinate", "Y Coordinate", "Streamlines of flow" );
/* pls->_setcontlabelparam(0.006, 0.3, 0.1, 1);
* pls->env(-1.0, 1.0, -1.0, 1.0, 0, 0);
* pls->col0(2);
* pls->cont(z, XPTS, YPTS, 1, XPTS, 1, YPTS, clevel, 11,
* pltr2, (void *) &cgrid2 );
* pls->styl(1, &mark, &space);
* pls->col0(3);
* pls->cont(w, XPTS, YPTS, 1, XPTS, 1, YPTS, clevel, 11,
* pltr2, (void *) &cgrid2 );
* pls->styl(1, &mark0, &space0);
* pls->col0(1);
* pls->lab("X Coordinate", "Y Coordinate", "Streamlines of flow");
*/
pls->setcontlabelparam( 0.006, 0.3, 0.1, 0 );
polar();
/*
* pls->setcontlabelparam(0.006, 0.3, 0.1, 1);
* polar();
*/
pls->setcontlabelparam( 0.006, 0.3, 0.1, 0 );
potential();
/*
* pls->setcontlabelparam(0.006, 0.3, 0.1, 1);
* potential();
*/
// pls->end();
pls->Free2dGrid( cgrid2.xg, XPTS, YPTS );
pls->Free2dGrid( cgrid2.yg, XPTS, YPTS );
pls->Free2dGrid( z, XPTS, YPTS );
pls->Free2dGrid( w, XPTS, YPTS );
delete pls;
delete[] yg1;
delete[] xg1;
}
void x09::polar()
// polar contour plot example.
{
int i, j;
PLFLT *px = new PLFLT[PERIMETERPTS];
PLFLT *py = new PLFLT[PERIMETERPTS];
PLcGrid2 cgrid2;
PLFLT **z;
PLFLT t, r, theta;
PLFLT *lev = new PLFLT[10];
pls->Alloc2dGrid( &cgrid2.xg, RPTS, THETAPTS );
pls->Alloc2dGrid( &cgrid2.yg, RPTS, THETAPTS );
pls->Alloc2dGrid( &z, RPTS, THETAPTS );
cgrid2.nx = RPTS;
cgrid2.ny = THETAPTS;
pls->env( -1., 1., -1., 1., 0, -2 );
pls->col0( 1 );
// Perimeter
for ( i = 0; i < PERIMETERPTS; i++ )
{
t = ( 2. * M_PI / ( PERIMETERPTS - 1 ) ) * (PLFLT) i;
px[i] = cos( t );
py[i] = sin( t );
}
pls->line( PERIMETERPTS, px, py );
// Create data to be contoured.
for ( i = 0; i < RPTS; i++ )
{
r = i / (PLFLT) ( RPTS - 1 );
for ( j = 0; j < THETAPTS; j++ )
{
theta = ( 2. * M_PI / (PLFLT) ( THETAPTS - 1 ) ) * (PLFLT) j;
cgrid2.xg[i][j] = r * cos( theta );
cgrid2.yg[i][j] = r * sin( theta );
z[i][j] = r;
}
}
for ( i = 0; i < 10; i++ )
{
lev[i] = 0.05 + 0.10 * (PLFLT) i;
}
pls->col0( 2 );
pls->cont( z, RPTS, THETAPTS, 1, RPTS, 1, THETAPTS, lev, 10,
plstream::tr2, (void *) &cgrid2 );
pls->col0( 1 );
pls->lab( "", "", "Polar Contour Plot" );
pls->Free2dGrid( cgrid2.xg, RPTS, THETAPTS );
pls->Free2dGrid( cgrid2.yg, RPTS, THETAPTS );
pls->Free2dGrid( z, RPTS, THETAPTS );
delete[] px;
delete[] py;
delete[] lev;
}
const void x09::potential()
// Shielded potential contour plot example.
{
int i, j;
PLFLT rmax, xmin, xmax, x0, ymin, ymax, y0, zmin, zmax;
PLFLT peps, xpmin, xpmax, ypmin, ypmax;
PLFLT eps, q1, d1, q1i, d1i, q2, d2, q2i, d2i;
PLFLT div1, div1i, div2, div2i;
PLcGrid2 cgrid2;
PLFLT **z;
int nlevelneg, nlevelpos;
PLFLT dz, clevel;
PLFLT *clevelneg = new PLFLT[PNLEVEL];
PLFLT *clevelpos = new PLFLT[PNLEVEL];
int ncollin, ncolbox, ncollab;
PLFLT *px = new PLFLT[PPERIMETERPTS];
PLFLT *py = new PLFLT[PPERIMETERPTS];
PLFLT t, r, theta;
// Create data to be contoured.
pls->Alloc2dGrid( &cgrid2.xg, PRPTS, PTHETAPTS );
pls->Alloc2dGrid( &cgrid2.yg, PRPTS, PTHETAPTS );
pls->Alloc2dGrid( &z, PRPTS, PTHETAPTS );
cgrid2.nx = PRPTS;
cgrid2.ny = PTHETAPTS;
// r = 0.;
for ( i = 0; i < PRPTS; i++ )
{
r = 0.5 + (PLFLT) i;
for ( j = 0; j < PTHETAPTS; j++ )
{
theta = ( 2. * M_PI / (PLFLT) ( PTHETAPTS - 1 ) ) * ( 0.5 + (PLFLT) j );
cgrid2.xg[i][j] = r * cos( theta );
cgrid2.yg[i][j] = r * sin( theta );
}
}
rmax = r;
pls->MinMax2dGrid( cgrid2.xg, PRPTS, PTHETAPTS, &xmax, &xmin );
pls->MinMax2dGrid( cgrid2.yg, PRPTS, PTHETAPTS, &ymax, &ymin );
x0 = ( xmin + xmax ) / 2.;
y0 = ( ymin + ymax ) / 2.;
// Expanded limits
peps = 0.05;
xpmin = xmin - fabs( xmin ) * peps;
xpmax = xmax + fabs( xmax ) * peps;
ypmin = ymin - fabs( ymin ) * peps;
ypmax = ymax + fabs( ymax ) * peps;
// Potential inside a conducting cylinder (or sphere) by method of images.
// Charge 1 is placed at (d1, d1), with image charge at (d2, d2).
// Charge 2 is placed at (d1, -d1), with image charge at (d2, -d2).
// Also put in smoothing term at small distances.
eps = 2.;
q1 = 1.;
d1 = rmax / 4.;
q1i = -q1 * rmax / d1;
d1i = pow( rmax, 2 ) / d1;
q2 = -1.;
d2 = rmax / 4.;
q2i = -q2 * rmax / d2;
d2i = pow( rmax, 2 ) / d2;
for ( i = 0; i < PRPTS; i++ )
{
for ( j = 0; j < PTHETAPTS; j++ )
{
div1 = sqrt( pow( cgrid2.xg[i][j] - d1, 2 ) + pow( cgrid2.yg[i][j] - d1, 2 ) + pow( eps, 2 ) );
div1i = sqrt( pow( cgrid2.xg[i][j] - d1i, 2 ) + pow( cgrid2.yg[i][j] - d1i, 2 ) + pow( eps, 2 ) );
div2 = sqrt( pow( cgrid2.xg[i][j] - d2, 2 ) + pow( cgrid2.yg[i][j] + d2, 2 ) + pow( eps, 2 ) );
div2i = sqrt( pow( cgrid2.xg[i][j] - d2i, 2 ) + pow( cgrid2.yg[i][j] + d2i, 2 ) + pow( eps, 2 ) );
z[i][j] = q1 / div1 + q1i / div1i + q2 / div2 + q2i / div2i;
}
}
pls->MinMax2dGrid( z, PRPTS, PTHETAPTS, &zmax, &zmin );
/* printf("%.15g %.15g %.15g %.15g %.15g %.15g %.15g %.15g \n",
* q1, d1, q1i, d1i, q2, d2, q2i, d2i);
* printf("%.15g %.15g %.15g %.15g %.15g %.15g\n",
* xmin,xmax,ymin,ymax,zmin,zmax);*/
// Positive and negative contour levels.
dz = ( zmax - zmin ) / (PLFLT) PNLEVEL;
nlevelneg = 0;
nlevelpos = 0;
for ( i = 0; i < PNLEVEL; i++ )
{
clevel = zmin + ( (PLFLT) i + 0.5 ) * dz;
if ( clevel <= 0. )
clevelneg[nlevelneg++] = clevel;
else
clevelpos[nlevelpos++] = clevel;
}
// Colours!
ncollin = 11;
ncolbox = 1;
ncollab = 2;
// Finally start plotting this page!
pls->adv( 0 );
pls->col0( ncolbox );
pls->vpas( 0.1, 0.9, 0.1, 0.9, 1.0 );
pls->wind( xpmin, xpmax, ypmin, ypmax );
pls->box( "", 0., 0, "", 0., 0 );
pls->col0( ncollin );
if ( nlevelneg > 0 )
{
// Negative contours
pls->lsty( 2 );
pls->cont( z, PRPTS, PTHETAPTS, 1, PRPTS, 1, PTHETAPTS,
clevelneg, nlevelneg, plstream::tr2, (void *) &cgrid2 );
}
if ( nlevelpos > 0 )
{
// Positive contours
pls->lsty( 1 );
pls->cont( z, PRPTS, PTHETAPTS, 1, PRPTS, 1, PTHETAPTS,
clevelpos, nlevelpos, plstream::tr2, (void *) &cgrid2 );
}
// Draw outer boundary
for ( i = 0; i < PPERIMETERPTS; i++ )
{
t = ( 2. * M_PI / ( PPERIMETERPTS - 1 ) ) * (PLFLT) i;
px[i] = x0 + rmax*cos( t );
py[i] = y0 + rmax*sin( t );
}
pls->col0( ncolbox );
pls->line( PPERIMETERPTS, px, py );
pls->col0( ncollab );
pls->lab( "", "", "Shielded potential of charges in a conducting sphere" );
pls->Free2dGrid( cgrid2.xg, RPTS, THETAPTS );
pls->Free2dGrid( cgrid2.yg, RPTS, THETAPTS );
pls->Free2dGrid( z, RPTS, THETAPTS );
delete[] clevelneg;
delete[] clevelpos;
delete[] px;
delete[] py;
}
int main( int argc, const char **argv )
{
x09 *x = new x09( argc, argv );
delete x;
}
//---------------------------------------------------------------------------//
// End of x09.cc
//---------------------------------------------------------------------------//
| [
"jjosburn@gmail.com"
] | jjosburn@gmail.com |
50e32925b020066233d23e0fc3245950bf4d1c27 | 2ee540793f0a390d3f418986aa7e124083760535 | /Online Judges/Kattis/RandomProblems/htoo.cpp | de4e878320e91fa3a6cf7484f09491ccc5134a19 | [] | no_license | dickynovanto1103/CP | 6323d27c3aed4ffa638939f26f257530993401b7 | f1e5606904f22bb556b1d4dda4e574b409abc17c | refs/heads/master | 2023-08-18T10:06:45.241453 | 2023-08-06T23:58:54 | 2023-08-06T23:58:54 | 97,298,343 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,340 | cpp | #include <bits/stdc++.h>
using namespace std;
#define inf 1000000000
#define unvisited -1
#define visited 1
#define eps 1e-9
#define mp make_pair
#define pb push_back
#define pi acos(-1.0)
#define uint64 unsigned long long
#define FastSlowInput ios_base::sync_with_stdio(false); cin.tie(NULL);
typedef long long ll;
typedef vector<int> vi;
typedef pair<int,int> ii;
typedef vector<ii> vii;
ll cnt[2][27];
void parse(const string& kata, int id) {
int i,j;
int pjg = kata.length();
char curKar = 'd';
int num = 0;
for(i=0;i<pjg;i++){
char kar = kata[i];
if(kar >= 'A' && kar <= 'Z'){
if(curKar == 'd')
num = 0;
else{
num = max(num, 1);
cnt[id][curKar-'A'] += num;
}
num = 0;
curKar = kar;
}else{
num *= 10;
num += (kar - '0');
}
}
num = max(num, 1);
// printf("num: %d\n",num);
cnt[id][curKar-'A'] += num;
// printf("cnt[%d][%c]: %lld\n",id,curKar, cnt[id][curKar-'A']);
}
int main(){
string kata, tujuan;
int banyak,i,j;
cin>>kata>>banyak>>tujuan;
parse(kata, 0); parse(tujuan, 1);
for(i=0;i<26;i++){
cnt[0][i] *= (ll)banyak;
}
ll ans = inf;
for(i=0;i<26;i++){
if(cnt[1][i] > cnt[0][i]){ans = 0; break;}
else{
if(cnt[1][i] == 0){continue;}
ans = min(ans, (ll)cnt[0][i] / cnt[1][i]);
// printf("ans jd: %lld\n",ans);
}
}
printf("%lld\n",ans);
return 0;
}; | [
"dickynovanto1103@gmail.com"
] | dickynovanto1103@gmail.com |
fdd41ac2ba233e40809133e973173995ff0d6036 | b2139a7f5e04114c39faea797f0f619e69b8b4ae | /src/poeticon/poeticonpp/blobDescriptorModule/include/iCub/BlobDescriptorSupport.h | f57160019faf4aeaf6bdce6e16306f0d0670a146 | [] | no_license | hychyc07/contrib_bk | 6b82391a965587603813f1553084a777fb54d9d7 | 6f3df0079b7ea52d5093042112f55a921c9ed14e | refs/heads/master | 2020-05-29T14:01:20.368837 | 2015-04-02T21:00:31 | 2015-04-02T21:00:31 | 33,312,790 | 5 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 3,223 | h | #ifndef __ICUB_BLOB_DESC_SUPPORT_H__
#define __ICUB_BLOB_DESC_SUPPORT_H__
/* helper classes and functions - most are taken from Ivana Cingovska's 2008 work */
/* OpenCV */
#include <opencv/cv.h>
#include <opencv/cxcore.h>
#include <opencv/highgui.h>
/* iCub */
#include <iCub/BlobDescriptorModule.h>
/* system */
//#include <fstream>
//#include <iostream>
//#include <sstream>
#include <math.h>
#include <string>
#include <stdio.h>
//#include <vector>
using namespace std;
/* objectDescriptor.h */
//Should create a class with proper constructors and destructors
class ObjectDescriptor
{
public: //everything public for a start
ObjectDescriptor();
bool Create(int width, int height);
~ObjectDescriptor();
int no; // number of objects in the image ??? It looks like it is more the index of the object in the array
int label;
int area;
CvPoint center;
bool valid;
//Color Histogram
CvHistogram *objHist; // colour descriptor? CHECK
//New fields added for color histogram computations - Alex 19/12/2009
int _w;
int _h;
CvSize _sz;
int _hist_size[2];
float _h_ranges[2], _s_ranges[2], _v_ranges[2];
int h_bins;
int s_bins;
int v_bins;
IplImage* mask_image; // object mask
unsigned char *mask_data;
CvScalar color; // for display? CHECK
//New fields added for tracker initialization - Alex 20/12/2009
int roi_x;
int roi_y;
int roi_width;
int roi_height;
int v_min;
int v_max;
int s_min;
int s_max;
//New fields added for contour processing - Alex 13/12/2009
CvMemStorage *storage; // = cvCreateMemStorage(0);
CvSeq *contours; // raw blob contours
CvSeq *affcontours; // processed contours for the description of affordances
CvSeq *convexhull; //
/* variables to define the shape */
double contour_area;
double contour_perimeter;
double convex_perimeter;
double major_axis;
double minor_axis;
double rect_area;
CvBox2D enclosing_rect;
CvRect bounding_rect;
/* shape descriptors for the affordances */
double convexity;
double eccentricity;
double compactness;
double circleness;
double squareness;
};
/* calcdistances.h */
class Distance
{
private:
float bhattacharyya(CvHistogram *hist1, CvHistogram *hist2, int h_bins, int s_bins);
double euclidian(CvPoint c1, CvPoint c2);
double weightB, weightE, weightA; // weight coefficients of the different distances that contribute to the overall distance
public:
Distance(double wB = 1, double wE = 1, double wA = 1);
double overallDistance(ObjectDescriptor *d1, ObjectDescriptor *d2);
};
/* selectObjects.h */
int selectObjects(IplImage *labeledImage, IplImage *out, int numLabels, int areaThres);
void whiteBalance(IplImage *maskImage, IplImage *originalImage, IplImage *whiteBalancedImg);
int indexOfL(int label, ObjectDescriptor *odTable, int length);
void extractObj(IplImage *labeledImage, int numObjects, ObjectDescriptor *objDescTable);
void int32ToInt8Image(IplImage *labeledIntImage, IplImage *labeledImage);
bool existsInList(int x, int a[], int numEl);
void printImgLabels(IplImage *img, int numObjects);
#endif // __ICUB_BLOB_DESC_SUPPORT_H__
| [
"hychyc07@cs.utexas.edu"
] | hychyc07@cs.utexas.edu |
dd76f270105958b1e5e6fc1d047bca955b6c4c4c | a16b0c6431cf763830a86b77abced4ccc9325804 | /tensorflow/lite/delegates/gpu/metal/metal_arguments.cc | 571cc0024f58843f43fdd93ca1dd073462d20c34 | [
"Apache-2.0"
] | permissive | foss-for-synopsys-dwc-arc-processors/tensorflow | 9812f077051973dafc66868e5ffaff05b42aa9f4 | 30d46c800e467e05e58415cf789c61d4582d2c0c | refs/heads/master | 2021-08-06T20:32:46.890206 | 2021-02-17T19:00:09 | 2021-02-17T19:00:09 | 206,022,279 | 2 | 1 | Apache-2.0 | 2020-06-09T12:18:11 | 2019-09-03T08:01:41 | C++ | UTF-8 | C++ | false | false | 28,601 | cc | /* Copyright 2020 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/lite/delegates/gpu/metal/metal_arguments.h"
#include <string>
#include "absl/strings/substitute.h"
#include "tensorflow/lite/delegates/gpu/common/task/util.h"
#include "tensorflow/lite/delegates/gpu/common/util.h"
#include "tensorflow/lite/delegates/gpu/metal/buffer.h"
#include "tensorflow/lite/delegates/gpu/metal/linear_storage.h"
#include "tensorflow/lite/delegates/gpu/metal/metal_spatial_tensor.h"
#include "tensorflow/lite/delegates/gpu/metal/texture2d.h"
namespace tflite {
namespace gpu {
namespace metal {
namespace {
bool IsWordSymbol(char symbol) {
return absl::ascii_isalnum(symbol) || symbol == '_';
}
void ReplaceAllWords(const std::string& old_word, const std::string& new_word,
std::string* str) {
size_t position = str->find(old_word);
while (position != std::string::npos) {
char prev = position == 0 ? '.' : (*str)[position - 1];
char next = position + old_word.size() < str->size()
? (*str)[position + old_word.size()]
: '.';
if (IsWordSymbol(prev) || IsWordSymbol(next)) {
position = str->find(old_word, position + 1);
continue;
}
str->replace(position, old_word.size(), new_word);
position = str->find(old_word, position + new_word.size());
}
}
std::string GetNextWord(const std::string& code, size_t first_position) {
size_t pos = first_position;
char t = code[pos];
while (IsWordSymbol(t)) {
pos++;
t = code[pos];
}
return code.substr(first_position, pos - first_position);
}
size_t FindEnclosingBracket(const std::string& text, size_t first_pos,
char bracket) {
const std::map<char, char> brackets = {
{'(', ')'},
{'{', '}'},
{'[', ']'},
{'<', '>'},
};
char b_open = bracket;
auto it = brackets.find(b_open);
if (it == brackets.end()) {
return -1;
}
char b_close = it->second;
size_t pos = first_pos;
int opened = 1;
int closed = 0;
while (opened != closed && pos < text.size()) {
if (text[pos] == b_open) {
opened++;
} else if (text[pos] == b_close) {
closed++;
}
pos++;
}
if (opened == closed) {
return pos;
} else {
return -1;
}
}
absl::Status ParseArgsInsideBrackets(const std::string& text,
size_t open_bracket_pos,
size_t* close_bracket_pos,
std::vector<std::string>* args) {
*close_bracket_pos =
FindEnclosingBracket(text, open_bracket_pos + 1, text[open_bracket_pos]);
if (*close_bracket_pos == -1) {
return absl::NotFoundError("Not found enclosing bracket");
}
std::string str_args = text.substr(open_bracket_pos + 1,
*close_bracket_pos - open_bracket_pos - 2);
std::vector<absl::string_view> words = absl::StrSplit(str_args, ',');
args->reserve(words.size());
for (const auto& word : words) {
absl::string_view arg = absl::StripAsciiWhitespace(word);
if (!arg.empty()) {
args->push_back(std::string(arg));
}
}
return absl::OkStatus();
}
void AppendArgument(const std::string& arg, std::string* args) {
if (!args->empty()) {
absl::StrAppend(args, ",\n");
}
absl::StrAppend(args, arg);
}
absl::Status CreateMetalObject(id<MTLDevice> device, GPUObjectDescriptor* desc,
GPUObjectPtr* result) {
const auto* buffer_desc = dynamic_cast<const BufferDescriptor*>(desc);
if (buffer_desc) {
Buffer gpu_buffer;
RETURN_IF_ERROR(
gpu_buffer.CreateFromBufferDescriptor(*buffer_desc, device));
*result = absl::make_unique<Buffer>(std::move(gpu_buffer));
return absl::OkStatus();
}
const auto* texture_desc = dynamic_cast<const Texture2DDescriptor*>(desc);
if (texture_desc) {
Texture2D gpu_texture;
RETURN_IF_ERROR(
gpu_texture.CreateFromTexture2DDescriptor(*texture_desc, device));
*result = absl::make_unique<Texture2D>(std::move(gpu_texture));
return absl::OkStatus();
}
const auto* linear_desc = dynamic_cast<const TensorLinearDescriptor*>(desc);
if (linear_desc) {
LinearStorage gpu_storage;
RETURN_IF_ERROR(
gpu_storage.CreateFromTensorLinearDescriptor(*linear_desc, device));
*result = absl::make_unique<LinearStorage>(std::move(gpu_storage));
return absl::OkStatus();
}
const auto* tensor_desc = dynamic_cast<const TensorDescriptor*>(desc);
if (tensor_desc) {
MetalSpatialTensor gpu_tensor;
RETURN_IF_ERROR(gpu_tensor.CreateFromDescriptor(*tensor_desc, device));
*result = absl::make_unique<MetalSpatialTensor>(std::move(gpu_tensor));
return absl::OkStatus();
}
return absl::InvalidArgumentError("Unknown GPU descriptor.");
}
std::string AccessToMetalTextureAccess(AccessType access_type) {
if (access_type == AccessType::READ) {
return "access::read";
} else if (access_type == AccessType::READ_WRITE) {
return "access::read_write";
} else if (access_type == AccessType::WRITE) {
return "access::write";
} else {
return "access::unknown";
}
}
} // namespace
// Static
constexpr char MetalArguments::kArgsPrefix[];
absl::Status MetalArguments::Init(
const std::map<std::string, std::string>& linkables, MetalDevice* device,
Arguments* args, std::string* code) {
RETURN_IF_ERROR(AllocateObjects(*args, device->device()));
RETURN_IF_ERROR(AddObjectArgs(args));
RETURN_IF_ERROR(
ResolveSelectorsPass(device->GetInfo(), *args, linkables, code));
object_refs_ = std::move(args->object_refs_);
args->GetActiveArguments(kArgsPrefix, *code);
std::string struct_desc = ScalarArgumentsToStructWithVec4Fields(args, code);
RETURN_IF_ERROR(SetObjectsResources(*args));
ResolveArgsPass(code);
std::string header = R"(
#include <metal_stdlib>
using namespace metal;
)";
header += struct_desc + "\n";
*code = header + *code;
std::string arguments = GetListOfArgs(/*buffer_offset*/ 0);
const bool use_global_id = code->find("GLOBAL_ID_") != std::string::npos;
const bool use_local_id = code->find("LOCAL_ID_") != std::string::npos;
const bool use_group_id = code->find("GROUP_ID_") != std::string::npos;
const bool use_group_size = code->find("GROUP_SIZE_") != std::string::npos;
const bool use_simd_id =
code->find("SUB_GROUP_LOCAL_ID") != std::string::npos;
if (use_global_id) {
AppendArgument("uint3 reserved_gid[[thread_position_in_grid]]", &arguments);
}
if (use_local_id) {
AppendArgument("uint3 reserved_lid[[thread_position_in_threadgroup]]",
&arguments);
}
if (use_group_id) {
AppendArgument("uint3 reserved_group_id[[threadgroup_position_in_grid]]",
&arguments);
}
if (use_group_size) {
AppendArgument("uint3 reserved_group_size[[threads_per_threadgroup]]",
&arguments);
}
if (use_simd_id) {
AppendArgument("uint reserved_simd_id[[thread_index_in_simdgroup]]",
&arguments);
}
if (!use_global_id && !use_local_id && !use_group_id && !use_group_size &&
!arguments.empty()) {
arguments += ",\n";
}
*code = absl::Substitute(*code, arguments);
return absl::OkStatus();
}
std::string MetalArguments::ScalarArgumentsToStructWithScalarFields(
Arguments* args, std::string* code) {
std::string struct_desc = "struct uniforms_buffer {\n";
int pos = 0;
for (auto& fvalue : args->float_values_) {
auto& new_val = float_values_[fvalue.first];
new_val.value = fvalue.second.value;
new_val.active = fvalue.second.active;
if (fvalue.second.active) {
new_val.bytes_offset = pos * 4;
pos++;
struct_desc += " float " + fvalue.first + ";\n";
ReplaceAllWords(kArgsPrefix + fvalue.first, "U." + fvalue.first, code);
}
}
for (const auto& hfvalue : args->half_values_) {
auto& new_val = float_values_[hfvalue.first];
new_val.value = hfvalue.second.value;
new_val.active = hfvalue.second.active;
if (hfvalue.second.active) {
new_val.bytes_offset = pos * 4;
pos++;
struct_desc += " float " + hfvalue.first + ";\n";
ReplaceAllWords(kArgsPrefix + hfvalue.first,
"static_cast<half>(U." + hfvalue.first + ")", code);
}
}
for (auto& ivalue : args->int_values_) {
auto& new_val = int_values_[ivalue.first];
new_val.value = ivalue.second.value;
new_val.active = ivalue.second.active;
if (ivalue.second.active) {
new_val.bytes_offset = pos * 4;
pos++;
struct_desc += " int " + ivalue.first + ";\n";
ReplaceAllWords(kArgsPrefix + ivalue.first, "U." + ivalue.first, code);
}
}
if (pos != 0) {
int aligned_pos = AlignByN(pos, 4);
for (int i = pos; i < aligned_pos; i++) {
struct_desc += " int dummy" + std::to_string(i - pos) + ";\n";
}
struct_desc += "};";
const_data_.resize(aligned_pos * 4);
for (auto& it : float_values_) {
if (it.second.active) {
float* ptr =
reinterpret_cast<float*>(&const_data_[it.second.bytes_offset]);
*ptr = it.second.value;
}
}
for (auto& it : int_values_) {
if (it.second.active) {
int32_t* ptr =
reinterpret_cast<int32_t*>(&const_data_[it.second.bytes_offset]);
*ptr = it.second.value;
}
}
} else {
struct_desc = "";
}
return struct_desc;
}
std::string MetalArguments::ScalarArgumentsToStructWithVec4Fields(
Arguments* args, std::string* code) {
std::string struct_desc = "struct uniforms_buffer {\n";
int pos = 0;
std::string channels[4] = {".x", ".y", ".z", ".w"};
for (auto& fvalue : args->float_values_) {
auto& new_val = float_values_[fvalue.first];
new_val.value = fvalue.second.value;
new_val.active = fvalue.second.active;
if (fvalue.second.active) {
new_val.bytes_offset = pos * 4;
if (pos % 4 == 0) {
struct_desc += " float4 cmp_float4_" + std::to_string(pos / 4) + ";\n";
}
std::string new_name =
"U.cmp_float4_" + std::to_string(pos / 4) + channels[pos % 4];
ReplaceAllWords(kArgsPrefix + fvalue.first, new_name, code);
pos++;
}
}
for (const auto& hfvalue : args->half_values_) {
auto& new_val = float_values_[hfvalue.first];
new_val.value = hfvalue.second.value;
new_val.active = hfvalue.second.active;
if (hfvalue.second.active) {
new_val.bytes_offset = pos * 4;
if (pos % 4 == 0) {
struct_desc += " float4 cmp_float4_" + std::to_string(pos / 4) + ";\n";
}
std::string new_name = "static_cast<half>(U.cmp_float4_" +
std::to_string(pos / 4) + channels[pos % 4] + ")";
ReplaceAllWords(kArgsPrefix + hfvalue.first, new_name, code);
pos++;
}
}
pos = AlignByN(pos, 4);
for (auto& ivalue : args->int_values_) {
auto& new_val = int_values_[ivalue.first];
new_val.value = ivalue.second.value;
new_val.active = ivalue.second.active;
if (ivalue.second.active) {
new_val.bytes_offset = pos * 4;
if (pos % 4 == 0) {
struct_desc += " int4 cmp_int4_" + std::to_string(pos / 4) + ";\n";
}
std::string new_name =
"U.cmp_int4_" + std::to_string(pos / 4) + channels[pos % 4];
ReplaceAllWords(kArgsPrefix + ivalue.first, new_name, code);
pos++;
}
}
if (pos != 0) {
int aligned_pos = AlignByN(pos, 4);
struct_desc += "};";
const_data_.resize(aligned_pos * 4);
for (auto& it : float_values_) {
if (it.second.active) {
float* ptr =
reinterpret_cast<float*>(&const_data_[it.second.bytes_offset]);
*ptr = it.second.value;
}
}
for (auto& it : int_values_) {
if (it.second.active) {
int32_t* ptr =
reinterpret_cast<int32_t*>(&const_data_[it.second.bytes_offset]);
*ptr = it.second.value;
}
}
} else {
struct_desc = "";
}
return struct_desc;
}
absl::Status MetalArguments::SetInt(const std::string& name, int value) {
auto it = int_values_.find(name);
if (it == int_values_.end()) {
return absl::NotFoundError(
absl::StrCat("No int argument with name - ", name));
}
it->second.value = value;
if (it->second.active) {
int32_t* ptr =
reinterpret_cast<int32_t*>(&const_data_[it->second.bytes_offset]);
*ptr = value;
}
return absl::OkStatus();
}
absl::Status MetalArguments::SetFloat(const std::string& name, float value) {
auto it = float_values_.find(name);
if (it == float_values_.end()) {
return absl::NotFoundError(
absl::StrCat("No float argument with name - ", name));
}
it->second.value = value;
if (it->second.active) {
float* ptr =
reinterpret_cast<float*>(&const_data_[it->second.bytes_offset]);
*ptr = value;
}
return absl::OkStatus();
}
absl::Status MetalArguments::SetHalf(const std::string& name, half value) {
auto it = float_values_.find(name);
if (it == float_values_.end()) {
return absl::NotFoundError(
absl::StrCat("No half argument with name - ", name));
}
it->second.value = value;
if (it->second.active) {
float* ptr =
reinterpret_cast<float*>(&const_data_[it->second.bytes_offset]);
*ptr = value;
}
return absl::OkStatus();
}
absl::Status MetalArguments::SetObjectRef(const std::string& name,
const GPUObject& object) {
auto it = object_refs_.find(name);
if (it == object_refs_.end()) {
return absl::NotFoundError(
absl::StrCat("No object ref with name - ", name));
}
GPUResourcesWithValue resources;
RETURN_IF_ERROR(object.GetGPUResources(it->second.get(), &resources));
return SetGPUResources(name, resources);
}
void MetalArguments::Encode(id<MTLComputeCommandEncoder> encoder,
int buffer_offset, int texture_offset) const {
for (auto& b : buffers_) {
[encoder setBuffer:b.second.handle offset:0 atIndex:buffer_offset];
buffer_offset++;
}
for (auto& image : images2d_) {
[encoder setTexture:image.second.handle atIndex:texture_offset];
texture_offset++;
}
for (auto& image : image2d_arrays_) {
[encoder setTexture:image.second.handle atIndex:texture_offset];
texture_offset++;
}
for (auto& image : images3d_) {
[encoder setTexture:image.second.handle atIndex:texture_offset];
texture_offset++;
}
for (auto& image : image_buffers_) {
[encoder setTexture:image.second.handle atIndex:texture_offset];
texture_offset++;
}
if (!const_data_.empty()) {
[encoder setBytes:const_data_.data()
length:const_data_.size()
atIndex:buffer_offset];
}
}
absl::Status MetalArguments::AllocateObjects(const Arguments& args,
id<MTLDevice> device) {
objects_.resize(args.objects_.size());
int i = 0;
for (auto& t : args.objects_) {
RETURN_IF_ERROR(CreateMetalObject(device, t.second.get(), &objects_[i]));
i++;
}
return absl::OkStatus();
}
absl::Status MetalArguments::AddObjectArgs(Arguments* args) {
for (auto& t : args->objects_) {
AddGPUResources(t.first, t.second->GetGPUResources(), args);
}
for (auto& t : args->object_refs_) {
AddGPUResources(t.first, t.second->GetGPUResources(), args);
}
return absl::OkStatus();
}
std::string MetalArguments::GetListOfArgs(int buffer_offset,
int textures_offset) {
std::string result;
for (auto& t : buffers_) {
AppendArgument(
absl::StrCat(MemoryTypeToMetalType(t.second.desc.memory_type), " ",
ToMetalDataType(t.second.desc.data_type,
t.second.desc.element_size),
"* ", t.first, "[[buffer(", buffer_offset, ")]]"),
&result);
buffer_offset++;
}
for (auto& t : images2d_) {
std::string access = AccessToMetalTextureAccess(t.second.desc.access_type);
std::string data_type = ToMetalDataType(t.second.desc.data_type);
AppendArgument(absl::StrCat("texture2d<", data_type, ", ", access, "> ",
t.first, "[[texture(", textures_offset, ")]]"),
&result);
textures_offset++;
}
for (auto& t : image2d_arrays_) {
std::string access = AccessToMetalTextureAccess(t.second.desc.access_type);
std::string data_type = ToMetalDataType(t.second.desc.data_type);
AppendArgument(
absl::StrCat("texture2d_array<", data_type, ", ", access, "> ", t.first,
"[[texture(", textures_offset, ")]]"),
&result);
textures_offset++;
}
for (auto& t : images3d_) {
std::string access = AccessToMetalTextureAccess(t.second.desc.access_type);
std::string data_type = ToMetalDataType(t.second.desc.data_type);
AppendArgument(absl::StrCat("texture3d<", data_type, ", ", access, "> ",
t.first, "[[texture(", textures_offset, ")]]"),
&result);
textures_offset++;
}
for (auto& t : image_buffers_) {
std::string access = AccessToMetalTextureAccess(t.second.desc.access_type);
std::string data_type = ToMetalDataType(t.second.desc.data_type);
AppendArgument(
absl::StrCat("texture_buffer<", data_type, ", ", access, "> ", t.first,
"[[texture(", textures_offset, ")]]"),
&result);
textures_offset++;
}
if (!const_data_.empty()) {
AppendArgument(absl::StrCat("constant uniforms_buffer& U[[buffer(",
buffer_offset, ")]]"),
&result);
buffer_offset++;
}
return result;
}
absl::Status MetalArguments::SetGPUResources(
const std::string& name, const GPUResourcesWithValue& resources) {
for (const auto& r : resources.ints) {
RETURN_IF_ERROR(SetInt(absl::StrCat(name, "_", r.first), r.second));
}
for (const auto& r : resources.floats) {
RETURN_IF_ERROR(SetFloat(absl::StrCat(name, "_", r.first), r.second));
}
for (const auto& r : resources.buffers) {
RETURN_IF_ERROR(SetBuffer(absl::StrCat(name, "_", r.first), r.second));
}
for (const auto& r : resources.images2d) {
RETURN_IF_ERROR(SetImage2D(absl::StrCat(name, "_", r.first), r.second));
}
for (const auto& r : resources.image2d_arrays) {
RETURN_IF_ERROR(
SetImage2DArray(absl::StrCat(name, "_", r.first), r.second));
}
for (const auto& r : resources.images3d) {
RETURN_IF_ERROR(SetImage3D(absl::StrCat(name, "_", r.first), r.second));
}
for (const auto& r : resources.image_buffers) {
RETURN_IF_ERROR(SetImageBuffer(absl::StrCat(name, "_", r.first), r.second));
}
return absl::OkStatus();
}
void MetalArguments::AddBuffer(const std::string& name,
const GPUBufferDescriptor& desc) {
buffers_[name].desc = desc;
}
void MetalArguments::AddImage2D(const std::string& name,
const GPUImage2DDescriptor& desc) {
images2d_[name].desc = desc;
}
void MetalArguments::AddImage2DArray(const std::string& name,
const GPUImage2DArrayDescriptor& desc) {
image2d_arrays_[name].desc = desc;
}
void MetalArguments::AddImage3D(const std::string& name,
const GPUImage3DDescriptor& desc) {
images3d_[name].desc = desc;
}
void MetalArguments::AddImageBuffer(const std::string& name,
const GPUImageBufferDescriptor& desc) {
image_buffers_[name].desc = desc;
}
void MetalArguments::AddGPUResources(const std::string& name,
const GPUResources& resources,
Arguments* args) {
for (const auto& r : resources.ints) {
args->AddInt(absl::StrCat(name, "_", r));
}
for (const auto& r : resources.floats) {
args->AddFloat(absl::StrCat(name, "_", r));
}
for (const auto& r : resources.buffers) {
AddBuffer(absl::StrCat(name, "_", r.first), r.second);
}
for (const auto& r : resources.images2d) {
AddImage2D(absl::StrCat(name, "_", r.first), r.second);
}
for (const auto& r : resources.image2d_arrays) {
AddImage2DArray(absl::StrCat(name, "_", r.first), r.second);
}
for (const auto& r : resources.images3d) {
AddImage3D(absl::StrCat(name, "_", r.first), r.second);
}
for (const auto& r : resources.image_buffers) {
AddImageBuffer(absl::StrCat(name, "_", r.first), r.second);
}
}
absl::Status MetalArguments::SetBuffer(const std::string& name,
id<MTLBuffer> handle) {
auto it = buffers_.find(name);
if (it == buffers_.end()) {
return absl::NotFoundError(
absl::StrCat("No buffer argument with name - ", name));
}
it->second.handle = handle;
return absl::OkStatus();
}
absl::Status MetalArguments::SetImage2D(const std::string& name,
id<MTLTexture> handle) {
auto it = images2d_.find(name);
if (it == images2d_.end()) {
return absl::NotFoundError(
absl::StrCat("No image2d argument with name - ", name));
}
it->second.handle = handle;
return absl::OkStatus();
}
absl::Status MetalArguments::SetImage2DArray(const std::string& name,
id<MTLTexture> handle) {
auto it = image2d_arrays_.find(name);
if (it == image2d_arrays_.end()) {
return absl::NotFoundError(
absl::StrCat("No image2d array argument with name - ", name));
}
it->second.handle = handle;
return absl::OkStatus();
}
absl::Status MetalArguments::SetImage3D(const std::string& name,
id<MTLTexture> handle) {
auto it = images3d_.find(name);
if (it == images3d_.end()) {
return absl::NotFoundError(
absl::StrCat("No image3d argument with name - ", name));
}
it->second.handle = handle;
return absl::OkStatus();
}
absl::Status MetalArguments::SetImageBuffer(const std::string& name,
id<MTLTexture> handle) {
auto it = image_buffers_.find(name);
if (it == image_buffers_.end()) {
return absl::NotFoundError(
absl::StrCat("No image buffer argument with name - ", name));
}
it->second.handle = handle;
return absl::OkStatus();
}
absl::Status MetalArguments::ResolveSelectorsPass(
const GpuInfo& gpu_info, const Arguments& args,
const std::map<std::string, std::string>& linkables, std::string* code) {
std::string result;
size_t position = 0;
size_t next_position = code->find(kArgsPrefix);
while (next_position != std::string::npos) {
size_t arg_pos = next_position;
next_position += strlen(kArgsPrefix);
std::string object_name = GetNextWord(*code, next_position);
char next = (*code)[next_position + object_name.size()];
if (next == '.') {
next_position += object_name.size() + 1;
std::string selector_name = GetNextWord(*code, next_position);
next_position += selector_name.size();
next = (*code)[next_position];
std::vector<std::string> template_args;
if (next == '<') {
size_t close_bracket_pos;
RETURN_IF_ERROR(ParseArgsInsideBrackets(
*code, next_position, &close_bracket_pos, &template_args));
next_position = close_bracket_pos;
next = (*code)[next_position];
}
if (next != '(') {
return absl::NotFoundError(absl::StrCat(
"Expected ( after ", object_name, ".", selector_name, " call"));
}
std::vector<std::string> function_args;
size_t close_bracket_pos;
RETURN_IF_ERROR(ParseArgsInsideBrackets(
*code, next_position, &close_bracket_pos, &function_args));
for (auto& arg : function_args) {
RETURN_IF_ERROR(ResolveSelectorsPass(gpu_info, args, {}, &arg));
}
std::string patch;
RETURN_IF_ERROR(ResolveSelector(gpu_info, args, linkables, object_name,
selector_name, function_args,
template_args, &patch));
code->replace(arg_pos, close_bracket_pos - arg_pos, patch);
position = arg_pos + patch.size();
} else {
position = arg_pos + strlen(kArgsPrefix);
}
next_position = code->find(kArgsPrefix, position);
}
return absl::OkStatus();
}
absl::Status MetalArguments::ResolveSelector(
const GpuInfo& gpu_info, const Arguments& args,
const std::map<std::string, std::string>& linkables,
const std::string& object_name, const std::string& selector,
const std::vector<std::string>& function_args,
const std::vector<std::string>& template_args, std::string* result) {
const GPUObjectDescriptor* desc_ptr;
auto it_ref = args.object_refs_.find(object_name);
auto it_obj = args.objects_.find(object_name);
if (it_ref != args.object_refs_.end()) {
desc_ptr = it_ref->second.get();
} else if (it_obj != args.objects_.end()) {
desc_ptr = it_obj->second.get();
} else {
return absl::NotFoundError(
absl::StrCat("No object with name - ", object_name));
}
auto names = desc_ptr->GetGPUResources().GetNames();
const auto* tensor_desc = dynamic_cast<const TensorDescriptor*>(desc_ptr);
if (tensor_desc && (selector == "Write" || selector == "Linking")) {
auto it = linkables.find(object_name);
if (it != linkables.end()) {
if (desc_ptr->GetAccess() != AccessType::WRITE &&
desc_ptr->GetAccess() != AccessType::READ_WRITE) {
return absl::FailedPreconditionError(absl::StrCat(
"Object with name - ", object_name, " should have Write access."));
}
std::string value_name, x_coord, y_coord, s_coord;
RETURN_IF_ERROR(tensor_desc->GetLinkingContextFromWriteSelector(
function_args, &value_name, &x_coord, &y_coord, &s_coord));
// x_coord can have batch size property of link_object
ResolveObjectNames(object_name, names, &x_coord);
*result = it->second;
ReplaceAllWords("in_out_value", value_name, result);
ReplaceAllWords("X_COORD", x_coord, result);
ReplaceAllWords("Y_COORD", y_coord, result);
ReplaceAllWords("S_COORD", s_coord, result);
RETURN_IF_ERROR(ResolveSelectorsPass(gpu_info, args, {}, result));
if (selector == "Linking") {
return absl::OkStatus();
}
}
}
std::string patch;
RETURN_IF_ERROR(desc_ptr->PerformSelector(gpu_info, selector, function_args,
template_args, &patch));
ResolveObjectNames(object_name, names, &patch);
*result += patch;
return absl::OkStatus();
}
void MetalArguments::ResolveObjectNames(
const std::string& object_name,
const std::vector<std::string>& member_names, std::string* code) {
for (const auto& member_name : member_names) {
const std::string new_name = kArgsPrefix + object_name + "_" + member_name;
ReplaceAllWords(member_name, new_name, code);
}
}
void MetalArguments::ResolveArgsPass(std::string* code) {
size_t position = 0;
size_t next_position = code->find(kArgsPrefix);
while (next_position != std::string::npos) {
size_t arg_pos = next_position;
next_position += strlen(kArgsPrefix);
std::string object_name = GetNextWord(*code, next_position);
std::string new_name = object_name;
code->replace(arg_pos, object_name.size() + strlen(kArgsPrefix), new_name);
position = arg_pos + new_name.size();
next_position = code->find(kArgsPrefix, position);
}
}
absl::Status MetalArguments::SetObjectsResources(const Arguments& args) {
int i = 0;
for (const auto& t : args.objects_) {
GPUResourcesWithValue resources;
RETURN_IF_ERROR(objects_[i]->GetGPUResources(t.second.get(), &resources));
RETURN_IF_ERROR(SetGPUResources(t.first, resources));
i++;
}
return absl::OkStatus();
}
} // namespace metal
} // namespace gpu
} // namespace tflite
| [
"gardener@tensorflow.org"
] | gardener@tensorflow.org |
12b384e9f3d457ec6f7fa76d50f7a4db568c67f9 | 92ada3eabb986350da3f4919a1d75c71a170854d | /autoupdate/common/3rd/boost/mpl/set/aux_/empty_impl.hpp | 5f4001ca62be7832591b0b9263ea1d56ad254feb | [] | no_license | jjzhang166/autoupdate | 126e52be7d610fe121b615c0998af69dcbe70104 | 7a54996619f03b0febd762c007d5de0c85045a31 | refs/heads/master | 2021-05-05T20:09:44.330623 | 2015-08-27T08:57:52 | 2015-08-27T08:57:52 | 103,895,533 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 817 | hpp |
#ifndef BOOST_MPL_SET_AUX_EMPTY_IMPL_HPP_INCLUDED
#define BOOST_MPL_SET_AUX_EMPTY_IMPL_HPP_INCLUDED
// Copyright Aleksey Gurtovoy 2003-2004
//
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
//
// See http://www.boost.org/libs/mpl for documentation.
// $Source: /repo/3rd/boost/mpl/set/aux_/empty_impl.hpp,v $
// $Date: 2010/04/29 03:06:06 $
// $Revision: 1.1.1.1 $
#include <boost/mpl/empty_fwd.hpp>
#include <boost/mpl/not.hpp>
#include <boost/mpl/set/aux_/tag.hpp>
namespace boost { namespace mpl {
template<>
struct empty_impl< aux::set_tag >
{
template< typename Set > struct apply
: not_< typename Set::size >
{
};
};
}}
#endif // BOOST_MPL_SET_AUX_EMPTY_IMPL_HPP_INCLUDED
| [
"269221745@qq.com"
] | 269221745@qq.com |
af5110e8f27a7081617eff26d55990bdb461fa5c | 3c9d2f061b369d25f562144b3d094f655ee8ea24 | /TowerSignalMain.cpp | a5537b6584b26ff55ea580c05dd882b7721f163b | [] | no_license | nessim-m/CS-202 | b7e99b1c89cf101495df5a2334f9139de15d9cf3 | 174a486ca2b8673150f6563a85fb0b132d5b3971 | refs/heads/master | 2020-07-07T23:30:17.884638 | 2019-08-22T22:24:59 | 2019-08-22T22:24:59 | 203,506,156 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,118 | cpp | #include <iostream>
#include "TowerSignal.h"
#include <string>
#include <fstream>
using namespace std;
int main()
{
ifstream infile;//ifstream to readin the file
string filename;//the following is a string for the file name
int numbers;//integers that holds the value of the numbers read in from the file
int x;//integer value for top tower
myStack Tower;//Tower object that store all the number read in from the file
myStack PlaceHolder;// Placeholder object holds the value of numbers that haven't been compared
myStack Range;// Range object holds the value of each tower's range
do
{
cout<< "Enter a filename: ";
cin>> filename;
//filename.c_str() returns a C style string version
infile.open(filename.c_str());
}
while(!infile.is_open());
//the following while loop read in from the file and pushes it to myStack Tower
while(!infile.eof())
{
infile>> numbers;
Tower.push(numbers);
}
/*The following loop checks if the last number pushed in is larger than the number pushed before it.*/
while(Tower.isEmpty()!= true)
{
int RangeCounter=1;
x= Tower.top();
Tower.pop();
//The following if statment checks if Tower is empty and if its it pushes rangecounter to Range
if(Tower.isEmpty()==true)
{
Range.push(RangeCounter);
break;
}
/*The following while loop checks x, which the last Tower.top() was pushed in, if the current Tower.
top is less than x it push it to PlaceHolder and increments rangecounter by 1. */
while(x > Tower.top())
{
PlaceHolder.push(Tower.top());
Tower.pop();
RangeCounter++;
}
Range.push(RangeCounter);
//The following while loop pushes back the stored numbers in placeholder to Tower
while(PlaceHolder.isEmpty() != true)
{
Tower.push(PlaceHolder.top());
PlaceHolder.pop();
}
}
cout<< "Here are the ranges for each tower"<< endl;
//the following while loop keeps outputting the numbers pushed in reverse
while(Range.isEmpty()!= true)
{
cout<<Range.top()<<" ";
Range.pop();
}
return 0;
} | [
"noreply@github.com"
] | noreply@github.com |
140021dd7697bd6a0d0e93565214f82464b20ca5 | 5419ec31b9aec07477ac45cb97ee3074fc6fba4c | /Helloworld/Classes/Scenes/CcbAccountBindingScene.h | 75111cd8d137df5df297ca90ce05dc3281cc358e | [] | no_license | Relvin/RelvinPetTwo | 59ceded93181f2d301f6d33e70367fb45906c9ba | 1b7bc4677c2a9620a2008e0fa9a925d4a5ca1af5 | refs/heads/master | 2020-03-30T06:39:00.198117 | 2015-01-07T09:55:49 | 2015-01-07T09:55:49 | 28,892,826 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 914 | h | //
// CcbAccountBindingScene.h
// HelloWorld
//
// Created by jun on 14-5-12.
//
//
#ifndef __HelloWorld__CcbAccountBindingScene__
#define __HelloWorld__CcbAccountBindingScene__
#include "cocos2d.h"
#include "cocos-ext.h"
USING_NS_CC;
USING_NS_CC_EXT;
class CcbAccountBindingScene:public CCLayer
, public CCBMemberVariableAssigner
{
public:
CcbAccountBindingScene();
~CcbAccountBindingScene();
CREATE_FUNC(CcbAccountBindingScene);
virtual bool onAssignCCBMemberVariable(cocos2d::CCObject* pTarget, const char* pMemberVariableName, cocos2d::CCNode* pNode);
static cocos2d::CCScene* scene();
public:
virtual bool init();
virtual void onEnter();
virtual void onExit();
virtual void onExitTransitionDidStart();
virtual void onEnterTransitionDidFinish();
private:
CCLabelTTF* m_pLabelTTFName;
};
#endif /* defined(__HelloWorld__CcbAccountBindingScene__) */
| [
"Relvin@Relvin.local"
] | Relvin@Relvin.local |
60b384d57040626c875c91bec49350cb93fc5cf0 | a0c124874ec5ab4dde8e3a02d418cd56954f2e33 | /solvers/laminarSMOKE/radiativeHeatTransferClass.H | 2c82c744097a3c93753a066fa0a8d69ba9d4dd0d | [] | no_license | kyleniemeyer/laminarSMOKE | 1511eb4dc8ed8f4e1555737c2962e22a9eace52d | c75bb6df84ba4245c886e75300c2753fc5ac94b3 | refs/heads/master | 2020-04-06T06:24:17.830759 | 2014-11-13T12:29:46 | 2014-11-13T12:29:46 | 29,838,295 | 1 | 0 | null | 2015-01-26T00:35:27 | 2015-01-26T00:35:27 | null | UTF-8 | C++ | false | false | 3,163 | h |
enum radiationModels { RADIATION_NONE, RADIATION_OPTICALLY_THIN} ;
class radiativeHeatTransferClass
{
public:
radiativeHeatTransferClass()
{
radiationModel_ = RADIATION_NONE;
Tenv_ = 0.;
Tenv4_ = 0.;
iCH4_ = 0;
iCO2_ = 0;
iCO_ = 0;
iH2O_ = 0;
xCH4_ = 0.;
xCO2_ = 0.;
xCO_ = 0.;
xH2O_ = 0.;
}
void SetThermodynamics(const OpenSMOKE::ThermodynamicsMap_CHEMKIN<double>& thermodynamicsMapXML)
{
iCH4_ = thermodynamicsMapXML.IndexOfSpeciesWithoutError("CH4");
iH2O_ = thermodynamicsMapXML.IndexOfSpeciesWithoutError("H2O");
iCO2_ = thermodynamicsMapXML.IndexOfSpeciesWithoutError("CO2");
iCO_ = thermodynamicsMapXML.IndexOfSpeciesWithoutError("CO");
if (iCH4_==0) iCH4_ = thermodynamicsMapXML.IndexOfSpeciesWithoutError("ch4");
if (iH2O_==0) iH2O_ = thermodynamicsMapXML.IndexOfSpeciesWithoutError("h2o");
if (iCO2_==0) iCO2_ = thermodynamicsMapXML.IndexOfSpeciesWithoutError("co2");
if (iCO_==0) iCO_ = thermodynamicsMapXML.IndexOfSpeciesWithoutError("co");
}
void SetRadiationModel(const radiationModels model)
{
radiationModel_ = model;
}
void SetEnvironmentTemperature(const double Tenv)
{
Tenv_ = Tenv;
Tenv4_ = Tenv*Tenv*Tenv*Tenv;
}
radiationModels radiationModel() const { return radiationModel_; }
double aPlanck(const double T, const double P_Pa, const OpenSMOKE::OpenSMOKEVectorDouble& x)
{
xCH4_ = (iCH4_>0) ? x[iCH4_] : 0. ;
xCO2_ = (iCO2_>0) ? x[iCO2_] : 0. ;
xCO_ = (iCO_>0) ? x[iCO_] : 0. ;
xH2O_ = (iH2O_>0) ? x[iH2O_] : 0. ;
return aPlanck(T, P_Pa, xCH4_, xH2O_, xCO2_, xCO_);
}
double Q(const double T, const double a)
{
return 4.*sigmaSB_*a*(T*T*T*T - Tenv4_);
}
private:
double Tenv_;
double Tenv4_;
radiationModels radiationModel_;
unsigned int iCH4_;
unsigned int iCO2_;
unsigned int iCO_;
unsigned int iH2O_;
double xH2O_;
double xCO_;
double xCO2_;
double xCH4_;
static const double sigmaSB_;
double aPlanck(const double T, const double P_Pa, const double xCH4, const double xH2O, const double xCO2, const double xCO);
};
const double radiativeHeatTransferClass::sigmaSB_ = 5.67e-8; // [W/m2/K4]
double radiativeHeatTransferClass::aPlanck(const double T, const double P_Pa, const double xCH4, const double xH2O, const double xCO2, const double xCO)
{
double a = 0.;
const double uT = 1000./T; // [1]
// 1. Water [1/m/bar]
if (iH2O_>0)
{
const double KH2O = -0.23093 +uT*(-1.1239+uT*(9.4153 +uT*(-2.9988 +uT*( 0.51382 + uT*(-1.8684e-5)))));
a+=KH2O*xH2O;
}
// 2. Carbon Dioxide [1/m/bar]
if (iCO2_>0)
{
const double KCO2 = 18.741 +uT*(-121.31+uT*(273.5 +uT*(-194.05 +uT*( 56.31 + uT*(-5.8169)))));
a+=KCO2*xCO2;
}
// 3. Carbon monoxide [1/m/bar]
if (iCO_>0)
{
const double KCO = ( T < 750. ) ?
4.7869+T*(-0.06953 + T*(2.95775e-4 + T*(-4.25732e-7 + T*2.02894e-10))) :
10.09+T*(-0.01183 + T*(4.7753e-6 + T*(-5.87209e-10 + T*-2.5334e-14)));
a+=KCO*xCO;
}
// 4. Methane [1/m/bar]
if (iCH4_>0)
{
const double KCH4 = 6.6334 +T*(- 0.0035686+T*(1.6682e-08+T*(2.5611e-10-2.6558e-14*T)));
a+=KCH4*xCH4;
}
// Planck mean absorption coefficient [1/m]
return a * (P_Pa/1.e5);
}
| [
"alberto.cuoci@gmail.com"
] | alberto.cuoci@gmail.com |
af323b9ba5f344484dccd2d28e17be492be11941 | 9f16ceb7f674234889f796a5b99d342f9edf3399 | /groupAnagram.cpp | 1cdbfaf5d1b0e396faacec203925e1e141854ed6 | [] | no_license | Segfred/leetcode | 382297025b790790a38f079d5938e158c3bd8260 | b102c4d9abea9caad0b08b7df0d9e89bc6dbc115 | refs/heads/master | 2021-06-11T05:10:21.853331 | 2021-04-03T02:42:59 | 2021-04-03T02:42:59 | 87,050,255 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 698 | cpp | class Solution {
public:
vector<vector<string>> groupAnagrams(vector<string>& strs) {
vector<vector<string>> res{};
if(strs.empty()) return res;
unordered_map<string,vector<size_t>> hash{};//排序后的字符串和下标映射
for(size_t i=0;i<strs.size();++i){
string cur=strs[i];
sort(cur.begin(),cur.end());
hash[cur].emplace_back(i);
}
for(auto &ele:hash){//遍历hash容易把所有相同string放到同一个vector,直接放结果里,遍历原来的strs就要一次次找对应
vector<string> item{};//string位置,比较麻烦
for(size_t idx:ele.second) item.emplace_back(strs[idx]);//存的是下标,不是字符串本身
res.emplace_back(item);
}
return res;
}
};
| [
"noreply@github.com"
] | noreply@github.com |
f74d291bd8403cfb88c620a4ceaba97ed63ef72e | 2aad21460b2aa836721bc211ef9b1e7727dcf824 | /IE_Tool/MoveLayer/MoveLayer.cpp | 85f98227f4bebe0496c8dec7ff4daa22ae165919 | [
"BSD-3-Clause"
] | permissive | chazix/frayer | 4b38c9d378ce8b3b50d66d1e90426792b2196e5b | ec0a671bc6df3c5f0fe3a94d07b6748a14a8ba91 | refs/heads/master | 2020-03-16T20:28:34.440698 | 2018-01-09T15:13:03 | 2018-01-09T15:13:03 | null | 0 | 0 | null | null | null | null | SHIFT_JIS | C++ | false | false | 2,884 | cpp | #include "resource.h"
#include "MoveLayer.h"
// for detect memory leak
#ifdef _DEBUG
#define _CRTDBG_MAP_ALLOC
#include <stdlib.h>
#include <cstdlib>
#include <crtdbg.h>
#define new new(_NORMAL_BLOCK, __FILE__, __LINE__)
#endif
static HMODULE g_hLibrary;
#ifdef _MANAGED
#pragma managed(push, off)
#endif
BOOL APIENTRY DllMain( HMODULE hModule,
DWORD ul_reason_for_call,
LPVOID lpReserved
)
{
g_hLibrary = hModule;
return TRUE;
}
#ifdef _MANAGED
#pragma managed(pop)
#endif
#define DISPLAY_NAME_JA "レイヤー平行移動"
#define DISPLAY_NAME DISPLAY_NAME_JA
IETOOL_EXPORT IEMODULE_ID GetIEModule_ID()
{
return IEMODULE_ID::TOOL;
}
IETOOL_EXPORT IIETool* CreateIETool()
{
return new MoveLayer;
}
IETOOL_EXPORT void ReleaseIETool(IIETool** ppTool)
{
if (*ppTool) {
delete (*ppTool);
(*ppTool) = NULL;
}
}
MoveLayer::MoveLayer()
{
strcpy_s(m_name, MAX_IE_MODULE_NAME, "MoveLayer");
strcpy_s(m_disp_name, MAX_IE_MODULE_DISPLAY_NAME, DISPLAY_NAME);
}
MoveLayer::~MoveLayer()
{
if (m_buttonImg) {
::DeleteObject(m_buttonImg);
}
}
HBITMAP MoveLayer::GetButtonImg()
{
if (m_buttonImg) {
::DeleteObject(m_buttonImg);
m_buttonImg = NULL;
}
m_buttonImg = ::LoadBitmap((HINSTANCE)g_hLibrary, MAKEINTRESOURCE(IDB_BUTTON_BMP));
return m_buttonImg;
}
void MoveLayer::OnMouseLButtonDown(UINT nFlags, const LPIE_INPUT_DATA lpd)
{
move_X = 0;
move_Y = 0;
startPt.x = beforPt.x = lpd->x;
startPt.y = beforPt.y = lpd->y;
ImgFile_Ptr f = m_pImgEdit->GetActiveFile();
if(!f) return;
m_pEditLayer = f->GetSelectLayer().lock();
if(!m_pEditLayer) return;
//
m_pMoveLayerHandle = (MoveLayerHandle*) f->CreateImgFileHandle(IFH_MOVE_LAYER);
strcpy_s(m_pMoveLayerHandle->handle_name, MAX_IMG_FILE_HANDLE_NAME, DISPLAY_NAME);
f->DoImgFileHandle( m_pMoveLayerHandle );
//
m_pEditLayer->GetLayerRect(&beforRc);
}
void MoveLayer::OnMouseLDrag(UINT nFlags, const LPIE_INPUT_DATA lpd)
{
ImgFile_Ptr f = m_pImgEdit->GetActiveFile();
if(!f) return;
m_pEditLayer = f->GetSelectLayer().lock();
if(!m_pEditLayer) return;
fMoveLayer(lpd, &beforPt);
beforPt.x = lpd->x;
beforPt.y = lpd->y;
}
void MoveLayer::OnMouseLButtonUp(UINT nFlags, const LPIE_INPUT_DATA lpd)
{
ImgFile_Ptr f = m_pImgEdit->GetActiveFile();
if(!f) return;
m_pEditLayer = f->GetSelectLayer().lock();
if(!m_pEditLayer) return;
fMoveLayer(lpd, &beforPt);
//レイヤー領域拡張
m_pEditLayer->ExtendLayer();
m_pMoveLayerHandle->Update();
}
void MoveLayer::fMoveLayer(LPIE_INPUT_DATA lpd, LPPOINT beforPt)
{
ImgFile_Ptr f = m_pImgEdit->GetActiveFile();
if(f){
int shiftX = lpd->x - beforPt->x;
int shiftY = lpd->y - beforPt->y;
move_X += shiftX;
move_Y += shiftY;
//レイヤーの移動
m_pMoveLayerHandle->SetMoveXY(move_X, move_Y);
//画像の更新
m_pMoveLayerHandle->Update();
}
} | [
"key0note@gmail.com"
] | key0note@gmail.com |
c38a24478270b48145d7fee0550bbf036c6d228f | efa6ff167e0fe600e28b10a8d84cbd1a3a44d764 | /src/activemasternode.h | fe8d5a8a6ae460629d41df7f7e2eae73cefeecb4 | [
"MIT"
] | permissive | BlancoCoin/Blanco | f3b55bd5df2887db8e31d55a17ee334697dd9a3d | 7398b5c169ebc518d565e42e1a9d38ba87daac59 | refs/heads/master | 2020-03-14T23:51:31.362556 | 2018-05-07T17:58:40 | 2018-05-07T17:58:40 | 131,854,703 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,846 | h | // Copyright (c) 2009-2010 Satoshi Nakamoto
// Copyright (c) 2009-2012 The DarkCoin developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#ifndef ACTIVEMASTERNODE_H
#define ACTIVEMASTERNODE_H
#include "uint256.h"
#include "sync.h"
#include "net.h"
#include "key.h"
#include "masternode.h"
#include "main.h"
#include "init.h"
#include "wallet.h"
#include "darksend.h"
// Responsible for activating the masternode and pinging the network
class CActiveMasternode
{
public:
// Initialized by init.cpp
// Keys for the main masternode
CPubKey pubKeyMasternode;
// Initialized while registering masternode
CTxIn vin;
CService service;
int status;
std::string notCapableReason;
CActiveMasternode()
{
status = MASTERNODE_NOT_PROCESSED;
}
void ManageStatus(); // manage status of main masternode
bool Dseep(std::string& errorMessage); // ping for main masternode
bool Dseep(CTxIn vin, CService service, CKey key, CPubKey pubKey, std::string &retErrorMessage, bool stop); // ping for any masternode
bool StopMasterNode(std::string& errorMessage); // stop main masternode
bool StopMasterNode(std::string strService, std::string strKeyMasternode, std::string& errorMessage); // stop remote masternode
bool StopMasterNode(CTxIn vin, CService service, CKey key, CPubKey pubKey, std::string& errorMessage); // stop any masternode
/// Register remote Masternode
bool Register(std::string strService, std::string strKey, std::string txHash, std::string strOutputIndex, std::string strRewardAddress, std::string strRewardPercentage, std::string& errorMessage);
/// Register any Masternode
bool Register(CTxIn vin, CService service, CKey key, CPubKey pubKey, CKey keyMasternode, CPubKey pubKeyMasternode, CScript rewardAddress, int rewardPercentage, std::string &retErrorMessage);
// get 5000 BAC input that can be used for the masternode
bool GetMasterNodeVin(CTxIn& vin, CPubKey& pubkey, CKey& secretKey);
bool GetMasterNodeVin(CTxIn& vin, CPubKey& pubkey, CKey& secretKey, std::string strTxHash, std::string strOutputIndex);
bool GetMasterNodeVinForPubKey(std::string collateralAddress, CTxIn& vin, CPubKey& pubkey, CKey& secretKey);
bool GetMasterNodeVinForPubKey(std::string collateralAddress, CTxIn& vin, CPubKey& pubkey, CKey& secretKey, std::string strTxHash, std::string strOutputIndex);
vector<COutput> SelectCoinsMasternode();
vector<COutput> SelectCoinsMasternodeForPubKey(std::string collateralAddress);
bool GetVinFromOutput(COutput out, CTxIn& vin, CPubKey& pubkey, CKey& secretKey);
// enable hot wallet mode (run a masternode with no funds)
bool EnableHotColdMasterNode(CTxIn& vin, CService& addr);
};
#endif
| [
" "
] | |
ee248f805af0abe0d20667ec3fdefd24e56884f0 | 5456502f97627278cbd6e16d002d50f1de3da7bb | /ui/app_list/views/search_box_view.cc | 83fa07c0c348038b6c3892ac996496da822a3fae | [
"BSD-3-Clause"
] | permissive | TrellixVulnTeam/Chromium_7C66 | 72d108a413909eb3bd36c73a6c2f98de1573b6e5 | c8649ab2a0f5a747369ed50351209a42f59672ee | refs/heads/master | 2023-03-16T12:51:40.231959 | 2017-12-20T10:38:26 | 2017-12-20T10:38:26 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 14,848 | cc | // Copyright (c) 2012 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.
#include "ui/app_list/views/search_box_view.h"
#include <algorithm>
#include "base/macros.h"
#include "base/memory/ptr_util.h"
#include "build/build_config.h"
#include "ui/app_list/app_list_constants.h"
#include "ui/app_list/app_list_model.h"
#include "ui/app_list/app_list_switches.h"
#include "ui/app_list/app_list_view_delegate.h"
#include "ui/app_list/resources/grit/app_list_resources.h"
#include "ui/app_list/search_box_model.h"
#include "ui/app_list/speech_ui_model.h"
#include "ui/app_list/views/contents_view.h"
#include "ui/app_list/views/search_box_view_delegate.h"
#include "ui/base/ime/text_input_flags.h"
#include "ui/base/l10n/l10n_util.h"
#include "ui/base/resource/resource_bundle.h"
#include "ui/events/event.h"
#include "ui/gfx/canvas.h"
#include "ui/gfx/shadow_value.h"
#include "ui/strings/grit/ui_strings.h"
#include "ui/views/background.h"
#include "ui/views/border.h"
#include "ui/views/controls/button/image_button.h"
#include "ui/views/controls/image_view.h"
#include "ui/views/controls/textfield/textfield.h"
#include "ui/views/layout/box_layout.h"
#include "ui/views/layout/fill_layout.h"
#include "ui/views/shadow_border.h"
namespace app_list {
namespace {
const int kPadding = 16;
const int kInnerPadding = 24;
const int kPreferredWidth = 360;
const int kPreferredHeight = 48;
const SkColor kHintTextColor = SkColorSetRGB(0xA0, 0xA0, 0xA0);
const int kBackgroundBorderCornerRadius = 2;
// A background that paints a solid white rounded rect with a thin grey border.
class SearchBoxBackground : public views::Background {
public:
SearchBoxBackground() {}
~SearchBoxBackground() override {}
private:
// views::Background overrides:
void Paint(gfx::Canvas* canvas, views::View* view) const override {
gfx::Rect bounds = view->GetContentsBounds();
SkPaint paint;
paint.setFlags(SkPaint::kAntiAlias_Flag);
paint.setColor(kSearchBoxBackground);
canvas->DrawRoundRect(bounds, kBackgroundBorderCornerRadius, paint);
}
DISALLOW_COPY_AND_ASSIGN(SearchBoxBackground);
};
} // namespace
// To paint grey background on mic and back buttons
class SearchBoxImageButton : public views::ImageButton {
public:
explicit SearchBoxImageButton(views::ButtonListener* listener)
: ImageButton(listener), selected_(false) {}
~SearchBoxImageButton() override {}
bool selected() { return selected_; }
void SetSelected(bool selected) {
if (selected_ == selected)
return;
selected_ = selected;
SchedulePaint();
if (selected)
NotifyAccessibilityEvent(ui::AX_EVENT_SELECTION, true);
}
bool OnKeyPressed(const ui::KeyEvent& event) override {
// Disable space key to press the button. The keyboard events received
// by this view are forwarded from a Textfield (SearchBoxView) and key
// released events are not forwarded. This leaves the button in pressed
// state.
if (event.key_code() == ui::VKEY_SPACE)
return false;
return CustomButton::OnKeyPressed(event);
}
private:
// views::View overrides:
void OnPaintBackground(gfx::Canvas* canvas) override {
if (state() == STATE_HOVERED || state() == STATE_PRESSED || selected_)
canvas->FillRect(gfx::Rect(size()), kSelectedColor);
}
bool selected_;
DISALLOW_COPY_AND_ASSIGN(SearchBoxImageButton);
};
SearchBoxView::SearchBoxView(SearchBoxViewDelegate* delegate,
AppListViewDelegate* view_delegate)
: delegate_(delegate),
view_delegate_(view_delegate),
model_(NULL),
content_container_(new views::View),
back_button_(NULL),
speech_button_(NULL),
search_box_(new views::Textfield),
contents_view_(NULL),
focused_view_(FOCUS_SEARCH_BOX) {
SetLayoutManager(new views::FillLayout);
AddChildView(content_container_);
SetShadow(GetShadowForZHeight(2));
back_button_ = new SearchBoxImageButton(this);
ui::ResourceBundle& rb = ui::ResourceBundle::GetSharedInstance();
back_button_->SetImage(views::ImageButton::STATE_NORMAL,
rb.GetImageSkiaNamed(IDR_APP_LIST_FOLDER_BACK_NORMAL));
back_button_->SetImageAlignment(views::ImageButton::ALIGN_CENTER,
views::ImageButton::ALIGN_MIDDLE);
SetBackButtonLabel(false);
content_container_->AddChildView(back_button_);
content_container_->set_background(new SearchBoxBackground());
views::BoxLayout* layout =
new views::BoxLayout(views::BoxLayout::kHorizontal, kPadding, 0,
kInnerPadding - views::Textfield::kTextPadding);
content_container_->SetLayoutManager(layout);
layout->set_cross_axis_alignment(
views::BoxLayout::CROSS_AXIS_ALIGNMENT_CENTER);
layout->set_minimum_cross_axis_size(kPreferredHeight);
search_box_->SetBorder(views::NullBorder());
search_box_->SetTextColor(kSearchTextColor);
search_box_->SetBackgroundColor(kSearchBoxBackground);
search_box_->set_placeholder_text_color(kHintTextColor);
search_box_->set_controller(this);
search_box_->SetTextInputType(ui::TEXT_INPUT_TYPE_SEARCH);
search_box_->SetTextInputFlags(ui::TEXT_INPUT_FLAG_AUTOCORRECT_OFF);
content_container_->AddChildView(search_box_);
layout->SetFlexForView(search_box_, 1);
view_delegate_->GetSpeechUI()->AddObserver(this);
ModelChanged();
}
SearchBoxView::~SearchBoxView() {
view_delegate_->GetSpeechUI()->RemoveObserver(this);
model_->search_box()->RemoveObserver(this);
}
void SearchBoxView::ModelChanged() {
if (model_)
model_->search_box()->RemoveObserver(this);
model_ = view_delegate_->GetModel();
DCHECK(model_);
model_->search_box()->AddObserver(this);
SpeechRecognitionButtonPropChanged();
HintTextChanged();
}
bool SearchBoxView::HasSearch() const {
return !search_box_->text().empty();
}
void SearchBoxView::ClearSearch() {
search_box_->SetText(base::string16());
view_delegate_->AutoLaunchCanceled();
// Updates model and fires query changed manually because SetText() above
// does not generate ContentsChanged() notification.
UpdateModel();
NotifyQueryChanged();
}
void SearchBoxView::SetShadow(const gfx::ShadowValue& shadow) {
SetBorder(base::MakeUnique<views::ShadowBorder>(shadow));
Layout();
}
gfx::Rect SearchBoxView::GetViewBoundsForSearchBoxContentsBounds(
const gfx::Rect& rect) const {
gfx::Rect view_bounds = rect;
view_bounds.Inset(-GetInsets());
return view_bounds;
}
views::ImageButton* SearchBoxView::back_button() {
return static_cast<views::ImageButton*>(back_button_);
}
// Returns true if set internally, i.e. if focused_view_ != CONTENTS_VIEW.
// Note: because we always want to be able to type in the edit box, this is only
// a faux-focus so that buttons can respond to the ENTER key.
bool SearchBoxView::MoveTabFocus(bool move_backwards) {
if (back_button_)
back_button_->SetSelected(false);
if (speech_button_)
speech_button_->SetSelected(false);
switch (focused_view_) {
case FOCUS_BACK_BUTTON:
focused_view_ = move_backwards ? FOCUS_BACK_BUTTON : FOCUS_SEARCH_BOX;
break;
case FOCUS_SEARCH_BOX:
if (move_backwards) {
focused_view_ = back_button_ && back_button_->visible()
? FOCUS_BACK_BUTTON : FOCUS_SEARCH_BOX;
} else {
focused_view_ = speech_button_ && speech_button_->visible()
? FOCUS_MIC_BUTTON : FOCUS_CONTENTS_VIEW;
}
break;
case FOCUS_MIC_BUTTON:
focused_view_ = move_backwards ? FOCUS_SEARCH_BOX : FOCUS_CONTENTS_VIEW;
break;
case FOCUS_CONTENTS_VIEW:
focused_view_ = move_backwards
? (speech_button_ && speech_button_->visible() ?
FOCUS_MIC_BUTTON : FOCUS_SEARCH_BOX)
: FOCUS_CONTENTS_VIEW;
break;
default:
DCHECK(false);
}
switch (focused_view_) {
case FOCUS_BACK_BUTTON:
if (back_button_)
back_button_->SetSelected(true);
break;
case FOCUS_SEARCH_BOX:
// Set the ChromeVox focus to the search box. However, DO NOT do this if
// we are in the search results state (i.e., if the search box has text in
// it), because the focus is about to be shifted to the first search
// result and we do not want to read out the name of the search box as
// well.
if (search_box_->text().empty())
search_box_->NotifyAccessibilityEvent(ui::AX_EVENT_FOCUS, true);
break;
case FOCUS_MIC_BUTTON:
if (speech_button_)
speech_button_->SetSelected(true);
break;
default:
break;
}
if (focused_view_ < FOCUS_CONTENTS_VIEW)
delegate_->SetSearchResultSelection(focused_view_ == FOCUS_SEARCH_BOX);
return (focused_view_ < FOCUS_CONTENTS_VIEW);
}
void SearchBoxView::ResetTabFocus(bool on_contents) {
if (back_button_)
back_button_->SetSelected(false);
if (speech_button_)
speech_button_->SetSelected(false);
focused_view_ = on_contents ? FOCUS_CONTENTS_VIEW : FOCUS_SEARCH_BOX;
}
void SearchBoxView::SetBackButtonLabel(bool folder) {
if (!back_button_)
return;
base::string16 back_button_label(l10n_util::GetStringUTF16(
folder ? IDS_APP_LIST_FOLDER_CLOSE_FOLDER_ACCESSIBILE_NAME
: IDS_APP_LIST_BACK));
back_button_->SetAccessibleName(back_button_label);
back_button_->SetTooltipText(back_button_label);
}
gfx::Size SearchBoxView::GetPreferredSize() const {
return gfx::Size(kPreferredWidth, kPreferredHeight);
}
bool SearchBoxView::OnMouseWheel(const ui::MouseWheelEvent& event) {
if (contents_view_)
return contents_view_->OnMouseWheel(event);
return false;
}
void SearchBoxView::OnEnabledChanged() {
search_box_->SetEnabled(enabled());
if (speech_button_)
speech_button_->SetEnabled(enabled());
}
void SearchBoxView::UpdateModel() {
// Temporarily remove from observer to ignore notifications caused by us.
model_->search_box()->RemoveObserver(this);
model_->search_box()->SetText(search_box_->text());
model_->search_box()->SetSelectionModel(search_box_->GetSelectionModel());
model_->search_box()->AddObserver(this);
}
void SearchBoxView::NotifyQueryChanged() {
DCHECK(delegate_);
delegate_->QueryChanged(this);
}
void SearchBoxView::ContentsChanged(views::Textfield* sender,
const base::string16& new_contents) {
UpdateModel();
view_delegate_->AutoLaunchCanceled();
NotifyQueryChanged();
}
bool SearchBoxView::HandleKeyEvent(views::Textfield* sender,
const ui::KeyEvent& key_event) {
if (key_event.type() == ui::ET_KEY_PRESSED) {
if (key_event.key_code() == ui::VKEY_TAB &&
focused_view_ != FOCUS_CONTENTS_VIEW &&
MoveTabFocus(key_event.IsShiftDown()))
return true;
if (focused_view_ == FOCUS_BACK_BUTTON && back_button_ &&
back_button_->OnKeyPressed(key_event))
return true;
if (focused_view_ == FOCUS_MIC_BUTTON && speech_button_ &&
speech_button_->OnKeyPressed(key_event))
return true;
const bool handled = contents_view_ && contents_view_->visible() &&
contents_view_->OnKeyPressed(key_event);
// Arrow keys may have selected an item. If they did, move focus off
// buttons.
// If they didn't, we still select the first search item, in case they're
// moving the caret through typed search text. The UP arrow never moves
// focus from text/buttons to app list/results, so ignore it.
if (focused_view_ < FOCUS_CONTENTS_VIEW &&
(key_event.key_code() == ui::VKEY_LEFT ||
key_event.key_code() == ui::VKEY_RIGHT ||
key_event.key_code() == ui::VKEY_DOWN)) {
if (!handled)
delegate_->SetSearchResultSelection(true);
ResetTabFocus(handled);
}
return handled;
}
if (key_event.type() == ui::ET_KEY_RELEASED) {
if (focused_view_ == FOCUS_BACK_BUTTON && back_button_ &&
back_button_->OnKeyReleased(key_event))
return true;
if (focused_view_ == FOCUS_MIC_BUTTON && speech_button_ &&
speech_button_->OnKeyReleased(key_event))
return true;
return contents_view_ && contents_view_->visible() &&
contents_view_->OnKeyReleased(key_event);
}
return false;
}
void SearchBoxView::ButtonPressed(views::Button* sender,
const ui::Event& event) {
if (back_button_ && sender == back_button_)
delegate_->BackButtonPressed();
else if (speech_button_ && sender == speech_button_)
view_delegate_->StartSpeechRecognition();
else
NOTREACHED();
}
void SearchBoxView::SpeechRecognitionButtonPropChanged() {
const SearchBoxModel::SpeechButtonProperty* speech_button_prop =
model_->search_box()->speech_button();
if (speech_button_prop) {
if (!speech_button_) {
speech_button_ = new SearchBoxImageButton(this);
content_container_->AddChildView(speech_button_);
}
speech_button_->SetAccessibleName(speech_button_prop->accessible_name);
if (view_delegate_->GetSpeechUI()->state() ==
SPEECH_RECOGNITION_HOTWORD_LISTENING) {
speech_button_->SetImage(
views::Button::STATE_NORMAL, &speech_button_prop->on_icon);
speech_button_->SetTooltipText(speech_button_prop->on_tooltip);
} else {
speech_button_->SetImage(
views::Button::STATE_NORMAL, &speech_button_prop->off_icon);
speech_button_->SetTooltipText(speech_button_prop->off_tooltip);
}
} else {
if (speech_button_) {
// Deleting a view will detach it from its parent.
delete speech_button_;
speech_button_ = NULL;
}
}
Layout();
}
void SearchBoxView::HintTextChanged() {
const app_list::SearchBoxModel* search_box = model_->search_box();
search_box_->set_placeholder_text(search_box->hint_text());
search_box_->SetAccessibleName(search_box->accessible_name());
}
void SearchBoxView::SelectionModelChanged() {
search_box_->SelectSelectionModel(model_->search_box()->selection_model());
}
void SearchBoxView::TextChanged() {
search_box_->SetText(model_->search_box()->text());
NotifyQueryChanged();
}
void SearchBoxView::OnSpeechRecognitionStateChanged(
SpeechRecognitionState new_state) {
SpeechRecognitionButtonPropChanged();
SchedulePaint();
}
} // namespace app_list
| [
"lixiaodonglove7@aliyun.com"
] | lixiaodonglove7@aliyun.com |
1dede3b42756523e6315358d30b9caac9f3ee60f | bdea879fa256cbba165dd15715ef7f0055878ec1 | /test/UnitTests/SharedPtrTest.cpp | 6b6e2485fa39351780534d0223dc0adae20fb7a5 | [] | no_license | Enseed/Season_build | a88f14706d1af58d9567072360431b1d81d6d7f6 | 0dba9632b9581bda81440419edd554cda8d46e02 | refs/heads/master | 2023-08-29T18:14:12.742009 | 2015-08-24T03:34:50 | 2015-08-24T03:34:50 | 41,276,457 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 439 | cpp | #include "Precompiled.h"
#include "gtest/gtest.h"
#include "Season/RapidSeason.h"
#include "Season/BoostSeason.h"
#include "Tests.h"
#include <memory>
TEST(SharedPtrTest, Read_RapidSeason)
{
std::shared_ptr<int> obj(new int(5));
TestRead<season::RapidJSONTree, decltype(obj)>(obj, "{d:5}");
}
TEST(SharedPtrTest, Read_BoostSeason)
{
std::shared_ptr<int> obj(new int(5));
TestRead<season::BoostTree, decltype(obj)>(obj, "{d:5}");
} | [
"gaspardpetit@gmail.com"
] | gaspardpetit@gmail.com |
2b505755538b480e37100df5c15bd01b47792e78 | addb0fe0a1098370e4a23284a58bb3e068082dc1 | /arduino/all the sketchs of my life/0sony/DNTV_RBS/RBS_RACK_UNO_2/Polycom.ino | 88ffd70739ba0e2a302f3fa53bc9074759426e5a | [] | no_license | fribari/things-api | e2c4a6905492b4b5d79af2eceff6ec995b59e91d | 1426ac8bb877c3a668b7bd7c059e699c5b2b77a4 | refs/heads/master | 2020-07-04T10:55:12.415534 | 2015-04-13T03:12:09 | 2015-04-13T03:12:09 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 452 | ino |
/*char* polycom_write(char* args) {
//Serial.println("Iniciando comunicao com Polycom");
//Serial1.begin(19200);
int codigo = atoi(args);
if(codigo==1) {
//Serial1.println("camera near 2");
}
else if(codigo==2) {
//Serial1.print("reboot\r\n");
}
}
char* polycom_read() {
char* r="\0";
Serial.println("Recebendo REsposta");
while(Serial1.available()) {
Serial.print((char) Serial1.read(),DEC);
}
}
*/
| [
"vinicius@globalcode.com.br"
] | vinicius@globalcode.com.br |
2062edfb952daedfe51ff1ab94be70c78bcfa77b | 45e6e2518fd69d4cd0aece10b15316d094637f90 | /src/smart/core/ShaderInterface.h | 643bbc1250f1e64a7d1f650edf1c165e79635388 | [] | no_license | elrinor/smart-rt | 34c8346d2165faecfaf97f8282310fc52d694ea5 | 241fdacc6cd2fd68cc1e095154eeeecc44190323 | refs/heads/master | 2021-05-29T12:09:00.209001 | 2015-08-04T17:49:12 | 2015-08-04T17:49:12 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,307 | h | #ifndef __SMART_SHADERINTERFACE_H__
#define __SMART_SHADERINTERFACE_H__
#include "common.h"
#include "Radiance.h"
#include "Ray.h"
#include "ShaderRegistrator.h"
namespace smart {
class TraceContext;
// -------------------------------------------------------------------------- //
// SurfaceShader
// -------------------------------------------------------------------------- //
/** Interface for surface shaders. */
class SurfaceShader {
public:
typedef void TriangleParam;
typedef void AttribParam;
void shade(TraceContext& ctx) const;
bool transparency(TraceContext& ctx) const;
void registerParams(const ShaderRegistrator& registrator) const;
};
// -------------------------------------------------------------------------- //
// EnvShader
// -------------------------------------------------------------------------- //
class EnvShader {
public:
void shade(TraceContext& ctx) const;
void registerParams(const ShaderRegistrator& registrator) const;
};
// -------------------------------------------------------------------------- //
// LightShader
// -------------------------------------------------------------------------- //
class LightShader {
public:
/* TODO: remove distance. */
bool illuminate(const Vector3f& position, Vector3f& direction, float& distance, Radiance& radiance) const;
void registerParams(const ShaderRegistrator& registrator) const;
};
// -------------------------------------------------------------------------- //
// CameraShader
// -------------------------------------------------------------------------- //
/** Interface for camera shaders. */
class CameraShader {
public:
/** This function requests a ray from a camera shader corresponding to
* (x, y) position on a virtual screen. Note that x and y are always in
* range [0, 1]. When rendering, (0, 0) coordinate of a virtual screen
* corresponds to the lower left corner of an image.
*
* The returned ray must be normalized. */
void initPrimaryRay(float x, float y, TraceContext& ctx) const;
void registerParams(const ShaderRegistrator& registrator) const;
};
} // namespace smart
#endif // __SMART_SHADERINTERFACE_H__
| [
"ru.elric@localhost"
] | ru.elric@localhost |
7eb10eb90e990102dc03b141beda5893ad3ff0ed | 1bdc1437459c5155f28d9b45702040564f72598f | /MainFrm.cpp | 3de39357219505464f336ecbe6bada8eb04ab690 | [] | no_license | ParsianRoboticLab/Simurosot11 | 10540096b140545d7aa4880da0b4ff712f66a64b | 6def80abb042d068ddd00ad26c9bc9cc40601ee6 | refs/heads/master | 2020-06-18T17:48:15.057400 | 2019-07-18T07:50:41 | 2019-07-18T07:50:41 | 196,388,066 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,578 | cpp | // MainFrm.cpp : implementation of the CMainFrame class
//
#include "stdafx.h"
#include "MicroClient.h"
#include "MainFrm.h"
#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif
/////////////////////////////////////////////////////////////////////////////
// CMainFrame
IMPLEMENT_DYNCREATE(CMainFrame, CFrameWnd
)
BEGIN_MESSAGE_MAP(CMainFrame, CFrameWnd
)
//{{AFX_MSG_MAP(CMainFrame)
// NOTE - the ClassWizard will add and remove mapping macros here.
// DO NOT EDIT what you see in these blocks of generated code !
ON_WM_CREATE()
//}}AFX_MSG_MAP
END_MESSAGE_MAP()
static UINT indicators[] =
{
ID_SEPARATOR, // status line indicator
ID_INDICATOR_CAPS,
ID_INDICATOR_NUM,
ID_INDICATOR_SCRL,
};
/////////////////////////////////////////////////////////////////////////////
// CMainFrame construction/destruction
CMainFrame::CMainFrame() {
// TODO: add member initialization code here
}
CMainFrame::~CMainFrame() {
}
int CMainFrame::OnCreate(LPCREATESTRUCT lpCreateStruct) {
if (CFrameWnd::OnCreate(lpCreateStruct) == -1)
return -1;
if (!m_wndToolBar.CreateEx(this, TBSTYLE_FLAT, WS_CHILD | WS_VISIBLE | CBRS_TOP
| CBRS_GRIPPER | CBRS_TOOLTIPS | CBRS_FLYBY | CBRS_SIZE_DYNAMIC) ||
!m_wndToolBar.LoadToolBar(IDR_MAINFRAME)) {
TRACE0("Failed to create toolbar\n");
return -1; // fail to create
}
/* if (!m_wndStatusBar.Create(this) ||
!m_wndStatusBar.SetIndicators(indicators,
sizeof(indicators)/sizeof(UINT)))
{
TRACE0("Failed to create status bar\n");
return -1; // fail to create
}*/
// TODO: Delete these three lines if you don't want the toolbar to
// be dockable
m_wndToolBar.EnableDocking(CBRS_ALIGN_ANY);
EnableDocking(CBRS_ALIGN_ANY);
DockControlBar(&m_wndToolBar);
return 0;
}
BOOL CMainFrame::PreCreateWindow(CREATESTRUCT &cs) {
if (!CFrameWnd::PreCreateWindow(cs))
return FALSE;
// TODO: Modify the Window class or styles here by modifying
// the CREATESTRUCT cs
return TRUE;
}
/////////////////////////////////////////////////////////////////////////////
// CMainFrame diagnostics
#ifdef _DEBUG
void CMainFrame::AssertValid() const
{
CFrameWnd::AssertValid();
}
void CMainFrame::Dump(CDumpContext& dc) const
{
CFrameWnd::Dump(dc);
}
#endif //_DEBUG
/////////////////////////////////////////////////////////////////////////////
// CMainFrame message handlers
| [
"mohammadmahdi76@Gmail.com"
] | mohammadmahdi76@Gmail.com |
ec3edcb6ee55fc6cd5a2c1dad4bde57c82260394 | db6f3e6486ad8367c62163a4f124da185a64ab5d | /include/retdec/ctypes/typedefed_type.h | a1399d30cb07a6e31f8af355930259f042869482 | [
"MIT",
"Zlib",
"JSON",
"LicenseRef-scancode-unknown-license-reference",
"MPL-2.0",
"BSD-3-Clause",
"GPL-2.0-only",
"NCSA",
"WTFPL",
"BSL-1.0",
"LicenseRef-scancode-proprietary-license",
"Apache-2.0"
] | permissive | avast/retdec | c199854e06454a0e41f5af046ba6f5b9bfaaa4b4 | b9791c884ad8f5b1c1c7f85c88301316010bc6f2 | refs/heads/master | 2023-08-31T16:03:49.626430 | 2023-08-07T08:15:07 | 2023-08-14T14:09:09 | 113,967,646 | 3,111 | 483 | MIT | 2023-08-17T05:02:35 | 2017-12-12T09:04:24 | C++ | UTF-8 | C++ | false | false | 1,169 | h | /**
* @file include/retdec/ctypes/typedefed_type.h
* @brief A representation of typedefed types.
* @copyright (c) 2017 Avast Software, licensed under the MIT license
*/
#ifndef RETDEC_CTYPES_TYPEDEFED_TYPE_H
#define RETDEC_CTYPES_TYPEDEFED_TYPE_H
#include <memory>
#include <string>
#include "retdec/ctypes/type.h"
namespace retdec {
namespace ctypes {
class Context;
/**
* @brief A representation of typedefed types.
*/
class TypedefedType: public Type
{
public:
static std::shared_ptr<TypedefedType> create(
const std::shared_ptr<Context> &context,
const std::string &name,
const std::shared_ptr<Type> &aliasedType
);
std::shared_ptr<Type> getAliasedType() const;
std::shared_ptr<Type> getRealType() const;
virtual bool isTypedef() const override;
/// @name Visitor interface.
/// @{
virtual void accept(Visitor *v) override;
/// @}
private:
// Instances are created by static method create().
TypedefedType(const std::string &name,
const std::shared_ptr<Type> &aliasedType);
private:
/// Type that this typedef stands for.
std::shared_ptr<Type> aliasedType;
};
} // namespace ctypes
} // namespace retdec
#endif
| [
"peter.matula@avast.com"
] | peter.matula@avast.com |
91ce704afd8dc844440c4dbb5e82eed9e4aff8b1 | 6da5140e9595582c2ab10f3a7def25115912973c | /03/02.menu/Demo.01/CBmpMenu.h | 9b4be9ab3601f62ea2d2e324cd822607df89871c | [] | no_license | s1040486/xiaohui | 6df6064bb0d1e858429375b45418e4f2d234d1a3 | 233b6dfbda130d021b8d91ae6a3736ecc0f9f936 | refs/heads/master | 2022-01-12T07:10:57.181009 | 2019-06-01T04:02:16 | 2019-06-01T04:02:16 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 8,358 | h | //********************************************************
//
// FILENAME : CBmpMenu.h
// CONTENTS : CBmpMenu class header file.
//
// Copyright(c), 1999-2000.
// All rights reserved
//
// Author : Dipti Deogade
//
//***************************************************************************************
//** REVISION LIST **********************************************************************
//
// Number Date Author Description
//
//
//***************************************************************************************
#if !defined(AFX_CBMPMENU_H__53F51970_5150_11D3_AB49_0004AC25CC15__INCLUDED_)
#define AFX_CBMPMENU_H__53F51970_5150_11D3_AB49_0004AC25CC15__INCLUDED_
#if _MSC_VER > 1000
#pragma once
#endif // _MSC_VER > 1000
//Internal user defined messages
#define WM_LBUTTONDOWNAFTER WM_USER + 101
#define WM_RESETDATA WM_USER + 102
#define WM_POPUPSUBMENU WM_USER + 103
//Global contants
#define MENU_SELECTFIRSTITEM 0x0100
#define OBM_CHECK 32760 //OEM bitmap id for checkmark...taken from winuser.h
//***************************************************************************************
// The CBmpMenu class provides a way to create popup menus with vertical bitmap
//(like windows start bitmap). Also an user can show a child controls by the
//side of menu items. CBmpMenu window provides a placeholder window for child controls.
//The menu behavior is implemented using a toolbar window, of type MenuToolBar class.
//
//In order to use CBmpMenu class, user needs to use the functions implemented by CMenu for
//showing a popup menu. All the Microsoft documentation for popup menus applies to CBmpMenu class.
//Only the deviations from that documentation are described below:-
//
// 1) An additional constructor has been implemented to pass on the vertical
// bitmap handle, bitmap width etc.
//
// CBmpMenu(int nBitmapW=0, BOOL bShowBmp4SubMenu=FALSE, HBITMAP hBitmap=0, BOOL bStretchBmp=TRUE);
// nBitmapW = Width of the blank space to be shown to the left side of menu items in a popup menu.
// bShowBmp4SubMenu = If TRUE, then blank space is shown for all submenus of a popup menu
// If FALSE, then blank space is shown only for main menu.
// hBitmap = If a valid handle is passed then this bitmap is drawn on the blank space
// bStretchBmp = If TRUE, then bitmap is drawn using StretchBlt.
// If False, then the blank space is filled with pattern brush created from the bitmap
//
// 2) The parameters passed in the message WM_ENTERMENULOOP, to the owner window of the
// menu has been changed.
//
// WM_ENTERMENULOOP:
// wParam = (HMENU)hMenu; //handle of menu which is entering the modal loop
// lParam = (HEND)hWindow; //handle of menu window(menu window is of type CBmpMenu)
//
// Remarks:
// If user wants to show a child control e.g. slider control to the left side of the control,
// then he needs to handle WM_ENTERMENULOOP in the owner window of the menu. Create child
// control with hWindow as parent and place them in the menu window using MoveWindow. User should
// take care that control is placed only in the blank space. Otherwise, it may not draw properly.
//
//***************************************************************************************
/////////////////////////////////////////////////////////////////////////////
// MenuToolBar window
class MenuToolBar : public CToolBar
{
private:
int m_nSelectedItem; //Index of the hot item
int m_nLastLBDownIndex; //Index of the button for which left mouse click event was last processed
CFont m_oMenuFont; //Stores the menu font
CPoint m_oHoverPt; //Stores the last point in the client area of toolbar window, for which WM_MOSEHOVER was created
int m_nLastHoverIndex; //Index of the button for which WM_MOUSEHOVE message was last created
// Construction
public:
MenuToolBar(); //default constructor
// Attributes
public:
// Operations
public:
// Overrides
// ClassWizard generated virtual function overrides
//{{AFX_VIRTUAL(MenuToolBar)
protected:
virtual LRESULT DefWindowProc(UINT message, WPARAM wParam, LPARAM lParam);
//}}AFX_VIRTUAL
// Implementation
public:
virtual ~MenuToolBar();
// Generated message map functions
protected:
//{{AFX_MSG(MenuToolBar)
afx_msg int OnCreate(LPCREATESTRUCT lpCreateStruct);
afx_msg void OnLButtonDown(UINT nFlags, CPoint point);
afx_msg void OnKeyDown(UINT nChar, UINT nRepCnt, UINT nFlags) ;
afx_msg void OnChar(UINT nChar, UINT nRepCnt, UINT nFlags);
afx_msg void OnCustomDrawNotify(LPARAM lParam, LRESULT* pResult ); //NM_CUSTOMDRAW handler
afx_msg void OnMouseMove(UINT nFlags, CPoint point);
//}}AFX_MSG
void OnPostLbuttonMsg(UINT nFlags, LPARAM point); //Called from OnLbuttonDown using PostMessage
BOOL KeyboardFilter(UINT nChar, UINT nRepCnt, UINT nFlags) ; //Helper function used by OnKeyDown
BOOL Draw3DCheckmark(CDC& dc, const CRect rc, BOOL bSelected, HBITMAP hbmCheck,
BOOL bDrawSunkenBdr, BOOL bGrayImage); //Helper function used by OnCustomDrawNotify
//to draw image in checked menu item
DECLARE_MESSAGE_MAP()
};
/////////////////////////////////////////////////////////////////////////////
// CBmpMenu window
class CBmpMenu : public CWnd, public CMenu
{
DECLARE_DYNAMIC(CBmpMenu);
// Construction
public:
//Constructor
CBmpMenu(int nBitmapW=0, BOOL bShowBmp4SubMenu=FALSE, HBITMAP hBitmap=0, BOOL bStretchBmp=TRUE);
//CMenu overridables
BOOL TrackPopupMenu( UINT nFlags, int x, int y, CWnd* pWnd, CRect* pMenuItemRect=NULL);
void operator delete( void* p ){ delete(p);};
// Attributes
public:
CWnd* m_pOwnerWnd; //pointer to owner window
// Operations
public:
// Overrides
// ClassWizard generated virtual function overrides
//{{AFX_VIRTUAL(CBmpMenu)
public:
virtual BOOL DestroyWindow();
protected:
virtual LRESULT DefWindowProc(UINT message, WPARAM wParam, LPARAM lParam);
virtual BOOL PreCreateWindow(CREATESTRUCT& cs);
//}}AFX_VIRTUAL
public:
// Implementation
virtual ~CBmpMenu();
BOOL Attach( HMENU hMenu );
HMENU Detach();
void DestroyRootMenu(); //Destroys all the menu windows starting from root menu window
void DestroySubMenus(); //Destroys all submenu windows of this menu window
// Generated message map functions
protected:
void InitToolBarData(CToolBar* pToolBar, CPoint pt, CRect* pRect); //Used to initialize toolbar and for menu window placement
void Cleanup(); //deletes allocated memory
//{{AFX_MSG(CBmpMenu)
afx_msg void OnKeyDown(UINT nChar, UINT nRepCnt, UINT nFlags);
afx_msg void OnPaint();
//}}AFX_MSG
void PopupSubMenu(WPARAM wp, BOOL bSelectFirstItem);
//pops up submenu at point CPoint(LOWORD(wp), HIWORD(wp)).
//If bSelectFirstItem is TRUE then the first item in the submenu is shown as a hot item.
DECLARE_MESSAGE_MAP()
private:
void PositionMenuWindow(CPoint pt, CRect* pItemRect, CRect rect); //Main menu window placement procedure
BOOL PositionSubMenu(CPoint pt, CRect menuRect, BOOL bRtAlign, BOOL bDnAlign); //submenu window placement procedure
CBmpMenu* m_pSubMenuWnd; //pointer to submenu window
HBITMAP m_hBitmap; //handle of vertical bitmap
BOOL m_bShowBmpAll; //Flag which indicates whether leave a vertical blank space for all submenus or not
BOOL m_bStretchBmp; //Flag indicating whether to use StretchBlt or PatBlt for filling up blank space
int m_nTBOffSet; //Width of blank space to be shown to left side of menu items
BOOL m_bSubMenu; //Flag indicating whether this menu is a submenu or not
MenuToolBar* m_pToolbar; //pointer to the toolbar window
};
/////////////////////////////////////////////////////////////////////////////
HBITMAP GetSysColorBitmap(HDC hDC, HBITMAP hSourceBitmap, BOOL bMono, BOOL bSelected);
//returns a bitmap with changed background colours of the image passed in hSourceBitmap
/////////////////////////////////////////////////////////////////////////////
//{{AFX_INSERT_LOCATION}}
// Microsoft Visual C++ will insert additional declarations immediately before the previous line.
#endif // !defined(AFX_CBMPMENU_H__53F51970_5150_11D3_AB49_0004AC25CC15__INCLUDED_)
| [
"haihai107@126.com"
] | haihai107@126.com |
e573a53ec223b54da78ce7aa8770a47201b65a24 | 293f1095803ea5031e9719d28c0fcefe9008473a | /Games/Koala/koala/Classes/Agents/Item.h | 6f4f4711b4eef58f40c33eea089b475524ebae1c | [] | no_license | Avnerus/ichigo | 23e24f547dde5d1bd158db7871a07a3f7679d4bb | 849c507bfca8989685f9fc64ac06f68bc5ce0576 | refs/heads/master | 2021-01-13T14:37:06.784739 | 2015-10-03T17:22:19 | 2015-10-03T17:22:19 | 43,607,246 | 1 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 517 | h | #ifndef __KOALA_ITEM_H__
#define __KOALA_ITEM_H__
#include "Agent.h"
namespace koala
{
class Item : public ichigo::Agent
{
public:
Item();
virtual ~Item();
virtual void deserialize(Json::Value &agentConfig);
virtual void setDescription(const std::string &desc);
virtual std::string getDescription();
protected:
std::string _description;
};
}
#endif // __KOALA_ITEM_H__
| [
"avnerus@gmail.com"
] | avnerus@gmail.com |
dc0366f04fd73224293461ada7a6bc6d6dc83b60 | 6ce5456f3a7e435e1b5914c8c208e3f3973537a6 | /Core/Rendering/Film.h | a8804cbaa0dce46d70bc4ee1a8719d0bf747615a | [] | no_license | derkaczda-forks/Raytracer | ee6786d1eb424a67c83d3590b39f6eb606d9bacd | 5d0b90edf13a69d9bcc1ae18f7df66caa985d7b9 | refs/heads/master | 2020-05-20T05:15:04.581375 | 2019-04-10T21:58:02 | 2019-04-10T21:58:02 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 757 | h | #pragma once
#include "../RayLib.h"
#include "../Math/Vector4.h"
namespace rt {
class Bitmap;
namespace math {
class Random;
} // namespace math
class Film
{
public:
Film(Bitmap& sum, Bitmap* secondarySum = nullptr);
RT_FORCE_INLINE Uint32 GetWidth() const
{
return mWidth;
}
RT_FORCE_INLINE Uint32 GetHeight() const
{
return mHeight;
}
void AccumulateColor(const math::Vector4& pos, const math::Vector4& sampleColor, math::Random& randomGenerator);
void AccumulateColor(const Uint32 x, const Uint32 y, const math::Vector4& sampleColor);
private:
math::Vector4 mFilmSize;
Bitmap& mSum;
Bitmap* mSecondarySum;
const Uint32 mWidth;
const Uint32 mHeight;
};
} // namespace rt
| [
"witek902@gmail.com"
] | witek902@gmail.com |
c57a5deedd0484fd70d1fdc73415a72ce242a563 | a8a3606a7f4e6e5dc6218b820e6b7bcd1a065cc3 | /Broker/src/device/types/CDeviceDrer.cpp | cc290502b6ea99cc8642b1a67e4d8177c8dce565 | [] | no_license | mstanovich/FREEDM | f585a9a5804b28b2f0c84e3923f3cb58abc2c6fb | 4c7e986f9c3601c2cc6d7817cf83400e756113dc | refs/heads/master | 2021-01-17T10:19:30.574548 | 2012-08-28T19:50:08 | 2012-08-29T20:50:28 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,321 | cpp | ////////////////////////////////////////////////////////////////////////////////
/// @file CDeviceDrer.cpp
///
/// @author Michael Catanzaro <michael.catanzaro@mst.edu>
///
/// @project FREEDM DGI
///
/// @description
/// Represents a distributed energy storage device.
///
/// @copyright
/// These source code files were created at Missouri University of Science
/// and Technology, and are intended for use in teaching or research. They
/// may be freely copied, modified, and redistributed as long as modified
/// versions are clearly marked as such and this notice is not removed.
/// Neither the authors nor Missouri S&T make any warranty, express or
/// implied, nor assume any legal responsibility for the accuracy,
/// completeness, or usefulness of these files or any information
/// distributed with these files.
///
/// Suggested modifications or questions about these files can be directed
/// to Dr. Bruce McMillin, Department of Computer Science, Missouri
/// University of Science and Technology, Rolla, MO 65409 <ff@mst.edu>.
////////////////////////////////////////////////////////////////////////////////
#include "CLogger.hpp"
#include "device/types/CDeviceDrer.hpp"
namespace freedm {
namespace broker {
namespace device {
namespace {
/// This file's logger.
CLocalLogger Logger(__FILE__);
}
////////////////////////////////////////////////////////////////////////////////
/// CDeviceDrer::CDeviceDrer(Identifier, IPhysicalAdapter::AdapterPtr)
///
/// @description Instantiates a device.
///
/// @param device The unique device identifier for the device.
/// @param adapter The adapter that implements operations for this device.
////////////////////////////////////////////////////////////////////////////////
CDeviceDrer::CDeviceDrer(const Identifier device,
IPhysicalAdapter::Pointer adapter)
: IDevice(device, adapter)
{
Logger.Trace << __PRETTY_FUNCTION__ << std::endl;
}
////////////////////////////////////////////////////////////////////////////////
/// CDeviceDrer::~CDeviceDrer()
///
/// @description Virtual destructor for derived classes.
////////////////////////////////////////////////////////////////////////////////
CDeviceDrer::~CDeviceDrer()
{
Logger.Trace << __PRETTY_FUNCTION__ << std::endl;
}
////////////////////////////////////////////////////////////////////////////////
/// CDeviceDrer::GetGeneration() const
///
/// @description Determines the energy generation of this DRER.
///
/// @return The energy generation of this DRER.
////////////////////////////////////////////////////////////////////////////////
SettingValue CDeviceDrer::GetGeneration() const
{
Logger.Trace << __PRETTY_FUNCTION__ << std::endl;
return Get("generation");
}
////////////////////////////////////////////////////////////////////////////////
/// CDeviceDrer::StepGeneration(const SettingValue)
///
/// @description Increases the energy generation of this DRER by step.
///
/// @pre None.
/// @post The energy generation has been increased by step.
////////////////////////////////////////////////////////////////////////////////
void CDeviceDrer::StepGeneration(const SettingValue step)
{
Logger.Trace << __PRETTY_FUNCTION__ << std::endl;
Set("generation", GetGeneration() + step);
}
}
}
}
| [
"michael.catanzaro@mst.edu"
] | michael.catanzaro@mst.edu |
a56bdef362df8837d037d8b4f92dbc768a1cfb60 | 7c187350a4f6ecac9651fa0bb41ce75ef683b308 | /AEngine/src/Rendering/SceneGraph.cpp | 60d58918f0cdc3b44c07495592126db6e57722b3 | [
"Unlicense"
] | permissive | Garciaj007/AEngine | 263040f5bf9bf0a78cf9e08d4e09e7e7bf177e4a | 1a64fc116efab3864b7c535bc8bd03e8aab4bb61 | refs/heads/master | 2020-07-21T14:01:56.884163 | 2020-02-18T05:30:39 | 2020-02-18T05:30:39 | 206,889,293 | 0 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 1,945 | cpp | #include <Core/AEpch.h>
#include "SceneGraph.h"
#include "Graphics/Model.h"
#include "GameObject.h"
#include "Physics/CollisionHandler.h"
std::unique_ptr<SceneGraph> SceneGraph::instance(nullptr);
std::map<GLuint, std::vector<Model*>> SceneGraph::shaderModels = std::map<GLuint, std::vector<Model*>>();
std::map<std::string, std::unique_ptr<GameObject>> SceneGraph::gameObjects = std::map<std::string, std::unique_ptr<GameObject>>();
SceneGraph* SceneGraph::GetInstance()
{
if(!instance) instance = std::unique_ptr<SceneGraph>(new SceneGraph());
return instance.get();
}
SceneGraph::~SceneGraph()
{}
void SceneGraph::AddModel(Model* modelComponent)
{
const auto shaderProgram = modelComponent->GetShaderProgram();
auto it = shaderModels.find(shaderProgram);
if(it != shaderModels.end())
it->second.push_back(modelComponent);
shaderModels.emplace(std::make_pair(shaderProgram, std::vector<Model*>()));
shaderModels[shaderProgram].push_back(modelComponent);
}
void SceneGraph::AddGameObject(GameObject* gameObjectPtr, std::string name)
{
if(gameObjects.find(name) != gameObjects.end()) return;
if(name.empty()) name = "GameObject_" + gameObjects.size();
gameObjects.emplace(std::make_pair(name, std::unique_ptr<GameObject>(gameObjectPtr)));
CollisionHandler::GetInstance()->AddGameObject(gameObjectPtr);
}
GameObject* SceneGraph::GetGameObjects(const std::string name)
{
const auto it = gameObjects.find(name);
if(it != gameObjects.end())
return it->second.get();
return nullptr;
}
void SceneGraph::Update(const float dt)
{
for(auto it = gameObjects.begin(); it != gameObjects.end(); ++it)
it->second->Update(dt);
}
void SceneGraph::Render()
{
CollisionHandler::GetInstance()->Render();
for(const auto shaderModel : shaderModels)
{
glUseProgram(shaderModel.first);
for(auto model : shaderModel.second)
model->Render();
}
}
void SceneGraph::Destroy() const
{
gameObjects.clear();
shaderModels.clear();
} | [
"jurielgarcia2010@gmail.com"
] | jurielgarcia2010@gmail.com |
5157b187d5b4573ec67f9d3b6f42ab4492ffef94 | 37c7f376a71809853ede5ee1d1154fb95fbb4471 | /Util/catter.h | 322f6a2f0887d1a07f1c801f10380562fbd9e2ad | [] | no_license | VishalAgarwal/compilerLab2 | 7892ca7da1ce6c96c1855c1ae82d2f9abe6ffc60 | 8edcd1b9d1bcb14bacd0e5781a0b423963daaf2a | refs/heads/master | 2021-01-15T10:18:02.159644 | 2015-03-12T05:29:23 | 2015-03-12T05:29:23 | 29,586,496 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 676 | h | #define PRINT_TOKEN false
class cat
{
public:
static void token(std::string message)
{
if(PRINT_TOKEN)
{
std::cout << "[TOKEN]: " << message << std::endl;
}
}
static std::string symtabtype(int index)
{
std::string symTabTypeInfo[] = {"INT", "FLOAT", "VOID", "CHAR", "ARRAY", "POINTER"};
return symTabTypeInfo[index];
}
static std::string symtabdecltype(int index)
{
std::string symTabDeclTypeInfo[] = {"GLOBAL","LOCAL","PARAM"};
return symTabDeclTypeInfo[index];
}
};
| [
"devdeepray@gmail.com"
] | devdeepray@gmail.com |
ec91b97637a25ae420475329e7607a9c6598ce90 | 9faf88d491040e3318a7c51cf57d9952a8416baa | /trabalho5/tipoinfo.h | fefb5db19d317b721834257ff1cff4c7052c3040 | [] | no_license | cabelotaina/estruturadedados | c1ebee483060da33ed36a8441716d4c7398aa78b | d0286b53ff2ab65b8cf4cdd8bde95970299f445b | refs/heads/master | 2016-09-03T07:22:06.715181 | 2012-12-04T17:03:02 | 2012-12-04T17:03:02 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 294 | h | #ifndef _TIPO_INFO_
#define _TIPO_INFO_
#include <string>
using namespace std;
class TipoInfo{
public:
TipoInfo();
~TipoInfo();
int telefone;
string nome;
bool maior(TipoInfo *dado);
bool menor(TipoInfo *dado);
bool igual(TipoInfo *dado);
};
#endif
| [
"cabelotaina@gmail.com"
] | cabelotaina@gmail.com |
b07aa567b78733944e700c9d79c4ab43b167ecca | b12656decebd74c0f8d69014df6be160767114d9 | /src/graphics/shader_attribute.h | a939b0f1a78f652ecd6333c781d818ba85a496f6 | [] | no_license | RikoOphorst/battleships | 7385231fc455962a63a3001fa075966642f260a6 | fafc61b66cadacf2ab3917c7f75de7f54988706d | refs/heads/master | 2021-01-20T22:05:19.434232 | 2017-08-29T20:19:17 | 2017-08-29T20:19:17 | 101,797,753 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,513 | h | #pragma once
#include "../graphics/opengl.h"
#include <iostream>
#include <map>
#include <string>
namespace igad
{
class Shader;
/**
* @class igad::ShaderAttribute
* @author Riko Ophorst
* @brief Represents a shader attribute (i.e. per vertex data)
*/
class ShaderAttribute
{
public:
/**
* @brief Creates an invalid shader attribute
*/
ShaderAttribute();
/**
* @brief Creates a shader attribute representation
* @param[in] shader (Shader*) the shader the attribute is attached to
* @param[in] name (const std::string&) the name of the attribute in the shader
* @param[in] type (GLenum) the type of the attribute
* @param[in] location (GLint) the location of the attribute in memory
*/
ShaderAttribute(Shader* shader, const std::string& name, GLenum type, GLint location);
/**
* @brief Default ShaderAttribute destructor
*/
~ShaderAttribute();
/**
* @brief Resets the shader attributes so that it now represents a new attribute
* @param[in] shader (Shader*) the shader the attribute is attached to
* @param[in] name (const std::string&) the name of the attribute in the shader
* @param[in] type (GLenum) the type of the attribute
* @param[in] location (GLint) the location of the attribute in memory
*/
void Reset(Shader* shader, const std::string& name, GLenum type, GLint location);
/**
* @brief Invalidates the shader attributes, meaning it can no longer the attribute it's representing
*/
void Invalidate();
/**
* @brief Sets the attribute pointer
* @param[in] size (GLint) the size of the memory in bytes the new pointer points to
*/
void SetAttributePointer(GLint size, GLenum type, GLboolean normalized, GLsizei stride, const GLvoid* pointer);
/**
* @brief Disables the attribute pointer
*/
void DisableAttributePointer();
/**
* @brief Is this attribute valid?
* @note Usually, if this returns false, it means the attribute is not present in the attached shader.
*/
bool IsValid() const;
/**
* @brief Returns the type of the attribute this is representing
*/
GLenum GetType() const;
/**
* @brief Returns the location of the attribute this is representing
*/
GLint GetLocation() const;
private:
Shader* shader_; //<! the shader this attribute belongs to
std::string name_; //<! the name of the attribute we are representing
GLenum type_; //<! the type of the attribute we are representing
GLint location_; //<! the location in memory of the attribute we are representing
};
} | [
"riko_ophorst@hotmail.com"
] | riko_ophorst@hotmail.com |
d0bb58993beb6d11d9985e33dc38c1d246cccd7c | c9be9e1fee68ff0ac6b6c92c5ea7c23f8a60af3c | /libipc/rename_fd.h | 163b86aaeecd351163e88713038db2547f68d4fc | [
"ISC"
] | permissive | dtzWill/ipcopter | a924fcca066377ad268e5bb525025961f4ff733f | 8391b2f923acb0e30c1e6cc80248ff1de02a2964 | refs/heads/master | 2020-04-09T23:55:14.385467 | 2015-08-11T02:52:34 | 2015-08-11T03:03:19 | 22,110,954 | 5 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 978 | h | //===-- rename_fd.h ---------------------------------------------*- C++ -*-===//
//
// Slipstream: Automatic Interprocess Communication Optimization
//
// Copyright (c) 2015, Will Dietz <w@wdtz.org>
// This file is distributed under the ISC license, see LICENSE for details.
//
// http://wdtz.org/slipstream
//
//===----------------------------------------------------------------------===//
//
// Helper for moving a file descriptor to somewhere
// that code is unlikely to attempt to attempt to use
// as a target of dup2(), etc.
//
//===----------------------------------------------------------------------===//
#ifndef _RENAME_FD_H_
#define _RENAME_FD_H_
// Attempt to duplicate fd into newfd and close fd,
// effectively 'renaming' fd to newfd.
// newfd will be closed if previously open.
// 'cloexec' indicates whether newfd should
// be set to CLOSE-ON-EXEC or not.
// Returns true on success.
bool rename_fd(int fd, int newfd, bool cloexec);
#endif // _RENAME_FD_H_
| [
"w@wdtz.org"
] | w@wdtz.org |
d8661de2b4edcdf9e3295bbd0b38f79b63504f10 | 953ccb4f0d628795965a6fc1e92f9176eff3625b | /Computer Programming(I)/hw11/1083321-hw11.cpp | f1f645f87446e29831986c6cf8a88110c31a8225 | [] | no_license | ping29065147/YZU-freshman | c532ab65e49eb3a2835a62644b05bdccdf791c62 | 729a9bbf0fafacd3724e3e988b228e364a962d2a | refs/heads/main | 2023-01-14T03:36:34.648553 | 2020-11-16T16:00:50 | 2020-11-16T16:00:50 | 313,335,087 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 11,859 | cpp | #include <iostream>
#include <fstream>
#include <iomanip>
#include <vector>
#include <ctime>
#include <stdlib.h>
#include <string.h>
#include <string>
using namespace::std;
char foods[14][48] = { "",
"Pork XiaoLongBao (12)",
"Steamed Vegetable and Ground Pork Dumplings (8)",
"Steamed Shrimp and Pork Dumplings (8)",
"Steamed Fish Dumplings (8)",
"Steamed Vegetarian Mushroom Dumplings (8)",
"Steamed Shrimp and Pork Shao Mai (12)",
"Pork Buns (5)",
"Vegetable and Ground Pork Buns (5)",
"Red Bean Buns (5)",
"Sesame Buns (5)",
"Taro Buns (5)",
"Vegetarian Mushroom Buns (5)",
"Golden Lava Buns (5)" };
int price[14] = { 0, 220, 176, 216, 200, 200, 432, 225,
225, 200, 200, 225, 250, 225 };
struct Date
{
int year;
int month;
int day;
};
struct Account
{
char email[40]; // used as the account number
char password[20];
char name[12];
char address[80];
char phone[12];
int cart[14]; // Cart[i] is the quantity of food #i in the shopping cart
};
struct Order
{
char orderNumber[12];
char email[40];
Date deliveryDate;
Date arrivalDate;
int quantity[14]; // quantity[i] is the quantity of food #i in the order
};
// input an integer in the range [ begin, end ]
int inputAnInteger(int begin, int end);
// add a new account to the file Accounts.dat
void registration(vector< Account > &accountDetails);
// return true if email belongs to accountDetails
bool exists(char email[], const vector< Account > &accountDetails);
// save all elements in accountDetails to the file Accounts.dat
void saveAllAccounts(const vector< Account > &accountDetails);
// login and call shopping
void login(vector< Account > &accountDetails);
// load all accounts details from the file Accounts.dat
void loadAccountDetails(vector< Account > &accountDetails);
// return true if there exists an account with specified email and password; and
// put the account with specified email and password into account
bool valid(char email[], char password[], Account &account,
const vector< Account > &accountDetails);
// add chosen Foods to the shopping cart
void shopping(Account &account);
// return true if the shopping cart is empty
bool emptyCart(const Account &account);
// display the shopping cart in account
bool displayCart(const Account &account);
// append account in the file Accounts.dat
void saveAccount(const Account &account);
// update the shopping cart in account
void updateCart(Account &account);
// generate a Bill and reset account.cart
void check(Account &account);
// compute the current date
void compCurrentDate(Date ¤tDate);
// open the file Orders.txt and call displayOrderDetails twice
void createOrder(const Account &account, const Order &order);
// write an order to Orders.txt or display it on the output window depending on os
void displayOrderDetails(ostream &os, const Account &account, const Order &order);
int main()
{
vector< Account > accountDetails; // account details for all accounts
cout << "Welcome to DintaiFung Shopping Mall!\n";
srand(static_cast<int>(time(0)));
int choice;
while (true)
{
cout << "\n1 - Registration\n";
cout << "2 - Login\n";
cout << "3 - End\n";
do cout << "\nEnter your choice (1~3): ";
while ((choice = inputAnInteger(1, 3)) == -1);
cout << endl;
switch (choice)
{
case 1:
registration(accountDetails);
break;
case 2:
login(accountDetails);
break;
case 3:
cout << "Thank you! Goodbye!\n\n";
system("pause");
return 0;
}
}
system("pause");
}
int inputAnInteger(int begin, int end)
{
string input;
int trans;
cin >> input;
if (input.size() == 2)
trans = (input[0] - '0') * 10 + (input[1] - '0');
else
trans = (input[0] - '0');
if (trans >= begin && trans <= end)
return trans;
else
return -1;
}
void registration(vector< Account > &accountDetails)
{
Account re;
int a;
cout << "Email address (Account number): ";
cin >> re.email;
if (exists(re.email, accountDetails))
cout << "\nYou are already a member!\n";
else {
cout << "Password: ";
cin >> re.password;
cout << "Name: ";
cin >> re.name;
cout << "Shipping address: ";
cin >> re.address;
cout << "Contact phone number: ";
cin >> re.phone;
for (a = 0; a < 14; a++)
re.cart[a] = 0;
accountDetails.push_back(re);
cout << "\nRegistration Completed!\n";
saveAllAccounts(accountDetails);
}
}
bool exists(char email[], const vector< Account > &accountDetails)
{
int a;
for (a = 0; a < accountDetails.size(); a++) {
if (!(strcmp(email, accountDetails[a].email)))
return true;
}
return false;
}
void saveAllAccounts(const vector< Account > &accountDetails)
{
int a;
ofstream outFile("Accounts.dat", ios::out | ios::binary);
for (a = 0; a < accountDetails.size(); a++) {
outFile.write(reinterpret_cast<const char*> (&(accountDetails[a])), sizeof(Account));
}
outFile.close();
}
void login(vector< Account > &accountDetails)
{
loadAccountDetails(accountDetails);
int a, choice;
char mail[40], pass[20];
bool check = true;
Account current;
while (1) {
cout << "Email address (0 to end): ";
cin >> mail;
if (strlen(mail) == 1 && mail[0] == '0')
return;
cout << "Password: ";
cin >> pass;
cout << endl;
if (valid(mail, pass, current, accountDetails))
break;
else
cout << "Invalid email address or password. Please try again.\n\n";
}
shopping(current);
}
void loadAccountDetails(vector< Account > &accountDetails)
{
ifstream inFile("Accounts.dat", ios::binary | ios::in);
accountDetails.clear();
Account input;
while (inFile.read((char*)&input, sizeof(Account)))
accountDetails.push_back(input);
inFile.close();
}
bool valid(char email[], char password[], Account &account,
const vector< Account > &accountDetails)
{
int a;
for (a = 0; a < accountDetails.size(); a++) {
if (!(strcmp(email, accountDetails[a].email)) && !(strcmp(password, accountDetails[a].password))) {
account = accountDetails[a];
return true;
}
}
return false;
}
void shopping(Account &account)
{
int a, choice, k, q;
for (a = 1; a < 14; a++)
cout << setw(2) << right << a << ". " << setw(50) << left << foods[a] << price[a] << endl;
k = 13;
if (!emptyCart(account)) {
cout << endl << "14. " << "View your shopping cart" << endl;
k = 14;
}
do cout << "\nEnter your choice (0 to logout): ";
while ((choice = inputAnInteger(0, k)) == -1);
if (choice == 0)
return;
else if (choice == 14) {
cout << "Your Shopping Cart Contents:\n\n";
displayCart(account);
}
else {
do cout << "\nEnter the quantity: ";
while ((q = inputAnInteger(0, 1000)) == -1);
cout << endl;
account.cart[choice] += q;
saveAccount(account);
cout << "Your Shopping Cart Contents:\n\n";
displayCart(account);
}
while (true) {
cout << "\n1. Continue Shopping\n";
cout << "2. Update Cart\n";
cout << "3. Check\n";
do cout << "\nEnter your choice (1~3): ";
while ((choice = inputAnInteger(1, 3)) == -1);
cout << endl;
switch (choice)
{
case 1:
shopping(account);
return;
case 2:
updateCart(account);
break;
case 3:
check(account);
return;
}
}
}
bool emptyCart(const Account &account)
{
int a;
for (a = 1; a < 14; a++) {
if (account.cart[a] != 0)
return false;
}
return true;
}
bool displayCart(const Account &account)
{
int a, total = 0;
cout << "Code" << setw(50) << right << "Item" << setw(7) << "Price" << setw(10) << "Quantity" << setw(10) << "Subtotal" << endl;
for (a = 1; a < 14; a++) {
if (account.cart[a] != 0) {
cout << setw(4) << right << a << setw(50) << foods[a] << setw(7) << price[a] << setw(10) << account.cart[a] << setw(10) << price[a] * account.cart[a] << endl;
total += price[a] * account.cart[a];
}
}
cout << "\nTotal Cost: " << total << endl;
return true;
}
void saveAccount(const Account &account)
{
vector<Account> data;
Account input;
int a, b;
ifstream inFile("Accounts.dat", ios::in | ios::binary);
while (inFile.read((char*)&input, sizeof(Account)))
data.push_back(input);
inFile.close();
for (a = 0; a < data.size(); a++) {
if (!strcmp(account.email, data[a].email)) {
for (b = 0; b < 14; b++)
data[a].cart[b] = account.cart[b];
}
}
ofstream outFile("Accounts.dat", ios::out | ios::binary);
for (a = 0; a < data.size(); a++) {
outFile.write(reinterpret_cast<const char*> (&(data[a])), sizeof(Account));
}
outFile.close();
}
void updateCart(Account &account)
{
int code, q;
while (1) {
cout << "Enter the product code: ";
cin >> code;
cout << endl;
if (account.cart[code] != 0)
break;
}
do cout << "\nEnter the quantity: ";
while ((q = inputAnInteger(0, 1000)) == -1);
cout << endl;
account.cart[code] = q;
saveAccount(account);
cout << "Your Shopping Cart Contents:\n\n";
displayCart(account);
}
void check(Account &account)
{
int a;
Order neworder;
strcpy_s(neworder.email, account.email);
cout << "Enter arrival dateDate";
cout << "\nyear: ";
cin >> neworder.arrivalDate.year;
cout << "month: ";
cin >> neworder.arrivalDate.month;
cout << "day: ";
cin >> neworder.arrivalDate.day;
srand(time(NULL));
neworder.orderNumber[0] = (rand() % 26) + 'A';
for (a = 1; a <= 9; a++)
neworder.orderNumber[a] = (rand() % 10) + '0';
compCurrentDate(neworder.deliveryDate);
for (a = 0; a < 14; a++)
neworder.quantity[a] = account.cart[a];
cout << "\n";
createOrder(account, neworder);
cout << "\nAn order has been created.\n";
for (a = 0; a < 14; a++)
account.cart[a] = 0;
saveAccount(account);
}
void compCurrentDate(Date ¤tDate)
{
tm structtime;
time_t rawtime = time(0);
localtime_s(&structtime, &rawtime);
currentDate.year = structtime.tm_year + 1900;
currentDate.month = structtime.tm_mon + 1;
currentDate.day = structtime.tm_mday;
}
void createOrder(const Account &account, const Order &order)
{
ofstream outFile("Orders.txt", ios::app);
outFile.close();
ifstream inFile("Orders.txt", ios::in);
displayOrderDetails(cout, account, order);
displayOrderDetails(outFile, account, order);
inFile.close();
}
void displayOrderDetails(ostream &os, const Account &account, const Order &order)
{
int a, total = 0;
os << "Order number: ";
for (a = 0; a < 10; a++)
os << order.orderNumber[a];
os << "\nDelivery Date: " << order.deliveryDate.year << "/" << order.deliveryDate.month << "/" << order.deliveryDate.day << endl;
os << "\nArrival Date: " << order.arrivalDate.year << "/" << order.arrivalDate.month << "/" << order.arrivalDate.day << endl;
os << "Recipient: " << account.name << endl;
os << "Contact Phone Number: " << account.phone << endl;
os << "Shipping address: " << account.address << endl;
os << "\nShopping details:\n\n";
os << "Code" << setw(50) << right << "Item" << setw(7) << "Price" << setw(10) << "Quantity" << setw(10) << "Subtotal" << endl;
for (a = 1; a < 14; a++) {
if (account.cart[a] != 0) {
os << setw(4) << right << a << setw(50) << foods[a] << setw(7) << price[a] << setw(10) << account.cart[a] << setw(10) << price[a] * account.cart[a] << endl;
total += price[a] * account.cart[a];
}
}
os << "\nTotal Cost: " << total << endl;
}
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head><meta http-equiv="Content-Type" content="text/html; charset=utf-8" /><title>
</title></head>
<body>
<form method="post" action="./File_DownLoad_Wk_zip.aspx?File_name=1083321-hw11.cpp&type=3&id=2838395" id="form1">
<div class="aspNetHidden">
<input type="hidden" name="__VIEWSTATE" id="__VIEWSTATE" value="/wEPDwUKLTEzNDM3NzkxOWRkwneTr34MFXJYUKyKKda+DU4gQVM=" />
</div>
<div class="aspNetHidden">
<input type="hidden" name="__VIEWSTATEGENERATOR" id="__VIEWSTATEGENERATOR" value="629601C3" />
</div>
<div>
</div>
</form>
</body>
</html>
| [
"pinghe.yeh@gmail.com"
] | pinghe.yeh@gmail.com |
35d7af9e9f8144a41f44aecebda6fc6e3718bab8 | e67983d5601a41fdb1e94277276f245d4b38a10a | /MFCApplication1/MFCApplication1/MFCApplication1Dlg.cpp | ecde6a11a1c4deb3f7e58fded31a76b2511e773e | [
"MIT"
] | permissive | makky-star/Chatprogram2 | 9fe24f8d413d97dbb099976e94e459a4d132a1a9 | dfb2c31b07dfbf9721e6eaa52c5daa8144b6459c | refs/heads/main | 2023-06-22T16:01:53.089569 | 2021-07-21T11:56:06 | 2021-07-21T11:56:06 | 388,095,347 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 7,855 | cpp |
// MFCApplication1Dlg.cpp : 実装ファイル
//
#include "pch.h"
#include "framework.h"
#include "MFCApplication1.h"
#include "MFCApplication1Dlg.h"
#include "afxdialogex.h"
#ifdef _DEBUG
#define new DEBUG_NEW
#endif
// アプリケーションのバージョン情報に使われる CAboutDlg ダイアログ
class CAboutDlg : public CDialogEx
{
public:
CAboutDlg();
// ダイアログ データ
#ifdef AFX_DESIGN_TIME
enum { IDD = IDD_ABOUTBOX };
#endif
protected:
virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV サポート
// 実装
protected:
DECLARE_MESSAGE_MAP()
};
CAboutDlg::CAboutDlg() : CDialogEx(IDD_ABOUTBOX)
{
}
void CAboutDlg::DoDataExchange(CDataExchange* pDX)
{
CDialogEx::DoDataExchange(pDX);
}
BEGIN_MESSAGE_MAP(CAboutDlg, CDialogEx)
END_MESSAGE_MAP()
// CMFCApplication1Dlg ダイアログ
CMFCApplication1Dlg::CMFCApplication1Dlg(CWnd* pParent /*=nullptr*/)
: CDialogEx(IDD_MFCAPPLICATION1_DIALOG, pParent)
{
m_hIcon = AfxGetApp()->LoadIcon(IDR_MAINFRAME);
}
void CMFCApplication1Dlg::DoDataExchange(CDataExchange* pDX)
{
CDialogEx::DoDataExchange(pDX);
}
BEGIN_MESSAGE_MAP(CMFCApplication1Dlg, CDialogEx)
ON_WM_SYSCOMMAND()
ON_WM_PAINT()
ON_WM_QUERYDRAGICON()
//ON_NOTIFY(TCN_SELCHANGE, IDC_TAB1, &CMFCApplication1Dlg::OnTcnSelchangeTab1)
ON_BN_CLICKED(IDC_BUTTON1, &CMFCApplication1Dlg::OnBnClickedButton1)
ON_EN_CHANGE(IDC_EDIT1, &CMFCApplication1Dlg::OnEnChangeEdit1)
//ON_LBN_SELCHANGE(IDC_LIST1, &CMFCApplication1Dlg::OnLbnSelchangeList1)
ON_EN_CHANGE(IDC_EDIT2, &CMFCApplication1Dlg::OnEnChangeEdit2)
ON_BN_CLICKED(IDC_RADIO2, &CMFCApplication1Dlg::OnBnClickedRadio2)
ON_EN_CHANGE(IDC_EDIT3, &CMFCApplication1Dlg::OnEnChangeEdit3)
//ON_LBN_SELCHANGE(IDC_LIST2, &CMFCApplication1Dlg::OnLbnSelchangeList2)
//ON_NOTIFY(IPN_FIELDCHANGED, IDC_IPADDRESS1, &CMFCApplication1Dlg::OnIpnFieldchangedIpaddress1)
ON_CBN_SELCHANGE(IDC_COMBO3, &CMFCApplication1Dlg::OnCbnSelchangeCombo3)
ON_BN_CLICKED(IDC_BUTTON2, &CMFCApplication1Dlg::OnBnClickedButton2)
//ON_NOTIFY(TVN_SELCHANGED, IDC_MFCSHELLTREE1, &CMFCApplication1Dlg::OnTvnSelchangedMfcshelltree1)
END_MESSAGE_MAP()
// CMFCApplication1Dlg メッセージ ハンドラー
BOOL CMFCApplication1Dlg::OnInitDialog()
{
CDialogEx::OnInitDialog();
// "バージョン情報..." メニューをシステム メニューに追加します。
// IDM_ABOUTBOX は、システム コマンドの範囲内になければなりません。
ASSERT((IDM_ABOUTBOX & 0xFFF0) == IDM_ABOUTBOX);
ASSERT(IDM_ABOUTBOX < 0xF000);
CMenu* pSysMenu = GetSystemMenu(FALSE);
if (pSysMenu != nullptr)
{
BOOL bNameValid;
CString strAboutMenu;
bNameValid = strAboutMenu.LoadString(IDS_ABOUTBOX);
ASSERT(bNameValid);
if (!strAboutMenu.IsEmpty())
{
pSysMenu->AppendMenu(MF_SEPARATOR);
pSysMenu->AppendMenu(MF_STRING, IDM_ABOUTBOX, strAboutMenu);
}
}
// このダイアログのアイコンを設定します。アプリケーションのメイン ウィンドウがダイアログでない場合、
// Framework は、この設定を自動的に行います。
SetIcon(m_hIcon, TRUE); // 大きいアイコンの設定
SetIcon(m_hIcon, FALSE); // 小さいアイコンの設定
// TODO: 初期化をここに追加します。
return TRUE; // フォーカスをコントロールに設定した場合を除き、TRUE を返します。
}
void CMFCApplication1Dlg::OnSysCommand(UINT nID, LPARAM lParam)
{
if ((nID & 0xFFF0) == IDM_ABOUTBOX)
{
CAboutDlg dlgAbout;
dlgAbout.DoModal();
}
else
{
CDialogEx::OnSysCommand(nID, lParam);
}
}
// ダイアログに最小化ボタンを追加する場合、アイコンを描画するための
// 下のコードが必要です。ドキュメント/ビュー モデルを使う MFC アプリケーションの場合、
// これは、Framework によって自動的に設定されます。
void CMFCApplication1Dlg::OnPaint()
{
if (IsIconic())
{
CPaintDC dc(this); // 描画のデバイス コンテキスト
SendMessage(WM_ICONERASEBKGND, reinterpret_cast<WPARAM>(dc.GetSafeHdc()), 0);
// クライアントの四角形領域内の中央
int cxIcon = GetSystemMetrics(SM_CXICON);
int cyIcon = GetSystemMetrics(SM_CYICON);
CRect rect;
GetClientRect(&rect);
int x = (rect.Width() - cxIcon + 1) / 2;
int y = (rect.Height() - cyIcon + 1) / 2;
// アイコンの描画
dc.DrawIcon(x, y, m_hIcon);
}
else
{
CDialogEx::OnPaint();
}
}
// ユーザーが最小化したウィンドウをドラッグしているときに表示するカーソルを取得するために、
// システムがこの関数を呼び出します。
HCURSOR CMFCApplication1Dlg::OnQueryDragIcon()
{
return static_cast<HCURSOR>(m_hIcon);
}
void CMFCApplication1Dlg::OnTcnSelchangeTab1(NMHDR* pNMHDR, LRESULT* pResult)
{
// TODO: ここにコントロール通知ハンドラー コードを追加します。
*pResult = 0;
}
void CMFCApplication1Dlg::OnBnClickedButton1()
{
// TODO: ここにコントロール通知ハンドラー コードを追加します。
}
void CMFCApplication1Dlg::OnEnChangeEdit1()
{
// TODO: これが RICHEDIT コントロールの場合、このコントロールが
// この通知を送信するには、CDialogEx::OnInitDialog() 関数をオーバーライドし、
// CRichEditCtrl().SetEventMask() を関数し呼び出します。
// OR 状態の ENM_CHANGE フラグをマスクに入れて呼び出す必要があります。
// TODO: ここにコントロール通知ハンドラー コードを追加してください。
}
void CMFCApplication1Dlg::OnLbnSelchangeList1()
{
// TODO: ここにコントロール通知ハンドラー コードを追加します。
}
void CMFCApplication1Dlg::OnEnChangeEdit2()
{
// TODO: これが RICHEDIT コントロールの場合、このコントロールが
// この通知を送信するには、CDialogEx::OnInitDialog() 関数をオーバーライドし、
// CRichEditCtrl().SetEventMask() を関数し呼び出します。
// OR 状態の ENM_CHANGE フラグをマスクに入れて呼び出す必要があります。
// TODO: ここにコントロール通知ハンドラー コードを追加してください。
}
void CMFCApplication1Dlg::OnBnClickedRadio2()
{
// TODO: ここにコントロール通知ハンドラー コードを追加します。
}
void CMFCApplication1Dlg::OnEnChangeEdit3()
{
// TODO: これが RICHEDIT コントロールの場合、このコントロールが
// この通知を送信するには、CDialogEx::OnInitDialog() 関数をオーバーライドし、
// CRichEditCtrl().SetEventMask() を関数し呼び出します。
// OR 状態の ENM_CHANGE フラグをマスクに入れて呼び出す必要があります。
// TODO: ここにコントロール通知ハンドラー コードを追加してください。
}
void CMFCApplication1Dlg::OnLbnSelchangeList2()
{
// TODO: ここにコントロール通知ハンドラー コードを追加します。
}
void CMFCApplication1Dlg::OnIpnFieldchangedIpaddress1(NMHDR* pNMHDR, LRESULT* pResult)
{
LPNMIPADDRESS pIPAddr = reinterpret_cast<LPNMIPADDRESS>(pNMHDR);
// TODO: ここにコントロール通知ハンドラー コードを追加します。
*pResult = 0;
}
void CMFCApplication1Dlg::OnCbnSelchangeCombo3()
{
// TODO: ここにコントロール通知ハンドラー コードを追加します。
}
void CMFCApplication1Dlg::OnBnClickedButton2()
{
// TODO: ここにコントロール通知ハンドラー コードを追加します。
}
void CMFCApplication1Dlg::OnTvnSelchangedMfcshelltree1(NMHDR* pNMHDR, LRESULT* pResult)
{
LPNMTREEVIEW pNMTreeView = reinterpret_cast<LPNMTREEVIEW>(pNMHDR);
// TODO: ここにコントロール通知ハンドラー コードを追加します。
*pResult = 0;
}
| [
"75469056+makky-star@users.noreply.github.com"
] | 75469056+makky-star@users.noreply.github.com |
d2471cd86f1b47f3cbe32c02263ce9b0c2016fa0 | 76e33c5c200d1672a282dc719c3bc369c59befdb | /dp/ugly-number-ii.cpp | 9342aecdb538f4f4aef02d0c2d4e55b3338b6304 | [] | 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 | 394 | cpp | #include "dp.h"
/*
* Write a program to find the n-th ugly number.
Ugly numbers are positive numbers whose prime factors only include 2, 3, 5.
Example:
Input: n = 10
Output: 12
Explanation: 1, 2, 3, 4, 5, 6, 8, 9, 10, 12 is the sequence of the first 10 ugly numbers.
Note:
1 is typically treated as an ugly number.
n does not exceed 1690.
*/
int nthUglyNumber(int n) {
return 0;
} | [
"ozcanay@itu.edu.tr"
] | ozcanay@itu.edu.tr |
7532835f93b5fee2f1c9fffddde8898f0841c932 | cd9d5422bfab6f6e7c573af09a16626d0a738916 | /spring16/282.ExpressionAddOperators.cpp | 8a7ee72c67119bc8b53ed3c9765708a9c6a0627a | [] | no_license | Lingfei-Li/leetcode | dd4bd8365a25ca279b51fc8cc546f44c02c5d7ef | 36bd3b2a9e679c61962e946901f995142b85efaa | refs/heads/master | 2021-01-19T06:58:57.783787 | 2016-06-21T04:37:58 | 2016-06-21T04:37:58 | 59,934,535 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,122 | cpp | // 1.12% slow (good job)
// DFS
// backtracking
#include"mytest.h"
void solve(vector<string>& ans, string& exp, int pos, string& num, long long target, int multiplyflag, long long multiplier) {
int n = num.size();
if(pos == -1) {
if(target == 0) ans.push_back(exp);
return;
}
for(int i = pos; i >= 0; i --) {
if(i != pos && num[i] == '0') continue;
long long tmp = atoi(num.substr(i, pos-i+1).c_str());
long long val = tmp;
if(multiplyflag) val *= multiplier;
if(val < 0) break; //overflow
int oldsz = exp.length();
exp += to_string(tmp);
if(i) exp.push_back('+');
solve(ans, exp, i-1, num, target-val, 0, 0);
exp.resize(oldsz);
if(i) {
exp += to_string(tmp);
exp.push_back('-');
solve(ans, exp, i-1, num, target+val, 0, 0);
exp.resize(oldsz);
exp += to_string(tmp);
exp.push_back('*');
solve(ans, exp, i-1, num, target, 1, val);
exp.resize(oldsz);
}
}
}
int isnum(char c){
return c>='0' && c<='9';
}
vector<string> addOperators(string num, int target) {
vector<string> intermediate;
int n = num.length();
string exp;
solve(intermediate, exp, n-1, num, target, 0, 0);
vector<string> ans;
for(int i = 0; i < intermediate.size(); i ++) {
exp.resize(0);
int j = intermediate[i].length() - 1;
int lastop = j+1;
while(j >= 0) {
while(j >= 0 && isnum(intermediate[i][j])) j--;
exp += intermediate[i].substr(j+1,lastop-j-1);
if(j>0) {
exp += intermediate[i][j];
}
lastop = j;
j--;
}
ans.push_back(exp);
}
return ans;
}
int main() {
srand(time(NULL));
string a;
int b;
while(cin>>a>>b) {
vector<string> ans = addOperators(a, b);
printVector(ans);
}
return 0;
}
| [
"lingfei@macaroni-01.cs.wisc.edu"
] | lingfei@macaroni-01.cs.wisc.edu |
d07122566768b21f41e0b83529f5d3ecac575fa3 | d2ad4024f446060cbd3947a1c8bf90a2f78a9287 | /src_project/Classes/view/Layer/Main/GameController.cpp | 38958ec06bd8d76e9afe8775742df63b0644ddf2 | [] | no_license | qingyin/BJLY.game.cpp_ui.com | d49ce7277d58bb524793e5f66da2ba3ecd93b14a | e5533715f0f1f51e219ef2f9bde21e8cdc2b268b | refs/heads/master | 2021-01-01T18:41:15.645592 | 2017-07-26T10:24:53 | 2017-07-26T10:24:59 | 98,408,784 | 0 | 0 | null | null | null | null | GB18030 | C++ | false | false | 25,366 | cpp | #include "GameController.h"
#include "controller/table/TableCommand.h"
#include "tool/Tools.h"
#include "model/MjData.h"
#include "view/Layer/Tip/TipContent.h"
#include "platform/JniFun.h"
#include "SimpleAudioEngine.h"
#include "Sound/ArmFun.h"
#include "view/Layer/Main/layer_chat.h"
#include "platform/MissionWeiXin.h"
#include "view/Layer/Lobby/LobbyView.h"
void GameController::onEnter()
{
ParentInfo::onEnter();
this->_eventDispatcher->addCustomEventListener("onresultunschedule",CC_CALLBACK_1(GameController::onresult,this));
this->_eventDispatcher->addCustomEventListener("onresultunscheduleQuake",CC_CALLBACK_1(GameController::stopQuake,this));
this->_eventDispatcher->addCustomEventListener("WeiXinShareInGame",CC_CALLBACK_1(GameController::WeiXinShareInGame,this));
schedule(schedule_selector(GameController::refreshberrty),2);
}
void GameController::onExit()
{
this->_eventDispatcher->removeCustomEventListeners("onresultunschedule");
this->_eventDispatcher->removeCustomEventListeners("onresultunscheduleQuake");
this->_eventDispatcher->removeCustomEventListeners("WeiXinShareInGame");
unschedule(schedule_selector(GameController::refreshberrty));
ParentInfo::onExit();
}
void GameController::refreshberrty(float dt)
{
float power = UserDefault::getInstance()->getFloatForKey("level_beterry");
#if CC_TARGET_PLATFORM == CC_PLATFORM_IOS
power = JniFun::getPower();
#endif
LoadingBar *l_be=(LoadingBar *)node_system->getChildByName("LoadingBar_1");
float rate=(power*1.0)/100.0f;
l_be->setPercent(power*1.0f);
Text * tx_baifenbi=(Text *)node_system->getChildByName("Text_174");
String *baifenbi=String::createWithFormat("%0.0lf%%",power);
tx_baifenbi->setString(baifenbi->getCString());
Text *tx_hour=(Text *)node_system->getChildByName("Text_174_0");
Text *tx_min=(Text *)node_system->getChildByName("Text_174_2");
std::vector<int >arr_time=Tools::getcurrentTime();
if(arr_time.size()==2)
{
tx_hour->setString(String::createWithFormat("%d",arr_time[0])->getCString());
if(arr_time[1]<10)
{
tx_min->setString(String::createWithFormat("0%d",arr_time[1])->getCString());
}
else
{
tx_min->setString(String::createWithFormat("%d",arr_time[1])->getCString());
}
}
}
void GameController::onresult(EventCustom* evt)
{
unschedule(schedule_selector(GameController::begintimehjisshiqi));
}
void GameController::stopQuake(EventCustom* evt)
{
unschedule(schedule_selector(GameController::begintimehjisshiqiQuake));
}
bool GameController::init()
{
if(!ParentInfo::init()) return false;
setSwallowTouches(false);
setOpacity(0);
//UI加载并且显示
uiLoadAndShow();
return true;
}
//UI加载并且显示
void GameController::uiLoadAndShow()
{
auto controller = CSLoader::createNode("res/loading/controller.csb") ; //游戏控制层
this->addChild(controller);
//电量
node_system=(Node *)controller->getChildByName("node_system");
//等待其他玩家UI
nodeWait = (Node*)controller->getChildByName("nodeWait");
auto btnExitRoom = (Button*)nodeWait->getChildByName("btnExitRoom");//退出房间
btnExitRoom->addTouchEventListener(CC_CALLBACK_2(GameController::ButtonHandler, this));
auto btnGetFriends = (Button*)nodeWait->getChildByName("btnGetFriends");//微信邀请好友
btnGetFriends->addTouchEventListener(CC_CALLBACK_2(GameController::ButtonHandler, this));
if(MjData::getInstance()->getisinapple()==1)
{
btnGetFriends->setEnabled(false);
btnGetFriends->setVisible(false);
}
auto btnDismiss = (Button*)nodeWait->getChildByName("btnDismiss");//解散房间
btnDismiss->addTouchEventListener(CC_CALLBACK_2(GameController::ButtonHandler, this));
if(GamerData::getInstance()->getSeatId()!=0)
{
btnDismiss->setVisible(false);
btnDismiss->setEnabled(false);
}
else
{
btnDismiss->setVisible(true);
btnDismiss->setEnabled(true);
}
//游戏主体底层
nodeBottom = (Node*)controller->getChildByName("nodeBottom");
auto btnSet = (Button*)nodeBottom->getChildByName("btnSet");//设置
btnSet->addTouchEventListener(CC_CALLBACK_2(GameController::ButtonHandler, this));
auto btnHelp = (Button*)nodeBottom->getChildByName("btnHelp");//帮助
btnHelp->addTouchEventListener(CC_CALLBACK_2(GameController::ButtonHandler, this));
bg_rule=(Sprite *)nodeBottom->getChildByName("bg_rule_zhuomian_1");
bt_go=(Button *)bg_rule->getChildByName("Button_go");
bt_go->setTag(1);
bt_go->addTouchEventListener(CC_CALLBACK_2(GameController::ButtonHandler,this));
Text *tx_id=(Text *)bg_rule->getChildByName("Text_fangjian_0");
tx_id->setText(String::createWithFormat("%d", GamerData::getInstance()->getTableId())->getCString());
Text *tx_jushu=(Text *)bg_rule->getChildByName("Text_fangjian_0_0");
if(MjData::getInstance()->getjushu()==4)
{
tx_jushu->setText(Tools::getChineseByKey("8ju").c_str());
}
else if(MjData::getInstance()->getjushu()==8)
{
tx_jushu->setText(Tools::getChineseByKey("16ju").c_str());
}
Text *tx_zigang=(Text *)bg_rule->getChildByName("Text_fangjian_0_0_0");
if(MjData::getInstance()->getIsgang_men())
{
tx_zigang->setText(Tools::getChineseByKey("zigang").c_str());
}
else
{
tx_zigang->setText(Tools::getChineseByKey("zhuanwan").c_str());
}
Text *tx_genzhuang=(Text *)bg_rule->getChildByName("Text_fangjian_0_0_0_0");
if(MjData::getInstance()->getIsgenZhuang())
{
tx_genzhuang->setText(Tools::getChineseByKey("gen").c_str());
}
else
{
tx_genzhuang->setText(Tools::getChineseByKey("bugen").c_str());
}
std::string rule;
if (MjData::getInstance()->getis258()==1)
{
rule = String::createWithFormat("%s %s",rule.c_str(),Tools::getChineseByKey("with258").c_str())->getCString();
}
if (MjData::getInstance()->getisfeng()==1)
{
rule = String::createWithFormat("%s %s",rule.c_str(),Tools::getChineseByKey("withfeng").c_str())->getCString();
}
if (MjData::getInstance()->getishua()==1)
{
rule = String::createWithFormat("%s %s",rule.c_str(),Tools::getChineseByKey("withhua").c_str())->getCString();
}
if (MjData::getInstance()->getisjiangyise()==1)
{
rule = String::createWithFormat("%s %s",rule.c_str(),Tools::getChineseByKey("withjiangyise").c_str())->getCString();
}
if (MjData::getInstance()->getisqidui()==1)
{
rule = String::createWithFormat("%s %s",rule.c_str(),Tools::getChineseByKey("withqidui").c_str())->getCString();
}
if (MjData::getInstance()->getisminglou()==1)
{
rule = String::createWithFormat("%s %s",rule.c_str(),Tools::getChineseByKey("minglou").c_str())->getCString();
}
auto tipGame = (Text*)nodeBottom->getChildByName("tipGame");//游戏规则提示
tipGame->setText(rule.c_str());
auto idRoom = (Text*)nodeBottom->getChildByName("idRoom"); //房间号
idRoom->setText(String::createWithFormat("%d", GamerData::getInstance()->getTableId())->getCString());
CCLOG("%d",GamerData::getInstance()->getTableId() );
auto powerBar = (LoadingBar*)nodeBottom->getChildByName("powerBar");//设备电量
auto btnChat = (Button*)nodeBottom->getChildByName("btnChat");//聊天
btnChat->addTouchEventListener(CC_CALLBACK_2(GameController::ButtonHandler, this));
//游戏中
nodeGame = (Node*)controller->getChildByName("nodeGame");
// nodeGame->setPositionY(nodeGame->getPositionY()+30);
nodeGame->setVisible(false);
numTime_game = (TextAtlas*)nodeGame->getChildByName("num");
numCards_game = (Text*)((ImageView*)nodeGame->getChildByName("bgShow1"))->getChildByName("texts2");
numJuShu_game = (Text*)((ImageView*)nodeGame->getChildByName("bgShow1"))->getChildByName("texts_0");
bgtime=(ImageView *)nodeGame->getChildByName("bgTime");
for(int i=0;i<4;i++)
{
String *path_arrow=String::createWithFormat("arrow%d",i+1);
Sprite *sp_arrow=(Sprite *)bgtime->getChildByName(path_arrow->getCString());
arr_arrows.push_back(sp_arrow);
sp_arrow->setVisible(false);
sp_arrow->setTag(i);
FadeOut *fo=FadeOut::create(0.5);
FadeIn *fi=FadeIn::create(0.5);
Sequence *se=Sequence::create(fo,fi,NULL);
RepeatForever *re=RepeatForever::create(se);
sp_arrow->runAction(re);
}
Button *bt_luyin=(Button *)nodeBottom->getChildByName("Button_luyin");
bt_luyin->addTouchEventListener(CC_CALLBACK_2(GameController::ButtonHandler, this));
n_luyinanimate=controller->getChildByName("Node_luyin");
}
void GameController::shouhuibgrule()
{
bg_rule->stopAllActions();
MoveTo *mt=MoveTo::create(0.3,Vec2(-51,594));
bg_rule->runAction(mt);
bt_go->setTag(0);
bt_go->loadTextures("res/loading/layer_result/btn_jiantou_suo.png","res/loading/layer_result/btn_jiantou_suo.png","res/loading/layer_result/btn_jiantou_suo.png");
}
void GameController::showLuxiangController()
{
nodeWait->setVisible(false);
nodeGame->setVisible(true);
nodeBottom->setVisible(false);
n_luyinanimate->setVisible(false);
numJuShu_game->setVisible(false);
numCards_game->setVisible(false);
numTime_game->setVisible(false);
Text *tx_shengyu1 = (Text*)((ImageView*)nodeGame->getChildByName("bgShow1"))->getChildByName("texts1");
tx_shengyu1->setVisible(false);
Text *tx_shengyu2 = (Text*)((ImageView*)nodeGame->getChildByName("bgShow1"))->getChildByName("texts3");
tx_shengyu2->setVisible(false);
Text *tx_shengyu3 = (Text*)((ImageView*)nodeGame->getChildByName("bgShow1"))->getChildByName("texts");
tx_shengyu3->setVisible(false);
Text *tx_shengyu4= (Text*)((ImageView*)nodeGame->getChildByName("bgShow1"))->getChildByName("texts_1");
tx_shengyu4->setVisible(false);
}
static int luyin_time=0;
void GameController::update(float dt)
{
luyin_time++;
}
void GameController::arrowvisible(bool isvisible)
{
for(int i=0;i<arr_arrows.size();i++)
{
arr_arrows[i]->setVisible(isvisible);
}
}
void GameController::refreshjushu()
{
numTime_game = (TextAtlas*)nodeGame->getChildByName("num");
numTime_game->setString("10");
const string shengyuStr = Tools::getChineseByKey("ShengYu");
const string zhangStr = Tools::getChineseByKey("Zheng");
const string juStr = Tools::getChineseByKey("Ju");
numCards_game = (Text*)((ImageView*)nodeGame->getChildByName("bgShow1"))->getChildByName("texts2");
String *left_cntString = String::createWithFormat("%d",0);
numCards_game->setText(left_cntString->getCString());
numJuShu_game = (Text*)((ImageView*)nodeGame->getChildByName("bgShow1"))->getChildByName("texts_0");
//0121
String *ju_cntString = String::createWithFormat("%d",MjData::getInstance()->getleftjushu());
numJuShu_game->setText(ju_cntString->getCString());
}
void GameController::playluyin(float dt)
{
//CocosDenshion::SimpleAudioEngine::getInstance()->playEffect(luyin_path.c_str());
}
//按钮回调函数
void GameController::ButtonHandler(Ref* pRef, ui::Widget::TouchEventType touchType)
{
Button *bt_luyin=(Button *)pRef;
if(bt_luyin->getName()=="Button_luyin")//luyin
{
if(UserDefault::getInstance()->getBoolForKey("isplayluyin")==false)
{
if(touchType==ui::Widget::TouchEventType::BEGAN)
{
//暂停背景音乐
Tools::pauseBackMusic();
JniFun::startSoundRecord();//开始录音
n_luyinanimate->setVisible(true);
Vector<SpriteFrame *>arr_frames;
for(int i=0;i<7;i++)
{
String *path=String::createWithFormat("res/srcRes/animate/startRecord/%d.png",i);
Sprite *sp=Sprite::create(path->getCString());
arr_frames.pushBack(sp->getSpriteFrame());
}
Animation *an=Animation::createWithSpriteFrames(arr_frames);
an->setDelayPerUnit(2.0f/6);
Animate *amt=Animate::create(an);
RepeatForever *re=RepeatForever::create(amt);
Sprite *sp_xinhao=(Sprite *)n_luyinanimate->getChildByName("Sprite_3");
sp_xinhao->runAction(re);
log("kaishi luyin");
}
else if(touchType==ui::Widget::TouchEventType::ENDED||touchType==ui::Widget::TouchEventType::CANCELED)
{
n_luyinanimate->setVisible(false);
Sprite *xinhao=(Sprite *)n_luyinanimate->getChildByName("Sprite_3");
xinhao->stopAllActions();
std::string path=JniFun::stopSoundRecord();
// luyin_path=path;
ssize_t iSize = 0;
std::string kDestFile = cocos2d::CCFileUtils::getInstance()->getWritablePath()+"talk.arm";
log("kDestFile: %s", kDestFile.c_str());
remove(kDestFile.c_str());
ArmFun::WavToArm(path.c_str(),kDestFile.c_str());
remove(path.c_str());
log("kDestFile-----------: %s", kDestFile.c_str());
unsigned char* pData = cocos2d::CCFileUtils::sharedFileUtils()->getFileData(kDestFile,"rb",&iSize);
if (!pData)
{
log("kDestFile-----------1111: %s", kDestFile.c_str());
return;
}
char *p=(char *)pData;
UserDefault::getInstance()->setBoolForKey("isplayluyin",true);
TableCommand::getInstance()->requestyuyin(p,iSize);
//继续背景音乐
Tools::resumeBackMusic();
}
}
}
if (touchType != ui::Widget::TouchEventType::ENDED)
return;
Button* pBtn = (Button*) pRef;
string name = pBtn->getName();
if (name == "btnExitRoom"){
//退出房间
//SEND_CUSTOM_MSG("gamemainexit");
TableCommand::getInstance()->requestLeaveTable(0);
}else if (name == "btnGetFriends"){
//微信邀请好友
// SEND_CUSTOM_MSG("gamemainstart"); //测试使用
//微信邀请好友
std::string jinping=Tools::getChineseByKey("jinping");
std::string rule;
rule = String::createWithFormat("%s %d",Tools::getChineseByKey("roomid").c_str(),GamerData::getInstance()->getTableId())->getCString();
if (MjData::getInstance()->getjushu()==4)
{
rule = String::createWithFormat("%s %s",rule.c_str(),Tools::getChineseByKey("8ju").c_str())->getCString();
}
if (MjData::getInstance()->getjushu()==8)
{
rule = String::createWithFormat("%s %s",rule.c_str(),Tools::getChineseByKey("16ju").c_str())->getCString();
}
if (MjData::getInstance()->getIsgang_men()==1)
{
rule = String::createWithFormat("%s %s",rule.c_str(),Tools::getChineseByKey("zigang").c_str())->getCString();
}
else
{
rule = String::createWithFormat("%s %s",rule.c_str(),Tools::getChineseByKey("zhuanwan").c_str())->getCString();
}
if (MjData::getInstance()->getIsgenZhuang()==1)
{
rule = String::createWithFormat("%s %s",rule.c_str(),Tools::getChineseByKey("gen").c_str())->getCString();
}
if(MjData::getInstance()->getpalyrule()==1)
{
rule = String::createWithFormat("%s %s",rule.c_str(),Tools::getChineseByKey("4renfang").c_str())->getCString();
}
else if(MjData::getInstance()->getpalyrule()==2)
{
rule = String::createWithFormat("%s %s",rule.c_str(),Tools::getChineseByKey("sandingguai").c_str())->getCString();
}
else if(MjData::getInstance()->getpalyrule()==3)
{
rule = String::createWithFormat("%s %s",rule.c_str(),Tools::getChineseByKey("2dingguai").c_str())->getCString();
}
else if(MjData::getInstance()->getpalyrule()==4)
{
rule = String::createWithFormat("%s %s",rule.c_str(),Tools::getChineseByKey("sandingliangfang").c_str())->getCString();
}
else if(MjData::getInstance()->getpalyrule()==5)
{
rule = String::createWithFormat("%s %s",rule.c_str(),Tools::getChineseByKey("erdingliangfang").c_str())->getCString();
}
MissionWeiXin::getinstance()->shareUrlWeiXin("http://d.laiyagame.com/jinping/download.html",jinping.c_str(),rule.c_str(),0);
//auto mLobbyView = LobbyView::create();
//mLobbyView->showUIWeiXinShare(1);
//this->addChild(mLobbyView);
}else if (name == "btnDismiss")
{//解散房间
TableCommand::getInstance()->requestLeaveTable(1);
}else if (name == "btnSet")
{//设置
auto lobbyView = LobbyView::create();
lobbyView->showUISetting(true);
this->getParent()->addChild(lobbyView,9);
}else if (name == "btnHelp")
{//帮助
auto tipConent = TipContent::create();
tipConent->showUIHelp();
this->getParent()->addChild(tipConent,9);
}else if (name == "btnChat")
{//聊天
//TableCommand::getInstance()->requestchat(2);
//TableCommand::getInstance()->requestcustomchat("hahaha");
layer_chat *l_c=layer_chat::create();
l_c->refreshchat(1);
this->getParent()->addChild(l_c, 10);
}
else if(name=="Button_go")
{
if(bt_go->getTag()==0)
{
bg_rule->stopAllActions();
MoveTo *mt=MoveTo::create(0.3,Vec2(90,594));
bg_rule->runAction(mt);
bt_go->setTag(1);
bt_go->loadTextures("res/loading/layer_result/btn_jiantou_shen.png","res/loading/layer_result/btn_jiantou_shen.png","res/loading/layer_result/btn_jiantou_shen.png");
}
else
{
bg_rule->stopAllActions();
MoveTo *mt=MoveTo::create(0.3,Vec2(-51,594));
bg_rule->runAction(mt);
bt_go->setTag(0);
bt_go->loadTextures("res/loading/layer_result/btn_jiantou_suo.png","res/loading/layer_result/btn_jiantou_suo.png","res/loading/layer_result/btn_jiantou_suo.png");
}
}
}
//游戏开始
void GameController::startGame_gameController(int left_card_cnt, int left_round_cnt)
{
nodeWait->setVisible(false);
nodeGame->setVisible(true);
numTime_game = (TextAtlas*)nodeGame->getChildByName("num");
numTime_game->setString("10");
const string shengyuStr = Tools::getChineseByKey("ShengYu");
const string zhangStr = Tools::getChineseByKey("Zheng");
const string juStr = Tools::getChineseByKey("Ju");
numCards_game = (Text*)((ImageView*)nodeGame->getChildByName("bgShow1"))->getChildByName("texts2");
String *left_cntString = String::createWithFormat("%d",left_card_cnt);
numCards_game->setText(left_cntString->getCString());
numJuShu_game = (Text*)((ImageView*)nodeGame->getChildByName("bgShow1"))->getChildByName("texts_0");
//0121
String *ju_cntString = String::createWithFormat("%d",left_round_cnt);
numJuShu_game->setText(ju_cntString->getCString());
shouhuibgrule();
}
//设置剩余张数
void GameController::setLeftCardCnt(int left_card_cnt)
{
const string shengyuStr = Tools::getChineseByKey("ShengYu");
const string zhangStr = Tools::getChineseByKey("Zheng");
numCards_game = (Text*)((ImageView*)nodeGame->getChildByName("bgShow1"))->getChildByName("texts2");
String *left_cntString = String::createWithFormat("%d",left_card_cnt);
numCards_game->setText(left_cntString->getCString());
}
static int time_daojishi=10;
static int uid=0;
void GameController::begintimehjisshiqi(float dt)
{
time_daojishi=time_daojishi-1;
if(time_daojishi>3)
{
String *time=String::createWithFormat("%d",time_daojishi);
numTime_game->setString(time->getCString());
}
else if(time_daojishi<=3&&time_daojishi>=0)
{
String *time=String::createWithFormat("%d",time_daojishi);
numTime_game->setString(time->getCString());
}
}
static int time_daojishiQuake=10;
void GameController::begintimehjisshiqiQuake(float dt)
{
time_daojishiQuake=time_daojishiQuake-1;
if(time_daojishiQuake==3)
{
if(uid==0)
{
// JniFun::variable();
Tools::playEffect("alarm.mp3");
}
}
}
//根据 庄的 viewid对 箭头数组重新排序
void GameController::setArrowRoatation(int bankerViewId)
{
std::vector<Sprite *>arr_arrows_temp;
if(bankerViewId==0)
{
bgtime->setRotation(90);
for(int i=0;i<arr_arrows.size();i++)
{
if(arr_arrows[i]->getTag()==1)
{
arr_arrows_temp.push_back(arr_arrows[i]);
}
}
for(int i=0;i<arr_arrows.size();i++)
{
if(arr_arrows[i]->getTag()==2)
{
arr_arrows_temp.push_back(arr_arrows[i]);
}
}
for(int i=0;i<arr_arrows.size();i++)
{
if(arr_arrows[i]->getTag()==3)
{
arr_arrows_temp.push_back(arr_arrows[i]);
}
}
for(int i=0;i<arr_arrows.size();i++)
{
if(arr_arrows[i]->getTag()==0)
{
arr_arrows_temp.push_back(arr_arrows[i]);
}
}
}
else if(bankerViewId==1)
{
bgtime->setRotation(0);
for(int i=0;i<arr_arrows.size();i++)
{
if(arr_arrows[i]->getTag()==0)
{
arr_arrows_temp.push_back(arr_arrows[i]);
}
}
for(int i=0;i<arr_arrows.size();i++)
{
if(arr_arrows[i]->getTag()==1)
{
arr_arrows_temp.push_back(arr_arrows[i]);
}
}
for(int i=0;i<arr_arrows.size();i++)
{
if(arr_arrows[i]->getTag()==2)
{
arr_arrows_temp.push_back(arr_arrows[i]);
}
}
for(int i=0;i<arr_arrows.size();i++)
{
if(arr_arrows[i]->getTag()==3)
{
arr_arrows_temp.push_back(arr_arrows[i]);
}
}
}
else if(bankerViewId==2)
{
bgtime->setRotation(-90);
for(int i=0;i<arr_arrows.size();i++)
{
if(arr_arrows[i]->getTag()==3)
{
arr_arrows_temp.push_back(arr_arrows[i]);
}
}
for(int i=0;i<arr_arrows.size();i++)
{
if(arr_arrows[i]->getTag()==0)
{
arr_arrows_temp.push_back(arr_arrows[i]);
}
}
for(int i=0;i<arr_arrows.size();i++)
{
if(arr_arrows[i]->getTag()==1)
{
arr_arrows_temp.push_back(arr_arrows[i]);
}
}
for(int i=0;i<arr_arrows.size();i++)
{
if(arr_arrows[i]->getTag()==2)
{
arr_arrows_temp.push_back(arr_arrows[i]);
}
}
}
else if(bankerViewId==3)
{
bgtime->setRotation(180);
for(int i=0;i<arr_arrows.size();i++)
{
if(arr_arrows[i]->getTag()==2)
{
arr_arrows_temp.push_back(arr_arrows[i]);
}
}
for(int i=0;i<arr_arrows.size();i++)
{
if(arr_arrows[i]->getTag()==3)
{
arr_arrows_temp.push_back(arr_arrows[i]);
}
}
for(int i=0;i<arr_arrows.size();i++)
{
if(arr_arrows[i]->getTag()==0)
{
arr_arrows_temp.push_back(arr_arrows[i]);
}
}
for(int i=0;i<arr_arrows.size();i++)
{
if(arr_arrows[i]->getTag()==1)
{
arr_arrows_temp.push_back(arr_arrows[i]);
}
}
}
arr_arrows.clear();
for(int i=0;i<arr_arrows_temp.size();i++)
{
arr_arrows.push_back(arr_arrows_temp[i]);
}
}
//修改箭头指向方位根据玩家[0:当前玩家;1:下家;2:对门;3:上家]
void GameController::setArrowDirection(int index)
{
if(index==0)
{
UserDefault::getInstance()->setBoolForKey("iscanoperatecard",true);
}
uid=index;
if(MjData::getInstance()->getpalyrule()==2||MjData::getInstance()->getpalyrule()==4)
{
if(index==2)
{
index=index+1;
}
}
else if(MjData::getInstance()->getpalyrule()==3||MjData::getInstance()->getpalyrule()==5)
{
if(index==1)
{
index=2;
}
}
time_daojishi=10;
schedule(schedule_selector(GameController::begintimehjisshiqi),1.0f);
time_daojishiQuake=10;
schedule(schedule_selector(GameController::begintimehjisshiqiQuake),1.0f);
for(int i=0;i<arr_arrows.size();i++)
{
arr_arrows[i]->setVisible(false);
}
arr_arrows[index]->setVisible(true);
}
void GameController::WeiXinShareInGame(EventCustom* evt)
{
int* type = (int*)evt->getUserData();
std::string jinping=Tools::getChineseByKey("jinping");
std::string rule;
rule = String::createWithFormat("%s %d",Tools::getChineseByKey("roomid").c_str(),GamerData::getInstance()->getTableId())->getCString();
if (MjData::getInstance()->getjushu()==4)
{
rule = String::createWithFormat("%s %s",rule.c_str(),Tools::getChineseByKey("8ju").c_str())->getCString();
}
if (MjData::getInstance()->getjushu()==8)
{
rule = String::createWithFormat("%s %s",rule.c_str(),Tools::getChineseByKey("16ju").c_str())->getCString();
}
if (MjData::getInstance()->getIsgang_men()==1)
{
rule = String::createWithFormat("%s %s",rule.c_str(),Tools::getChineseByKey("zigang").c_str())->getCString();
}
else
{
rule = String::createWithFormat("%s %s",rule.c_str(),Tools::getChineseByKey("zhuanwan").c_str())->getCString();
}
if (MjData::getInstance()->getIsgenZhuang()==1)
{
rule = String::createWithFormat("%s %s",rule.c_str(),Tools::getChineseByKey("gen").c_str())->getCString();
}
if(MjData::getInstance()->getpalyrule()==1)
{
rule = String::createWithFormat("%s %s",rule.c_str(),Tools::getChineseByKey("4renfang").c_str())->getCString();
}
else if(MjData::getInstance()->getpalyrule()==2)
{
rule = String::createWithFormat("%s %s",rule.c_str(),Tools::getChineseByKey("sandingguai").c_str())->getCString();
}
else if(MjData::getInstance()->getpalyrule()==3)
{
rule = String::createWithFormat("%s %s",rule.c_str(),Tools::getChineseByKey("2dingguai").c_str())->getCString();
}
else if(MjData::getInstance()->getpalyrule()==4)
{
rule = String::createWithFormat("%s %s",rule.c_str(),Tools::getChineseByKey("sandingliangfang").c_str())->getCString();
}
else if(MjData::getInstance()->getpalyrule()==5)
{
rule = String::createWithFormat("%s %s",rule.c_str(),Tools::getChineseByKey("erdingliangfang").c_str())->getCString();
}
if(*type==0)
{
MissionWeiXin::getinstance()->shareUrlWeiXin("http://d.laiyagame.com/jinping/download.html",jinping.c_str(),rule.c_str(),*type);
}
else
{
MissionWeiXin::getinstance()->shareUrlWeiXin("http://d.laiyagame.com/jinping/download.html",rule.c_str(),rule.c_str(),*type);
}
} | [
"sck@qq.com"
] | sck@qq.com |
5f9e32254a12f9116f482a3cbfc01e304fb82850 | b83cfd7ffac96422b7c07526b8cad4eeec9749c1 | /include/AplCam/histogram.h | 4b12d7cc16e3ee587b9a5877a78c2b505567f96a | [] | no_license | amarburg/aplcam | ec27a22a06e83129e0f371c92d53aa0ebcf4c0a4 | 31824115d17cdf4b8c1d8a949bdcdf9db869c494 | refs/heads/master | 2021-01-19T15:06:46.888346 | 2018-12-10T23:27:42 | 2018-12-10T23:27:42 | 88,195,934 | 0 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 1,192 | h | #ifndef __HISTOGRAM_H__
#define __HISTOGRAM_H__
#include <vector>
#include <opencv2/core.hpp>
namespace AplCam {
using std::vector;
class Gaussian {
public:
Gaussian( double mean, double var )
: _mean(mean), _var(var)
{;}
double mean( void ) const { return _mean; }
double var( void ) const { return _var; }
double stddev( void ) const { return sqrt(_var); }
double sigma( void ) const { return stddev(); }
protected:
double _mean, _var;
};
template <typename _Tp>
class _Histogram {
public:
_Histogram( unsigned int numBins ); //, float min = 0.0, float max = 1.0 );
unsigned int numBins( void ) const { return _bins.size(); }
void add( float value );
vector<float> percentages( void ) const;
template <typename _St> _St sum( void ) const;
cv::Mat draw( unsigned int height, float scale = 1.0 ) const;
cv::Mat draw( unsigned int height, const Gaussian &g, float scale = 1.0, float sigma = 1.0 ) const;
Gaussian fitGaussian( void ) const;
protected:
vector<_Tp> _bins;
//float _min, _max;
};
typedef _Histogram<unsigned int> Histogram;
}
#include "histogram_impl.h"
#endif
| [
"amarburg@apl.washington.edu"
] | amarburg@apl.washington.edu |
281661615ada1337a2738bb45b3c391cc4e421a6 | 1e479abbfedb5e28bb9d5060a62286b1aa3746c7 | /sobel_hls/solution1/syn/systemc/fifo_w8_d2_A.h | 59cda052d71a45b119cc9c3a3749f655d555523f | [] | no_license | Yueqh999/Xilinx_Summer_School_Project | 12ca31126f2bb5b876ff9c1571970c7190f0266b | 0167e26b25655fa4ce48fc9eb675aa2c17874169 | refs/heads/master | 2022-11-26T17:09:53.103468 | 2020-08-01T14:07:20 | 2020-08-01T14:07:20 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,625 | h | // ==============================================================
// File generated on Wed Jul 29 15:03:33 +0800 2020
// Vivado(TM) HLS - High-Level Synthesis from C, C++ and SystemC v2018.3 (64-bit)
// SW Build 2405991 on Thu Dec 6 23:38:27 MST 2018
// IP Build 2404404 on Fri Dec 7 01:43:56 MST 2018
// Copyright 1986-2018 Xilinx, Inc. All Rights Reserved.
// ==============================================================
#ifndef fifo_w8_d2_A_HH_
#define fifo_w8_d2_A_HH_
#include <systemc>
using namespace std;
SC_MODULE(fifo_w8_d2_A) {
static const unsigned int DATA_WIDTH = 8;
static const unsigned int ADDR_WIDTH = 2;
static const unsigned int fifo_w8_d2_A_depth = 3;
sc_core::sc_in_clk clk;
sc_core::sc_in< sc_dt::sc_logic > reset;
sc_core::sc_out< sc_dt::sc_logic > if_empty_n;
sc_core::sc_in< sc_dt::sc_logic > if_read_ce;
sc_core::sc_in< sc_dt::sc_logic > if_read;
sc_core::sc_out< sc_dt::sc_lv<DATA_WIDTH> > if_dout;
sc_core::sc_out< sc_dt::sc_logic > if_full_n;
sc_core::sc_in< sc_dt::sc_logic > if_write_ce;
sc_core::sc_in< sc_dt::sc_logic > if_write;
sc_core::sc_in< sc_dt::sc_lv<DATA_WIDTH> > if_din;
sc_core::sc_signal< sc_dt::sc_logic > internal_empty_n;
sc_core::sc_signal< sc_dt::sc_logic > internal_full_n;
sc_core::sc_signal< sc_dt::sc_lv<DATA_WIDTH> > mStorage[fifo_w8_d2_A_depth];
sc_core::sc_signal< sc_dt::sc_uint<ADDR_WIDTH> > mInPtr;
sc_core::sc_signal< sc_dt::sc_uint<ADDR_WIDTH> > mOutPtr;
sc_core::sc_signal< sc_dt::sc_uint<1> > mFlag_nEF_hint;
sc_core::sc_trace_file* mTrace;
SC_CTOR(fifo_w8_d2_A) : mTrace(0) {
const char* dump_vcd = std::getenv("AP_WRITE_VCD");
if (dump_vcd && string(dump_vcd) == "1") {
std::string tracefn = "sc_trace_" + std::string(name());
mTrace = sc_core::sc_create_vcd_trace_file( tracefn.c_str());
sc_trace(mTrace, clk, "(port)clk");
sc_trace(mTrace, reset, "(port)reset");
sc_trace(mTrace, if_full_n, "(port)if_full_n");
sc_trace(mTrace, if_write_ce, "(port)if_write_ce");
sc_trace(mTrace, if_write, "(port)if_write");
sc_trace(mTrace, if_din, "(port)if_din");
sc_trace(mTrace, if_empty_n, "(port)if_empty_n");
sc_trace(mTrace, if_read_ce, "(port)if_read_ce");
sc_trace(mTrace, if_read, "(port)if_read");
sc_trace(mTrace, if_dout, "(port)if_dout");
sc_trace(mTrace, mInPtr, "mInPtr");
sc_trace(mTrace, mOutPtr, "mOutPtr");
sc_trace(mTrace, mFlag_nEF_hint, "mFlag_nEF_hint");
}
mInPtr = 0;
mOutPtr = 0;
mFlag_nEF_hint = 0;
SC_METHOD(proc_read_write);
sensitive << clk.pos();
SC_METHOD(proc_dout);
sensitive << mOutPtr;
for (unsigned i = 0; i < fifo_w8_d2_A_depth; i++) {
sensitive << mStorage[i];
}
SC_METHOD(proc_ptr);
sensitive << mInPtr << mOutPtr<< mFlag_nEF_hint;
SC_METHOD(proc_status);
sensitive << internal_empty_n << internal_full_n;
}
~fifo_w8_d2_A() {
if (mTrace) sc_core::sc_close_vcd_trace_file(mTrace);
}
void proc_status() {
if_empty_n.write(internal_empty_n.read());
if_full_n.write(internal_full_n.read());
}
void proc_read_write() {
if (reset.read() == sc_dt::SC_LOGIC_1) {
mInPtr.write(0);
mOutPtr.write(0);
mFlag_nEF_hint.write(0);
}
else {
if (if_read_ce.read() == sc_dt::SC_LOGIC_1
&& if_read.read() == sc_dt::SC_LOGIC_1
&& internal_empty_n.read() == sc_dt::SC_LOGIC_1) {
sc_dt::sc_uint<ADDR_WIDTH> ptr;
if (mOutPtr.read().to_uint() == (fifo_w8_d2_A_depth-1)) {
ptr = 0;
mFlag_nEF_hint.write(~mFlag_nEF_hint.read());
}
else {
ptr = mOutPtr.read();
ptr++;
}
assert(ptr.to_uint() < fifo_w8_d2_A_depth);
mOutPtr.write(ptr);
}
if (if_write_ce.read() == sc_dt::SC_LOGIC_1
&& if_write.read() == sc_dt::SC_LOGIC_1
&& internal_full_n.read() == sc_dt::SC_LOGIC_1) {
sc_dt::sc_uint<ADDR_WIDTH> ptr;
ptr = mInPtr.read();
mStorage[ptr.to_uint()].write(if_din.read());
if (ptr.to_uint() == (fifo_w8_d2_A_depth-1)) {
ptr = 0;
mFlag_nEF_hint.write(~mFlag_nEF_hint.read());
} else {
ptr++;
assert(ptr.to_uint() < fifo_w8_d2_A_depth);
}
mInPtr.write(ptr);
}
}
}
void proc_dout() {
sc_dt::sc_uint<ADDR_WIDTH> ptr = mOutPtr.read();
if (ptr.to_uint() > fifo_w8_d2_A_depth) {
if_dout.write(sc_dt::sc_lv<DATA_WIDTH>());
}
else {
if_dout.write(mStorage[ptr.to_uint()]);
}
}
void proc_ptr() {
if (mInPtr.read() == mOutPtr.read() && mFlag_nEF_hint.read().to_uint()==0) {
internal_empty_n.write(sc_dt::SC_LOGIC_0);
}
else {
internal_empty_n.write(sc_dt::SC_LOGIC_1);
}
if (mInPtr.read() == mOutPtr.read() && mFlag_nEF_hint.read().to_uint()==1) {
internal_full_n.write(sc_dt::SC_LOGIC_0);
}
else {
internal_full_n.write(sc_dt::SC_LOGIC_1);
}
}
};
#endif //fifo_w8_d2_A_HH_
| [
"961492356@qq.com"
] | 961492356@qq.com |
cf495266ded6437ffcc796d3efa64f8e67009777 | 479e14786392aa362b3e2ec1405031a2f8db79d9 | /First-Round/tmp4.cpp | 87314f2431c7fe10178097583f9ea426fabff632 | [
"MIT"
] | permissive | shink/Huawei-CodeCraft-2020 | 75b13921dbc98757107e74cd8572d5e12ca3c851 | 75a4ab211efc82ebd1253f5880ba52a6a7fc7bd2 | refs/heads/master | 2022-12-01T03:46:39.466162 | 2020-08-17T04:09:58 | 2020-08-17T04:09:58 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 7,680 | cpp | #include <bits/stdc++.h>
#include <iostream>
#include <unistd.h>
#include <sys/mman.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <fcntl.h>
#include <vector>
const int THREAD_COUNT = 4;
const int RECORD_MAX = 280000;
const int DOUBLE_RECORD_MAX = RECORD_MAX << 1;
const int NODE_MAX = 200000;
const int INDEGREE_MAX = 50;
const int OUTDEGREE_MAX = 50;
using namespace std;
struct Path {
int length;
vector<int> path;
Path(int length, const vector<int> &path) : length(length), path(path) {}
bool operator<(const Path &rhs) const {
if (length != rhs.length) return length < rhs.length;
for (int i = 0; i < length; ++i) {
if (path[i] != rhs.path[i])
return path[i] < rhs.path[i];
}
return false;
}
};
int node_sum = 1;
int graph[NODE_MAX][OUTDEGREE_MAX + 1];
int graphIn[NODE_MAX][INDEGREE_MAX + 1];
int nodes[NODE_MAX];
int pathDetail[THREAD_COUNT][NODE_MAX][600];
vector<Path> res[THREAD_COUNT];
void createGraph(const char *buffer) {
int input_num = 0;
int input[DOUBLE_RECORD_MAX], temp[DOUBLE_RECORD_MAX];
int data[3] = {0, 0, 0};
int i = 0, flag = 0;
while (buffer[i]) {
int c = buffer[i] - '0';
if (buffer[i] == '\n') {
input[input_num] = data[0];
temp[input_num++] = data[0];
input[input_num] = data[1];
temp[input_num++] = data[1];
data[0] = data[1] = data[2] = flag = 0;
++i;
} else if (c >= 0) {
while (c >= 0) {
data[flag] = data[flag] * 10 + c;
c = buffer[++i] - '0';
}
++flag;
} else ++i;
}
sort(temp, temp + input_num);
nodes[0] = temp[0];
for (i = 1; i < input_num; ++i) {
if (temp[i - 1] != temp[i])
nodes[node_sum++] = temp[i];
}
for (i = 0; i < node_sum; ++i) {
int node = nodes[i];
graph[node][0] = 0;
graphIn[node][0] = 0;
}
for (i = 0; i < input_num; i += 2) {
int u = input[i];
int v = input[i + 1];
int outDegree = ++graph[u][0];
graph[u][outDegree] = v;
int inDegree = ++graphIn[v][0];
graphIn[v][inDegree] = u;
}
for (i = 0; i < node_sum; ++i) {
int node = nodes[i];
sort(graph[node] + 1, graph[node] + (graph[node][0] + 1));
sort(graphIn[node] + 1, graphIn[node] + (graphIn[node][0] + 1));
}
}
void readData(const string &file_name) {
int fd = open(file_name.c_str(), O_RDONLY);
long file_size = lseek(fd, 0, SEEK_END);
char *buffer = (char *) mmap(NULL, file_size, PROT_READ, MAP_PRIVATE, fd, 0);
close(fd);
createGraph(buffer);
munmap(buffer, file_size);
}
void dfs(int tid, bool *visit, int head, int cur, int depth, vector<int> &path) {
visit[cur] = true;
path.push_back(cur);
int *it = lower_bound(graph[cur] + 1, graph[cur] + (graph[cur][0] + 1), head);
if (it != graph[cur] + (graph[cur][0] + 1) && *it == head && depth >= 3 && depth <= 4) {
res[tid].emplace_back(Path(depth, path));
}
if (depth < 4) {
for (; it != graph[cur] + (graph[cur][0] + 1); ++it) {
if (!visit[*it]) {
dfs(tid, visit, head, *it, depth + 1, path);
}
}
} else if (depth == 4) {
for (int i = 1; i <= pathDetail[tid][cur][552]; ++i) {
int u1 = pathDetail[tid][cur][552 + i];
if (!visit[u1]) {
auto temp = path;
temp.push_back(u1);
res[tid].emplace_back(Path(5, temp));
}
}
for (int j = 1; j <= pathDetail[tid][cur][451] * 2; j += 2) {
int u2 = pathDetail[tid][cur][451 + j], u1 = pathDetail[tid][cur][451 + j + 1];
if (!visit[u2] && !visit[u1]) {
auto temp = path;
temp.push_back(u2);
temp.push_back(u1);
res[tid].emplace_back(Path(6, temp));
}
}
for (int k = 1; k <= pathDetail[tid][cur][0] * 3; k += 3) {
int u3 = pathDetail[tid][cur][k], u2 = pathDetail[tid][cur][k + 1], u1 = pathDetail[tid][cur][k + 2];
if (!visit[u3] && !visit[u2] && !visit[u1]) {
auto temp = path;
temp.push_back(u3);
temp.push_back(u2);
temp.push_back(u1);
res[tid].emplace_back(Path(7, temp));
}
}
}
visit[cur] = false;
path.pop_back();
}
void threadFunc(int start) {
bool visit[NODE_MAX];
fill(visit, visit + NODE_MAX, false);
vector<int> path;
for (int i = start; i < node_sum - 2; i += THREAD_COUNT) {
int head = nodes[i];
if (graph[head][0] > 0) {
for (int j = 0; j < node_sum; ++j) {
pathDetail[start][nodes[j]][0] = 0;
pathDetail[start][nodes[j]][451] = 0;
pathDetail[start][nodes[j]][552] = 0;
}
for (int k = 1; k <= graphIn[head][0]; ++k) {
int u1 = graphIn[head][k];
if (u1 > head) {
for (int l = 1; l <= graphIn[u1][0]; ++l) {
int u2 = graphIn[u1][l];
if (u2 > head && u2 != u1) {
int sum1 = ++pathDetail[start][u2][552];
pathDetail[start][u2][552 + sum1] = u1;
for (int m = 1; m <= graphIn[u2][0]; ++m) {
int u3 = graphIn[u2][m];
if (u3 > head && u3 != u1 && u3 != u2) {
int sum2 = ++pathDetail[start][u3][451];
pathDetail[start][u3][451 + 2 * sum2 - 1] = u2;
pathDetail[start][u3][451 + 2 * sum2] = u1;
for (int n = 1; n <= graphIn[u3][0]; ++n) {
int u4 = graphIn[u3][n];
if (u4 > head && u4 != u1 && u4 != u2 && u4 != u3) {
int sum3 = ++pathDetail[start][u4][0];
pathDetail[start][u3][3 * sum3 - 2] = u3;
pathDetail[start][u3][3 * sum3 - 1] = u2;
pathDetail[start][u3][3 * sum3] = u1;
}
}
}
}
}
}
}
}
dfs(start, visit, head, head, 1, path);
}
}
}
void work(const string &file_name) {
vector<thread> td(THREAD_COUNT);
for (int i = 0; i < THREAD_COUNT; ++i) {
td[i] = thread(&threadFunc, i);
}
for (auto &t : td) {
t.join();
}
for (int i = 1; i < THREAD_COUNT; ++i) {
res[0].insert(res[0].end(), res[i].begin(), res[i].end());
}
sort(res[0].begin(), res[0].end());
ofstream out(file_name);
out << res[0].size() << '\n';
for (auto item : res[0]) {
auto path = item.path;
out << path[0];
for (int i = 1; i < item.length; ++i)
out << "," << path[i];
out << '\n';
}
}
int main(int argc, char *argv[]) {
string file = argc > 1 ? argv[1] : "test";
string file_name = "datasets/" + file + "/test_data.txt";
string save_file_name = "result.txt";
readData(file_name);
work(save_file_name);
exit(0);
}
| [
"tsund@qq.com"
] | tsund@qq.com |
55688b4acf1a00eab530319a868fabad1051a315 | 4efa4b003c7bb756bcb8380124910c0a1e4368b7 | /palmod/Game/Game_SVG_SNES.h | f868f02db903592c480eca1ed5e64e4f6cfd21ef | [] | no_license | eziochiu/PalMod | 41ad6bea84302e015852d133ee518a152ec47021 | 5c6fb2b7fa7b99e29ec55324d6dc0ec8ae4100c4 | refs/heads/master | 2023-08-27T03:04:29.246553 | 2021-10-26T19:40:47 | 2021-10-26T19:40:47 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,903 | h | #pragma once
#include "gameclass.h"
#include "SVG_SNES_DEF.h"
#include "..\extrafile.h"
class CGame_SVG_SNES : public CGameWithExtrasFile
{
private:
static UINT32 m_nTotalPaletteCountForSVG;
static int rgExtraCountAll[SVG_SNES_NUMUNIT + 1];
static int rgExtraLoc[SVG_SNES_NUMUNIT + 1];
static void InitializeStatics();
static UINT32 m_nExpectedGameROMSize;
static UINT32 m_nConfirmedROMSize;
void LoadSpecificPaletteData(UINT16 nUnitId, UINT16 nPalId);
UINT16 GetPaletteCountForUnit(UINT16 nUnitId);
static constexpr auto EXTRA_FILENAME_SVG_SNES = L"SVGE.txt";
static constexpr auto SVG_SNES_PRIMARY_ROMNAME = L"Super Variable Geo (J).sfc";
public:
CGame_SVG_SNES(UINT32 nConfirmedROMSize);
~CGame_SVG_SNES(void);
//Static functions / variables
static CDescTree MainDescTree;
static sDescTreeNode* InitDescTree();
static sFileRule GetRule(UINT16 nUnitId);
//Extra palette function
static int GetExtraCt(UINT16 nUnitId, BOOL bCountVisibleOnly = FALSE);
static int GetExtraLoc(UINT16 nUnitId);
//Normal functions
CDescTree* GetMainTree();
static UINT16 GetCollectionCountForUnit(UINT16 nUnitId);
// We don't fold these into one sDescTreeNode return because we need to handle the Extra section.
static UINT16 GetNodeCountForCollection(UINT16 nUnitId, UINT16 nCollectionId);
static LPCWSTR GetDescriptionForCollection(UINT16 nUnitId, UINT16 nCollectionId);
static const sGame_PaletteDataset* GetPaletteSet(UINT16 nUnitId, UINT16 nCollectionId);
static const sGame_PaletteDataset* GetSpecificPalette(UINT16 nUnitId, UINT16 nPaletteId);
const sDescTreeNode* GetNodeFromPaletteId(UINT16 nUnitId, UINT16 nPaletteId, bool fReturnBasicNodesOnly);
BOOL UpdatePalImg(int Node01 = -1, int Node02 = -1, int Node03 = -1, int Node04 = -1);
static stExtraDef* SVG_SNES_EXTRA_CUSTOM;
};
| [
"meandyouftw@gmail.com"
] | meandyouftw@gmail.com |
ddc0864de37d6e0f9b65b6d3490844f84936e047 | fb6010e5992307fd420309cbd99a01fef13200dc | /UNK/UNK. Rank Transform of a Matrix.cpp | a8966bbe48ff305d8744662c3b3d5ee3073c1d44 | [] | no_license | MegrezZhu/LeetCode | 018e803701bbdb56827d98a3811fdb63cc787792 | 9105298f18a1284a5eeee7e2cc4745f5b45476c8 | refs/heads/master | 2023-02-10T08:55:08.884565 | 2021-01-11T05:44:39 | 2021-01-11T05:44:39 | 107,408,579 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,415 | cpp | class Solution {
int n, m;
vector<vector<int>> matrix;
vector<int> row, col; // max rank in the row/col
map<pair<int, int>, vector<int>> rowMap, colMap; // <row/col, val> to index of id
vector<pair<int, int>> id;
public:
vector<vector<int>> matrixRankTransform(vector<vector<int>> mm) {
matrix = move(mm);
rowMap.clear();
colMap.clear();
id.clear();
n = matrix.size();
m = matrix.front().size();
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
id.push_back({ i, j });
}
}
vector<vector<int>> rank(n, vector<int>(m, -1));
row = vector<int>(n, -1);
col = vector<int>(m, -1);
sort(id.begin(), id.end(), [&](const pair<int, int>& pa, const pair<int, int>& pb) {
return matrix[pa.first][pa.second] < matrix[pb.first][pb.second];
});
for (int i = 0; i < id.size(); i++) {
auto [x, y] = id[i];
int val = matrix[x][y];
rowMap[{x, val}].push_back(i);
colMap[{y, val}].push_back(i);
}
for (const auto& p : id) {
auto [x, y] = p;
if (rank[x][y] != -1) continue;
auto g = group(x, y);
int rankVal = -1;
for (auto i : g) {
auto [tx, ty] = id[i];
rankVal = max(rankVal, minRank(rank, tx, ty));
}
for (auto i : g) {
auto [tx, ty] = id[i];
rank[tx][ty] = rankVal;
row[tx] = max(row[tx], rankVal);
col[ty] = max(col[ty], rankVal);
}
}
return rank;
}
int minRank(vector<vector<int>> &rank, int x, int y) {
int val = 1;
val = max(val, row[x] + 1);
val = max(val, col[y] + 1);
return val;
}
// group of ids, that have the same value and rank
unordered_set<int> group(int x, int y) {
unordered_set<int> res;
int val = matrix[x][y];
list<pair<bool, int>> li = { {true, x}, {false, y} }; // <T for row, val>
while (!li.empty()) {
auto [isRow, ind] = li.front();
li.pop_front();
if (isRow) {
auto it = rowMap.find(make_pair(ind, val));
if (it != rowMap.end()) {
for (int ii : it->second) { // ii: index to id
int i = id[ii].second; // col
if (res.find(ii) == res.end()) {
res.insert(ii);
li.push_back({ false, i });
}
}
}
}
else {
auto it = colMap.find(make_pair(ind, val));
if (it != colMap.end()) {
for (int ii : it->second) {
int i = id[ii].first;
if (res.find(ii) == res.end()) {
res.insert(ii);
li.push_back({ true, i });
}
}
}
}
}
return res;
}
}; | [
"mystery490815101@gmail.com"
] | mystery490815101@gmail.com |
83c53dec77ae282f6dfd23bfb6ccb17ac523dbff | 63a381d90124527f8dd7d833f3da70b3160f1869 | /src/Model3D/IModel3d.hpp | b1991a44d4547d317a96c8d22ffd5c631155ec13 | [] | no_license | zengnotes/MultiplayerOnlineGame | f75fe82c1ce53c631466c209db7c397ecbff27e2 | 31561dedb03d77d69dff0ea2853aa666ec4c7751 | refs/heads/master | 2021-01-20T06:32:50.570693 | 2014-11-11T20:02:43 | 2014-11-11T20:02:43 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 683 | hpp | //
// MultiplayerOnlineGame - multiplayer game project
// Copyright (C) 2008-2014 Michael Fink
//
/// \file IModel3d.hpp Interface for 3d model
//
#pragma once
/// \brief interface for 3d model
/// \details A model contains the data that is loaded and used for all
/// instances of this model. Model instances are managed using instances
/// of classes derived from IModelDisplayState.
class IModel3d
{
public:
/// dtor
virtual ~IModel3d() throw() {}
/// prepares model for rendering
virtual void Prepare() throw() = 0;
/// uploads data to graphics card
virtual void Upload() throw() = 0;
};
/// 3d model smart ptr
typedef std::shared_ptr<IModel3d> Model3dPtr;
| [
"michael.fink@asamnet.de"
] | michael.fink@asamnet.de |
6d0cd1c27d9a8d525ba72b5c0949950d5ad8c53d | 75106c3a7a7d16f643e6ebe54fcbfe636b2da174 | /Arrays/7_leaders.cpp | b46d0b4858594526e83764e9482e166ef6e7b562 | [] | no_license | i7sharath/geeks4geeks | b7f604189111c6ba45008d6d5ac5491533a7576e | 9c02e45dc2b73a007db2c2bba96a9491538818c7 | refs/heads/master | 2021-05-01T17:00:36.132885 | 2016-09-17T17:44:08 | 2016-09-17T17:44:08 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 464 | cpp | #include <iostream>
#include <cstdio>
#include <cstring>
#include <vector>
#include <algorithm>
using namespace std;
void findLeaders(vector<int>& vec)
{
int leader=vec[vec.size()-1];
cout<<leader<<" ";
for(int i=vec.size()-2;i>=0;i--)
{
if(vec[i] > leader)
{
leader=vec[i];
cout<<leader<<" ";
}
}
cout<<endl;
return;
}
int main()
{
int n;
cin>>n;
vector<int> vec(n);
for(int i=0;i<n;i++)
cin>>vec[i];
findLeaders(vec);
return 0;
} | [
"rashi.1234chauhan11@gmail.com"
] | rashi.1234chauhan11@gmail.com |
2170fcd0b422ee20f688cbd6eefbcca4f09a660e | 232f03d5ec7286989a7b0c43f269ff6e702fa72f | /jakdojade/inc/read.hpp | c7b8de3efe6528816f3ec9ff7784fd0f3d22a832 | [] | no_license | poorpy/pamsi | e06a91e2ee909e39ea0f1917bb383113c23330a1 | 6e2c62765c00ec8a345fac46d341ab0027d2f440 | refs/heads/master | 2021-03-22T01:11:57.241653 | 2020-05-06T20:27:59 | 2020-05-06T20:27:59 | 123,011,939 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 327 | hpp | #pragma once
#include "graph.hpp"
#include <fstream>
#include <sstream>
#include <string>
#include <vector>
Graph parseFileToGraph(const std::string & pathToFile, const std::string & delimeter);
std::list<edge> parseFileToEdges(const std::string & pathToFile,
const std::string & delimeter);
| [
"marczynski.bartosz@gmail.com"
] | marczynski.bartosz@gmail.com |
b0a16b44b204d04e25f492d32df72a194fb6761f | c7e88d66ffaeb1c830ecd600d116a8fea040e9ea | /PI_20191111_Dibujo ASCII Libre.cpp | 507aac21ccfacdcd710dfd7f32425b4f52a60adf | [] | no_license | insert-edgelordname/HAGU-LEARN | 800e079446a5657376d3d8545a401022ca38afee | f98445334eeb0b41bee210ffd5cea48f92963e8b | refs/heads/master | 2020-12-18T16:34:00.460858 | 2020-12-10T01:21:36 | 2020-12-10T01:21:36 | 235,456,963 | 0 | 0 | null | null | null | null | ISO-8859-2 | C++ | false | false | 3,131 | cpp | /*Titulo: Dibujo Libre
Alumno: Hugo Alberto González Uribe
NUA: 146871
Fecha: 09 de Noviembre de 2019
*/
#include <iostream>
using namespace std;
int main()
{
char c1 = '%', c2 = '/';
int w, v, x, y, z;
int i = 0;
for (x = 1; x <= 5; x++)
{
for (v = 1; v <= 6; v++)
{
//Part 1,1:
for (w = 1; w <= (0 + x); w ++)
{
cout << c1;
}
//Part 2,1:
for (w = 8; w >= (-1 + x); w --)
{
cout << c2;
}
//Part 2,2:
for (w = 8; w >= (-1 + x); w --)
{
cout << " ";
}
//Part 1,2
for (w = 1; w <= (0 + x); w ++)
{
cout << c1;
}
}
}
for (x = 1; x <= 120; x ++)
{
cout << "=";
}
//Ending HEader 1:
//Inbetween:
cout << endl;
for (x = 1; x <= 114; x ++)
{
cout << " ";
}
cout << "_ _ _ ";
for (x = 1; x <= 113; x ++)
{
cout << " ";
}
cout << "I U U U";
for (x = 1; x <= 113; x ++)
{
cout << " ";
}
cout << "I ";
for (x = 1; x <= 90; x ++)
{
cout << " ";
}
cout << "Oh Romeo, Oh Romeo";
cout << " I O/ ";
for (x = 1; x <= 95; x ++)
{
cout << " ";
}
cout << "Where are thou?";
cout << " I ' ";
for (x = 1; x <= 113; x ++)
{
cout << " ";
}
cout << "I _ ";
for (x = 1; x <= 79; x ++)
{
cout << " ";
}
cout << "O/";
for (x = 1; x <= 32; x ++)
{
cout << " ";
}
cout << "I l l ";
for (x = 1; x <= 78; x ++)
{
cout << " ";
}
cout << "/|";
for (x = 1; x <= 33; x ++)
{
cout << " ";
}
cout << "I l l ";
for (x = 1; x <= 79; x ++)
{
cout << "_";
}
cout << "/|";
for (x = 1; x <= 32; x ++)
{
cout << "_";
}
cout << "I 1 1 ";
cout << endl;
cout << endl;
//Begining HEader 2:
for (x = 1; x <= 120; x ++)
{
cout << "=";
}
for (x = 1; x <= 5; x++)
{
for (v = 1; v <= 6; v++)
{
//Part 1,1:
for (w = 5; w > (-1 + x); w --)
{
cout << c1;
}
//Part 2,1:
for (w = 1; w <= (4 + x); w ++)
{
cout << c2;
}
//Part 2,2:
for (w = 1; w <= (4 + x); w ++)
{
cout << " ";
}
//Part 1,2
for (w = 5; w > (-1 + x); w --)
{
cout << c1;
}
}
}
for (x = 1; x <= 3; x ++)
{
for (v = 1; v <= 40; v ++)
{
cout << " _ ";
}
for (v = 1; v <= 40; v ++)
{
cout << "I I";
}
}
}
| [
"noreply@github.com"
] | noreply@github.com |
23f16df6516127eb7fce0b1c666ba1c789f435e8 | c85ad769f3aa58def3f925354d0cdf27ff91673b | /include/GeneralBrush.hpp | 8bc9ee9323a61d9d0c6004b0b46a8c8141dac324 | [] | no_license | JapherS/Pumpkin-Brush | 57e6c58e6f6eef4e270cb0516a58b73227731e52 | ea1902e1bf106b01767ef48bec492f239e8b3475 | refs/heads/master | 2023-05-02T23:17:14.071295 | 2021-05-22T00:54:49 | 2021-05-22T00:54:49 | 369,633,156 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 625 | hpp | #ifndef GENERALBRUSH_HPP
#define GENERALBRUSH_HPP
// Include our Third-Party SFML header
#include <SFML/Graphics/Color.hpp>
#include <vector>
// enum of size of the brush
enum size {small, medium, large};
/*! \brief GeneralBrush class which represent the brush instance when drawing on the canvas
*
*/
class GeneralBrush {
private:
public:
virtual ~GeneralBrush(){};
virtual sf::Color getColor() = 0;
virtual void setColor(sf::Color) = 0;
virtual void setSize(size) = 0;
virtual int getSize() = 0;
virtual std::vector<std::vector<int>> getShader() = 0;
virtual int getType() = 0;
};
#endif
| [
"japhersu@Japhers-MacBook-Pro.local"
] | japhersu@Japhers-MacBook-Pro.local |
fbd8eddf6dee53549cb4c5de4699c79f1f037005 | e4a0a57fc40bdcea6e2317abcf517fda353365f2 | /8_clases_2/integerArray/IntegerArray.h | 353fbc2ba7f013850a497d097d05481175dbb53c | [] | no_license | ahmamani/CCOMP-Verano | 37adca799cee86c7171f2bc7e7c18253df8b33e7 | aaad6a69536f79d73e7185c31b0c33f00d4d5381 | refs/heads/main | 2023-02-25T19:44:21.068075 | 2021-02-04T13:45:53 | 2021-02-04T13:45:53 | 329,090,720 | 1 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 244 | h | #ifndef __INTEGER_ARRAY__
#define __INTEGER_ARRAY__
class IntegerArray {
private:
int *data;
int size;
public:
IntegerArray(int size);
IntegerArray(IntegerArray &o);
~IntegerArray();
};
#endif | [
"amamaniali@unsa.edu.pe"
] | amamaniali@unsa.edu.pe |
8dd5d932ab9dee28da0b7dcb5cf6d5b3cdd6892a | 5e8db76679d5cf4d67a435858eee9c4a97ec75af | /4a.2.2/source/hitprocess/clas12/svt/bst_hitprocess.cc | 24e6c3d47c1038851fc216576416544b9dbaa1cd | [] | no_license | efrainsegarra/clas12Tags | 94f5daa18a6640107953de733a98eeb4d5239368 | ccf90c57d086554e930dd4119f901cd1ea6ad176 | refs/heads/master | 2023-01-09T20:36:53.053681 | 2020-11-10T20:52:19 | 2020-11-10T20:52:19 | 285,655,680 | 0 | 0 | null | 2020-08-06T19:35:40 | 2020-08-06T19:35:39 | null | UTF-8 | C++ | false | false | 8,244 | cc | // gemc headers
#include "bst_hitprocess.h"
#include "bst_strip.h"
// CLHEP units
#include "CLHEP/Units/PhysicalConstants.h"
using namespace CLHEP;
// geant4
#include "Randomize.hh"
// ccdb
#include <CCDB/Calibration.h>
#include <CCDB/Model/Assignment.h>
#include <CCDB/CalibrationGenerator.h>
using namespace ccdb;
static bstConstants initializeBSTConstants(int runno)
{
// all these constants should be read from CCDB
bstConstants bstc;
// database
bstc.runNo = runno;
bstc.date = "2016-03-15";
if(getenv ("CCDB_CONNECTION") != NULL)
bstc.connection = (string) getenv("CCDB_CONNECTION");
else
bstc.connection = "mysql://clas12reader@clasdb.jlab.org/clas12";
bstc.variation = "main";
auto_ptr<Calibration> calib(CalibrationGenerator::CreateCalibration(bstc.connection));
return bstc;
}
map<string, double> bst_HitProcess :: integrateDgt(MHit* aHit, int hitn)
{
map<string, double> dgtz;
vector<identifier> identity = aHit->GetId();
class bst_strip bsts;
bsts.fill_infos();
if(!aHit->isElectronicNoise) {
// double checking dimensions
double SensorLength = 2.0*aHit->GetDetector().dimensions[2]/mm; // length of 1 card
double SensorWidth = 2.0*aHit->GetDetector().dimensions[0]/mm; // width 1 card
double diffLen = SensorLength - bsts.SensorLength;
double diffWid = SensorWidth - bsts.SensorWidth;
// there may be precision issues that's why it is not compared to zero
if( diffLen > 1E-3 || diffWid > 1E-3 )
cout << " Warning: dimensions mismatch between sensor reconstruction dimensions and gemc card dimensions." << endl << endl;
}
int layer = 2*identity[0].id + identity[1].id - 2 ;
int sector = identity[2].id;
int card = identity[3].id;
int strip = identity[4].id;
trueInfos tInfos(aHit);
// 1 DAC is 0.87 keV
// If deposited energy is below 26.1 keV there is no hit.
// If deposited energy is above 117.47 keV the hit will be in the last ADC bin
// (from 117.47 keV to infinity), which means overflow.
// I.e. there are 7 bins plus an overflow bin.
double minHit = 0.0261*MeV;
double maxHit = 0.11747*MeV;
double deltaADC = maxHit - minHit;
int adc = floor( 7*(tInfos.eTot - minHit)/deltaADC);
int adchd = floor(8196*(tInfos.eTot - minHit)/deltaADC);
if(tInfos.eTot>maxHit)
{
adc = 7;
adchd = 8196;
}
if(tInfos.eTot<minHit)
{
adc = -5;
adchd = -5000;
}
if(verbosity>4)
{
cout << log_msg << " layer: " << layer << " sector: " << sector << " Card: " << card << " Strip: " << strip
<< " x=" << tInfos.x << " y=" << tInfos.y << " z=" << tInfos.z << endl;
}
dgtz["hitn"] = hitn;
dgtz["layer"] = layer;
dgtz["sector"] = sector;
dgtz["strip"] = strip;
dgtz["ADC"] = adc;
dgtz["ADCHD"] = adchd;
dgtz["time"] = tInfos.time;
dgtz["bco"] = (int) 255*G4UniformRand();
// decide if write an hit or not
writeHit = true;
// define conditions to reject hit
bool rejectHitConditions = false;
if(rejectHitConditions) {
writeHit = false;
}
return dgtz;
}
vector<identifier> bst_HitProcess :: processID(vector<identifier> id, G4Step* aStep, detector Detector)
{
// yid is the current strip identifier.
// it has 5 dimensions:
// 0. superlayer
// 1. region
// 2. sector
// 3. sensor
// 4. strip id
// the first 4 are set in the identifer:
// superlayer manual 1 type manual 1 segment manual 3 module manual 1 strip manual 1
// the strip id is set by this routine
//
// this routine ALSO identifies contiguos strips and their energy sharing
// this strip original identifier - the dimension is ONE identifier
// later we'll push_back the contiguos strips
vector<identifier> yid = id;
G4ThreeVector xyz = aStep->GetPostStepPoint()->GetPosition();
G4ThreeVector Lxyz = aStep->GetPreStepPoint()->GetTouchableHandle()->GetHistory() ///< Local Coordinates of interaction
->GetTopTransform().TransformPoint(xyz);
class bst_strip bsts;
bsts.fill_infos();
int layer = 2*yid[0].id + yid[1].id - 2 ;
int sector = yid[2].id;
int isensor = yid[3].id;
// FindStrip returns the strips index that are hit
// this vector odd values are the strip numbers, the second number is the energy sharing
// for bst there can be:
// - no energy sharing
// - energy sharing to ONE contiguos (left OR right) strip
vector<double> multi_hit = bsts.FindStrip(layer-1, sector-1, isensor, Lxyz);
// n_multi_hits: number of contiguous strips
// it is either single strip (n_multi_hits = 1) or both strips are hit (n_multi_hits=2)
int n_multi_hits = multi_hit.size()/2;
// closest strip: this identifier is always set
// assigning the closest strip number to identifier id
yid[4].id = (int) multi_hit[0];
// assigning variable id_sharing to all the identifiers
// for the first strip
yid[0].id_sharing = multi_hit[1];
yid[1].id_sharing = multi_hit[1];
yid[2].id_sharing = multi_hit[1];
yid[3].id_sharing = multi_hit[1];
yid[4].id_sharing = multi_hit[1];
// additional strip
if(n_multi_hits == 2) {
// the first four identifiers are
// 0. superlayer
// 1. region
// 2. sector
// 3. sensor
// if n_multi_hits has size two:
// creating ONE additional identifier vector.
// the first 4 identifier are the same as the original strip, so copying them
// the sharing percentage for that strip is multi_hit[3]
for(int j=0; j<4; j++) {
identifier this_id;
this_id.name = yid[j].name;
this_id.rule = yid[j].rule;
this_id.id = yid[j].id;
this_id.time = yid[j].time;
this_id.TimeWindow = yid[j].TimeWindow;
this_id.TrackId = yid[j].TrackId;
this_id.id_sharing = multi_hit[3];
yid.push_back(this_id);
}
// last identifier for the additional hit is is the strip id
// copying infos from original strip
identifier this_id;
this_id.name = yid[4].name;
this_id.rule = yid[4].rule;
this_id.time = yid[4].time;
this_id.TimeWindow = yid[4].TimeWindow;
this_id.TrackId = yid[4].TrackId;
// now assigning strip ID and sharing percentage
this_id.id = (int) multi_hit[2];
this_id.id_sharing = multi_hit[3];
yid.push_back(this_id);
}
return yid;
}
void bst_HitProcess::initWithRunNumber(int runno)
{
if(bstc.runNo != runno) {
cout << " > Initializing " << HCname << " digitization for run number " << runno << endl;
bstc = initializeBSTConstants(runno);
bstc.runNo = runno;
}
}
// - electronicNoise: returns a vector of hits generated / by electronics.
vector<MHit*> bst_HitProcess :: electronicNoise()
{
vector<MHit*> noiseHits;
// first, identify the cells that would have electronic noise
// then instantiate hit with energy E, time T, identifier IDF:
//
// MHit* thisNoiseHit = new MHit(E, T, IDF, pid);
// push to noiseHits collection:
// noiseHits.push_back(thisNoiseHit)
vector<identifier> fullID;
identifier superLayerID;
superLayerID.id = 1;
superLayerID.name = "svtNoise";
identifier regionID;
regionID.id = 1;
regionID.name = "svtNoise";
identifier sectorID;
sectorID.id = 1;
sectorID.name = "svtNoise";
identifier sensorID;
sensorID.id = 1;
sensorID.name = "svtNoise";
identifier stripID;
stripID.id = 1;
stripID.name = "svtNoise";
fullID.push_back(superLayerID);
fullID.push_back(regionID);
fullID.push_back(sectorID);
fullID.push_back(sensorID);
fullID.push_back(stripID);
double energy = 0.5;
double time = 5.5;
int pid = 123;
MHit* thisNoiseHit = new MHit(energy, time, fullID, pid);
noiseHits.push_back(thisNoiseHit);
return noiseHits;
}
map< string, vector <int> > bst_HitProcess :: multiDgt(MHit* aHit, int hitn)
{
map< string, vector <int> > MH;
return MH;
}
// - charge: returns charge/time digitized information / step
map< int, vector <double> > bst_HitProcess :: chargeTime(MHit* aHit, int hitn)
{
map< int, vector <double> > CT;
return CT;
}
// - voltage: returns a voltage value for a given time. The inputs are:
// charge value (coming from chargeAtElectronics)
// time (coming from timeAtElectronics)
double bst_HitProcess :: voltage(double charge, double time, double forTime)
{
return 0.0;
}
// this static function will be loaded first thing by the executable
bstConstants bst_HitProcess::bstc = initializeBSTConstants(-1);
| [
"maurizio.ungaro@cnu.edu"
] | maurizio.ungaro@cnu.edu |
6c92ade2c0dd450625f7200a6ad3bc4c1c9af343 | 3a7d5f93fc842f6481a7bdbb15f3def59dee6b7d | /libraries/src/DW1000.cpp | 71368449779377f0e9610e4c3e94c5db69c8d398 | [] | no_license | victorialqy/RTLS | 79a38e23ab5fe39aaa5b08e76f84f3ca9de69fd8 | 7451b47de4a60ac0b1a4d10bfd5c4cd2c9a77df8 | refs/heads/master | 2021-01-20T18:07:18.652377 | 2016-07-24T10:51:27 | 2016-07-24T10:51:27 | 63,516,101 | 2 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 53,528 | cpp | /*
* Copyright (c) 2015 by Thomas Trojer <thomas@trojer.net>
* Decawave DW1000 library for arduino.
*
* 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 DW1000.cpp
* Arduino driver library (source file) for the Decawave DW1000 UWB transceiver IC.
*/
#ifdef __AVR__
#include "digitalWriteFast.h"
#endif
#include "pins_arduino.h"
#include "DW1000.h"
DW1000Class DW1000;
/* ###########################################################################
* #### Static member variables ##############################################
* ######################################################################### */
// pins
unsigned int DW1000Class::_ss;
unsigned int DW1000Class::_rst;
unsigned int DW1000Class::_irq;
// IRQ callbacks
void (* DW1000Class::_handleSent)(void) = 0;
void (* DW1000Class::_handleError)(void) = 0;
void (* DW1000Class::_handleReceived)(void) = 0;
void (* DW1000Class::_handleReceiveFailed)(void) = 0;
void (* DW1000Class::_handleReceiveTimeout)(void) = 0;
void (* DW1000Class::_handleReceiveTimestampAvailable)(void) = 0;
// registers
byte DW1000Class::_syscfg[LEN_SYS_CFG];
byte DW1000Class::_sysctrl[LEN_SYS_CTRL];
byte DW1000Class::_sysstatus[LEN_SYS_STATUS];
byte DW1000Class::_txfctrl[LEN_TX_FCTRL];
byte DW1000Class::_sysmask[LEN_SYS_MASK];
byte DW1000Class::_chanctrl[LEN_CHAN_CTRL];
byte DW1000Class::_networkAndAddress[LEN_PANADR];
// driver internal state
byte DW1000Class::_extendedFrameLength = FRAME_LENGTH_NORMAL;
byte DW1000Class::_pacSize = PAC_SIZE_8;
byte DW1000Class::_pulseFrequency = TX_PULSE_FREQ_16MHZ;
byte DW1000Class::_dataRate = TRX_RATE_6800KBPS;
byte DW1000Class::_preambleLength = TX_PREAMBLE_LEN_128;
byte DW1000Class::_preambleCode = PREAMBLE_CODE_16MHZ_4;
byte DW1000Class::_channel = CHANNEL_5;
DW1000Time DW1000Class::_antennaDelay;
boolean DW1000Class::_smartPower = false;
boolean DW1000Class::_frameCheck = true;
boolean DW1000Class::_permanentReceive = false;
int DW1000Class::_deviceMode = IDLE_MODE;
// modes of operation
const byte DW1000Class::MODE_LONGDATA_RANGE_LOWPOWER[] = {TRX_RATE_110KBPS, TX_PULSE_FREQ_16MHZ, TX_PREAMBLE_LEN_2048};
const byte DW1000Class::MODE_SHORTDATA_FAST_LOWPOWER[] = {TRX_RATE_6800KBPS, TX_PULSE_FREQ_16MHZ, TX_PREAMBLE_LEN_128};
const byte DW1000Class::MODE_LONGDATA_FAST_LOWPOWER[] = {TRX_RATE_6800KBPS, TX_PULSE_FREQ_16MHZ, TX_PREAMBLE_LEN_1024};
const byte DW1000Class::MODE_SHORTDATA_FAST_ACCURACY[] = {TRX_RATE_6800KBPS, TX_PULSE_FREQ_64MHZ, TX_PREAMBLE_LEN_128};
const byte DW1000Class::MODE_LONGDATA_FAST_ACCURACY[] = {TRX_RATE_6800KBPS, TX_PULSE_FREQ_64MHZ, TX_PREAMBLE_LEN_1024};
const byte DW1000Class::MODE_LONGDATA_RANGE_ACCURACY[] = {TRX_RATE_110KBPS, TX_PULSE_FREQ_64MHZ, TX_PREAMBLE_LEN_2048};
// range bias tables (500 MHz in [mm] and 900 MHz in [2mm] - to fit into bytes)
const byte DW1000Class::BIAS_500_16[] = {198, 187, 179, 163, 143, 127, 109, 84, 59, 31, 0, 36, 65, 84, 97, 106, 110, 112};
const byte DW1000Class::BIAS_500_64[] = {110, 105, 100, 93, 82, 69, 51, 27, 0, 21, 35, 42, 49, 62, 71, 76, 81, 86};
const byte DW1000Class::BIAS_900_16[] = {137, 122, 105, 88, 69, 47, 25, 0, 21, 48, 79, 105, 127, 147, 160, 169, 178, 197};
const byte DW1000Class::BIAS_900_64[] = {147, 133, 117, 99, 75, 50, 29, 0, 24, 45, 63, 76, 87, 98, 116, 122, 132, 142};
// SPI settings
const SPISettings DW1000Class::_fastSPI = SPISettings(16000000L, MSBFIRST, SPI_MODE0);
const SPISettings DW1000Class::_slowSPI = SPISettings(2000000L, MSBFIRST, SPI_MODE0);
const SPISettings* DW1000Class::_currentSPI = &_fastSPI;
/* ###########################################################################
* #### Init and end #######################################################
* ######################################################################### */
void DW1000Class::end() {
SPI.end();
}
void DW1000Class::select(int ss) {
reselect(ss);
// try locking clock at PLL speed (should be done already,
// but just to be sure)
enableClock(AUTO_CLOCK);
delay(5);
// reset chip (either soft or hard)
if(_rst > 0) {
// dw1000 data sheet v2.08 §5.6.1 page 20, the RSTn pin should not be driven high but left floating.
pinMode(_rst, INPUT);
}
reset();
// default network and node id
writeValueToBytes(_networkAndAddress, 0xFF, LEN_PANADR);
writeNetworkIdAndDeviceAddress();
// default system configuration
memset(_syscfg, 0, LEN_SYS_CFG);
setDoubleBuffering(false);
setInterruptPolarity(true);
writeSystemConfigurationRegister();
// default interrupt mask, i.e. no interrupts
clearInterrupts();
writeSystemEventMaskRegister();
// load LDE micro-code
enableClock(XTI_CLOCK);
delay(5);
manageLDE();
delay(5);
enableClock(AUTO_CLOCK);
delay(5);
}
void DW1000Class::reselect(int ss) {
_ss = ss;
pinMode(_ss, OUTPUT);
digitalWrite(_ss, HIGH);
}
void DW1000Class::begin(int irq) {
begin(irq, -1);
}
void DW1000Class::begin(int irq, int rst) {
// generous initial init/wake-up-idle delay
delay(5);
// start SPI
SPI.begin();
SPI.usingInterrupt(digitalPinToInterrupt(irq));
// pin and basic member setup
_rst = rst;
_irq = irq;
_deviceMode = IDLE_MODE;
// attach interrupt
// TODO throw error if pin is not a interrupt pin
attachInterrupt(digitalPinToInterrupt(_irq), DW1000Class::handleInterrupt, RISING);
}
void DW1000Class::manageLDE() {
// transfer any ldo tune values
byte ldoTune[LEN_OTP_RDAT];
readBytesOTP(0x04, ldoTune); // TODO #define
if(ldoTune[0] != 0) {
// TODO tuning available, copy over to RAM: use OTP_LDO bit
}
// tell the chip to load the LDE microcode
// TODO remove clock-related code (PMSC_CTRL) as handled separately
byte pmscctrl0[LEN_PMSC_CTRL0];
byte otpctrl[LEN_OTP_CTRL];
memset(pmscctrl0, 0, LEN_PMSC_CTRL0);
memset(otpctrl, 0, LEN_OTP_CTRL);
readBytes(PMSC, PMSC_CTRL0_SUB, pmscctrl0, LEN_PMSC_CTRL0);
readBytes(OTP_IF, OTP_CTRL_SUB, otpctrl, LEN_OTP_CTRL);
pmscctrl0[0] = 0x01;
pmscctrl0[1] = 0x03;
otpctrl[0] = 0x00;
otpctrl[1] = 0x80;
writeBytes(PMSC, PMSC_CTRL0_SUB, pmscctrl0, LEN_PMSC_CTRL0);
writeBytes(OTP_IF, OTP_CTRL_SUB, otpctrl, LEN_OTP_CTRL);
delay(5);
pmscctrl0[0] = 0x00;
pmscctrl0[1] = 0x02;
writeBytes(PMSC, PMSC_CTRL0_SUB, pmscctrl0, LEN_PMSC_CTRL0);
}
void DW1000Class::enableClock(byte clock) {
byte pmscctrl0[LEN_PMSC_CTRL0];
memset(pmscctrl0, 0, LEN_PMSC_CTRL0);
readBytes(PMSC, PMSC_CTRL0_SUB, pmscctrl0, LEN_PMSC_CTRL0);
if(clock == AUTO_CLOCK) {
_currentSPI = &_fastSPI;
pmscctrl0[0] = AUTO_CLOCK;
pmscctrl0[1] &= 0xFE;
} else if(clock == XTI_CLOCK) {
_currentSPI = &_slowSPI;
pmscctrl0[0] &= 0xFC;
pmscctrl0[0] |= XTI_CLOCK;
} else if(clock == PLL_CLOCK) {
_currentSPI = &_fastSPI;
pmscctrl0[0] &= 0xFC;
pmscctrl0[0] |= PLL_CLOCK;
} else {
// TODO deliver proper warning
}
writeBytes(PMSC, PMSC_CTRL0_SUB, pmscctrl0, 1);
writeBytes(PMSC, PMSC_CTRL0_SUB, pmscctrl0, LEN_PMSC_CTRL0);
}
void DW1000Class::reset() {
if(_rst < 0) {
softReset();
} else {
// dw1000 data sheet v2.08 §5.6.1 page 20, the RSTn pin should not be driven high but left floating.
pinMode(_rst, OUTPUT);
digitalWrite(_rst, LOW);
delay(2); // dw1000 data sheet v2.08 §5.6.1 page 20: nominal 50ns, to be safe take more time
pinMode(_rst, INPUT);
delay(10); // dwm1000 data sheet v1.2 page 5: nominal 3 ms, to be safe take more time
// force into idle mode (although it should be already after reset)
idle();
}
}
void DW1000Class::softReset() {
byte pmscctrl0[LEN_PMSC_CTRL0];
readBytes(PMSC, PMSC_CTRL0_SUB, pmscctrl0, LEN_PMSC_CTRL0);
pmscctrl0[0] = 0x01;
writeBytes(PMSC, PMSC_CTRL0_SUB, pmscctrl0, LEN_PMSC_CTRL0);
pmscctrl0[3] = 0x00;
writeBytes(PMSC, PMSC_CTRL0_SUB, pmscctrl0, LEN_PMSC_CTRL0);
delay(10);
pmscctrl0[0] = 0x00;
pmscctrl0[3] = 0xF0;
writeBytes(PMSC, PMSC_CTRL0_SUB, pmscctrl0, LEN_PMSC_CTRL0);
// force into idle mode
idle();
}
void DW1000Class::enableMode(const byte mode[]) {
setDataRate(mode[0]);
setPulseFrequency(mode[1]);
setPreambleLength(mode[2]);
// TODO add channel and code to mode tuples
// TODO add channel and code settings with checks (see Table 58)
setChannel(CHANNEL_5);
if(mode[1] == TX_PULSE_FREQ_16MHZ) {
setPreambleCode(PREAMBLE_CODE_16MHZ_4);
} else {
setPreambleCode(PREAMBLE_CODE_64MHZ_10);
}
}
void DW1000Class::tune() {
// these registers are going to be tuned/configured
byte agctune1[LEN_AGC_TUNE1];
byte agctune2[LEN_AGC_TUNE2];
byte agctune3[LEN_AGC_TUNE3];
byte drxtune0b[LEN_DRX_TUNE0b];
byte drxtune1a[LEN_DRX_TUNE1a];
byte drxtune1b[LEN_DRX_TUNE1b];
byte drxtune2[LEN_DRX_TUNE2];
byte drxtune4H[LEN_DRX_TUNE4H];
byte ldecfg1[LEN_LDE_CFG1];
byte ldecfg2[LEN_LDE_CFG2];
byte lderepc[LEN_LDE_REPC];
byte txpower[LEN_TX_POWER];
byte rfrxctrlh[LEN_RF_RXCTRLH];
byte rftxctrl[LEN_RF_TXCTRL];
byte tcpgdelay[LEN_TC_PGDELAY];
byte fspllcfg[LEN_FS_PLLCFG];
byte fsplltune[LEN_FS_PLLTUNE];
byte fsxtalt[LEN_FS_XTALT];
// AGC_TUNE1
if(_pulseFrequency == TX_PULSE_FREQ_16MHZ) {
writeValueToBytes(agctune1, 0x8870, LEN_AGC_TUNE1);
} else if(_pulseFrequency == TX_PULSE_FREQ_64MHZ) {
writeValueToBytes(agctune1, 0x889B, LEN_AGC_TUNE1);
} else {
// TODO proper error/warning handling
}
// AGC_TUNE2
writeValueToBytes(agctune2, 0x2502A907L, LEN_AGC_TUNE2);
// AGC_TUNE3
writeValueToBytes(agctune3, 0x0035, LEN_AGC_TUNE3);
// DRX_TUNE0b (already optimized according to Table 20 of user manual)
if(_dataRate == TRX_RATE_110KBPS) {
writeValueToBytes(drxtune0b, 0x0016, LEN_DRX_TUNE0b);
} else if(_dataRate == TRX_RATE_850KBPS) {
writeValueToBytes(drxtune0b, 0x0006, LEN_DRX_TUNE0b);
} else if(_dataRate == TRX_RATE_6800KBPS) {
writeValueToBytes(drxtune0b, 0x0001, LEN_DRX_TUNE0b);
} else {
// TODO proper error/warning handling
}
// DRX_TUNE1a
if(_pulseFrequency == TX_PULSE_FREQ_16MHZ) {
writeValueToBytes(drxtune1a, 0x0087, LEN_DRX_TUNE1a);
} else if(_pulseFrequency == TX_PULSE_FREQ_64MHZ) {
writeValueToBytes(drxtune1a, 0x008D, LEN_DRX_TUNE1a);
} else {
// TODO proper error/warning handling
}
// DRX_TUNE1b
if(_preambleLength == TX_PREAMBLE_LEN_1536 || _preambleLength == TX_PREAMBLE_LEN_2048 ||
_preambleLength == TX_PREAMBLE_LEN_4096) {
if(_dataRate == TRX_RATE_110KBPS) {
writeValueToBytes(drxtune1b, 0x0064, LEN_DRX_TUNE1b);
} else {
// TODO proper error/warning handling
}
} else if(_preambleLength != TX_PREAMBLE_LEN_64) {
if(_dataRate == TRX_RATE_850KBPS || _dataRate == TRX_RATE_6800KBPS) {
writeValueToBytes(drxtune1b, 0x0020, LEN_DRX_TUNE1b);
} else {
// TODO proper error/warning handling
}
} else {
if(_dataRate == TRX_RATE_6800KBPS) {
writeValueToBytes(drxtune1b, 0x0010, LEN_DRX_TUNE1b);
} else {
// TODO proper error/warning handling
}
}
// DRX_TUNE2
if(_pacSize == PAC_SIZE_8) {
if(_pulseFrequency == TX_PULSE_FREQ_16MHZ) {
writeValueToBytes(drxtune2, 0x311A002DL, LEN_DRX_TUNE2);
} else if(_pulseFrequency == TX_PULSE_FREQ_64MHZ) {
writeValueToBytes(drxtune2, 0x313B006BL, LEN_DRX_TUNE2);
} else {
// TODO proper error/warning handling
}
} else if(_pacSize == PAC_SIZE_16) {
if(_pulseFrequency == TX_PULSE_FREQ_16MHZ) {
writeValueToBytes(drxtune2, 0x331A0052L, LEN_DRX_TUNE2);
} else if(_pulseFrequency == TX_PULSE_FREQ_64MHZ) {
writeValueToBytes(drxtune2, 0x333B00BEL, LEN_DRX_TUNE2);
} else {
// TODO proper error/warning handling
}
} else if(_pacSize == PAC_SIZE_32) {
if(_pulseFrequency == TX_PULSE_FREQ_16MHZ) {
writeValueToBytes(drxtune2, 0x351A009AL, LEN_DRX_TUNE2);
} else if(_pulseFrequency == TX_PULSE_FREQ_64MHZ) {
writeValueToBytes(drxtune2, 0x353B015EL, LEN_DRX_TUNE2);
} else {
// TODO proper error/warning handling
}
} else if(_pacSize == PAC_SIZE_64) {
if(_pulseFrequency == TX_PULSE_FREQ_16MHZ) {
writeValueToBytes(drxtune2, 0x371A011DL, LEN_DRX_TUNE2);
} else if(_pulseFrequency == TX_PULSE_FREQ_64MHZ) {
writeValueToBytes(drxtune2, 0x373B0296L, LEN_DRX_TUNE2);
} else {
// TODO proper error/warning handling
}
} else {
// TODO proper error/warning handling
}
// DRX_TUNE4H
if(_preambleLength == TX_PREAMBLE_LEN_64) {
writeValueToBytes(drxtune4H, 0x0010, LEN_DRX_TUNE4H);
} else {
writeValueToBytes(drxtune4H, 0x0028, LEN_DRX_TUNE4H);
}
// RF_RXCTRLH
if(_channel != CHANNEL_4 && _channel != CHANNEL_7) {
writeValueToBytes(rfrxctrlh, 0xD8, LEN_RF_RXCTRLH);
} else {
writeValueToBytes(rfrxctrlh, 0xBC, LEN_RF_RXCTRLH);
}
// RX_TXCTRL
if(_channel == CHANNEL_1) {
writeValueToBytes(rftxctrl, 0x00005C40L, LEN_RF_TXCTRL);
} else if(_channel == CHANNEL_2) {
writeValueToBytes(rftxctrl, 0x00045CA0L, LEN_RF_TXCTRL);
} else if(_channel == CHANNEL_3) {
writeValueToBytes(rftxctrl, 0x00086CC0L, LEN_RF_TXCTRL);
} else if(_channel == CHANNEL_4) {
writeValueToBytes(rftxctrl, 0x00045C80L, LEN_RF_TXCTRL);
} else if(_channel == CHANNEL_5) {
writeValueToBytes(rftxctrl, 0x001E3FE0L, LEN_RF_TXCTRL);
} else if(_channel == CHANNEL_7) {
writeValueToBytes(rftxctrl, 0x001E7DE0L, LEN_RF_TXCTRL);
} else {
// TODO proper error/warning handling
}
// TC_PGDELAY
if(_channel == CHANNEL_1) {
writeValueToBytes(tcpgdelay, 0xC9, LEN_TC_PGDELAY);
} else if(_channel == CHANNEL_2) {
writeValueToBytes(tcpgdelay, 0xC2, LEN_TC_PGDELAY);
} else if(_channel == CHANNEL_3) {
writeValueToBytes(tcpgdelay, 0xC5, LEN_TC_PGDELAY);
} else if(_channel == CHANNEL_4) {
writeValueToBytes(tcpgdelay, 0x95, LEN_TC_PGDELAY);
} else if(_channel == CHANNEL_5) {
writeValueToBytes(tcpgdelay, 0xC0, LEN_TC_PGDELAY);
} else if(_channel == CHANNEL_7) {
writeValueToBytes(tcpgdelay, 0x93, LEN_TC_PGDELAY);
} else {
// TODO proper error/warning handling
}
// FS_PLLCFG and FS_PLLTUNE
if(_channel == CHANNEL_1) {
writeValueToBytes(fspllcfg, 0x09000407L, LEN_FS_PLLCFG);
writeValueToBytes(fsplltune, 0x1E, LEN_FS_PLLTUNE);
} else if(_channel == CHANNEL_2 || _channel == CHANNEL_4) {
writeValueToBytes(fspllcfg, 0x08400508L, LEN_FS_PLLCFG);
writeValueToBytes(fsplltune, 0x26, LEN_FS_PLLTUNE);
} else if(_channel == CHANNEL_3) {
writeValueToBytes(fspllcfg, 0x08401009L, LEN_FS_PLLCFG);
writeValueToBytes(fsplltune, 0x5E, LEN_FS_PLLTUNE);
} else if(_channel == CHANNEL_5 || _channel == CHANNEL_7) {
writeValueToBytes(fspllcfg, 0x0800041DL, LEN_FS_PLLCFG);
writeValueToBytes(fsplltune, 0xA6, LEN_FS_PLLTUNE);
} else {
// TODO proper error/warning handling
}
// LDE_CFG1
writeValueToBytes(ldecfg1, 0xD, LEN_LDE_CFG1);
// LDE_CFG2
if(_pulseFrequency == TX_PULSE_FREQ_16MHZ) {
writeValueToBytes(ldecfg2, 0x1607, LEN_LDE_CFG2);
} else if(_pulseFrequency == TX_PULSE_FREQ_64MHZ) {
writeValueToBytes(ldecfg2, 0x0607, LEN_LDE_CFG2);
} else {
// TODO proper error/warning handling
}
// LDE_REPC
if(_preambleCode == PREAMBLE_CODE_16MHZ_1 || _preambleCode == PREAMBLE_CODE_16MHZ_2) {
if(_dataRate == TRX_RATE_110KBPS) {
writeValueToBytes(lderepc, ((0x5998 >> 3) & 0xFFFF), LEN_LDE_REPC);
} else {
writeValueToBytes(lderepc, 0x5998, LEN_LDE_REPC);
}
} else if(_preambleCode == PREAMBLE_CODE_16MHZ_3 || _preambleCode == PREAMBLE_CODE_16MHZ_8) {
if(_dataRate == TRX_RATE_110KBPS) {
writeValueToBytes(lderepc, ((0x51EA >> 3) & 0xFFFF), LEN_LDE_REPC);
} else {
writeValueToBytes(lderepc, 0x51EA, LEN_LDE_REPC);
}
} else if(_preambleCode == PREAMBLE_CODE_16MHZ_4) {
if(_dataRate == TRX_RATE_110KBPS) {
writeValueToBytes(lderepc, ((0x428E >> 3) & 0xFFFF), LEN_LDE_REPC);
} else {
writeValueToBytes(lderepc, 0x428E, LEN_LDE_REPC);
}
} else if(_preambleCode == PREAMBLE_CODE_16MHZ_5) {
if(_dataRate == TRX_RATE_110KBPS) {
writeValueToBytes(lderepc, ((0x451E >> 3) & 0xFFFF), LEN_LDE_REPC);
} else {
writeValueToBytes(lderepc, 0x451E, LEN_LDE_REPC);
}
} else if(_preambleCode == PREAMBLE_CODE_16MHZ_6) {
if(_dataRate == TRX_RATE_110KBPS) {
writeValueToBytes(lderepc, ((0x2E14 >> 3) & 0xFFFF), LEN_LDE_REPC);
} else {
writeValueToBytes(lderepc, 0x2E14, LEN_LDE_REPC);
}
} else if(_preambleCode == PREAMBLE_CODE_16MHZ_7) {
if(_dataRate == TRX_RATE_110KBPS) {
writeValueToBytes(lderepc, ((0x8000 >> 3) & 0xFFFF), LEN_LDE_REPC);
} else {
writeValueToBytes(lderepc, 0x8000, LEN_LDE_REPC);
}
} else if(_preambleCode == PREAMBLE_CODE_64MHZ_9) {
if(_dataRate == TRX_RATE_110KBPS) {
writeValueToBytes(lderepc, ((0x28F4 >> 3) & 0xFFFF), LEN_LDE_REPC);
} else {
writeValueToBytes(lderepc, 0x28F4, LEN_LDE_REPC);
}
} else if(_preambleCode == PREAMBLE_CODE_64MHZ_10 || _preambleCode == PREAMBLE_CODE_64MHZ_17) {
if(_dataRate == TRX_RATE_110KBPS) {
writeValueToBytes(lderepc, ((0x3332 >> 3) & 0xFFFF), LEN_LDE_REPC);
} else {
writeValueToBytes(lderepc, 0x3332, LEN_LDE_REPC);
}
} else if(_preambleCode == PREAMBLE_CODE_64MHZ_11) {
if(_dataRate == TRX_RATE_110KBPS) {
writeValueToBytes(lderepc, ((0x3AE0 >> 3) & 0xFFFF), LEN_LDE_REPC);
} else {
writeValueToBytes(lderepc, 0x3AE0, LEN_LDE_REPC);
}
} else if(_preambleCode == PREAMBLE_CODE_64MHZ_12) {
if(_dataRate == TRX_RATE_110KBPS) {
writeValueToBytes(lderepc, ((0x3D70 >> 3) & 0xFFFF), LEN_LDE_REPC);
} else {
writeValueToBytes(lderepc, 0x3D70, LEN_LDE_REPC);
}
} else if(_preambleCode == PREAMBLE_CODE_64MHZ_18 || _preambleCode == PREAMBLE_CODE_64MHZ_19) {
if(_dataRate == TRX_RATE_110KBPS) {
writeValueToBytes(lderepc, ((0x35C2 >> 3) & 0xFFFF), LEN_LDE_REPC);
} else {
writeValueToBytes(lderepc, 0x35C2, LEN_LDE_REPC);
}
} else if(_preambleCode == PREAMBLE_CODE_64MHZ_20) {
if(_dataRate == TRX_RATE_110KBPS) {
writeValueToBytes(lderepc, ((0x47AE >> 3) & 0xFFFF), LEN_LDE_REPC);
} else {
writeValueToBytes(lderepc, 0x47AE, LEN_LDE_REPC);
}
} else {
// TODO proper error/warning handling
}
// TX_POWER (enabled smart transmit power control)
if(_channel == CHANNEL_1 || _channel == CHANNEL_2) {
if(_pulseFrequency == TX_PULSE_FREQ_16MHZ) {
if(_smartPower) {
writeValueToBytes(txpower, 0x15355575L, LEN_TX_POWER);
} else {
writeValueToBytes(txpower, 0x75757575L, LEN_TX_POWER);
}
} else if(_pulseFrequency == TX_PULSE_FREQ_64MHZ) {
if(_smartPower) {
writeValueToBytes(txpower, 0x07274767L, LEN_TX_POWER);
} else {
writeValueToBytes(txpower, 0x67676767L, LEN_TX_POWER);
}
} else {
// TODO proper error/warning handling
}
} else if(_channel == CHANNEL_3) {
if(_pulseFrequency == TX_PULSE_FREQ_16MHZ) {
if(_smartPower) {
writeValueToBytes(txpower, 0x0F2F4F6FL, LEN_TX_POWER);
} else {
writeValueToBytes(txpower, 0x6F6F6F6FL, LEN_TX_POWER);
}
} else if(_pulseFrequency == TX_PULSE_FREQ_64MHZ) {
if(_smartPower) {
writeValueToBytes(txpower, 0x2B4B6B8BL, LEN_TX_POWER);
} else {
writeValueToBytes(txpower, 0x8B8B8B8BL, LEN_TX_POWER);
}
} else {
// TODO proper error/warning handling
}
} else if(_channel == CHANNEL_4) {
if(_pulseFrequency == TX_PULSE_FREQ_16MHZ) {
if(_smartPower) {
writeValueToBytes(txpower, 0x1F1F3F5FL, LEN_TX_POWER);
} else {
writeValueToBytes(txpower, 0x5F5F5F5FL, LEN_TX_POWER);
}
} else if(_pulseFrequency == TX_PULSE_FREQ_64MHZ) {
if(_smartPower) {
writeValueToBytes(txpower, 0x3A5A7A9AL, LEN_TX_POWER);
} else {
writeValueToBytes(txpower, 0x9A9A9A9AL, LEN_TX_POWER);
}
} else {
// TODO proper error/warning handling
}
} else if(_channel == CHANNEL_5) {
if(_pulseFrequency == TX_PULSE_FREQ_16MHZ) {
if(_smartPower) {
writeValueToBytes(txpower, 0x0E082848L, LEN_TX_POWER);
} else {
writeValueToBytes(txpower, 0x48484848L, LEN_TX_POWER);
}
} else if(_pulseFrequency == TX_PULSE_FREQ_64MHZ) {
if(_smartPower) {
writeValueToBytes(txpower, 0x25456585L, LEN_TX_POWER);
} else {
writeValueToBytes(txpower, 0x85858585L, LEN_TX_POWER);
}
} else {
// TODO proper error/warning handling
}
} else if(_channel == CHANNEL_7) {
if(_pulseFrequency == TX_PULSE_FREQ_16MHZ) {
if(_smartPower) {
writeValueToBytes(txpower, 0x32527292L, LEN_TX_POWER);
} else {
writeValueToBytes(txpower, 0x92929292L, LEN_TX_POWER);
}
} else if(_pulseFrequency == TX_PULSE_FREQ_64MHZ) {
if(_smartPower) {
writeValueToBytes(txpower, 0x5171B1D1L, LEN_TX_POWER);
} else {
writeValueToBytes(txpower, 0xD1D1D1D1L, LEN_TX_POWER);
}
} else {
// TODO proper error/warning handling
}
} else {
// TODO proper error/warning handling
}
// mid range XTAL trim (TODO here we assume no calibration data available in OTP)
//writeValueToBytes(fsxtalt, 0x60, LEN_FS_XTALT);
// write configuration back to chip
writeBytes(AGC_TUNE, AGC_TUNE1_SUB, agctune1, LEN_AGC_TUNE1);
writeBytes(AGC_TUNE, AGC_TUNE2_SUB, agctune2, LEN_AGC_TUNE2);
writeBytes(AGC_TUNE, AGC_TUNE3_SUB, agctune3, LEN_AGC_TUNE3);
writeBytes(DRX_TUNE, DRX_TUNE0b_SUB, drxtune0b, LEN_DRX_TUNE0b);
writeBytes(DRX_TUNE, DRX_TUNE1a_SUB, drxtune1a, LEN_DRX_TUNE1a);
writeBytes(DRX_TUNE, DRX_TUNE1b_SUB, drxtune1b, LEN_DRX_TUNE1b);
writeBytes(DRX_TUNE, DRX_TUNE2_SUB, drxtune2, LEN_DRX_TUNE2);
writeBytes(DRX_TUNE, DRX_TUNE4H_SUB, drxtune4H, LEN_DRX_TUNE4H);
writeBytes(LDE_IF, LDE_CFG1_SUB, ldecfg1, LEN_LDE_CFG1);
writeBytes(LDE_IF, LDE_CFG2_SUB, ldecfg2, LEN_LDE_CFG2);
writeBytes(LDE_IF, LDE_REPC_SUB, lderepc, LEN_LDE_REPC);
writeBytes(TX_POWER, NO_SUB, txpower, LEN_TX_POWER);
writeBytes(RF_CONF, RF_RXCTRLH_SUB, rfrxctrlh, LEN_RF_RXCTRLH);
writeBytes(RF_CONF, RF_TXCTRL_SUB, rftxctrl, LEN_RF_TXCTRL);
writeBytes(TX_CAL, TC_PGDELAY_SUB, tcpgdelay, LEN_TC_PGDELAY);
writeBytes(FS_CTRL, FS_PLLTUNE_SUB, fsplltune, LEN_FS_PLLTUNE);
writeBytes(FS_CTRL, FS_PLLCFG_SUB, fspllcfg, LEN_FS_PLLCFG);
//writeBytes(FS_CTRL, FS_XTALT_SUB, fsxtalt, LEN_FS_XTALT);
}
/* ###########################################################################
* #### Interrupt handling ###################################################
* ######################################################################### */
void DW1000Class::handleInterrupt() {
// read current status and handle via callbacks
readSystemEventStatusRegister();
if(isClockProblem() /* TODO and others */ && _handleError != 0) {
(*_handleError)();
}
if(isTransmitDone() && _handleSent != 0) {
(*_handleSent)();
clearTransmitStatus();
}
if(isReceiveTimestampAvailable() && _handleReceiveTimestampAvailable != 0) {
(*_handleReceiveTimestampAvailable)();
clearReceiveTimestampAvailableStatus();
}
if(isReceiveFailed() && _handleReceiveFailed != 0) {
(*_handleReceiveFailed)();
clearReceiveStatus();
if(_permanentReceive) {
newReceive();
startReceive();
}
} else if(isReceiveTimeout() && _handleReceiveTimeout != 0) {
(*_handleReceiveTimeout)();
clearReceiveStatus();
if(_permanentReceive) {
newReceive();
startReceive();
}
} else if(isReceiveDone() && _handleReceived != 0) {
(*_handleReceived)();
clearReceiveStatus();
if(_permanentReceive) {
newReceive();
startReceive();
}
}
// clear all status that is left unhandled
clearAllStatus();
}
/* ###########################################################################
* #### Pretty printed device information ####################################
* ######################################################################### */
void DW1000Class::getPrintableDeviceIdentifier(char msgBuffer[]) {
byte data[LEN_DEV_ID];
readBytes(DEV_ID, NO_SUB, data, LEN_DEV_ID);
sprintf(msgBuffer, "DECA - model: %d, version: %d, revision: %d",
data[1], (data[0] >> 4) & 0x0F, data[0] & 0x0F);
}
void DW1000Class::getPrintableExtendedUniqueIdentifier(char msgBuffer[]) {
byte data[LEN_EUI];
readBytes(EUI, NO_SUB, data, LEN_EUI);
sprintf(msgBuffer, "%02X:%02X:%02X:%02X:%02X:%02X:%02X:%02X",
data[7], data[6], data[5], data[4], data[3], data[2], data[1], data[0]);
}
void DW1000Class::getPrintableNetworkIdAndShortAddress(char msgBuffer[]) {
byte data[LEN_PANADR];
readBytes(PANADR, NO_SUB, data, LEN_PANADR);
sprintf(msgBuffer, "PAN: %02X, Short Address: %02X",
(unsigned int)((data[3] << 8) | data[2]), (unsigned int)((data[1] << 8) | data[0]));
}
void DW1000Class::getPrintableDeviceMode(char msgBuffer[]) {
unsigned short prf;
unsigned int plen;
unsigned int dr;
unsigned short ch;
unsigned short pcode;
if(_pulseFrequency == TX_PULSE_FREQ_16MHZ) {
prf = 16;
} else {
prf = 64;
}
if(_preambleLength == TX_PREAMBLE_LEN_64) {
plen = 64;
} else if(_preambleLength == TX_PREAMBLE_LEN_128) {
plen = 128;
} else if(_preambleLength == TX_PREAMBLE_LEN_256) {
plen = 256;
} else if(_preambleLength == TX_PREAMBLE_LEN_512) {
plen = 512;
} else if(_preambleLength == TX_PREAMBLE_LEN_1024) {
plen = 1024;
} else if(_preambleLength == TX_PREAMBLE_LEN_1536) {
plen = 1536;
} else if(_preambleLength == TX_PREAMBLE_LEN_2048) {
plen = 2048;
} else {
plen = 4096;
}
if(_dataRate == TRX_RATE_110KBPS) {
dr = 110;
} else if(_dataRate == TRX_RATE_850KBPS) {
dr = 850;
} else {
dr = 6800;
}
ch = (short)_channel;
pcode = (short)_preambleCode;
sprintf(msgBuffer, "Data rate: %u kb/s, PRF: %u MHz, Preamble: %u symbols (code #%u), Channel: #%u", dr, prf, plen, pcode, ch);
}
/* ###########################################################################
* #### DW1000 register read/write ###########################################
* ######################################################################### */
void DW1000Class::readSystemConfigurationRegister() {
readBytes(SYS_CFG, NO_SUB, _syscfg, LEN_SYS_CFG);
}
void DW1000Class::writeSystemConfigurationRegister() {
writeBytes(SYS_CFG, NO_SUB, _syscfg, LEN_SYS_CFG);
}
void DW1000Class::readSystemEventStatusRegister() {
readBytes(SYS_STATUS, NO_SUB, _sysstatus, LEN_SYS_STATUS);
}
void DW1000Class::readNetworkIdAndDeviceAddress() {
readBytes(PANADR, NO_SUB, _networkAndAddress, LEN_PANADR);
}
void DW1000Class::writeNetworkIdAndDeviceAddress() {
writeBytes(PANADR, NO_SUB, _networkAndAddress, LEN_PANADR);
}
void DW1000Class::readSystemEventMaskRegister() {
readBytes(SYS_MASK, NO_SUB, _sysmask, LEN_SYS_MASK);
}
void DW1000Class::writeSystemEventMaskRegister() {
writeBytes(SYS_MASK, NO_SUB, _sysmask, LEN_SYS_MASK);
}
void DW1000Class::readChannelControlRegister() {
readBytes(CHAN_CTRL, NO_SUB, _chanctrl, LEN_CHAN_CTRL);
}
void DW1000Class::writeChannelControlRegister() {
writeBytes(CHAN_CTRL, NO_SUB, _chanctrl, LEN_CHAN_CTRL);
}
void DW1000Class::readTransmitFrameControlRegister() {
readBytes(TX_FCTRL, NO_SUB, _txfctrl, LEN_TX_FCTRL);
}
void DW1000Class::writeTransmitFrameControlRegister() {
writeBytes(TX_FCTRL, NO_SUB, _txfctrl, LEN_TX_FCTRL);
}
/* ###########################################################################
* #### DW1000 operation functions ###########################################
* ######################################################################### */
void DW1000Class::setNetworkId(unsigned int val) {
_networkAndAddress[2] = (byte)(val & 0xFF);
_networkAndAddress[3] = (byte)((val >> 8) & 0xFF);
}
void DW1000Class::setDeviceAddress(unsigned int val) {
_networkAndAddress[0] = (byte)(val & 0xFF);
_networkAndAddress[1] = (byte)((val >> 8) & 0xFF);
}
int DW1000Class::nibbleFromChar(char c) {
if(c >= '0' && c <= '9') {
return c-'0';
}
if(c >= 'a' && c <= 'f') {
return c-'a'+10;
}
if(c >= 'A' && c <= 'F') {
return c-'A'+10;
}
return 255;
}
void DW1000Class::convertToByte(char string[], byte* bytes) {
byte eui_byte[LEN_EUI];
// we fill it with the char array under the form of "AA:FF:1C:...."
for(int i = 0; i < LEN_EUI; i++) {
eui_byte[i] = (nibbleFromChar(string[i*3]) << 4)+nibbleFromChar(string[i*3+1]);
}
memcpy(bytes, eui_byte, LEN_EUI);
}
void DW1000Class::setEUI(char eui[]) {
byte eui_byte[LEN_EUI];
convertToByte(eui, eui_byte);
setEUI(eui_byte);
}
void DW1000Class::setEUI(byte eui[]) {
//we reverse the address->
byte reverseEUI[8];
int size = 8;
for(int i = 0; i < size; i++) {
*(reverseEUI+i) = *(eui+size-i-1);
}
writeBytes(EUI, NO_SUB, reverseEUI, LEN_EUI);
}
//Frame Filtering BIT in the SYS_CFG register
void DW1000Class::setFrameFilter(boolean val) {
setBit(_syscfg, LEN_SYS_CFG, FFEN_BIT, val);
}
void DW1000Class::setFrameFilterBehaveCoordinator(boolean val) {
setBit(_syscfg, LEN_SYS_CFG, FFBC_BIT, val);
}
void DW1000Class::setFrameFilterAllowBeacon(boolean val) {
setBit(_syscfg, LEN_SYS_CFG, FFAB_BIT, val);
}
void DW1000Class::setFrameFilterAllowData(boolean val) {
setBit(_syscfg, LEN_SYS_CFG, FFAD_BIT, val);
}
void DW1000Class::setFrameFilterAllowAcknowledgement(boolean val) {
setBit(_syscfg, LEN_SYS_CFG, FFAA_BIT, val);
}
void DW1000Class::setFrameFilterAllowMAC(boolean val) {
setBit(_syscfg, LEN_SYS_CFG, FFAM_BIT, val);
}
void DW1000Class::setFrameFilterAllowReserved(boolean val) {
setBit(_syscfg, LEN_SYS_CFG, FFAR_BIT, val);
}
void DW1000Class::setDoubleBuffering(boolean val) {
setBit(_syscfg, LEN_SYS_CFG, DIS_DRXB_BIT, !val);
}
void DW1000Class::setInterruptPolarity(boolean val) {
setBit(_syscfg, LEN_SYS_CFG, HIRQ_POL_BIT, val);
}
void DW1000Class::setReceiverAutoReenable(boolean val) {
setBit(_syscfg, LEN_SYS_CFG, RXAUTR_BIT, val);
}
void DW1000Class::interruptOnSent(boolean val) {
setBit(_sysmask, LEN_SYS_MASK, TXFRS_BIT, val);
}
void DW1000Class::interruptOnReceived(boolean val) {
setBit(_sysmask, LEN_SYS_MASK, RXDFR_BIT, val);
setBit(_sysmask, LEN_SYS_MASK, RXFCG_BIT, val);
}
void DW1000Class::interruptOnReceiveFailed(boolean val) {
setBit(_sysmask, LEN_SYS_STATUS, LDEERR_BIT, val);
setBit(_sysmask, LEN_SYS_STATUS, RXFCE_BIT, val);
setBit(_sysmask, LEN_SYS_STATUS, RXPHE_BIT, val);
setBit(_sysmask, LEN_SYS_STATUS, RXRFSL_BIT, val);
}
void DW1000Class::interruptOnReceiveTimeout(boolean val) {
setBit(_sysmask, LEN_SYS_MASK, RXRFTO_BIT, val);
}
void DW1000Class::interruptOnReceiveTimestampAvailable(boolean val) {
setBit(_sysmask, LEN_SYS_MASK, LDEDONE_BIT, val);
}
void DW1000Class::interruptOnAutomaticAcknowledgeTrigger(boolean val) {
setBit(_sysmask, LEN_SYS_MASK, AAT_BIT, val);
}
void DW1000Class::clearInterrupts() {
memset(_sysmask, 0, LEN_SYS_MASK);
}
void DW1000Class::idle() {
memset(_sysctrl, 0, LEN_SYS_CTRL);
setBit(_sysctrl, LEN_SYS_CTRL, TRXOFF_BIT, true);
_deviceMode = IDLE_MODE;
writeBytes(SYS_CTRL, NO_SUB, _sysctrl, LEN_SYS_CTRL);
}
void DW1000Class::newReceive() {
idle();
memset(_sysctrl, 0, LEN_SYS_CTRL);
clearReceiveStatus();
_deviceMode = RX_MODE;
}
void DW1000Class::startReceive() {
setBit(_sysctrl, LEN_SYS_CTRL, SFCST_BIT, !_frameCheck);
setBit(_sysctrl, LEN_SYS_CTRL, RXENAB_BIT, true);
writeBytes(SYS_CTRL, NO_SUB, _sysctrl, LEN_SYS_CTRL);
}
void DW1000Class::newTransmit() {
idle();
memset(_sysctrl, 0, LEN_SYS_CTRL);
clearTransmitStatus();
_deviceMode = TX_MODE;
}
void DW1000Class::startTransmit() {
writeTransmitFrameControlRegister();
setBit(_sysctrl, LEN_SYS_CTRL, SFCST_BIT, !_frameCheck);
setBit(_sysctrl, LEN_SYS_CTRL, TXSTRT_BIT, true);
writeBytes(SYS_CTRL, NO_SUB, _sysctrl, LEN_SYS_CTRL);
if(_permanentReceive) {
memset(_sysctrl, 0, LEN_SYS_CTRL);
_deviceMode = RX_MODE;
startReceive();
} else {
_deviceMode = IDLE_MODE;
}
}
void DW1000Class::newConfiguration() {
idle();
readNetworkIdAndDeviceAddress();
readSystemConfigurationRegister();
readChannelControlRegister();
readTransmitFrameControlRegister();
readSystemEventMaskRegister();
}
void DW1000Class::commitConfiguration() {
// write all configurations back to device
writeNetworkIdAndDeviceAddress();
writeSystemConfigurationRegister();
writeChannelControlRegister();
writeTransmitFrameControlRegister();
writeSystemEventMaskRegister();
// tune according to configuration
tune();
// TODO clean up code + antenna delay/calibration API
// TODO setter + check not larger two bytes integer
byte antennaDelayBytes[LEN_STAMP];
writeValueToBytes(antennaDelayBytes, 16384, LEN_STAMP);
_antennaDelay.setTimestamp(antennaDelayBytes);
writeBytes(TX_ANTD, NO_SUB, antennaDelayBytes, LEN_TX_ANTD);
writeBytes(LDE_IF, LDE_RXANTD_SUB, antennaDelayBytes, LEN_LDE_RXANTD);
}
void DW1000Class::waitForResponse(boolean val) {
setBit(_sysctrl, LEN_SYS_CTRL, WAIT4RESP_BIT, val);
}
void DW1000Class::suppressFrameCheck(boolean val) {
_frameCheck = !val;
}
void DW1000Class::useSmartPower(boolean smartPower) {
_smartPower = smartPower;
setBit(_syscfg, LEN_SYS_CFG, DIS_STXP_BIT, !smartPower);
}
DW1000Time DW1000Class::setDelay(const DW1000Time& delay) {
if(_deviceMode == TX_MODE) {
setBit(_sysctrl, LEN_SYS_CTRL, TXDLYS_BIT, true);
} else if(_deviceMode == RX_MODE) {
setBit(_sysctrl, LEN_SYS_CTRL, RXDLYS_BIT, true);
} else {
// in idle, ignore
return DW1000Time();
}
byte delayBytes[5];
DW1000Time futureTime;
getSystemTimestamp(futureTime);
futureTime += delay;
futureTime.getTimestamp(delayBytes);
delayBytes[0] = 0;
delayBytes[1] &= 0xFE;
writeBytes(DX_TIME, NO_SUB, delayBytes, LEN_DX_TIME);
// adjust expected time with configured antenna delay
futureTime.setTimestamp(delayBytes);
futureTime += _antennaDelay;
return futureTime;
}
void DW1000Class::setDataRate(byte rate) {
rate &= 0x03;
_txfctrl[1] &= 0x83;
_txfctrl[1] |= (byte)((rate << 5) & 0xFF);
// special 110kbps flag
if(rate == TRX_RATE_110KBPS) {
setBit(_syscfg, LEN_SYS_CFG, RXM110K_BIT, true);
} else {
setBit(_syscfg, LEN_SYS_CFG, RXM110K_BIT, false);
}
// SFD mode and type (non-configurable, as in Table )
if(rate == TRX_RATE_6800KBPS) {
setBit(_chanctrl, LEN_CHAN_CTRL, DWSFD_BIT, false);
setBit(_chanctrl, LEN_CHAN_CTRL, TNSSFD_BIT, false);
setBit(_chanctrl, LEN_CHAN_CTRL, RNSSFD_BIT, false);
} else {
setBit(_chanctrl, LEN_CHAN_CTRL, DWSFD_BIT, true);
setBit(_chanctrl, LEN_CHAN_CTRL, TNSSFD_BIT, true);
setBit(_chanctrl, LEN_CHAN_CTRL, RNSSFD_BIT, true);
}
byte sfdLength;
if(rate == TRX_RATE_6800KBPS) {
sfdLength = 0x08;
} else if(rate == TRX_RATE_850KBPS) {
sfdLength = 0x10;
} else {
sfdLength = 0x40;
}
writeBytes(USR_SFD, SFD_LENGTH_SUB, &sfdLength, LEN_SFD_LENGTH);
_dataRate = rate;
}
void DW1000Class::setPulseFrequency(byte freq) {
freq &= 0x03;
_txfctrl[2] &= 0xFC;
_txfctrl[2] |= (byte)(freq & 0xFF);
_chanctrl[2] &= 0xF3;
_chanctrl[2] |= (byte)((freq << 2) & 0xFF);
_pulseFrequency = freq;
}
byte DW1000Class::getPulseFrequency() {
return _pulseFrequency;
}
void DW1000Class::setPreambleLength(byte prealen) {
prealen &= 0x0F;
_txfctrl[2] &= 0xC3;
_txfctrl[2] |= (byte)((prealen << 2) & 0xFF);
if(prealen == TX_PREAMBLE_LEN_64 || prealen == TX_PREAMBLE_LEN_128) {
_pacSize = PAC_SIZE_8;
} else if(prealen == TX_PREAMBLE_LEN_256 || prealen == TX_PREAMBLE_LEN_512) {
_pacSize = PAC_SIZE_16;
} else if(prealen == TX_PREAMBLE_LEN_1024) {
_pacSize = PAC_SIZE_32;
} else {
_pacSize = PAC_SIZE_64;
}
_preambleLength = prealen;
}
void DW1000Class::useExtendedFrameLength(boolean val) {
_extendedFrameLength = (val ? FRAME_LENGTH_EXTENDED : FRAME_LENGTH_NORMAL);
_syscfg[2] &= 0xFC;
_syscfg[2] |= _extendedFrameLength;
}
void DW1000Class::receivePermanently(boolean val) {
_permanentReceive = val;
if(val) {
// in case permanent, also reenable receiver once failed
setReceiverAutoReenable(true);
writeSystemConfigurationRegister();
}
}
void DW1000Class::setChannel(byte channel) {
channel &= 0xF;
_chanctrl[0] = ((channel | (channel << 4)) & 0xFF);
_channel = channel;
}
void DW1000Class::setPreambleCode(byte preacode) {
preacode &= 0x1F;
_chanctrl[2] &= 0x3F;
_chanctrl[2] |= ((preacode << 6) & 0xFF);
_chanctrl[3] = 0x00;
_chanctrl[3] = ((((preacode >> 2) & 0x07) | (preacode << 3)) & 0xFF);
_preambleCode = preacode;
}
void DW1000Class::setDefaults() {
if(_deviceMode == TX_MODE) {
} else if(_deviceMode == RX_MODE) {
} else if(_deviceMode == IDLE_MODE) {
useExtendedFrameLength(false);
useSmartPower(false);
suppressFrameCheck(false);
//for global frame filtering
setFrameFilter(false);
/* old defaults with active frame filter - better set filter in every script where you really need it
setFrameFilter(true);
//for data frame (poll, poll_ack, range, range report, range failed) filtering
setFrameFilterAllowData(true);
//for reserved (blink) frame filtering
setFrameFilterAllowReserved(true);
//setFrameFilterAllowMAC(true);
//setFrameFilterAllowBeacon(true);
//setFrameFilterAllowAcknowledgement(true);
*/
interruptOnSent(true);
interruptOnReceived(true);
interruptOnReceiveFailed(true);
interruptOnReceiveTimestampAvailable(false);
interruptOnAutomaticAcknowledgeTrigger(true);
setReceiverAutoReenable(true);
// default mode when powering up the chip
// still explicitly selected for later tuning
enableMode(MODE_LONGDATA_RANGE_LOWPOWER);
}
}
void DW1000Class::setData(byte data[], unsigned int n) {
if(_frameCheck) {
n += 2; // two bytes CRC-16
}
if(n > LEN_EXT_UWB_FRAMES) {
return; // TODO proper error handling: frame/buffer size
}
if(n > LEN_UWB_FRAMES && !_extendedFrameLength) {
return; // TODO proper error handling: frame/buffer size
}
// transmit data and length
writeBytes(TX_BUFFER, NO_SUB, data, n);
_txfctrl[0] = (byte)(n & 0xFF); // 1 byte (regular length + 1 bit)
_txfctrl[1] &= 0xE0;
_txfctrl[1] |= (byte)((n >> 8) & 0x03); // 2 added bits if extended length
}
void DW1000Class::setData(const String& data) {
unsigned int n = data.length()+1;
byte* dataBytes = (byte*)malloc(n);
data.getBytes(dataBytes, n);
setData(dataBytes, n);
free(dataBytes);
}
unsigned int DW1000Class::getDataLength() {
unsigned int len = 0;
if(_deviceMode == TX_MODE) {
// 10 bits of TX frame control register
len = ((((unsigned int)_txfctrl[1] << 8) | (unsigned int)_txfctrl[0]) & 0x03FF);
} else if(_deviceMode == RX_MODE) {
// 10 bits of RX frame control register
byte rxFrameInfo[LEN_RX_FINFO];
readBytes(RX_FINFO, NO_SUB, rxFrameInfo, LEN_RX_FINFO);
len = ((((unsigned int)rxFrameInfo[1] << 8) | (unsigned int)rxFrameInfo[0]) & 0x03FF);
}
if(_frameCheck && len > 2) {
return len-2;
}
return len;
}
void DW1000Class::getData(byte data[], unsigned int n) {
if(n <= 0) {
return;
}
readBytes(RX_BUFFER, NO_SUB, data, n);
}
void DW1000Class::getData(String& data) {
unsigned int i;
unsigned int n = getDataLength(); // number of bytes w/o the two FCS ones
if(n <= 0) { // TODO
return;
}
byte* dataBytes = (byte*)malloc(n);
getData(dataBytes, n);
// clear string
data.remove(0);
data = "";
// append to string
for(i = 0; i < n; i++) {
data += (char)dataBytes[i];
}
free(dataBytes);
}
void DW1000Class::getTransmitTimestamp(DW1000Time& time) {
byte txTimeBytes[LEN_TX_STAMP];
readBytes(TX_TIME, TX_STAMP_SUB, txTimeBytes, LEN_TX_STAMP);
time.setTimestamp(txTimeBytes);
}
void DW1000Class::getReceiveTimestamp(DW1000Time& time) {
byte rxTimeBytes[LEN_RX_STAMP];
readBytes(RX_TIME, RX_STAMP_SUB, rxTimeBytes, LEN_RX_STAMP);
time.setTimestamp(rxTimeBytes);
// correct timestamp (i.e. consider range bias)
correctTimestamp(time);
}
void DW1000Class::correctTimestamp(DW1000Time& timestamp) {
// base line dBm, which is -61, 2 dBm steps, total 18 data points (down to -95 dBm)
float rxPowerBase = -(getReceivePower()+61.0f)*0.5f;
int rxPowerBaseLow = (int)rxPowerBase;
int rxPowerBaseHigh = rxPowerBaseLow+1;
if(rxPowerBaseLow < 0) {
rxPowerBaseLow = 0;
rxPowerBaseHigh = 0;
} else if(rxPowerBaseHigh > 17) {
rxPowerBaseLow = 17;
rxPowerBaseHigh = 17;
}
// select range low/high values from corresponding table
int rangeBiasHigh;
int rangeBiasLow;
if(_channel == CHANNEL_4 || _channel == CHANNEL_7) {
// 900 MHz receiver bandwidth
if(_pulseFrequency == TX_PULSE_FREQ_16MHZ) {
rangeBiasHigh = (rxPowerBaseHigh < BIAS_900_16_ZERO ? -BIAS_900_16[rxPowerBaseHigh] : BIAS_900_16[rxPowerBaseHigh]);
rangeBiasHigh <<= 1;
rangeBiasLow = (rxPowerBaseLow < BIAS_900_16_ZERO ? -BIAS_900_16[rxPowerBaseLow] : BIAS_900_16[rxPowerBaseLow]);
rangeBiasLow <<= 1;
} else if(_pulseFrequency == TX_PULSE_FREQ_64MHZ) {
rangeBiasHigh = (rxPowerBaseHigh < BIAS_900_64_ZERO ? -BIAS_900_64[rxPowerBaseHigh] : BIAS_900_64[rxPowerBaseHigh]);
rangeBiasHigh <<= 1;
rangeBiasLow = (rxPowerBaseLow < BIAS_900_64_ZERO ? -BIAS_900_64[rxPowerBaseLow] : BIAS_900_64[rxPowerBaseLow]);
rangeBiasLow <<= 1;
} else {
// TODO proper error handling
}
} else {
// 500 MHz receiver bandwidth
if(_pulseFrequency == TX_PULSE_FREQ_16MHZ) {
rangeBiasHigh = (rxPowerBaseHigh < BIAS_500_16_ZERO ? -BIAS_500_16[rxPowerBaseHigh] : BIAS_500_16[rxPowerBaseHigh]);
rangeBiasLow = (rxPowerBaseLow < BIAS_500_16_ZERO ? -BIAS_500_16[rxPowerBaseLow] : BIAS_500_16[rxPowerBaseLow]);
} else if(_pulseFrequency == TX_PULSE_FREQ_64MHZ) {
rangeBiasHigh = (rxPowerBaseHigh < BIAS_500_64_ZERO ? -BIAS_500_64[rxPowerBaseHigh] : BIAS_500_64[rxPowerBaseHigh]);
rangeBiasLow = (rxPowerBaseLow < BIAS_500_64_ZERO ? -BIAS_500_64[rxPowerBaseLow] : BIAS_500_64[rxPowerBaseLow]);
} else {
// TODO proper error handling
}
}
// linear interpolation of bias values
float rangeBias = rangeBiasLow+(rxPowerBase-rxPowerBaseLow)*(rangeBiasHigh-rangeBiasLow);
// range bias [mm] to timestamp modification value conversion
DW1000Time adjustmentTime;
adjustmentTime.setTimestamp((int)(rangeBias*DISTANCE_OF_RADIO_INV*0.001f));
// apply correction
timestamp += adjustmentTime;
}
void DW1000Class::getSystemTimestamp(DW1000Time& time) {
byte sysTimeBytes[LEN_SYS_TIME];
readBytes(SYS_TIME, NO_SUB, sysTimeBytes, LEN_SYS_TIME);
time.setTimestamp(sysTimeBytes);
}
void DW1000Class::getTransmitTimestamp(byte data[]) {
readBytes(TX_TIME, TX_STAMP_SUB, data, LEN_TX_STAMP);
}
void DW1000Class::getReceiveTimestamp(byte data[]) {
readBytes(RX_TIME, RX_STAMP_SUB, data, LEN_RX_STAMP);
}
void DW1000Class::getSystemTimestamp(byte data[]) {
readBytes(SYS_TIME, NO_SUB, data, LEN_SYS_TIME);
}
boolean DW1000Class::isTransmitDone() {
return getBit(_sysstatus, LEN_SYS_STATUS, TXFRS_BIT);
}
boolean DW1000Class::isReceiveTimestampAvailable() {
return getBit(_sysstatus, LEN_SYS_STATUS, LDEDONE_BIT);
}
boolean DW1000Class::isReceiveDone() {
if(_frameCheck) {
return getBit(_sysstatus, LEN_SYS_STATUS, RXFCG_BIT);
}
return getBit(_sysstatus, LEN_SYS_STATUS, RXDFR_BIT);
}
boolean DW1000Class::isReceiveFailed() {
boolean ldeErr, rxCRCErr, rxHeaderErr, rxDecodeErr;
ldeErr = getBit(_sysstatus, LEN_SYS_STATUS, LDEERR_BIT);
rxCRCErr = getBit(_sysstatus, LEN_SYS_STATUS, RXFCE_BIT);
rxHeaderErr = getBit(_sysstatus, LEN_SYS_STATUS, RXPHE_BIT);
rxDecodeErr = getBit(_sysstatus, LEN_SYS_STATUS, RXRFSL_BIT);
if(ldeErr || rxCRCErr || rxHeaderErr || rxDecodeErr) {
return true;
}
return false;
}
boolean DW1000Class::isReceiveTimeout() {
return getBit(_sysstatus, LEN_SYS_STATUS, RXRFTO_BIT);
}
boolean DW1000Class::isClockProblem() {
boolean clkllErr, rfllErr;
clkllErr = getBit(_sysstatus, LEN_SYS_STATUS, CLKPLL_LL_BIT);
rfllErr = getBit(_sysstatus, LEN_SYS_STATUS, RFPLL_LL_BIT);
if(clkllErr || rfllErr) {
return true;
}
return false;
}
void DW1000Class::clearAllStatus() {
memset(_sysstatus, 0, LEN_SYS_STATUS);
writeBytes(SYS_STATUS, NO_SUB, _sysstatus, LEN_SYS_STATUS);
}
void DW1000Class::clearReceiveTimestampAvailableStatus() {
setBit(_sysstatus, LEN_SYS_STATUS, LDEDONE_BIT, true);
writeBytes(SYS_STATUS, NO_SUB, _sysstatus, LEN_SYS_STATUS);
}
void DW1000Class::clearReceiveStatus() {
// clear latched RX bits (i.e. write 1 to clear)
setBit(_sysstatus, LEN_SYS_STATUS, RXDFR_BIT, true);
setBit(_sysstatus, LEN_SYS_STATUS, LDEDONE_BIT, true);
setBit(_sysstatus, LEN_SYS_STATUS, LDEERR_BIT, true);
setBit(_sysstatus, LEN_SYS_STATUS, RXPHE_BIT, true);
setBit(_sysstatus, LEN_SYS_STATUS, RXFCE_BIT, true);
setBit(_sysstatus, LEN_SYS_STATUS, RXFCG_BIT, true);
setBit(_sysstatus, LEN_SYS_STATUS, RXRFSL_BIT, true);
writeBytes(SYS_STATUS, NO_SUB, _sysstatus, LEN_SYS_STATUS);
}
void DW1000Class::clearTransmitStatus() {
// clear latched TX bits
setBit(_sysstatus, LEN_SYS_STATUS, TXFRB_BIT, true);
setBit(_sysstatus, LEN_SYS_STATUS, TXPRS_BIT, true);
setBit(_sysstatus, LEN_SYS_STATUS, TXPHS_BIT, true);
setBit(_sysstatus, LEN_SYS_STATUS, TXFRS_BIT, true);
writeBytes(SYS_STATUS, NO_SUB, _sysstatus, LEN_SYS_STATUS);
}
float DW1000Class::getReceiveQuality() {
byte noiseBytes[LEN_STD_NOISE];
byte fpAmpl2Bytes[LEN_FP_AMPL2];
unsigned int noise, f2;
readBytes(RX_FQUAL, STD_NOISE_SUB, noiseBytes, LEN_STD_NOISE);
readBytes(RX_FQUAL, FP_AMPL2_SUB, fpAmpl2Bytes, LEN_FP_AMPL2);
noise = (unsigned int)noiseBytes[0] | ((unsigned int)noiseBytes[1] << 8);
f2 = (unsigned int)fpAmpl2Bytes[0] | ((unsigned int)fpAmpl2Bytes[1] << 8);
return (float)f2/noise;
}
float DW1000Class::getFirstPathPower() {
byte fpAmpl1Bytes[LEN_FP_AMPL1];
byte fpAmpl2Bytes[LEN_FP_AMPL2];
byte fpAmpl3Bytes[LEN_FP_AMPL3];
byte rxFrameInfo[LEN_RX_FINFO];
unsigned int f1, f2, f3, N;
float A, corrFac;
readBytes(RX_TIME, FP_AMPL1_SUB, fpAmpl1Bytes, LEN_FP_AMPL1);
readBytes(RX_FQUAL, FP_AMPL2_SUB, fpAmpl2Bytes, LEN_FP_AMPL2);
readBytes(RX_FQUAL, FP_AMPL3_SUB, fpAmpl3Bytes, LEN_FP_AMPL3);
readBytes(RX_FINFO, NO_SUB, rxFrameInfo, LEN_RX_FINFO);
f1 = (unsigned int)fpAmpl1Bytes[0] | ((unsigned int)fpAmpl1Bytes[1] << 8);
f2 = (unsigned int)fpAmpl2Bytes[0] | ((unsigned int)fpAmpl2Bytes[1] << 8);
f3 = (unsigned int)fpAmpl3Bytes[0] | ((unsigned int)fpAmpl3Bytes[1] << 8);
N = (((unsigned int)rxFrameInfo[2] >> 4) & 0xFF) | ((unsigned int)rxFrameInfo[3] << 4);
if(_pulseFrequency == TX_PULSE_FREQ_16MHZ) {
A = 115.72;
corrFac = 2.3334;
} else {
A = 121.74;
corrFac = 1.1667;
}
float estFpPwr = 10.0*log10(((float)f1*(float)f1+(float)f2*(float)f2+(float)f3*(float)f3)/((float)N*(float)N))-A;
if(estFpPwr <= -88) {
return estFpPwr;
} else {
// approximation of Fig. 22 in user manual for dbm correction
estFpPwr += (estFpPwr+88)*corrFac;
}
return estFpPwr;
}
float DW1000Class::getReceivePower() {
byte cirPwrBytes[LEN_CIR_PWR];
byte rxFrameInfo[LEN_RX_FINFO];
unsigned long twoPower17 = 131072;
unsigned int C, N;
float A, corrFac;
readBytes(RX_FQUAL, CIR_PWR_SUB, cirPwrBytes, LEN_CIR_PWR);
readBytes(RX_FINFO, NO_SUB, rxFrameInfo, LEN_RX_FINFO);
C = (unsigned int)cirPwrBytes[0] | ((unsigned int)cirPwrBytes[1] << 8);
N = (((unsigned int)rxFrameInfo[2] >> 4) & 0xFF) | ((unsigned int)rxFrameInfo[3] << 4);
if(_pulseFrequency == TX_PULSE_FREQ_16MHZ) {
A = 115.72;
corrFac = 2.3334;
} else {
A = 121.74;
corrFac = 1.1667;
}
float estRxPwr = 10.0*log10(((float)C*(float)twoPower17)/((float)N*(float)N))-A;
if(estRxPwr <= -88) {
return estRxPwr;
} else {
// approximation of Fig. 22 in user manual for dbm correction
estRxPwr += (estRxPwr+88)*corrFac;
}
return estRxPwr;
}
/* ###########################################################################
* #### Helper functions #####################################################
* ######################################################################### */
/*
* Set the value of a bit in an array of bytes that are considered
* consecutive and stored from MSB to LSB.
* @param data
* The number as byte array.
* @param n
* The number of bytes in the array.
* @param bit
* The position of the bit to be set.
* @param val
* The boolean value to be set to the given bit position.
*/
void DW1000Class::setBit(byte data[], unsigned int n, unsigned int bit, boolean val) {
int idx;
int shift;
idx = bit/8;
if(idx >= n) {
return; // TODO proper error handling: out of bounds
}
byte* targetByte = &data[idx];
shift = bit%8;
if(val) {
bitSet(*targetByte, shift);
} else {
bitClear(*targetByte, shift);
}
}
/*
* Check the value of a bit in an array of bytes that are considered
* consecutive and stored from MSB to LSB.
* @param data
* The number as byte array.
* @param n
* The number of bytes in the array.
* @param bit
* The position of the bit to be checked.
*/
boolean DW1000Class::getBit(byte data[], unsigned int n, unsigned int bit) {
int idx;
int shift;
idx = bit/8;
if(idx >= n) {
return false; // TODO proper error handling: out of bounds
}
byte targetByte = data[idx];
shift = bit%8;
return bitRead(targetByte, shift);
}
void DW1000Class::writeValueToBytes(byte data[], long val, unsigned int n) {
int i;
for(i = 0; i < n; i++) {
data[i] = ((val >> (i*8)) & 0xFF);
}
}
/*
* Read bytes from the DW1000. Number of bytes depend on register length.
* @param cmd
* The register address (see Chapter 7 in the DW1000 user manual).
* @param data
* The data array to be read into.
* @param n
* The number of bytes expected to be received.
*/
void DW1000Class::readBytes(byte cmd, word offset, byte data[], unsigned int n) {
byte header[3];
int headerLen = 1;
int i;
if(offset == NO_SUB) {
header[0] = READ | cmd;
} else {
header[0] = READ_SUB | cmd;
if(offset < 128) {
header[1] = (byte)offset;
headerLen++;
} else {
header[1] = RW_SUB_EXT | (byte)offset;
header[2] = (byte)(offset >> 7);
headerLen += 2;
}
}
SPI.beginTransaction(*_currentSPI);
#ifdef __AVR__
digitalWriteFast(_ss, LOW);
#else
digitalWrite(_ss, LOW);
#endif
for(i = 0; i < headerLen; i++) {
SPI.transfer(header[i]);
}
for(i = 0; i < n; i++) {
data[i] = SPI.transfer(JUNK);
}
delayMicroseconds(5);
#ifdef __AVR__
digitalWriteFast(_ss, HIGH);
#else
digitalWrite(_ss, HIGH);
#endif
SPI.endTransaction();
}
// always 4 bytes
void DW1000Class::readBytesOTP(word address, byte data[]) {
byte addressBytes[LEN_OTP_ADDR];
byte otpctrl[LEN_OTP_CTRL];
readBytes(OTP_IF, OTP_CTRL_SUB, otpctrl, LEN_OTP_CTRL);
// bytes of address
addressBytes[0] = (address & 0xFF);
addressBytes[1] = ((address >> 8) & 0xFF);
// set address
writeBytes(OTP_IF, OTP_ADDR_SUB, addressBytes, LEN_OTP_ADDR);
otpctrl[0] = 0x03;
writeBytes(OTP_IF, OTP_CTRL_SUB, otpctrl, LEN_OTP_CTRL);
otpctrl[0] = 0x01;
writeBytes(OTP_IF, OTP_CTRL_SUB, otpctrl, LEN_OTP_CTRL);
// read value
readBytes(OTP_IF, OTP_RDAT_SUB, data, LEN_OTP_RDAT);
otpctrl[0] = 0x00;
writeBytes(OTP_IF, OTP_CTRL_SUB, otpctrl, LEN_OTP_CTRL);
}
/*
* Write bytes to the DW1000. Single bytes can be written to registers via sub-addressing.
* @param cmd
* The register address (see Chapter 7 in the DW1000 user manual).
* @param offset
* The offset to select register sub-parts for writing, or 0x00 to disable
* sub-adressing.
* @param data
* The data array to be written.
* @param n
* The number of bytes to be written (take care not to go out of bounds of
* the register).
*/
void DW1000Class::writeBytes(byte cmd, word offset, byte data[], unsigned int n) {
byte header[3];
int headerLen = 1;
int i;
// TODO proper error handling: address out of bounds
if(offset == NO_SUB) {
header[0] = WRITE | cmd;
} else {
header[0] = WRITE_SUB | cmd;
if(offset < 128) {
header[1] = (byte)offset;
headerLen++;
} else {
header[1] = RW_SUB_EXT | (byte)offset;
header[2] = (byte)(offset >> 7);
headerLen += 2;
}
}
SPI.beginTransaction(*_currentSPI);
#ifdef __AVR__
digitalWriteFast(_ss, LOW);
#else
digitalWrite(_ss, LOW);
#endif
for(i = 0; i < headerLen; i++) {
SPI.transfer(header[i]);
}
for(i = 0; i < n; i++) {
SPI.transfer(data[i]);
}
delayMicroseconds(5);
#ifdef __AVR__
digitalWriteFast(_ss, HIGH);
#else
digitalWrite(_ss, HIGH);
#endif
SPI.endTransaction();
}
void DW1000Class::getPrettyBytes(byte data[], char msgBuffer[], unsigned int n) {
unsigned int i, j, b;
b = sprintf(msgBuffer, "Data, bytes: %d\nB: 7 6 5 4 3 2 1 0\n", n);
for(i = 0; i < n; i++) {
byte curByte = data[i];
snprintf(&msgBuffer[b++], 2, "%d", (i+1));
msgBuffer[b++] = (char)((i+1) & 0xFF);
msgBuffer[b++] = ':';
msgBuffer[b++] = ' ';
for(j = 0; j < 8; j++) {
msgBuffer[b++] = ((curByte >> (7-j)) & 0x01) ? '1' : '0';
if(j < 7) {
msgBuffer[b++] = ' ';
} else if(i < n-1) {
msgBuffer[b++] = '\n';
} else {
msgBuffer[b++] = '\0';
}
}
}
msgBuffer[b++] = '\0';
}
void DW1000Class::getPrettyBytes(byte cmd, word offset, char msgBuffer[], unsigned int n) {
unsigned int i, j, b;
byte* readBuf = (byte*)malloc(n);
readBytes(cmd, offset, readBuf, n);
b = sprintf(msgBuffer, "Reg: 0x%02x, bytes: %d\nB: 7 6 5 4 3 2 1 0\n", cmd, n);
for(i = 0; i < n; i++) {
byte curByte = readBuf[i];
snprintf(&msgBuffer[b++], 2, "%d", (i+1));
msgBuffer[b++] = (char)((i+1) & 0xFF);
msgBuffer[b++] = ':';
msgBuffer[b++] = ' ';
for(j = 0; j < 8; j++) {
msgBuffer[b++] = ((curByte >> (7-j)) & 0x01) ? '1' : '0';
if(j < 7) {
msgBuffer[b++] = ' ';
} else if(i < n-1) {
msgBuffer[b++] = '\n';
} else {
msgBuffer[b++] = '\0';
}
}
}
msgBuffer[b++] = '\0';
free(readBuf);
}
| [
"vicliang93@gmail.com"
] | vicliang93@gmail.com |
7b6c5d2ce7a4d71a93d0ccd8840762a7cb509b7f | b8a1e222355dc1c17456d746c918b19705cca7e2 | /Encryptions/MISTY1.h | 780df436b8798dd31ae827d44fa47282ec93cffc | [
"LicenseRef-scancode-unknown-license-reference",
"MIT"
] | permissive | duerbin/Encryptions | 5e3d54acaf36709d6f47d69455dc49f67436fde7 | 5be788a46af91237d14d6d462306b68c5d5a2172 | refs/heads/master | 2021-01-18T07:33:41.263964 | 2015-06-20T17:01:41 | 2015-06-20T17:01:41 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 717 | h | #ifndef __MISTY1__
#define __MISTY1__
#include "../common/includes.h"
#include "SymAlg.h"
#include "MISTY1_Const.h"
class MISTY1 : public SymAlg{
private:
uint16_t EK[32];
uint16_t FI(const uint16_t FI_IN, const uint16_t FI_KEY);
uint32_t FO(const uint32_t FO_IN, const uint16_t k);
uint32_t FL(const uint32_t FL_IN, const uint32_t k);
uint32_t FLINV(const uint32_t FL_IN, const uint32_t k);
public:
MISTY1();
MISTY1(const std::string & KEY);
void setkey(const std::string & KEY);
std::string encrypt(const std::string & DATA);
std::string decrypt(const std::string & DATA);
unsigned int blocksize() const;
};
#endif
| [
"calccrypto@gmail.com"
] | calccrypto@gmail.com |
a1e6f0040c81fe4558bf0e1fe152bdf7626eb79a | 2cbe7ff001d564e3aa2874c40cdfaa88f97833c2 | /Server/BackEndMonitoringServer/include/IInfoDatabase.h | b4c5b5eeeddbf57cf7fe68afafbc4d067756afa4 | [
"MIT"
] | permissive | ITA-Dnipro/BackEndMonitoring | 3e4eb1751ceecde910c239c32e953eef55b6a713 | 2962b6e14e47c789daaf6f6c5e200c8ec419bc7e | refs/heads/main | 2023-03-07T06:03:55.526458 | 2021-02-24T21:52:57 | 2021-02-24T21:52:57 | 325,792,708 | 0 | 0 | MIT | 2021-02-24T21:52:58 | 2020-12-31T12:09:29 | C++ | UTF-8 | C++ | false | false | 226 | h | #pragma once
class IInfoDatabase
{
public:
virtual bool GetAllInfo(std::string& data) = 0;
virtual bool GetLastInfo(std::string& data) = 0;
virtual bool GetSelectedInfo(time_t from, time_t to, std::string& data) = 0;
};
| [
"noreply@github.com"
] | noreply@github.com |
35855ff93dbccd4707565f3f635d33c967c1a632 | 176754474863f1b22b2bfa145cf9f097d79de059 | /Math/EulerPhi.cpp | ffdd3a2496bb7300c06e53693107315b1f2f465f | [] | no_license | Redleaf23477/lightbulbCodeBook | 7b9eaf8639776fe61cee8c2bbebe18e974575e38 | c7b62dc4b287f7995755dcc968154e1cb2510729 | refs/heads/master | 2020-03-12T06:10:02.760722 | 2020-02-27T07:01:01 | 2020-02-27T07:01:01 | 130,479,367 | 1 | 0 | null | 2018-11-24T16:39:25 | 2018-04-21T14:04:54 | C++ | UTF-8 | C++ | false | false | 590 | cpp | //find in O(sqrt(N))
int euler_phi(int N)
{
int res=N;
for(int i=2;i*i<=N;i++)
{
if(N%i==0)
{
res=res/i*(i-1);
for(;N%i==0;N/=i);
}
}
if(N!=1)res=res/N*(N-1);//self=prime
return res;
}
//tabulate in O(MAXN)
int euler[MAXN];
void euler_phi2()
{
for(int i=0;i<MAXN;i++)euler[i]=i;
for(int i=2;i<MAXN;i++)
{
if(euler[i]==i)
{
for(int j=i;j<MAXN;j+=i)
{
euler[j]=euler[j]/i*(i-1);
}
}
}
}
| [
"schpokeool@gmail.com"
] | schpokeool@gmail.com |
a6424025cb75a867f2df2c5203855bf5bc1b27ac | 04948b0dfa23f945b623c4bc2a51492c809dedf6 | /Source/Renderer/ComputeShaderRenderer.h | 53612e5e4d7fb0a52e84f6ee7812993c5a08ac1e | [
"MIT"
] | permissive | HuCoco/RayTracing | f85967c2a982b3ed510d0bdbb3e76519befe6d29 | e1d620a2d263a986a3557379588b72aea01f9181 | refs/heads/master | 2020-03-19T00:08:49.699935 | 2018-07-31T15:58:56 | 2018-07-31T15:58:56 | 135,456,573 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,100 | h | #pragma once
#include <Platform/Platform.h>
#include <Math/Vec3f.h>
#include <Core/Scene.h>
namespace PBR
{
class ComputeShaderRenderer
{
protected:
ComputeShaderRenderer();
~ComputeShaderRenderer();
public:
static ComputeShaderRenderer* GetInstance();
void Initialize();
void CreateOutputImage(uint32_t width, uint32_t height);
void Finalize();
void Render();
void PrepareShaderData();
void PassShaderData();
void GenerateShaderData(const Scene& scene);
GLuint GetOutputImageHandle() { return mOutputImage; }
private:
GLuint mShader;
GLuint mProgram;
GLuint mOutputImage;
uint32_t mTargetImageWidth;
uint32_t mTargetImageHeight;
//Direction Light
GLuint DirectionLightHandle;
GLuint PointLightsHandle;
GLuint MaterialsHandle;
GLuint SpheresHandle;
GLuint CameraHandle;
private:
struct Material
{
Color albedo;
float metallic;
float roughness;
float _pad[3];
};
Material mMaterialList[32];
uint32_t mNumActiveMaterials;
struct Sphere
{
Vec3f center;
float radius;
uint32_t mat;
float _pad[3];
};
Sphere mSphereList[32];
uint32_t mNumActiveSpheres;
struct PointLight
{
Vec3f position;
float _pad_1;
Color color;
float _pad_2;
};
PointLight mPointLightList[32];
uint32_t mNumActivePointLight;
struct DirectionLight
{
Color color;
};
DirectionLight mDirectionLight;
struct Camera
{
Vec3f COP;
float _pad_1;
Vec3f ImageOrigin;
float _pad_2;
Vec3f ImageU;
float _pad_3;
Vec3f ImageV;
int ImageWidth;
int ImageHeight;
};
Camera mCamera;
};
} | [
"hu-coco@qq.com"
] | hu-coco@qq.com |
174d1674e89093c1cebcf8f81dab8841c7ddfb39 | 11b9965933d407ed3708a252aebcdafc21c98664 | /MassGrav/src/CalGt.cpp | 34e0debc676fcea5d743aa8452a887bb38b9e96e | [
"BSD-3-Clause"
] | permissive | lanl/Dendro-GRCA | a265131e2a5d8327eba49e2133257d553826a41e | 8a475b1abd8832c3dfc19d00cc0ec4b9e2789c8a | refs/heads/master | 2023-05-31T06:25:06.113867 | 2020-09-23T18:00:13 | 2020-09-23T18:00:13 | 297,793,620 | 1 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 4,110 | cpp | massgrav::timer::t_rhs.start();
for (unsigned int k = 3; k < nz-3; k++) {
z = pmin[2] + k*hz;
for (unsigned int j = 3; j < ny-3; j++) {
y = pmin[1] + j*hy;
for (unsigned int i = 3; i < nx-3; i++) {
x = pmin[0] + i*hx;
pp = i + nx*(j + ny*k);
r_coord = sqrt(x*x + y*y + z*z);
eta=ETA_CONST;
if (r_coord >= ETA_R0) {
eta *= pow( (ETA_R0/r_coord), ETA_DAMPING_EXP);
}
// Dendro: {{{
// Dendro: original ops: 1716
// Dendro: printing temp variables
double DENDRO_0 = pow(gt4[pp], 2);
double DENDRO_1 = pow(gt1[pp], 2);
double DENDRO_2 = pow(gt2[pp], 2);
double DENDRO_3 = gt0[pp]*gt3[pp];
double DENDRO_4 = gt1[pp]*gt2[pp];
double DENDRO_5 = pow(DENDRO_0*gt0[pp] + DENDRO_1*gt5[pp] + DENDRO_2*gt3[pp] - DENDRO_3*gt5[pp] - 2*DENDRO_4*gt4[pp], -2);
double DENDRO_6 = -DENDRO_4 + gt0[pp]*gt4[pp];
double DENDRO_7 = grad_2_gt3[pp];
double DENDRO_8 = gt1[pp]*gt5[pp] - gt2[pp]*gt4[pp];
double DENDRO_9 = grad_1_gt5[pp];
double DENDRO_10 = gt1[pp]*gt4[pp] - gt2[pp]*gt3[pp];
double DENDRO_11 = -DENDRO_0 + gt3[pp]*gt5[pp];
double DENDRO_12 = grad_1_gt2[pp];
double DENDRO_13 = grad_2_gt1[pp];
double DENDRO_14 = grad_0_gt4[pp];
double DENDRO_15 = DENDRO_12 + DENDRO_13 - DENDRO_14;
double DENDRO_16 = grad_0_gt3[pp];
double DENDRO_17 = grad_1_gt0[pp];
double DENDRO_18 = DENDRO_12 - DENDRO_13 + DENDRO_14;
double DENDRO_19 = 1.0*gt1[pp]*gt4[pp] - 1.0*gt2[pp]*gt3[pp];
double DENDRO_20 = grad_0_gt5[pp];
double DENDRO_21 = grad_2_gt0[pp];
double DENDRO_22 = -DENDRO_12 + DENDRO_13 + DENDRO_14;
double DENDRO_23 = -DENDRO_1 + DENDRO_3;
double DENDRO_24 = grad_2_gt5[pp];
double DENDRO_25 = 0.5*gt1[pp]*gt4[pp] - 0.5*gt2[pp]*gt3[pp];
double DENDRO_26 = 0.5*DENDRO_9 - 1.0*grad_2_gt4[pp];
double DENDRO_27 = 0.5*DENDRO_20 - 1.0*grad_2_gt2[pp];
double DENDRO_28 = -DENDRO_2 + gt0[pp]*gt5[pp];
double DENDRO_29 = grad_1_gt3[pp];
double DENDRO_30 = 0.5*gt1[pp]*gt5[pp] - 0.5*gt2[pp]*gt4[pp];
double DENDRO_31 = -0.5*DENDRO_7 + 1.0*grad_1_gt4[pp];
double DENDRO_32 = 0.5*DENDRO_16 - 1.0*grad_1_gt1[pp];
double DENDRO_33 = grad_0_gt0[pp];
double DENDRO_34 = -0.5*DENDRO_17 + 1.0*grad_0_gt1[pp];
double DENDRO_35 = -0.5*DENDRO_21 + 1.0*grad_0_gt2[pp];
double DENDRO_36 = 0.5*gt0[pp]*gt4[pp] - 0.5*gt1[pp]*gt2[pp];
// Dendro: printing variables
//--
CalGt0[pp] = DENDRO_5*(-DENDRO_11*(-DENDRO_10*DENDRO_35 - 0.5*DENDRO_11*DENDRO_33 + DENDRO_34*DENDRO_8) - DENDRO_19*(-DENDRO_10*DENDRO_20 - DENDRO_11*DENDRO_21 + DENDRO_22*DENDRO_8) - DENDRO_23*(DENDRO_11*DENDRO_27 - DENDRO_24*DENDRO_25 - DENDRO_26*DENDRO_8) - DENDRO_28*(-DENDRO_10*DENDRO_31 + DENDRO_11*DENDRO_32 + DENDRO_29*DENDRO_30) + DENDRO_6*(-DENDRO_10*DENDRO_9 - DENDRO_11*DENDRO_15 + DENDRO_7*DENDRO_8) + DENDRO_8*(-DENDRO_10*DENDRO_18 - DENDRO_11*DENDRO_17 + DENDRO_16*DENDRO_8));
//--
CalGt1[pp] = DENDRO_5*(-DENDRO_11*(-DENDRO_28*DENDRO_34 + DENDRO_30*DENDRO_33 + DENDRO_35*DENDRO_6) - DENDRO_19*(DENDRO_20*DENDRO_6 + DENDRO_21*DENDRO_8 - DENDRO_22*DENDRO_28) - DENDRO_23*(DENDRO_24*DENDRO_36 + DENDRO_26*DENDRO_28 - DENDRO_27*DENDRO_8) - DENDRO_28*(-0.5*DENDRO_28*DENDRO_29 + DENDRO_31*DENDRO_6 - DENDRO_32*DENDRO_8) + DENDRO_6*(DENDRO_15*DENDRO_8 - DENDRO_28*DENDRO_7 + DENDRO_6*DENDRO_9) + DENDRO_8*(-DENDRO_16*DENDRO_28 + DENDRO_17*DENDRO_8 + DENDRO_18*DENDRO_6));
//--
CalGt2[pp] = DENDRO_5*(-DENDRO_11*(-DENDRO_23*DENDRO_35 - DENDRO_25*DENDRO_33 + DENDRO_34*DENDRO_6) - DENDRO_19*(-DENDRO_10*DENDRO_21 - DENDRO_20*DENDRO_23 + DENDRO_22*DENDRO_6) - DENDRO_23*(DENDRO_10*DENDRO_27 - 0.5*DENDRO_23*DENDRO_24 - DENDRO_26*DENDRO_6) - DENDRO_28*(DENDRO_10*DENDRO_32 - DENDRO_23*DENDRO_31 + DENDRO_29*DENDRO_36) + DENDRO_6*(-DENDRO_10*DENDRO_15 - DENDRO_23*DENDRO_9 + DENDRO_6*DENDRO_7) + DENDRO_8*(-DENDRO_10*DENDRO_17 + DENDRO_16*DENDRO_6 - DENDRO_18*DENDRO_23));
// Dendro: reduced ops: 221
// Dendro: }}}
/* debugging */
/*unsigned int qi = 46 - 1;
unsigned int qj = 10 - 1;
unsigned int qk = 60 - 1;
unsigned int qidx = qi + nx*(qj + ny*qk);
if (0 && qidx == pp) {
std::cout << ".... end OPTIMIZED debug stuff..." << std::endl;
}*/
}
}
}
massgrav::timer::t_rhs.stop();
| [
"hylim1988@gmail.com"
] | hylim1988@gmail.com |
038c54e50e762515ed71594d4d1b88907fbdf97c | 09f8c5fa77ea1556ca3d526c549186894cb28847 | /树/102.二叉树的层次遍历.cpp | a65383b626a07f1e4d55ba83b821d37649034dfe | [] | no_license | Kay-Rick/Algorithm | fbfb026b8b9fbae4b0af285a9ac0c43d92fc0f1f | e51213288483b2f39b75ac8fe9a9bb0ceb4e4c4d | refs/heads/master | 2021-01-04T07:13:17.132915 | 2020-08-19T06:40:06 | 2020-08-19T06:40:06 | 240,444,144 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,387 | cpp | /*
* @Author: Rick
* @Email: Kay_Rick@outlook.com
* @Github: https://github.com/Kay-Rick
* @Date: 2020-03-12 22:18:06
* @LastEditors: Kay_Rick@outlook.com
* @LastEditTime: 2020-06-25 10:19:21
* @FilePath: /LeetCode/src/Accepted/102.二叉树的层次遍历.cpp
* @Description: BFS 使用队列进行层次遍历
*/
/*
* @lc app=leetcode.cn id=102 lang=cpp
*
* [102] 二叉树的层次遍历
*
* https://leetcode-cn.com/problems/binary-tree-level-order-traversal/description/
*
* algorithms
* Medium (59.96%)
* Likes: 402
* Dislikes: 0
* Total Accepted: 88.5K
* Total Submissions: 144.9K
* Testcase Example: '[3,9,20,null,null,15,7]'
*
* 给定一个二叉树,返回其按层次遍历的节点值。 (即逐层地,从左到右访问所有节点)。
*
* 例如:
* 给定二叉树: [3,9,20,null,null,15,7],
*
* 3
* / \
* 9 20
* / \
* 15 7
*
*
* 返回其层次遍历结果:
*
* [
* [3],
* [9,20],
* [15,7]
* ]
*
*
*/
#include <iostream>
#include <vector>
#include <queue>
using namespace std;
struct TreeNode {
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
// @lc code=start
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
/**
* @brief 层序遍历:使用队列 BFS 思想
* @param root
* @return vector<vector<int>>
*/
vector<vector<int>> levelOrder(TreeNode* root) {
vector<vector<int>> res;
queue<TreeNode*> q;
if (root == NULL) {
return res;
}
q.push(root);
while (!q.empty()) {
vector<int> v;
// 使用count记录每一层的个数
int count = q.size();
while (count--) {
TreeNode* T;
T = q.front();
q.pop();
v.push_back(T->val);
if (T->left != NULL) {
q.push(T->left);
}
if (T->right != NULL) {
q.push(T->right);
}
}
res.push_back(v);
}
return res;
}
};
// @lc code=end
| [
"Kay_Rick@outlook.com"
] | Kay_Rick@outlook.com |
2f320cd74ff7aa915a41fb31cac7a56095b6cd6e | 7849b3b7d948f8679f0ff7bb657d9c640903e215 | /Stack.h | 5889cf6fc4a3de0a505474030cdbee334c3afea8 | [] | no_license | SergeyShopik/Cpp_Parametrized_Queue_Stack_List | 156ef1903bec4f52c499b473b126279ea366cb79 | bf92933bfa8ca0d313ef85a6dea0f895f0412a97 | refs/heads/master | 2023-01-28T05:00:51.461480 | 2020-12-15T10:30:28 | 2020-12-15T10:30:28 | 321,631,419 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 984 | h | #pragma once
#include"List.h"
template<class T>
class Stack : public List<T>
{
public:
Stack();
~Stack();
void pushBack(const T&);
T pop();
void print() const;
};
template<class T>
Stack<T>::Stack() : List<T>() {}
template<class T>
Stack<T>::~Stack()
{
while (List<T>::getSize() != 0)
pop();
}
template<class T>
void Stack<T>::pushBack(const T& element)
{
Node<T>* newNode = new Node<T>(element, List<T>::getTail());
List<T>::setTail(newNode);
List<T>::setSize(List<T>::getSize() + 1);
}
template<class T>
T Stack<T>::pop()
{
T key;
if (List<T>::getSize() == 0)
{
std::cout << "Stack is empty.\n";
return T();
}
else
{
Node<T>* temp = List<T>::getTail();
key = temp->data;
List<T>::setTail(temp->prev);
List<T>::setSize(List<T>::getSize() - 1);
delete temp;
return key;
}
}
template<class T>
void Stack<T>::print() const
{
for (Node<T>* i = List<T>::getTail(); i; i = i->prev)
{
std::cout << i->data << " ";
}
std::cout << std::endl;
} | [
"sergey.shopik101@gmail.com"
] | sergey.shopik101@gmail.com |
6794d91a2f465db97234030bf6a162a74fa71c0e | 5a790ed9f325efa8c25c17dd4cdbca39d2db726b | /code/chap05/main.cpp | e5520e2932745b171fa0398faba9abea10669783 | [] | no_license | brazilian-code/csc212 | 7c8ce002fd203f031726b723b404c69ca3d30547 | 15420a54abd72af1ecc88f047208a7de1644f7c9 | refs/heads/master | 2020-05-27T11:30:17.213598 | 2019-05-24T05:16:01 | 2019-05-24T05:16:01 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 486 | cpp | #include <iostream>
#include "node1.h"
using namespace main_savitch_5;
int main(){
node* tail = new node(1.0);
node* second = new node(2.0, tail);
node* first = new node(3.0, second);
std::cout<<"length: "<<list_length(first)<<std::endl;
list_head_insert(first, 13.9);
std::cout<<"length: "<<list_length(first)<<std::endl;
std::cout<<"head: "<<first->data()<<std::endl;
std::cout<<"second: "<<(first->link())->data()<<std::endl;
return 0;
}
| [
"story645@gmail.com"
] | story645@gmail.com |
7b2d47172749ca0798e07eb2c9533f6d0e2f81ed | 835f6871723128ca520cea613e8b34de4e89697f | /kernel/terminal.cpp | 7c814b4e3ef5ed413309c6657f5e061a23f3aa7d | [] | no_license | Acasune/MikanOS-practice | 00b9eebc153c34415ac680b8e4b9e0724fc25b80 | 7cd140a987e1df85661629e224db7d792b246a61 | refs/heads/main | 2023-07-16T15:44:05.184738 | 2021-08-29T05:54:20 | 2021-08-29T05:54:20 | 388,670,928 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 24,891 | cpp | #include "terminal.hpp"
#include <cstring>
#include <limits>
#include "font.hpp"
#include "layer.hpp"
#include "pci.hpp"
#include "asmfunc.h"
#include "elf.hpp"
#include "memory_manager.hpp"
#include "paging.hpp"
#include "timer.hpp"
#include "keyboard.hpp"
#include "logger.hpp"
namespace {
WithError<int> MakeArgVector(char* command, char* first_arg,
char** argv, int argv_len, char* argbuf, int argbuf_len) {
int argc = 0;
int argbuf_index = 0;
auto push_to_argv = [&](const char* s) {
if (argc >= argv_len || argbuf_index >= argbuf_len) {
return MAKE_ERROR(Error::kFull);
}
argv[argc] = &argbuf[argbuf_index];
++argc;
strcpy(&argbuf[argbuf_index], s);
argbuf_index += strlen(s) + 1;
return MAKE_ERROR(Error::kSuccess);
};
if (auto err = push_to_argv(command)) {
return { argc, err };
}
if (!first_arg) {
return { argc, MAKE_ERROR(Error::kSuccess) };
}
char* p = first_arg;
while (true) {
while (isspace(p[0])) {
++p;
}
if (p[0] == 0) {
break;
}
const char* arg = p;
while (p[0] != 0 && !isspace(p[0])) {
++p;
}
// here: p[0] == 0 || isspace(p[0])
const bool is_end = p[0] == 0;
p[0] = 0;
if (auto err = push_to_argv(arg)) {
return { argc, err };
}
if (is_end) {
break;
}
++p;
}
return { argc, MAKE_ERROR(Error::kSuccess) };
}
Elf64_Phdr* GetProgramHeader(Elf64_Ehdr* ehdr) {
return reinterpret_cast<Elf64_Phdr*>(
reinterpret_cast<uintptr_t>(ehdr) + ehdr->e_phoff);
}
uintptr_t GetFirstLoadAddress(Elf64_Ehdr* ehdr) {
auto phdr = GetProgramHeader(ehdr);
for (int i = 0; i < ehdr->e_phnum; ++i) {
if (phdr[i].p_type != PT_LOAD) continue;
return phdr[i].p_vaddr;
}
return 0;
}
static_assert(kBytesPerFrame >= 4096);
WithError<uint64_t> CopyLoadSegments(Elf64_Ehdr* ehdr) {
auto phdr = GetProgramHeader(ehdr);
uint64_t last_addr = 0;
for (int i = 0; i < ehdr->e_phnum; ++i) {
if (phdr[i].p_type != PT_LOAD) continue;
LinearAddress4Level dest_addr;
dest_addr.value = phdr[i].p_vaddr;
last_addr = std::max(last_addr, phdr[i].p_vaddr + phdr[i].p_memsz);
const auto num_4kpages = (phdr[i].p_memsz + 4095) / 4096;
// setup pagemaps as readonly (writable = false)
if (auto err = SetupPageMaps(dest_addr, num_4kpages, false)) {
return { last_addr, err };
}
const auto src = reinterpret_cast<uint8_t*>(ehdr) + phdr[i].p_offset;
const auto dst = reinterpret_cast<uint8_t*>(phdr[i].p_vaddr);
memcpy(dst, src, phdr[i].p_filesz);
memset(dst + phdr[i].p_filesz, 0, phdr[i].p_memsz - phdr[i].p_filesz);
}
return { last_addr, MAKE_ERROR(Error::kSuccess) };
}
WithError<uint64_t> LoadELF(Elf64_Ehdr* ehdr) {
if (ehdr->e_type != ET_EXEC) {
return { 0, MAKE_ERROR(Error::kInvalidFormat) };
}
const auto addr_first = GetFirstLoadAddress(ehdr);
if (addr_first < 0xffff'8000'0000'0000) {
return { 0, MAKE_ERROR(Error::kInvalidFormat) };
}
return CopyLoadSegments(ehdr);
}
WithError<PageMapEntry*> SetupPML4(Task& current_task) {
auto pml4 = NewPageMap();
if (pml4.error) {
return pml4;
}
const auto current_pml4 = reinterpret_cast<PageMapEntry*>(GetCR3());
memcpy(pml4.value, current_pml4, 256 * sizeof(uint64_t));
const auto cr3 = reinterpret_cast<uint64_t>(pml4.value);
SetCR3(cr3);
current_task.Context().cr3 = cr3;
return pml4;
}
Error FreePML4(Task& current_task) {
const auto cr3 = current_task.Context().cr3;
current_task.Context().cr3 = 0;
ResetCR3();
return FreePageMap(reinterpret_cast<PageMapEntry*>(cr3));
}
void ListAllEntries(FileDescriptor& fd, uint32_t dir_cluster) {
const auto kEntriesPerCluster =
fat::bytes_per_cluster / sizeof(fat::DirectoryEntry);
while (dir_cluster != fat::kEndOfClusterchain) {
auto dir = fat::GetSectorByCluster<fat::DirectoryEntry>(dir_cluster);
for (int i = 0; i < kEntriesPerCluster; ++i) {
if (dir[i].name[0] == 0x00) {
return;
} else if (static_cast<uint8_t>(dir[i].name[0]) == 0xe5) {
continue;
} else if (dir[i].attr == fat::Attribute::kLongName) {
continue;
}
char name[13];
fat::FormatName(dir[i], name);
PrintToFD(fd, "%s\n", name);
}
dir_cluster = fat::NextCluster(dir_cluster);
}
}
WithError<AppLoadInfo> LoadApp(fat::DirectoryEntry& file_entry, Task& task) {
PageMapEntry* temp_pml4;
if (auto [ pml4, err ] = SetupPML4(task); err) {
return { {}, err };
} else {
temp_pml4 = pml4;
}
if (auto it = app_loads->find(&file_entry); it != app_loads->end()) {
AppLoadInfo app_load = it->second;
auto err = CopyPageMaps(temp_pml4, app_load.pml4, 4, 256);
app_load.pml4 = temp_pml4;
return { app_load, err };
}
std::vector<uint8_t> file_buf(file_entry.file_size);
fat::LoadFile(&file_buf[0], file_buf.size(), file_entry);
auto elf_header = reinterpret_cast<Elf64_Ehdr*>(&file_buf[0]);
if (memcmp(elf_header->e_ident, "\x7f" "ELF", 4) != 0) {
return { {}, MAKE_ERROR(Error::kInvalidFile) };
}
auto [ last_addr, err_load ] = LoadELF(elf_header);
if (err_load) {
return { {}, err_load };
}
AppLoadInfo app_load{last_addr, elf_header->e_entry, temp_pml4};
app_loads->insert(std::make_pair(&file_entry, app_load));
if (auto [ pml4, err ] = SetupPML4(task); err) {
return { app_load, err };
} else {
app_load.pml4 = pml4;
}
auto err = CopyPageMaps(app_load.pml4, temp_pml4, 4, 256);
return { app_load, err };
}
fat::DirectoryEntry* FindCommand(const char* command, unsigned long dir_cluster = 0) {
auto file_entry = fat::FindFile(command, dir_cluster);
if (file_entry.first != nullptr &&
(file_entry.first->attr == fat::Attribute::kDirectory || file_entry.second)) {
return nullptr;
} else if (file_entry.first) {
return file_entry.first;
}
if (dir_cluster != 0 || strchr(command, '/') != nullptr) {
return nullptr;
}
auto apps_entry = fat::FindFile("apps");
if ( apps_entry.first == nullptr ||
apps_entry.first->attr != fat::Attribute::kDirectory) {
return nullptr;
}
return FindCommand(command, apps_entry.first->FirstCluster());
}
} // namespace
std::map<fat::DirectoryEntry*, AppLoadInfo>* app_loads;
Terminal::Terminal(Task& task, const TerminalDescriptor* term_desc)
: task_{task} {
if (term_desc) {
show_window_ = term_desc->show_window;
for (int i = 0; i < files_.size(); ++i) {
files_[i] = term_desc->files[i];
}
} else {
show_window_ = true;
for (int i = 0; i < files_.size(); ++i) {
files_[i] = std::make_shared<TerminalFileDescriptor>(*this);
}
}
if (show_window_) {
window_ = std::make_shared<ToplevelWindow>(
kColumns * 8 + 8 + ToplevelWindow::kMarginX,
kRows * 16 + 8 + ToplevelWindow::kMarginY,
screen_config.pixel_format,
"MikanTerm");
DrawTerminal(*window_->InnerWriter(), {0, 0}, window_->InnerSize());
layer_id_ = layer_manager->NewLayer()
.SetWindow(window_)
.SetDraggable(true)
.ID();
Print(">");
}
cmd_history_.resize(8);
}
Rectangle<int> Terminal::BlinkCursor() {
cursor_visible_ = !cursor_visible_;
DrawCursor(cursor_visible_);
return {CalcCursorPos(), {7, 15}};
}
void Terminal::DrawCursor(bool visible) {
if (show_window_) {
const auto color = visible ? ToColor(0xffffff) : ToColor(0);
FillRectangle(*window_->Writer(), CalcCursorPos(), {7, 15}, color);
}
}
Vector2D<int> Terminal::CalcCursorPos() const {
return ToplevelWindow::kTopLeftMargin +
Vector2D<int>{4 + 8 * cursor_.x, 4 + 16 * cursor_.y};
}
Rectangle<int> Terminal::InputKey(
uint8_t modifier, uint8_t keycode, char ascii) {
DrawCursor(false);
Rectangle<int> draw_area{CalcCursorPos(), {8*2, 16}};
if (ascii == '\n') {
linebuf_[linebuf_index_] = 0;
if (linebuf_index_ > 0) {
cmd_history_.pop_back();
cmd_history_.push_front(linebuf_);
}
linebuf_index_ = 0;
cmd_history_index_ = -1;
cursor_.x = 0;
if (cursor_.y < kRows - 1) {
++cursor_.y;
} else {
Scroll1();
}
ExecuteLine();
Print(">");
draw_area.pos = ToplevelWindow::kTopLeftMargin;
draw_area.size = window_->InnerSize();
} else if (ascii == '\b') {
if (cursor_.x > 0) {
--cursor_.x;
if (show_window_) {
FillRectangle(*window_->Writer(), CalcCursorPos(), {8, 16}, {0, 0, 0});
}
draw_area.pos = CalcCursorPos();
if (linebuf_index_ > 0) {
--linebuf_index_;
}
}
} else if (ascii != 0) {
if (cursor_.x < kColumns - 1 && linebuf_index_ < kLineMax - 1) {
linebuf_[linebuf_index_] = ascii;
++linebuf_index_;
if (show_window_) {
WriteAscii(*window_->Writer(), CalcCursorPos(), ascii, {255, 255, 255});
}
++cursor_.x;
}
} else if (keycode == 0x51) { // down arrow
draw_area = HistoryUpDown(-1);
} else if (keycode == 0x52) { // up arrow
draw_area = HistoryUpDown(1);
}
DrawCursor(true);
return draw_area;
}
void Terminal::Scroll1() {
Rectangle<int> move_src{
ToplevelWindow::kTopLeftMargin + Vector2D<int>{4, 4 + 16},
{8*kColumns, 16*(kRows - 1)}
};
window_->Move(ToplevelWindow::kTopLeftMargin + Vector2D<int>{4, 4}, move_src);
FillRectangle(*window_->InnerWriter(),
{4, 4 + 16*cursor_.y}, {8*kColumns, 16}, {0, 0, 0});
}
void Terminal::ExecuteLine() {
char* command = &linebuf_[0];
char* first_arg = strchr(&linebuf_[0], ' ');
char* redir_char = strchr(&linebuf_[0], '>');
char* pipe_char = strchr(&linebuf_[0], '|');
if (first_arg) {
*first_arg = 0;
do {
++first_arg;
} while (isspace(*first_arg));
}
auto original_stdout = files_[1];
int exit_code = 0;
if (redir_char) {
*redir_char = 0;
char* redir_dest = &redir_char[1];
while (isspace(*redir_dest)) {
++redir_dest;
}
auto [ file, post_slash ] = fat::FindFile(redir_dest);
if (file == nullptr) {
auto [ new_file, err ] = fat::CreateFile(redir_dest);
if (err) {
PrintToFD(*files_[2],
"failed to create a redirect file: %s\n", err.Name());
return;
}
file = new_file;
} else if (file->attr == fat::Attribute::kDirectory || post_slash) {
PrintToFD(*files_[2], "cannot redirect to a directory\n");
return;
}
files_[1] = std::make_shared<fat::FileDescriptor>(*file);
}
std::shared_ptr<PipeDescriptor> pipe_fd;
uint64_t subtask_id = 0;
if (pipe_char) {
*pipe_char = 0;
char* subcommand = &pipe_char[1];
while (isspace(*subcommand)) {
++subcommand;
}
auto& subtask = task_manager->NewTask();
pipe_fd = std::make_shared<PipeDescriptor>(subtask);
auto term_desc = new TerminalDescriptor{
subcommand, true, false,
{ pipe_fd, files_[1], files_[2] }
};
files_[1] = pipe_fd;
subtask_id = subtask
.InitContext(TaskTerminal, reinterpret_cast<int64_t>(term_desc))
.Wakeup()
.ID();
(*layer_task_map)[layer_id_] = subtask_id;
}
if (strcmp(command, "echo") == 0) {
if (first_arg && first_arg[0] == '$') {
if (strcmp(&first_arg[1], "?") == 0) {
PrintToFD(*files_[1], "%d", last_exit_code_);
}
} else if (first_arg) {
PrintToFD(*files_[1], "%s", first_arg);
}
PrintToFD(*files_[1], "\n");
} else if (strcmp(command, "clear") == 0) {
if (show_window_) {
FillRectangle(*window_->InnerWriter(),
{4, 4}, {8*kColumns, 16*kRows}, {0, 0, 0});
}
cursor_.y = 0;
} else if (strcmp(command, "lspci") == 0) {
for (int i = 0; i < pci::num_device; ++i) {
const auto& dev = pci::devices[i];
auto vendor_id = pci::ReadVendorId(dev.bus, dev.device, dev.function);
PrintToFD(*files_[1],
"%02x:%02x.%d vend=%04x head=%02x class=%02x.%02x.%02x\n",
dev.bus, dev.device, dev.function, vendor_id, dev.header_type,
dev.class_code.base, dev.class_code.sub, dev.class_code.interface);
}
} else if (strcmp(command, "ls") == 0) {
if (!first_arg || first_arg[0] == '\0') {
ListAllEntries(*files_[1], fat::boot_volume_image->root_cluster);
} else {
auto [ dir, post_slash ] = fat::FindFile(first_arg);
if (dir == nullptr) {
PrintToFD(*files_[2], "No such file or directory: %s\n", first_arg);
exit_code = 1;
} else if (dir->attr == fat::Attribute::kDirectory) {
ListAllEntries(*files_[1], dir->FirstCluster());
} else {
char name[13];
fat::FormatName(*dir, name);
if (post_slash) {
PrintToFD(*files_[2], "%s is not a directory\n", name);
exit_code = 1;
} else {
PrintToFD(*files_[1], "%s\n", name);
}
}
}
} else if (strcmp(command, "cat") == 0) {
std::shared_ptr<FileDescriptor> fd;
if (!first_arg || first_arg[0] == '\0') {
fd = files_[0];
} else {
auto [ file_entry, post_slash ] = fat::FindFile(first_arg);
if (!file_entry) {
PrintToFD(*files_[2], "no such file: %s\n", first_arg);
exit_code = 1;
} else if (file_entry->attr != fat::Attribute::kDirectory && post_slash) {
char name[13];
fat::FormatName(*file_entry, name);
PrintToFD(*files_[2], "%s is not a directory\n", name);
exit_code = 1;
} else {
fd = std::make_shared<fat::FileDescriptor>(*file_entry);
}
}
if (fd) {
char u8buf[1024];
DrawCursor(false);
while (true) {
if (ReadDelim(*fd, '\n', u8buf, sizeof(u8buf)) == 0) {
break;
}
PrintToFD(*files_[1], "%s", u8buf);
}
DrawCursor(true);
}
} else if (strcmp(command, "noterm") == 0) {
auto term_desc = new TerminalDescriptor{
first_arg, true, false, files_
};
task_manager->NewTask()
.InitContext(TaskTerminal, reinterpret_cast<int64_t>(term_desc))
.Wakeup();
} else if (strcmp(command, "memstat") == 0) {
const auto p_stat = memory_manager->Stat();
PrintToFD(*files_[1], "Phys used : %lu frames (%llu MiB)\n",
p_stat.allocated_frames,
p_stat.allocated_frames * kBytesPerFrame / 1024 / 1024);
PrintToFD(*files_[1], "Phys total: %lu frames (%llu MiB)\n",
p_stat.total_frames,
p_stat.total_frames * kBytesPerFrame / 1024 / 1024);
} else if (command[0] != 0) {
auto file_entry = FindCommand(command);
if (!file_entry) {
PrintToFD(*files_[2], "no such command: %s\n", command);
exit_code = 1;
} else {
auto [ ec, err ] = ExecuteFile(*file_entry, command, first_arg);
if (err) {
PrintToFD(*files_[2], "failed to exec file: %s\n", err.Name());
exit_code = -ec;
} else {
exit_code = ec;
}
}
}
if (pipe_fd) {
pipe_fd->FinishWrite();
__asm__("cli");
auto [ ec, err ] = task_manager->WaitFinish(subtask_id);
(*layer_task_map)[layer_id_] = task_.ID();
__asm__("sti");
if (err) {
Log(kWarn, "failed to wait finish: %s\n", err.Name());
}
exit_code = ec;
}
last_exit_code_ = exit_code;
files_[1] = original_stdout;
}
WithError<int> Terminal::ExecuteFile(fat::DirectoryEntry& file_entry,
char* command, char* first_arg) {
__asm__("cli");
auto& task = task_manager->CurrentTask();
__asm__("sti");
auto [ app_load, err ] = LoadApp(file_entry, task);
if (err) {
return { 0, err };
}
LinearAddress4Level args_frame_addr{0xffff'ffff'ffff'f000};
if (auto err = SetupPageMaps(args_frame_addr, 1)) {
return { 0, err };
}
auto argv = reinterpret_cast<char**>(args_frame_addr.value);
int argv_len = 32; // argv = 8x32 = 256 bytes
auto argbuf = reinterpret_cast<char*>(args_frame_addr.value + sizeof(char**) * argv_len);
int argbuf_len = 4096 - sizeof(char**) * argv_len;
auto argc = MakeArgVector(command, first_arg, argv, argv_len, argbuf, argbuf_len);
if (argc.error) {
return { 0, argc.error };
}
const int stack_size = 16 * 4096;
LinearAddress4Level stack_frame_addr{0xffff'ffff'ffff'f000 - stack_size};
if (auto err = SetupPageMaps(stack_frame_addr, stack_size / 4096)) {
return { 0, err };
}
for (int i = 0; i < files_.size(); ++i) {
task.Files().push_back(files_[i]);
}
const uint64_t elf_next_page =
(app_load.vaddr_end + 4095) & 0xffff'ffff'ffff'f000;
task.SetDPagingBegin(elf_next_page);
task.SetDPagingEnd(elf_next_page);
task.SetFileMapEnd(stack_frame_addr.value);
int ret = CallApp(argc.value, argv, 3 << 3 | 3, app_load.entry,
stack_frame_addr.value + stack_size - 8,
&task.OSStackPointer());
task.Files().clear();
task.FileMaps().clear();
if (auto err = CleanPageMaps(LinearAddress4Level{0xffff'8000'0000'0000})) {
return { ret, err };
}
return { ret, FreePML4(task) };
}
void Terminal::Print(char32_t c) {
if (!show_window_) {
return;
}
auto newline = [this]() {
cursor_.x = 0;
if (cursor_.y < kRows - 1) {
++cursor_.y;
} else {
Scroll1();
}
};
if (c == U'\n') {
newline();
} else if (IsHankaku(c)) {
if (cursor_.x == kColumns) {
newline();
}
WriteUnicode(*window_->Writer(), CalcCursorPos(), c, {255, 255, 255});
++cursor_.x;
} else {
if (cursor_.x >= kColumns - 1) {
newline();
}
WriteUnicode(*window_->Writer(), CalcCursorPos(), c, {255, 255, 255});
cursor_.x += 2;
}
}
void Terminal::Print(const char* s, std::optional<size_t> len) {
const auto cursor_before = CalcCursorPos();
DrawCursor(false);
size_t i = 0;
const size_t len_ = len ? *len : std::numeric_limits<size_t>::max();
while (s[i] && i < len_) {
const auto [ u32, bytes ] = ConvertUTF8To32(&s[i]);
Print(u32);
i += bytes;
}
DrawCursor(true);
const auto cursor_after = CalcCursorPos();
Vector2D<int> draw_pos{ToplevelWindow::kTopLeftMargin.x, cursor_before.y};
Vector2D<int> draw_size{window_->InnerSize().x,
cursor_after.y - cursor_before.y + 16};
Rectangle<int> draw_area{draw_pos, draw_size};
Message msg = MakeLayerMessage(
task_.ID(), LayerID(), LayerOperation::DrawArea, draw_area);
__asm__("cli");
task_manager->SendMessage(1, msg);
__asm__("sti");
}
void Terminal::Redraw() {
Rectangle<int> draw_area{ToplevelWindow::kTopLeftMargin,
window_->InnerSize()};
Message msg = MakeLayerMessage(
task_.ID(), LayerID(), LayerOperation::DrawArea, draw_area);
__asm__("cli");
task_manager->SendMessage(1, msg);
__asm__("sti");
}
Rectangle<int> Terminal::HistoryUpDown(int direction) {
if (direction == -1 && cmd_history_index_ >= 0) {
--cmd_history_index_;
} else if (direction == 1 && cmd_history_index_ + 1 < cmd_history_.size()) {
++cmd_history_index_;
}
cursor_.x = 1;
const auto first_pos = CalcCursorPos();
Rectangle<int> draw_area{first_pos, {8*(kColumns - 1), 16}};
FillRectangle(*window_->Writer(), draw_area.pos, draw_area.size, {0, 0, 0});
const char* history = "";
if (cmd_history_index_ >= 0) {
history = &cmd_history_[cmd_history_index_][0];
}
strcpy(&linebuf_[0], history);
linebuf_index_ = strlen(history);
WriteString(*window_->Writer(), first_pos, history, {255, 255, 255});
cursor_.x = linebuf_index_ + 1;
return draw_area;
}
void TaskTerminal(uint64_t task_id, int64_t data) {
const auto term_desc = reinterpret_cast<TerminalDescriptor*>(data);
bool show_window = true;
if (term_desc) {
show_window = term_desc->show_window;
}
__asm__("cli");
Task& task = task_manager->CurrentTask();
Terminal* terminal = new Terminal{task, term_desc};
if (show_window) {
layer_manager->Move(terminal->LayerID(), {100, 200});
layer_task_map->insert(std::make_pair(terminal->LayerID(), task_id));
active_layer->Activate(terminal->LayerID());
}
__asm__("sti");
if (term_desc && !term_desc->command_line.empty()) {
for (int i = 0; i < term_desc->command_line.length(); ++i) {
terminal->InputKey(0, 0, term_desc->command_line[i]);
}
terminal->InputKey(0, 0, '\n');
}
if (term_desc && term_desc->exit_after_command) {
delete term_desc;
__asm__("cli");
task_manager->Finish(terminal->LastExitCode());
__asm__("sti");
}
auto add_blink_timer = [task_id](unsigned long t){
timer_manager->AddTimer(Timer{t + static_cast<int>(kTimerFreq * 0.5),
1, task_id});
};
add_blink_timer(timer_manager->CurrentTick());
bool window_isactive = false;
while (true) {
__asm__("cli");
auto msg = task.ReceiveMessage();
if (!msg) {
task.Sleep();
__asm__("sti");
continue;
}
__asm__("sti");
switch (msg->type) {
case Message::kTimerTimeout:
add_blink_timer(msg->arg.timer.timeout);
if (show_window && window_isactive) {
const auto area = terminal->BlinkCursor();
Message msg = MakeLayerMessage(
task_id, terminal->LayerID(), LayerOperation::DrawArea, area);
__asm__("cli");
task_manager->SendMessage(1, msg);
__asm__("sti");
}
break;
case Message::kKeyPush:
if (msg->arg.keyboard.press) {
const auto area = terminal->InputKey(msg->arg.keyboard.modifier,
msg->arg.keyboard.keycode,
msg->arg.keyboard.ascii);
if (show_window) {
Message msg = MakeLayerMessage(
task_id, terminal->LayerID(), LayerOperation::DrawArea, area);
__asm__("cli");
task_manager->SendMessage(1, msg);
__asm__("sti");
}
}
break;
case Message::kWindowActive:
window_isactive = msg->arg.window_active.activate;
break;
case Message::kWindowClose:
CloseLayer(msg->arg.window_close.layer_id);
__asm__("cli");
task_manager->Finish(terminal->LastExitCode());
break;
default:
break;
}
}
}
TerminalFileDescriptor::TerminalFileDescriptor(Terminal& term)
: term_{term} {
}
size_t TerminalFileDescriptor::Read(void* buf, size_t len) {
char* bufc = reinterpret_cast<char*>(buf);
while (true) {
__asm__("cli");
auto msg = term_.UnderlyingTask().ReceiveMessage();
if (!msg) {
term_.UnderlyingTask().Sleep();
continue;
}
__asm__("sti");
if (msg->type != Message::kKeyPush || !msg->arg.keyboard.press) {
continue;
}
if (msg->arg.keyboard.modifier & (kLControlBitMask | kRControlBitMask)) {
char s[3] = "^ ";
s[1] = toupper(msg->arg.keyboard.ascii);
term_.Print(s);
if (msg->arg.keyboard.keycode == 7 /* D */) {
return 0; // EOT
}
continue;
}
bufc[0] = msg->arg.keyboard.ascii;
term_.Print(bufc, 1);
term_.Redraw();
return 1;
}
}
size_t TerminalFileDescriptor::Write(const void* buf, size_t len) {
term_.Print(reinterpret_cast<const char*>(buf), len);
term_.Redraw();
return len;
}
size_t TerminalFileDescriptor::Load(void* buf, size_t len, size_t offset) {
return 0;
}
PipeDescriptor::PipeDescriptor(Task& task) : task_{task} {
}
size_t PipeDescriptor::Read(void* buf, size_t len) {
if (len_ > 0) {
const size_t copy_bytes = std::min(len_, len);
memcpy(buf, data_, copy_bytes);
len_ -= copy_bytes;
memmove(data_, &data_[copy_bytes], len_);
return copy_bytes;
}
if (closed_) {
return 0;
}
while (true) {
__asm__("cli");
auto msg = task_.ReceiveMessage();
if (!msg) {
task_.Sleep();
continue;
}
__asm__("sti");
if (msg->type != Message::kPipe) {
continue;
}
if (msg->arg.pipe.len == 0) {
closed_ = true;
return 0;
}
const size_t copy_bytes = std::min<size_t>(msg->arg.pipe.len, len);
memcpy(buf, msg->arg.pipe.data, copy_bytes);
len_ = msg->arg.pipe.len - copy_bytes;
memcpy(data_, &msg->arg.pipe.data[copy_bytes], len_);
return copy_bytes;
}
}
size_t PipeDescriptor::Write(const void* buf, size_t len) {
auto bufc = reinterpret_cast<const char*>(buf);
Message msg{Message::kPipe};
size_t sent_bytes = 0;
while (sent_bytes < len) {
msg.arg.pipe.len = std::min(len - sent_bytes, sizeof(msg.arg.pipe.data));
memcpy(msg.arg.pipe.data, &bufc[sent_bytes], msg.arg.pipe.len);
sent_bytes += msg.arg.pipe.len;
__asm__("cli");
task_.SendMessage(msg);
__asm__("sti");
}
return len;
}
void PipeDescriptor::FinishWrite() {
Message msg{Message::kPipe};
msg.arg.pipe.len = 0;
__asm__("cli");
task_.SendMessage(msg);
__asm__("sti");
}
// #@@range_end(pipe_fd_finishwrite)
| [
"tttt4aaaa@gmail.com"
] | tttt4aaaa@gmail.com |
4152ccc6ea7c45ae0f606ceeb1edc4b554551fda | 9e4efb5e58c7184d0152789075f84a7a957e3d7a | /src/FFXController.cpp | bddae354b99f499e8665222ee49df060189dc4db | [
"MIT"
] | permissive | Fejitatete/FastFX | 6346ab8fafe316153ea23bfeeba199a428ad1aec | 8cbcc39c3e9beae4b6b53b2cfb37a0fe502b70c1 | refs/heads/master | 2022-04-17T16:06:36.575429 | 2020-04-16T12:34:18 | 2020-04-16T12:34:18 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,477 | cpp | //
// FFXController.cpp
//
// Copyright 2020 - Geoff Moehrke
// gmoehrke@gmail.com
//
#include "FFXController.h"
#include "FFXCoreEffects.h"
FFXController::FFXController( FFXPixelController *initSC ) {
initialize( initSC );
}
FFXController::FFXController() {
}
void FFXController::initialize( FFXPixelController *initPC ) {
if (ledController) {
delete ledController;
}
for (auto seg : segments) { delete seg; }
segments.clear();
ledController = initPC;
ledController->setBrightness(255);
numLeds = ledController->getNumLeds();
liveLeds = ledController->getLeds();
addSegment( PRIMARY_SEG_NAME, 0, numLeds-1, nullptr );
}
void FFXController::setFX( FFXBase *newFX ) {
if (newFX) {
getPrimarySegment()->setFX(newFX);
}
}
void FFXController::setOverlayFX( FFXOverlay *newFX ) {
if (newFX) {
if (ovlFX) {
onFXEvent( "", FX_OVERLAY_STOPPED, ovlFX->getFXName() );
removeOverlayFX();
}
if (ovlLeds == nullptr) {
ovlLeds = new CRGB[numLeds];
}
fill_solid( ovlLeds, numLeds, CRGB::Black );
if (ovlFrameView == nullptr) {
ovlFrameView = new FFXFrameProvider(getPrimarySegment(), ovlLeds);
}
ovlFX = newFX;
ovlFX->start();
onFXEvent( "", FX_OVERLAY_STARTED, ovlFX->getFXName() );
}
}
void FFXController::removeOverlayFX() {
if (ovlFrameView) {
delete ovlFrameView;
ovlFrameView = nullptr;
}
if (ovlFX) {
delete ovlFX;
ovlFX = nullptr;
}
if (ovlLeds) {
delete ovlLeds;
ovlLeds = nullptr;
}
}
FFXSegment *FFXController::addSegment(String initTag, uint16_t initStartIdx, uint16_t initEndIdx, FFXBase* initEffect ) {
FFXSegment *result = nullptr;
auto it = std::find_if( segments.begin(), segments.end(), [&initTag](FFXSegment*& element) -> bool { return element->compareTag(initTag); } );
if (it!=segments.end()) {
result = *it;
}
else {
if (!initEffect) { initEffect = new SolidFX( initEndIdx-initStartIdx+1 ); }
result = new FFXSegment( initTag, initStartIdx, initEndIdx, initEffect, liveLeds, this );
segments.push_back( result );
if (result->getFX()) {
result->getFX()->start();
}
}
return result;
}
FFXSegment *FFXController::findSegment(String &tag) {
auto it = std::find_if( segments.begin(), segments.end(), [&tag](FFXSegment*& element) -> bool { return element->compareTag(tag); } );
if (it==segments.end()) {
return getPrimarySegment();
}
else {
return *it;
}
}
void FFXController::show() {
if (centerOffset > 0) {
FFXBase::rotateBufferForwardWithWrap( liveLeds, liveLeds, numLeds, centerOffset );
}
if (ovlFX) { ovlFX->applyOverlay( ovlLeds, liveLeds ); }
if (centerOffset > 0) {
FFXBase::rotateBufferBackwardWithWrap( liveLeds, liveLeds, numLeds, centerOffset );
}
ledController->show();
}
void FFXController::update() {
for (auto seg : segments) {
seg->updateFrame( liveLeds );
}
if (ovlFX) {
ovlFrameView->updateFrame( ovlLeds, ovlFX );
if (ovlFX->isDone()) {
onFXEvent( "", FX_OVERLAY_COMPLETED, ovlFX->getFXName());
removeOverlayFX();
}
}
bool segUpdated = false;
for (auto i : segments) {
if (i->isUpdated()) { segUpdated=true; }
if (i->isStateChanged()) { this->onFXStateChange(i); i->resetStateChanged(); }
}
if ( segUpdated || ovlFX ) {
show();
showCount++;
}
}
| [
"gmoehrke@gmail.com"
] | gmoehrke@gmail.com |
189ee0ccedaaa4871e0839aebf0626385f8b9ee7 | f621c6b39a0ee97dae850809c5c4796e0e3f4fb3 | /RunningSum/Solution.cpp | a5cc88b3e6f62d77952120f227ce07adc67dd732 | [] | no_license | JacobRammer/LeetCode | cfe0766304f7fcd3efa4e4bb9b544e5d1970fe31 | 297a67e7c6961de1dd4a6418689c193d0b72fb9b | refs/heads/master | 2022-11-22T13:07:49.522305 | 2020-07-25T06:11:29 | 2020-07-25T06:11:29 | 279,920,075 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 373 | cpp | //
// Created by Jacob Rammer on 7/15/20.
//
#include "Solution.h"
vector<int> Solution::runningSum(vector<int> &nums) {
int itterLen = nums.size() - 1;
vector<int> retVal;
retVal.reserve(nums.size());
retVal.push_back(nums[0]);
for(int i = 0; i < itterLen; i++)
{
retVal.push_back(retVal[i] + nums[i + 1]);
}
return retVal;
}
| [
"jrammer101@gmail.com"
] | jrammer101@gmail.com |
093343c6183a9a884251c4c73d3b978c43d28413 | a5a99f646e371b45974a6fb6ccc06b0a674818f2 | /CalibPPS/AlignmentRelative/interface/LocalTrackFitter.h | dc68f1bd628858a9da8d14bcd4ee18f8b554cefc | [
"Apache-2.0"
] | permissive | cms-sw/cmssw | 4ecd2c1105d59c66d385551230542c6615b9ab58 | 19c178740257eb48367778593da55dcad08b7a4f | refs/heads/master | 2023-08-23T21:57:42.491143 | 2023-08-22T20:22:40 | 2023-08-22T20:22:40 | 10,969,551 | 1,006 | 3,696 | Apache-2.0 | 2023-09-14T19:14:28 | 2013-06-26T14:09:07 | C++ | UTF-8 | C++ | false | false | 1,723 | h | /****************************************************************************
* Authors:
* Jan Kašpar (jan.kaspar@gmail.com)
****************************************************************************/
#ifndef CalibPPS_AlignmentRelative_LocalTrackFitter_h
#define CalibPPS_AlignmentRelative_LocalTrackFitter_h
#include "CalibPPS/AlignmentRelative/interface/LocalTrackFit.h"
#include "CalibPPS/AlignmentRelative/interface/AlignmentGeometry.h"
#include "CalibPPS/AlignmentRelative/interface/HitCollection.h"
namespace edm {
class ParameterSet;
}
/**
*\brief Performs straight-line fit and outlier rejection.
**/
class LocalTrackFitter {
public:
/// dummy constructor (not to be used)
LocalTrackFitter() {}
/// normal constructor
LocalTrackFitter(const edm::ParameterSet &);
virtual ~LocalTrackFitter() {}
/// runs the fit and outlier-removal loop
/// returns true in case of success
bool fit(HitCollection &, const AlignmentGeometry &, LocalTrackFit &) const;
protected:
/// verbosity level
unsigned int verbosity;
/// minimum of hits to accept data from a RP
unsigned int minimumHitsPerProjectionPerRP;
/// hits with higher ratio residual/sigma will be dropped
double maxResidualToSigma;
/// fits the collection of hits and removes hits with too high residual/sigma ratio
/// \param failed whether the fit has failed
/// \param selectionChanged whether some hits have been removed
void fitAndRemoveOutliers(
HitCollection &, const AlignmentGeometry &, LocalTrackFit &, bool &failed, bool &selectionChanged) const;
/// removes the hits of pots with too few planes active
void removeInsufficientPots(HitCollection &, bool &selectionChanged) const;
};
#endif
| [
"noreply@github.com"
] | noreply@github.com |
2ae59f2cc6209edc3992febc59b9381739a7e71e | b19f30140cef064cbf4b18e749c9d8ebdd8bf27f | /D3DGame_181122_076_1_Geometry_Billboard/Renders/Context.cpp | dc2d11a011dfb02afe517b09a519cf585acce618 | [] | no_license | evehour/SGADHLee | 675580e199991916cf3134e7c61749b0a0bfa070 | 0ebbedf5d0692b782e2e5f9a372911c65f98ddc4 | refs/heads/master | 2020-03-25T13:22:42.597811 | 2019-01-03T07:05:54 | 2019-01-03T07:05:54 | 143,822,128 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,370 | cpp | #include "stdafx.h"
#include "Context.h"
#include "../Viewer/Perspective.h"
#include "../Viewer/Viewport.h"
#include "../Viewer/Freedom.h"
Context* Context::instance = NULL;
void Context::Create()
{
assert(instance == NULL);
instance = new Context();
}
void Context::Delete()
{
SAFE_DELETE(instance);
}
Context * Context::Get()
{
return instance;
}
void Context::Update()
{
mainCamera->Update();
mainCamera->Matrix(&perFrame.View);
mainCamera->Position(&perFrame.ViewPosition);
mainCamera->Forward(&perFrame.ViewDirection);
perFrame.Time = Time::Get()->Running();
for (pair<Shader *, CBuffer*> temp : perFrameMap)
temp.second->Change();
CBuffers::Update();
}
Context::Context()
{
D3DDesc desc;
D3D::GetDesc(&desc);
perspective = new Perspective(desc.Width, desc.Height);
perspective->GetMatrix(&projection.Project);
mainCamera = new Freedom();
viewport = new Viewport(desc.Width, desc.Height);
}
Context::~Context()
{
for (pair<Shader *, CBuffer*> temp : perFrameMap)
SAFE_DELETE(temp.second);
for (pair<Shader *, CBuffer*> temp : projectionMap)
SAFE_DELETE(temp.second);
for (pair<Shader *, CBuffer*> temp : lightMap)
SAFE_DELETE(temp.second);
SAFE_DELETE(mainCamera);
SAFE_DELETE(perspective);
SAFE_DELETE(viewport);
}
void Context::AddShader(Shader * shader)
{
CBuffer* cbPerFrame = new CBuffer(shader, "CB_PerFrame", &perFrame, sizeof(PerFrame));
perFrameMap.insert(pair<Shader *, CBuffer*>(shader, cbPerFrame));
CBuffer* cbProjection = new CBuffer(shader, "CB_Projection", &projection, sizeof(Projection));
projectionMap.insert(pair<Shader *, CBuffer*>(shader, cbProjection));
CBuffer* cbLight = new CBuffer(shader, "CB_Light", &light, sizeof(GlobalLight));
lightMap.insert(pair<Shader *, CBuffer*>(shader, cbLight));
}
Perspective * Context::GetPerspective()
{
return perspective;
}
void Context::ChangePerspective()
{
for (pair<Shader *, CBuffer*> temp : projectionMap)
temp.second->Change();
}
Viewport * Context::GetViewport()
{
return viewport;
}
void Context::ChangeView()
{
for (pair<Shader *, CBuffer*> temp : perFrameMap)
temp.second->Change();
}
Camera * Context::GetMainCamera()
{
return mainCamera;
}
Context::GlobalLight * Context::GetGlobalLight()
{
return &light;
}
void Context::ChangeGlobalLight()
{
for (pair<Shader *, CBuffer*> temp : lightMap)
temp.second->Change();
} | [
"evehour@gmail.com"
] | evehour@gmail.com |
d5d9c6f52857de63aa4040c6d0c9db393ef265ca | 1ae40287c5705f341886bbb5cc9e9e9cfba073f7 | /Osmium/SDK/FN_GCN_Carmine_Punch_Impact_classes.hpp | 8c9ae47a3588647e87731a4d8f21f0c33b91f693 | [] | no_license | NeoniteDev/Osmium | 183094adee1e8fdb0d6cbf86be8f98c3e18ce7c0 | aec854e60beca3c6804f18f21b6a0a0549e8fbf6 | refs/heads/master | 2023-07-05T16:40:30.662392 | 2023-06-28T23:17:42 | 2023-06-28T23:17:42 | 340,056,499 | 14 | 8 | null | null | null | null | UTF-8 | C++ | false | false | 833 | hpp | #pragma once
// Fortnite (4.5-CL-4159770) SDK
#ifdef _MSC_VER
#pragma pack(push, 0x8)
#endif
namespace SDK
{
//---------------------------------------------------------------------------
//Classes
//---------------------------------------------------------------------------
// BlueprintGeneratedClass GCN_Carmine_Punch_Impact.GCN_Carmine_Punch_Impact_C
// 0x0000 (0x0080 - 0x0080)
class UGCN_Carmine_Punch_Impact_C : public UFortGameplayCueNotify_Simple
{
public:
static UClass* StaticClass()
{
static auto ptr = UObject::FindClass("BlueprintGeneratedClass GCN_Carmine_Punch_Impact.GCN_Carmine_Punch_Impact_C");
return ptr;
}
void OnStartParticleSystemSpawned(class UParticleSystemComponent** SpawnedParticleSysComponent, struct FGameplayCueParameters* Parameters);
};
}
#ifdef _MSC_VER
#pragma pack(pop)
#endif
| [
"kareemolim@gmail.com"
] | kareemolim@gmail.com |
2b45a532c3911b561d625539ed073c95161daed8 | 6c620e457c2f9f6de22dc6fbf43438da20e4aa57 | /testlib/checker.cpp | f0e300661d1b7024789274290ac2f09515a58fec | [
"MIT"
] | permissive | ZSYTY/DOJ | 5d07741b41f2b2ad14b4b0c83511afd326606da5 | 26c5d792742061f7a9322985d1753232bb083172 | refs/heads/master | 2020-03-30T08:00:34.255940 | 2018-09-29T09:40:21 | 2018-09-29T09:40:21 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 992 | cpp | #include "testlib.h"
using namespace std;
bool spaces(string s) {
int len = s.length();
for (int i = 0; i < len; i++)
if (s[i] != ' ')
return false;
return true;
}
bool compare(string a, string b) {
int i, alen = a.length(), blen = b.length();
for (i = 0; i < alen && i < blen; i++)
if (a[i] != b[i])
return false;
while (i < alen)
if (a[i++] != ' ')
return false;
while (i < blen)
if (b[i++] != ' ')
return false;
return true;
}
int main(int argc, char * argv[]) {
setName("Answer checker, ignore trailing spaces and empty lines");
registerTestlibCmd(argc, argv);
int line = 0;
while (!ouf.seekEof() && !ans.seekEof())
if (line++, !compare(ouf.readLine(), ans.readLine()))
quitf(_wa, "at line %d", line);
while (!ouf.seekEof())
if (line++, !spaces(ouf.readLine()))
quitf(_wa, "at line %d", line);
while (!ans.seekEof())
if (line++, !spaces(ans.readLine()))
quitf(_wa, "at line %d", line);
quitf(_ok, "- %d line(s) in total", line);
}
| [
"doveccl@live.com"
] | doveccl@live.com |
7ca1f54e073c1b5878a459ffb78eb4f61a727eea | 570fc184f62d1cf8624ca2a5a7fc487af1452754 | /layout/style/test/ListCSSProperties.cpp | d0b3c130b6f11521ee293e4aa1d5e23eeea74d2e | [] | no_license | roytam1/palemoon26 | 726424415a96fb36fe47d5d414a2cfafabecb3e6 | 43b0deedf05166f30d62bd666c040a3165a761a1 | refs/heads/master | 2023-09-03T15:25:23.800487 | 2018-08-25T16:35:59 | 2018-08-28T12:32:52 | 115,328,093 | 6 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 6,417 | cpp | /* vim: set shiftwidth=4 tabstop=8 autoindent cindent expandtab: */
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
/* build (from code) lists of all supported CSS properties */
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
struct PropertyInfo {
const char *propName;
const char *domName;
const char *pref;
};
const PropertyInfo gLonghandProperties[] = {
#define CSS_PROP_PUBLIC_OR_PRIVATE(publicname_, privatename_) publicname_
#define CSS_PROP(name_, id_, method_, flags_, pref_, parsevariant_, kwtable_, \
stylestruct_, stylestructoffset_, animtype_) \
{ #name_, #method_, pref_ },
#include "nsCSSPropList.h"
#undef CSS_PROP
#undef CSS_PROP_PUBLIC_OR_PRIVATE
};
/*
* These are the properties for which domName in the above list should
* be used. They're in the same order as the above list, with some
* items skipped.
*/
const char* gLonghandPropertiesWithDOMProp[] = {
#define CSS_PROP_LIST_EXCLUDE_INTERNAL
#define CSS_PROP(name_, id_, method_, flags_, pref_, parsevariant_, kwtable_, \
stylestruct_, stylestructoffset_, animtype_) \
#name_,
#include "nsCSSPropList.h"
#undef CSS_PROP
#undef CSS_PROP_LIST_EXCLUDE_INTERNAL
};
const PropertyInfo gShorthandProperties[] = {
#define CSS_PROP_PUBLIC_OR_PRIVATE(publicname_, privatename_) publicname_
// Need an extra level of macro nesting to force expansion of method_
// params before they get pasted.
#define LISTCSSPROPERTIES_INNER_MACRO(method_) #method_
#define CSS_PROP_SHORTHAND(name_, id_, method_, flags_, pref_) \
{ #name_, LISTCSSPROPERTIES_INNER_MACRO(method_), pref_ },
#include "nsCSSPropList.h"
#undef CSS_PROP_SHORTHAND
#undef LISTCSSPROPERTIES_INNER_MACRO
#undef CSS_PROP_PUBLIC_OR_PRIVATE
#define CSS_PROP_ALIAS(name_, id_, method_, pref_) \
{ #name_, #method_, pref_ },
#include "nsCSSPropAliasList.h"
#undef CSS_PROP_ALIAS
};
/* see gLonghandPropertiesWithDOMProp */
const char* gShorthandPropertiesWithDOMProp[] = {
#define CSS_PROP_LIST_EXCLUDE_INTERNAL
#define CSS_PROP_SHORTHAND(name_, id_, method_, flags_, pref_) \
#name_,
#include "nsCSSPropList.h"
#undef CSS_PROP_SHORTHAND
#undef CSS_PROP_LIST_EXCLUDE_INTERNAL
#define CSS_PROP_ALIAS(name_, id_, method_, pref_) \
#name_,
#include "nsCSSPropAliasList.h"
#undef CSS_PROP_ALIAS
};
#define ARRAY_LENGTH(a_) (sizeof(a_)/sizeof((a_)[0]))
const char *gInaccessibleProperties[] = {
// Don't print the properties that aren't accepted by the parser, per
// CSSParserImpl::ParseProperty
"-x-cols",
"-x-lang",
"-x-span",
"-x-system-font",
"-x-text-zoom",
"border-end-color-value",
"border-end-style-value",
"border-end-width-value",
"border-left-color-value",
"border-left-color-ltr-source",
"border-left-color-rtl-source",
"border-left-style-value",
"border-left-style-ltr-source",
"border-left-style-rtl-source",
"border-left-width-value",
"border-left-width-ltr-source",
"border-left-width-rtl-source",
"border-right-color-value",
"border-right-color-ltr-source",
"border-right-color-rtl-source",
"border-right-style-value",
"border-right-style-ltr-source",
"border-right-style-rtl-source",
"border-right-width-value",
"border-right-width-ltr-source",
"border-right-width-rtl-source",
"border-start-color-value",
"border-start-style-value",
"border-start-width-value",
"margin-end-value",
"margin-left-value",
"margin-right-value",
"margin-start-value",
"margin-left-ltr-source",
"margin-left-rtl-source",
"margin-right-ltr-source",
"margin-right-rtl-source",
"padding-end-value",
"padding-left-value",
"padding-right-value",
"padding-start-value",
"padding-left-ltr-source",
"padding-left-rtl-source",
"padding-right-ltr-source",
"padding-right-rtl-source",
"-moz-script-level", // parsed by UA sheets only
"-moz-script-size-multiplier",
"-moz-script-min-size"
};
inline int
is_inaccessible(const char* aPropName)
{
for (unsigned j = 0; j < ARRAY_LENGTH(gInaccessibleProperties); ++j) {
if (strcmp(aPropName, gInaccessibleProperties[j]) == 0)
return 1;
}
return 0;
}
void
print_array(const char *aName,
const PropertyInfo *aProps, unsigned aPropsLength,
const char * const * aDOMProps, unsigned aDOMPropsLength)
{
printf("var %s = [\n", aName);
int first = 1;
unsigned j = 0; // index into DOM prop list
for (unsigned i = 0; i < aPropsLength; ++i) {
const PropertyInfo *p = aProps + i;
if (is_inaccessible(p->propName))
// inaccessible properties never have DOM props, so don't
// worry about incrementing j. The assertion below will
// catch if they do.
continue;
if (first)
first = 0;
else
printf(",\n");
printf("\t{ name: \"%s\", prop: ", p->propName);
if (j >= aDOMPropsLength || strcmp(p->propName, aDOMProps[j]) != 0)
printf("null");
else {
++j;
if (strncmp(p->domName, "Moz", 3) == 0)
printf("\"%s\"", p->domName);
else
// lowercase the first letter
printf("\"%c%s\"", p->domName[0] + 32, p->domName + 1);
}
if (p->pref[0]) {
printf(", pref: \"%s\"", p->pref);
}
printf(" }");
}
if (j != aDOMPropsLength) {
fprintf(stderr, "Assertion failure %s:%d\n", __FILE__, __LINE__);
fprintf(stderr, "j==%d, aDOMPropsLength == %d\n", j, aDOMPropsLength);
exit(1);
}
printf("\n];\n\n");
}
int
main()
{
print_array("gLonghandProperties",
gLonghandProperties,
ARRAY_LENGTH(gLonghandProperties),
gLonghandPropertiesWithDOMProp,
ARRAY_LENGTH(gLonghandPropertiesWithDOMProp));
print_array("gShorthandProperties",
gShorthandProperties,
ARRAY_LENGTH(gShorthandProperties),
gShorthandPropertiesWithDOMProp,
ARRAY_LENGTH(gShorthandPropertiesWithDOMProp));
return 0;
}
| [
"roytam@gmail.com"
] | roytam@gmail.com |
4647593d142aa881a85e6f8214036e424ac8f55d | b28305dab0be0e03765c62b97bcd7f49a4f8073d | /chromeos/services/assistant/platform/audio_output_provider_impl.h | 8c891968f7a44566b94cf9f2721c9f1aa890c369 | [
"BSD-3-Clause"
] | permissive | svarvel/browser-android-tabs | 9e5e27e0a6e302a12fe784ca06123e5ce090ced5 | bd198b4c7a1aca2f3e91f33005d881f42a8d0c3f | refs/heads/base-72.0.3626.105 | 2020-04-24T12:16:31.442851 | 2019-08-02T19:15:36 | 2019-08-02T19:15:36 | 171,950,555 | 1 | 2 | NOASSERTION | 2019-08-02T19:15:37 | 2019-02-21T21:47:44 | null | UTF-8 | C++ | false | false | 5,619 | h | // Copyright 2018 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 CHROMEOS_SERVICES_ASSISTANT_PLATFORM_AUDIO_OUTPUT_PROVIDER_IMPL_H_
#define CHROMEOS_SERVICES_ASSISTANT_PLATFORM_AUDIO_OUTPUT_PROVIDER_IMPL_H_
#include <memory>
#include <vector>
#include "ash/public/interfaces/assistant_volume_control.mojom.h"
#include "base/macros.h"
#include "base/single_thread_task_runner.h"
#include "chromeos/services/assistant/public/mojom/assistant_audio_decoder.mojom.h"
#include "libassistant/shared/public/platform_audio_output.h"
#include "media/base/audio_block_fifo.h"
#include "media/base/audio_parameters.h"
#include "media/base/audio_renderer_sink.h"
#include "mojo/public/cpp/bindings/binding.h"
#include "services/audio/public/cpp/output_device.h"
namespace service_manager {
class Connector;
} // namespace service_manager
namespace chromeos {
namespace assistant {
class VolumeControlImpl : public assistant_client::VolumeControl,
public ash::mojom::VolumeObserver {
public:
explicit VolumeControlImpl(service_manager::Connector* connector);
~VolumeControlImpl() override;
// assistant_client::VolumeControl overrides:
void SetAudioFocus(
assistant_client::OutputStreamType focused_stream) override;
float GetSystemVolume() override;
void SetSystemVolume(float new_volume, bool user_initiated) override;
float GetAlarmVolume() override;
void SetAlarmVolume(float new_volume, bool user_initiated) override;
bool IsSystemMuted() override;
void SetSystemMuted(bool muted) override;
// ash::mojom::VolumeObserver overrides:
void OnVolumeChanged(int volume) override;
void OnMuteStateChanged(bool mute) override;
private:
void SetSystemVolumeOnMainThread(float new_volume, bool user_initiated);
void SetSystemMutedOnMainThread(bool muted);
ash::mojom::AssistantVolumeControlPtr volume_control_ptr_;
mojo::Binding<ash::mojom::VolumeObserver> binding_;
scoped_refptr<base::SequencedTaskRunner> main_thread_task_runner_;
int volume_ = 100;
bool mute_ = false;
base::WeakPtrFactory<VolumeControlImpl> weak_factory_;
DISALLOW_COPY_AND_ASSIGN(VolumeControlImpl);
};
class AudioOutputProviderImpl : public assistant_client::AudioOutputProvider {
public:
explicit AudioOutputProviderImpl(
service_manager::Connector* connector,
scoped_refptr<base::SequencedTaskRunner> background_task_runner);
~AudioOutputProviderImpl() override;
// assistant_client::AudioOutputProvider overrides:
assistant_client::AudioOutput* CreateAudioOutput(
assistant_client::OutputStreamType type,
const assistant_client::OutputStreamFormat& stream_format) override;
std::vector<assistant_client::OutputStreamEncoding>
GetSupportedStreamEncodings() override;
assistant_client::AudioInput* GetReferenceInput() override;
bool SupportsPlaybackTimestamp() const override;
assistant_client::VolumeControl& GetVolumeControl() override;
void RegisterAudioEmittingStateCallback(
AudioEmittingStateCallback callback) override;
private:
VolumeControlImpl volume_control_impl_;
service_manager::Connector* connector_;
scoped_refptr<base::SequencedTaskRunner> main_thread_task_runner_;
scoped_refptr<base::SequencedTaskRunner> background_task_runner_;
mojom::AssistantAudioDecoderFactoryPtr audio_decoder_factory_ptr_;
mojom::AssistantAudioDecoderFactory* audio_decoder_factory_;
DISALLOW_COPY_AND_ASSIGN(AudioOutputProviderImpl);
};
class AudioDeviceOwner : public media::AudioRendererSink::RenderCallback {
public:
AudioDeviceOwner(
scoped_refptr<base::SequencedTaskRunner> task_runner,
scoped_refptr<base::SequencedTaskRunner> background_task_runner);
~AudioDeviceOwner() override;
void StartOnMainThread(assistant_client::AudioOutput::Delegate* delegate,
service_manager::Connector* connector,
const assistant_client::OutputStreamFormat& format);
void StopOnBackgroundThread();
// media::AudioRenderSink::RenderCallback overrides:
int Render(base::TimeDelta delay,
base::TimeTicks delay_timestamp,
int prior_frames_skipped,
media::AudioBus* dest) override;
void OnRenderError() override;
void SetDelegate(assistant_client::AudioOutput::Delegate* delegate);
private:
void StartDeviceOnBackgroundThread(
std::unique_ptr<service_manager::Connector> connector);
// Requests assistant to fill buffer with more data.
void ScheduleFillLocked(const base::TimeTicks& time);
// Callback for assistant to notify that it completes the filling.
void BufferFillDone(int num_bytes);
scoped_refptr<base::SequencedTaskRunner> main_thread_task_runner_;
scoped_refptr<base::SequencedTaskRunner> background_task_runner_;
base::Lock lock_;
std::unique_ptr<media::AudioBlockFifo> audio_fifo_; // guarded by lock_.
// Whether assistant is filling the buffer -- delegate_->FillBuffer is called
// and BufferFillDone() is not called yet.
// guarded by lock_.
bool is_filling_ = false;
assistant_client::AudioOutput::Delegate* delegate_;
std::unique_ptr<audio::OutputDevice> output_device_;
// Stores audio frames generated by assistant.
std::vector<uint8_t> audio_data_;
assistant_client::OutputStreamFormat format_;
media::AudioParameters audio_param_;
DISALLOW_COPY_AND_ASSIGN(AudioDeviceOwner);
};
} // namespace assistant
} // namespace chromeos
#endif // CHROMEOS_SERVICES_ASSISTANT_PLATFORM_AUDIO_OUTPUT_PROVIDER_IMPL_H_
| [
"artem@brave.com"
] | artem@brave.com |
38ff0fd53401c2e9b77fec5fc5666ab62ce13b9a | 72a146dad10c3330548f175643822e6cc2e2ccba | /content/renderer/media/webrtc_audio_renderer.cc | c41b69fd56269fc9483a76a0a243c99fe83ae048 | [
"BSD-3-Clause"
] | permissive | daotianya/browser-android-tabs | bb6772394c2138e2f3859a83ec6e0860d01a6161 | 44e83a97eb1c7775944a04144e161d99cbb7de5b | refs/heads/master | 2020-06-10T18:07:58.392087 | 2016-12-07T15:37:13 | 2016-12-07T15:37:13 | 75,914,703 | 1 | 0 | null | 2016-12-08T07:37:51 | 2016-12-08T07:37:51 | null | UTF-8 | C++ | false | false | 23,290 | cc | // Copyright (c) 2012 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.
#include "content/renderer/media/webrtc_audio_renderer.h"
#include <utility>
#include "base/bind.h"
#include "base/bind_helpers.h"
#include "base/location.h"
#include "base/logging.h"
#include "base/metrics/histogram.h"
#include "base/strings/string_util.h"
#include "base/strings/stringprintf.h"
#include "build/build_config.h"
#include "content/renderer/media/audio_device_factory.h"
#include "content/renderer/media/media_stream_audio_track.h"
#include "content/renderer/media/webrtc/peer_connection_remote_audio_source.h"
#include "content/renderer/media/webrtc_logging.h"
#include "media/audio/sample_rates.h"
#include "media/base/audio_capturer_source.h"
#include "media/base/audio_latency.h"
#include "media/base/audio_parameters.h"
#include "third_party/WebKit/public/platform/WebMediaStreamTrack.h"
#include "third_party/webrtc/api/mediastreaminterface.h"
#if defined(OS_WIN)
#include "base/win/windows_version.h"
#include "media/audio/win/core_audio_util_win.h"
#endif
namespace content {
namespace {
// Audio parameters that don't change.
const media::AudioParameters::Format kFormat =
media::AudioParameters::AUDIO_PCM_LOW_LATENCY;
const media::ChannelLayout kChannelLayout = media::CHANNEL_LAYOUT_STEREO;
const int kChannels = 2;
const int kBitsPerSample = 16;
// Used for UMA histograms.
const int kRenderTimeHistogramMinMicroseconds = 100;
const int kRenderTimeHistogramMaxMicroseconds = 1 * 1000 * 1000; // 1 second
// This is a simple wrapper class that's handed out to users of a shared
// WebRtcAudioRenderer instance. This class maintains the per-user 'playing'
// and 'started' states to avoid problems related to incorrect usage which
// might violate the implementation assumptions inside WebRtcAudioRenderer
// (see the play reference count).
class SharedAudioRenderer : public MediaStreamAudioRenderer {
public:
// Callback definition for a callback that is called when when Play(), Pause()
// or SetVolume are called (whenever the internal |playing_state_| changes).
typedef base::Callback<void(const blink::WebMediaStream&,
WebRtcAudioRenderer::PlayingState*)>
OnPlayStateChanged;
SharedAudioRenderer(const scoped_refptr<MediaStreamAudioRenderer>& delegate,
const blink::WebMediaStream& media_stream,
const OnPlayStateChanged& on_play_state_changed)
: delegate_(delegate),
media_stream_(media_stream),
started_(false),
on_play_state_changed_(on_play_state_changed) {
DCHECK(!on_play_state_changed_.is_null());
DCHECK(!media_stream_.isNull());
}
protected:
~SharedAudioRenderer() override {
DCHECK(thread_checker_.CalledOnValidThread());
DVLOG(1) << __func__;
Stop();
}
void Start() override {
DCHECK(thread_checker_.CalledOnValidThread());
if (started_)
return;
started_ = true;
delegate_->Start();
}
void Play() override {
DCHECK(thread_checker_.CalledOnValidThread());
DCHECK(started_);
if (playing_state_.playing())
return;
playing_state_.set_playing(true);
on_play_state_changed_.Run(media_stream_, &playing_state_);
}
void Pause() override {
DCHECK(thread_checker_.CalledOnValidThread());
DCHECK(started_);
if (!playing_state_.playing())
return;
playing_state_.set_playing(false);
on_play_state_changed_.Run(media_stream_, &playing_state_);
}
void Stop() override {
DCHECK(thread_checker_.CalledOnValidThread());
if (!started_)
return;
Pause();
started_ = false;
delegate_->Stop();
}
void SetVolume(float volume) override {
DCHECK(thread_checker_.CalledOnValidThread());
DCHECK(volume >= 0.0f && volume <= 1.0f);
playing_state_.set_volume(volume);
on_play_state_changed_.Run(media_stream_, &playing_state_);
}
media::OutputDeviceInfo GetOutputDeviceInfo() override {
DCHECK(thread_checker_.CalledOnValidThread());
return delegate_->GetOutputDeviceInfo();
}
void SwitchOutputDevice(
const std::string& device_id,
const url::Origin& security_origin,
const media::OutputDeviceStatusCB& callback) override {
DCHECK(thread_checker_.CalledOnValidThread());
return delegate_->SwitchOutputDevice(device_id, security_origin, callback);
}
base::TimeDelta GetCurrentRenderTime() const override {
DCHECK(thread_checker_.CalledOnValidThread());
return delegate_->GetCurrentRenderTime();
}
bool IsLocalRenderer() const override {
DCHECK(thread_checker_.CalledOnValidThread());
return delegate_->IsLocalRenderer();
}
private:
base::ThreadChecker thread_checker_;
const scoped_refptr<MediaStreamAudioRenderer> delegate_;
const blink::WebMediaStream media_stream_;
bool started_;
WebRtcAudioRenderer::PlayingState playing_state_;
OnPlayStateChanged on_play_state_changed_;
};
} // namespace
WebRtcAudioRenderer::WebRtcAudioRenderer(
const scoped_refptr<base::SingleThreadTaskRunner>& signaling_thread,
const blink::WebMediaStream& media_stream,
int source_render_frame_id,
int session_id,
const std::string& device_id,
const url::Origin& security_origin)
: state_(UNINITIALIZED),
source_render_frame_id_(source_render_frame_id),
session_id_(session_id),
signaling_thread_(signaling_thread),
media_stream_(media_stream),
source_(NULL),
play_ref_count_(0),
start_ref_count_(0),
audio_delay_milliseconds_(0),
sink_params_(kFormat, kChannelLayout, 0, kBitsPerSample, 0),
output_device_id_(device_id),
security_origin_(security_origin) {
WebRtcLogMessage(base::StringPrintf(
"WAR::WAR. source_render_frame_id=%d, session_id=%d, effects=%i",
source_render_frame_id, session_id, sink_params_.effects()));
}
WebRtcAudioRenderer::~WebRtcAudioRenderer() {
DCHECK(thread_checker_.CalledOnValidThread());
DCHECK_EQ(state_, UNINITIALIZED);
}
bool WebRtcAudioRenderer::Initialize(WebRtcAudioRendererSource* source) {
DVLOG(1) << "WebRtcAudioRenderer::Initialize()";
DCHECK(thread_checker_.CalledOnValidThread());
DCHECK(source);
DCHECK(!sink_.get());
DCHECK_GE(session_id_, 0);
{
base::AutoLock auto_lock(lock_);
DCHECK_EQ(state_, UNINITIALIZED);
DCHECK(!source_);
}
sink_ = AudioDeviceFactory::NewAudioRendererSink(
AudioDeviceFactory::kSourceWebRtc, source_render_frame_id_, session_id_,
output_device_id_, security_origin_);
if (sink_->GetOutputDeviceInfo().device_status() !=
media::OUTPUT_DEVICE_STATUS_OK) {
return false;
}
PrepareSink();
{
// No need to reassert the preconditions because the other thread accessing
// the fields only reads them.
base::AutoLock auto_lock(lock_);
source_ = source;
// User must call Play() before any audio can be heard.
state_ = PAUSED;
}
sink_->Start();
sink_->Play(); // Not all the sinks play on start.
return true;
}
scoped_refptr<MediaStreamAudioRenderer>
WebRtcAudioRenderer::CreateSharedAudioRendererProxy(
const blink::WebMediaStream& media_stream) {
content::SharedAudioRenderer::OnPlayStateChanged on_play_state_changed =
base::Bind(&WebRtcAudioRenderer::OnPlayStateChanged, this);
return new SharedAudioRenderer(this, media_stream, on_play_state_changed);
}
bool WebRtcAudioRenderer::IsStarted() const {
DCHECK(thread_checker_.CalledOnValidThread());
return start_ref_count_ != 0;
}
bool WebRtcAudioRenderer::CurrentThreadIsRenderingThread() {
return sink_->CurrentThreadIsRenderingThread();
}
void WebRtcAudioRenderer::Start() {
DVLOG(1) << "WebRtcAudioRenderer::Start()";
DCHECK(thread_checker_.CalledOnValidThread());
++start_ref_count_;
}
void WebRtcAudioRenderer::Play() {
DVLOG(1) << "WebRtcAudioRenderer::Play()";
DCHECK(thread_checker_.CalledOnValidThread());
if (playing_state_.playing())
return;
playing_state_.set_playing(true);
OnPlayStateChanged(media_stream_, &playing_state_);
}
void WebRtcAudioRenderer::EnterPlayState() {
DVLOG(1) << "WebRtcAudioRenderer::EnterPlayState()";
DCHECK(thread_checker_.CalledOnValidThread());
DCHECK_GT(start_ref_count_, 0) << "Did you forget to call Start()?";
base::AutoLock auto_lock(lock_);
if (state_ == UNINITIALIZED)
return;
DCHECK(play_ref_count_ == 0 || state_ == PLAYING);
++play_ref_count_;
if (state_ != PLAYING) {
state_ = PLAYING;
if (audio_fifo_) {
audio_delay_milliseconds_ = 0;
audio_fifo_->Clear();
}
}
}
void WebRtcAudioRenderer::Pause() {
DVLOG(1) << "WebRtcAudioRenderer::Pause()";
DCHECK(thread_checker_.CalledOnValidThread());
if (!playing_state_.playing())
return;
playing_state_.set_playing(false);
OnPlayStateChanged(media_stream_, &playing_state_);
}
void WebRtcAudioRenderer::EnterPauseState() {
DVLOG(1) << "WebRtcAudioRenderer::EnterPauseState()";
DCHECK(thread_checker_.CalledOnValidThread());
DCHECK_GT(start_ref_count_, 0) << "Did you forget to call Start()?";
base::AutoLock auto_lock(lock_);
if (state_ == UNINITIALIZED)
return;
DCHECK_EQ(state_, PLAYING);
DCHECK_GT(play_ref_count_, 0);
if (!--play_ref_count_)
state_ = PAUSED;
}
void WebRtcAudioRenderer::Stop() {
DVLOG(1) << "WebRtcAudioRenderer::Stop()";
DCHECK(thread_checker_.CalledOnValidThread());
{
base::AutoLock auto_lock(lock_);
if (state_ == UNINITIALIZED)
return;
if (--start_ref_count_)
return;
DVLOG(1) << "Calling RemoveAudioRenderer and Stop().";
source_->RemoveAudioRenderer(this);
source_ = NULL;
state_ = UNINITIALIZED;
}
// Apart from here, |max_render_time_| is only accessed in SourceCallback(),
// which is guaranteed to not run after |source_| has been set to null, and
// not before this function has returned.
// If |max_render_time_| is zero, no render call has been made.
if (!max_render_time_.is_zero()) {
UMA_HISTOGRAM_CUSTOM_COUNTS(
"Media.Audio.Render.GetSourceDataTimeMax.WebRTC",
max_render_time_.InMicroseconds(),
kRenderTimeHistogramMinMicroseconds,
kRenderTimeHistogramMaxMicroseconds, 50);
max_render_time_ = base::TimeDelta();
}
// Make sure to stop the sink while _not_ holding the lock since the Render()
// callback may currently be executing and trying to grab the lock while we're
// stopping the thread on which it runs.
sink_->Stop();
}
void WebRtcAudioRenderer::SetVolume(float volume) {
DCHECK(thread_checker_.CalledOnValidThread());
DCHECK(volume >= 0.0f && volume <= 1.0f);
playing_state_.set_volume(volume);
OnPlayStateChanged(media_stream_, &playing_state_);
}
media::OutputDeviceInfo WebRtcAudioRenderer::GetOutputDeviceInfo() {
DCHECK(thread_checker_.CalledOnValidThread());
return sink_ ? sink_->GetOutputDeviceInfo() : media::OutputDeviceInfo();
}
base::TimeDelta WebRtcAudioRenderer::GetCurrentRenderTime() const {
DCHECK(thread_checker_.CalledOnValidThread());
base::AutoLock auto_lock(lock_);
return current_time_;
}
bool WebRtcAudioRenderer::IsLocalRenderer() const {
return false;
}
void WebRtcAudioRenderer::SwitchOutputDevice(
const std::string& device_id,
const url::Origin& security_origin,
const media::OutputDeviceStatusCB& callback) {
DVLOG(1) << "WebRtcAudioRenderer::SwitchOutputDevice()";
DCHECK(thread_checker_.CalledOnValidThread());
DCHECK_GE(session_id_, 0);
{
base::AutoLock auto_lock(lock_);
DCHECK(source_);
DCHECK_NE(state_, UNINITIALIZED);
}
scoped_refptr<media::AudioRendererSink> new_sink =
AudioDeviceFactory::NewAudioRendererSink(
AudioDeviceFactory::kSourceWebRtc, source_render_frame_id_,
session_id_, device_id, security_origin);
media::OutputDeviceStatus status =
new_sink->GetOutputDeviceInfo().device_status();
if (status != media::OUTPUT_DEVICE_STATUS_OK) {
callback.Run(status);
return;
}
// Make sure to stop the sink while _not_ holding the lock since the Render()
// callback may currently be executing and trying to grab the lock while we're
// stopping the thread on which it runs.
sink_->Stop();
sink_ = new_sink;
output_device_id_ = device_id;
security_origin_ = security_origin;
{
base::AutoLock auto_lock(lock_);
source_->AudioRendererThreadStopped();
}
PrepareSink();
sink_->Start();
sink_->Play(); // Not all the sinks play on start.
callback.Run(media::OUTPUT_DEVICE_STATUS_OK);
}
int WebRtcAudioRenderer::Render(media::AudioBus* audio_bus,
uint32_t frames_delayed,
uint32_t frames_skipped) {
DCHECK(sink_->CurrentThreadIsRenderingThread());
base::AutoLock auto_lock(lock_);
if (!source_)
return 0;
// TODO(grunell): Converting from frames to milliseconds will potentially lose
// hundreds of microseconds which may cause audio video drift. Update
// this class and all usage of render delay msec -> frames (possibly even
// using a double type for frames). See http://crbug.com/586540
uint32_t audio_delay_milliseconds = static_cast<double>(frames_delayed) *
base::Time::kMillisecondsPerSecond /
sink_params_.sample_rate();
DVLOG(2) << "WebRtcAudioRenderer::Render()";
DVLOG(2) << "audio_delay_milliseconds: " << audio_delay_milliseconds;
DCHECK_LE(audio_delay_milliseconds, static_cast<uint32_t>(INT_MAX));
audio_delay_milliseconds_ = static_cast<int>(audio_delay_milliseconds);
// If there are skipped frames, pull and throw away the same amount. We always
// pull 10 ms of data from the source (see PrepareSink()), so the fifo is only
// required if the number of frames to drop doesn't correspond to 10 ms.
if (frames_skipped > 0) {
const uint32_t source_frames_per_buffer =
static_cast<uint32_t>(sink_params_.sample_rate() / 100);
if (!audio_fifo_ && frames_skipped != source_frames_per_buffer) {
audio_fifo_.reset(new media::AudioPullFifo(
kChannels, source_frames_per_buffer,
base::Bind(&WebRtcAudioRenderer::SourceCallback,
base::Unretained(this))));
}
std::unique_ptr<media::AudioBus> drop_bus =
media::AudioBus::Create(audio_bus->channels(), frames_skipped);
if (audio_fifo_)
audio_fifo_->Consume(drop_bus.get(), drop_bus->frames());
else
SourceCallback(0, drop_bus.get());
}
// Pull the data we will deliver.
if (audio_fifo_)
audio_fifo_->Consume(audio_bus, audio_bus->frames());
else
SourceCallback(0, audio_bus);
return (state_ == PLAYING) ? audio_bus->frames() : 0;
}
void WebRtcAudioRenderer::OnRenderError() {
NOTIMPLEMENTED();
LOG(ERROR) << "OnRenderError()";
}
// Called by AudioPullFifo when more data is necessary.
void WebRtcAudioRenderer::SourceCallback(
int fifo_frame_delay, media::AudioBus* audio_bus) {
DCHECK(sink_->CurrentThreadIsRenderingThread());
base::TimeTicks start_time = base::TimeTicks::Now();
DVLOG(2) << "WebRtcAudioRenderer::SourceCallback("
<< fifo_frame_delay << ", "
<< audio_bus->frames() << ")";
int output_delay_milliseconds = audio_delay_milliseconds_;
// TODO(grunell): This integer division by sample_rate will cause loss of
// partial milliseconds, and may cause avsync drift. http://crbug.com/586540
output_delay_milliseconds += fifo_frame_delay *
base::Time::kMillisecondsPerSecond /
sink_params_.sample_rate();
DVLOG(2) << "output_delay_milliseconds: " << output_delay_milliseconds;
// We need to keep render data for the |source_| regardless of |state_|,
// otherwise the data will be buffered up inside |source_|.
source_->RenderData(audio_bus, sink_params_.sample_rate(),
output_delay_milliseconds,
¤t_time_);
// Avoid filling up the audio bus if we are not playing; instead
// return here and ensure that the returned value in Render() is 0.
if (state_ != PLAYING)
audio_bus->Zero();
// Measure the elapsed time for this function and log it to UMA. Store the max
// value. Don't do this for low resolution clocks to not skew data.
if (base::TimeTicks::IsHighResolution()) {
base::TimeDelta elapsed = base::TimeTicks::Now() - start_time;
UMA_HISTOGRAM_CUSTOM_COUNTS("Media.Audio.Render.GetSourceDataTime.WebRTC",
elapsed.InMicroseconds(),
kRenderTimeHistogramMinMicroseconds,
kRenderTimeHistogramMaxMicroseconds, 50);
if (elapsed > max_render_time_)
max_render_time_ = elapsed;
}
}
void WebRtcAudioRenderer::UpdateSourceVolume(
webrtc::AudioSourceInterface* source) {
DCHECK(thread_checker_.CalledOnValidThread());
// Note: If there are no playing audio renderers, then the volume will be
// set to 0.0.
float volume = 0.0f;
SourcePlayingStates::iterator entry = source_playing_states_.find(source);
if (entry != source_playing_states_.end()) {
PlayingStates& states = entry->second;
for (PlayingStates::const_iterator it = states.begin();
it != states.end(); ++it) {
if ((*it)->playing())
volume += (*it)->volume();
}
}
// The valid range for volume scaling of a remote webrtc source is
// 0.0-10.0 where 1.0 is no attenuation/boost.
DCHECK(volume >= 0.0f);
if (volume > 10.0f)
volume = 10.0f;
DVLOG(1) << "Setting remote source volume: " << volume;
if (!signaling_thread_->BelongsToCurrentThread()) {
// Libjingle hands out proxy objects in most cases, but the audio source
// object is an exception (bug?). So, to work around that, we need to make
// sure we call SetVolume on the signaling thread.
signaling_thread_->PostTask(FROM_HERE,
base::Bind(&webrtc::AudioSourceInterface::SetVolume, source, volume));
} else {
source->SetVolume(volume);
}
}
bool WebRtcAudioRenderer::AddPlayingState(
webrtc::AudioSourceInterface* source,
PlayingState* state) {
DCHECK(thread_checker_.CalledOnValidThread());
DCHECK(state->playing());
// Look up or add the |source| to the map.
PlayingStates& array = source_playing_states_[source];
if (std::find(array.begin(), array.end(), state) != array.end())
return false;
array.push_back(state);
return true;
}
bool WebRtcAudioRenderer::RemovePlayingState(
webrtc::AudioSourceInterface* source,
PlayingState* state) {
DCHECK(thread_checker_.CalledOnValidThread());
DCHECK(!state->playing());
SourcePlayingStates::iterator found = source_playing_states_.find(source);
if (found == source_playing_states_.end())
return false;
PlayingStates& array = found->second;
PlayingStates::iterator state_it =
std::find(array.begin(), array.end(), state);
if (state_it == array.end())
return false;
array.erase(state_it);
if (array.empty())
source_playing_states_.erase(found);
return true;
}
void WebRtcAudioRenderer::OnPlayStateChanged(
const blink::WebMediaStream& media_stream,
PlayingState* state) {
DCHECK(thread_checker_.CalledOnValidThread());
blink::WebVector<blink::WebMediaStreamTrack> web_tracks;
media_stream.audioTracks(web_tracks);
for (const blink::WebMediaStreamTrack& web_track : web_tracks) {
// WebRtcAudioRenderer can only render audio tracks received from a remote
// peer. Since the actual MediaStream is mutable from JavaScript, we need
// to make sure |web_track| is actually a remote track.
PeerConnectionRemoteAudioTrack* const remote_track =
PeerConnectionRemoteAudioTrack::From(
MediaStreamAudioTrack::From(web_track));
if (!remote_track)
continue;
webrtc::AudioSourceInterface* source =
remote_track->track_interface()->GetSource();
DCHECK(source);
if (!state->playing()) {
if (RemovePlayingState(source, state))
EnterPauseState();
} else if (AddPlayingState(source, state)) {
EnterPlayState();
}
UpdateSourceVolume(source);
}
}
void WebRtcAudioRenderer::PrepareSink() {
DCHECK(thread_checker_.CalledOnValidThread());
media::AudioParameters new_sink_params;
{
base::AutoLock lock(lock_);
new_sink_params = sink_params_;
}
const media::OutputDeviceInfo& device_info = sink_->GetOutputDeviceInfo();
DCHECK_EQ(device_info.device_status(), media::OUTPUT_DEVICE_STATUS_OK);
// WebRTC does not yet support higher rates than 96000 on the client side
// and 48000 is the preferred sample rate. Therefore, if 192000 is detected,
// we change the rate to 48000 instead. The consequence is that the native
// layer will be opened up at 192kHz but WebRTC will provide data at 48kHz
// which will then be resampled by the audio converted on the browser side
// to match the native audio layer.
int sample_rate = device_info.output_params().sample_rate();
DVLOG(1) << "Audio output hardware sample rate: " << sample_rate;
if (sample_rate >= 192000) {
DVLOG(1) << "Resampling from 48000 to " << sample_rate << " is required";
sample_rate = 48000;
}
media::AudioSampleRate asr;
if (media::ToAudioSampleRate(sample_rate, &asr)) {
UMA_HISTOGRAM_ENUMERATION("WebRTC.AudioOutputSampleRate", asr,
media::kAudioSampleRateMax + 1);
} else {
UMA_HISTOGRAM_COUNTS("WebRTC.AudioOutputSampleRateUnexpected", sample_rate);
}
// Calculate the frames per buffer for the source, i.e. the WebRTC client. We
// use 10 ms of data since the WebRTC client only supports multiples of 10 ms
// as buffer size where 10 ms is preferred for lowest possible delay.
const int source_frames_per_buffer = (sample_rate / 100);
DVLOG(1) << "Using WebRTC output buffer size: " << source_frames_per_buffer;
// Setup sink parameters.
const int sink_frames_per_buffer = media::AudioLatency::GetRtcBufferSize(
sample_rate, device_info.output_params().frames_per_buffer());
new_sink_params.set_sample_rate(sample_rate);
new_sink_params.set_frames_per_buffer(sink_frames_per_buffer);
// Create a FIFO if re-buffering is required to match the source input with
// the sink request. The source acts as provider here and the sink as
// consumer.
const bool different_source_sink_frames =
source_frames_per_buffer != new_sink_params.frames_per_buffer();
if (different_source_sink_frames) {
DVLOG(1) << "Rebuffering from " << source_frames_per_buffer << " to "
<< new_sink_params.frames_per_buffer();
}
{
base::AutoLock lock(lock_);
if ((!audio_fifo_ && different_source_sink_frames) ||
(audio_fifo_ &&
audio_fifo_->SizeInFrames() != source_frames_per_buffer)) {
audio_fifo_.reset(new media::AudioPullFifo(
kChannels, source_frames_per_buffer,
base::Bind(&WebRtcAudioRenderer::SourceCallback,
base::Unretained(this))));
}
sink_params_ = new_sink_params;
}
sink_->Initialize(new_sink_params, this);
}
} // namespace content
| [
"serg.zhukovsky@gmail.com"
] | serg.zhukovsky@gmail.com |
329c349714ed24d3734e13eb5b8d45482236ad86 | 8d1aa597eae7ff732ee475feb91999e78386e47d | /coast/modules/Queueing/Test/QueueWorkingModuleTest.cpp | de6a86feabccd58186daf2d48d0a06c2cd370d89 | [] | no_license | chenbk85/CuteTestForCoastTest | 63111ba3b54ab2b027684dd6f1b9c5859fcdde9b | 37d933c5fe2e0ce9a801f51b2aa27c7a18098511 | refs/heads/master | 2021-01-12T20:17:22.462721 | 2015-06-08T18:42:09 | 2015-06-10T13:13:35 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,922 | cpp | /*
* Copyright (c) 2005, Peter Sommerlad and IFS Institute for Software at HSR Rapperswil, Switzerland
* All rights reserved.
*
* This library/application is free software; you can redistribute and/or modify it under the terms of
* the license that is included with this library/application in the file license.txt.
*/
#include "QueueWorkingModuleTest.h"
#include "QueueWorkingModule.h"
#include "TestSuite.h"
#include "Queue.h"
#include "Tracer.h"
//---- QueueWorkingModuleTest ----------------------------------------------------------------
QueueWorkingModuleTest::QueueWorkingModuleTest(TString tstrName)
: TestCaseType(tstrName)
{
StartTrace(QueueWorkingModuleTest.QueueWorkingModuleTest);
}
TString QueueWorkingModuleTest::getConfigFileName()
{
return "QueueWorkingModuleTestConfig";
}
QueueWorkingModuleTest::~QueueWorkingModuleTest()
{
StartTrace(QueueWorkingModuleTest.Dtor);
}
void QueueWorkingModuleTest::InitFinisNoModuleConfigTest()
{
StartTrace(QueueWorkingModuleTest.InitFinisNoModuleConfigTest);
AnyQueueWorkingModule aModule("QueueWorkingModule");
t_assertm( !aModule.Init(GetTestCaseConfig()["ModuleConfig"]), "module init should have failed due to missing configuration" );
}
void QueueWorkingModuleTest::InitFinisDefaultsTest()
{
StartTrace(QueueWorkingModuleTest.InitFinisDefaultsTest);
AnyQueueWorkingModule aModule("QueueWorkingModule");
if ( t_assertm( aModule.Init(GetTestCaseConfig()["ModuleConfig"]), "module init should have succeeded" ) )
{
if ( t_assert( aModule.GetContext() != NULL ) )
{
assertAnyEqual(GetTestCaseConfig()["ModuleConfig"]["QueueWorkingModule"], aModule.GetContext()->GetEnvStore());
}
if ( t_assert( aModule.GetQueue() != NULL ) )
{
assertEqualm(0L, aModule.GetQueue()->GetSize(), "expected queue to be empty");
Anything anyStatistics;
aModule.GetQueueStatistics(anyStatistics);
assertEqualm(100L, anyStatistics["QueueSize"].AsLong(-1L), "expected default queue size to be 100");
}
// terminate module and perform some checks
t_assert( aModule.Finis() );
t_assert( aModule.GetContext() == NULL );
t_assert( aModule.GetQueue() == NULL );
}
}
void QueueWorkingModuleTest::InitFinisTest()
{
StartTrace(QueueWorkingModuleTest.InitFinisTest);
AnyQueueWorkingModule aModule("QueueWorkingModule");
if ( t_assertm( aModule.Init(GetTestCaseConfig()["ModuleConfig"]), "module init should have succeeded" ) )
{
if ( t_assert( aModule.GetContext() != NULL ) )
{
// check for invalid Server
t_assertm( NULL == aModule.GetContext()->GetServer(), "server must be NULL because of non-existing server");
assertAnyEqual(GetTestCaseConfig()["ModuleConfig"]["QueueWorkingModule"], aModule.GetContext()->GetEnvStore());
}
if ( t_assert( aModule.GetQueue() != NULL ) )
{
assertEqualm(0L, aModule.GetCurrentSize(), "expected queue to be empty");
Anything anyStatistics;
aModule.GetQueueStatistics(anyStatistics);
assertEqualm(25L, anyStatistics["QueueSize"].AsLong(-1L), "expected queue size to be 25 as configured");
}
// terminate module and perform some checks
t_assert( aModule.Finis() );
t_assert( aModule.GetContext() == NULL );
t_assert( aModule.GetQueue() == NULL );
}
}
void QueueWorkingModuleTest::GetAndPutbackTest()
{
StartTrace(QueueWorkingModuleTest.GetAndPutbackTest);
AnyQueueWorkingModule aModule("QueueWorkingModule");
typedef AnyQueueWorkingModule::QueueType QueueType;
// set modules fAlive-field to enable working of the functions
// first check if they don't work
{
Anything anyMsg;
// must fail
assertEqual( QueueType::eDead, aModule.PutElement(anyMsg, false) );
// fails because of uninitialized queue
assertEqual( QueueType::eDead, aModule.GetElement(anyMsg,false) );
}
aModule.IntInitQueue(GetTestCaseConfig()["ModuleConfig"]["QueueWorkingModule"]);
{
Anything anyMsg;
// must still fail because of dead-state
assertEqual( QueueType::eDead, aModule.GetElement(anyMsg,false) );
}
aModule.fAlive = 0xf007f007;
if ( t_assertm( aModule.GetQueue() != NULL , "queue should be created" ) )
{
// queue is empty, so retrieving an element with tryLock=true should
// return immediately and fail.
{
Anything anyElement;
assertEqual( QueueType::eEmpty, aModule.GetElement(anyElement,true) );
}
// queue size is 1, so we load it with 1 element
{
Anything anyMsg;
anyMsg["Number"] = 1;
// this one must succeed
assertEqual( QueueType::eSuccess, aModule.PutElement(anyMsg, false) );
}
// now putback one message
{
Anything anyMsg;
anyMsg["Number"] = 2;
// this one must fail
if ( assertEqual( QueueType::eFull, aModule.PutElement(anyMsg, true) ) )
{
aModule.PutBackElement(anyMsg);
assertEqualm(1, aModule.fFailedPutbackMessages->GetSize(), "expected overflow buffer to contain an element");
}
}
Anything anyElement;
if ( assertEqual( QueueType::eSuccess, aModule.GetElement(anyElement) ) )
{
assertEqualm( 2, anyElement["Number"].AsLong(-1L), "expected to get putback element first");
}
assertEqualm( 0, aModule.fFailedPutbackMessages->GetSize(), "expected overflow buffer to be empty now");
if ( assertEqual( QueueType::eSuccess, aModule.GetElement(anyElement) ) )
{
assertEqualm( 1, anyElement["Number"].AsLong(-1L), "expected to get regular queue element last");
}
assertEqualm( 0, aModule.GetCurrentSize(), "expected queue to be empty now");
aModule.IntCleanupQueue();
}
}
// builds up a suite of tests, add a line for each testmethod
Test *QueueWorkingModuleTest::suite ()
{
StartTrace(QueueWorkingModuleTest.suite);
TestSuite *testSuite = new TestSuite;
ADD_CASE(testSuite, QueueWorkingModuleTest, InitFinisNoModuleConfigTest);
ADD_CASE(testSuite, QueueWorkingModuleTest, InitFinisDefaultsTest);
ADD_CASE(testSuite, QueueWorkingModuleTest, InitFinisTest);
ADD_CASE(testSuite, QueueWorkingModuleTest, GetAndPutbackTest);
return testSuite;
}
| [
"marcel.huber@hsr.ch"
] | marcel.huber@hsr.ch |
6b905e7cf881a8619d0f48bfd244f816f8955e15 | 408ee5d2f42086100cdc0289a33eec3487a2c28b | /DummySensor.h | 9cd223199e7b73568d0136a0f4fd430e48bcce7d | [
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | charattoon/toon-encryption | 4a2bb4e40086e0fa7de1f8414cd25ff4b9526d58 | 5bc390e9851be6edfd50d2898f79c2f94e4b9448 | refs/heads/master | 2021-09-04T10:46:28.147716 | 2020-03-28T09:20:01 | 2020-03-28T09:20:01 | 184,621,823 | 0 | 0 | Apache-2.0 | 2021-08-09T20:49:16 | 2019-05-02T17:19:18 | C | UTF-8 | C++ | false | false | 1,095 | h | /**
* Copyright (c) 2017, Arm Limited and affiliates.
* SPDX-License-Identifier: Apache-2.0
*
* 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.
*/
#ifndef MBED_LORAWAN_DUMMYSENSOR_H_
#define MBED_LORAWAN_DUMMYSENSOR_H_
/*
* A dummy sensor for Mbed LoRa Test Application
*/
class DS1820 {
public:
DS1820(uint32_t)
{
value = 1.0f;
};
bool begin()
{
return true;
};
void startConversion() {};
float read()
{
value += 1.1f;
return value;
}
private:
float value;
};
#endif /* MBED_LORAWAN_DUMMYSENSOR_H_ */
| [
"charattoon@hotmail.com"
] | charattoon@hotmail.com |
0b419127041330f2cd9581268e5713caeb35d685 | 1eb962b733ff89dddb01655c3986e2665bd1ffc2 | /143D/main.cpp | 921adf92f3336ffa1d904fe7e49fda4dc164d2cc | [] | no_license | sh19910711/codeforces-solutions | b4d6affe8d9bb0298275f7d0e94657e5472f2276 | 5784408c23fd61b6fcf32e3dacc8a706f31ac96e | refs/heads/master | 2021-01-23T03:53:52.931042 | 2015-10-03T20:01:00 | 2015-10-03T20:03:22 | 8,685,265 | 3 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,923 | cpp |
// @snippet<sh19910711/contest:headers.cpp>
#include <iostream>
#include <sstream>
#include <fstream>
#include <iomanip>
#include <vector>
#include <set>
#include <map>
#include <stack>
#include <queue>
#include <algorithm>
#include <numeric>
#include <limits>
#include <complex>
#include <functional>
#include <iterator>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <cmath>
// @snippet<sh19910711/contest:solution/interface.cpp>
namespace solution {
class SolutionInterface {
public:
virtual int run() = 0;
protected:
virtual void pre_calc() {}
virtual bool action() = 0;
virtual void init() {};
virtual bool input() { return false; };
virtual void output() {};
SolutionInterface() {}
private:
};
}
// @snippet<sh19910711/contest:solution/solution-base.cpp>
namespace solution {
class SolutionBase: public SolutionInterface {
public:
virtual int run() {
pre_calc();
while ( action() );
return 0;
}
};
}
// @snippet<sh19910711/contest:solution/typedef.cpp>
namespace solution {
typedef std::istringstream ISS;
typedef std::ostringstream OSS;
typedef std::vector<std::string> VS;
typedef long long LL;
typedef int INT;
typedef std::vector<INT> VI;
typedef std::vector<VI> VVI;
typedef std::pair<INT,INT> II;
typedef std::vector<II> VII;
}
// @snippet<sh19910711/contest:solution/namespace-area.cpp>
namespace solution {
// namespaces, types
using namespace std;
}
// @snippet<sh19910711/contest:solution/variables-area.cpp>
namespace solution {
// constant vars
// storages
int n, m;
int result;
}
// @snippet<sh19910711/contest:solution/solver-area.cpp>
namespace solution {
class Solver {
public:
void solve() {
result = 0;
if ( n == 1 ) {
result = max(result, m);
}
if ( m == 1 ) {
result = max(result, n);
}
if ( n == 2 ) {
if ( m % 4 == 3 ) {
result = max(result, m + 1);
} else {
result = max(result, m + m % 4);
}
}
if ( m == 2 ) {
if ( n % 4 == 3 ) {
result = max(result, n + 1);
} else {
result = max(result, n + n % 4);
}
}
result = max(result, (int)( ( n * m + 1.0 ) / 2 ));
}
private:
};
}
// @snippet<sh19910711/contest:solution/solution.cpp>
namespace solution {
class Solution: public SolutionBase {
public:
protected:
virtual bool action() {
init();
if ( ! input() )
return false;
solver.solve();
output();
return true;
}
bool input() {
return cin >> n >> m;
}
void output() {
cout << result << endl;
}
private:
Solver solver;
};
}
// @snippet<sh19910711/contest:main.cpp>
#ifndef __MY_UNIT_TEST__
int main() {
return solution::Solution().run();
}
#endif
| [
"sh19910711@gmail.com"
] | sh19910711@gmail.com |
9e723b419ea974d88c2a5b9cdc987a21d1c5d8a6 | e81435f0433f3f8f4010785999aa0b010e7e51f5 | /co20_swamps_zbad_is_bad.zargabad/revive_sqf/dialogs/rev_cam_dialog.hpp | db0cf05e1963ea34bf7f8f0fb7b3f81143c9eb36 | [] | no_license | SwampGod/ARMA2-Missons | 3edf4a406be3d95f33bad6fa1331ff7f444915c7 | 34fae53040a388aafecd1ed4d6ddb7fd2a69374a | refs/heads/master | 2016-09-05T14:03:54.414576 | 2014-10-17T20:25:34 | 2014-10-17T20:25:34 | null | 0 | 0 | null | null | null | null | WINDOWS-1252 | C++ | false | false | 5,078 | hpp | /*
REVIVE CAMERA DIALOG
© JULY 2009 - norrin
**********************************************************************************************************************************
rev_cam_dialog.hpp
*/
class rev_cam_dialog
{
idd = 99123;
movingEnable = false;
objects[] = {};
controls[] = {mouse,TOP_BORDER,BOTTOM_BORDER,TITLE_DIALOG,PRESS_HELP,HELP_DIALOG,CAM_LIST,CAM_select,FRIEND_LIST,FRIEND_select,Help_1,
HINT_BOX0,HINT_BOX1,HINT_BOX2,HINT_BOX3,HINT_BOX4,HINT_BOX5,HINT_BOX6,HINT_BOX7,HINT_BOX8,HINT_BOX9};
controlsBackground[] = {};
class mouse : NORRNmouseHandler {};
class TOP_BORDER
{
idc = -1;
type = CT_STATIC;
style = ST_CENTER;
//x = -1.5; y = -0.2;
x = -1.5; y = safeZoneY;
w = 4.0; h = 0.28;
font = "TahomaB";
sizeEx = 0.04;
colorText[] = { 1, 1, 1, 1 };
colorBackground[] = {0,0,0,1};
text = "";
};
class BOTTOM_BORDER {
idc = -1;
type = CT_STATIC;
style = ST_CENTER;
x = -1.5; y = (safeZoneY + safeZoneH) -0.25;
w = 4.0; h = 0.26;
font = "TahomaB";
sizeEx = 0.04;
colorText[] = { 1, 1, 1, 1 };
colorBackground[] = {0,0,0,1};
text = "";
};
class TITLE_DIALOG {
idc = -1;
type = CT_ACTIVETEXT;
style = ST_LEFT;
//x = 0.38; y = 0.03;
x = (safeZoneX + safeZoneW/2)-0.1; y = 0.03 + safeZoneY;
w = 0.4; h = 0.04;
font = "TahomaB";
sizeEx = 0.04;
color[] = { 1, 1, 1, 1 };
colorActive[] = { 1, 0.2, 0.2, 1 };
colorText[] = { 1, 1, 1, 1 };
colorBackground[] = {0,0,0,1};
soundEnter[] = { "", 0, 1 }; // no sound
soundPush[] = { "", 0, 1 };
soundClick[] = { "", 0, 1 };
soundEscape[] = { "", 0, 1 };
action = "";
text = "Unconscious Camera";
default = true;
};
class PRESS_HELP : NORRNRscText {
idc = 10000;
style = ST_MULTI;
linespacing = 1;
x = (safeZoneX + safeZoneW) -0.25; y = (safeZoneY + safeZoneH) -0.18;
w = 0.2; h = 0.1;
text = "";
};
class HELP_DIALOG : NORRNRscActiveText {
idc = -1;
style = ST_LEFT;
linespacing = 1;
x = (safeZoneX + safeZoneW) -0.25; y = (safeZoneY + safeZoneH) -0.2;
w = 0.4; h = 0.02;
sizeEx = 0.02;
action = "ctrlSetText [10000, ""Keyboard controls:\n A/D - Previous/Next target\n W/S - Previous/Next camera\n N - Toggle NV for Free Cam""]";
text = "Press for Help";
};
class CAM_LIST: NORRNRscCombo {
idc = 10004;
x = safeZoneX +0.09; y = safeZoneY +0.03;
w = 0.15; h = 0.04;
//sizeEx = 0.02;
};
class CAM_select {
idc = 10001;
type = CT_STATIC;
style = ST_LEFT;
colorText[] = {1, 1, 1, 1};
colorBackground[] = {0,0,0,0};
x = safeZoneX +0.02; y = safeZoneY +0.03;
w = 0.08; h = 0.04;
font = "TahomaB";
sizeEx = 0.02;
text = "Camera:";
default = true;
};
class FRIEND_LIST: NORRNRscCombo {
idc = 10005;
x = (safeZoneX + safeZoneW)-0.18; y = safeZoneY +0.03;
w = 0.15; h = 0.04;
//sizeEx = 0.02;
};
class FRIEND_select {
idc = 10002;
type = CT_STATIC;
style = ST_LEFT;
colorText[] = {1, 1, 1, 1};
colorBackground[] = {0,0,0,0};
x = (safeZoneX + safeZoneW)-0.25; y = safeZoneY +0.03;
w = 0.08; h = 0.04;
font = "TahomaB";
sizeEx = 0.02;
text = "Target:";
default = true;
};
class Help_1 : NORRNRscNavButton
{
x = safeZoneX +0.02; y = safeZoneY +0.10;
w = 0.11; h = 0.04;
idc = 5;
colorBackground[] = { 1, 1, 1, 0.5 };
text = "Call for Help";
action = "[] call Norrn_Call4Help";
};
class HINT_BOX0 : NORRNRscText
{
idc = 10;
x = safeZoneX +0.02; y = (safeZoneY + safeZoneH)-0.2;
w = 0.4; h = 0.1;
};
class HINT_BOX1 : NORRNRscText
{
idc = 11;
x = safeZoneX +0.02; y = (safeZoneY + safeZoneH)-0.18;
w = 0.4; h = 0.1;
};
class HINT_BOX2 : NORRNRscText
{
idc = 12;
x = safeZoneX +0.02; y = (safeZoneY + safeZoneH)-0.16;
w = 0.4; h = 0.1;
};
class HINT_BOX3 : NORRNRscText
{
idc = 13;
x = safeZoneX +0.56; y = (safeZoneY + safeZoneH)-0.2;
w = 0.4; h = 0.1;
};
class HINT_BOX4 : NORRNRscText
{
idc = 14;
x = safeZoneX +0.56; y = (safeZoneY + safeZoneH)-0.18;
w = 0.4; h = 0.1;
};
class HINT_BOX5 : NORRNRscText
{
idc = 15;
x = safeZoneX +0.56; y = (safeZoneY + safeZoneH)-0.16;
w = 0.4; h = 0.1;
};
class HINT_BOX6 : NORRNRscText
{
idc = 16;
x = safeZoneX +0.30; y = (safeZoneY + safeZoneH)-0.2;
w = 0.4; h = 0.1;
};
class HINT_BOX7 : NORRNRscText
{
idc = 17;
x = safeZoneX +0.30; y = (safeZoneY + safeZoneH)-0.18;
w = 0.4; h = 0.1;
};
class HINT_BOX8 : NORRNRscText
{
idc = 18;
x = safeZoneX +0.30; y = (safeZoneY + safeZoneH)-0.16;
w = 0.4; h = 0.1;
};
class HINT_BOX9 : NORRNRscText
{
idc = 19;
x = safeZoneX +0.30; y = (safeZoneY + safeZoneH)-0.14;
w = 0.4; h = 0.1;
};
};
| [
"swamp@LV-223.(none)"
] | swamp@LV-223.(none) |
8d238cd90bba1f03788744a61a6084bad9f7e90b | 3b9b4049a8e7d38b49e07bb752780b2f1d792851 | /src/chrome/browser/android/offline_pages/prerendering_offliner_unittest.cc | eef086b15126e5ab7b1c4fca8515074fb65088b6 | [
"BSD-3-Clause",
"Apache-2.0"
] | permissive | webosce/chromium53 | f8e745e91363586aee9620c609aacf15b3261540 | 9171447efcf0bb393d41d1dc877c7c13c46d8e38 | refs/heads/webosce | 2020-03-26T23:08:14.416858 | 2018-08-23T08:35:17 | 2018-09-20T14:25:18 | 145,513,343 | 0 | 2 | Apache-2.0 | 2019-08-21T22:44:55 | 2018-08-21T05:52:31 | null | UTF-8 | C++ | false | false | 11,415 | cc | // Copyright 2016 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.
#include "chrome/browser/android/offline_pages/prerendering_offliner.h"
#include <memory>
#include "base/bind.h"
#include "base/run_loop.h"
#include "base/threading/thread_task_runner_handle.h"
#include "chrome/browser/android/offline_pages/prerendering_loader.h"
#include "chrome/test/base/testing_profile.h"
#include "components/offline_pages/background/offliner.h"
#include "components/offline_pages/background/save_page_request.h"
#include "components/offline_pages/stub_offline_page_model.h"
#include "content/public/test/test_browser_thread_bundle.h"
#include "content/public/test/web_contents_tester.h"
#include "testing/gtest/include/gtest/gtest.h"
namespace offline_pages {
namespace {
const int64_t kRequestId = 7;
const GURL kHttpUrl("http://tunafish.com");
const GURL kFileUrl("file://sailfish.png");
const ClientId kClientId("AsyncLoading", "88");
// Mock Loader for testing the Offliner calls.
class MockPrerenderingLoader : public PrerenderingLoader {
public:
explicit MockPrerenderingLoader(content::BrowserContext* browser_context)
: PrerenderingLoader(browser_context),
can_prerender_(true),
mock_loading_(false),
mock_loaded_(false) {}
~MockPrerenderingLoader() override {}
bool LoadPage(const GURL& url, const LoadPageCallback& callback) override {
mock_loading_ = true;
load_page_callback_ = callback;
return mock_loading_;
}
void StopLoading() override {
mock_loading_ = false;
mock_loaded_ = false;
}
bool CanPrerender() override { return can_prerender_; }
bool IsIdle() override { return !mock_loading_ && !mock_loaded_; }
bool IsLoaded() override { return mock_loaded_; }
void CompleteLoadingAsFailed() {
DCHECK(mock_loading_);
mock_loading_ = false;
mock_loaded_ = false;
base::ThreadTaskRunnerHandle::Get()->PostTask(
FROM_HERE,
base::Bind(load_page_callback_, Offliner::RequestStatus::FAILED,
nullptr /* web_contents */));
}
void CompleteLoadingAsLoaded() {
DCHECK(mock_loading_);
mock_loading_ = false;
mock_loaded_ = true;
base::ThreadTaskRunnerHandle::Get()->PostTask(
FROM_HERE,
base::Bind(load_page_callback_, Offliner::RequestStatus::LOADED,
content::WebContentsTester::CreateTestWebContents(
new TestingProfile(), NULL)));
}
void CompleteLoadingAsCanceled() {
DCHECK(!IsIdle());
mock_loading_ = false;
mock_loaded_ = false;
base::ThreadTaskRunnerHandle::Get()->PostTask(
FROM_HERE,
base::Bind(load_page_callback_, Offliner::RequestStatus::CANCELED,
nullptr /* web_contents */));
}
void DisablePrerendering() { can_prerender_ = false; }
const LoadPageCallback& load_page_callback() { return load_page_callback_; }
private:
bool can_prerender_;
bool mock_loading_;
bool mock_loaded_;
LoadPageCallback load_page_callback_;
DISALLOW_COPY_AND_ASSIGN(MockPrerenderingLoader);
};
// Mock OfflinePageModel for testing the SavePage calls.
class MockOfflinePageModel : public StubOfflinePageModel {
public:
MockOfflinePageModel() : mock_saving_(false) {}
~MockOfflinePageModel() override {}
void SavePage(const GURL& url,
const ClientId& client_id,
std::unique_ptr<OfflinePageArchiver> archiver,
const SavePageCallback& callback) override {
mock_saving_ = true;
save_page_callback_ = callback;
}
void CompleteSavingAsArchiveCreationFailed() {
DCHECK(mock_saving_);
mock_saving_ = false;
base::ThreadTaskRunnerHandle::Get()->PostTask(
FROM_HERE, base::Bind(save_page_callback_,
SavePageResult::ARCHIVE_CREATION_FAILED, 0));
}
void CompleteSavingAsSuccess() {
DCHECK(mock_saving_);
mock_saving_ = false;
base::ThreadTaskRunnerHandle::Get()->PostTask(
FROM_HERE,
base::Bind(save_page_callback_, SavePageResult::SUCCESS, 123456));
}
bool mock_saving() const { return mock_saving_; }
private:
bool mock_saving_;
SavePageCallback save_page_callback_;
DISALLOW_COPY_AND_ASSIGN(MockOfflinePageModel);
};
void PumpLoop() {
base::RunLoop().RunUntilIdle();
}
} // namespace
class PrerenderingOfflinerTest : public testing::Test {
public:
PrerenderingOfflinerTest();
~PrerenderingOfflinerTest() override;
void SetUp() override;
PrerenderingOffliner* offliner() const { return offliner_.get(); }
Offliner::CompletionCallback const callback() {
return base::Bind(&PrerenderingOfflinerTest::OnCompletion,
base::Unretained(this));
}
bool SaveInProgress() const { return model_->mock_saving(); }
MockPrerenderingLoader* loader() { return loader_; }
MockOfflinePageModel* model() { return model_; }
bool completion_callback_called() { return completion_callback_called_; }
Offliner::RequestStatus request_status() { return request_status_; }
private:
void OnCompletion(const SavePageRequest& request,
Offliner::RequestStatus status);
content::TestBrowserThreadBundle thread_bundle_;
std::unique_ptr<PrerenderingOffliner> offliner_;
// Not owned.
MockPrerenderingLoader* loader_;
MockOfflinePageModel* model_;
bool completion_callback_called_;
Offliner::RequestStatus request_status_;
DISALLOW_COPY_AND_ASSIGN(PrerenderingOfflinerTest);
};
PrerenderingOfflinerTest::PrerenderingOfflinerTest()
: thread_bundle_(content::TestBrowserThreadBundle::IO_MAINLOOP),
completion_callback_called_(false),
request_status_(Offliner::RequestStatus::UNKNOWN) {}
PrerenderingOfflinerTest::~PrerenderingOfflinerTest() {}
void PrerenderingOfflinerTest::SetUp() {
model_ = new MockOfflinePageModel();
offliner_.reset(new PrerenderingOffliner(nullptr, nullptr, model_));
std::unique_ptr<MockPrerenderingLoader> mock_loader(
new MockPrerenderingLoader(nullptr));
loader_ = mock_loader.get();
offliner_->SetLoaderForTesting(std::move(mock_loader));
}
void PrerenderingOfflinerTest::OnCompletion(const SavePageRequest& request,
Offliner::RequestStatus status) {
DCHECK(!completion_callback_called_); // Expect single callback per request.
completion_callback_called_ = true;
request_status_ = status;
}
TEST_F(PrerenderingOfflinerTest, LoadAndSaveBadUrl) {
base::Time creation_time = base::Time::Now();
SavePageRequest request(kRequestId, kFileUrl, kClientId, creation_time);
EXPECT_FALSE(offliner()->LoadAndSave(request, callback()));
EXPECT_TRUE(loader()->IsIdle());
}
TEST_F(PrerenderingOfflinerTest, LoadAndSavePrerenderingDisabled) {
base::Time creation_time = base::Time::Now();
SavePageRequest request(kRequestId, kHttpUrl, kClientId, creation_time);
loader()->DisablePrerendering();
EXPECT_FALSE(offliner()->LoadAndSave(request, callback()));
EXPECT_TRUE(loader()->IsIdle());
}
TEST_F(PrerenderingOfflinerTest, LoadAndSaveLoadStartedButFails) {
base::Time creation_time = base::Time::Now();
SavePageRequest request(kRequestId, kHttpUrl, kClientId, creation_time);
EXPECT_TRUE(offliner()->LoadAndSave(request, callback()));
EXPECT_FALSE(loader()->IsIdle());
EXPECT_EQ(Offliner::RequestStatus::UNKNOWN, request_status());
loader()->CompleteLoadingAsFailed();
PumpLoop();
EXPECT_TRUE(completion_callback_called());
EXPECT_EQ(Offliner::RequestStatus::FAILED, request_status());
EXPECT_TRUE(loader()->IsIdle());
EXPECT_FALSE(SaveInProgress());
}
TEST_F(PrerenderingOfflinerTest, CancelWhenLoading) {
base::Time creation_time = base::Time::Now();
SavePageRequest request(kRequestId, kHttpUrl, kClientId, creation_time);
EXPECT_TRUE(offliner()->LoadAndSave(request, callback()));
EXPECT_FALSE(loader()->IsIdle());
offliner()->Cancel();
EXPECT_TRUE(loader()->IsIdle());
}
TEST_F(PrerenderingOfflinerTest, CancelWhenLoaded) {
base::Time creation_time = base::Time::Now();
SavePageRequest request(kRequestId, kHttpUrl, kClientId, creation_time);
EXPECT_TRUE(offliner()->LoadAndSave(request, callback()));
EXPECT_FALSE(loader()->IsIdle());
EXPECT_EQ(Offliner::RequestStatus::UNKNOWN, request_status());
loader()->CompleteLoadingAsLoaded();
PumpLoop();
EXPECT_FALSE(completion_callback_called());
EXPECT_TRUE(loader()->IsLoaded());
EXPECT_TRUE(SaveInProgress());
offliner()->Cancel();
PumpLoop();
EXPECT_FALSE(completion_callback_called());
EXPECT_FALSE(loader()->IsLoaded());
// Note: save still in progress since it does not support canceling.
EXPECT_TRUE(SaveInProgress());
// Subsequent save callback causes no harm (no crash and no callback).
model()->CompleteSavingAsArchiveCreationFailed();
PumpLoop();
EXPECT_FALSE(completion_callback_called());
EXPECT_TRUE(loader()->IsIdle());
EXPECT_FALSE(SaveInProgress());
}
TEST_F(PrerenderingOfflinerTest, LoadAndSaveLoadedButSaveFails) {
base::Time creation_time = base::Time::Now();
SavePageRequest request(kRequestId, kHttpUrl, kClientId, creation_time);
EXPECT_TRUE(offliner()->LoadAndSave(request, callback()));
EXPECT_FALSE(loader()->IsIdle());
EXPECT_EQ(Offliner::RequestStatus::UNKNOWN, request_status());
loader()->CompleteLoadingAsLoaded();
PumpLoop();
EXPECT_FALSE(completion_callback_called());
EXPECT_TRUE(loader()->IsLoaded());
EXPECT_TRUE(SaveInProgress());
model()->CompleteSavingAsArchiveCreationFailed();
PumpLoop();
EXPECT_TRUE(completion_callback_called());
EXPECT_EQ(Offliner::RequestStatus::FAILED_SAVE, request_status());
EXPECT_FALSE(loader()->IsLoaded());
EXPECT_FALSE(SaveInProgress());
}
TEST_F(PrerenderingOfflinerTest, LoadAndSaveSuccessful) {
base::Time creation_time = base::Time::Now();
SavePageRequest request(kRequestId, kHttpUrl, kClientId, creation_time);
EXPECT_TRUE(offliner()->LoadAndSave(request, callback()));
EXPECT_FALSE(loader()->IsIdle());
EXPECT_EQ(Offliner::RequestStatus::UNKNOWN, request_status());
loader()->CompleteLoadingAsLoaded();
PumpLoop();
EXPECT_FALSE(completion_callback_called());
EXPECT_TRUE(loader()->IsLoaded());
EXPECT_TRUE(SaveInProgress());
model()->CompleteSavingAsSuccess();
PumpLoop();
EXPECT_TRUE(completion_callback_called());
EXPECT_EQ(Offliner::RequestStatus::SAVED, request_status());
EXPECT_FALSE(loader()->IsLoaded());
EXPECT_FALSE(SaveInProgress());
}
TEST_F(PrerenderingOfflinerTest, LoadAndSaveLoadedButThenCanceledFromLoader) {
base::Time creation_time = base::Time::Now();
SavePageRequest request(kRequestId, kHttpUrl, kClientId, creation_time);
EXPECT_TRUE(offliner()->LoadAndSave(request, callback()));
EXPECT_FALSE(loader()->IsIdle());
EXPECT_EQ(Offliner::RequestStatus::UNKNOWN, request_status());
loader()->CompleteLoadingAsLoaded();
PumpLoop();
EXPECT_FALSE(completion_callback_called());
EXPECT_TRUE(loader()->IsLoaded());
EXPECT_TRUE(SaveInProgress());
loader()->CompleteLoadingAsCanceled();
PumpLoop();
EXPECT_TRUE(completion_callback_called());
EXPECT_EQ(Offliner::RequestStatus::CANCELED, request_status());
EXPECT_FALSE(loader()->IsLoaded());
// Note: save still in progress since it does not support canceling.
EXPECT_TRUE(SaveInProgress());
}
} // namespace offline_pages
| [
"changhyeok.bae@lge.com"
] | changhyeok.bae@lge.com |
9bf39966d4e83069073565e2b12595d6cc379631 | a1595e54ca38f03adec6c1e288baff269d409ec9 | /Bit Manipulation/counting_bits.cpp | 772060a2f0261ed25a592d6ddcd28b5e34f30a09 | [] | no_license | biswa1612/Data-Structure-And-Algorithm | 4bbe400ef262e0afc92e2fcb795727dc1dc82d85 | afbef87036497da13be11765dafacf16aef25fc7 | refs/heads/master | 2023-07-06T16:14:37.124474 | 2021-08-15T20:54:13 | 2021-08-15T20:54:13 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 382 | cpp | #include<bits/stdc++.h>
using namespace std;
int main(){
int n;
cin>>n;
vector <int> v;
int count=0;
for(int i=0;i<=n;i++){
int value = i;
while(value>0){
value= (value & (value-1));
count++;
}
v.push_back(count);
count = 0;
}
for(int i=0;i<v.size();i++){
cout<<v[i]<<" ";
}
} | [
"b119018@iiit-bh.ac.in"
] | b119018@iiit-bh.ac.in |
8673c7d42fb2932e51f8a1cac2acaac2ed1276aa | 44c50a0a5e48b0ae367f0b6943a0411db156995b | /CarRefuel.cpp | 30bc4beb078e6c4525544e92d305d0808b41b353 | [] | no_license | naruto361/CourseraDSAAlgorithmToolBox | 209274d0a3174e754612f806626b97835f0bb616 | e79f3f742ba460fa03a7822c81851326517bf1ac | refs/heads/master | 2022-11-15T09:30:10.821979 | 2020-07-06T04:46:36 | 2020-07-06T04:46:36 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 647 | cpp | #include <iostream>
using namespace std;
int main()
{
int d,m,n;
cin>>d>>m>>n;
if(m>=d) {cout<<0;exit(0);}
int a[n];
for(int i=0;i<n;i++)
cin>>a[i];
for(int i=1;i<n;i++)
{
if(a[i]-a[i-1]>m)
{cout<<-1;exit(0);}
}
if(d-a[n-1] > m) {cout<<-1;exit(0);}
int refills=0,start=0;
for(int i=0;i<n;i++)
{
if(d-a[i]<=m)
{ refills++;break;}
if(a[i]-start<=m && a[i+1]-start>m)
{refills++;
start=a[i];
}
else if(a[i]-start==m)
{
refills++;
start=a[i];
}
}
cout<<refills;
}
| [
"noreply@github.com"
] | noreply@github.com |
90794f5286aa8a8301e39b45a1c53bd766ed2cbf | 124197f939c215d082007bd1736c925642a8a332 | /Game Engine - Titan Voyager - Rony Hanna/Voyager/Dependencies/assimp/include/assimp/StreamWriter.h | 5ce3b172b1ceb5f83eaa5d0e6b9b299c6b4c0075 | [] | no_license | festiveBean/Titan-Voyager-Custom-Game-Engine | f8d72295a4229a9af61e68a84c69e2821348a2e9 | 3b4f1858f598985c581c44c34c4378b5dc966760 | refs/heads/master | 2022-12-30T04:16:50.024394 | 2020-10-18T23:21:41 | 2020-10-18T23:21:41 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 10,138 | h | /*
---------------------------------------------------------------------------
Open Asset Import Library (assimp)
---------------------------------------------------------------------------
Copyright (c) 2006-2018, assimp team
All rights reserved.
Redistribution and use of this software in source and binary forms,
with or without modification, are permitted provided that the following
conditions are met:
* Redistributions of source code must retain the above
copyright notice, this list of conditions and the
following disclaimer.
* Redistributions in binary form must reproduce the above
copyright notice, this list of conditions and the
following disclaimer in the documentation and/or other
materials provided with the distribution.
* Neither the name of the assimp team, nor the names of its
contributors may be used to endorse or promote products
derived from this software without specific prior
written permission of the assimp team.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
---------------------------------------------------------------------------
*/
/** @file Defines the StreamWriter class which writes data to
* a binary stream with a well-defined endianness. */
#ifndef AI_STREAMWRITER_H_INCLUDED
#define AI_STREAMWRITER_H_INCLUDED
#include "ByteSwapper.h"
#include <assimp/IOStream.hpp>
#include <memory>
#include <vector>
namespace Assimp {
// --------------------------------------------------------------------------------------------
/** Wrapper class around IOStream to allow for consistent writing of binary data in both
* little and big endian format. Don't attempt to instance the template directly. Use
* StreamWriterLE to write to a little-endian stream and StreamWriterBE to write to a
* BE stream. Alternatively, there is StreamWriterAny if the endianness of the output
* stream is to be determined at runtime.
*/
// --------------------------------------------------------------------------------------------
template <bool SwapEndianess = false, bool RuntimeSwitch = false>
class StreamWriter
{
enum {
INITIAL_CAPACITY = 1024
};
public:
// ---------------------------------------------------------------------
/** Construction from a given stream with a well-defined endianness.
*
* The StreamReader holds a permanent strong reference to the
* stream, which is released upon destruction.
* @param stream Input stream. The stream is not re-seeked and writing
continues at the current position of the stream cursor.
* @param le If @c RuntimeSwitch is true: specifies whether the
* stream is in little endian byte order. Otherwise the
* endianness information is defined by the @c SwapEndianess
* template parameter and this parameter is meaningless. */
StreamWriter(std::shared_ptr<IOStream> stream, bool le = false)
: stream(stream)
, le(le)
, cursor()
{
ai_assert(stream);
buffer.reserve(INITIAL_CAPACITY);
}
// ---------------------------------------------------------------------
StreamWriter(IOStream* stream, bool le = false)
: stream(std::shared_ptr<IOStream>(stream))
, le(le)
, cursor()
{
ai_assert(stream);
buffer.reserve(INITIAL_CAPACITY);
}
// ---------------------------------------------------------------------
~StreamWriter() {
stream->Write(buffer.data(), 1, buffer.size());
stream->Flush();
}
public:
// ---------------------------------------------------------------------
/** Flush the contents of the internal buffer, and the output IOStream */
void Flush()
{
stream->Write(buffer.data(), 1, buffer.size());
stream->Flush();
buffer.clear();
cursor = 0;
}
// ---------------------------------------------------------------------
/** Seek to the given offset / origin in the output IOStream.
*
* Flushes the internal buffer and the output IOStream prior to seeking. */
aiReturn Seek(size_t pOffset, aiOrigin pOrigin=aiOrigin_SET)
{
Flush();
return stream->Seek(pOffset, pOrigin);
}
// ---------------------------------------------------------------------
/** Tell the current position in the output IOStream.
*
* First flushes the internal buffer and the output IOStream. */
size_t Tell()
{
Flush();
return stream->Tell();
}
public:
// ---------------------------------------------------------------------
/** Write a float to the stream */
void PutF4(float f)
{
Put(f);
}
// ---------------------------------------------------------------------
/** Write a double to the stream */
void PutF8(double d) {
Put(d);
}
// ---------------------------------------------------------------------
/** Write a signed 16 bit integer to the stream */
void PutI2(int16_t n) {
Put(n);
}
// ---------------------------------------------------------------------
/** Write a signed 8 bit integer to the stream */
void PutI1(int8_t n) {
Put(n);
}
// ---------------------------------------------------------------------
/** Write an signed 32 bit integer to the stream */
void PutI4(int32_t n) {
Put(n);
}
// ---------------------------------------------------------------------
/** Write a signed 64 bit integer to the stream */
void PutI8(int64_t n) {
Put(n);
}
// ---------------------------------------------------------------------
/** Write a unsigned 16 bit integer to the stream */
void PutU2(uint16_t n) {
Put(n);
}
// ---------------------------------------------------------------------
/** Write a unsigned 8 bit integer to the stream */
void PutU1(uint8_t n) {
Put(n);
}
// ---------------------------------------------------------------------
/** Write an unsigned 32 bit integer to the stream */
void PutU4(uint32_t n) {
Put(n);
}
// ---------------------------------------------------------------------
/** Write a unsigned 64 bit integer to the stream */
void PutU8(uint64_t n) {
Put(n);
}
// ---------------------------------------------------------------------
/** Write a single character to the stream */
void PutChar(char c) {
Put(c);
}
// ---------------------------------------------------------------------
/** Write an aiString to the stream */
void PutString(const aiString& s)
{
// as Put(T f) below
if (cursor + s.length >= buffer.size()) {
buffer.resize(cursor + s.length);
}
void* dest = &buffer[cursor];
::memcpy(dest, s.C_Str(), s.length);
cursor += s.length;
}
// ---------------------------------------------------------------------
/** Write a std::string to the stream */
void PutString(const std::string& s)
{
// as Put(T f) below
if (cursor + s.size() >= buffer.size()) {
buffer.resize(cursor + s.size());
}
void* dest = &buffer[cursor];
::memcpy(dest, s.c_str(), s.size());
cursor += s.size();
}
public:
// ---------------------------------------------------------------------
/** overload operator<< and allow chaining of MM ops. */
template <typename T>
StreamWriter& operator << (T f) {
Put(f);
return *this;
}
// ---------------------------------------------------------------------
std::size_t GetCurrentPos() const {
return cursor;
}
// ---------------------------------------------------------------------
void SetCurrentPos(std::size_t new_cursor) {
cursor = new_cursor;
}
private:
// ---------------------------------------------------------------------
/** Generic write method. ByteSwap::Swap(T*) *must* be defined */
template <typename T>
void Put(T f) {
Intern :: Getter<SwapEndianess,T,RuntimeSwitch>() (&f, le);
if (cursor + sizeof(T) >= buffer.size()) {
buffer.resize(cursor + sizeof(T));
}
void* dest = &buffer[cursor];
// reinterpret_cast + assignment breaks strict aliasing rules
// and generally causes trouble on platforms such as ARM that
// do not silently ignore alignment faults.
::memcpy(dest, &f, sizeof(T));
cursor += sizeof(T);
}
private:
std::shared_ptr<IOStream> stream;
bool le;
std::vector<uint8_t> buffer;
std::size_t cursor;
};
// --------------------------------------------------------------------------------------------
// `static` StreamWriter. Their byte order is fixed and they might be a little bit faster.
#ifdef AI_BUILD_BIG_ENDIAN
typedef StreamWriter<true> StreamWriterLE;
typedef StreamWriter<false> StreamWriterBE;
#else
typedef StreamWriter<true> StreamWriterBE;
typedef StreamWriter<false> StreamWriterLE;
#endif
// `dynamic` StreamWriter. The byte order of the input data is specified in the
// c'tor. This involves runtime branching and might be a little bit slower.
typedef StreamWriter<true,true> StreamWriterAny;
} // end namespace Assimp
#endif // !! AI_STREAMWriter_H_INCLUDED
| [
"RonyHannaSE@hotmail.com"
] | RonyHannaSE@hotmail.com |
a0ca48039bb6a273f3bf81db255586782a38e944 | 3f7028cc89a79582266a19acbde0d6b066a568de | /tools/testdata/check_format/regex.cc | 53241fae9cba0c8d8aa6cee3c4e58a173a75dc8f | [
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | envoyproxy/envoy | 882d3c7f316bf755889fb628bee514bb2f6f66f0 | 72f129d273fa32f49581db3abbaf4b62e3e3703c | refs/heads/main | 2023-08-31T09:20:01.278000 | 2023-08-31T08:58:36 | 2023-08-31T08:58:36 | 65,214,191 | 21,404 | 4,756 | Apache-2.0 | 2023-09-14T21:56:37 | 2016-08-08T15:07:24 | C++ | UTF-8 | C++ | false | false | 98 | cc | #include <regex>
namespace Envoy {
struct BadRegex {
std::regex bad_;
}
} // namespace Envoy
| [
"htuch@users.noreply.github.com"
] | htuch@users.noreply.github.com |
0d5cb8da46d7fb4001a98fa794c57dc97d0ce7c5 | 2b866c56e0b435557fda9f48b68e362f4b2ed615 | /CoreLib/LibNet/networking-ts-impl/include/experimental/__net_ts/detail/keyword_tss_ptr.hpp | da399a6cafc53b9ab8bd2e2edcd2ff5ba3c3d6bc | [] | no_license | zh880517/Server | 31df474a9cef3df00d63de7a5b63afef2cec5d55 | 1b9b02f33147ff03e6e6c06b060163ae3d158402 | refs/heads/master | 2021-01-01T19:17:12.056249 | 2017-07-27T16:10:33 | 2017-07-27T16:10:33 | 98,555,490 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 1,535 | hpp | //
// detail/keyword_tss_ptr.hpp
// ~~~~~~~~~~~~~~~~~~~~~~~~~~
//
// Copyright (c) 2003-2016 Christopher M. Kohlhoff (chris at kohlhoff dot com)
//
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
//
#ifndef NET_TS_DETAIL_KEYWORD_TSS_PTR_HPP
#define NET_TS_DETAIL_KEYWORD_TSS_PTR_HPP
#if defined(_MSC_VER) && (_MSC_VER >= 1200)
# pragma once
#endif // defined(_MSC_VER) && (_MSC_VER >= 1200)
#include <experimental/__net_ts/detail/config.hpp>
#if defined(NET_TS_HAS_THREAD_KEYWORD_EXTENSION)
#include <experimental/__net_ts/detail/noncopyable.hpp>
#include <experimental/__net_ts/detail/push_options.hpp>
namespace std {
namespace experimental {
namespace net {
inline namespace v1 {
namespace detail {
template <typename T>
class keyword_tss_ptr
: private noncopyable
{
public:
// Constructor.
keyword_tss_ptr()
{
}
// Destructor.
~keyword_tss_ptr()
{
}
// Get the value.
operator T*() const
{
return value_;
}
// Set the value.
void operator=(T* value)
{
value_ = value;
}
private:
static NET_TS_THREAD_KEYWORD T* value_;
};
template <typename T>
NET_TS_THREAD_KEYWORD T* keyword_tss_ptr<T>::value_;
} // namespace detail
} // inline namespace v1
} // namespace net
} // namespace experimental
} // namespace std
#include <experimental/__net_ts/detail/pop_options.hpp>
#endif // defined(NET_TS_HAS_THREAD_KEYWORD_EXTENSION)
#endif // NET_TS_DETAIL_KEYWORD_TSS_PTR_HPP
| [
"zh880517@163.com"
] | zh880517@163.com |
e2d18a19c774aa2250dbd86ce7828cdbb5f8a644 | e8d4656ff8e14998ecce03cff52ca3fe7bcab196 | /tesseract_visualization/include/tesseract_visualization/markers/toolpath_marker.h | b0c787771fb6438a722b6edb7ea54e07252289b9 | [
"BSD-3-Clause",
"Apache-2.0",
"BSD-2-Clause"
] | permissive | Levi-Armstrong/tesseract-1 | 622c8da3ef1e608d63bb4e70c66b86de25e94e01 | 998e16e235e81075a77fb595d9ed92e6d815e853 | refs/heads/master | 2023-09-04T02:08:59.012052 | 2021-12-15T20:25:57 | 2021-12-15T20:27:24 | 140,607,982 | 1 | 4 | NOASSERTION | 2021-12-15T20:27:24 | 2018-07-11T17:25:53 | C++ | UTF-8 | C++ | false | false | 1,040 | h | #ifndef TESSERACT_VISUALIZATION_MARKERS_TOOLPATH_MARKER_H
#define TESSERACT_VISUALIZATION_MARKERS_TOOLPATH_MARKER_H
#include <tesseract_common/macros.h>
TESSERACT_COMMON_IGNORE_WARNINGS_PUSH
#include <vector>
TESSERACT_COMMON_IGNORE_WARNINGS_POP
#include <tesseract_visualization/markers/marker.h>
#include <tesseract_common/types.h>
#ifdef SWIG
%shared_ptr(tesseract_visualization::ToolpathMarker)
#endif // SWIG
namespace tesseract_visualization
{
/** @brief An arrow defined by two points */
class ToolpathMarker : public Marker
{
public:
EIGEN_MAKE_ALIGNED_OPERATOR_NEW
ToolpathMarker() = default;
ToolpathMarker(tesseract_common::Toolpath toolpath) : toolpath(std::move(toolpath)) {}
int getType() const override { return static_cast<int>(MarkerType::TOOLPATH); }
bool show_path{ true };
bool show_axis{ true };
tesseract_common::Toolpath toolpath;
Eigen::Vector3d scale{ Eigen::Vector3d::Constant(0.03) };
};
} // namespace tesseract_visualization
#endif // TESSERACT_VISUALIZATION_MARKERS_TOOLPATH_MARKER_H
| [
"levi.armstrong@gmail.com"
] | levi.armstrong@gmail.com |
cdc0119cdba5a801b135a3beb2e908e7b0152f93 | e9d4afde74808b142810ce2cf8f1a854ee9fbc0d | /droid2600/jni/application/stella/src/gui/ListWidget.cxx | 14f0bb7f9e6e2be7f843a0619991f53d48dc35d6 | [] | no_license | hayate891/droid2600 | 994618c9b22773af7e3298a7f74da0716f1021f5 | 6abf13cd207be61e13588a2300b9f967ccce985a | refs/heads/master | 2021-01-20T08:49:08.233419 | 2016-01-06T09:07:00 | 2016-01-06T09:07:00 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 12,086 | cxx | //============================================================================
//
// SSSS tt lll lll
// SS SS tt ll ll
// SS tttttt eeee ll ll aaaa
// SSSS tt ee ee ll ll aa
// SS tt eeeeee ll ll aaaaa -- "An Atari 2600 VCS Emulator"
// SS SS tt ee ll ll aa aa
// SSSS ttt eeeee llll llll aaaaa
//
// Copyright (c) 1995-2010 by Bradford W. Mott, Stephen Anthony
// and the Stella Team
//
// See the file "License.txt" for information on usage and redistribution of
// this file, and for a DISCLAIMER OF ALL WARRANTIES.
//
// $Id: ListWidget.cxx,v 1.1.1.1 2010-10-26 03:44:58 cvs Exp $
//
// Based on code from ScummVM - Scumm Interpreter
// Copyright (C) 2002-2004 The ScummVM project
//============================================================================
#include <cctype>
#include <algorithm>
#include "OSystem.hxx"
#include "Widget.hxx"
#include "ScrollBarWidget.hxx"
#include "Dialog.hxx"
#include "FrameBuffer.hxx"
#include "ListWidget.hxx"
#include "bspf.hxx"
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
ListWidget::ListWidget(GuiObject* boss, const GUI::Font& font,
int x, int y, int w, int h, bool quickSelect)
: EditableWidget(boss, font, x, y, 16, 16),
_rows(0),
_cols(0),
_currentPos(0),
_selectedItem(-1),
_highlightedItem(-1),
_currentKeyDown(0),
_editMode(false),
_quickSelect(quickSelect),
_quickSelectTime(0)
{
_flags = WIDGET_ENABLED | WIDGET_CLEARBG | WIDGET_RETAIN_FOCUS;
_type = kListWidget;
_bgcolor = kWidColor;
_bgcolorhi = kWidColor;
_textcolor = kTextColor;
_textcolorhi = kTextColor;
_cols = w / _fontWidth;
_rows = h / _fontHeight;
// Set real dimensions
_w = w - kScrollBarWidth;
_h = h + 2;
// Create scrollbar and attach to the list
_scrollBar = new ScrollBarWidget(boss, font, _x + _w, _y, kScrollBarWidth, _h);
_scrollBar->setTarget(this);
}
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
ListWidget::~ListWidget()
{
}
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
void ListWidget::setSelected(int item)
{
if(item < -1 || item >= (int)_list.size())
return;
if(isEnabled())
{
if(_editMode)
abortEditMode();
_selectedItem = item;
sendCommand(kListSelectionChangedCmd, _selectedItem, _id);
_currentPos = _selectedItem - _rows / 2;
scrollToSelected();
}
}
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
void ListWidget::setHighlighted(int item)
{
if(item < -1 || item >= (int)_list.size())
return;
if(isEnabled())
{
if(_editMode)
abortEditMode();
_highlightedItem = item;
// Only scroll the list if we're about to pass the page boundary
if(_currentPos == 0)
_currentPos = _highlightedItem;
else if(_highlightedItem == _currentPos + _rows)
_currentPos += _rows;
scrollToHighlighted();
}
}
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
void ListWidget::scrollTo(int item)
{
int size = _list.size();
if (item >= size)
item = size - 1;
if (item < 0)
item = 0;
if(_currentPos != item)
{
_currentPos = item;
scrollBarRecalc();
}
}
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
void ListWidget::recalc()
{
int size = _list.size();
if (_currentPos >= size)
_currentPos = size - 1;
if (_currentPos < 0)
_currentPos = 0;
if(_selectedItem < 0 || _selectedItem >= size)
_selectedItem = 0;
_editMode = false;
_scrollBar->_numEntries = _list.size();
_scrollBar->_entriesPerPage = _rows;
// Reset to normal data entry
abortEditMode();
}
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
void ListWidget::scrollBarRecalc()
{
_scrollBar->_currentPos = _currentPos;
_scrollBar->recalc();
sendCommand(kListScrolledCmd, _currentPos, _id);
}
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
void ListWidget::handleMouseDown(int x, int y, int button, int clickCount)
{
if (!isEnabled())
return;
// First check whether the selection changed
int newSelectedItem;
newSelectedItem = findItem(x, y);
if (newSelectedItem > (int)_list.size() - 1)
newSelectedItem = -1;
if (_selectedItem != newSelectedItem)
{
if (_editMode)
abortEditMode();
_selectedItem = newSelectedItem;
sendCommand(kListSelectionChangedCmd, _selectedItem, _id);
setDirty(); draw();
}
// TODO: Determine where inside the string the user clicked and place the
// caret accordingly. See _editScrollOffset and EditTextWidget::handleMouseDown.
}
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
void ListWidget::handleMouseUp(int x, int y, int button, int clickCount)
{
// If this was a double click and the mouse is still over the selected item,
// send the double click command
if (clickCount == 2 && (_selectedItem == findItem(x, y)))
{
sendCommand(kListItemDoubleClickedCmd, _selectedItem, _id);
// Start edit mode
if(_editable && !_editMode)
startEditMode();
}
}
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
void ListWidget::handleMouseWheel(int x, int y, int direction)
{
_scrollBar->handleMouseWheel(x, y, direction);
}
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
int ListWidget::findItem(int x, int y) const
{
return (y - 1) / _fontHeight + _currentPos;
}
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
bool ListWidget::handleKeyDown(int ascii, int keycode, int modifiers)
{
// Ignore all Alt-mod keys
if(instance().eventHandler().kbdAlt(modifiers))
return true;
bool handled = true;
int oldSelectedItem = _selectedItem;
if (!_editMode && _quickSelect &&
((isalnum((char)ascii)) || isspace((char)ascii)))
{
// Quick selection mode: Go to first list item starting with this key
// (or a substring accumulated from the last couple key presses).
// Only works in a useful fashion if the list entries are sorted.
// TODO: Maybe this should be off by default, and instead we add a
// method "enableQuickSelect()" or so ?
uInt64 time = instance().getTicks() / 1000;
if (_quickSelectTime < time)
_quickSelectStr = (char)ascii;
else
_quickSelectStr += (char)ascii;
_quickSelectTime = time + _QUICK_SELECT_DELAY;
// FIXME: This is bad slow code (it scans the list linearly each time a
// key is pressed); it could be much faster. Only of importance if we have
// quite big lists to deal with -- so for now we can live with this lazy
// implementation :-)
int newSelectedItem = 0;
for (StringList::const_iterator i = _list.begin(); i != _list.end(); ++i)
{
if(BSPF_strncasecmp((*i).c_str(), _quickSelectStr.c_str(),
_quickSelectStr.length()) == 0)
{
_selectedItem = newSelectedItem;
break;
}
newSelectedItem++;
}
}
else if (_editMode)
{
// Class EditableWidget handles all text editing related key presses for us
handled = EditableWidget::handleKeyDown(ascii, keycode, modifiers);
}
else
{
// not editmode
switch (keycode)
{
case ' ': // space
// Snap list back to currently highlighted line
if(_highlightedItem >= 0)
{
_currentPos = _highlightedItem;
scrollToHighlighted();
}
break;
default:
handled = false;
}
}
if (_selectedItem != oldSelectedItem)
{
_scrollBar->draw();
scrollToSelected();
sendCommand(kListSelectionChangedCmd, _selectedItem, _id);
}
_currentKeyDown = keycode;
return handled;
}
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
bool ListWidget::handleKeyUp(int ascii, int keycode, int modifiers)
{
if (keycode == _currentKeyDown)
_currentKeyDown = 0;
return true;
}
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
bool ListWidget::handleEvent(Event::Type e)
{
if(!isEnabled() || _editMode)
return false;
bool handled = true;
int oldSelectedItem = _selectedItem;
switch(e)
{
case Event::UISelect:
if (_selectedItem >= 0)
{
if (_editable)
startEditMode();
else
sendCommand(kListItemActivatedCmd, _selectedItem, _id);
}
break;
case Event::UIUp:
if (_selectedItem > 0)
_selectedItem--;
break;
case Event::UIDown:
if (_selectedItem < (int)_list.size() - 1)
_selectedItem++;
break;
case Event::UIPgUp:
_selectedItem -= _rows - 1;
if (_selectedItem < 0)
_selectedItem = 0;
break;
case Event::UIPgDown:
_selectedItem += _rows - 1;
if (_selectedItem >= (int)_list.size() )
_selectedItem = _list.size() - 1;
break;
case Event::UIHome:
_selectedItem = 0;
break;
case Event::UIEnd:
_selectedItem = _list.size() - 1;
break;
case Event::UIPrevDir:
sendCommand(kListPrevDirCmd, _selectedItem, _id);
break;
default:
handled = false;
}
if (_selectedItem != oldSelectedItem)
{
_scrollBar->draw();
scrollToSelected();
sendCommand(kListSelectionChangedCmd, _selectedItem, _id);
}
return handled;
}
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
void ListWidget::lostFocusWidget()
{
_editMode = false;
// Reset to normal data entry
abortEditMode();
}
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
void ListWidget::handleCommand(CommandSender* sender, int cmd, int data, int id)
{
switch (cmd)
{
case kSetPositionCmd:
if (_currentPos != (int)data)
{
_currentPos = data;
setDirty(); draw();
// Let boss know the list has scrolled
sendCommand(kListScrolledCmd, _currentPos, _id);
}
break;
}
}
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
void ListWidget::scrollToCurrent(int item)
{
// Only do something if the current item is not in our view port
if (item < _currentPos)
{
// it's above our view
_currentPos = item;
}
else if (item >= _currentPos + _rows )
{
// it's below our view
_currentPos = item - _rows + 1;
}
if (_currentPos < 0 || _rows > (int)_list.size())
_currentPos = 0;
else if (_currentPos + _rows > (int)_list.size())
_currentPos = _list.size() - _rows;
int oldScrollPos = _scrollBar->_currentPos;
_scrollBar->_currentPos = _currentPos;
_scrollBar->recalc();
setDirty(); draw();
if(oldScrollPos != _currentPos)
sendCommand(kListScrolledCmd, _currentPos, _id);
}
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
void ListWidget::startEditMode()
{
if (_editable && !_editMode && _selectedItem >= 0)
{
_editMode = true;
setEditString(_list[_selectedItem]);
// Widget gets raw data while editing
EditableWidget::startEditMode();
}
}
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
void ListWidget::endEditMode()
{
if (!_editMode)
return;
// Send a message that editing finished with a return/enter key press
_editMode = false;
_list[_selectedItem] = _editString;
sendCommand(kListItemDataChangedCmd, _selectedItem, _id);
// Reset to normal data entry
EditableWidget::endEditMode();
}
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
void ListWidget::abortEditMode()
{
// Undo any changes made
_editMode = false;
// Reset to normal data entry
EditableWidget::abortEditMode();
}
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
uInt64 ListWidget::_QUICK_SELECT_DELAY = 300;
| [
"diggerbonk@8dcf4d61-0491-8b3c-6e88-956cef96344b"
] | diggerbonk@8dcf4d61-0491-8b3c-6e88-956cef96344b |
de41e7e6304666c372381360e65ccbff893cc1f1 | 40712dc426dfb114dfabe5913b0bfa08ab618961 | /Extras/wxWidgets-2.9.0/include/wx/msw/listbox.h | c672122730c1c411d2764782f41ea76ec19acb2a | [] | no_license | erwincoumans/dynamica | 7dc8e06966ca1ced3fc56bd3b655a40c38dae8fa | 8b5eb35467de0495f43ed929d82617c21d2abecb | refs/heads/master | 2021-01-17T05:53:34.958159 | 2015-02-10T18:34:11 | 2015-02-10T18:34:11 | 31,622,543 | 7 | 3 | null | null | null | null | UTF-8 | C++ | false | false | 5,903 | h | /////////////////////////////////////////////////////////////////////////////
// Name: wx/msw/listbox.h
// Purpose: wxListBox class
// Author: Julian Smart
// Modified by:
// Created: 01/02/97
// RCS-ID: $Id: listbox.h 53743 2008-05-25 20:54:30Z RR $
// Copyright: (c) Julian Smart
// Licence: wxWindows licence
/////////////////////////////////////////////////////////////////////////////
#ifndef _WX_LISTBOX_H_
#define _WX_LISTBOX_H_
#if wxUSE_LISTBOX
// ----------------------------------------------------------------------------
// simple types
// ----------------------------------------------------------------------------
#if wxUSE_OWNER_DRAWN
class WXDLLIMPEXP_FWD_CORE wxOwnerDrawn;
// define the array of list box items
#include "wx/dynarray.h"
WX_DEFINE_EXPORTED_ARRAY_PTR(wxOwnerDrawn *, wxListBoxItemsArray);
#endif // wxUSE_OWNER_DRAWN
// forward decl for GetSelections()
class WXDLLIMPEXP_FWD_BASE wxArrayInt;
// ----------------------------------------------------------------------------
// List box control
// ----------------------------------------------------------------------------
class WXDLLIMPEXP_CORE wxListBox : public wxListBoxBase
{
public:
// ctors and such
wxListBox();
wxListBox(wxWindow *parent, wxWindowID id,
const wxPoint& pos = wxDefaultPosition,
const wxSize& size = wxDefaultSize,
int n = 0, const wxString choices[] = NULL,
long style = 0,
const wxValidator& validator = wxDefaultValidator,
const wxString& name = wxListBoxNameStr)
{
Create(parent, id, pos, size, n, choices, style, validator, name);
}
wxListBox(wxWindow *parent, wxWindowID id,
const wxPoint& pos,
const wxSize& size,
const wxArrayString& choices,
long style = 0,
const wxValidator& validator = wxDefaultValidator,
const wxString& name = wxListBoxNameStr)
{
Create(parent, id, pos, size, choices, style, validator, name);
}
bool Create(wxWindow *parent, wxWindowID id,
const wxPoint& pos = wxDefaultPosition,
const wxSize& size = wxDefaultSize,
int n = 0, const wxString choices[] = NULL,
long style = 0,
const wxValidator& validator = wxDefaultValidator,
const wxString& name = wxListBoxNameStr);
bool Create(wxWindow *parent, wxWindowID id,
const wxPoint& pos,
const wxSize& size,
const wxArrayString& choices,
long style = 0,
const wxValidator& validator = wxDefaultValidator,
const wxString& name = wxListBoxNameStr);
virtual ~wxListBox();
virtual unsigned int GetCount() const;
virtual wxString GetString(unsigned int n) const;
virtual void SetString(unsigned int n, const wxString& s);
virtual int FindString(const wxString& s, bool bCase = false) const;
virtual bool IsSelected(int n) const;
virtual int GetSelection() const;
virtual int GetSelections(wxArrayInt& aSelections) const;
// wxCheckListBox support
#if wxUSE_OWNER_DRAWN
bool MSWOnMeasure(WXMEASUREITEMSTRUCT *item);
bool MSWOnDraw(WXDRAWITEMSTRUCT *item);
// plug-in for derived classes
virtual wxOwnerDrawn *CreateLboxItem(size_t n);
// allows to get the item and use SetXXX functions to set it's appearance
wxOwnerDrawn *GetItem(size_t n) const { return m_aItems[n]; }
// get the index of the given item
int GetItemIndex(wxOwnerDrawn *item) const { return m_aItems.Index(item); }
#endif // wxUSE_OWNER_DRAWN
// Windows-specific code to update the horizontal extent of the listbox, if
// necessary. If s is non-empty, the horizontal extent is increased to the
// length of this string if it's currently too short, otherwise the maximum
// extent of all strings is used. In any case calls InvalidateBestSize()
virtual void SetHorizontalExtent(const wxString& s = wxEmptyString);
// Windows callbacks
bool MSWCommand(WXUINT param, WXWORD id);
WXDWORD MSWGetStyle(long style, WXDWORD *exstyle) const;
// under XP when using "transition effect for menus and tooltips" if we
// return true for WM_PRINTCLIENT here then it causes noticable slowdown
virtual bool MSWShouldPropagatePrintChild()
{
return false;
}
virtual wxVisualAttributes GetDefaultAttributes() const
{
return GetClassDefaultAttributes(GetWindowVariant());
}
static wxVisualAttributes
GetClassDefaultAttributes(wxWindowVariant variant = wxWINDOW_VARIANT_NORMAL)
{
return GetCompositeControlsDefaultAttributes(variant);
}
// returns true if the platform should explicitly apply a theme border
virtual bool CanApplyThemeBorder() const { return false; }
protected:
virtual void DoClear();
virtual void DoDeleteOneItem(unsigned int n);
virtual void DoSetSelection(int n, bool select);
virtual int DoInsertItems(const wxArrayStringsAdapter& items,
unsigned int pos,
void **clientData, wxClientDataType type);
virtual void DoSetFirstItem(int n);
virtual void DoSetItemClientData(unsigned int n, void* clientData);
virtual void* DoGetItemClientData(unsigned int n) const;
virtual int DoListHitTest(const wxPoint& point) const;
bool m_updateHorizontalExtent;
virtual void OnInternalIdle();
// free memory (common part of Clear() and dtor)
void Free();
unsigned int m_noItems;
virtual wxSize DoGetBestSize() const;
#if wxUSE_OWNER_DRAWN
// control items
wxListBoxItemsArray m_aItems;
#endif
private:
DECLARE_DYNAMIC_CLASS_NO_COPY(wxListBox)
};
#endif // wxUSE_LISTBOX
#endif
// _WX_LISTBOX_H_
| [
"erwin.coumans@e05b9ecc-110c-11df-b47a-af0d17c1a499"
] | erwin.coumans@e05b9ecc-110c-11df-b47a-af0d17c1a499 |
16d50f078dc22303a6ff30a244ab1f64dc358703 | d9ed9b7780110a0c53be11e49708198d3f032850 | /Album.hpp | ccc66fb863d13d2b0a1190df01681aa13459b4f0 | [] | no_license | grantsrb/cpp-library_catalog | 790be8a09ae9e6207495c57e0cd6c907de769d0f | b4400f17284bd8f1a3fddd07cd0392d9b17aa588 | refs/heads/master | 2020-06-13T15:36:57.225344 | 2016-12-02T06:08:47 | 2016-12-02T06:08:47 | 75,364,802 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 571 | hpp | /*
Author: Satchel Grant
Date: 05/30/16
Description: Album Class inherits from LibraryItem Class. It describes an album
in the library inventory.
*/
#ifndef ALBUM_HPP
#define ALBUM_HPP
#include "LibraryItem.hpp"
#include <string>
#include <vector>
class Album: public LibraryItem {
private:
std::string artist;
public:
Album(std::string idc, std::string t, std::string artistName);
static const int CHECK_OUT_LENGTH; // Days till overdue
std::string getArtist();
void setArtist(std::string artistName);
virtual int getCheckOutLength();
};
#endif
| [
"grantsrb@gmail.com"
] | grantsrb@gmail.com |
e7d190bd05f99d9f3b95b7a02e1b54e3e487dfbe | 3438e8c139a5833836a91140af412311aebf9e86 | /ui/compositor/layer_unittest.cc | 0a58a648e5284b89f852ab5efc38a79a12f0a743 | [
"BSD-3-Clause"
] | permissive | Exstream-OpenSource/Chromium | 345b4336b2fbc1d5609ac5a67dbf361812b84f54 | 718ca933938a85c6d5548c5fad97ea7ca1128751 | refs/heads/master | 2022-12-21T20:07:40.786370 | 2016-10-18T04:53:43 | 2016-10-18T04:53:43 | 71,210,435 | 0 | 2 | BSD-3-Clause | 2022-12-18T12:14:22 | 2016-10-18T04:58:13 | null | UTF-8 | C++ | false | false | 70,842 | cc | // Copyright (c) 2012 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.
#include "ui/compositor/layer.h"
#include <stddef.h>
#include <memory>
#include <utility>
#include "base/bind.h"
#include "base/compiler_specific.h"
#include "base/files/file_path.h"
#include "base/files/file_util.h"
#include "base/json/json_reader.h"
#include "base/macros.h"
#include "base/memory/ptr_util.h"
#include "base/message_loop/message_loop.h"
#include "base/path_service.h"
#include "base/strings/string_util.h"
#include "base/strings/stringprintf.h"
#include "base/strings/utf_string_conversions.h"
#include "base/trace_event/trace_event.h"
#include "cc/animation/animation_player.h"
#include "cc/layers/layer.h"
#include "cc/output/copy_output_request.h"
#include "cc/output/copy_output_result.h"
#include "cc/surfaces/surface_id.h"
#include "cc/surfaces/surface_sequence.h"
#include "cc/test/pixel_test_utils.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "third_party/khronos/GLES2/gl2.h"
#include "ui/compositor/compositor_observer.h"
#include "ui/compositor/dip_util.h"
#include "ui/compositor/layer_animation_element.h"
#include "ui/compositor/layer_animation_observer.h"
#include "ui/compositor/layer_animation_sequence.h"
#include "ui/compositor/layer_animator.h"
#include "ui/compositor/paint_context.h"
#include "ui/compositor/paint_recorder.h"
#include "ui/compositor/scoped_animation_duration_scale_mode.h"
#include "ui/compositor/scoped_layer_animation_settings.h"
#include "ui/compositor/test/context_factories_for_test.h"
#include "ui/compositor/test/draw_waiter_for_test.h"
#include "ui/compositor/test/test_compositor_host.h"
#include "ui/compositor/test/test_layers.h"
#include "ui/gfx/canvas.h"
#include "ui/gfx/codec/png_codec.h"
#include "ui/gfx/font_list.h"
#include "ui/gfx/gfx_paths.h"
#include "ui/gfx/skia_util.h"
using cc::MatchesPNGFile;
using cc::WritePNGFile;
namespace ui {
namespace {
// There are three test classes in here that configure the Compositor and
// Layer's slightly differently:
// - LayerWithNullDelegateTest uses NullLayerDelegate as the LayerDelegate. This
// is typically the base class you want to use.
// - LayerWithDelegateTest uses LayerDelegate on the delegates.
// - LayerWithRealCompositorTest when a real compositor is required for testing.
// - Slow because they bring up a window and run the real compositor. This
// is typically not what you want.
class ColoredLayer : public Layer, public LayerDelegate {
public:
explicit ColoredLayer(SkColor color)
: Layer(LAYER_TEXTURED),
color_(color) {
set_delegate(this);
}
~ColoredLayer() override {}
// Overridden from LayerDelegate:
void OnPaintLayer(const ui::PaintContext& context) override {
ui::PaintRecorder recorder(context, size());
recorder.canvas()->DrawColor(color_);
}
void OnDelegatedFrameDamage(const gfx::Rect& damage_rect_in_dip) override {}
void OnDeviceScaleFactorChanged(float device_scale_factor) override {}
private:
SkColor color_;
};
// Layer delegate for painting text with effects on canvas.
class DrawStringLayerDelegate : public LayerDelegate {
public:
enum DrawFunction {
STRING_WITH_HALO,
STRING_FADED,
STRING_WITH_SHADOWS
};
DrawStringLayerDelegate(
SkColor back_color, SkColor halo_color,
DrawFunction func, const gfx::Size& layer_size)
: background_color_(back_color),
halo_color_(halo_color),
func_(func),
layer_size_(layer_size) {
}
~DrawStringLayerDelegate() override {}
// Overridden from LayerDelegate:
void OnPaintLayer(const ui::PaintContext& context) override {
ui::PaintRecorder recorder(context, layer_size_);
gfx::Rect bounds(layer_size_);
recorder.canvas()->DrawColor(background_color_);
const base::string16 text = base::ASCIIToUTF16("Tests!");
switch (func_) {
case STRING_WITH_HALO:
recorder.canvas()->DrawStringRectWithHalo(
text, font_list_, SK_ColorRED, halo_color_, bounds, 0);
break;
case STRING_FADED:
recorder.canvas()->DrawFadedString(
text, font_list_, SK_ColorRED, bounds, 0);
break;
case STRING_WITH_SHADOWS: {
gfx::ShadowValues shadows;
shadows.push_back(
gfx::ShadowValue(gfx::Vector2d(2, 2), 2, SK_ColorRED));
recorder.canvas()->DrawStringRectWithShadows(
text, font_list_, SK_ColorRED, bounds, 0, 0, shadows);
break;
}
default:
NOTREACHED();
}
}
void OnDelegatedFrameDamage(const gfx::Rect& damage_rect_in_dip) override {}
void OnDeviceScaleFactorChanged(float device_scale_factor) override {}
private:
const SkColor background_color_;
const SkColor halo_color_;
const DrawFunction func_;
const gfx::FontList font_list_;
const gfx::Size layer_size_;
DISALLOW_COPY_AND_ASSIGN(DrawStringLayerDelegate);
};
class LayerWithRealCompositorTest : public testing::Test {
public:
LayerWithRealCompositorTest() {
if (PathService::Get(gfx::DIR_TEST_DATA, &test_data_directory_)) {
test_data_directory_ = test_data_directory_.AppendASCII("compositor");
} else {
LOG(ERROR) << "Could not open test data directory.";
}
gfx::FontList::SetDefaultFontDescription("Arial, Times New Roman, 15px");
}
~LayerWithRealCompositorTest() override {}
// Overridden from testing::Test:
void SetUp() override {
bool enable_pixel_output = true;
ui::ContextFactory* context_factory =
InitializeContextFactoryForTests(enable_pixel_output);
const gfx::Rect host_bounds(10, 10, 500, 500);
compositor_host_.reset(
TestCompositorHost::Create(host_bounds, context_factory));
compositor_host_->Show();
}
void TearDown() override {
ResetCompositor();
TerminateContextFactoryForTests();
}
Compositor* GetCompositor() { return compositor_host_->GetCompositor(); }
void ResetCompositor() {
compositor_host_.reset();
}
Layer* CreateLayer(LayerType type) {
return new Layer(type);
}
Layer* CreateColorLayer(SkColor color, const gfx::Rect& bounds) {
Layer* layer = new ColoredLayer(color);
layer->SetBounds(bounds);
return layer;
}
Layer* CreateNoTextureLayer(const gfx::Rect& bounds) {
Layer* layer = CreateLayer(LAYER_NOT_DRAWN);
layer->SetBounds(bounds);
return layer;
}
std::unique_ptr<Layer> CreateDrawStringLayer(
const gfx::Rect& bounds, DrawStringLayerDelegate* delegate) {
std::unique_ptr<Layer> layer(new Layer(LAYER_TEXTURED));
layer->SetBounds(bounds);
layer->set_delegate(delegate);
return layer;
}
void DrawTree(Layer* root) {
GetCompositor()->SetRootLayer(root);
GetCompositor()->ScheduleDraw();
WaitForSwap();
}
void ReadPixels(SkBitmap* bitmap) {
ReadPixels(bitmap, gfx::Rect(GetCompositor()->size()));
}
void ReadPixels(SkBitmap* bitmap, gfx::Rect source_rect) {
scoped_refptr<ReadbackHolder> holder(new ReadbackHolder);
std::unique_ptr<cc::CopyOutputRequest> request =
cc::CopyOutputRequest::CreateBitmapRequest(
base::Bind(&ReadbackHolder::OutputRequestCallback, holder));
request->set_area(source_rect);
GetCompositor()->root_layer()->RequestCopyOfOutput(std::move(request));
// Wait for copy response. This needs to wait as the compositor could
// be in the middle of a draw right now, and the commit with the
// copy output request may not be done on the first draw.
for (int i = 0; i < 2; i++) {
GetCompositor()->ScheduleFullRedraw();
WaitForDraw();
}
// Waits for the callback to finish run and return result.
holder->WaitForReadback();
*bitmap = holder->result();
}
void WaitForDraw() {
ui::DrawWaiterForTest::WaitForCompositingStarted(GetCompositor());
}
void WaitForSwap() {
DrawWaiterForTest::WaitForCompositingEnded(GetCompositor());
}
void WaitForCommit() {
ui::DrawWaiterForTest::WaitForCommit(GetCompositor());
}
// Invalidates the entire contents of the layer.
void SchedulePaintForLayer(Layer* layer) {
layer->SchedulePaint(
gfx::Rect(0, 0, layer->bounds().width(), layer->bounds().height()));
}
const base::FilePath& test_data_directory() const {
return test_data_directory_;
}
private:
class ReadbackHolder : public base::RefCountedThreadSafe<ReadbackHolder> {
public:
ReadbackHolder() : run_loop_(new base::RunLoop) {}
void OutputRequestCallback(std::unique_ptr<cc::CopyOutputResult> result) {
result_ = result->TakeBitmap();
run_loop_->Quit();
}
void WaitForReadback() { run_loop_->Run(); }
const SkBitmap& result() const { return *result_; }
private:
friend class base::RefCountedThreadSafe<ReadbackHolder>;
virtual ~ReadbackHolder() {}
std::unique_ptr<SkBitmap> result_;
std::unique_ptr<base::RunLoop> run_loop_;
};
std::unique_ptr<TestCompositorHost> compositor_host_;
// The root directory for test files.
base::FilePath test_data_directory_;
DISALLOW_COPY_AND_ASSIGN(LayerWithRealCompositorTest);
};
// LayerDelegate that paints colors to the layer.
class TestLayerDelegate : public LayerDelegate {
public:
TestLayerDelegate() { reset(); }
~TestLayerDelegate() override {}
void AddColor(SkColor color) {
colors_.push_back(color);
}
int color_index() const { return color_index_; }
float device_scale_factor() const {
return device_scale_factor_;
}
void set_layer_bounds(const gfx::Rect& layer_bounds) {
layer_bounds_ = layer_bounds;
}
// Overridden from LayerDelegate:
void OnPaintLayer(const ui::PaintContext& context) override {
ui::PaintRecorder recorder(context, layer_bounds_.size());
recorder.canvas()->DrawColor(colors_[color_index_]);
color_index_ = (color_index_ + 1) % static_cast<int>(colors_.size());
}
void OnDelegatedFrameDamage(const gfx::Rect& damage_rect_in_dip) override {}
void OnDeviceScaleFactorChanged(float device_scale_factor) override {
device_scale_factor_ = device_scale_factor;
}
void reset() {
color_index_ = 0;
device_scale_factor_ = 0.0f;
}
private:
std::vector<SkColor> colors_;
int color_index_;
float device_scale_factor_;
gfx::Rect layer_bounds_;
DISALLOW_COPY_AND_ASSIGN(TestLayerDelegate);
};
// LayerDelegate that verifies that a layer was asked to update its canvas.
class DrawTreeLayerDelegate : public LayerDelegate {
public:
DrawTreeLayerDelegate(const gfx::Rect& layer_bounds)
: painted_(false), layer_bounds_(layer_bounds) {}
~DrawTreeLayerDelegate() override {}
void Reset() {
painted_ = false;
}
bool painted() const { return painted_; }
private:
// Overridden from LayerDelegate:
void OnPaintLayer(const ui::PaintContext& context) override {
painted_ = true;
ui::PaintRecorder recorder(context, layer_bounds_.size());
recorder.canvas()->DrawColor(SK_ColorWHITE);
}
void OnDelegatedFrameDamage(const gfx::Rect& damage_rect_in_dip) override {}
void OnDeviceScaleFactorChanged(float device_scale_factor) override {}
bool painted_;
const gfx::Rect layer_bounds_;
DISALLOW_COPY_AND_ASSIGN(DrawTreeLayerDelegate);
};
// The simplest possible layer delegate. Does nothing.
class NullLayerDelegate : public LayerDelegate {
public:
NullLayerDelegate() {}
~NullLayerDelegate() override {}
private:
// Overridden from LayerDelegate:
void OnPaintLayer(const ui::PaintContext& context) override {}
void OnDelegatedFrameDamage(const gfx::Rect& damage_rect_in_dip) override {}
void OnDeviceScaleFactorChanged(float device_scale_factor) override {}
DISALLOW_COPY_AND_ASSIGN(NullLayerDelegate);
};
// Remembers if it has been notified.
class TestCompositorObserver : public CompositorObserver {
public:
TestCompositorObserver()
: committed_(false), started_(false), ended_(false), aborted_(false) {}
bool committed() const { return committed_; }
bool notified() const { return started_ && ended_; }
bool aborted() const { return aborted_; }
void Reset() {
committed_ = false;
started_ = false;
ended_ = false;
aborted_ = false;
}
private:
void OnCompositingDidCommit(Compositor* compositor) override {
committed_ = true;
}
void OnCompositingStarted(Compositor* compositor,
base::TimeTicks start_time) override {
started_ = true;
}
void OnCompositingEnded(Compositor* compositor) override { ended_ = true; }
void OnCompositingAborted(Compositor* compositor) override {
aborted_ = true;
}
void OnCompositingLockStateChanged(Compositor* compositor) override {}
void OnCompositingShuttingDown(Compositor* compositor) override {}
bool committed_;
bool started_;
bool ended_;
bool aborted_;
DISALLOW_COPY_AND_ASSIGN(TestCompositorObserver);
};
class TestCompositorAnimationObserver : public CompositorAnimationObserver {
public:
explicit TestCompositorAnimationObserver(ui::Compositor* compositor)
: compositor_(compositor),
animation_step_count_(0),
shutdown_(false) {
DCHECK(compositor_);
compositor_->AddAnimationObserver(this);
}
~TestCompositorAnimationObserver() override {
if (compositor_)
compositor_->RemoveAnimationObserver(this);
}
size_t animation_step_count() const { return animation_step_count_; }
bool shutdown() const { return shutdown_; }
private:
void OnAnimationStep(base::TimeTicks timestamp) override {
++animation_step_count_;
}
void OnCompositingShuttingDown(Compositor* compositor) override {
DCHECK_EQ(compositor_, compositor);
compositor_->RemoveAnimationObserver(this);
compositor_ = nullptr;
shutdown_ = true;
}
ui::Compositor* compositor_;
size_t animation_step_count_;
bool shutdown_;
DISALLOW_COPY_AND_ASSIGN(TestCompositorAnimationObserver);
};
} // namespace
TEST_F(LayerWithRealCompositorTest, Draw) {
std::unique_ptr<Layer> layer(
CreateColorLayer(SK_ColorRED, gfx::Rect(20, 20, 50, 50)));
DrawTree(layer.get());
}
// Create this hierarchy:
// L1 - red
// +-- L2 - blue
// | +-- L3 - yellow
// +-- L4 - magenta
//
TEST_F(LayerWithRealCompositorTest, Hierarchy) {
std::unique_ptr<Layer> l1(
CreateColorLayer(SK_ColorRED, gfx::Rect(20, 20, 400, 400)));
std::unique_ptr<Layer> l2(
CreateColorLayer(SK_ColorBLUE, gfx::Rect(10, 10, 350, 350)));
std::unique_ptr<Layer> l3(
CreateColorLayer(SK_ColorYELLOW, gfx::Rect(5, 5, 25, 25)));
std::unique_ptr<Layer> l4(
CreateColorLayer(SK_ColorMAGENTA, gfx::Rect(300, 300, 100, 100)));
l1->Add(l2.get());
l1->Add(l4.get());
l2->Add(l3.get());
DrawTree(l1.get());
}
class LayerWithDelegateTest : public testing::Test {
public:
LayerWithDelegateTest() {}
~LayerWithDelegateTest() override {}
// Overridden from testing::Test:
void SetUp() override {
bool enable_pixel_output = false;
ui::ContextFactory* context_factory =
InitializeContextFactoryForTests(enable_pixel_output);
const gfx::Rect host_bounds(1000, 1000);
compositor_host_.reset(TestCompositorHost::Create(host_bounds,
context_factory));
compositor_host_->Show();
}
void TearDown() override {
compositor_host_.reset();
TerminateContextFactoryForTests();
}
Compositor* compositor() { return compositor_host_->GetCompositor(); }
virtual Layer* CreateLayer(LayerType type) {
return new Layer(type);
}
Layer* CreateColorLayer(SkColor color, const gfx::Rect& bounds) {
Layer* layer = new ColoredLayer(color);
layer->SetBounds(bounds);
return layer;
}
virtual Layer* CreateNoTextureLayer(const gfx::Rect& bounds) {
Layer* layer = CreateLayer(LAYER_NOT_DRAWN);
layer->SetBounds(bounds);
return layer;
}
void DrawTree(Layer* root) {
compositor()->SetRootLayer(root);
Draw();
}
// Invalidates the entire contents of the layer.
void SchedulePaintForLayer(Layer* layer) {
layer->SchedulePaint(
gfx::Rect(0, 0, layer->bounds().width(), layer->bounds().height()));
}
// Invokes DrawTree on the compositor.
void Draw() {
compositor()->ScheduleDraw();
WaitForDraw();
}
void WaitForDraw() {
DrawWaiterForTest::WaitForCompositingStarted(compositor());
}
void WaitForCommit() {
DrawWaiterForTest::WaitForCommit(compositor());
}
private:
std::unique_ptr<TestCompositorHost> compositor_host_;
DISALLOW_COPY_AND_ASSIGN(LayerWithDelegateTest);
};
void ReturnMailbox(bool* run, const gpu::SyncToken& sync_token, bool is_lost) {
*run = true;
}
TEST(LayerStandaloneTest, ReleaseMailboxOnDestruction) {
std::unique_ptr<Layer> layer(new Layer(LAYER_TEXTURED));
bool callback_run = false;
cc::TextureMailbox mailbox(gpu::Mailbox::Generate(), gpu::SyncToken(), 0);
layer->SetTextureMailbox(mailbox,
cc::SingleReleaseCallback::Create(
base::Bind(ReturnMailbox, &callback_run)),
gfx::Size(10, 10));
EXPECT_FALSE(callback_run);
layer.reset();
EXPECT_TRUE(callback_run);
}
// L1
// +-- L2
TEST_F(LayerWithDelegateTest, ConvertPointToLayer_Simple) {
std::unique_ptr<Layer> l1(
CreateColorLayer(SK_ColorRED, gfx::Rect(20, 20, 400, 400)));
std::unique_ptr<Layer> l2(
CreateColorLayer(SK_ColorBLUE, gfx::Rect(10, 10, 350, 350)));
l1->Add(l2.get());
DrawTree(l1.get());
gfx::Point point1_in_l2_coords(5, 5);
Layer::ConvertPointToLayer(l2.get(), l1.get(), &point1_in_l2_coords);
gfx::Point point1_in_l1_coords(15, 15);
EXPECT_EQ(point1_in_l1_coords, point1_in_l2_coords);
gfx::Point point2_in_l1_coords(5, 5);
Layer::ConvertPointToLayer(l1.get(), l2.get(), &point2_in_l1_coords);
gfx::Point point2_in_l2_coords(-5, -5);
EXPECT_EQ(point2_in_l2_coords, point2_in_l1_coords);
}
// L1
// +-- L2
// +-- L3
TEST_F(LayerWithDelegateTest, ConvertPointToLayer_Medium) {
std::unique_ptr<Layer> l1(
CreateColorLayer(SK_ColorRED, gfx::Rect(20, 20, 400, 400)));
std::unique_ptr<Layer> l2(
CreateColorLayer(SK_ColorBLUE, gfx::Rect(10, 10, 350, 350)));
std::unique_ptr<Layer> l3(
CreateColorLayer(SK_ColorYELLOW, gfx::Rect(10, 10, 100, 100)));
l1->Add(l2.get());
l2->Add(l3.get());
DrawTree(l1.get());
gfx::Point point1_in_l3_coords(5, 5);
Layer::ConvertPointToLayer(l3.get(), l1.get(), &point1_in_l3_coords);
gfx::Point point1_in_l1_coords(25, 25);
EXPECT_EQ(point1_in_l1_coords, point1_in_l3_coords);
gfx::Point point2_in_l1_coords(5, 5);
Layer::ConvertPointToLayer(l1.get(), l3.get(), &point2_in_l1_coords);
gfx::Point point2_in_l3_coords(-15, -15);
EXPECT_EQ(point2_in_l3_coords, point2_in_l1_coords);
}
TEST_F(LayerWithRealCompositorTest, Delegate) {
// This test makes sure that whenever paint happens at a layer, its layer
// delegate gets the paint, which in this test update its color and
// |color_index|.
std::unique_ptr<Layer> l1(
CreateColorLayer(SK_ColorBLACK, gfx::Rect(20, 20, 400, 400)));
GetCompositor()->SetRootLayer(l1.get());
WaitForDraw();
TestLayerDelegate delegate;
l1->set_delegate(&delegate);
delegate.set_layer_bounds(l1->bounds());
delegate.AddColor(SK_ColorWHITE);
delegate.AddColor(SK_ColorYELLOW);
delegate.AddColor(SK_ColorGREEN);
l1->SchedulePaint(gfx::Rect(0, 0, 400, 400));
WaitForDraw();
// Test that paint happened at layer delegate.
EXPECT_EQ(1, delegate.color_index());
l1->SchedulePaint(gfx::Rect(10, 10, 200, 200));
WaitForDraw();
// Test that paint happened at layer delegate.
EXPECT_EQ(2, delegate.color_index());
l1->SchedulePaint(gfx::Rect(5, 5, 50, 50));
WaitForDraw();
// Test that paint happened at layer delegate.
EXPECT_EQ(0, delegate.color_index());
}
TEST_F(LayerWithRealCompositorTest, DrawTree) {
std::unique_ptr<Layer> l1(
CreateColorLayer(SK_ColorRED, gfx::Rect(20, 20, 400, 400)));
std::unique_ptr<Layer> l2(
CreateColorLayer(SK_ColorBLUE, gfx::Rect(10, 10, 350, 350)));
std::unique_ptr<Layer> l3(
CreateColorLayer(SK_ColorYELLOW, gfx::Rect(10, 10, 100, 100)));
l1->Add(l2.get());
l2->Add(l3.get());
GetCompositor()->SetRootLayer(l1.get());
WaitForDraw();
DrawTreeLayerDelegate d1(l1->bounds());
l1->set_delegate(&d1);
DrawTreeLayerDelegate d2(l2->bounds());
l2->set_delegate(&d2);
DrawTreeLayerDelegate d3(l3->bounds());
l3->set_delegate(&d3);
l2->SchedulePaint(gfx::Rect(5, 5, 5, 5));
WaitForDraw();
EXPECT_FALSE(d1.painted());
EXPECT_TRUE(d2.painted());
EXPECT_FALSE(d3.painted());
}
// Tests that scheduling paint on a layer with a mask updates the mask.
TEST_F(LayerWithRealCompositorTest, SchedulePaintUpdatesMask) {
std::unique_ptr<Layer> layer(
CreateColorLayer(SK_ColorRED, gfx::Rect(20, 20, 400, 400)));
std::unique_ptr<Layer> mask_layer(CreateLayer(ui::LAYER_TEXTURED));
mask_layer->SetBounds(gfx::Rect(layer->GetTargetBounds().size()));
layer->SetMaskLayer(mask_layer.get());
GetCompositor()->SetRootLayer(layer.get());
WaitForDraw();
DrawTreeLayerDelegate d1(layer->bounds());
layer->set_delegate(&d1);
DrawTreeLayerDelegate d2(mask_layer->bounds());
mask_layer->set_delegate(&d2);
layer->SchedulePaint(gfx::Rect(5, 5, 5, 5));
WaitForDraw();
EXPECT_TRUE(d1.painted());
EXPECT_TRUE(d2.painted());
}
// Tests no-texture Layers.
// Create this hierarchy:
// L1 - red
// +-- L2 - NO TEXTURE
// | +-- L3 - yellow
// +-- L4 - magenta
//
TEST_F(LayerWithRealCompositorTest, HierarchyNoTexture) {
std::unique_ptr<Layer> l1(
CreateColorLayer(SK_ColorRED, gfx::Rect(20, 20, 400, 400)));
std::unique_ptr<Layer> l2(CreateNoTextureLayer(gfx::Rect(10, 10, 350, 350)));
std::unique_ptr<Layer> l3(
CreateColorLayer(SK_ColorYELLOW, gfx::Rect(5, 5, 25, 25)));
std::unique_ptr<Layer> l4(
CreateColorLayer(SK_ColorMAGENTA, gfx::Rect(300, 300, 100, 100)));
l1->Add(l2.get());
l1->Add(l4.get());
l2->Add(l3.get());
GetCompositor()->SetRootLayer(l1.get());
WaitForDraw();
DrawTreeLayerDelegate d2(l2->bounds());
l2->set_delegate(&d2);
DrawTreeLayerDelegate d3(l3->bounds());
l3->set_delegate(&d3);
l2->SchedulePaint(gfx::Rect(5, 5, 5, 5));
l3->SchedulePaint(gfx::Rect(5, 5, 5, 5));
WaitForDraw();
// |d2| should not have received a paint notification since it has no texture.
EXPECT_FALSE(d2.painted());
// |d3| should have received a paint notification.
EXPECT_TRUE(d3.painted());
}
class LayerWithNullDelegateTest : public LayerWithDelegateTest {
public:
LayerWithNullDelegateTest() {}
~LayerWithNullDelegateTest() override {}
void SetUp() override {
LayerWithDelegateTest::SetUp();
default_layer_delegate_.reset(new NullLayerDelegate());
}
Layer* CreateLayer(LayerType type) override {
Layer* layer = new Layer(type);
layer->set_delegate(default_layer_delegate_.get());
return layer;
}
Layer* CreateTextureRootLayer(const gfx::Rect& bounds) {
Layer* layer = CreateTextureLayer(bounds);
compositor()->SetRootLayer(layer);
return layer;
}
Layer* CreateTextureLayer(const gfx::Rect& bounds) {
Layer* layer = CreateLayer(LAYER_TEXTURED);
layer->SetBounds(bounds);
return layer;
}
Layer* CreateNoTextureLayer(const gfx::Rect& bounds) override {
Layer* layer = CreateLayer(LAYER_NOT_DRAWN);
layer->SetBounds(bounds);
return layer;
}
private:
std::unique_ptr<NullLayerDelegate> default_layer_delegate_;
DISALLOW_COPY_AND_ASSIGN(LayerWithNullDelegateTest);
};
TEST_F(LayerWithNullDelegateTest, EscapedDebugNames) {
std::unique_ptr<Layer> layer(CreateLayer(LAYER_NOT_DRAWN));
std::string name = "\"\'\\/\b\f\n\r\t\n";
layer->set_name(name);
std::unique_ptr<base::trace_event::ConvertableToTraceFormat> debug_info(
layer->TakeDebugInfo(layer->cc_layer_for_testing()));
EXPECT_TRUE(debug_info.get());
std::string json;
debug_info->AppendAsTraceFormat(&json);
base::JSONReader json_reader;
std::unique_ptr<base::Value> debug_info_value(json_reader.ReadToValue(json));
EXPECT_TRUE(debug_info_value);
EXPECT_TRUE(debug_info_value->IsType(base::Value::TYPE_DICTIONARY));
base::DictionaryValue* dictionary = 0;
EXPECT_TRUE(debug_info_value->GetAsDictionary(&dictionary));
std::string roundtrip;
EXPECT_TRUE(dictionary->GetString("layer_name", &roundtrip));
EXPECT_EQ(name, roundtrip);
}
TEST_F(LayerWithNullDelegateTest, SwitchLayerPreservesCCLayerState) {
std::unique_ptr<Layer> l1(CreateLayer(LAYER_SOLID_COLOR));
l1->SetFillsBoundsOpaquely(true);
l1->SetVisible(false);
l1->SetBounds(gfx::Rect(4, 5));
EXPECT_EQ(gfx::Point3F(), l1->cc_layer_for_testing()->transform_origin());
EXPECT_TRUE(l1->cc_layer_for_testing()->DrawsContent());
EXPECT_TRUE(l1->cc_layer_for_testing()->contents_opaque());
EXPECT_TRUE(l1->cc_layer_for_testing()->hide_layer_and_subtree());
EXPECT_EQ(gfx::Size(4, 5), l1->cc_layer_for_testing()->bounds());
cc::Layer* before_layer = l1->cc_layer_for_testing();
bool callback1_run = false;
cc::TextureMailbox mailbox(gpu::Mailbox::Generate(), gpu::SyncToken(), 0);
l1->SetTextureMailbox(mailbox, cc::SingleReleaseCallback::Create(
base::Bind(ReturnMailbox, &callback1_run)),
gfx::Size(10, 10));
EXPECT_NE(before_layer, l1->cc_layer_for_testing());
EXPECT_EQ(gfx::Point3F(), l1->cc_layer_for_testing()->transform_origin());
EXPECT_TRUE(l1->cc_layer_for_testing()->DrawsContent());
EXPECT_TRUE(l1->cc_layer_for_testing()->contents_opaque());
EXPECT_TRUE(l1->cc_layer_for_testing()->hide_layer_and_subtree());
EXPECT_EQ(gfx::Size(4, 5), l1->cc_layer_for_testing()->bounds());
EXPECT_FALSE(callback1_run);
bool callback2_run = false;
mailbox = cc::TextureMailbox(gpu::Mailbox::Generate(), gpu::SyncToken(), 0);
l1->SetTextureMailbox(mailbox, cc::SingleReleaseCallback::Create(
base::Bind(ReturnMailbox, &callback2_run)),
gfx::Size(10, 10));
EXPECT_TRUE(callback1_run);
EXPECT_FALSE(callback2_run);
// Show solid color instead.
l1->SetShowSolidColorContent();
EXPECT_EQ(gfx::Point3F(), l1->cc_layer_for_testing()->transform_origin());
EXPECT_TRUE(l1->cc_layer_for_testing()->DrawsContent());
EXPECT_TRUE(l1->cc_layer_for_testing()->contents_opaque());
EXPECT_TRUE(l1->cc_layer_for_testing()->hide_layer_and_subtree());
EXPECT_EQ(gfx::Size(4, 5), l1->cc_layer_for_testing()->bounds());
EXPECT_TRUE(callback2_run);
before_layer = l1->cc_layer_for_testing();
// Back to a texture, without changing the bounds of the layer or the texture.
bool callback3_run = false;
mailbox = cc::TextureMailbox(gpu::Mailbox::Generate(), gpu::SyncToken(), 0);
l1->SetTextureMailbox(mailbox, cc::SingleReleaseCallback::Create(
base::Bind(ReturnMailbox, &callback3_run)),
gfx::Size(10, 10));
EXPECT_NE(before_layer, l1->cc_layer_for_testing());
EXPECT_EQ(gfx::Point3F(), l1->cc_layer_for_testing()->transform_origin());
EXPECT_TRUE(l1->cc_layer_for_testing()->DrawsContent());
EXPECT_TRUE(l1->cc_layer_for_testing()->contents_opaque());
EXPECT_TRUE(l1->cc_layer_for_testing()->hide_layer_and_subtree());
EXPECT_EQ(gfx::Size(4, 5), l1->cc_layer_for_testing()->bounds());
EXPECT_FALSE(callback3_run);
// Release the on |l1| mailbox to clean up the test.
l1->SetShowSolidColorContent();
}
// Various visibile/drawn assertions.
TEST_F(LayerWithNullDelegateTest, Visibility) {
std::unique_ptr<Layer> l1(new Layer(LAYER_TEXTURED));
std::unique_ptr<Layer> l2(new Layer(LAYER_TEXTURED));
std::unique_ptr<Layer> l3(new Layer(LAYER_TEXTURED));
l1->Add(l2.get());
l2->Add(l3.get());
NullLayerDelegate delegate;
l1->set_delegate(&delegate);
l2->set_delegate(&delegate);
l3->set_delegate(&delegate);
// Layers should initially be drawn.
EXPECT_TRUE(l1->IsDrawn());
EXPECT_TRUE(l2->IsDrawn());
EXPECT_TRUE(l3->IsDrawn());
EXPECT_FALSE(l1->cc_layer_for_testing()->hide_layer_and_subtree());
EXPECT_FALSE(l2->cc_layer_for_testing()->hide_layer_and_subtree());
EXPECT_FALSE(l3->cc_layer_for_testing()->hide_layer_and_subtree());
compositor()->SetRootLayer(l1.get());
Draw();
l1->SetVisible(false);
EXPECT_FALSE(l1->IsDrawn());
EXPECT_FALSE(l2->IsDrawn());
EXPECT_FALSE(l3->IsDrawn());
EXPECT_TRUE(l1->cc_layer_for_testing()->hide_layer_and_subtree());
EXPECT_FALSE(l2->cc_layer_for_testing()->hide_layer_and_subtree());
EXPECT_FALSE(l3->cc_layer_for_testing()->hide_layer_and_subtree());
l3->SetVisible(false);
EXPECT_FALSE(l1->IsDrawn());
EXPECT_FALSE(l2->IsDrawn());
EXPECT_FALSE(l3->IsDrawn());
EXPECT_TRUE(l1->cc_layer_for_testing()->hide_layer_and_subtree());
EXPECT_FALSE(l2->cc_layer_for_testing()->hide_layer_and_subtree());
EXPECT_TRUE(l3->cc_layer_for_testing()->hide_layer_and_subtree());
l1->SetVisible(true);
EXPECT_TRUE(l1->IsDrawn());
EXPECT_TRUE(l2->IsDrawn());
EXPECT_FALSE(l3->IsDrawn());
EXPECT_FALSE(l1->cc_layer_for_testing()->hide_layer_and_subtree());
EXPECT_FALSE(l2->cc_layer_for_testing()->hide_layer_and_subtree());
EXPECT_TRUE(l3->cc_layer_for_testing()->hide_layer_and_subtree());
}
// Checks that stacking-related methods behave as advertised.
TEST_F(LayerWithNullDelegateTest, Stacking) {
std::unique_ptr<Layer> root(new Layer(LAYER_NOT_DRAWN));
std::unique_ptr<Layer> l1(new Layer(LAYER_TEXTURED));
std::unique_ptr<Layer> l2(new Layer(LAYER_TEXTURED));
std::unique_ptr<Layer> l3(new Layer(LAYER_TEXTURED));
l1->set_name("1");
l2->set_name("2");
l3->set_name("3");
root->Add(l3.get());
root->Add(l2.get());
root->Add(l1.get());
// Layers' children are stored in bottom-to-top order.
EXPECT_EQ("3 2 1", test::ChildLayerNamesAsString(*root.get()));
root->StackAtTop(l3.get());
EXPECT_EQ("2 1 3", test::ChildLayerNamesAsString(*root.get()));
root->StackAtTop(l1.get());
EXPECT_EQ("2 3 1", test::ChildLayerNamesAsString(*root.get()));
root->StackAtTop(l1.get());
EXPECT_EQ("2 3 1", test::ChildLayerNamesAsString(*root.get()));
root->StackAbove(l2.get(), l3.get());
EXPECT_EQ("3 2 1", test::ChildLayerNamesAsString(*root.get()));
root->StackAbove(l1.get(), l3.get());
EXPECT_EQ("3 1 2", test::ChildLayerNamesAsString(*root.get()));
root->StackAbove(l2.get(), l1.get());
EXPECT_EQ("3 1 2", test::ChildLayerNamesAsString(*root.get()));
root->StackAtBottom(l2.get());
EXPECT_EQ("2 3 1", test::ChildLayerNamesAsString(*root.get()));
root->StackAtBottom(l3.get());
EXPECT_EQ("3 2 1", test::ChildLayerNamesAsString(*root.get()));
root->StackAtBottom(l3.get());
EXPECT_EQ("3 2 1", test::ChildLayerNamesAsString(*root.get()));
root->StackBelow(l2.get(), l3.get());
EXPECT_EQ("2 3 1", test::ChildLayerNamesAsString(*root.get()));
root->StackBelow(l1.get(), l3.get());
EXPECT_EQ("2 1 3", test::ChildLayerNamesAsString(*root.get()));
root->StackBelow(l3.get(), l2.get());
EXPECT_EQ("3 2 1", test::ChildLayerNamesAsString(*root.get()));
root->StackBelow(l3.get(), l2.get());
EXPECT_EQ("3 2 1", test::ChildLayerNamesAsString(*root.get()));
root->StackBelow(l3.get(), l1.get());
EXPECT_EQ("2 3 1", test::ChildLayerNamesAsString(*root.get()));
}
// Verifies SetBounds triggers the appropriate painting/drawing.
TEST_F(LayerWithNullDelegateTest, SetBoundsSchedulesPaint) {
std::unique_ptr<Layer> l1(CreateTextureLayer(gfx::Rect(0, 0, 200, 200)));
compositor()->SetRootLayer(l1.get());
Draw();
l1->SetBounds(gfx::Rect(5, 5, 200, 200));
// The CompositorDelegate (us) should have been told to draw for a move.
WaitForDraw();
l1->SetBounds(gfx::Rect(5, 5, 100, 100));
// The CompositorDelegate (us) should have been told to draw for a resize.
WaitForDraw();
}
static void EmptyReleaseCallback(const gpu::SyncToken& sync_token,
bool is_lost) {}
// Checks that the damage rect for a TextureLayer is empty after a commit.
TEST_F(LayerWithNullDelegateTest, EmptyDamagedRect) {
std::unique_ptr<Layer> root(CreateLayer(LAYER_SOLID_COLOR));
cc::TextureMailbox mailbox(gpu::Mailbox::Generate(), gpu::SyncToken(),
GL_TEXTURE_2D);
root->SetTextureMailbox(mailbox, cc::SingleReleaseCallback::Create(
base::Bind(EmptyReleaseCallback)),
gfx::Size(10, 10));
compositor()->SetRootLayer(root.get());
root->SetBounds(gfx::Rect(0, 0, 10, 10));
root->SetVisible(true);
WaitForCommit();
gfx::Rect damaged_rect(0, 0, 5, 5);
root->SchedulePaint(damaged_rect);
EXPECT_EQ(damaged_rect, root->damaged_region_for_testing().bounds());
WaitForCommit();
EXPECT_TRUE(root->damaged_region_for_testing().IsEmpty());
compositor()->SetRootLayer(nullptr);
root.reset();
WaitForCommit();
}
void ExpectRgba(int x, int y, SkColor expected_color, SkColor actual_color) {
EXPECT_EQ(expected_color, actual_color)
<< "Pixel error at x=" << x << " y=" << y << "; "
<< "actual RGBA=("
<< SkColorGetR(actual_color) << ","
<< SkColorGetG(actual_color) << ","
<< SkColorGetB(actual_color) << ","
<< SkColorGetA(actual_color) << "); "
<< "expected RGBA=("
<< SkColorGetR(expected_color) << ","
<< SkColorGetG(expected_color) << ","
<< SkColorGetB(expected_color) << ","
<< SkColorGetA(expected_color) << ")";
}
// Checks that pixels are actually drawn to the screen with a read back.
TEST_F(LayerWithRealCompositorTest, DrawPixels) {
gfx::Size viewport_size = GetCompositor()->size();
// The window should be some non-trivial size but may not be exactly
// 500x500 on all platforms/bots.
EXPECT_GE(viewport_size.width(), 200);
EXPECT_GE(viewport_size.height(), 200);
int blue_height = 10;
std::unique_ptr<Layer> layer(
CreateColorLayer(SK_ColorRED, gfx::Rect(viewport_size)));
std::unique_ptr<Layer> layer2(CreateColorLayer(
SK_ColorBLUE, gfx::Rect(0, 0, viewport_size.width(), blue_height)));
layer->Add(layer2.get());
DrawTree(layer.get());
SkBitmap bitmap;
ReadPixels(&bitmap, gfx::Rect(viewport_size));
ASSERT_FALSE(bitmap.empty());
SkAutoLockPixels lock(bitmap);
for (int x = 0; x < viewport_size.width(); x++) {
for (int y = 0; y < viewport_size.height(); y++) {
SkColor actual_color = bitmap.getColor(x, y);
SkColor expected_color = y < blue_height ? SK_ColorBLUE : SK_ColorRED;
ExpectRgba(x, y, expected_color, actual_color);
}
}
}
// Checks that drawing a layer with transparent pixels is blended correctly
// with the lower layer.
TEST_F(LayerWithRealCompositorTest, DrawAlphaBlendedPixels) {
gfx::Size viewport_size = GetCompositor()->size();
int test_size = 200;
EXPECT_GE(viewport_size.width(), test_size);
EXPECT_GE(viewport_size.height(), test_size);
// Blue with a wee bit of transparency.
SkColor blue_with_alpha = SkColorSetARGBInline(40, 10, 20, 200);
SkColor blend_color = SkColorSetARGBInline(255, 216, 3, 32);
std::unique_ptr<Layer> background_layer(
CreateColorLayer(SK_ColorRED, gfx::Rect(viewport_size)));
std::unique_ptr<Layer> foreground_layer(
CreateColorLayer(blue_with_alpha, gfx::Rect(viewport_size)));
// This must be set to false for layers with alpha to be blended correctly.
foreground_layer->SetFillsBoundsOpaquely(false);
background_layer->Add(foreground_layer.get());
DrawTree(background_layer.get());
SkBitmap bitmap;
ReadPixels(&bitmap, gfx::Rect(viewport_size));
ASSERT_FALSE(bitmap.empty());
SkAutoLockPixels lock(bitmap);
for (int x = 0; x < test_size; x++) {
for (int y = 0; y < test_size; y++) {
SkColor actual_color = bitmap.getColor(x, y);
ExpectRgba(x, y, blend_color, actual_color);
}
}
}
// Checks that using the AlphaShape filter applied to a layer with
// transparency, alpha-blends properly with the layer below.
TEST_F(LayerWithRealCompositorTest, DrawAlphaThresholdFilterPixels) {
gfx::Size viewport_size = GetCompositor()->size();
int test_size = 200;
EXPECT_GE(viewport_size.width(), test_size);
EXPECT_GE(viewport_size.height(), test_size);
int blue_height = 10;
SkColor blue_with_alpha = SkColorSetARGBInline(40, 0, 0, 255);
SkColor blend_color = SkColorSetARGBInline(255, 215, 0, 40);
std::unique_ptr<Layer> background_layer(
CreateColorLayer(SK_ColorRED, gfx::Rect(viewport_size)));
std::unique_ptr<Layer> foreground_layer(
CreateColorLayer(blue_with_alpha, gfx::Rect(viewport_size)));
// Add a shape to restrict the visible part of the layer.
SkRegion shape;
shape.setRect(0, 0, viewport_size.width(), blue_height);
foreground_layer->SetAlphaShape(base::WrapUnique(new SkRegion(shape)));
foreground_layer->SetFillsBoundsOpaquely(false);
background_layer->Add(foreground_layer.get());
DrawTree(background_layer.get());
SkBitmap bitmap;
ReadPixels(&bitmap, gfx::Rect(viewport_size));
ASSERT_FALSE(bitmap.empty());
SkAutoLockPixels lock(bitmap);
for (int x = 0; x < test_size; x++) {
for (int y = 0; y < test_size; y++) {
SkColor actual_color = bitmap.getColor(x, y);
ExpectRgba(x, y, actual_color,
y < blue_height ? blend_color : SK_ColorRED);
}
}
}
// Checks the logic around Compositor::SetRootLayer and Layer::SetCompositor.
TEST_F(LayerWithRealCompositorTest, SetRootLayer) {
Compositor* compositor = GetCompositor();
std::unique_ptr<Layer> l1(
CreateColorLayer(SK_ColorRED, gfx::Rect(20, 20, 400, 400)));
std::unique_ptr<Layer> l2(
CreateColorLayer(SK_ColorBLUE, gfx::Rect(10, 10, 350, 350)));
EXPECT_EQ(NULL, l1->GetCompositor());
EXPECT_EQ(NULL, l2->GetCompositor());
compositor->SetRootLayer(l1.get());
EXPECT_EQ(compositor, l1->GetCompositor());
l1->Add(l2.get());
EXPECT_EQ(compositor, l2->GetCompositor());
l1->Remove(l2.get());
EXPECT_EQ(NULL, l2->GetCompositor());
l1->Add(l2.get());
EXPECT_EQ(compositor, l2->GetCompositor());
compositor->SetRootLayer(NULL);
EXPECT_EQ(NULL, l1->GetCompositor());
EXPECT_EQ(NULL, l2->GetCompositor());
}
// Checks that compositor observers are notified when:
// - DrawTree is called,
// - After ScheduleDraw is called, or
// - Whenever SetBounds, SetOpacity or SetTransform are called.
// TODO(vollick): could be reorganized into compositor_unittest.cc
TEST_F(LayerWithRealCompositorTest, CompositorObservers) {
std::unique_ptr<Layer> l1(
CreateColorLayer(SK_ColorRED, gfx::Rect(20, 20, 400, 400)));
std::unique_ptr<Layer> l2(
CreateColorLayer(SK_ColorBLUE, gfx::Rect(10, 10, 350, 350)));
l1->Add(l2.get());
TestCompositorObserver observer;
GetCompositor()->AddObserver(&observer);
// Explicitly called DrawTree should cause the observers to be notified.
// NOTE: this call to DrawTree sets l1 to be the compositor's root layer.
DrawTree(l1.get());
EXPECT_TRUE(observer.notified());
// ScheduleDraw without any visible change should cause a commit.
observer.Reset();
l1->ScheduleDraw();
WaitForCommit();
EXPECT_TRUE(observer.committed());
// Moving, but not resizing, a layer should alert the observers.
observer.Reset();
l2->SetBounds(gfx::Rect(0, 0, 350, 350));
WaitForSwap();
EXPECT_TRUE(observer.notified());
// So should resizing a layer.
observer.Reset();
l2->SetBounds(gfx::Rect(0, 0, 400, 400));
WaitForSwap();
EXPECT_TRUE(observer.notified());
// Opacity changes should alert the observers.
observer.Reset();
l2->SetOpacity(0.5f);
WaitForSwap();
EXPECT_TRUE(observer.notified());
// So should setting the opacity back.
observer.Reset();
l2->SetOpacity(1.0f);
WaitForSwap();
EXPECT_TRUE(observer.notified());
// Setting the transform of a layer should alert the observers.
observer.Reset();
gfx::Transform transform;
transform.Translate(200.0, 200.0);
transform.Rotate(90.0);
transform.Translate(-200.0, -200.0);
l2->SetTransform(transform);
WaitForSwap();
EXPECT_TRUE(observer.notified());
// A change resulting in an aborted swap buffer should alert the observer
// and also signal an abort.
observer.Reset();
l2->SetOpacity(0.1f);
GetCompositor()->DidAbortSwapBuffers();
WaitForSwap();
EXPECT_TRUE(observer.notified());
EXPECT_TRUE(observer.aborted());
GetCompositor()->RemoveObserver(&observer);
// Opacity changes should no longer alert the removed observer.
observer.Reset();
l2->SetOpacity(0.5f);
WaitForSwap();
EXPECT_FALSE(observer.notified());
}
// Checks that modifying the hierarchy correctly affects final composite.
TEST_F(LayerWithRealCompositorTest, ModifyHierarchy) {
GetCompositor()->SetScaleAndSize(1.0f, gfx::Size(50, 50));
// l0
// +-l11
// | +-l21
// +-l12
std::unique_ptr<Layer> l0(
CreateColorLayer(SK_ColorRED, gfx::Rect(0, 0, 50, 50)));
std::unique_ptr<Layer> l11(
CreateColorLayer(SK_ColorGREEN, gfx::Rect(0, 0, 25, 25)));
std::unique_ptr<Layer> l21(
CreateColorLayer(SK_ColorMAGENTA, gfx::Rect(0, 0, 15, 15)));
std::unique_ptr<Layer> l12(
CreateColorLayer(SK_ColorBLUE, gfx::Rect(10, 10, 25, 25)));
base::FilePath ref_img1 =
test_data_directory().AppendASCII("ModifyHierarchy1.png");
base::FilePath ref_img2 =
test_data_directory().AppendASCII("ModifyHierarchy2.png");
SkBitmap bitmap;
l0->Add(l11.get());
l11->Add(l21.get());
l0->Add(l12.get());
DrawTree(l0.get());
ReadPixels(&bitmap);
ASSERT_FALSE(bitmap.empty());
// WritePNGFile(bitmap, ref_img1);
EXPECT_TRUE(MatchesPNGFile(bitmap, ref_img1, cc::ExactPixelComparator(true)));
l0->StackAtTop(l11.get());
DrawTree(l0.get());
ReadPixels(&bitmap);
ASSERT_FALSE(bitmap.empty());
// WritePNGFile(bitmap, ref_img2);
EXPECT_TRUE(MatchesPNGFile(bitmap, ref_img2, cc::ExactPixelComparator(true)));
// should restore to original configuration
l0->StackAbove(l12.get(), l11.get());
DrawTree(l0.get());
ReadPixels(&bitmap);
ASSERT_FALSE(bitmap.empty());
EXPECT_TRUE(MatchesPNGFile(bitmap, ref_img1, cc::ExactPixelComparator(true)));
// l11 back to front
l0->StackAtTop(l11.get());
DrawTree(l0.get());
ReadPixels(&bitmap);
ASSERT_FALSE(bitmap.empty());
EXPECT_TRUE(MatchesPNGFile(bitmap, ref_img2, cc::ExactPixelComparator(true)));
// should restore to original configuration
l0->StackAbove(l12.get(), l11.get());
DrawTree(l0.get());
ReadPixels(&bitmap);
ASSERT_FALSE(bitmap.empty());
EXPECT_TRUE(MatchesPNGFile(bitmap, ref_img1, cc::ExactPixelComparator(true)));
// l11 back to front
l0->StackAbove(l11.get(), l12.get());
DrawTree(l0.get());
ReadPixels(&bitmap);
ASSERT_FALSE(bitmap.empty());
EXPECT_TRUE(MatchesPNGFile(bitmap, ref_img2, cc::ExactPixelComparator(true)));
}
// It is really hard to write pixel test on text rendering,
// due to different font appearance.
// So we choose to check result only on Windows.
// See https://codereview.chromium.org/1634103003/#msg41
#if defined(OS_WIN)
TEST_F(LayerWithRealCompositorTest, CanvasDrawStringRectWithHalo) {
gfx::Size size(50, 50);
GetCompositor()->SetScaleAndSize(1.0f, size);
DrawStringLayerDelegate delegate(SK_ColorBLUE, SK_ColorWHITE,
DrawStringLayerDelegate::STRING_WITH_HALO,
size);
std::unique_ptr<Layer> layer(
CreateDrawStringLayer(gfx::Rect(size), &delegate));
DrawTree(layer.get());
SkBitmap bitmap;
ReadPixels(&bitmap);
ASSERT_FALSE(bitmap.empty());
base::FilePath ref_img =
test_data_directory().AppendASCII("string_with_halo.png");
// WritePNGFile(bitmap, ref_img, true);
float percentage_pixels_large_error = 1.0f;
float percentage_pixels_small_error = 0.0f;
float average_error_allowed_in_bad_pixels = 1.f;
int large_error_allowed = 1;
int small_error_allowed = 0;
EXPECT_TRUE(MatchesPNGFile(bitmap, ref_img,
cc::FuzzyPixelComparator(
true,
percentage_pixels_large_error,
percentage_pixels_small_error,
average_error_allowed_in_bad_pixels,
large_error_allowed,
small_error_allowed)));
}
TEST_F(LayerWithRealCompositorTest, CanvasDrawFadedString) {
gfx::Size size(50, 50);
GetCompositor()->SetScaleAndSize(1.0f, size);
DrawStringLayerDelegate delegate(SK_ColorBLUE, SK_ColorWHITE,
DrawStringLayerDelegate::STRING_FADED,
size);
std::unique_ptr<Layer> layer(
CreateDrawStringLayer(gfx::Rect(size), &delegate));
DrawTree(layer.get());
SkBitmap bitmap;
ReadPixels(&bitmap);
ASSERT_FALSE(bitmap.empty());
base::FilePath ref_img =
test_data_directory().AppendASCII("string_faded.png");
// WritePNGFile(bitmap, ref_img, true);
float percentage_pixels_large_error = 8.0f; // 200px / (50*50)
float percentage_pixels_small_error = 0.0f;
float average_error_allowed_in_bad_pixels = 80.f;
int large_error_allowed = 255;
int small_error_allowed = 0;
EXPECT_TRUE(MatchesPNGFile(bitmap, ref_img,
cc::FuzzyPixelComparator(
true,
percentage_pixels_large_error,
percentage_pixels_small_error,
average_error_allowed_in_bad_pixels,
large_error_allowed,
small_error_allowed)));
}
TEST_F(LayerWithRealCompositorTest, CanvasDrawStringRectWithShadows) {
gfx::Size size(50, 50);
GetCompositor()->SetScaleAndSize(1.0f, size);
DrawStringLayerDelegate delegate(
SK_ColorBLUE, SK_ColorWHITE,
DrawStringLayerDelegate::STRING_WITH_SHADOWS,
size);
std::unique_ptr<Layer> layer(
CreateDrawStringLayer(gfx::Rect(size), &delegate));
DrawTree(layer.get());
SkBitmap bitmap;
ReadPixels(&bitmap);
ASSERT_FALSE(bitmap.empty());
base::FilePath ref_img =
test_data_directory().AppendASCII("string_with_shadows.png");
// WritePNGFile(bitmap, ref_img, true);
float percentage_pixels_large_error = 7.4f; // 185px / (50*50)
float percentage_pixels_small_error = 0.0f;
float average_error_allowed_in_bad_pixels = 60.f;
int large_error_allowed = 246;
int small_error_allowed = 0;
EXPECT_TRUE(MatchesPNGFile(bitmap, ref_img,
cc::FuzzyPixelComparator(
true,
percentage_pixels_large_error,
percentage_pixels_small_error,
average_error_allowed_in_bad_pixels,
large_error_allowed,
small_error_allowed)));
}
#endif // defined(OS_WIN)
// Opacity is rendered correctly.
// Checks that modifying the hierarchy correctly affects final composite.
TEST_F(LayerWithRealCompositorTest, Opacity) {
GetCompositor()->SetScaleAndSize(1.0f, gfx::Size(50, 50));
// l0
// +-l11
std::unique_ptr<Layer> l0(
CreateColorLayer(SK_ColorRED, gfx::Rect(0, 0, 50, 50)));
std::unique_ptr<Layer> l11(
CreateColorLayer(SK_ColorGREEN, gfx::Rect(0, 0, 25, 25)));
base::FilePath ref_img = test_data_directory().AppendASCII("Opacity.png");
l11->SetOpacity(0.75);
l0->Add(l11.get());
DrawTree(l0.get());
SkBitmap bitmap;
ReadPixels(&bitmap);
ASSERT_FALSE(bitmap.empty());
// WritePNGFile(bitmap, ref_img);
EXPECT_TRUE(MatchesPNGFile(bitmap, ref_img, cc::ExactPixelComparator(true)));
}
namespace {
class SchedulePaintLayerDelegate : public LayerDelegate {
public:
SchedulePaintLayerDelegate() : paint_count_(0), layer_(NULL) {}
~SchedulePaintLayerDelegate() override {}
void set_layer(Layer* layer) {
layer_ = layer;
layer_->set_delegate(this);
}
void SetSchedulePaintRect(const gfx::Rect& rect) {
schedule_paint_rect_ = rect;
}
int GetPaintCountAndClear() {
int value = paint_count_;
paint_count_ = 0;
return value;
}
const gfx::Rect& last_clip_rect() const { return last_clip_rect_; }
private:
// Overridden from LayerDelegate:
void OnPaintLayer(const ui::PaintContext& context) override {
paint_count_++;
if (!schedule_paint_rect_.IsEmpty()) {
layer_->SchedulePaint(schedule_paint_rect_);
schedule_paint_rect_ = gfx::Rect();
}
last_clip_rect_ = context.InvalidationForTesting();
}
void OnDelegatedFrameDamage(const gfx::Rect& damage_rect_in_dip) override {}
void OnDeviceScaleFactorChanged(float device_scale_factor) override {}
int paint_count_;
Layer* layer_;
gfx::Rect schedule_paint_rect_;
gfx::Rect last_clip_rect_;
DISALLOW_COPY_AND_ASSIGN(SchedulePaintLayerDelegate);
};
} // namespace
// Verifies that if SchedulePaint is invoked during painting the layer is still
// marked dirty.
TEST_F(LayerWithDelegateTest, SchedulePaintFromOnPaintLayer) {
std::unique_ptr<Layer> root(
CreateColorLayer(SK_ColorRED, gfx::Rect(0, 0, 500, 500)));
SchedulePaintLayerDelegate child_delegate;
std::unique_ptr<Layer> child(
CreateColorLayer(SK_ColorBLUE, gfx::Rect(0, 0, 200, 200)));
child_delegate.set_layer(child.get());
root->Add(child.get());
SchedulePaintForLayer(root.get());
DrawTree(root.get());
child->SchedulePaint(gfx::Rect(0, 0, 20, 20));
EXPECT_EQ(1, child_delegate.GetPaintCountAndClear());
// Set a rect so that when OnPaintLayer() is invoked SchedulePaint is invoked
// again.
child_delegate.SetSchedulePaintRect(gfx::Rect(10, 10, 30, 30));
WaitForCommit();
EXPECT_EQ(1, child_delegate.GetPaintCountAndClear());
// Because SchedulePaint() was invoked from OnPaintLayer() |child| should
// still need to be painted.
WaitForCommit();
EXPECT_EQ(1, child_delegate.GetPaintCountAndClear());
EXPECT_TRUE(child_delegate.last_clip_rect().Contains(
gfx::Rect(10, 10, 30, 30)));
}
TEST_F(LayerWithRealCompositorTest, ScaleUpDown) {
std::unique_ptr<Layer> root(
CreateColorLayer(SK_ColorWHITE, gfx::Rect(10, 20, 200, 220)));
TestLayerDelegate root_delegate;
root_delegate.AddColor(SK_ColorWHITE);
root->set_delegate(&root_delegate);
root_delegate.set_layer_bounds(root->bounds());
std::unique_ptr<Layer> l1(
CreateColorLayer(SK_ColorWHITE, gfx::Rect(10, 20, 140, 180)));
TestLayerDelegate l1_delegate;
l1_delegate.AddColor(SK_ColorWHITE);
l1->set_delegate(&l1_delegate);
l1_delegate.set_layer_bounds(l1->bounds());
GetCompositor()->SetScaleAndSize(1.0f, gfx::Size(500, 500));
GetCompositor()->SetRootLayer(root.get());
root->Add(l1.get());
WaitForDraw();
EXPECT_EQ("10,20 200x220", root->bounds().ToString());
EXPECT_EQ("10,20 140x180", l1->bounds().ToString());
gfx::Size cc_bounds_size = root->cc_layer_for_testing()->bounds();
EXPECT_EQ("200x220", cc_bounds_size.ToString());
cc_bounds_size = l1->cc_layer_for_testing()->bounds();
EXPECT_EQ("140x180", cc_bounds_size.ToString());
// No scale change, so no scale notification.
EXPECT_EQ(0.0f, root_delegate.device_scale_factor());
EXPECT_EQ(0.0f, l1_delegate.device_scale_factor());
// Scale up to 2.0. Changing scale doesn't change the bounds in DIP.
GetCompositor()->SetScaleAndSize(2.0f, gfx::Size(500, 500));
EXPECT_EQ("10,20 200x220", root->bounds().ToString());
EXPECT_EQ("10,20 140x180", l1->bounds().ToString());
// CC layer should still match the UI layer bounds.
cc_bounds_size = root->cc_layer_for_testing()->bounds();
EXPECT_EQ("200x220", cc_bounds_size.ToString());
cc_bounds_size = l1->cc_layer_for_testing()->bounds();
EXPECT_EQ("140x180", cc_bounds_size.ToString());
// New scale factor must have been notified. Make sure painting happens at
// right scale.
EXPECT_EQ(2.0f, root_delegate.device_scale_factor());
EXPECT_EQ(2.0f, l1_delegate.device_scale_factor());
// Scale down back to 1.0f.
GetCompositor()->SetScaleAndSize(1.0f, gfx::Size(500, 500));
EXPECT_EQ("10,20 200x220", root->bounds().ToString());
EXPECT_EQ("10,20 140x180", l1->bounds().ToString());
// CC layer should still match the UI layer bounds.
cc_bounds_size = root->cc_layer_for_testing()->bounds();
EXPECT_EQ("200x220", cc_bounds_size.ToString());
cc_bounds_size = l1->cc_layer_for_testing()->bounds();
EXPECT_EQ("140x180", cc_bounds_size.ToString());
// New scale factor must have been notified. Make sure painting happens at
// right scale.
EXPECT_EQ(1.0f, root_delegate.device_scale_factor());
EXPECT_EQ(1.0f, l1_delegate.device_scale_factor());
root_delegate.reset();
l1_delegate.reset();
// Just changing the size shouldn't notify the scale change nor
// trigger repaint.
GetCompositor()->SetScaleAndSize(1.0f, gfx::Size(1000, 1000));
// No scale change, so no scale notification.
EXPECT_EQ(0.0f, root_delegate.device_scale_factor());
EXPECT_EQ(0.0f, l1_delegate.device_scale_factor());
}
TEST_F(LayerWithRealCompositorTest, ScaleReparent) {
std::unique_ptr<Layer> root(
CreateColorLayer(SK_ColorWHITE, gfx::Rect(10, 20, 200, 220)));
std::unique_ptr<Layer> l1(
CreateColorLayer(SK_ColorWHITE, gfx::Rect(10, 20, 140, 180)));
TestLayerDelegate l1_delegate;
l1_delegate.AddColor(SK_ColorWHITE);
l1->set_delegate(&l1_delegate);
l1_delegate.set_layer_bounds(l1->bounds());
GetCompositor()->SetScaleAndSize(1.0f, gfx::Size(500, 500));
GetCompositor()->SetRootLayer(root.get());
root->Add(l1.get());
EXPECT_EQ("10,20 140x180", l1->bounds().ToString());
gfx::Size cc_bounds_size = l1->cc_layer_for_testing()->bounds();
EXPECT_EQ("140x180", cc_bounds_size.ToString());
EXPECT_EQ(0.0f, l1_delegate.device_scale_factor());
// Remove l1 from root and change the scale.
root->Remove(l1.get());
EXPECT_EQ(NULL, l1->parent());
EXPECT_EQ(NULL, l1->GetCompositor());
GetCompositor()->SetScaleAndSize(2.0f, gfx::Size(500, 500));
// Sanity check on root and l1.
EXPECT_EQ("10,20 200x220", root->bounds().ToString());
cc_bounds_size = l1->cc_layer_for_testing()->bounds();
EXPECT_EQ("140x180", cc_bounds_size.ToString());
root->Add(l1.get());
EXPECT_EQ("10,20 140x180", l1->bounds().ToString());
cc_bounds_size = l1->cc_layer_for_testing()->bounds();
EXPECT_EQ("140x180", cc_bounds_size.ToString());
EXPECT_EQ(2.0f, l1_delegate.device_scale_factor());
}
// Verifies that when changing bounds on a layer that is invisible, and then
// made visible, the right thing happens:
// - if just a move, then no painting should happen.
// - if a resize, the layer should be repainted.
TEST_F(LayerWithDelegateTest, SetBoundsWhenInvisible) {
std::unique_ptr<Layer> root(
CreateNoTextureLayer(gfx::Rect(0, 0, 1000, 1000)));
std::unique_ptr<Layer> child(CreateLayer(LAYER_TEXTURED));
child->SetBounds(gfx::Rect(0, 0, 500, 500));
DrawTreeLayerDelegate delegate(child->bounds());
child->set_delegate(&delegate);
root->Add(child.get());
// Paint once for initial damage.
child->SetVisible(true);
DrawTree(root.get());
// Reset into invisible state.
child->SetVisible(false);
DrawTree(root.get());
delegate.Reset();
// Move layer.
child->SetBounds(gfx::Rect(200, 200, 500, 500));
child->SetVisible(true);
DrawTree(root.get());
EXPECT_FALSE(delegate.painted());
// Reset into invisible state.
child->SetVisible(false);
DrawTree(root.get());
delegate.Reset();
// Resize layer.
child->SetBounds(gfx::Rect(200, 200, 400, 400));
child->SetVisible(true);
DrawTree(root.get());
EXPECT_TRUE(delegate.painted());
}
namespace {
void FakeSatisfyCallback(const cc::SurfaceSequence&) {}
void FakeRequireCallback(const cc::SurfaceId&, const cc::SurfaceSequence&) {}
} // namespace
TEST_F(LayerWithDelegateTest, ExternalContent) {
std::unique_ptr<Layer> root(
CreateNoTextureLayer(gfx::Rect(0, 0, 1000, 1000)));
std::unique_ptr<Layer> child(CreateLayer(LAYER_SOLID_COLOR));
child->SetBounds(gfx::Rect(0, 0, 10, 10));
child->SetVisible(true);
root->Add(child.get());
// The layer is already showing solid color content, so the cc layer won't
// change.
scoped_refptr<cc::Layer> before = child->cc_layer_for_testing();
child->SetShowSolidColorContent();
EXPECT_TRUE(child->cc_layer_for_testing());
EXPECT_EQ(before.get(), child->cc_layer_for_testing());
// Showing surface content changes the underlying cc layer.
before = child->cc_layer_for_testing();
child->SetShowSurface(cc::SurfaceId(), base::Bind(&FakeSatisfyCallback),
base::Bind(&FakeRequireCallback), gfx::Size(10, 10),
1.0, gfx::Size(10, 10));
EXPECT_TRUE(child->cc_layer_for_testing());
EXPECT_NE(before.get(), child->cc_layer_for_testing());
// Changing to painted content should change the underlying cc layer.
before = child->cc_layer_for_testing();
child->SetShowSolidColorContent();
EXPECT_TRUE(child->cc_layer_for_testing());
EXPECT_NE(before.get(), child->cc_layer_for_testing());
}
// Verifies that layer filters still attached after changing implementation
// layer.
TEST_F(LayerWithDelegateTest, LayerFiltersSurvival) {
std::unique_ptr<Layer> layer(CreateLayer(LAYER_TEXTURED));
layer->SetBounds(gfx::Rect(0, 0, 10, 10));
EXPECT_TRUE(layer->cc_layer_for_testing());
EXPECT_EQ(0u, layer->cc_layer_for_testing()->filters().size());
layer->SetLayerGrayscale(0.5f);
EXPECT_EQ(layer->layer_grayscale(), 0.5f);
EXPECT_EQ(1u, layer->cc_layer_for_testing()->filters().size());
// Showing surface content changes the underlying cc layer.
scoped_refptr<cc::Layer> before = layer->cc_layer_for_testing();
layer->SetShowSurface(cc::SurfaceId(), base::Bind(&FakeSatisfyCallback),
base::Bind(&FakeRequireCallback), gfx::Size(10, 10),
1.0, gfx::Size(10, 10));
EXPECT_EQ(layer->layer_grayscale(), 0.5f);
EXPECT_TRUE(layer->cc_layer_for_testing());
EXPECT_NE(before.get(), layer->cc_layer_for_testing());
EXPECT_EQ(1u, layer->cc_layer_for_testing()->filters().size());
}
// Tests Layer::AddThreadedAnimation and Layer::RemoveThreadedAnimation.
TEST_F(LayerWithRealCompositorTest, AddRemoveThreadedAnimations) {
std::unique_ptr<Layer> root(CreateLayer(LAYER_TEXTURED));
std::unique_ptr<Layer> l1(CreateLayer(LAYER_TEXTURED));
std::unique_ptr<Layer> l2(CreateLayer(LAYER_TEXTURED));
l1->SetAnimator(LayerAnimator::CreateImplicitAnimator());
l2->SetAnimator(LayerAnimator::CreateImplicitAnimator());
auto player1 = l1->GetAnimator()->GetAnimationPlayerForTesting();
auto player2 = l2->GetAnimator()->GetAnimationPlayerForTesting();
EXPECT_FALSE(player1->has_any_animation());
// Trigger a threaded animation.
l1->SetOpacity(0.5f);
EXPECT_TRUE(player1->has_any_animation());
// Ensure we can remove a pending threaded animation.
l1->GetAnimator()->StopAnimating();
EXPECT_FALSE(player1->has_any_animation());
// Trigger another threaded animation.
l1->SetOpacity(0.2f);
EXPECT_TRUE(player1->has_any_animation());
root->Add(l1.get());
GetCompositor()->SetRootLayer(root.get());
// Now l1 is part of a tree.
EXPECT_TRUE(player1->has_any_animation());
l1->SetOpacity(0.1f);
// IMMEDIATELY_SET_NEW_TARGET is a default preemption strategy for conflicting
// animations.
EXPECT_FALSE(player1->has_any_animation());
// Adding a layer to an existing tree.
l2->SetOpacity(0.5f);
EXPECT_TRUE(player2->has_any_animation());
l1->Add(l2.get());
EXPECT_TRUE(player2->has_any_animation());
}
// Tests that in-progress threaded animations complete when a Layer's
// cc::Layer changes.
TEST_F(LayerWithRealCompositorTest, SwitchCCLayerAnimations) {
std::unique_ptr<Layer> root(CreateLayer(LAYER_TEXTURED));
std::unique_ptr<Layer> l1(CreateLayer(LAYER_TEXTURED));
GetCompositor()->SetRootLayer(root.get());
root->Add(l1.get());
l1->SetAnimator(LayerAnimator::CreateImplicitAnimator());
EXPECT_FLOAT_EQ(l1->opacity(), 1.0f);
// Trigger a threaded animation.
l1->SetOpacity(0.5f);
// Change l1's cc::Layer.
l1->SwitchCCLayerForTest();
// Ensure that the opacity animation completed.
EXPECT_FLOAT_EQ(l1->opacity(), 0.5f);
}
// Tests that when a LAYER_SOLID_COLOR has its CC layer switched, that
// opaqueness and color set while not animating, are maintained.
TEST_F(LayerWithRealCompositorTest, SwitchCCLayerSolidColorNotAnimating) {
SkColor transparent = SK_ColorTRANSPARENT;
std::unique_ptr<Layer> root(CreateLayer(LAYER_SOLID_COLOR));
GetCompositor()->SetRootLayer(root.get());
root->SetFillsBoundsOpaquely(false);
root->SetColor(transparent);
EXPECT_FALSE(root->fills_bounds_opaquely());
EXPECT_FALSE(
root->GetAnimator()->IsAnimatingProperty(LayerAnimationElement::COLOR));
EXPECT_EQ(transparent, root->background_color());
EXPECT_EQ(transparent, root->GetTargetColor());
// Changing the underlying layer should not affect targets.
root->SwitchCCLayerForTest();
EXPECT_FALSE(root->fills_bounds_opaquely());
EXPECT_FALSE(
root->GetAnimator()->IsAnimatingProperty(LayerAnimationElement::COLOR));
EXPECT_EQ(transparent, root->background_color());
EXPECT_EQ(transparent, root->GetTargetColor());
}
// Tests that when a LAYER_SOLID_COLOR has its CC layer switched during an
// animation of its opaquness and color, that both the current values, and the
// targets are maintained.
TEST_F(LayerWithRealCompositorTest, SwitchCCLayerSolidColorWhileAnimating) {
SkColor transparent = SK_ColorTRANSPARENT;
std::unique_ptr<Layer> root(CreateLayer(LAYER_SOLID_COLOR));
GetCompositor()->SetRootLayer(root.get());
root->SetColor(SK_ColorBLACK);
EXPECT_TRUE(root->fills_bounds_opaquely());
EXPECT_EQ(SK_ColorBLACK, root->GetTargetColor());
std::unique_ptr<ui::ScopedAnimationDurationScaleMode> long_duration_animation(
new ui::ScopedAnimationDurationScaleMode(
ui::ScopedAnimationDurationScaleMode::SLOW_DURATION));
{
ui::ScopedLayerAnimationSettings animation(root->GetAnimator());
animation.SetTransitionDuration(base::TimeDelta::FromMilliseconds(1000));
root->SetFillsBoundsOpaquely(false);
root->SetColor(transparent);
}
EXPECT_TRUE(root->fills_bounds_opaquely());
EXPECT_TRUE(
root->GetAnimator()->IsAnimatingProperty(LayerAnimationElement::COLOR));
EXPECT_EQ(SK_ColorBLACK, root->background_color());
EXPECT_EQ(transparent, root->GetTargetColor());
// Changing the underlying layer should not affect targets.
root->SwitchCCLayerForTest();
EXPECT_TRUE(root->fills_bounds_opaquely());
EXPECT_TRUE(
root->GetAnimator()->IsAnimatingProperty(LayerAnimationElement::COLOR));
EXPECT_EQ(SK_ColorBLACK, root->background_color());
EXPECT_EQ(transparent, root->GetTargetColor());
// End all animations.
root->GetAnimator()->StopAnimating();
EXPECT_FALSE(root->fills_bounds_opaquely());
EXPECT_FALSE(
root->GetAnimator()->IsAnimatingProperty(LayerAnimationElement::COLOR));
EXPECT_EQ(transparent, root->background_color());
EXPECT_EQ(transparent, root->GetTargetColor());
}
// Tests that the animators in the layer tree is added to the
// animator-collection when the root-layer is set to the compositor.
TEST_F(LayerWithDelegateTest, RootLayerAnimatorsInCompositor) {
std::unique_ptr<Layer> root(CreateLayer(LAYER_SOLID_COLOR));
std::unique_ptr<Layer> child(
CreateColorLayer(SK_ColorRED, gfx::Rect(10, 10)));
child->SetAnimator(LayerAnimator::CreateImplicitAnimator());
child->SetOpacity(0.5f);
root->Add(child.get());
EXPECT_FALSE(compositor()->layer_animator_collection()->HasActiveAnimators());
compositor()->SetRootLayer(root.get());
EXPECT_TRUE(compositor()->layer_animator_collection()->HasActiveAnimators());
}
// Tests that adding/removing a layer adds/removes the animator from its entire
// subtree from the compositor's animator-collection.
TEST_F(LayerWithDelegateTest, AddRemoveLayerUpdatesAnimatorsFromSubtree) {
std::unique_ptr<Layer> root(CreateLayer(LAYER_TEXTURED));
std::unique_ptr<Layer> child(CreateLayer(LAYER_TEXTURED));
std::unique_ptr<Layer> grandchild(
CreateColorLayer(SK_ColorRED, gfx::Rect(10, 10)));
root->Add(child.get());
child->Add(grandchild.get());
compositor()->SetRootLayer(root.get());
grandchild->SetAnimator(LayerAnimator::CreateImplicitAnimator());
grandchild->SetOpacity(0.5f);
EXPECT_TRUE(compositor()->layer_animator_collection()->HasActiveAnimators());
root->Remove(child.get());
EXPECT_FALSE(compositor()->layer_animator_collection()->HasActiveAnimators());
root->Add(child.get());
EXPECT_TRUE(compositor()->layer_animator_collection()->HasActiveAnimators());
}
TEST_F(LayerWithDelegateTest, DestroyingLayerRemovesTheAnimatorFromCollection) {
std::unique_ptr<Layer> root(CreateLayer(LAYER_TEXTURED));
std::unique_ptr<Layer> child(CreateLayer(LAYER_TEXTURED));
root->Add(child.get());
compositor()->SetRootLayer(root.get());
child->SetAnimator(LayerAnimator::CreateImplicitAnimator());
child->SetOpacity(0.5f);
EXPECT_TRUE(compositor()->layer_animator_collection()->HasActiveAnimators());
child.reset();
EXPECT_FALSE(compositor()->layer_animator_collection()->HasActiveAnimators());
}
// A LayerAnimationObserver that removes a child layer from a parent when an
// animation completes.
class LayerRemovingLayerAnimationObserver : public LayerAnimationObserver {
public:
LayerRemovingLayerAnimationObserver(Layer* root, Layer* child)
: root_(root), child_(child) {}
// LayerAnimationObserver:
void OnLayerAnimationEnded(LayerAnimationSequence* sequence) override {
root_->Remove(child_);
}
void OnLayerAnimationAborted(LayerAnimationSequence* sequence) override {
root_->Remove(child_);
}
void OnLayerAnimationScheduled(LayerAnimationSequence* sequence) override {}
private:
Layer* root_;
Layer* child_;
DISALLOW_COPY_AND_ASSIGN(LayerRemovingLayerAnimationObserver);
};
// Verifies that empty LayerAnimators are not left behind when removing child
// Layers that own an empty LayerAnimator. See http://crbug.com/552037.
TEST_F(LayerWithDelegateTest, NonAnimatingAnimatorsAreRemovedFromCollection) {
std::unique_ptr<Layer> root(CreateLayer(LAYER_TEXTURED));
std::unique_ptr<Layer> parent(CreateLayer(LAYER_TEXTURED));
std::unique_ptr<Layer> child(CreateLayer(LAYER_TEXTURED));
root->Add(parent.get());
parent->Add(child.get());
compositor()->SetRootLayer(root.get());
child->SetAnimator(LayerAnimator::CreateDefaultAnimator());
LayerRemovingLayerAnimationObserver observer(root.get(), parent.get());
child->GetAnimator()->AddObserver(&observer);
LayerAnimationElement* element =
ui::LayerAnimationElement::CreateOpacityElement(
0.5f, base::TimeDelta::FromSeconds(1));
LayerAnimationSequence* sequence = new LayerAnimationSequence(element);
child->GetAnimator()->StartAnimation(sequence);
EXPECT_TRUE(compositor()->layer_animator_collection()->HasActiveAnimators());
child->GetAnimator()->StopAnimating();
EXPECT_FALSE(root->Contains(parent.get()));
EXPECT_FALSE(compositor()->layer_animator_collection()->HasActiveAnimators());
}
namespace {
std::string Vector2dFTo100thPercisionString(const gfx::Vector2dF& vector) {
return base::StringPrintf("%.2f %0.2f", vector.x(), vector.y());
}
} // namespace
TEST_F(LayerWithRealCompositorTest, SnapLayerToPixels) {
std::unique_ptr<Layer> root(CreateLayer(LAYER_TEXTURED));
std::unique_ptr<Layer> c1(CreateLayer(LAYER_TEXTURED));
std::unique_ptr<Layer> c11(CreateLayer(LAYER_TEXTURED));
GetCompositor()->SetScaleAndSize(1.25f, gfx::Size(100, 100));
GetCompositor()->SetRootLayer(root.get());
root->Add(c1.get());
c1->Add(c11.get());
root->SetBounds(gfx::Rect(0, 0, 100, 100));
c1->SetBounds(gfx::Rect(1, 1, 10, 10));
c11->SetBounds(gfx::Rect(1, 1, 10, 10));
SnapLayerToPhysicalPixelBoundary(root.get(), c11.get());
// 0.5 at 1.25 scale : (1 - 0.25 + 0.25) / 1.25 = 0.4
EXPECT_EQ("0.40 0.40",
Vector2dFTo100thPercisionString(c11->subpixel_position_offset()));
GetCompositor()->SetScaleAndSize(1.5f, gfx::Size(100, 100));
SnapLayerToPhysicalPixelBoundary(root.get(), c11.get());
// c11 must already be aligned at 1.5 scale.
EXPECT_EQ("0.00 0.00",
Vector2dFTo100thPercisionString(c11->subpixel_position_offset()));
c11->SetBounds(gfx::Rect(2, 2, 10, 10));
SnapLayerToPhysicalPixelBoundary(root.get(), c11.get());
// c11 is now off the pixel.
// 0.5 / 1.5 = 0.333...
EXPECT_EQ("0.33 0.33",
Vector2dFTo100thPercisionString(c11->subpixel_position_offset()));
}
class FrameDamageCheckingDelegate : public TestLayerDelegate {
public:
FrameDamageCheckingDelegate() : delegated_frame_damage_called_(false) {}
void OnDelegatedFrameDamage(const gfx::Rect& damage_rect_in_dip) override {
delegated_frame_damage_called_ = true;
delegated_frame_damage_rect_ = damage_rect_in_dip;
}
const gfx::Rect& delegated_frame_damage_rect() const {
return delegated_frame_damage_rect_;
}
bool delegated_frame_damage_called() const {
return delegated_frame_damage_called_;
}
private:
gfx::Rect delegated_frame_damage_rect_;
bool delegated_frame_damage_called_;
DISALLOW_COPY_AND_ASSIGN(FrameDamageCheckingDelegate);
};
TEST(LayerDelegateTest, DelegatedFrameDamage) {
std::unique_ptr<Layer> layer(new Layer(LAYER_TEXTURED));
gfx::Rect damage_rect(2, 1, 5, 3);
FrameDamageCheckingDelegate delegate;
layer->set_delegate(&delegate);
layer->SetShowSurface(cc::SurfaceId(), base::Bind(&FakeSatisfyCallback),
base::Bind(&FakeRequireCallback), gfx::Size(10, 10),
1.0, gfx::Size(10, 10));
EXPECT_FALSE(delegate.delegated_frame_damage_called());
layer->OnDelegatedFrameDamage(damage_rect);
EXPECT_TRUE(delegate.delegated_frame_damage_called());
EXPECT_EQ(damage_rect, delegate.delegated_frame_damage_rect());
}
TEST_F(LayerWithRealCompositorTest, CompositorAnimationObserverTest) {
std::unique_ptr<Layer> root(CreateLayer(LAYER_TEXTURED));
root->SetAnimator(LayerAnimator::CreateImplicitAnimator());
TestCompositorAnimationObserver animation_observer(GetCompositor());
EXPECT_EQ(0u, animation_observer.animation_step_count());
root->SetOpacity(0.5f);
WaitForSwap();
EXPECT_EQ(1u, animation_observer.animation_step_count());
EXPECT_FALSE(animation_observer.shutdown());
ResetCompositor();
EXPECT_TRUE(animation_observer.shutdown());
}
} // namespace ui
| [
"support@opentext.com"
] | support@opentext.com |
664f8e00dc447e1e885e0963563c1c913f610eb7 | 8b76d8f5949e7d1a2a2b2d84cbeab08d3d2e0b62 | /inc/i_event_distributor.hpp | c1d9afc917d4b48358650961a683b4ddfe01e180 | [] | no_license | RoyMattar/smart-home | a5690d1de4c22a94f55960d9fe8d19f199bac17d | 5a27facdd225df252a6f3d9e1d1edbcc10514dd4 | refs/heads/master | 2022-07-03T10:55:42.119093 | 2020-05-18T08:58:11 | 2020-05-18T08:58:11 | 264,874,482 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 599 | hpp | #ifndef I_EVENT_DISTRIBUTOR_HPP
#define I_EVENT_DISTRIBUTOR_HPP
#include "common_utils.hpp"
#include "event.hpp"
#include "distribution_list_tagged.hpp"
namespace smart_home
{
class IEventDistributor
{
public:
virtual ~IEventDistributor ();
//@exception throws std::out_of_range if no channel found by the given tag
virtual void Distribute (SharedPtr<Event> const& a_pEvent,
SharedPtr<DistributionListTagged> const& a_distributionListTagged) = 0;
};
inline IEventDistributor::~IEventDistributor () { }
} // smart_home
#endif // I_EVENT_DISTRIBUTOR_HPP | [
"roy.mattars@gmail.com"
] | roy.mattars@gmail.com |
b72d23b124992eebf3c315eba300795bc5246823 | d9e1a0b6e9a41c88dea4c5452aeb5c5bd9db8698 | /Dx3D2/cHead.cpp | 05b23a32570a8db60df9b356df8a022e0a47b172 | [] | no_license | LeeDongYoun/3DLecture | 9f04b02d5fb9468eb5d5dda1866274546d356cc0 | 3406c73de35a0c2434d2ab474592037cba1636ca | refs/heads/master | 2021-01-01T18:05:56.517281 | 2017-07-27T12:21:27 | 2017-07-27T12:21:27 | 98,248,662 | 0 | 0 | null | null | null | null | UHC | C++ | false | false | 6,673 | cpp | #include "stdafx.h"
#include "cHead.h"
cHead::cHead()
:m_vPos(0,0,0)
, m_fAngle(0)
, m_angles(0,0,0)
, _direction(0)
{
}
cHead::~cHead()
{
SAFE_RELEASE(m_pTexture);
}
void cHead::Setup(D3DXMATRIX * pmat, D3DXVECTOR3 pos)
{
m_vPos = pos;
D3DXCreateTextureFromFile(g_pD3DDevice,
"Iron_Man_Skin.png",
&m_pTexture);
/*vector<ST_PT_VERTEX> m_vecVertex;
vector<DWORD> vecIndex;
0vecVertexHead.push_back(ST_PT_VERTEX(D3DXVECTOR3(-1.0f, -1.0f, -1.0f), D3DXVECTOR2(0.125,0.5)));
1vecVertexHead.push_back(ST_PT_VERTEX(D3DXVECTOR3(-1.0f, 1.0f, -1.0f), D3DXVECTOR2(0.125, 0.25)));
2vecVertexHead.push_back(ST_PT_VERTEX(D3DXVECTOR3(1.0f, 1.0f, -1.0f), D3DXVECTOR2(0.25, 0.25)));
3vecVertexHead.push_back(ST_PT_VERTEX(D3DXVECTOR3(1.0f, -1.0f, -1.0f), D3DXVECTOR2(0.25, 0.5)));
4vecVertexHead.push_back(ST_PT_VERTEX(D3DXVECTOR3(-1.0f, -1.0f, 1.0f), D3DXVECTOR2(0.375, 0.5)));
5vecVertexHead.push_back(ST_PT_VERTEX(D3DXVECTOR3(-1.0f, 1.0f, 1.0f), D3DXVECTOR2(0.375, 0.25)));
6vecVertexHead.push_back(ST_PT_VERTEX(D3DXVECTOR3(1.0f, 1.0f, 1.0f), D3DXVECTOR2(0.5, 0.25)));
7vecVertexHead.push_back(ST_PT_VERTEX(D3DXVECTOR3(1.0f, -1.0f, 1.0f), D3DXVECTOR2(0.5, 0.5)));*/
//========================앞 012/023
m_vecVertex.push_back(ST_PNT_VERTEX(D3DXVECTOR3(-1.0f, -1.0f, -1.0f), D3DXVECTOR2(0.125, 0.5)));
m_vecVertex.push_back(ST_PNT_VERTEX(D3DXVECTOR3(-1.0f, 1.0f, -1.0f), D3DXVECTOR2(0.125, 0.25)));
m_vecVertex.push_back(ST_PNT_VERTEX(D3DXVECTOR3(1.0f, 1.0f, -1.0f), D3DXVECTOR2(0.25, 0.25)));
m_vecVertex.push_back(ST_PNT_VERTEX(D3DXVECTOR3(-1.0f, -1.0f, -1.0f), D3DXVECTOR2(0.125, 0.5)));
m_vecVertex.push_back(ST_PNT_VERTEX(D3DXVECTOR3(1.0f, 1.0f, -1.0f), D3DXVECTOR2(0.25, 0.25)));
m_vecVertex.push_back(ST_PNT_VERTEX(D3DXVECTOR3(1.0f, -1.0f, -1.0f), D3DXVECTOR2(0.25, 0.5)));
//=============뒤465/476
m_vecVertex.push_back(ST_PNT_VERTEX(D3DXVECTOR3(-1.0f, -1.0f, 1.0f), D3DXVECTOR2(0.375, 0.5)));
m_vecVertex.push_back(ST_PNT_VERTEX(D3DXVECTOR3(1.0f, 1.0f, 1.0f), D3DXVECTOR2(0.5, 0.25)));
m_vecVertex.push_back(ST_PNT_VERTEX(D3DXVECTOR3(-1.0f, 1.0f, 1.0f), D3DXVECTOR2(0.375, 0.25)));
m_vecVertex.push_back(ST_PNT_VERTEX(D3DXVECTOR3(-1.0f, -1.0f, 1.0f), D3DXVECTOR2(0.375, 0.5)));
m_vecVertex.push_back(ST_PNT_VERTEX(D3DXVECTOR3(1.0f, -1.0f, 1.0f), D3DXVECTOR2(0.5, 0.5)));
m_vecVertex.push_back(ST_PNT_VERTEX(D3DXVECTOR3(1.0f, 1.0f, 1.0f), D3DXVECTOR2(0.5, 0.25)));
//==================좌451/410
m_vecVertex.push_back(ST_PNT_VERTEX(D3DXVECTOR3(-1.0f, -1.0f, 1.0f), D3DXVECTOR2(0.375, 0.5)));
m_vecVertex.push_back(ST_PNT_VERTEX(D3DXVECTOR3(-1.0f, 1.0f, 1.0f), D3DXVECTOR2(0.375, 0.25)));
m_vecVertex.push_back(ST_PNT_VERTEX(D3DXVECTOR3(-1.0f, 1.0f, -1.0f), D3DXVECTOR2(0.25, 0.25)));
m_vecVertex.push_back(ST_PNT_VERTEX(D3DXVECTOR3(-1.0f, -1.0f, 1.0f), D3DXVECTOR2(0.375, 0.5)));
m_vecVertex.push_back(ST_PNT_VERTEX(D3DXVECTOR3(-1.0f, 1.0f, -1.0f), D3DXVECTOR2(0.25, 0.25)));
m_vecVertex.push_back(ST_PNT_VERTEX(D3DXVECTOR3(-1.0f, -1.0f, -1.0f), D3DXVECTOR2(0.25, 0.5)));
//===================우326/367
m_vecVertex.push_back(ST_PNT_VERTEX(D3DXVECTOR3(1.0f, -1.0f, -1.0f), D3DXVECTOR2(0, 0.5)));
m_vecVertex.push_back(ST_PNT_VERTEX(D3DXVECTOR3(1.0f, 1.0f, -1.0f), D3DXVECTOR2(0, 0.25)));
m_vecVertex.push_back(ST_PNT_VERTEX(D3DXVECTOR3(1.0f, 1.0f, 1.0f), D3DXVECTOR2(0.125, 0.25)));
m_vecVertex.push_back(ST_PNT_VERTEX(D3DXVECTOR3(1.0f, -1.0f, -1.0f), D3DXVECTOR2(0, 0.5)));
m_vecVertex.push_back(ST_PNT_VERTEX(D3DXVECTOR3(1.0f, 1.0f, 1.0f), D3DXVECTOR2(0.125, 0.25)));
m_vecVertex.push_back(ST_PNT_VERTEX(D3DXVECTOR3(1.0f, -1.0f, 1.0f), D3DXVECTOR2(0.125, 0.5)));
//======================위156/162
m_vecVertex.push_back(ST_PNT_VERTEX(D3DXVECTOR3(-1.0f, 1.0f, -1.0f), D3DXVECTOR2(0.125, 0.25)));
m_vecVertex.push_back(ST_PNT_VERTEX(D3DXVECTOR3(-1.0f, 1.0f, 1.0f), D3DXVECTOR2(0.125, 0)));
m_vecVertex.push_back(ST_PNT_VERTEX(D3DXVECTOR3(1.0f, 1.0f, 1.0f), D3DXVECTOR2(0.25, 0)));
m_vecVertex.push_back(ST_PNT_VERTEX(D3DXVECTOR3(-1.0f, 1.0f, -1.0f), D3DXVECTOR2(0.125, 0.25)));
m_vecVertex.push_back(ST_PNT_VERTEX(D3DXVECTOR3(1.0f, 1.0f, 1.0f), D3DXVECTOR2(0.25, 0)));
m_vecVertex.push_back(ST_PNT_VERTEX(D3DXVECTOR3(1.0f, 1.0f, -1.0f), D3DXVECTOR2(0.25, 0.25)));
//================아래403/437
m_vecVertex.push_back(ST_PNT_VERTEX(D3DXVECTOR3(-1.0f, -1.0f, 1.0f), D3DXVECTOR2(0.25, 0)));
m_vecVertex.push_back(ST_PNT_VERTEX(D3DXVECTOR3(-1.0f, -1.0f, -1.0f), D3DXVECTOR2(0.25, 0.25)));
m_vecVertex.push_back(ST_PNT_VERTEX(D3DXVECTOR3(1.0f, -1.0f, -1.0f), D3DXVECTOR2(0.375, 0.25)));
m_vecVertex.push_back(ST_PNT_VERTEX(D3DXVECTOR3(-1.0f, -1.0f, 1.0f), D3DXVECTOR2(0.25, 0)));
m_vecVertex.push_back(ST_PNT_VERTEX(D3DXVECTOR3(1.0f, -1.0f, -1.0f), D3DXVECTOR2(0.375, 0.25)));
m_vecVertex.push_back(ST_PNT_VERTEX(D3DXVECTOR3(1.0f, -1.0f, 1.0f), D3DXVECTOR2(0.375, 0)));
if (pmat)
{
for (size_t i = 0; i < m_vecVertex.size(); ++i)
{
D3DXVec3TransformCoord(&m_vecVertex[i].p,
&m_vecVertex[i].p,
pmat);
}
}
for (size_t i = 0; i < m_vecVertex.size(); i+=3) {
D3DXVECTOR3 u = (m_vecVertex[i+1].p) - (m_vecVertex[i].p);
D3DXVECTOR3 v = (m_vecVertex[i+2].p) - (m_vecVertex[i].p);
D3DXVECTOR3 n;
D3DXVec3Cross(&n, &u, &v);
D3DXVec3Normalize(&n, &n);
/*D3DXVECTOR3 vn;
vn = (n + n + n) / 3;*/
m_vecVertex[i].np = n;
m_vecVertex[i+1].np = n;
m_vecVertex[i+2].np = n;
}
ZeroMemory(&m_Material, sizeof(m_Material));
m_Material.Diffuse = D3DXCOLOR(1.0f, 1.0f, 1.0f, 1.0f);
m_Material.Ambient = D3DXCOLOR(1.0, 1.0f, 1.0f, 1.0f);
m_Material.Specular = D3DXCOLOR(1.0f, 1.0f, 1.0f, 1.0f);
m_Material.Emissive = D3DXCOLOR(0.0f, 0.0f, 0.0f, 1.0f);
m_Material.Power = 5.0f;
}
void cHead::Update(int direction)
{
_direction = direction;
static int count = 0;
if (_direction == 1) {
m_angles.y = 0.4 * sin(count*0.05);
m_angles.z = 0;
}
else if (_direction == 0|| _direction == 2|| _direction == 3) {
m_angles.x = 0;
m_angles.y = 0;
m_angles.z = 0;
}
count++;
}
void cHead::Render(D3DXMATRIX* body)
{
g_pD3DDevice->SetMaterial(&m_Material);
g_pD3DDevice->SetRenderState(D3DRS_NORMALIZENORMALS, true);
D3DXMATRIX matR;
D3DXMatrixRotationYawPitchRoll(&matR, m_angles.y, m_angles.x, m_angles.z);
D3DXMATRIX matT;
D3DXMatrixTranslation(&matT, m_vPos.x, m_vPos.y, m_vPos.z);
D3DXMATRIX _body = *body;
D3DXMATRIX matWorld = matR * matT;
matWorld = (matWorld) * (_body);
g_pD3DDevice->SetTexture(0, m_pTexture);
g_pD3DDevice->SetTransform(D3DTS_WORLD, &matWorld);
g_pD3DDevice->SetFVF(ST_PNT_VERTEX::FVF);
g_pD3DDevice->DrawPrimitiveUP(D3DPT_TRIANGLELIST,
m_vecVertex.size() / 3,
&m_vecVertex[0],
sizeof(ST_PNT_VERTEX));
}
| [
"dkdla12@naver.com"
] | dkdla12@naver.com |
827b2d0dbe6ded7a61ccba5400cdbdde3942f6ed | ccad8b8747b43181651047a0f341ed208443ff29 | /objectManager.h | 00e109bda52723ad8b3252787feb83592359bf02 | [] | no_license | MagicMantis/416Project2 | 48cf57d94a7a6fc3d70f08635059a107bcc7e1ec | 4cea9334ce4056424bc34f9e9237b25c677e0737 | refs/heads/master | 2021-03-19T06:09:16.784645 | 2017-02-21T18:56:28 | 2017-02-21T18:56:28 | 82,123,104 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 738 | h | #include "gameObject.h"
#include "rain.h"
#include "building.h"
#include "texture.h"
#include "detective.h"
#include "criminal.h"
#include "stageObject.h"
#include "lightning.h"
#include "fadeout.h"
#include "textureManager.h"
#include <vector>
const int rain_count = 200;
/**
* ObjectManager class: this class contains a vector of all game
* objects and manages updating and rendering them each frame.
*/
class ObjectManager {
public:
ObjectManager() : gameObjects() {}
~ObjectManager();
void initGameObjects(TextureManager& tm); //generate all objects in the scene
void updateObjects(int stage); //update all objects
void drawObjects(SDL_Renderer* rend); //draw all objects
private:
std::vector<GameObject*> gameObjects;
};
| [
"joesavold@hotmail.com"
] | joesavold@hotmail.com |
1b67ee3267ad1032eed24f8ff97eaf7d6bd41ef0 | 84be9dbc13fb07b3059b5cff9a8b662365571284 | /07 Standard Template Library/uva 12592(map).cpp | a5fa9652aaf16941d64f2cb07bbf76ca09e03d89 | [] | no_license | BarunBlog/Algorithm--Data_Structure--Structure_Programming | 375f6cea68eb147933d27bac0dcc75f644e7e3d4 | 9372546f546796fa7f68e0d055edf5bc73013049 | refs/heads/master | 2022-05-02T21:36:10.411733 | 2022-04-10T14:42:12 | 2022-04-10T14:42:12 | 235,832,118 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 591 | cpp | #include<bits/stdc++.h>
using namespace std;
int main()
{
map<string,string>mymap;
int N,Q,i;
string str1,str2;
while(cin>>N)
{
mymap.clear();
getchar();
for(i=0;i<N;i++)
{
getline(cin,str1);
getline(cin,str2);
mymap.insert(make_pair(str1,str2));
}
map<string,string>::iterator it;
cin>>Q;
getchar();
for(i=0;i<Q;i++)
{
getline(cin,str1);
it=mymap.find(str1);
cout<<(*it).second<<endl;
}
}
return 0;
}
| [
"bhattacharjeebarun25@gmail.com"
] | bhattacharjeebarun25@gmail.com |
87b20b56f160d68da38b52387095ae7b9939ce0e | 68f86397eca871101ca89175e6dd6283688ab9d7 | /xtreme3.cpp | 8a7a45a6640cfb7875cfd99b1d75d2a10a8964fa | [] | no_license | vinayakaraju46/cpp_DSA | d2a096c5c98fb8bc928d102fd6bd56b685720a39 | 1730551b6e47722f87dc9b154cd3552d3a516dcd | refs/heads/main | 2023-06-24T09:08:43.921102 | 2021-07-19T14:47:33 | 2021-07-19T14:47:33 | 387,498,632 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,908 | cpp | #include<bits/stdc++.h>
using namespace std;
class Node
{
public:
int data;
int height;
Node *left;
Node *right;
Node(const int &val,int count)
{
data = val;
left = NULL;
right = NULL;
height = count;
}
};
class BinTree
{
public:
Node *root;
BinTree()
{
root = NULL;
}
int calcHeight(Node *node)
{
if(node == NULL)
{
return 1;
}
return node->height;
}
Node *insert(const int &val)
{
root = insertNode(val, root,1);
}
Node *insertNode(const int &val, Node *node, int count)
{
if(node == NULL)
{
cout << count;
return new Node(val,count);
}
if(val < node->data | val == node->data)
{
node->left = insertNode(val, node->left,count+1);
}
if(val > node->data)
{
node->right = insertNode(val, node->right,count+1);
}
// node->height = max(calcHeight(node->left),calcHeight(node->right)) + 1;
return node;
}
// void topView(Node * root)
// {
// map<int,int> dict;
// map<int,int>::iterator itr;
// queue<pair<Node*,int> > que;
// Node *temp = NULL;
// que.push(pair<Node*,int>(root,1));
// while(que.size() != 0)
// {
// temp = que.front().first;
// int d = que.front().second;
// que.pop();
// dict.insert(pair<int,int>(d,temp->data));
// if(temp->left)
// {
// que.push(pair<Node*,int>( temp->left, d+1 ));
// }
// if(temp->right)
// {
// que.push(pair<Node*,int>( temp->right, d+1 ));
// }
// }
// for(itr=dict.begin();itr!=dict.end();++itr)
// {
// cout << itr->first << " ";
// }
// }
void traverse()
{
traverseinorder(root);
}
void traverseinorder(Node *node)
{
if(node->left)
{
traverseinorder(node->left);
}
cout << node->data << " , "<< node->height << endl;
if(node->right)
{
traverseinorder(node->right);
}
}
};
int main()
{BinTree tr;
int n,elem;
cin >> n;
for(int i=0; i<n; i++)
{
cin >> elem;
tr.insert(elem);
cout << endl;
}
// tr.topView(tr.root);
// tr.traverse();
return 0;
} | [
"vinayakaraju46@gmail.com"
] | vinayakaraju46@gmail.com |
f190778b0b41fe5f203d3184c355f36a354b1967 | d8244a96536c96050d8425d53fddb5df23a17596 | /Mysensor_1.54_DoubleRelaywithButtonActuators.ino | 46ce4c5a38eb00ca1759f5cdd626c59ae1568850 | [] | no_license | pengli534/hass-development | a62f86a8b237cac5740ae68573983c9e82594ee4 | 13cd087ee4124a03bacbd60a4f244bd41e6d856d | refs/heads/master | 2020-09-23T04:36:04.871079 | 2017-04-26T16:45:47 | 2017-04-26T16:45:47 | 67,652,160 | 3 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,785 | ino | // Sketch for double relay Actuators with buttons with/without DS18B20 temp sensor
// in loop() method, if (value2 != oldValue) {...} can be changed for Rocker switch
// this sketch is coded under mysensor with version 1.5.4
// pengli534@gmail.com
#include <MySensor.h>
#include <SPI.h>
#include <Bounce2.h>
#define RELAY_PIN 3 // Arduino Digital I/O pin number for relay
#define RELAY_PIN_2 5
#define BUTTON_PIN 4 // Arduino Digital I/O pin number for button
#define BUTTON_PIN_2 7
#define CHILD_ID_2 12
#define CHILD_ID 11 // Id of the sensor child
#define RELAY_ON 1
#define RELAY_OFF 0
Bounce debouncer = Bounce();
int oldValue=0;
bool state;
Bounce debouncer2 = Bounce();
int oldValue2=0;
bool state2;
MySensor gw;
MyMessage msg(CHILD_ID,V_LIGHT);
MyMessage msg2(CHILD_ID_2,V_LIGHT);
void incomingMessage(const MyMessage &message) {
// We only expect one type of message from controller. But we better check anyway.
if (message.isAck()) {
Serial.println("This is an ack from gateway");
}
if (message.type == V_LIGHT && message.sensor == 11) {
// Change relay state
state = message.getBool();
digitalWrite(RELAY_PIN, state?RELAY_ON:RELAY_OFF);
// Store state in eeprom
gw.saveState(CHILD_ID, state);
}
else if(message.type == V_LIGHT && message.sensor == 12){
state2 = message.getBool();
digitalWrite(RELAY_PIN_2, state2?RELAY_ON:RELAY_OFF);
// Store state in eeprom
gw.saveState(CHILD_ID_2, state2);
// Write some debug info
Serial.print("Incoming change for sensor:");
Serial.print(message.sensor);
Serial.print(", New status: ");
Serial.println(message.getBool());
}
}
void setup()
{
gw.begin(incomingMessage, AUTO, true);
// Send the sketch version information to the gateway and Controller
gw.sendSketchInfo("Double Relay & Button", "0.1");
// Setup the button
pinMode(BUTTON_PIN,INPUT);
// Activate internal pull-up
digitalWrite(BUTTON_PIN,HIGH);
// Setup the button
pinMode(BUTTON_PIN_2,INPUT);
// Activate internal pull-up
digitalWrite(BUTTON_PIN_2,HIGH);
// After setting up the button, setup debouncer
debouncer.attach(BUTTON_PIN);
debouncer.interval(5);
debouncer2.attach(BUTTON_PIN_2);
debouncer2.interval(5);
// Register all sensors to gw (they will be created as child devices)
gw.present(CHILD_ID, S_LIGHT);
gw.present(CHILD_ID_2, S_LIGHT);
// Make sure relays are off when starting up
digitalWrite(RELAY_PIN, RELAY_OFF);
// Then set relay pins in output mode
pinMode(RELAY_PIN, OUTPUT);
digitalWrite(RELAY_PIN_2, RELAY_OFF);
// Then set relay pins in output mode
pinMode(RELAY_PIN_2, OUTPUT);
// Set relay to last known state (using eeprom storage)
state = gw.loadState(CHILD_ID);
digitalWrite(RELAY_PIN, state?RELAY_ON:RELAY_OFF);
state2 = gw.loadState(CHILD_ID_2);
digitalWrite(RELAY_PIN_2, state2?RELAY_ON:RELAY_OFF);
}
/*
* Example on how to asynchronously check for new messages from gw
*/
void loop()
{
gw.process();
debouncer.update();
debouncer2.update();
// Get the update value
int value = debouncer.read();
int value2 = debouncer2.read();
// // if (value2 != oldValue) {...} change for contact switch/Rocker switch
if (value != oldValue && value == 0) {
gw.send(msg.set(state?false:true), true); // Send new state and request ack back
}
oldValue = value;
// if (value2 != oldValue2) {...}
if (value2 != oldValue2 && value2 == 0) {
gw.send(msg2.set(state2?false:true), true); // Send new state and request ack back
}
oldValue2 = value2;
}
| [
"noreply@github.com"
] | noreply@github.com |
8daef24f5f4f795a2d29ab34c81865c52bce1707 | 27a759daff7c3f5b611d9ac73ddd08feed0fa343 | /lab02/Roster.h | 9cfb431a46af76c36169f3a630028142f089c763 | [] | no_license | kctoombs/CS32 | a57433c2bc6c53e36957ad107a78ccd694cc5232 | a2b99a5d7e3b12edddf132e1962b0600cfff81ad | refs/heads/master | 2020-07-12T03:17:22.297512 | 2017-06-14T01:31:54 | 2017-06-14T01:31:54 | 94,274,985 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,269 | h | #ifndef ROSTER_H
#define ROSTER_H
#include <iostream>
#include <string>
#include "Student.h"
class Roster {
public:
Roster();
static const int ROSTER_MAX = 1024;
void addStudentsFromStream(std::istream &is);
void addStudentsFromFile(std::string filename);
int getNumStudents() const;
Student getStudentAt(int index) const;
std::string toString() const;
// Format of Roster::toString()
// opening "{\n",
// one Student toString() per line, each followed by ",\n"
// closing "}\n"
// No comma on last line before closing }
// Example:
// {\n
// [1234567,Smith,Mary Kay],\n
// [7654321,Perez,Carlos]\n
// }\n
void sortByPerm(); // use Selection Sort
/* DEFERRED TO LAB03:
void sortByName(); // use Insertion Sort, first on fname, then lname */
void resetRoster(); // delete all students from roster
// By rights, these next two helper functions
// should probably be private. We expose them as
// public so they are easily unit testable.
void sortByPermHelper(int k); // swaps max perm from [0..k-1] with elem [k-1]
int indexOfMaxPermAmongFirstKStudents(int k) const;
private:
// pointers to Students on heap!
Student *students[ROSTER_MAX];
int numStudents;
};
#endif
| [
"kctoombs@umail.ucsb.edu"
] | kctoombs@umail.ucsb.edu |
fd1654f153298fdfddead0f7f55de00c679aaf9c | 3ff1fe3888e34cd3576d91319bf0f08ca955940f | /essbasic/src/v20201222/model/RejectFlowResponse.cpp | 56ad87c4cf39c35bb6b9c05b96e644636024638b | [
"Apache-2.0"
] | permissive | TencentCloud/tencentcloud-sdk-cpp | 9f5df8220eaaf72f7eaee07b2ede94f89313651f | 42a76b812b81d1b52ec6a217fafc8faa135e06ca | refs/heads/master | 2023-08-30T03:22:45.269556 | 2023-08-30T00:45:39 | 2023-08-30T00:45:39 | 188,991,963 | 55 | 37 | Apache-2.0 | 2023-08-17T03:13:20 | 2019-05-28T08:56:08 | C++ | UTF-8 | C++ | false | false | 3,029 | cpp | /*
* Copyright (c) 2017-2019 THL A29 Limited, a Tencent company. 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 <tencentcloud/essbasic/v20201222/model/RejectFlowResponse.h>
#include <tencentcloud/core/utils/rapidjson/document.h>
#include <tencentcloud/core/utils/rapidjson/writer.h>
#include <tencentcloud/core/utils/rapidjson/stringbuffer.h>
using TencentCloud::CoreInternalOutcome;
using namespace TencentCloud::Essbasic::V20201222::Model;
using namespace std;
RejectFlowResponse::RejectFlowResponse()
{
}
CoreInternalOutcome RejectFlowResponse::Deserialize(const string &payload)
{
rapidjson::Document d;
d.Parse(payload.c_str());
if (d.HasParseError() || !d.IsObject())
{
return CoreInternalOutcome(Core::Error("response not json format"));
}
if (!d.HasMember("Response") || !d["Response"].IsObject())
{
return CoreInternalOutcome(Core::Error("response `Response` is null or not object"));
}
rapidjson::Value &rsp = d["Response"];
if (!rsp.HasMember("RequestId") || !rsp["RequestId"].IsString())
{
return CoreInternalOutcome(Core::Error("response `Response.RequestId` is null or not string"));
}
string requestId(rsp["RequestId"].GetString());
SetRequestId(requestId);
if (rsp.HasMember("Error"))
{
if (!rsp["Error"].IsObject() ||
!rsp["Error"].HasMember("Code") || !rsp["Error"]["Code"].IsString() ||
!rsp["Error"].HasMember("Message") || !rsp["Error"]["Message"].IsString())
{
return CoreInternalOutcome(Core::Error("response `Response.Error` format error").SetRequestId(requestId));
}
string errorCode(rsp["Error"]["Code"].GetString());
string errorMsg(rsp["Error"]["Message"].GetString());
return CoreInternalOutcome(Core::Error(errorCode, errorMsg).SetRequestId(requestId));
}
return CoreInternalOutcome(true);
}
string RejectFlowResponse::ToJsonString() const
{
rapidjson::Document value;
value.SetObject();
rapidjson::Document::AllocatorType& allocator = value.GetAllocator();
rapidjson::Value iKey(rapidjson::kStringType);
string key = "RequestId";
iKey.SetString(key.c_str(), allocator);
value.AddMember(iKey, rapidjson::Value().SetString(GetRequestId().c_str(), allocator), allocator);
rapidjson::StringBuffer buffer;
rapidjson::Writer<rapidjson::StringBuffer> writer(buffer);
value.Accept(writer);
return buffer.GetString();
}
| [
"tencentcloudapi@tencent.com"
] | tencentcloudapi@tencent.com |
7465ee319438546bff70426828336c51c3ed5e06 | 5a6723c8681abe909fe9cf8ca97c216ce6e99933 | /gamecore/CvGameAI.cpp | c4e799daf1e13f1e6cdcbf6ccf4b7e823b35395c | [] | no_license | gdambrauskas/anewdawn1.74Hspinoff | 4a1fdf36ea3ca148e62d85d838a0fb1cc0f554ff | 164e6221da147a87471f6f80e2657692bb55c4c3 | refs/heads/master | 2016-09-06T10:35:43.952504 | 2015-04-06T20:32:42 | 2015-04-06T20:32:42 | 3,645,687 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,357 | cpp | // gameAI.cpp
#include "CvGameCoreDLL.h"
#include "CvGameAI.h"
#include "CvPlayerAI.h"
#include "CvTeamAI.h"
#include "CvGlobals.h"
#include "CvInfos.h"
// Public Functions...
CvGameAI::CvGameAI()
{
AI_reset();
}
CvGameAI::~CvGameAI()
{
AI_uninit();
}
void CvGameAI::AI_init()
{
AI_reset();
//--------------------------------
// Init other game data
}
void CvGameAI::AI_uninit()
{
}
void CvGameAI::AI_reset()
{
AI_uninit();
m_iPad = 0;
}
void CvGameAI::AI_makeAssignWorkDirty()
{
int iI;
for (iI = 0; iI < MAX_PLAYERS; iI++)
{
if (GET_PLAYER((PlayerTypes)iI).isAlive())
{
GET_PLAYER((PlayerTypes)iI).AI_makeAssignWorkDirty();
}
}
}
void CvGameAI::AI_updateAssignWork()
{
int iI;
for (iI = 0; iI < MAX_PLAYERS; iI++)
{
CvPlayer& kLoopPlayer = GET_PLAYER((PlayerTypes)iI);
if (GET_TEAM(kLoopPlayer.getTeam()).isHuman() && kLoopPlayer.isAlive())
{
kLoopPlayer.AI_updateAssignWork();
}
}
}
int CvGameAI::AI_combatValue(UnitTypes eUnit)
{
int iValue;
iValue = 100;
if (GC.getUnitInfo(eUnit).getDomainType() == DOMAIN_AIR)
{
iValue *= GC.getUnitInfo(eUnit).getAirCombat();
}
else
{
iValue *= GC.getUnitInfo(eUnit).getCombat();
// UncutDragon
// original
//iValue *= ((((GC.getUnitInfo(eUnit).getFirstStrikes() * 2) + GC.getUnitInfo(eUnit).getChanceFirstStrikes()) * (GC.getDefineINT("COMBAT_DAMAGE") / 5)) + 100);
// modified
iValue *= ((((GC.getUnitInfo(eUnit).getFirstStrikes() * 2) + GC.getUnitInfo(eUnit).getChanceFirstStrikes()) * (GC.getCOMBAT_DAMAGE() / 5)) + 100);
// /UncutDragon
iValue /= 100;
}
iValue /= getBestLandUnitCombat();
return iValue;
}
int CvGameAI::AI_turnsPercent(int iTurns, int iPercent)
{
FAssert(iPercent > 0);
if (iTurns != MAX_INT)
{
iTurns *= (iPercent);
iTurns /= 100;
}
return std::max(1, iTurns);
}
void CvGameAI::read(FDataStreamBase* pStream)
{
CvGame::read(pStream);
uint uiFlag=0;
pStream->Read(&uiFlag); // flags for expansion
pStream->Read(&m_iPad);
}
void CvGameAI::write(FDataStreamBase* pStream)
{
CvGame::write(pStream);
uint uiFlag=0;
pStream->Write(uiFlag); // flag for expansion
pStream->Write(m_iPad);
}
// Protected Functions...
// Private Functions...
| [
"gdambrauskas@gmail.com"
] | gdambrauskas@gmail.com |
e8711aa31475e8924e53c7e58fa7d3be80ed1a3f | a61431ec8c236d257455f5abd655575dd2681d0e | /eleSignal/mainwindow.cpp | e0bb6b6fd11b69e88eecb3234e262e5b3cbe51c4 | [] | no_license | BigCircleLaw/Draw | 7cdc5903291486fd5f6b76cfb8b2333b1915a757 | 54b8aeada0b7456f49dd6acb160841d8a7f9939b | refs/heads/master | 2020-06-25T09:34:45.885433 | 2019-08-19T13:27:30 | 2019-08-19T13:27:30 | 199,273,514 | 5 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 9,686 | cpp | #include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QDebug>
#include <QDateTime>
MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
serial = nullptr;
setFixedSize(1400, 800);
// setWindowFlags(Qt::WindowCloseButtonHint);
for (int i = 0; i < 3; i++)
{
pix[i] = new QPixmap(PLOT_WIDTH, PLOT_HEIGHT);
pix[i]->fill(Qt::black);
plot[i] = new QPainter(pix[i]);
}
plot[0]->setPen(QPen(QColor(Qt::yellow), 1));
plot[1]->setPen(QPen(QColor(Qt::red), 1));
plot[2]->setPen(QPen(QColor(Qt::green), 1));
drawTim = new QTimer(this);
connect(drawTim, SIGNAL(timeout()), this, SLOT(drawPlot()));
drawTim->start(100);
ui->pathText->setText(QCoreApplication::applicationDirPath());
showState[0] = ui->checkBox;
showState[1] = ui->checkBox_2;
showState[2] = ui->checkBox_3;
showState[3] = ui->checkBox_4;
showState[4] = ui->checkBox_5;
showState[5] = ui->checkBox_6;
for (int i = 0; i < 6; i++)
{
showState[i]->setTristate();
}
stateVal[0] = 0;
stateVal[1] = 0;
flag = 0;
// showState[0]->setCheckState(Qt::PartiallyChecked);
// showState[1]->setChecked(false);
}
MainWindow::~MainWindow()
{
delete ui;
}
void MainWindow::drawPlot()
{
int *data[3], startPosition[3];
data[0] = myparse.getDrawData(startPosition[0], 0);
data[1] = myparse.getDrawData(startPosition[1], 1);
data[2] = myparse.getDrawData(startPosition[2], 2);
pix[0]->fill(Qt::black);
pix[1]->fill(Qt::black);
pix[2]->fill(Qt::black);
for (int i = 0; i < (pix[0]->width() - 1); i++)
{
for (unsigned char j = 0; j < 3; j++)
{
int position = (startPosition[j] + i * DRAW_STEP_VAL) % PARSE_DATA_LEN;
plot[j]->drawLine(i, data[j][position], i + 1, data[j][(position + DRAW_STEP_VAL) % PARSE_DATA_LEN]);
}
// qDebug() << data[position] << data[(position + 1) % PARSE_DATA_LEN];
}
// if(flag == 0)
{
for (int i = 0; i < 3; i++)
{
if ((stateVal[0] & (0x10 << i)) != 0)
{
showState[i]->setCheckState(Qt::PartiallyChecked);
}
else
{
showState[i]->setCheckState(Qt::Unchecked);
}
if ((stateVal[1] & (0x10 << i)) != 0)
{
showState[i + 3]->setCheckState(Qt::PartiallyChecked);
}
else
{
showState[i + 3]->setCheckState(Qt::Unchecked);
}
}
}
// else
// {
// for (int i = 0; i < 6; i++)
// {
// showState[i]->setCheckState(Qt::Unchecked);
// }
// }
repaint();
}
void MainWindow::on_startButton_pressed()
{
static int count = 0;
ui->serialPortBox->clear();
auto infos = QSerialPortInfo::availablePorts();
for (const QSerialPortInfo &info : infos)
{
ui->serialPortBox->addItem(info.portName());
ui->textBrowser->setText(QString::number(info.productIdentifier()) + "\r\n");
qDebug() << info.portName() << ", PID:" << info.productIdentifier() << ", VID:" << info.vendorIdentifier();
}
count++;
}
void MainWindow::on_startButton_released()
{
// ui->startButton->setText("结束");
}
void MainWindow::on_beginButton_pressed()
{
ui->textBrowser->setText("开始");
qDebug() << ui->serialPortBox->currentText();
if (ui->serialPortBox->currentText() == "")
{
ui->textBrowser->append("串口选择错误!!!");
ui->textBrowser->append("运行失败!!!");
return;
}
if (serial == nullptr)
serial = new QSerialPort();
if (serial->isOpen()) //如果串口已经打开了 先给他关闭了
{
serial->clear();
serial->close();
}
serial->setPortName(ui->serialPortBox->currentText());
if (!serial->open(QIODevice::ReadWrite)) //用ReadWrite 的模式尝试打开串口
{
qDebug() << ui->serialPortBox->currentText() << "打开失败!";
ui->textBrowser->append("串口打开失败!!");
return;
}
//打开成功
qDebug() << serial->isOpen();
serial->setBaudRate(512000, QSerialPort::AllDirections); //设置波特率和读写方向
serial->setDataBits(QSerialPort::Data8); //数据位为8位
serial->setFlowControl(QSerialPort::NoFlowControl); //无流控制
serial->setParity(QSerialPort::NoParity); //无校验位
serial->setStopBits(QSerialPort::OneStop); //一位停止位
serial->setDataTerminalReady(true);
serial->setReadBufferSize(2048);
connect(serial, SIGNAL(readyRead()), this, SLOT(serialPut()));
ui->beginButton->setEnabled(false);
ui->endButton->setEnabled(true);
ui->startSave->setEnabled(true);
ui->endSave->setEnabled(false);
ui->enableLoffButton->setEnabled(false);
ui->disableLoffButton->setEnabled(true);
unsigned char startCmd[3] = {0xFF, 0x01, 0xFE};
serial->write((const char *)startCmd, 3);
}
void MainWindow::on_endButton_pressed()
{
unsigned char endCmd[3] = {0xFF, 0x02, 0xFE};
serial->write((const char *)endCmd, 3);
if (serial != nullptr)
{
if (serial->isOpen())
{
serial->clear();
serial->close();
qDebug() << serial->isOpen();
}
delete serial;
serial = nullptr;
}
ui->textBrowser->append("运行结束");
myparse.end();
ui->endButton->setEnabled(false);
ui->beginButton->setEnabled(true);
ui->startSave->setEnabled(false);
ui->endSave->setEnabled(false);
ui->disableLoffButton->setEnabled(false);
ui->enableLoffButton->setEnabled(false);
}
void MainWindow::serialPut()
{
QByteArray temp = serial->readAll();
// qDebug()<<temp.size();
// ui->textBrowser->setText(QString::number(temp.size()));
for (int i = 0; i < temp.size(); i++)
{
// ui->textBrowser->append(QString::number((unsigned char)temp[i], 16));
// ui->textBrowser->append(" ");
Receiver_put((unsigned char)temp[i]);
}
}
void MainWindow::paintEvent(QPaintEvent *)
{
QPainter p(this);
p.drawPixmap(320, 70, PLOT_WIDTH, PLOT_HEIGHT, *pix[0]);
p.drawPixmap(320, 320, PLOT_WIDTH, PLOT_HEIGHT, *pix[1]);
p.drawPixmap(320, 570, PLOT_WIDTH, PLOT_HEIGHT, *pix[2]);
}
void MainWindow::RequestHandle(unsigned char *data, unsigned char len)
{
if (12 == len)
{
stateVal[0] = data[1];
stateVal[1] = data[2];
for (int i = 0; i < 3; i++)
{
currentValue[i] = myparse.getADS1294Value(data + 3 + i * 3, i);
// ui->textBrowser->append(QString::number(currentValue[i]));
}
// qDebug()<<currentValue[0]<<currentValue[1]<<currentValue[2];
}
else
{
switch (data[0])
{
}
}
}
/**
* @brief 判断一个包是否完成
* @param data:字节数据
* @retval None
*/
void MainWindow::Receiver_put(unsigned char data)
{
if (0xFF == data)
{
this->buf.index = 0;
}
this->buf.buf[this->buf.index++] = data;
//#if defined WONDERBITS_STM32||defined WONDERBITS_STM32GUN||defined WONDERBITS_STM32BIG||defined WONDERBITS_STM32BIG_GUN
if (this->buf.index >= MSG_MAX_LENGTH_ALL)
this->buf.index = MSG_MAX_LENGTH_ALL - 1;
//#endif
if (0xFE == data)
{
translate(this->buf.buf + 1); //掠过包起始位
{
RequestHandle(this->package.buf, this->package.index);
}
}
}
/**
* @brief 数据转义
* @param buf:去掉包起始位的缓存区
* @retval None
*/
void MainWindow::translate(unsigned char *buf)
{
int i;
unsigned char DataBuffer;
unsigned char index;
index = 0;
for (i = 0; buf[i] != MSG_END_TAG;)
{
DataBuffer = buf[i++];
if (DataBuffer == MSG_TRANSLATE_TAG)
DataBuffer += buf[i++]; //Combine the value that have been broke up(0xFD, 0xFE and 0xFF)
this->package.buf[index++] = DataBuffer;
}
this->package.index = index;
}
void MainWindow::on_startSave_pressed()
{
QDateTime current_time = QDateTime::currentDateTime();
bool state = myparse.begin(ui->pathText->text(), current_time.toString("yyyy-MM-dd hh-mm-ss"));
if (!state)
{
ui->textBrowser->append("文件打开失败!!!");
}
ui->startSave->setEnabled(false);
ui->endSave->setEnabled(true);
}
void MainWindow::on_endSave_pressed()
{
myparse.end();
ui->endSave->setEnabled(false);
ui->startSave->setEnabled(true);
}
void MainWindow::on_enableLoffButton_pressed()
{
unsigned char enableLoffCmd[3] = {0xFF, 0x03, 0xFE};
serial->write((const char *)enableLoffCmd, 3);
flag = 0;
ui->disableLoffButton->setEnabled(true);
ui->enableLoffButton->setEnabled(false);
}
void MainWindow::on_disableLoffButton_pressed()
{
unsigned char disableLoffCmd[3] = {0xFF, 0x04, 0xFE};
serial->write((const char *)disableLoffCmd, 3);
flag = 1;
ui->enableLoffButton->setEnabled(true);
ui->disableLoffButton->setEnabled(false);
}
| [
"794557226@qq.com"
] | 794557226@qq.com |
dbc921eda9389f665c9a771769cdd4716a4ec0e1 | a271ed32c59e774f185ee4fa4bb577e06bd492b8 | /moc_clientmodel.cpp | e951a6963173378a154a80a56d49e17498573460 | [
"MIT"
] | permissive | IonCoinDev/IonCoin | 0d9fae6dadb18e0bedf14284260b66b900fdf380 | 534d193336ded0dab9715503ea2d29abd5cdef80 | refs/heads/master | 2021-01-10T19:33:16.232951 | 2014-05-28T23:12:54 | 2014-05-28T23:12:54 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,542 | cpp | /****************************************************************************
** Meta object code from reading C++ file 'clientmodel.h'
**
** Created by: The Qt Meta Object Compiler version 67 (Qt 5.2.1)
**
** WARNING! All changes made in this file will be lost!
*****************************************************************************/
#include "src/qt/clientmodel.h"
#include <QtCore/qbytearray.h>
#include <QtCore/qmetatype.h>
#if !defined(Q_MOC_OUTPUT_REVISION)
#error "The header file 'clientmodel.h' doesn't include <QObject>."
#elif Q_MOC_OUTPUT_REVISION != 67
#error "This file was generated using the moc from 5.2.1. It"
#error "cannot be used with the include files from this version of Qt."
#error "(The moc has changed too much.)"
#endif
QT_BEGIN_MOC_NAMESPACE
struct qt_meta_stringdata_ClientModel_t {
QByteArrayData data[16];
char stringdata[170];
};
#define QT_MOC_LITERAL(idx, ofs, len) \
Q_STATIC_BYTE_ARRAY_DATA_HEADER_INITIALIZER_WITH_OFFSET(len, \
offsetof(qt_meta_stringdata_ClientModel_t, stringdata) + ofs \
- idx * sizeof(QByteArrayData) \
)
static const qt_meta_stringdata_ClientModel_t qt_meta_stringdata_ClientModel = {
{
QT_MOC_LITERAL(0, 0, 11),
QT_MOC_LITERAL(1, 12, 21),
QT_MOC_LITERAL(2, 34, 0),
QT_MOC_LITERAL(3, 35, 5),
QT_MOC_LITERAL(4, 41, 16),
QT_MOC_LITERAL(5, 58, 12),
QT_MOC_LITERAL(6, 71, 5),
QT_MOC_LITERAL(7, 77, 5),
QT_MOC_LITERAL(8, 83, 7),
QT_MOC_LITERAL(9, 91, 5),
QT_MOC_LITERAL(10, 97, 11),
QT_MOC_LITERAL(11, 109, 20),
QT_MOC_LITERAL(12, 130, 14),
QT_MOC_LITERAL(13, 145, 11),
QT_MOC_LITERAL(14, 157, 4),
QT_MOC_LITERAL(15, 162, 6)
},
"ClientModel\0numConnectionsChanged\0\0"
"count\0numBlocksChanged\0countOfPeers\0"
"error\0title\0message\0modal\0updateTimer\0"
"updateNumConnections\0numConnections\0"
"updateAlert\0hash\0status\0"
};
#undef QT_MOC_LITERAL
static const uint qt_meta_data_ClientModel[] = {
// content:
7, // revision
0, // classname
0, 0, // classinfo
6, 14, // methods
0, 0, // properties
0, 0, // enums/sets
0, 0, // constructors
0, // flags
3, // signalCount
// signals: name, argc, parameters, tag, flags
1, 1, 44, 2, 0x06,
4, 2, 47, 2, 0x06,
6, 3, 52, 2, 0x06,
// slots: name, argc, parameters, tag, flags
10, 0, 59, 2, 0x0a,
11, 1, 60, 2, 0x0a,
13, 2, 63, 2, 0x0a,
// signals: parameters
QMetaType::Void, QMetaType::Int, 3,
QMetaType::Void, QMetaType::Int, QMetaType::Int, 3, 5,
QMetaType::Void, QMetaType::QString, QMetaType::QString, QMetaType::Bool, 7, 8, 9,
// slots: parameters
QMetaType::Void,
QMetaType::Void, QMetaType::Int, 12,
QMetaType::Void, QMetaType::QString, QMetaType::Int, 14, 15,
0 // eod
};
void ClientModel::qt_static_metacall(QObject *_o, QMetaObject::Call _c, int _id, void **_a)
{
if (_c == QMetaObject::InvokeMetaMethod) {
ClientModel *_t = static_cast<ClientModel *>(_o);
switch (_id) {
case 0: _t->numConnectionsChanged((*reinterpret_cast< int(*)>(_a[1]))); break;
case 1: _t->numBlocksChanged((*reinterpret_cast< int(*)>(_a[1])),(*reinterpret_cast< int(*)>(_a[2]))); break;
case 2: _t->error((*reinterpret_cast< const QString(*)>(_a[1])),(*reinterpret_cast< const QString(*)>(_a[2])),(*reinterpret_cast< bool(*)>(_a[3]))); break;
case 3: _t->updateTimer(); break;
case 4: _t->updateNumConnections((*reinterpret_cast< int(*)>(_a[1]))); break;
case 5: _t->updateAlert((*reinterpret_cast< const QString(*)>(_a[1])),(*reinterpret_cast< int(*)>(_a[2]))); break;
default: ;
}
} else if (_c == QMetaObject::IndexOfMethod) {
int *result = reinterpret_cast<int *>(_a[0]);
void **func = reinterpret_cast<void **>(_a[1]);
{
typedef void (ClientModel::*_t)(int );
if (*reinterpret_cast<_t *>(func) == static_cast<_t>(&ClientModel::numConnectionsChanged)) {
*result = 0;
}
}
{
typedef void (ClientModel::*_t)(int , int );
if (*reinterpret_cast<_t *>(func) == static_cast<_t>(&ClientModel::numBlocksChanged)) {
*result = 1;
}
}
{
typedef void (ClientModel::*_t)(const QString & , const QString & , bool );
if (*reinterpret_cast<_t *>(func) == static_cast<_t>(&ClientModel::error)) {
*result = 2;
}
}
}
}
const QMetaObject ClientModel::staticMetaObject = {
{ &QObject::staticMetaObject, qt_meta_stringdata_ClientModel.data,
qt_meta_data_ClientModel, qt_static_metacall, 0, 0}
};
const QMetaObject *ClientModel::metaObject() const
{
return QObject::d_ptr->metaObject ? QObject::d_ptr->dynamicMetaObject() : &staticMetaObject;
}
void *ClientModel::qt_metacast(const char *_clname)
{
if (!_clname) return 0;
if (!strcmp(_clname, qt_meta_stringdata_ClientModel.stringdata))
return static_cast<void*>(const_cast< ClientModel*>(this));
return QObject::qt_metacast(_clname);
}
int ClientModel::qt_metacall(QMetaObject::Call _c, int _id, void **_a)
{
_id = QObject::qt_metacall(_c, _id, _a);
if (_id < 0)
return _id;
if (_c == QMetaObject::InvokeMetaMethod) {
if (_id < 6)
qt_static_metacall(this, _c, _id, _a);
_id -= 6;
} else if (_c == QMetaObject::RegisterMethodArgumentMetaType) {
if (_id < 6)
*reinterpret_cast<int*>(_a[0]) = -1;
_id -= 6;
}
return _id;
}
// SIGNAL 0
void ClientModel::numConnectionsChanged(int _t1)
{
void *_a[] = { 0, const_cast<void*>(reinterpret_cast<const void*>(&_t1)) };
QMetaObject::activate(this, &staticMetaObject, 0, _a);
}
// SIGNAL 1
void ClientModel::numBlocksChanged(int _t1, int _t2)
{
void *_a[] = { 0, const_cast<void*>(reinterpret_cast<const void*>(&_t1)), const_cast<void*>(reinterpret_cast<const void*>(&_t2)) };
QMetaObject::activate(this, &staticMetaObject, 1, _a);
}
// SIGNAL 2
void ClientModel::error(const QString & _t1, const QString & _t2, bool _t3)
{
void *_a[] = { 0, const_cast<void*>(reinterpret_cast<const void*>(&_t1)), const_cast<void*>(reinterpret_cast<const void*>(&_t2)), const_cast<void*>(reinterpret_cast<const void*>(&_t3)) };
QMetaObject::activate(this, &staticMetaObject, 2, _a);
}
QT_END_MOC_NAMESPACE
| [
"ioncoindev@gmail.com"
] | ioncoindev@gmail.com |
600f5c39be81c0cd93ba5840f8f3aa3996d17f6d | f31b8497718c5c00e233c9fb17160339fa0275e1 | /TheQuestOfTheBurningHeart/GroupSolidBlockTileData.h | 5a11625ab29b8a67a18a38123fb654eb7145b0d1 | [] | no_license | bliou/TheQuestOfTheBurningHeart | 30a6876e80e7424dba6dd8dfa670a5ddabf4a46a | edbb98644f82fb6fcc2182b9bfc79a7fd9872bc2 | refs/heads/master | 2020-04-17T22:34:01.563921 | 2019-02-16T15:41:50 | 2019-02-16T15:41:50 | 166,999,372 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 380 | h | #pragma once
#include "SolidBlockTileData.h"
class GroupSolidBlockTileData: public SolidBlockTileData
{
public:
GroupSolidBlockTileData(BaseTileType tileType);
~GroupSolidBlockTileData();
virtual void initializeEntity(
std::string dataId,
anax::Entity& entity,
GameScreen& gameInstance,
sf::Vector2f position,
nlohmann::json::value_type specificData) override;
};
| [
"jacques.eid@gmail.com"
] | jacques.eid@gmail.com |
747f98d8f4becfc609ba6e7b443fd6e9662408d5 | e4b19a045f116d31cffe062cfd691f69f0955d22 | /NetWork-Lib/Server.cpp | a5f87e748c3a4d009e4d7c20ddc771436fce0976 | [] | no_license | lixuhao/MyWebServer | 3a1d9c0807263b16bbbb047d0ffd17fd3adfd29d | ee5408680b537c6af398b1572215e3705e87687d | refs/heads/master | 2020-07-28T20:48:00.749224 | 2019-09-19T13:29:43 | 2019-09-19T13:29:43 | 209,529,711 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,738 | cpp | // @Author Lixuhao
// @Email xxx@qq.com
#include "Server.h"
#include "base/Logging.h"
#include "Util.h"
#include <functional>
#include <netinet/in.h>
#include <sys/socket.h>
#include <arpa/inet.h>
Server::Server(EventLoop *loop, int threadNum, int port)
: loop_(loop),
threadNum_(threadNum),
eventLoopThreadPool_(new EventLoopThreadPool(loop_, threadNum)),
started_(false),
acceptChannel_(new Channel(loop_)),
port_(port),
listenFd_(socket_bind_listen(port_))
{
acceptChannel_->setFd(listenFd_);
handle_for_sigpipe();
if (setSocketNonBlocking(listenFd_) < 0)
{
perror("set socket non block failed");
abort();
}
}
void Server::start()
{
eventLoopThreadPool_->start();
//acceptChannel_->setEvents(EPOLLIN | EPOLLET | EPOLLONESHOT);
acceptChannel_->setEvents(EPOLLIN | EPOLLET);
acceptChannel_->setReadHandler(bind(&Server::handNewConn, this));
acceptChannel_->setConnHandler(bind(&Server::handThisConn, this));
loop_->addToPoller(acceptChannel_, 0);
started_ = true;
}
void Server::handNewConn()
{
struct sockaddr_in client_addr;
memset(&client_addr, 0, sizeof(struct sockaddr_in));
socklen_t client_addr_len = sizeof(client_addr);
int accept_fd = 0;
while((accept_fd = accept(listenFd_, (struct sockaddr*)&client_addr, &client_addr_len)) > 0)
{
EventLoop *loop = eventLoopThreadPool_->getNextLoop();
LOG << "New connection from " << inet_ntoa(client_addr.sin_addr) << ":" << ntohs(client_addr.sin_port);
// cout << "new connection" << endl;
// cout << inet_ntoa(client_addr.sin_addr) << endl;
// cout << ntohs(client_addr.sin_port) << endl;
/*
// TCP的保活机制默认是关闭的
int optval = 0;
socklen_t len_optval = 4;
getsockopt(accept_fd, SOL_SOCKET, SO_KEEPALIVE, &optval, &len_optval);
cout << "optval ==" << optval << endl;
*/
// 限制服务器的最大并发连接数
if (accept_fd >= MAXFDS)
{
close(accept_fd);
continue;
}
// 设为非阻塞模式
if (setSocketNonBlocking(accept_fd) < 0)
{
LOG << "Set non block failed!";
//perror("Set non block failed!");
return;
}
setSocketNodelay(accept_fd);
//setSocketNoLinger(accept_fd);
shared_ptr<HttpData> req_info(new HttpData(loop, accept_fd));
req_info->getChannel()->setHolder(req_info);
loop->queueInLoop(std::bind(&HttpData::newEvent, req_info));
}
acceptChannel_->setEvents(EPOLLIN | EPOLLET);
}
| [
"1596453962@qq.com"
] | 1596453962@qq.com |
c5b254a4dfd6d98d204ede9697e4b431eb7cb2df | 0eff74b05b60098333ad66cf801bdd93becc9ea4 | /second/download/rsync/gumtree/rsync_old_log_540.cpp | 2da016988b87722bd76b339411ad29e0eda5667b | [] | 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 | 87 | cpp | fprintf(FERROR,"failed to set permissions on %s : %s\n",
fname,strerror(errno)); | [
"993273596@qq.com"
] | 993273596@qq.com |
b82d07745175bcff92bb6314eb5213ab7d2df9e5 | ab5c19cf7af83931cdf7acf11b6a1dbe3ea96eb6 | /MiniGame/MiniGame/GameMenu.h | 61a07c7d57d483800c13eda0c7a9a183d00e406c | [] | no_license | rkddlsgh1234/MyGameSource | ecc4f16d94017834fd3695241cc052baf43beee3 | 54c15d457f26608b9e9f02368d10febaa3f01a2d | refs/heads/master | 2020-07-02T03:39:20.417188 | 2019-08-09T08:37:47 | 2019-08-09T08:37:47 | 201,403,584 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,409 | h | #pragma once
#include <IncludeDefine.h>
#include <BitMap.h>
#include <InputManager.h>
#include "CardGameScene.h"
#define BUTTON_SIZE_X 48
#define BUTTON_SIZE_Y 50
#define BUTTON_END 3
enum SCENE_STATE
{
SCENE_TITLE,
SCENE_GAMEMENU,
SCENE_CARD_GAME,
SCENE_AIRPLANE_GAME,
SCENE_END,
};
enum BUTTON_TYPE
{
BUTTON_TYPE_SELECT,
BUTTON_TYPE_OK,
};
enum BUTTON_STATE
{
BUTTON_STATE_WAIT,
BUTTON_STATE_PUSH,
BUTTON_STATE_DESTORY,
};
class GameMenu
{
private:
float m_fX;
float m_fY;
float m_fButtonX;
float m_fButtonY;
float m_fButtonMotionDelay;
int m_iCount;
SCENE_STATE m_eGameType;
BUTTON_TYPE m_eButtonType;
BUTTON_STATE m_eButtonState;
Engine::BitMap* m_pBitMap;
Engine::BitMap* m_pButton[2];
public:
GameMenu();
virtual ~GameMenu();
void Init(int x, int y, Engine::BitMap* pBitMap, SCENE_STATE GameType, BUTTON_TYPE ButtonType);
void Draw();
void ChangeButtonState();
void Motion(float fElapseTime);
void SetButtonPos(float x, float y);
void DestoryButton();
virtual inline RECT GetButtonSize()
{
RECT rc = { (LONG)m_fButtonX, (LONG)m_fButtonY, (LONG)m_fButtonX + m_pButton[0]->GetSize().cx, (LONG)m_fButtonY + m_pButton[0]->GetSize().cy };
return rc;
}
virtual inline SCENE_STATE GetGameType()
{
return m_eGameType;
}
virtual inline int GetButtonCount()
{
return m_iCount;
}
virtual inline BUTTON_STATE GetButtonState()
{
return m_eButtonState;
}
};
| [
"inho2456@naver.com"
] | inho2456@naver.com |
d0ab62847e397c2a25b56eac50f31b4d98ede9df | 46f53e9a564192eed2f40dc927af6448f8608d13 | /content/common/gpu/gpu_memory_buffer_factory_io_surface.cc | 604c1b4927388f956c415939b023ce24b242932c | [
"BSD-3-Clause"
] | permissive | sgraham/nope | deb2d106a090d71ae882ac1e32e7c371f42eaca9 | f974e0c234388a330aab71a3e5bbf33c4dcfc33c | refs/heads/master | 2022-12-21T01:44:15.776329 | 2015-03-23T17:25:47 | 2015-03-23T17:25:47 | 32,344,868 | 2 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 5,496 | cc | // 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.
#include "content/common/gpu/gpu_memory_buffer_factory_io_surface.h"
#include <CoreFoundation/CoreFoundation.h>
#include "base/logging.h"
#include "ui/gl/gl_image_io_surface.h"
namespace content {
namespace {
void AddBooleanValue(CFMutableDictionaryRef dictionary,
const CFStringRef key,
bool value) {
CFDictionaryAddValue(
dictionary, key, value ? kCFBooleanTrue : kCFBooleanFalse);
}
void AddIntegerValue(CFMutableDictionaryRef dictionary,
const CFStringRef key,
int32 value) {
base::ScopedCFTypeRef<CFNumberRef> number(
CFNumberCreate(NULL, kCFNumberSInt32Type, &value));
CFDictionaryAddValue(dictionary, key, number.get());
}
int32 BytesPerPixel(gfx::GpuMemoryBuffer::Format format) {
switch (format) {
case gfx::GpuMemoryBuffer::BGRA_8888:
return 4;
case gfx::GpuMemoryBuffer::ATC:
case gfx::GpuMemoryBuffer::ATCIA:
case gfx::GpuMemoryBuffer::DXT1:
case gfx::GpuMemoryBuffer::DXT5:
case gfx::GpuMemoryBuffer::ETC1:
case gfx::GpuMemoryBuffer::RGBA_8888:
case gfx::GpuMemoryBuffer::RGBX_8888:
NOTREACHED();
return 0;
}
NOTREACHED();
return 0;
}
int32 PixelFormat(gfx::GpuMemoryBuffer::Format format) {
switch (format) {
case gfx::GpuMemoryBuffer::BGRA_8888:
return 'BGRA';
case gfx::GpuMemoryBuffer::ATC:
case gfx::GpuMemoryBuffer::ATCIA:
case gfx::GpuMemoryBuffer::DXT1:
case gfx::GpuMemoryBuffer::DXT5:
case gfx::GpuMemoryBuffer::ETC1:
case gfx::GpuMemoryBuffer::RGBA_8888:
case gfx::GpuMemoryBuffer::RGBX_8888:
NOTREACHED();
return 0;
}
NOTREACHED();
return 0;
}
const GpuMemoryBufferFactory::Configuration kSupportedConfigurations[] = {
{ gfx::GpuMemoryBuffer::BGRA_8888, gfx::GpuMemoryBuffer::MAP }
};
} // namespace
GpuMemoryBufferFactoryIOSurface::GpuMemoryBufferFactoryIOSurface() {
}
GpuMemoryBufferFactoryIOSurface::~GpuMemoryBufferFactoryIOSurface() {
}
// static
bool GpuMemoryBufferFactoryIOSurface::IsGpuMemoryBufferConfigurationSupported(
gfx::GpuMemoryBuffer::Format format,
gfx::GpuMemoryBuffer::Usage usage) {
for (auto& configuration : kSupportedConfigurations) {
if (configuration.format == format && configuration.usage == usage)
return true;
}
return false;
}
void GpuMemoryBufferFactoryIOSurface::GetSupportedGpuMemoryBufferConfigurations(
std::vector<Configuration>* configurations) {
configurations->assign(
kSupportedConfigurations,
kSupportedConfigurations + arraysize(kSupportedConfigurations));
}
gfx::GpuMemoryBufferHandle
GpuMemoryBufferFactoryIOSurface::CreateGpuMemoryBuffer(
gfx::GpuMemoryBufferId id,
const gfx::Size& size,
gfx::GpuMemoryBuffer::Format format,
gfx::GpuMemoryBuffer::Usage usage,
int client_id,
gfx::PluginWindowHandle surface_handle) {
base::ScopedCFTypeRef<CFMutableDictionaryRef> properties;
properties.reset(CFDictionaryCreateMutable(kCFAllocatorDefault,
0,
&kCFTypeDictionaryKeyCallBacks,
&kCFTypeDictionaryValueCallBacks));
AddIntegerValue(properties, kIOSurfaceWidth, size.width());
AddIntegerValue(properties, kIOSurfaceHeight, size.height());
AddIntegerValue(properties, kIOSurfaceBytesPerElement, BytesPerPixel(format));
AddIntegerValue(properties, kIOSurfacePixelFormat, PixelFormat(format));
// TODO(reveman): Remove this when using a mach_port_t to transfer
// IOSurface to browser and renderer process. crbug.com/323304
AddBooleanValue(properties, kIOSurfaceIsGlobal, true);
base::ScopedCFTypeRef<IOSurfaceRef> io_surface(IOSurfaceCreate(properties));
if (!io_surface)
return gfx::GpuMemoryBufferHandle();
{
base::AutoLock lock(io_surfaces_lock_);
IOSurfaceMapKey key(id, client_id);
DCHECK(io_surfaces_.find(key) == io_surfaces_.end());
io_surfaces_[key] = io_surface;
}
gfx::GpuMemoryBufferHandle handle;
handle.type = gfx::IO_SURFACE_BUFFER;
handle.id = id;
handle.io_surface_id = IOSurfaceGetID(io_surface);
return handle;
}
void GpuMemoryBufferFactoryIOSurface::DestroyGpuMemoryBuffer(
gfx::GpuMemoryBufferId id,
int client_id) {
base::AutoLock lock(io_surfaces_lock_);
IOSurfaceMapKey key(id, client_id);
IOSurfaceMap::iterator it = io_surfaces_.find(key);
if (it != io_surfaces_.end())
io_surfaces_.erase(it);
}
gpu::ImageFactory* GpuMemoryBufferFactoryIOSurface::AsImageFactory() {
return this;
}
scoped_refptr<gfx::GLImage>
GpuMemoryBufferFactoryIOSurface::CreateImageForGpuMemoryBuffer(
const gfx::GpuMemoryBufferHandle& handle,
const gfx::Size& size,
gfx::GpuMemoryBuffer::Format format,
unsigned internalformat,
int client_id) {
base::AutoLock lock(io_surfaces_lock_);
DCHECK_EQ(handle.type, gfx::IO_SURFACE_BUFFER);
IOSurfaceMapKey key(handle.id, client_id);
IOSurfaceMap::iterator it = io_surfaces_.find(key);
if (it == io_surfaces_.end())
return scoped_refptr<gfx::GLImage>();
scoped_refptr<gfx::GLImageIOSurface> image(new gfx::GLImageIOSurface(size));
if (!image->Initialize(it->second.get()))
return scoped_refptr<gfx::GLImage>();
return image;
}
} // namespace content
| [
"scottmg@chromium.org"
] | scottmg@chromium.org |
118ac504d5c107eaf514b219f9544a0659452250 | 0e9f1350ea9b336f61ca4bfa83b189382a9bc068 | /src/Storage.h | d3b834ae942872dc413ff8bb8aa930dbd81d1900 | [] | no_license | LestherSK/Arduino-Storage | 8a9bedb5bacc8a7b235a979213db7e13018e6f3d | a86a4fbe17c7562b0d3b18a73b572803bd605e30 | refs/heads/master | 2020-04-14T06:06:23.332173 | 2017-10-14T01:11:47 | 2017-10-14T01:11:47 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 10,435 | h | /**
* @file Storage.h
* @version 1.0
*
* @section License
* Copyright (C) 2017, Mikael Patel
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library 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.
*/
#ifndef STORAGE_H
#define STORAGE_H
/**
* External memory storage interface, data block read/write, caching
* and streaming class. Handles linear allocation of storage blocks on
* the device.
*/
class Storage {
public:
/** Number of bytes on device. */
const uint32_t SIZE;
/**
* Create storage manager with given number of bytes.
* @param[in] size number of bytes on device.
*/
Storage(uint32_t size) : SIZE(size), m_addr(0) {}
/**
* Returns number of bytes that may be allocated.
* @return number of bytes.
*/
uint32_t room()
{
return (SIZE - m_addr);
}
/**
* Allocate block with given number of bytes on storage. Returns
* storage address if successful otherwise UINT32_MAX.
* @param[in] count number of bytes.
* @return address of allocated block, otherwise UINT32_MAX.
*/
uint32_t alloc(size_t count)
{
if (count > room()) return (UINT32_MAX);
uint32_t res = m_addr;
m_addr += count;
return (res);
}
/**
* Reset allocation point to given address.
* @param[in] addr address of allocated block.
*/
void free(uint32_t addr)
{
if (addr < m_addr) m_addr = addr;
}
/**
* Read count number of bytes from storage address to
* buffer. Returns number of bytes read or negative error code.
* @param[in] dest destination buffer pointer.
* @param[in] src source memory address on device.
* @param[in] count number of bytes to read from device.
* @return number of bytes read or negative error code.
*/
virtual int read(void* dest, uint32_t src, size_t count) = 0;
/**
* Write count number of bytes to storage address from
* buffer. Returns number of bytes read or negative error code.
* @param[in] dest destination memory address on device.
* @param[in] src source buffer pointer.
* @param[in] count number of bytes to write to device.
* @return number of bytes written or negative error code.
*/
virtual int write(uint32_t dest, const void* src, size_t count) = 0;
/**
* Allocated block of memory on storage.
*/
class Block {
public:
/**
* Construct block with given size on given storage device.
* @param[in] mem storage device for block.
* @param[in] size number of bytes.
*/
Block(Storage &mem, uint32_t size) :
SIZE(size),
m_mem(mem),
m_addr(m_mem.alloc(size))
{
}
/**
* Destruct block and free allocated memory on storage device.
*/
~Block()
{
m_mem.free(m_addr);
}
/**
* Returns storage address for the memory block.
* @return address.
*/
uint32_t addr()
{
return (m_addr);
}
/**
* Read given number of bytes from offset within block to given
* buffer. Returns number of bytes read or negative error code.
* @param[in] buf buffer pointer.
* @param[in] offset offset within block.
* @param[in] size number of bytes to read.
* @return number of bytes read or negative error code.
*/
int read(void* buf, uint32_t offset, size_t size)
{
if (offset + size <= SIZE)
return (m_mem.read(buf, m_addr + offset, size));
return (-1);
}
/**
* Write given number of bytes from buffer to given offset
* within block. Returns number of bytes written or negative error
* code.
* @param[in] buf buffer pointer.
* @param[in] offset offset within block.
* @param[in] size number of bytes to write.
* @return number of bytes written or negative error code.
*/
int write(uint32_t offset, const void* buf, size_t size)
{
if (offset + size <= SIZE)
return (m_mem.write(m_addr + offset, buf, size));
return (-1);
}
/** Size of memory block. */
const uint32_t SIZE;
protected:
/** Storage device from memory block. */
Storage& m_mem;
/** Address on storage device. */
const uint32_t m_addr;
};
/**
* Storage Cache for data; temporary or persistent external storage
* of data with local memory copy. Allows element access of vectors
* on external storage.
*/
class Cache : public Block {
public:
/**
* Construct cached block on given storage device with the given
* local buffer, member size and number of members. Storage is
* allocated on the device for the total storage of the
* members. The buffer is assumed to only hold a single member.
* @param[in] mem storage device for block.
* @param[in] buf buffer address.
* @param[in] size number of bytes per member.
* @param[in] nmemb number of members (default 1).
*/
Cache(Storage &mem, void* buf, size_t size, size_t nmemb = 1) :
Block(mem, size * nmemb),
MSIZE(size),
NMEMB(nmemb),
m_buf(buf)
{
}
/**
* Returns storage address for the indexed storage block.
* @param[in] ix member index (default 0):
* @return address.
*/
uint32_t addr(size_t ix = 0)
{
if (ix == 0)
return (m_addr);
if (ix < NMEMB)
return (m_addr + (ix * MSIZE));
return (UINT32_MAX);
}
/**
* Read indexed storage block to buffer. Default index is the
* first member. Returns number of bytes read or negative error
* code.
* @param[in] ix member index (default 0):
* @return number of bytes read or negative error code.
*/
int read(size_t ix = 0)
{
if (ix == 0)
return (m_mem.read(m_buf, m_addr, MSIZE));
if (ix < NMEMB)
return (m_mem.read(m_buf, m_addr + (ix * MSIZE), MSIZE));
return (-1);
}
/**
* Write buffer to indexed storage block. Default index is the
* first member. Returns number of bytes written or negative error
* code.
* @param[in] ix member index (default 0):
* @return number of bytes written or negative error code.
*/
int write(size_t ix = 0)
{
if (ix == 0)
return (m_mem.write(m_addr, m_buf, MSIZE));
if (ix < NMEMB)
return (m_mem.write(m_addr + (ix * MSIZE), m_buf, MSIZE));
return (-1);
}
/** Size of member. */
const size_t MSIZE;
/** Number of members. */
const size_t NMEMB;
protected:
/** Buffer for data. */
void* m_buf;
};
/**
* Stream of given size on given storage. Write/print intermediate
* data to the stream that may later be read and transfered.
* Multiple stream may be created on the same device.
*/
class Stream : public ::Stream {
public:
/**
* Construct stream on given storage device with the given size.
* @param[in] mem storage device for stream.
* @param[in] size number of bytes in stream.
*/
Stream(Storage &mem, size_t size) :
SIZE(size),
m_mem(mem),
m_addr(m_mem.alloc(size)),
m_put(0),
m_get(0),
m_count(0)
{
}
/**
* Returns storage address for stream.
* @return address.
*/
uint32_t addr()
{
return (m_addr);
}
/**
* @override{Stream}
* Write given byte to stream. Return number of bytes written,
* zero if full.
* @param[in] byte to write.
* @return number of bytes written(1).
*/
virtual size_t write(uint8_t byte)
{
if (m_count == SIZE) return (0);
m_mem.write(m_addr + m_put, &byte, sizeof(byte));
m_count += 1;
m_put += 1;
if (m_put == SIZE) m_put = 0;
return (sizeof(byte));
}
/**
* @override{Stream}
* Write given buffer and number of bytes to stream. Return number
* of bytes written, or zero if stream is full.
* @param[in] buffer to write.
* @param[in] size number of byets to write.
* @return number of bytes.
*/
virtual size_t write(const uint8_t *buffer, size_t size)
{
uint16_t room = SIZE - m_count;
if (room == 0) return (0);
if (size > room) size = room;
size_t res = size;
room = SIZE - m_put;
if (size > room) {
m_mem.write(m_addr + m_put, buffer, room);
buffer += room;
size -= room;
m_count += room;
m_put = 0;
}
m_mem.write(m_addr + m_put, buffer, size);
m_count += size;
m_put += size;
return (res);
}
/**
* @override{Stream}
* Returns number of bytes available for read().
* @return bytes available.
*/
virtual int available()
{
return (m_count);
}
/**
* @override{Stream}
* Return next byte in stream (without removing) if available
* otherwise negative error code(-1).
* @return next byte or negative error code.
*/
virtual int peek()
{
if (m_count == 0) return (-1);
uint8_t res = 0;
m_mem.read(&res, m_addr + m_get, sizeof(res));
return (res);
}
/**
* @override{Stream}
* Return next byte if available otherwise negative error
* code(-1).
* @return next byte or negative error code.
*/
virtual int read()
{
if (m_count == 0) return (-1);
uint8_t res = 0;
m_mem.read(&res, m_addr + m_get, sizeof(res));
m_count -= 1;
m_get += 1;
if (m_get == SIZE) m_get = 0;
return (res);
}
/**
* @override{Stream}
* Flush all data and reset stream.
*/
virtual void flush()
{
m_put = 0;
m_get = 0;
m_count = 0;
}
/** Total size of the stream. */
size_t SIZE;
protected:
/** Storage device for the stream. */
Storage& m_mem;
/** Address on storage for the stream data. */
const uint32_t m_addr;
/** Index for the next write. */
uint16_t m_put;
/** Index for the next read/peek. */
uint16_t m_get;
/** Number of bytes available. */
uint16_t m_count;
};
protected:
/** Address of the next allocation. */
uint32_t m_addr;
};
#endif
| [
"mikael.patel@gmail.com"
] | mikael.patel@gmail.com |
ad50543da6393fc1964570fd18311a9aea967807 | fc38a55144a0ad33bd94301e2d06abd65bd2da3c | /thirdparty/cgal/CGAL-4.13/include/CGAL/point_generators_3.h | 7e83b1dab3cc522e98d1b480048ea210648ae673 | [
"MIT",
"LicenseRef-scancode-free-unknown",
"LGPL-2.0-or-later",
"LGPL-3.0-or-later",
"GPL-1.0-or-later",
"LicenseRef-scancode-warranty-disclaimer",
"LicenseRef-scancode-commercial-license",
"LGPL-3.0-only",
"GPL-3.0-only",
"LGPL-2.1-or-later",
"LicenseRef-scancode-proprietary-license",
"Licens... | permissive | bobpepin/dust3d | 20fc2fa4380865bc6376724f0843100accd4b08d | 6dcc6b1675cb49ef3fac4a58845f9c9025aa4c9f | refs/heads/master | 2022-11-30T06:00:10.020207 | 2020-08-09T09:54:29 | 2020-08-09T09:54:29 | 286,051,200 | 0 | 0 | MIT | 2020-08-08T13:45:15 | 2020-08-08T13:45:14 | null | UTF-8 | C++ | false | false | 26,348 | h | // Copyright (c) 1997
// Utrecht University (The Netherlands),
// ETH Zurich (Switzerland),
// INRIA Sophia-Antipolis (France),
// Max-Planck-Institute Saarbruecken (Germany),
// and Tel-Aviv University (Israel). All rights reserved.
//
// This file is part of CGAL (www.cgal.org); 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.
//
// Licensees holding a valid commercial license may use this file in
// accordance with the commercial license agreement provided with the software.
//
// This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
// WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
//
// $URL$
// $Id$
// SPDX-License-Identifier: LGPL-3.0+
//
//
// Author(s) : Lutz Kettner <kettner@inf.ethz.ch>
// Pedro Machado Manhaes de Castro <pmmc@cin.ufpe.br>
// Alexandru Tifrea
// Maxime Gimeno
#ifndef CGAL_POINT_GENERATORS_3_H
#define CGAL_POINT_GENERATORS_3_H 1
#include <CGAL/disable_warnings.h>
#include <CGAL/generators.h>
#include <CGAL/point_generators_2.h>
#include <CGAL/number_type_basic.h>
#include <CGAL/internal/Generic_random_point_generator.h>
#include <CGAL/boost/graph/property_maps.h>
namespace CGAL {
template < class P, class Creator =
Creator_uniform_3<typename Kernel_traits<P>::Kernel::RT,P> >
class Random_points_in_sphere_3 : public Random_generator_base<P> {
void generate_point();
public:
typedef Random_points_in_sphere_3<P,Creator> This;
Random_points_in_sphere_3( double r = 1, Random& rnd = CGAL::get_default_random())
// g is an input iterator creating points of type `P' uniformly
// distributed in the open sphere with radius r, i.e. |`*g'| < r .
// Three random numbers are needed from `rnd' for each point
: Random_generator_base<P>( r, rnd) { generate_point(); }
This& operator++() {
generate_point();
return *this;
}
This operator++(int) {
This tmp = *this;
++(*this);
return tmp;
}
};
template < class P, class Creator >
void
Random_points_in_sphere_3<P,Creator>::
generate_point() {
// A strip between z and z+dz has an area independant of z
typedef typename Creator::argument_type T;
double alpha = this->_rnd.get_double() * 2.0 * CGAL_PI;
double z = 2 * this->_rnd.get_double() - 1.0;
double r = std::sqrt( 1 - z * z);
r *= std::pow( this->_rnd.get_double() , 1.0/3.0 );
Creator creator;
this->d_item = creator( T(this->d_range * r * std::cos(alpha)),
T(this->d_range * r * std::sin(alpha)),
T(this->d_range * z));
}
template < class P, class Creator =
Creator_uniform_3<typename Kernel_traits<P>::Kernel::RT,P> >
class Random_points_on_sphere_3 : public Random_generator_base<P> {
void generate_point();
public:
typedef Random_points_on_sphere_3<P,Creator> This;
Random_points_on_sphere_3( double r = 1, Random& rnd = CGAL::get_default_random())
// g is an input iterator creating points of type `P' uniformly
// distributed on the sphere with radius r, i.e. |`*g'| == r . A
// two random numbers are needed from `rnd' for each point.
: Random_generator_base<P>( r, rnd) { generate_point(); }
This& operator++() {
generate_point();
return *this;
}
This operator++(int) {
This tmp = *this;
++(*this);
return tmp;
}
};
template < class P, class Creator >
void
Random_points_on_sphere_3<P,Creator>::
generate_point() {
// A strip between z and z+dz has an area independant of z
typedef typename Creator::argument_type T;
double alpha = this->_rnd.get_double() * 2.0 * CGAL_PI;
double z = 2 * this->_rnd.get_double() - 1.0;
double r = std::sqrt( 1 - z * z);
Creator creator;
this->d_item = creator( T(this->d_range * r * std::cos(alpha)),
T(this->d_range * r * std::sin(alpha)),
T(this->d_range * z));
}
template < class P, class Creator =
Creator_uniform_3<typename Kernel_traits<P>::Kernel::RT,P> >
class Random_points_in_cube_3 : public Random_generator_base<P>{
void generate_point();
public:
typedef Random_points_in_cube_3<P,Creator> This;
Random_points_in_cube_3( double a = 1, Random& rnd = CGAL::get_default_random())
: Random_generator_base<P>( a, rnd) { generate_point(); }
This& operator++() {
generate_point();
return *this;
}
This operator++(int) {
This tmp = *this;
++(*this);
return tmp;
}
};
template < class P, class Creator >
void
Random_points_in_cube_3<P,Creator>::
generate_point() {
typedef typename Creator::argument_type T;
Creator creator;
this->d_item =
creator( T(this->d_range * ( 2 * this->_rnd.get_double() - 1.0)),
T(this->d_range * ( 2 * this->_rnd.get_double() - 1.0)),
T(this->d_range * ( 2 * this->_rnd.get_double() - 1.0)));
}
template <class OutputIterator, class Creator>
OutputIterator
points_on_cube_grid_3( double a, std::size_t n,
OutputIterator o, Creator creator)
{
if (n == 0)
return o;
int m = int(std::ceil(
std::sqrt(std::sqrt(static_cast<double>(n)))));
while (m*m*m < int(n)) m++;
double base = -a; // Left and bottom boundary.
double step = 2*a/(m-1);
int j = 0;
int k = 0;
double px = base;
double py = base;
double pz = base;
*o++ = creator( px, py, pz);
for (std::size_t i = 1; i < n; i++) {
j++;
if ( j == m) {
k++;
if ( k == m) {
py = base;
px = base;
pz = pz + step;
k = 0;
}
else {
px = base;
py = py + step;
}
j = 0;
} else {
px = px + step;
}
*o++ = creator( px, py, pz);
}
return o;
}
template <class OutputIterator>
OutputIterator
points_on_cube_grid_3( double a, std::size_t n, OutputIterator o)
{
typedef std::iterator_traits<OutputIterator> ITraits;
typedef typename ITraits::value_type P;
return points_on_square_grid_3(a, n, o,
Creator_uniform_3<typename Kernel_traits<P>::Kernel::RT,P>());
}
template < class P, class Creator =
Creator_uniform_3<typename Kernel_traits<P>::Kernel::RT,P> >
class Random_points_in_triangle_3 : public Random_generator_base<P> {
P _p,_q,_r;
void generate_point();
public:
typedef P result_type;
typedef Random_points_in_triangle_3<P, Creator> This;
typedef typename Kernel_traits<P>::Kernel::Triangle_3 Triangle_3;
Random_points_in_triangle_3() {}
Random_points_in_triangle_3( const This& x,Random& rnd)
: Random_generator_base<P>( 1, rnd ),_p(x._p),_q(x._q),_r(x._r) {
generate_point();
}
Random_points_in_triangle_3( const P& p, const P& q, const P& r, Random& rnd = get_default_random())
: Random_generator_base<P>( 1, rnd ),_p(p),_q(q),_r(r) {
generate_point();
}
Random_points_in_triangle_3( const Triangle_3& triangle,Random& rnd = get_default_random())
: Random_generator_base<P>( 1,
rnd),_p(triangle[0]),_q(triangle[1]),_r(triangle[2]) {
generate_point();
}
This& operator++() {
generate_point();
return *this;
}
This operator++(int) {
This tmp = *this;
++(*this);
return tmp;
}
};
template<class P, class Creator >
void Random_points_in_triangle_3<P, Creator>::generate_point() {
typedef typename Creator::argument_type T;
Creator creator;
double a1 = this->_rnd.get_double(0,1);
double a2 = this->_rnd.get_double(0,1);
if(a1>a2) std::swap(a1,a2);
double b1 = a1;
double b2 = a2-a1;
double b3 = 1.0-a2;
T ret[3];
for(int i = 0; i < 3; ++i) {
ret[i] = T(to_double(_p[i])*b1+to_double(_q[i])*b2+to_double(_r[i])*b3);
}
this->d_item = creator(ret[0],ret[1],ret[2]);
}
template < class P, class Creator =
Creator_uniform_3<typename Kernel_traits<P>::Kernel::RT,P> >
class Random_points_on_segment_3 : public Random_generator_base<P> {
P _p;
P _q;
void generate_point();
public:
typedef Random_points_on_segment_3<P,Creator> This;
Random_points_on_segment_3() {}
Random_points_on_segment_3( const P& p,
const P& q,
Random& rnd = CGAL::get_default_random())
// g is an input iterator creating points of type `P' uniformly
// distributed on the segment from p to q except q, i.e. `*g' ==
// \lambda p + (1-\lambda)\, q where 0 <= \lambda < 1 . A single
// random number is needed from `rnd' for each point.
: Random_generator_base<P>( (std::max)( (std::max)( (std::max)(to_double(p.x()), to_double(q.x())),
(std::max)(to_double(p.y()), to_double(q.y()))),
(std::max)(to_double(p.z()), to_double(q.z()))),
rnd) , _p(p), _q(q)
{
generate_point();
}
template <class Segment_3>
Random_points_on_segment_3( const Segment_3& s,
Random& rnd = CGAL::get_default_random())
// g is an input iterator creating points of type `P' uniformly
// distributed on the segment from p to q except q, i.e. `*g' ==
// \lambda p + (1-\lambda)\, q where 0 <= \lambda < 1 . A single
// random number is needed from `rnd' for each point.
: Random_generator_base<P>( (std::max)( (std::max)( (std::max)(to_double(s[0].x()), to_double(s[1].x())),
(std::max)(to_double(s[0].y()), to_double(s[1].y()))),
(std::max)(to_double(s[0].z()), to_double(s[1].z()))),
rnd) , _p(s[0]), _q(s[1])
{
generate_point();
}
const P& source() const { return _p; }
const P& target() const { return _q; }
This& operator++() {
generate_point();
return *this;
}
This operator++(int) {
This tmp = *this;
++(*this);
return tmp;
}
};
template < class P, class Creator >
void
Random_points_on_segment_3<P,Creator>::
generate_point() {
typedef typename Creator::argument_type T;
double la = this->_rnd.get_double();
double mu = 1.0 - la;
Creator creator;
this->d_item = creator(T(mu * to_double(_p.x()) + la * to_double(_q.x())),
T(mu * to_double(_p.y()) + la * to_double(_q.y())),
T(mu * to_double(_p.z()) + la * to_double(_q.z())));
}
template < class P, class Creator =
Creator_uniform_3<typename Kernel_traits<P>::Kernel::RT,P> >
class Random_points_in_tetrahedron_3 : public Random_generator_base<P> {
P _p,_q,_r,_s;
void generate_point();
public:
typedef P result_type;
typedef Random_points_in_tetrahedron_3<P, Creator> This;
typedef typename Kernel_traits<P>::Kernel::Tetrahedron_3 Tetrahedron_3;
Random_points_in_tetrahedron_3() {}
Random_points_in_tetrahedron_3( const This& x,Random& rnd)
: Random_generator_base<P>( 1, rnd ),_p(x._p),_q(x._q),_r(x._r),_s(x._s) {
generate_point();
}
Random_points_in_tetrahedron_3( const P& p, const P& q, const P& r, const P& s,Random& rnd = get_default_random())
: Random_generator_base<P>( 1, rnd ),_p(p),_q(q),_r(r),_s(s) {
generate_point();
}
Random_points_in_tetrahedron_3( const Tetrahedron_3& tetrahedron,Random& rnd = get_default_random())
: Random_generator_base<P>( 1, rnd),_p(tetrahedron[0]),_q(tetrahedron[1]),_r(tetrahedron[2]),_s(tetrahedron[3]) {
generate_point();
}
This& operator++() {
generate_point();
return *this;
}
This operator++(int) {
This tmp = *this;
++(*this);
return tmp;
}
};
template<class P, class Creator >
void Random_points_in_tetrahedron_3<P, Creator>::generate_point() {
typedef typename Creator::argument_type T;
Creator creator;
double a[3];
for(int i = 0; i < 3; ++i) {
a[i]=this->_rnd.get_double(0,1);
}
std::sort(a,a+3);
double b[4];
b[0]=a[0];
b[1]=a[1]-a[0];
b[2]=a[2]-a[1];
b[3]=1.0-a[2];
T ret[3];
for(int i = 0; i < 3; ++i) {
ret[i] = T(to_double(_p[i])*b[0]+to_double(_q[i])*b[1]+to_double(_r[i])*b[2]+to_double(_s[i])*b[3]);
}
this->d_item = creator(ret[0],ret[1],ret[2]);
}
template <class TriangleMesh,
class VertexPointMap = typename boost::property_map<TriangleMesh,
CGAL::vertex_point_t>::const_type,
class Creator = Creator_uniform_3<
typename Kernel_traits< typename boost::property_traits<VertexPointMap>::value_type >::Kernel::RT,
typename boost::property_traits<VertexPointMap>::value_type >
>
struct Random_points_in_triangle_mesh_3
: public Generic_random_point_generator<
typename boost::graph_traits <TriangleMesh>::face_descriptor ,
CGAL::Property_map_to_unary_function<CGAL::Triangle_from_face_descriptor_map<
TriangleMesh, VertexPointMap > >,
Random_points_in_triangle_3<typename boost::property_traits<VertexPointMap>::value_type, Creator>,
typename boost::property_traits<VertexPointMap>::value_type>
{
typedef typename boost::property_traits<VertexPointMap>::value_type P;
typedef Generic_random_point_generator<
typename boost::graph_traits <TriangleMesh>::face_descriptor ,
CGAL::Property_map_to_unary_function<CGAL::Triangle_from_face_descriptor_map<
TriangleMesh,VertexPointMap> >,
Random_points_in_triangle_3<P, Creator> , P> Base;
typedef typename CGAL::Triangle_from_face_descriptor_map<
TriangleMesh,VertexPointMap> Object_from_id;
typedef typename boost::graph_traits<TriangleMesh>::face_descriptor Id;
typedef P result_type;
typedef Random_points_in_triangle_mesh_3< TriangleMesh, VertexPointMap, Creator> This;
Random_points_in_triangle_mesh_3( const TriangleMesh& mesh,Random& rnd = get_default_random())
: Base( faces(mesh),
CGAL::Property_map_to_unary_function<Object_from_id>(Object_from_id(&mesh, get(vertex_point, mesh))),
internal::Apply_approx_sqrt<typename Kernel_traits<P>::Kernel::Compute_squared_area_3>(),
rnd )
{
}
Random_points_in_triangle_mesh_3( const TriangleMesh& mesh, VertexPointMap vpm, Random& rnd = get_default_random())
: Base( faces(mesh),
CGAL::Property_map_to_unary_function<Object_from_id>(Object_from_id(&mesh, vpm)),
internal::Apply_approx_sqrt<typename Kernel_traits<P>::Kernel::Compute_squared_area_3>(),
rnd )
{
}
This& operator++() {
Base::generate_point();
return *this;
}
This operator++(int) {
This tmp = *this;
++(*this);
return tmp;
}
double mesh_area() const
{
return this->sum_of_weights();
}
};
template <class EdgeListGraph,
class VertexPointMap = typename boost::property_map<EdgeListGraph,
CGAL::vertex_point_t>::const_type,
class Creator = Creator_uniform_3<
typename Kernel_traits< typename boost::property_traits<VertexPointMap>::value_type >::Kernel::RT,
typename boost::property_traits<VertexPointMap>::value_type >
>
struct Random_points_on_edge_list_graph_3
: public Generic_random_point_generator<
typename boost::graph_traits <EdgeListGraph>::edge_descriptor,
CGAL::Property_map_to_unary_function<CGAL::Segment_from_edge_descriptor_map<
EdgeListGraph, VertexPointMap > >,
Random_points_on_segment_3<typename boost::property_traits<VertexPointMap>::value_type, Creator>,
typename boost::property_traits<VertexPointMap>::value_type>
{
typedef typename boost::property_traits<VertexPointMap>::value_type P;
typedef Generic_random_point_generator<
typename boost::graph_traits <EdgeListGraph>::edge_descriptor,
CGAL::Property_map_to_unary_function<CGAL::Segment_from_edge_descriptor_map<
EdgeListGraph, VertexPointMap > >,
Random_points_on_segment_3<P, Creator> , P> Base;
typedef typename CGAL::Segment_from_edge_descriptor_map<
EdgeListGraph,VertexPointMap> Object_from_id;
typedef typename boost::graph_traits<EdgeListGraph>::edge_descriptor Id;
typedef P result_type;
typedef Random_points_on_edge_list_graph_3< EdgeListGraph, VertexPointMap, Creator> This;
Random_points_on_edge_list_graph_3( const EdgeListGraph& mesh,Random& rnd = get_default_random())
: Base( edges(mesh),
CGAL::Property_map_to_unary_function<Object_from_id>(Object_from_id(&mesh, get(vertex_point, mesh))),
internal::Apply_approx_sqrt<typename Kernel_traits<P>::Kernel::Compute_squared_length_3>(),
rnd )
{
}
Random_points_on_edge_list_graph_3( const EdgeListGraph& mesh, VertexPointMap vpm, Random& rnd = get_default_random())
: Base( edges(mesh),
CGAL::Property_map_to_unary_function<Object_from_id>(Object_from_id(&mesh, vpm)),
internal::Apply_approx_sqrt<typename Kernel_traits<P>::Kernel::Compute_squared_length_3>(),
rnd )
{
}
This& operator++() {
Base::generate_point();
return *this;
}
This operator++(int) {
This tmp = *this;
++(*this);
return tmp;
}
double mesh_length() const
{
return this->sum_of_weights();
}
};
namespace internal
{
template<class C3T3>
class Triangle_from_c3t3_facet
{
typedef typename C3T3::Triangulation Tr;
typedef typename Tr::Bare_point Bare_point;
typedef typename Tr::Triangle Triangle;
typedef typename Tr::Facet Facet;
typedef typename Tr::Cell_handle Cell_handle;
public:
typedef Triangle result_type;
Triangle_from_c3t3_facet(const C3T3& c3t3) : tr(c3t3.triangulation()) { }
Triangle operator()(const Facet& facet)const
{
Cell_handle cell = facet.first;
int index = facet.second;
typename Tr::Geom_traits::Construct_point_3 wp2p =
tr.geom_traits().construct_point_3_object();
const Bare_point& pa = wp2p(tr.point(cell, (index+1)&3));
const Bare_point& pb = wp2p(tr.point(cell, (index+2)&3));
const Bare_point& pc = wp2p(tr.point(cell, (index+3)&3));
return Triangle(pa, pb, pc);
}
const Tr& tr;
};
template<class C3T3>
class Tetrahedron_from_c3t3_cell
{
typedef typename C3T3::Triangulation Tr;
typedef typename Tr::Cell_handle Cell;
typedef typename Tr::Bare_point Bare_point;
typedef typename Tr::Tetrahedron Tetrahedron;
public:
typedef Tetrahedron result_type;
Tetrahedron_from_c3t3_cell(const C3T3& c3t3) : tr(c3t3.triangulation()) { }
Tetrahedron operator()(const Cell cell)const
{
typename Tr::Geom_traits::Construct_point_3 wp2p =
tr.geom_traits().construct_point_3_object();
const Bare_point& p0 = wp2p(tr.point(cell, 0));
const Bare_point& p1 = wp2p(tr.point(cell, 1));
const Bare_point& p2 = wp2p(tr.point(cell, 2));
const Bare_point& p3 = wp2p(tr.point(cell, 3));
return Tetrahedron(p0, p1, p2, p3);
}
const Tr& tr;
};
}//end namespace internal
template <class C3t3,
class Creator = Creator_uniform_3<
typename Kernel_traits<
typename C3t3::Triangulation::Point_3 >::Kernel::RT,
typename C3t3::Triangulation::Point_3 >
>
class Random_points_in_tetrahedral_mesh_boundary_3
: public Generic_random_point_generator<
typename C3t3::Triangulation::Facet,
internal::Triangle_from_c3t3_facet<C3t3>,
Random_points_in_triangle_3<typename C3t3::Triangulation::Point_3>,
typename C3t3::Triangulation::Point_3>
{
typedef Random_points_in_tetrahedral_mesh_boundary_3<C3t3, Creator> This;
public:
typedef typename C3t3::Triangulation Tr;
typedef typename Tr::Point_3 Point_3;
typedef typename Tr::Facet Facet;
typedef typename Tr::Cell_handle Cell_handle;
typedef Generic_random_point_generator<
Facet, internal::Triangle_from_c3t3_facet<C3t3>,
Random_points_in_triangle_3<Point_3, Creator>,
Point_3> Base;
typedef Facet Id;
typedef Point_3 result_type;
typedef typename Kernel_traits<Point_3>::Kernel K;
typedef typename K::Compute_squared_area_3 Compute_squared_area_3;
typedef typename internal::Apply_approx_sqrt<Compute_squared_area_3>
Compute_squared_area_3_with_approx_sqrt;
Random_points_in_tetrahedral_mesh_boundary_3(const C3t3& c3t3,
Random& rnd = get_default_random())
: Base( make_range( c3t3.facets_in_complex_begin(),
c3t3.facets_in_complex_end() ),
internal::Triangle_from_c3t3_facet<C3t3>(c3t3),
Compute_squared_area_3_with_approx_sqrt(),
rnd )
{
}
This& operator++() {
Base::generate_point();
return *this;
}
This operator++(int) {
This tmp = *this;
++(*this);
return tmp;
}
};
template <class C3t3,
class Creator = Creator_uniform_3<
typename Kernel_traits<
typename C3t3::Triangulation::Point_3 >::Kernel::RT,
typename C3t3::Triangulation::Point_3 >
>
class Random_points_in_tetrahedral_mesh_3
: public Generic_random_point_generator<
typename C3t3::Triangulation::Cell_handle,
internal::Tetrahedron_from_c3t3_cell<C3t3>,
Random_points_in_tetrahedron_3<
typename C3t3::Triangulation::Point_3>,
typename C3t3::Triangulation::Point_3>
{
typedef Random_points_in_tetrahedral_mesh_3<C3t3, Creator> This;
public:
typedef typename C3t3::Triangulation Tr;
typedef typename Tr::Point_3 Point_3;
typedef typename Tr::Cell_handle Cell_handle;
typedef Generic_random_point_generator<Cell_handle,
internal::Tetrahedron_from_c3t3_cell<C3t3>,
Random_points_in_tetrahedron_3<Point_3, Creator>,
Point_3> Base;
typedef Cell_handle Id;
typedef Point_3 result_type;
typedef typename Kernel_traits<Point_3>::Kernel K;
typedef typename K::Compute_volume_3 Compute_volume_3;
Random_points_in_tetrahedral_mesh_3(const C3t3& c3t3,
Random& rnd = get_default_random())
: Base( CGAL::make_prevent_deref_range(c3t3.cells_in_complex_begin(),
c3t3.cells_in_complex_end() ),
internal::Tetrahedron_from_c3t3_cell<C3t3>(c3t3),
Compute_volume_3(),
rnd )
{
}
This& operator++() {
Base::generate_point();
return *this;
}
This operator++(int) {
This tmp = *this;
++(*this);
return tmp;
}
};
template <class Point_3,
class Triangle_3=typename Kernel_traits<Point_3>::Kernel::Triangle_3,
class Creator = Creator_uniform_3<
typename Kernel_traits< Point_3 >::Kernel::RT,
Point_3 >
>
struct Random_points_in_triangles_3
: public Generic_random_point_generator<const Triangle_3*,
internal::Deref<Triangle_3>,
Random_points_in_triangle_3<Point_3>,
Point_3>
{
typedef Generic_random_point_generator<const Triangle_3*,
internal::Deref<Triangle_3>,
Random_points_in_triangle_3<Point_3, Creator>,
Point_3> Base;
typedef const Triangle_3* Id;
typedef Point_3 result_type;
typedef Random_points_in_triangles_3<Point_3, Triangle_3, Creator> This;
template<typename TriangleRange>
Random_points_in_triangles_3( const TriangleRange& triangles, Random& rnd = get_default_random())
: Base(make_range( boost::make_transform_iterator(triangles.begin(), internal::Address_of<Triangle_3>()),
boost::make_transform_iterator(triangles.end(), internal::Address_of<Triangle_3>()) ),
internal::Deref<Triangle_3>(),
internal::Apply_approx_sqrt<typename Kernel_traits<Point_3>::Kernel::Compute_squared_area_3>()
,rnd )
{
}
This& operator++() {
Base::generate_point();
return *this;
}
This operator++(int) {
This tmp = *this;
++(*this);
return tmp;
}
};
} //namespace CGAL
#include <CGAL/enable_warnings.h>
#endif // CGAL_POINT_GENERATORS_3_H //
// EOF //
| [
"huxingyi@msn.com"
] | huxingyi@msn.com |
734c5b7a6809e0eb8b6c7542d0e39960939c0a38 | 662ce8117e08effde0ca3abe881b939699a28879 | /数据结构/01线性表/2_2_3_综合应用.cpp | ea5979610b86a2cfd39f7b6209abfdcae9854063 | [] | no_license | XXXYYYZZZLB/Notes-on-learning-programming | d47d4e6c81e51cf197907028c098530d963a6c99 | ca244b7e7f714521375e2a9715c01ea8fa04c68b | refs/heads/main | 2023-03-14T13:23:46.828259 | 2021-03-08T01:51:02 | 2021-03-08T01:51:02 | 341,437,764 | 1 | 0 | null | null | null | null | GB18030 | C++ | false | false | 1,755 | cpp | //2.2.3-综合应用题
// 1
bool ListDeleteMin(SqList &L,int &e){
if(L.length==0) return false;
e=L.data[0];
int index=0;
for(int i=0;i<L.length;i++){
if(e>L.data[i]){
index=i;
}
}
L.data[i]=L.data[L.length-1];
L.length--;
return true;
}
// 2
//循环n/2,时间复杂度是O(1)
void ReverseList(SqList &L){
for(int i=0;i<L.length;i++){
int temp=L.data[L.length-i-1];
L.data[L.length-i-1]=L.data[i];
L.data[i]=temp;
}
}
// 3
void DeleteListElem(SqList &L,int e){
int j=0;
for(int i=0;i<L.length;i++){
if(L.data[i]!=e){
L.data[j]=L.data[i];
j++
}
}
L.length=j;
}
// 4
bool DeleteListAtoB(SqList &L,int a,int b){
if(a>=b||L.length==0) return false;
int index=0;
for(int i=0;i<L.length;i++){
if(L.data[i]>=b||L.data[i]<=a){
L.data[index]=L.data[i];
index++;
}
}
L.length=index;
return true;
}
// 5
bool DeleteListAtoB(SqList &L,int a,int b){
if(a>=b||L.length==0) return false;
int index=0;
for(int i=0;i<L.length;i++){
if(L.data[i]>b||L.data[i]<a){
L.data[index]=L.data[i];
index++;
}
}
L.length=index;
return true;
}
// 6(有序顺序表)
void ListDuplicateRemoval(SqList &L){
int index=0;
for(int i=1;i<L.length;i++){
if(L.data[index]!=L.data[i]){
L.data[index]=L.data[i];
index++;
}
}
L.length=index;
}
// 7
bool ListSum(SqList A,SqList B,SqList &C){
if(A.length+B.length>C.MaxSize) return false;
int i,j,k=0;
while(i<A.length&&j<B.length){
if(A.data[i]<=B.data[j]){
C.data[k++]=A.data[i++];
}else{
C.data[k++]=B.data[j++];
}
}
//如果还有没比完的就都添加
while(i<A.length){
C.data[k++]=A.data[i++];
}
while(j<B.length){
C.data[k++]=B.data[j++];
}
C.length=k;
return true;
}
// 8
// 9
// 10
// 11
// 12
// 13
// 14
| [
"254074270@qq.com"
] | 254074270@qq.com |
32b43307e92b14d3a99d5eee1f6536590e53a062 | ff6a7a9c4a0bf23e71b8011c13b865a579572e34 | /Old CP repo competetive-coding/graph theory/dfs using vector with recursion ans to find connected component with video.cpp | 60a554060ea5a49edd89553edf411b8435312c41 | [] | no_license | agrawalsajal02/Interviews-Preparation-and-Cp | c12599335573ebdcb88d797a32a377ac2079a374 | 4e00c5b6f1b174e4def288b069d2211afda7dc9a | refs/heads/master | 2022-12-19T13:20:03.531979 | 2020-10-03T09:45:32 | 2020-10-03T09:45:32 | 300,845,662 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 793 | cpp | //https://unacademy.com/lesson/graph-traversal-technique-ii-dfsdepth-first-search/4IXFCEPQ
//dfs implementation to find no of connected component
//time complexicity :- o(v+e)
#include<bits/stdc++.h>
#define ll long long int
using namespace std;
vector<ll>vi[1000];
bool vis[1000];
void dfs(ll s){
vis[s]=1;
for(ll i=0;i<vi[s].size();i++){
if(!vis[vi[s][i]]){
dfs(vi[s][i]);
}
}
}
void init(ll n){
for(ll i=0;i<n;i++){
vis[i]=0;
}
}
int main(){
ll edge,vertix,connectedcomponent=0;
cin>>vertix>>edge;
for(ll i=0;i<edge;i++){
ll a,b;
cin>>a>>b;
vi[a].push_back(b);
vi[b].push_back(a);
}
ll p=0;
for(ll i=0;i<vertix;i++){
if(!vis[i]){
connectedcomponent++;
dfs(i);
}
}cout<<endl;
cout<<" no of compo :"<<connectedcomponent<<endl;
}
| [
"sajal.agarwal703@gmail.com"
] | sajal.agarwal703@gmail.com |
0509c2b3530de45e225b936e7c905f3d77e2c1d3 | 759e7532e050b2a8cd5f6d1205a83b5ba809aa98 | /day7/initializer_list.cpp | d8b79d3b519e74dd005067aeaf86d89a4a911857 | [] | no_license | pmh9960/LEARN-CPP-2020 | f39ff19787a443a7dcc35699b0cd152f7d7b44e3 | c2150cab41cc4a59584c87f5a4ce11a7a263e5ad | refs/heads/master | 2023-03-21T20:01:36.195026 | 2021-03-13T13:23:58 | 2021-03-13T13:23:58 | 282,670,900 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 908 | cpp | #include <iostream>
#include <string>
class Example
{
public:
Example()
{
std::cout << "Created Entity!" << std::endl;
}
Example(int x)
{
std::cout << "Created Entity with " << x << "!" << std::endl;
}
};
class Entity
{
private:
std::string m_Name;
Example m_Example;
public:
// Entity()
// {
// m_Name = "Unknown";
// m_Example = Example(10);
// }
Entity()
: m_Name("Unknown"), m_Example(10) // or m_Example(Example(8))
{
// You have to write the initializer list in the same order as declared.
}
Entity(const std::string &name)
: m_Name(name)
{
}
const std::string GetName() const { return m_Name; }
};
int main()
{
// Entity e0;
// std::cout << e0.GetName() << std::endl;
// Entity e1("Minho");
// std::cout << e1.GetName() << std::endl;
Entity ex;
} | [
"pmh9960@korea.ac.kr"
] | pmh9960@korea.ac.kr |
75abd040df30b525e968c306cc4238027d355ee4 | af0ecafb5428bd556d49575da2a72f6f80d3d14b | /CodeJamCrawler/dataset/12_8637_35.cpp | 917efc8411e722298f8529fb629424b84b6d4599 | [] | no_license | gbrlas/AVSP | 0a2a08be5661c1b4a2238e875b6cdc88b4ee0997 | e259090bf282694676b2568023745f9ffb6d73fd | refs/heads/master | 2021-06-16T22:25:41.585830 | 2017-06-09T06:32:01 | 2017-06-09T06:32:01 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 421 | cpp | #include<stdio.h>
int main()
{ int t,n,i,j,k;
char s[105],te[105],a[26]={'y','h','e','s','o','c','v','x','d','u','i','g','l','b','k','r','z','t','n','w','j','p','f','m','a','q'};
scanf("%d\n",&t);
for(i=0;i<t;i++)
{ gets(s);
for(j=0;j<strlen(s);j++)
if(s[j]==' ')
te[j]=' ';
else
te[j]=a[s[j]-'a'];
te[j]='\0';
printf("Case #%d: %s\n",i+1,te);
}
return 0;
}
| [
"nikola.mrzljak@fer.hr"
] | nikola.mrzljak@fer.hr |
87f45ef2f0964d5e63d5d7fd6a499d6bfc0204e0 | 7d53a69d03e89ef291f59c17602c9cb6c1180622 | /src/kalman_filter.cpp | 9aafc40593bbfb2658eab32153fbfc0c2f3101ec | [
"MIT"
] | permissive | surjithbs17/ExtendedKalmanFilter | 87b456bde9cd3b6a0eaba4af66ebc45e844c2c50 | 3b52a298f3c086b995b7faa0be70332c9b255f83 | refs/heads/master | 2020-03-14T19:42:49.741028 | 2018-05-03T14:11:55 | 2018-05-03T14:11:55 | 131,765,069 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,867 | cpp | #include "kalman_filter.h"
using Eigen::MatrixXd;
using Eigen::VectorXd;
// Please note that the Eigen library does not initialize
// VectorXd or MatrixXd objects with zeros upon creation.
KalmanFilter::KalmanFilter() {}
KalmanFilter::~KalmanFilter() {}
void KalmanFilter::Init(VectorXd &x_in, MatrixXd &P_in, MatrixXd &F_in,
MatrixXd &H_in, MatrixXd &R_in, MatrixXd &Q_in) {
x_ = x_in;
P_ = P_in;
F_ = F_in;
H_ = H_in;
R_ = R_in;
Q_ = Q_in;
}
void KalmanFilter::Predict() {
/**
TODO:
* predict the state
*/
x_ =F_*x_;
MatrixXd Ft = F_.transpose();
P_= F_*P_*Ft+Q_;
}
void KalmanFilter::Update(const VectorXd &z) {
/**
TODO:
* update the state by using Kalman Filter equations
*/
VectorXd y = z - H_ * x_;
MatrixXd Ht = H_.transpose();
MatrixXd S = H_ * (P_ * Ht) + R_;
MatrixXd Si = S.inverse();
MatrixXd K = P_ * Ht * Si;
MatrixXd I = MatrixXd::Identity(x_.size(), x_.size());
x_ = x_ + (K * y);
P_ = (I - K * H_) * P_;
}
void KalmanFilter::UpdateEKF(const VectorXd &z) {
/**
TODO:
* update the state by using Extended Kalman Filter equations
*/
float px = x_(0);
float py = x_(1);
float vx = x_(2);
float vy = x_(3);
float rho = sqrt(px*px+py*py);
float theta = atan2(py,px);
float ro_dot;
if(px == 0 && py == 0)
{ro_dot = 0;}
else
{ro_dot = (px*vx+py*vy)/rho;}
Hj_=tools.CalculateJacobian(x_);
VectorXd z_pred = VectorXd(3);
z_pred << rho,theta,ro_dot;
VectorXd y = z - z_pred;
double width = 2 * M_PI;
double offsetValue = y(1) + M_PI;
y(1) = (offsetValue - (floor(offsetValue / width) * width)) - M_PI;
MatrixXd Hjt = Hj_.transpose();
MatrixXd S = Hj_ * (P_ * Hjt) + R_;
MatrixXd Si = S.inverse();
MatrixXd K = P_ * Hjt * Si;
MatrixXd I = MatrixXd::Identity(x_.size(), x_.size());
x_ = x_ + (K * y);
P_ = (I - K * Hj_) * P_;
}
| [
"surjith.singh@ketra.com"
] | surjith.singh@ketra.com |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.