text
string
size
int64
token_count
int64
#include "cube.h" #include "server.h" extern "C" { #include "../lua/src/lua.h" #include "../lua/src/lauxlib.h" #include "../lua/src/lualib.h" } extern "C" { #include "../lanes/src/threading.h" } #include "lua.h" #include "lua_functions.h" #include <stdlib.h> #include <string.h> #include <stdarg.h> #include <dirent.h> /// http://softagalleria.net/dirent.php #include <string> #include <signal.h> #define ALL_SCRIPTS for ( int _i = 0; _i < Lua::numberOfScripts; _i++ ) #define SCRIPT Lua::scripts[_i] static const char *extensions[] = { ".lua", ".luac" }; const double Lua::version = 1.6; lua_State **Lua::scripts = NULL; int Lua::numberOfScripts = 0; extern "C" int luaopen_lanes_core( lua_State *L ); extern "C" int luaG_inter_copy( lua_State*, lua_State*, uint n ); //extern "C" int luaG_inter_copy_from( lua_State*, lua_State*, uint n, uint from ); /// from serverfiles.h /// { #define SERVERMAP_PATH "packages/maps/servermaps/" #define SERVERMAP_PATH_BUILTIN "packages/maps/official/" #define SERVERMAP_PATH_INCOMING "packages/maps/servermaps/incoming/" enum { MAP_NOTFOUND = 0, MAP_TEMP, MAP_CUSTOM, MAP_LOCAL, MAP_OFFICIAL, MAP_VOID }; #define readonlymap(x) ((x) >= MAP_CUSTOM) /// } extern void serverdamage( client*, client*, int, int, bool, const vec&, bool fromLua ); extern void sendserveropinfo( int ); extern void sdropflag( int ); extern servercommandline scl; extern void sendresume( client&, bool ); extern void sendinitclient( client& ); extern void shuffleteams( int = FTR_AUTOTEAM ); extern int sendservermode( bool = true ); extern bool checkgban( enet_uint32 ); extern void addgban( const char* ); extern void cleargbans(); extern void updatemasterserver( int, int, int, bool fromLua ); extern void checkintermission(); extern void sendspawn( client*, bool fromLua ); extern bool mapisok( mapstats* ); extern void flagaction( int, int, int, bool fromLua ); extern void changemastermode( int ); extern client& addclient(); extern void sendteamtext( char*, int, int ); extern void sendvoicecomteam( int, int ); extern void rereadcfgs( bool fromLua = true ); extern int clienthasflag( int ); extern int spawntime( int type ); struct pwddetail { string pwd; int line; bool denyadmin; }; struct serverpasswords: serverconfigfile { vector <pwddetail> adminpwds; int staticpasses; }; struct servernickblacklist: serverconfigfile {}; struct configset { string mapname; int mode, time, vote, minplayer, maxplayer, skiplines; }; struct servermaprot: serverconfigfile { vector <configset> configsets; virtual int get_next( bool fromLua = true ); virtual configset* get( int ); }; struct serveripblacklist: serverconfigfile { vector <iprange> ipranges; }; struct voteinfo {}; extern int framemillis; extern int intermission_check_shear; extern void checkintermission(); extern int masterservers; extern unsigned long long int Lua_totalSent; extern unsigned long long int Lua_totalReceived; /** * Неприятный баг на уровне конструкций языка ассемблера вынуждает к этому действию. * (Неожиданная подмена адреса таблицы виртуальных функций для объектов дочерних классов класса serveraction.) **/ extern void Lua_evaluateVote( bool = false ); extern void Lua_endVote( int result ); extern voteinfo *curvote; extern int server_protocol_version; extern struct sflaginfo { int state, actor_cn; float pos[3]; int lastupdate; int stolentime; short x, y; } sflaginfos[2]; extern vector<client*> clients; extern int gamemillis, servmillis, gamelimit; extern string servdesc_current; extern char *global_name; extern serverpasswords passwords; extern serveripblacklist ipblacklist; extern servernickblacklist nickblacklist; extern servermaprot maprot; extern int smode; extern int nextgamemode; extern string nextmapname; extern bool items_blocked, autoteam; extern int arenaround, gamemillis; extern bool forceintermission; extern int mastermode; extern bool autoteam; extern vector<ban> bans; extern guninfo guns[NUMGUNS]; extern itemstat ammostats[NUMGUNS]; extern vector<server_entity> sents; extern ENetHost *serverhost; extern vector<std::string> mastername; struct IteratorData // для cla(), rvsf(), players() { int player_cn; bool alive_only; }; static MUTEX_T callHandlerMutex; static void as_player( int player_cn, const char *format, ... ) { int exclude_cn = -1; packetbuf packet( MAXTRANS, ENET_PACKET_FLAG_RELIABLE ), buffer( MAXTRANS, ENET_PACKET_FLAG_RELIABLE ); putint( packet, SV_CLIENT ); putint( packet, player_cn ); va_list args; va_start( args, format ); while ( *format ) switch ( *format++ ) { case 'x': { exclude_cn = va_arg( args, int ); break; } case 'i': { int n = isdigit( *format ) ? *format++ - '0' : 1; loopi(n) putint( buffer, va_arg( args, int ) ); //putint( buffer, va_arg( args, int ) ); break; } case 's': { sendstring( va_arg( args, const char* ), buffer ); break; } } va_end( args ); putuint( packet, buffer.length() ); packet.put( buffer.buf, buffer.length() ); sendpacket( -1, 1, packet.finalize(), exclude_cn ); } void Lua::initialize( const char *scriptsPath ) { printf( "<Lua> Initializing framework...\n" ); MUTEX_RECURSIVE_INIT( &callHandlerMutex ); DIR *dp = opendir( scriptsPath ); if ( dp ) { dirent *entry; while ( ( entry = readdir(dp) ) != NULL ) { bool match = false; for ( unsigned i = 0; i < sizeof( extensions ) / sizeof( extensions[0] ); i++ ) if ( ( match = !strcasecmp( entry->d_name + ( strlen(entry->d_name) - strlen(extensions[i]) ), extensions[i] ) ) ) break; if ( match ) { scripts = ( lua_State** ) realloc( scripts, ( ++numberOfScripts ) * sizeof( lua_State* ) ); scripts[ numberOfScripts-1 ] = lua_open(); lua_State *L = scripts[ numberOfScripts-1 ]; luaL_openlibs( L ); // Lua mod appendix { openExtraLibs( L ); registerGlobals( L ); // } string scriptFilename = { '\0' }; copystring( scriptFilename, scriptsPath ); strcat( scriptFilename, entry->d_name ); if ( luaL_dofile( L, scriptFilename ) ) { printf( "<Lua> Could not load %s:\n%s\n", entry->d_name, lua_tostring( L, lua_gettop( L ) ) ); lua_close( L ); scripts = ( lua_State** ) realloc( scripts, ( --numberOfScripts ) * sizeof( lua_State* ) ); } else { printf( "<Lua> Script loaded: %s\n", entry->d_name ); lua_getglobal( L, LUA_ON_INIT ); if ( lua_isfunction( L, lua_gettop( L ) ) ) { if ( lua_pcall( L, 0, 0, 0 ) ) { printf( "<Lua> Error when calling %s handler:\n%s\n", LUA_ON_INIT, lua_tostring( L, lua_gettop( L ) ) ); lua_pop( L, 1 ); } } else lua_pop( L, 1 ); lua_getglobal( L, "PLUGIN_NAME" ); printf( "<Lua> -- Name: %s\n", lua_tostring( L, lua_gettop( L ) ) ); lua_getglobal( L, "PLUGIN_AUTHOR" ); printf( "<Lua> -- Author: %s\n", lua_tostring( L, lua_gettop( L ) ) ); lua_getglobal( L, "PLUGIN_VERSION" ); printf( "<Lua> -- Version: %s\n", lua_tostring( L, lua_gettop( L ) ) ); lua_pop( L, 3 ); } } } } else printf( "<Lua> Could not enter scripts' directory\n" ); printf( "<Lua> Framework initialized, %d scripts loaded\n", numberOfScripts ); } void Lua::destroy() { printf( "<Lua> Destroying framework...\n" ); if ( numberOfScripts ) { callHandler( LUA_ON_DESTROY, "" ); tmr_free(); ALL_SCRIPTS { lua_gc( SCRIPT, LUA_GCCOLLECT, 0 ); lua_close( SCRIPT ); } numberOfScripts = 0; free( scripts ); scripts = NULL; } MUTEX_FREE( &callHandlerMutex ); printf( "<Lua> Framework destroyed\n" ); } void Lua::openExtraLibs( lua_State *L ) { lua_getfield( L, LUA_REGISTRYINDEX, "_LOADED" ); #define LUA_OPEN_EXTRA_LIB(opener, libName) \ lua_pushcfunction( L, opener ); \ lua_pushstring( L, libName ); \ lua_call( L, 1, 1 ); \ lua_setfield( L, 1, libName ) LUA_OPEN_EXTRA_LIB (luaopen_tmr, "tmr"); LUA_OPEN_EXTRA_LIB (luaopen_cfg, "cfg"); LUA_OPEN_EXTRA_LIB (luaopen_lanes_core, "lanes.core"); lua_pop( L, 1 ); // _LOADED } void Lua::registerGlobals( lua_State *L ) { luaL_newmetatable( L, "IteratorData" ); /* lua_pushstring( L, "__gc" ); lua_pushcfunction( L, __IteratorData_gc ); lua_settable( L, -3 ); */ lua_pop( L, 1 ); lua_pushnumber( L, version ); lua_setglobal( L, "LUA_API_VERSION" ); #define LUA_SET_CONSTANTN(name, constant) lua_pushinteger( L, constant ); lua_setglobal( L, name ) #define LUA_SET_CONSTANT(constant) LUA_SET_CONSTANTN(#constant, constant) LUA_SET_CONSTANT (PLUGIN_BLOCK); LUA_SET_CONSTANTN ("DAMAGE_MAX", INT_MAX); // client roles LUA_SET_CONSTANT (CR_ADMIN); LUA_SET_CONSTANT (CR_DEFAULT); // client states LUA_SET_CONSTANT (CS_ALIVE); LUA_SET_CONSTANT (CS_DEAD); LUA_SET_CONSTANT (CS_SPAWNING); LUA_SET_CONSTANT (CS_LAGGED); LUA_SET_CONSTANT (CS_EDITING); LUA_SET_CONSTANT (CS_SPECTATE); // weapons LUA_SET_CONSTANT (GUN_KNIFE); LUA_SET_CONSTANT (GUN_PISTOL); LUA_SET_CONSTANT (GUN_CARBINE); LUA_SET_CONSTANT (GUN_SHOTGUN); LUA_SET_CONSTANT (GUN_SUBGUN); LUA_SET_CONSTANT (GUN_SNIPER); LUA_SET_CONSTANT (GUN_ASSAULT); LUA_SET_CONSTANT (GUN_CPISTOL); LUA_SET_CONSTANT (GUN_GRENADE); LUA_SET_CONSTANT (GUN_AKIMBO); // game modes LUA_SET_CONSTANTN ("GM_DEMO", GMODE_DEMO); LUA_SET_CONSTANTN ("GM_TDM", GMODE_TEAMDEATHMATCH); LUA_SET_CONSTANTN ("GM_COOP", GMODE_COOPEDIT); LUA_SET_CONSTANTN ("GM_DM", GMODE_DEATHMATCH); LUA_SET_CONSTANTN ("GM_SURV", GMODE_SURVIVOR); LUA_SET_CONSTANTN ("GM_TSURV", GMODE_TEAMSURVIVOR); LUA_SET_CONSTANTN ("GM_CTF", GMODE_CTF); LUA_SET_CONSTANTN ("GM_PF", GMODE_PISTOLFRENZY); LUA_SET_CONSTANTN ("GM_LSS", GMODE_LASTSWISSSTANDING); LUA_SET_CONSTANTN ("GM_OSOK", GMODE_ONESHOTONEKILL); LUA_SET_CONSTANTN ("GM_TOSOK", GMODE_TEAMONESHOTONEKILL); LUA_SET_CONSTANTN ("GM_HTF", GMODE_HUNTTHEFLAG); LUA_SET_CONSTANTN ("GM_TKTF", GMODE_TEAMKEEPTHEFLAG); LUA_SET_CONSTANTN ("GM_KTF", GMODE_KEEPTHEFLAG); LUA_SET_CONSTANTN ("GM_NUM", GMODE_NUM); // disconnect reasons LUA_SET_CONSTANT (DISC_NONE); LUA_SET_CONSTANT (DISC_EOP); LUA_SET_CONSTANT (DISC_CN); LUA_SET_CONSTANT (DISC_MKICK); LUA_SET_CONSTANT (DISC_MBAN); LUA_SET_CONSTANT (DISC_TAGT); LUA_SET_CONSTANT (DISC_BANREFUSE); LUA_SET_CONSTANT (DISC_WRONGPW); LUA_SET_CONSTANT (DISC_SOPLOGINFAIL); LUA_SET_CONSTANT (DISC_MAXCLIENTS); LUA_SET_CONSTANT (DISC_MASTERMODE); LUA_SET_CONSTANT (DISC_AUTOKICK); LUA_SET_CONSTANT (DISC_AUTOBAN); LUA_SET_CONSTANT (DISC_DUP); LUA_SET_CONSTANT (DISC_BADNICK); LUA_SET_CONSTANT (DISC_OVERFLOW); LUA_SET_CONSTANT (DISC_ABUSE); LUA_SET_CONSTANT (DISC_AFK); LUA_SET_CONSTANT (DISC_FFIRE); LUA_SET_CONSTANT (DISC_CHEAT); // flag actions LUA_SET_CONSTANT (FA_PICKUP); LUA_SET_CONSTANT (FA_STEAL); LUA_SET_CONSTANT (FA_DROP); LUA_SET_CONSTANT (FA_LOST); LUA_SET_CONSTANT (FA_RETURN); LUA_SET_CONSTANT (FA_SCORE); LUA_SET_CONSTANT (FA_RESET); // vote actions LUA_SET_CONSTANT (VOTE_NEUTRAL); LUA_SET_CONSTANT (VOTE_YES); LUA_SET_CONSTANT (VOTE_NO); // vote types LUA_SET_CONSTANT (SA_KICK); LUA_SET_CONSTANT (SA_BAN); LUA_SET_CONSTANT (SA_REMBANS); LUA_SET_CONSTANT (SA_MASTERMODE); LUA_SET_CONSTANT (SA_AUTOTEAM); LUA_SET_CONSTANT (SA_FORCETEAM); LUA_SET_CONSTANT (SA_GIVEADMIN); LUA_SET_CONSTANT (SA_MAP); LUA_SET_CONSTANT (SA_RECORDDEMO); LUA_SET_CONSTANT (SA_STOPDEMO); LUA_SET_CONSTANT (SA_CLEARDEMOS); LUA_SET_CONSTANT (SA_SERVERDESC); LUA_SET_CONSTANT (SA_SHUFFLETEAMS); // master modes LUA_SET_CONSTANT (MM_OPEN); LUA_SET_CONSTANT (MM_PRIVATE); LUA_SET_CONSTANT (MM_MATCH); // teams LUA_SET_CONSTANT (TEAM_CLA); LUA_SET_CONSTANT (TEAM_RVSF); LUA_SET_CONSTANT (TEAM_CLA_SPECT); LUA_SET_CONSTANT (TEAM_RVSF_SPECT); LUA_SET_CONSTANT (TEAM_SPECT); // entity types LUA_SET_CONSTANT (NOTUSED); LUA_SET_CONSTANT (LIGHT); LUA_SET_CONSTANT (PLAYERSTART); LUA_SET_CONSTANT (I_CLIPS); LUA_SET_CONSTANT (I_AMMO); LUA_SET_CONSTANT (I_GRENADE); LUA_SET_CONSTANT (I_HEALTH); LUA_SET_CONSTANT (I_HELMET); LUA_SET_CONSTANT (I_ARMOUR); LUA_SET_CONSTANT (I_AKIMBO); LUA_SET_CONSTANT (MAPMODEL); LUA_SET_CONSTANT (CARROT); LUA_SET_CONSTANT (LADDER); LUA_SET_CONSTANT (CTF_FLAG); LUA_SET_CONSTANT (SOUND); LUA_SET_CONSTANT (CLIP); LUA_SET_CONSTANT (PLCLIP); // sounds LUA_SET_CONSTANT (S_AFFIRMATIVE); LUA_SET_CONSTANT (S_ALLRIGHTSIR); LUA_SET_CONSTANT (S_COMEONMOVE); LUA_SET_CONSTANT (S_COMINGINWITHTHEFLAG); LUA_SET_CONSTANT (S_COVERME); LUA_SET_CONSTANT (S_DEFENDTHEFLAG); LUA_SET_CONSTANT (S_ENEMYDOWN); LUA_SET_CONSTANT (S_GOGETEMBOYS); LUA_SET_CONSTANT (S_GOODJOBTEAM); LUA_SET_CONSTANT (S_IGOTONE); LUA_SET_CONSTANT (S_IMADECONTACT); LUA_SET_CONSTANT (S_IMATTACKING); LUA_SET_CONSTANT (S_IMONDEFENSE); LUA_SET_CONSTANT (S_IMONYOURTEAMMAN); LUA_SET_CONSTANT (S_NEGATIVE); LUA_SET_CONSTANT (S_NOCANDO); LUA_SET_CONSTANT (S_RECOVERTHEFLAG); LUA_SET_CONSTANT (S_SORRY); LUA_SET_CONSTANT (S_SPREADOUT); LUA_SET_CONSTANT (S_STAYHERE); LUA_SET_CONSTANT (S_STAYTOGETHER); LUA_SET_CONSTANT (S_THERESNOWAYSIR); LUA_SET_CONSTANT (S_WEDIDIT); LUA_SET_CONSTANT (S_YES); LUA_SET_CONSTANT (S_ONTHEMOVE1); LUA_SET_CONSTANT (S_ONTHEMOVE2); LUA_SET_CONSTANT (S_GOTURBACK); LUA_SET_CONSTANT (S_GOTUCOVERED); LUA_SET_CONSTANT (S_INPOSITION1); LUA_SET_CONSTANT (S_INPOSITION2); LUA_SET_CONSTANT (S_REPORTIN); LUA_SET_CONSTANT (S_NICESHOT); LUA_SET_CONSTANT (S_THANKS1); LUA_SET_CONSTANT (S_THANKS2); LUA_SET_CONSTANT (S_AWESOME1); LUA_SET_CONSTANT (S_AWESOME2); // socket types LUA_SET_CONSTANT (ST_EMPTY); LUA_SET_CONSTANT (ST_LOCAL); LUA_SET_CONSTANT (ST_TCPIP); // log levels LUA_SET_CONSTANT (ACLOG_DEBUG); LUA_SET_CONSTANT (ACLOG_VERBOSE); LUA_SET_CONSTANT (ACLOG_INFO); LUA_SET_CONSTANT (ACLOG_WARNING); LUA_SET_CONSTANT (ACLOG_ERROR); // vote errors LUA_SET_CONSTANTN ("VOTEE_NOERROR", -1); LUA_SET_CONSTANT (VOTEE_DISABLED); LUA_SET_CONSTANT (VOTEE_CUR); LUA_SET_CONSTANT (VOTEE_MUL); LUA_SET_CONSTANT (VOTEE_MAX); LUA_SET_CONSTANT (VOTEE_AREA); LUA_SET_CONSTANT (VOTEE_PERMISSION); LUA_SET_CONSTANT (VOTEE_INVALID); LUA_SET_CONSTANT (VOTEE_WEAK); LUA_SET_CONSTANT (VOTEE_NEXT); // forceteam reasons LUA_SET_CONSTANT (FTR_INFO); LUA_SET_CONSTANT (FTR_PLAYERWISH); LUA_SET_CONSTANT (FTR_AUTOTEAM); LUA_SET_CONSTANT (FTR_SILENTFORCE); // upload map errors LUA_SET_CONSTANTN ("UE_IGNORE", -2); LUA_SET_CONSTANT (UE_NOERROR); LUA_SET_CONSTANT (UE_READONLY); LUA_SET_CONSTANT (UE_LIMITACHIEVED); LUA_SET_CONSTANT (UE_NOUPLOADPERMISSION); LUA_SET_CONSTANT (UE_NOUPDATEPERMISSION); LUA_SET_CONSTANT (UE_NOREVERTPERMISSION); // remove map errors LUA_SET_CONSTANTN ("RE_IGNORE", -2); LUA_SET_CONSTANT (RE_NOERROR); LUA_SET_CONSTANT (RE_NOPERMISSION); LUA_SET_CONSTANT (RE_READONLY); LUA_SET_CONSTANT (RE_NOTFOUND); // ban types LUA_SET_CONSTANT (BAN_NONE); LUA_SET_CONSTANT (BAN_VOTE); LUA_SET_CONSTANT (BAN_AUTO); LUA_SET_CONSTANT (BAN_BLACKLIST); LUA_SET_CONSTANT (BAN_MASTER); #define LUA_SET_FUNCTION_PREFIX(prefix, function) lua_register( L, #function, prefix##function ) #define LUA_SET_FUNCTION(function) LUA_SET_FUNCTION_PREFIX(__, function) LUA_SET_FUNCTION (include); LUA_SET_FUNCTION (clientprint); LUA_SET_FUNCTION (kill); LUA_SET_FUNCTION (forcedeath); LUA_SET_FUNCTION (spawn); LUA_SET_FUNCTION (dodamage); LUA_SET_FUNCTION (isconnected); LUA_SET_FUNCTION (isadmin); LUA_SET_FUNCTION (getstate); LUA_SET_FUNCTION (getname); LUA_SET_FUNCTION (getip); LUA_SET_FUNCTION (getweapon); LUA_SET_FUNCTION (getpos); LUA_SET_FUNCTION (gethealth); LUA_SET_FUNCTION (getarmor); LUA_SET_FUNCTION (getfrags); LUA_SET_FUNCTION (getdeaths); LUA_SET_FUNCTION (getping); LUA_SET_FUNCTION (getteam); LUA_SET_FUNCTION (getflags); LUA_SET_FUNCTION (getammo); LUA_SET_FUNCTION (getnextprimary); LUA_SET_FUNCTION (getvelocity); LUA_SET_FUNCTION (getangle); LUA_SET_FUNCTION (getskin); LUA_SET_FUNCTION (setpos); LUA_SET_FUNCTION (setammo); LUA_SET_FUNCTION (setname); LUA_SET_FUNCTION (sethealth); LUA_SET_FUNCTION (setarmor); LUA_SET_FUNCTION (setweapon); LUA_SET_FUNCTION (setrole); LUA_SET_FUNCTION (setteam); LUA_SET_FUNCTION (setfrags); LUA_SET_FUNCTION (setflags); LUA_SET_FUNCTION (setdeaths); LUA_SET_FUNCTION (setskin); LUA_SET_FUNCTION (voteend); LUA_SET_FUNCTION (setservname); LUA_SET_FUNCTION (setmaxcl); LUA_SET_FUNCTION (setpwd); LUA_SET_FUNCTION (setadminpwd); LUA_SET_FUNCTION (setmotd); LUA_SET_FUNCTION (setblacklist); LUA_SET_FUNCTION (setnickblist); LUA_SET_FUNCTION (setmaprot); LUA_SET_FUNCTION (setkickthres); LUA_SET_FUNCTION (setbanthres); LUA_SET_FUNCTION (getmapname); LUA_SET_FUNCTION (gettimeleft); LUA_SET_FUNCTION (getgamemode); LUA_SET_FUNCTION (getsvtick); LUA_SET_FUNCTION (maxclient); LUA_SET_FUNCTION (changemap); LUA_SET_FUNCTION (flagaction); LUA_SET_FUNCTION (setnextmode); LUA_SET_FUNCTION (setnextmap); LUA_SET_FUNCTION (setmastermode); LUA_SET_FUNCTION (forcearenawin); LUA_SET_FUNCTION (forcemapend); LUA_SET_FUNCTION (getmastermode); LUA_SET_FUNCTION (settimeleft); LUA_SET_FUNCTION (getautoteam); LUA_SET_FUNCTION (setautoteam); LUA_SET_FUNCTION (disconnect); LUA_SET_FUNCTION (ban); LUA_SET_FUNCTION (setvelocity); LUA_SET_FUNCTION (getflagkeeper); LUA_SET_FUNCTION (getprimary); LUA_SET_FUNCTION (setprimary); LUA_SET_FUNCTION (getdefaultammo); LUA_SET_FUNCTION (getservermaps); LUA_SET_FUNCTION (giveitem); LUA_SET_FUNCTION (shuffleteams); LUA_SET_FUNCTION (setprotocol); LUA_SET_FUNCTION (getdefaultprotocol); LUA_SET_FUNCTION (getprotocol); LUA_SET_FUNCTION (luanotice); LUA_SET_FUNCTION (getnextmode); LUA_SET_FUNCTION (getnextmap); LUA_SET_FUNCTION (getmapitems); LUA_SET_FUNCTION (spawnitem); LUA_SET_FUNCTION (removebans); LUA_SET_FUNCTION (getscore); LUA_SET_FUNCTION (setscore); LUA_SET_FUNCTION (getadminpwd); LUA_SET_FUNCTION (removeadminpwd); LUA_SET_FUNCTION (setmasterserver); LUA_SET_FUNCTION (getmaprotnextmap); LUA_SET_FUNCTION (getmaprotnextmode); LUA_SET_FUNCTION (getadminpwds); LUA_SET_FUNCTION (getwholemaprot); LUA_SET_FUNCTION (setwholemaprot); LUA_SET_FUNCTION (addmaprotentry); LUA_SET_FUNCTION (getwholebl); LUA_SET_FUNCTION (setwholebl); LUA_SET_FUNCTION (strtoiprange); LUA_SET_FUNCTION (setsockettype); LUA_SET_FUNCTION (addclient); LUA_SET_FUNCTION (initclient); LUA_SET_FUNCTION (delclient); LUA_SET_FUNCTION (sethostname); LUA_SET_FUNCTION (sayas); LUA_SET_FUNCTION (voiceas); LUA_SET_FUNCTION (getgamemillis); LUA_SET_FUNCTION (getgamelimit); LUA_SET_FUNCTION (gettimeleftmillis); LUA_SET_FUNCTION (settimeleftmillis); LUA_SET_FUNCTION (setping); LUA_SET_FUNCTION (setangle); LUA_SET_FUNCTION (removeban); LUA_SET_FUNCTION (getbans); LUA_SET_FUNCTION (getmaprotnextentry); LUA_SET_FUNCTION (getspawnmillis); LUA_SET_FUNCTION (players); LUA_SET_FUNCTION (spectators); LUA_SET_FUNCTION (rvsf); LUA_SET_FUNCTION (cla); LUA_SET_FUNCTION (logline); LUA_SET_FUNCTION (setmaprotnextentry); LUA_SET_FUNCTION (setmaprotnextmap); LUA_SET_FUNCTION (setmaprotnextmode); LUA_SET_FUNCTION (setmaprotnexttimeleft); LUA_SET_FUNCTION (getreloadtime); LUA_SET_FUNCTION (getattackdelay); LUA_SET_FUNCTION (getmagsize); LUA_SET_FUNCTION (getsessionid); LUA_SET_FUNCTION (setscoping); LUA_SET_FUNCTION (setcrouching); LUA_SET_FUNCTION (shootas); LUA_SET_FUNCTION (reloadas); LUA_SET_FUNCTION (pickupas); LUA_SET_FUNCTION (setip); LUA_SET_FUNCTION (getmaprotnexttimeleft); LUA_SET_FUNCTION (removemap); LUA_SET_FUNCTION (mapisok); LUA_SET_FUNCTION (mapexists); LUA_SET_FUNCTION (isonfloor); LUA_SET_FUNCTION (isonladder); LUA_SET_FUNCTION (isscoping); LUA_SET_FUNCTION (iscrouching); LUA_SET_FUNCTION (voteas); LUA_SET_FUNCTION (getitempos); LUA_SET_FUNCTION (isitemspawned); LUA_SET_FUNCTION (setstate); LUA_SET_FUNCTION (sendspawn); LUA_SET_FUNCTION (clienthasflag); LUA_SET_FUNCTION (getmappath); LUA_SET_FUNCTION (getvote); LUA_SET_FUNCTION (getpushfactor); LUA_SET_FUNCTION (genpwdhash); LUA_SET_FUNCTION (addms); LUA_SET_FUNCTION (updatems); LUA_SET_FUNCTION (getmasterserver); LUA_SET_FUNCTION (getmasterservers); LUA_SET_FUNCTION (removems); LUA_SET_FUNCTION (getacversion); LUA_SET_FUNCTION (getacbuildtype); LUA_SET_FUNCTION (getconnectmillis); LUA_SET_FUNCTION (gettotalsent); LUA_SET_FUNCTION (gettotalreceived); LUA_SET_FUNCTION (cleargbans); LUA_SET_FUNCTION (addgban); LUA_SET_FUNCTION (checkgban); LUA_SET_FUNCTION (getteamkills); LUA_SET_FUNCTION (setteamkills); LUA_SET_FUNCTION (rereadcfgs); LUA_SET_FUNCTION (callhandler); LUA_SET_FUNCTION (isediting); LUA_SET_FUNCTION (flashonradar); LUA_SET_FUNCTION (isalive); LUA_SET_FUNCTION (getwaterlevel); LUA_SET_FUNCTION (isinwater); LUA_SET_FUNCTION (isunderwater); LUA_SET_FUNCTION (callgenerator); LUA_SET_FUNCTION (getlastsay); LUA_SET_FUNCTION (getlastsaytext); LUA_SET_FUNCTION (authclient); LUA_SET_FUNCTION (isauthed); LUA_SET_FUNCTION (spawntime); } static LuaArg* prepareArgs( const char *arguments, va_list vl, int &argc ) { LuaArg *args = NULL; argc = 0; while (*arguments) { LuaArg arg; arg.type = *arguments; switch (*arguments++) { case 'i': // integer { arg.i = va_arg( vl, int ); } break; case 's': // string { arg.ccp = va_arg( vl, const char* ); } break; case 'b': // boolean { arg.b = va_arg( vl, int ); } break; case 'r': // real { arg.d = va_arg( vl, double ); } break; case 'o': // object(s); объекты, которые находятся на данный момент на вершине стека скрипта, переданного как аргумент { arg.lsp = va_arg( vl, lua_State* ); arg.origin = va_arg( vl, int ); arg.count = isdigit( *arguments ) ? ( ( *arguments++ ) - '0' ) : 1; } break; case 'R': // result [out] { arg.bp = va_arg( vl, bool* ); } break; case 't': // table { arg.luatbl = ( *arguments++ ) - '0'; } break; case 'S': // sender [out] { arg.lsp = va_arg( vl, lua_State* ); arg.origin = va_arg( vl, int ); } break; } args = ( LuaArg* ) realloc( args, ( argc + 1 ) * sizeof( LuaArg ) ); args[argc++] = arg; } return args; } static void parseArgs( int argc, const LuaArg *args, int &numberOfArguments, ... ) { va_list vl; va_start( vl, numberOfArguments ); numberOfArguments = 0; for ( int i = 0; i < argc; ++i ) { switch ( args[i].type ) { case 'i': { int integer = args[i].i; ALL_SCRIPTS lua_pushinteger( SCRIPT, integer ); numberOfArguments++; } break; case 's': { const char *string = args[i].ccp; ALL_SCRIPTS lua_pushstring( SCRIPT, string ); numberOfArguments++; } break; case 'b': { int boolean = args[i].b; ALL_SCRIPTS lua_pushboolean( SCRIPT, boolean ); numberOfArguments++; } break; case 'r': { double real = args[i].d; ALL_SCRIPTS lua_pushnumber( SCRIPT, real ); numberOfArguments++; } break; case 'o': // объекты, которые находятся на данный момент на вершине стека скрипта, переданного как аргумент { int n = args[i].count; if ( n > 0 ) { lua_State *donor = args[i].lsp; int origin = args[i].origin; ALL_SCRIPTS { if ( SCRIPT == donor ) for ( int i = 0; i < n; ++i ) lua_pushvalue( SCRIPT, origin + i ); else { /* int excess = lua_gettop( donor ) - origin - n + 1; luaG_inter_copy( donor, SCRIPT, n + excess ); lua_pop( SCRIPT, excess ); */ // The lualanes module isn't able to interchange debug.traceback() function ._. // I don't know, where luaG_inter_copy_from comes from, replace it with luaG_inter_copy for now - UKnowMe? // luaG_inter_copy_from( donor, SCRIPT, n, origin ); luaG_inter_copy(donor, SCRIPT, n); } } for ( int i = 0; i < n; ++i ) lua_remove( donor, origin ); numberOfArguments += n; } } break; case 'R': { bool **actionPerformed = va_arg( vl, bool** ); *actionPerformed = args[i].bp; } break; case 't': { int n = args[i].luatbl; numberOfArguments -= n; ALL_SCRIPTS { lua_newtable( SCRIPT ); loopi( n ) { int table = lua_gettop( SCRIPT ); lua_pushinteger( SCRIPT, i + 1 ); lua_pushvalue( SCRIPT, table - n + i ); lua_settable( SCRIPT, table ); lua_remove( SCRIPT, table - n + i ); } } numberOfArguments++; } break; case 'S': { lua_State **L = va_arg( vl, lua_State** ); int *origin = va_arg( vl, int* ); *L = args[i].lsp; if ( origin ) *origin = args[i].origin; } break; } } va_end( vl ); } int Lua::callHandler( const char *handler, const char *arguments, ... ) { if ( numberOfScripts == 0 ) return -PLUGIN_BLOCK; LuaArg *args = NULL; int argc = 0; va_list vl; va_start( vl, arguments ); args = prepareArgs( arguments, vl, argc ); va_end( vl ); int result = callHandler( handler, argc, args ); if ( args ) free( args ); return result; } int Lua::callHandler( const char *handler, int argc, const LuaArg *args ) { if ( numberOfScripts == 0 ) return -PLUGIN_BLOCK; MUTEX_LOCK( &callHandlerMutex ); ALL_SCRIPTS { lua_getglobal( SCRIPT, "debug" ); lua_getfield( SCRIPT, lua_gettop( SCRIPT ), "traceback" ); lua_getglobal( SCRIPT, handler ); } /* Исход прерываемого с помощью PLUGIN_BLOCK действия (имеет место лишь тогда, когда по меньшей мере один из обработчиков вернул PLUGIN_BLOCK): * true - действие выполнено в одном из вызываемых обработчиков, который вернул 2 результата: PLUGIN_BLOCK и значение исхода (true/false); * false - действие не выполнено ни в одном из вызываемых обработчиков. */ bool *actionPerformed = NULL; int numberOfArguments = 0; parseArgs( argc, args, numberOfArguments, &actionPerformed ); int result = -PLUGIN_BLOCK; // результат работы обработчика bool fakeActionOutcome; if ( actionPerformed == NULL ) actionPerformed = &fakeActionOutcome; *actionPerformed = false; ALL_SCRIPTS { if ( lua_isfunction( SCRIPT, lua_gettop( SCRIPT ) - numberOfArguments ) ) { if ( !lua_pcall( SCRIPT, numberOfArguments, 2, lua_gettop( SCRIPT ) - numberOfArguments - 1 ) ) { if ( !(*actionPerformed) && lua_isboolean( SCRIPT, lua_gettop( SCRIPT ) ) ) *actionPerformed = (bool) lua_toboolean( SCRIPT, lua_gettop( SCRIPT ) ); lua_pop( SCRIPT, 1 ); // actionPerformed if ( result != PLUGIN_BLOCK && lua_isnumber( SCRIPT, lua_gettop( SCRIPT ) ) ) result = (int) lua_tonumber( SCRIPT, lua_gettop( SCRIPT ) ); lua_pop( SCRIPT, 1 ); // result } else { printf( "<Lua> Error when calling %s handler:\n%s\n", handler, lua_tostring( SCRIPT, lua_gettop( SCRIPT ) ) ); lua_pop( SCRIPT, 1 ); // текст ошибки } lua_pop( SCRIPT, 2 ); // обработчики ошибок } else lua_pop( SCRIPT, numberOfArguments + 1 /* функция */ + 2 /* обработчики ошибок */ ); } MUTEX_UNLOCK( &callHandlerMutex ); return result; } void* Lua::getFakeVariable( const char *generator, int *numberOfReturns, int luaTypeReturned, const char* arguments, ... ) { if ( numberOfScripts == 0 ) return NULL; LuaArg *args = NULL; int argc = 0; va_list vl; va_start( vl, arguments ); args = prepareArgs( arguments, vl, argc ); va_end( vl ); void *result = getFakeVariable( generator, numberOfReturns, luaTypeReturned, argc, args ); if ( args ) free( args ); return result; } void* Lua::getFakeVariable( const char *generator, int *numberOfReturns, int luaTypeReturned, int argc, const LuaArg *args ) { // Циклично вызываем все функции-генераторы с данным именем; останавливаемся, как только получили первый результат. if ( numberOfScripts == 0 ) return NULL; MUTEX_LOCK( &callHandlerMutex ); ALL_SCRIPTS { lua_getglobal( SCRIPT, "debug" ); lua_getfield( SCRIPT, lua_gettop( SCRIPT ), "traceback" ); lua_getglobal( SCRIPT, generator ); } int numberOfArguments = 0; lua_State *senderL = NULL; int senderOrigin = 0; parseArgs( argc, args, numberOfArguments, &senderL, &senderOrigin ); void *result = NULL; bool resultGotten = false; ALL_SCRIPTS { if ( !resultGotten && lua_isfunction( SCRIPT, lua_gettop( SCRIPT ) - numberOfArguments ) ) { int top1 = lua_gettop( SCRIPT ); if ( !lua_pcall( SCRIPT, numberOfArguments, LUA_MULTRET, lua_gettop( SCRIPT ) - numberOfArguments - 1 ) ) { top1 -= numberOfArguments + 1; int top2 = lua_gettop( SCRIPT ); int n = top2 - top1; if ( n > 0 ) { if ( numberOfReturns ) *numberOfReturns = n; resultGotten = true; switch ( luaTypeReturned ) { case LUA_TNUMBER: { result = ( void* ) new double[n]; for ( int i = 0; i < n; i++ ) { if ( lua_isnumber( SCRIPT, lua_gettop( SCRIPT ) - n + i + 1 ) ) ( ( double* ) result )[i] = (double) lua_tonumber( SCRIPT, lua_gettop( SCRIPT ) - n + i + 1 ); else { delete[] ( double* ) result; result = NULL; resultGotten = false; break; } } } break; case LUA_TBOOLEAN: { result = ( void* ) new bool[n]; for ( int i = 0; i < n; i++ ) { if ( lua_isboolean( SCRIPT, lua_gettop( SCRIPT ) - n + i + 1 ) ) ( ( bool* ) result )[i] = (bool) lua_toboolean( SCRIPT, lua_gettop( SCRIPT ) - n + i + 1 ); else { delete[] ( bool* ) result; result = NULL; resultGotten = false; break; } } } break; case LUA_TNONE: { if ( SCRIPT != senderL ) luaG_inter_copy( SCRIPT, senderL, n ); for ( int i = 0; i < n; ++i ) lua_insert( senderL, senderOrigin ); if ( SCRIPT == senderL ) lua_settop( SCRIPT, top2 + n ); // push n nils } break; } lua_pop( SCRIPT, n ); } } else { printf( "<Lua> Error when calling %s generator:\n%s\n", generator, lua_tostring( SCRIPT, lua_gettop( SCRIPT ) ) ); lua_pop( SCRIPT, 1 ); // текст ошибки } lua_pop( SCRIPT, 2 ); // обработчики ошибок } else lua_pop( SCRIPT, numberOfArguments + 1 /* функция */ + 2 /* обработчики ошибок */ ); } MUTEX_UNLOCK( &callHandlerMutex ); return result; } static int traceback (lua_State *L) { if (!lua_isstring(L, 1)) /* 'message' not a string? */ return 1; /* keep it intact */ lua_getfield(L, LUA_GLOBALSINDEX, "debug"); if (!lua_istable(L, -1)) { lua_pop(L, 1); return 1; } lua_getfield(L, -1, "traceback"); if (!lua_isfunction(L, -1)) { lua_pop(L, 2); return 1; } lua_pushvalue(L, 1); /* pass error message */ lua_pushinteger(L, 2); /* skip this function and traceback */ lua_call(L, 2, 1); /* call debug.traceback */ return 1; } static bool checkArguments( lua_State *L, const char *format, const char **desc = NULL ) { lua_checkstack( L, strlen( format ) ); for ( int i = 0; *format; ++i ) { int expectation = LUA_TNONE; bool expected = true; switch ( format[i] ) { case 'n': expected = lua_isnumber(L, i + 1); expectation = LUA_TNUMBER; break; case 's': expected = lua_isstring(L, i + 1); expectation = LUA_TSTRING; break; case 'b': expected = lua_isboolean(L, i + 1); expectation = LUA_TBOOLEAN; break; case 'f': expected = lua_isfunction(L, i + 1); expectation = LUA_TFUNCTION; break; case 't': expected = lua_istable(L, i + 1); expectation = LUA_TTABLE; break; } if ( !expected) { if ( desc ) { string message; sprintf( message, "Expected %s for argument '%s', got: %s", lua_typename( L, expectation ), desc[i], lua_typename( L, lua_type( L, i+1 ) ) ); traceback( L ); } return false; } } return true; } //BEGIN Lua global functions LUA_FUNCTION (include) { //* lua_checkstack( L, 1 ); if ( !lua_isstring( L, 1 ) ) return 0; //*/ //checkArguments( L, "s", { "filename" } ); string filenameINC = { '\0' }; copystring( filenameINC, LUA_INCLUDES_PATH ); strcat( filenameINC, lua_tostring( L, 1 ) ); strcat( filenameINC, ".inc" ); if ( luaL_dofile( L, filenameINC ) != 0 ) { for ( unsigned i = 0; i < sizeof( extensions ) / sizeof( extensions[0] ); i++ ) { string filenameLUA = { '\0' }; copystring( filenameLUA, LUA_INCLUDES_PATH ); strcat( filenameLUA, lua_tostring( L, 1 ) ); strcat( filenameLUA, extensions[i] ); if ( luaL_dofile( L, filenameLUA ) == 0 ) break; } } return 0; } LUA_FUNCTION (clientprint) { lua_checkstack( L, 3 ); if ( !lua_isnumber( L, 1 ) || !lua_isstring( L, 2 ) ) return 0; int target_cn = (int) lua_tonumber( L, 1 ); if ( !valid_client( target_cn ) && target_cn != -1 ) return 0; const char *message = lua_tostring( L, 2 ); if ( !strlen( message ) ) return 0; int exclude_cn = -1; // no one to be excluded if ( lua_isnumber( L, 3 ) ) exclude_cn = (int) lua_tonumber( L, 3 ); sendf( target_cn, 1, "risx", SV_SERVMSG, message, exclude_cn ); return 0; } LUA_FUNCTION (kill) { lua_checkstack( L, 2 ); if ( !lua_isnumber( L, 1 ) || !lua_isboolean( L, 2 ) ) return 0; int target_cn = (int) lua_tonumber( L, 1 ); if ( !valid_client( target_cn ) ) return 0; bool gib = (bool) lua_toboolean( L, 2 ); sendf( -1, 1, "ri5", gib ? SV_GIBDIED : SV_DIED, target_cn, target_cn, clients[target_cn]->state.frags, GUN_KNIFE ); return 0; } LUA_FUNCTION (getflagkeeper) { lua_checkstack( L, 1 ); if ( !lua_isnumber( L, 1 ) ) return 0; int flag = (int) lua_tonumber( L, 1 ); if ( !valid_flag( flag ) ) return 0; int keeper_cn = sflaginfos[flag].actor_cn; if ( sflaginfos[flag].state != CTFF_STOLEN || keeper_cn == -1 ) return 0; lua_pushinteger( L, keeper_cn ); return 1; } LUA_FUNCTION (forcedeath) { lua_checkstack( L, 1 ); if ( !lua_isnumber( L, 1 ) ) return 0; int target_cn = (int) lua_tonumber( L, 1 ); if ( !valid_client( target_cn ) ) return 0; forcedeath( clients[target_cn] ); return 0; } LUA_FUNCTION (spawn) { lua_checkstack( L, 8 ); for ( int i = 1; i <= 8; i++ ) if ( !lua_isnumber( L, i ) ) return 0; int target_cn = (int) lua_tonumber( L, 1 ); if ( !valid_client( target_cn ) ) return 0; if ( team_isspect( clients[target_cn]->team ) ) return 0; clientstate &gs = clients[target_cn]->state; int health = (int) lua_tonumber( L, 2 ); int armour = (int) lua_tonumber( L, 3 ); int ammo = (int) lua_tonumber( L, 4 ); int mag = (int) lua_tonumber( L, 5 ); int weapon = (int) lua_tonumber( L, 6 ); if ( !( weapon >= 0 && weapon < NUMGUNS ) ) weapon = gs.gunselect; int gamemode = (int) lua_tonumber( L, 7 ); if ( !( gamemode >= 0 && gamemode < GMODE_NUM ) ) gamemode = smode; int primaryweapon = (int) lua_tonumber( L, 8 ); if ( !( primaryweapon >= 0 && primaryweapon < NUMGUNS ) ) primaryweapon = gs.primary; gs.respawn(); gs.spawnstate( gamemode ); gs.lifesequence++; gs.ammo[primaryweapon] = ammo; gs.mag[primaryweapon] = mag; gs.health = health; gs.armour = armour; gs.primary = gs.nextprimary = primaryweapon; gs.gunselect = weapon; sendf( target_cn, 1, "ri7vv", SV_SPAWNSTATE, gs.lifesequence, gs.health, gs.armour, gs.primary, gs.gunselect, ( m_arena ) ? clients[target_cn]->spawnindex : -1, NUMGUNS, gs.ammo, NUMGUNS, gs.mag ); gs.lastspawn = gamemillis; return 0; } LUA_FUNCTION (dodamage) { lua_checkstack( L, 4 ); for ( int i = 1; i <= 4; i++ ) if ( !lua_isnumber( L, i ) ) return 0; int target_cn = (int) lua_tonumber( L, 1 ); int actor_cn = (int) lua_tonumber( L, 2 ); if ( !valid_client( target_cn ) || !valid_client( actor_cn ) ) return 0; if ( team_isspect( clients[target_cn]->team ) ) return 0; int damage = (int) lua_tonumber( L, 3 ); int weapon = (int) lua_tonumber( L, 4 ); if ( !( weapon >= 0 && weapon < NUMGUNS ) ) return 0; serverdamage( clients[target_cn], clients[actor_cn], damage, weapon, damage == INT_MAX, vec(0,0,0), true ); return 0; } LUA_FUNCTION (isconnected) { lua_checkstack( L, 1 ); if ( !lua_isnumber( L, 1 ) ) return 0; int player_cn = (int) lua_tonumber( L, 1 ); if ( !clients.inrange( player_cn ) ) return 0; lua_pushboolean( L, (int) ( clients[player_cn]->type != ST_EMPTY ) ); return 1; } LUA_FUNCTION (isadmin) { lua_checkstack( L, 1 ); if ( !lua_isnumber( L, 1 ) ) return 0; int player_cn = (int) lua_tonumber( L, 1 ); if ( !valid_client( player_cn ) ) return 0; lua_pushboolean( L, (int) ( clients[player_cn]->role == CR_ADMIN ) ); return 1; } LUA_FUNCTION (getstate) { lua_checkstack( L, 1 ); if ( !lua_isnumber( L, 1 ) ) return 0; int player_cn = (int) lua_tonumber( L, 1 ); if ( !valid_client( player_cn ) ) return 0; lua_pushinteger( L, clients[player_cn]->state.state ); return 1; } LUA_FUNCTION (getname) { lua_checkstack( L, 1 ); if ( !lua_isnumber( L, 1 ) ) return 0; int player_cn = (int) lua_tonumber( L, 1 ); if ( !valid_client( player_cn ) ) return 0; lua_pushstring( L, clients[player_cn]->name ); return 1; } LUA_FUNCTION (getip) { lua_checkstack( L, 1 ); if ( !lua_isnumber( L, 1 ) ) return 0; int player_cn = (int) lua_tonumber( L, 1 ); if ( !valid_client( player_cn ) ) return 0; lua_pushstring( L, clients[player_cn]->hostname ); return 1; } LUA_FUNCTION (getweapon) { lua_checkstack( L, 1 ); if ( !lua_isnumber( L, 1 ) ) return 0; int player_cn = (int) lua_tonumber( L, 1 ); if ( !valid_client( player_cn ) ) return 0; lua_pushinteger( L, clients[player_cn]->state.gunselect ); return 1; } LUA_FUNCTION (getprimary) { lua_checkstack( L, 1 ); if ( !lua_isnumber( L, 1 ) ) return 0; int player_cn = (int) lua_tonumber( L, 1 ); if ( !valid_client( player_cn ) ) return 0; lua_pushinteger( L, clients[player_cn]->state.primary ); return 1; } LUA_FUNCTION (getpos) { lua_checkstack( L, 1 ); if ( !lua_isnumber( L, 1 ) ) return 0; int player_cn = (int) lua_tonumber( L, 1 ); if ( !valid_client( player_cn ) ) return 0; /* lua_newtable( L ); int table = lua_gettop( L ); lua_pushnumber( L, (lua_Number) clients[player_cn]->state.o[0] ); lua_setfield( L, table, "x" ); lua_pushnumber( L, (lua_Number) clients[player_cn]->state.o[1] ); lua_setfield( L, table, "y" ); lua_pushnumber( L, (lua_Number) clients[player_cn]->state.o[2] ); lua_setfield( L, table, "z" ); */ lua_pushnumber( L, (lua_Number) clients[player_cn]->state.o[0] ); lua_pushnumber( L, (lua_Number) clients[player_cn]->state.o[1] ); lua_pushnumber( L, (lua_Number) clients[player_cn]->state.o[2] ); return 3; } LUA_FUNCTION (gethealth) { lua_checkstack( L, 1 ); if ( !lua_isnumber( L, 1 ) ) return 0; int player_cn = (int) lua_tonumber( L, 1 ); if ( !valid_client( player_cn ) ) return 0; lua_pushinteger( L, clients[player_cn]->state.health ); return 1; } LUA_FUNCTION (getarmor) { lua_checkstack( L, 1 ); if ( !lua_isnumber( L, 1 ) ) return 0; int player_cn = (int) lua_tonumber( L, 1 ); if ( !valid_client( player_cn ) ) return 0; lua_pushinteger( L, clients[player_cn]->state.armour ); return 1; } LUA_FUNCTION (getfrags) { lua_checkstack( L, 1 ); if ( !lua_isnumber( L, 1 ) ) return 0; int player_cn = (int) lua_tonumber( L, 1 ); if ( !valid_client( player_cn ) ) return 0; lua_pushinteger( L, clients[player_cn]->state.frags ); return 1; } LUA_FUNCTION (getdeaths) { lua_checkstack( L, 1 ); if ( !lua_isnumber( L, 1 ) ) return 0; int player_cn = (int) lua_tonumber( L, 1 ); if ( !valid_client( player_cn ) ) return 0; lua_pushinteger( L, clients[player_cn]->state.deaths ); return 1; } LUA_FUNCTION (getping) { lua_checkstack( L, 1 ); if ( !lua_isnumber( L, 1 ) ) return 0; int player_cn = (int) lua_tonumber( L, 1 ); if ( !valid_client( player_cn ) ) return 0; lua_pushinteger( L, clients[player_cn]->ping ); return 1; } LUA_FUNCTION (getteam) { lua_checkstack( L, 1 ); if ( !lua_isnumber( L, 1 ) ) return 0; int player_cn = (int) lua_tonumber( L, 1 ); if ( !valid_client( player_cn ) ) return 0; lua_pushinteger( L, clients[player_cn]->team ); return 1; } LUA_FUNCTION (getflags) { lua_checkstack( L, 1 ); if ( !lua_isnumber( L, 1 ) ) return 0; int player_cn = (int) lua_tonumber( L, 1 ); if ( !valid_client( player_cn ) ) return 0; lua_pushinteger( L, clients[player_cn]->state.flagscore ); return 1; } LUA_FUNCTION (getammo) { lua_checkstack( L, 2 ); for ( int i = 1; i <= 2; i++ ) if ( !lua_isnumber( L, i ) ) return 0; int player_cn = (int) lua_tonumber( L, 1 ); if ( !valid_client( player_cn ) ) return 0; int weapon = (int) lua_tonumber( L, 2 ); if ( !( weapon >= 0 && weapon < NUMGUNS ) ) return 0; lua_pushinteger( L, clients[player_cn]->state.ammo[weapon] ); lua_pushinteger( L, clients[player_cn]->state.mag[weapon] ); return 2; } LUA_FUNCTION (getnextprimary) { lua_checkstack( L, 1 ); if ( !lua_isnumber( L, 1 ) ) return 0; int player_cn = (int) lua_tonumber( L, 1 ); if ( !valid_client( player_cn ) ) return 0; lua_pushinteger( L, clients[player_cn]->state.nextprimary ); return 1; } LUA_FUNCTION (getvelocity) { lua_checkstack( L, 1 ); if ( !lua_isnumber( L, 1 ) ) return 0; int player_cn = (int) lua_tonumber( L, 1 ); if ( !valid_client( player_cn ) ) return 0; lua_pushnumber( L, (lua_Number) clients[player_cn]->state.vel.x ); lua_pushnumber( L, (lua_Number) clients[player_cn]->state.vel.y ); lua_pushnumber( L, (lua_Number) clients[player_cn]->state.vel.z ); return 3; } LUA_FUNCTION (getangle) { lua_checkstack( L, 1 ); if ( !lua_isnumber( L, 1 ) ) return 0; int player_cn = (int) lua_tonumber( L, 1 ); if ( !valid_client( player_cn ) ) return 0; lua_pushinteger( L, clients[player_cn]->y ); // hor lua_pushinteger( L, clients[player_cn]->p ); // ver return 2; } LUA_FUNCTION (getskin) { lua_checkstack( L, 1 ); if ( !lua_isnumber( L, 1 ) ) return 0; int player_cn = (int) lua_tonumber( L, 1 ); if ( !valid_client( player_cn ) ) return 0; if ( !team_isactive( clients[player_cn]->team ) ) return 0; lua_pushinteger( L, clients[player_cn]->skin[clients[player_cn]->team] ); return 1; } LUA_FUNCTION (setpos) { lua_checkstack( L, 4 ); for ( int i = 1; i <= 4; i++ ) if ( !lua_isnumber( L, i ) ) return 0; int target_cn = (int) lua_tonumber( L, 1 ); if ( !valid_client( target_cn ) ) return 0; clients[target_cn]->state.o[0] = lua_tonumber( L, 2 ); clients[target_cn]->state.o[1] = lua_tonumber( L, 3 ); clients[target_cn]->state.o[2] = lua_tonumber( L, 4 ); return 0; } LUA_FUNCTION (setammo) { lua_checkstack( L, 4 ); for ( int i = 1; i <= 4; i++ ) if ( !lua_isnumber( L, i ) ) return 0; int target_cn = (int) lua_tonumber( L, 1 ); if ( !valid_client( target_cn ) ) return 0; int weapon = (int) lua_tonumber( L, 2 ); if ( !( weapon >= 0 && weapon < NUMGUNS ) ) return 0; clients[target_cn]->state.ammo[weapon] = (int) lua_tonumber( L, 3 ); clients[target_cn]->state.mag[weapon] = (int) lua_tonumber( L, 4 ); sendresume( *clients[target_cn], true ); return 0; } LUA_FUNCTION (setname) { lua_checkstack( L, 2 ); if ( !lua_isnumber( L, 1 ) || !lua_isstring( L, 2 ) ) return 0; int target_cn = (int) lua_tonumber( L, 1 ); if ( !valid_client( target_cn ) ) return 0; copystring( clients[target_cn]->name, lua_tostring( L, 2 ) ); //sendinitclient( *clients[target_cn] ); as_player( target_cn, "is", SV_SWITCHNAME, clients[target_cn]->name ); return 0; } LUA_FUNCTION (sethealth) { lua_checkstack( L, 2 ); for ( int i = 1; i <= 2; i++ ) if ( !lua_isnumber( L, i ) ) return 0; int target_cn = (int) lua_tonumber( L, 1 ); if ( !valid_client( target_cn ) ) return 0; clients[target_cn]->state.health = (int) lua_tonumber( L, 2 ); sendresume( *clients[target_cn], true ); return 0; } LUA_FUNCTION (setarmor) { lua_checkstack( L, 2 ); for ( int i = 1; i <= 2; i++ ) if ( !lua_isnumber( L, i ) ) return 0; int target_cn = (int) lua_tonumber( L, 1 ); if ( !valid_client( target_cn ) ) return 0; clients[target_cn]->state.armour = (int) lua_tonumber( L, 2 ); sendresume( *clients[target_cn], true ); return 0; } LUA_FUNCTION (setweapon) { lua_checkstack( L, 2 ); for ( int i = 1; i <= 2; i++ ) if ( !lua_isnumber( L, i ) ) return 0; int target_cn = (int) lua_tonumber( L, 1 ); if ( !valid_client( target_cn ) ) return 0; int weapon = (int) lua_tonumber( L, 2 ); if ( !( weapon >= 0 && weapon < NUMGUNS ) ) return 0; clients[target_cn]->state.gunselect = weapon; //sendf( target_cn, 1, "ri2", SV_WEAPCHANGE, weapon ); sendresume( *clients[target_cn], true ); return 0; } LUA_FUNCTION (setprimary) { lua_checkstack( L, 2 ); for ( int i = 1; i <= 2; i++ ) if ( !lua_isnumber( L, i ) ) return 0; int target_cn = (int) lua_tonumber( L, 1 ); if ( !valid_client( target_cn ) ) return 0; int weapon = (int) lua_tonumber( L, 2 ); if ( !( weapon >= 0 && weapon < NUMGUNS ) ) return 0; clients[target_cn]->state.primary = weapon; sendresume( *clients[target_cn], true ); return 0; } LUA_FUNCTION (setrole) { lua_checkstack( L, 3 ); for ( int i = 1; i <= 2; i++ ) if ( !lua_isnumber( L, i ) ) return 0; int target_cn = (int) lua_tonumber( L, 1 ); if ( !valid_client( target_cn ) ) return 0; int role = (int) lua_tonumber( L, 2 ); if ( !( role == CR_ADMIN || role == CR_DEFAULT ) ) return 0; if ( lua_toboolean( L, 3 ) ) { if ( role == CR_ADMIN ) for ( int i = 0; i < clients.length(); i++ ) clients[i]->role = CR_DEFAULT; clients[target_cn]->role = role; } else clients[target_cn]->role = role; sendserveropinfo( -1 ); if ( curvote ) Lua_evaluateVote(); return 0; } LUA_FUNCTION (setteam) { lua_checkstack( L, 3 ); for ( int i = 1; i <= 2; i++ ) if ( !lua_isnumber( L, i ) ) return 0; int target_cn = (int) lua_tonumber( L, 1 ); if ( !valid_client( target_cn ) ) return 0; int team = (int) lua_tonumber( L, 2 ); if ( !team_isvalid( team ) ) return 0; if ( clients[target_cn]->team != team ) { //sdropflag( target_cn ); int ftr = FTR_INFO; if ( lua_isnumber( L, 3 ) ) ftr = (int) lua_tonumber( L, 3 ); clients[target_cn]->team = team; sendf( -1, 1, "riii", SV_SETTEAM, target_cn, team | ( ftr << 4 ) ); } return 0; } LUA_FUNCTION (setfrags) { lua_checkstack( L, 2 ); for ( int i = 1; i <= 2; i++ ) if ( !lua_isnumber( L, i ) ) return 0; int target_cn = (int) lua_tonumber( L, 1 ); if ( !valid_client( target_cn ) ) return 0; clients[target_cn]->state.frags = (int) lua_tonumber( L, 2 ); sendresume( *clients[target_cn], true ); return 0; } LUA_FUNCTION (setflags) { lua_checkstack( L, 2 ); for ( int i = 1; i <= 2; i++ ) if ( !lua_isnumber( L, i ) ) return 0; int target_cn = (int) lua_tonumber( L, 1 ); if ( !valid_client( target_cn ) ) return 0; clients[target_cn]->state.flagscore = (int) lua_tonumber( L, 2 ); sendresume( *clients[target_cn], true ); return 0; } LUA_FUNCTION (setdeaths) { lua_checkstack( L, 2 ); for ( int i = 1; i <= 2; i++ ) if ( !lua_isnumber( L, i ) ) return 0; int target_cn = (int) lua_tonumber( L, 1 ); if ( !valid_client( target_cn ) ) return 0; clients[target_cn]->state.deaths = (int) lua_tonumber( L, 2 ); sendresume( *clients[target_cn], true ); return 0; } LUA_FUNCTION (setskin) { lua_checkstack( L, 2 ); for ( int i = 1; i <= 2; i++ ) if ( !lua_isnumber( L, i ) ) return 0; int target_cn = (int) lua_tonumber( L, 1 ); if ( !valid_client( target_cn ) ) return 0; int skin = (int) lua_tonumber( L, 2 ); for ( int i = 0; i < 2; i++ ) clients[target_cn]->skin[i] = skin; //sendinitclient( *clients[target_cn] ); as_player( target_cn, "iii", SV_SWITCHSKIN, clients[target_cn]->skin[0], clients[target_cn]->skin[1] ); return 0; } LUA_FUNCTION (voteend) { lua_checkstack( L, 1 ); if ( !lua_isnumber( L, 1 ) ) return 0; int result = (int) lua_tonumber( L, 1 ); if ( !( result >= 0 && result < VOTE_NUM ) ) return 0; Lua_endVote( result ); return 0; } LUA_FUNCTION (setservname) { lua_checkstack( L, 1 ); if ( !lua_isstring( L, 1 ) ) return 0; filterrichtext( scl.servdesc_full, lua_tostring( L, 1 ) ); filterservdesc( scl.servdesc_full, scl.servdesc_full ); copystring( servdesc_current, scl.servdesc_full ); global_name = scl.servdesc_full; return 0; } LUA_FUNCTION (setmaxcl) { lua_checkstack( L, 1 ); if ( !lua_isnumber( L, 1 ) ) return 0; int max_clients = (int) lua_tonumber( L, 1 ); if ( max_clients <= 0 ) return 0; scl.maxclients = ( max_clients > MAXCLIENTS ) ? MAXCLIENTS : max_clients; return 0; } LUA_FUNCTION (setpwd) { static string pwd = { '\0' }; lua_checkstack( L, 1 ); if ( !lua_isstring( L, 1 ) ) return 0; copystring( pwd, lua_tostring( L, 1 ) ); scl.serverpassword = pwd; return 0; } LUA_FUNCTION (setadminpwd) { lua_checkstack( L, 3 ); if ( !lua_isstring( L, 1 ) ) return 0; int line = 0; if ( lua_isnumber( L, 2 ) ) line = (int) lua_tonumber( L, 2 ); bool denyadmin = false; if ( lua_isboolean( L, 3 ) ) denyadmin = (bool) lua_toboolean( L, 3 ); int i; for ( i = 0; i < passwords.adminpwds.length(); i++ ) if ( passwords.adminpwds[i].line == line ) { i = -1; copystring( passwords.adminpwds[i].pwd, lua_tostring( L, 1 ) ); if ( line != 0 ) passwords.adminpwds[i].denyadmin = denyadmin; if ( line == 0 ) scl.adminpasswd = passwords.adminpwds[i].pwd; break; } if ( i != -1 ) { pwddetail adminpwd; copystring( adminpwd.pwd, lua_tostring( L, 1 ) ); adminpwd.line = line; if ( line == 0 ) adminpwd.denyadmin = false; else adminpwd.denyadmin = denyadmin; passwords.adminpwds.insert( 0, adminpwd ); passwords.staticpasses++; } return 0; } LUA_FUNCTION (setmotd) { lua_checkstack( L, 1 ); if ( !lua_isstring( L, 1 ) ) return 0; filterrichtext( scl.motd, lua_tostring( L, 1 ) ); return 0; } LUA_FUNCTION (setblacklist) { static string filename = { '\0' }; lua_checkstack( L, 1 ); if ( !lua_isstring( L, 1 ) ) return 0; copystring( filename, lua_tostring( L, 1 ) ); scl.blfile = filename; ipblacklist.init( scl.blfile ); return 0; } LUA_FUNCTION (setnickblist) { static string filename = { '\0' }; lua_checkstack( L, 1 ); if ( !lua_isstring( L, 1 ) ) return 0; copystring( filename, lua_tostring( L, 1 ) ); scl.nbfile = filename; nickblacklist.init( scl.nbfile ); return 0; } LUA_FUNCTION (setmaprot) { static string filename = { '\0' }; lua_checkstack( L, 1 ); if ( !lua_isstring( L, 1 ) ) return 0; copystring( filename, lua_tostring( L, 1 ) ); scl.maprot = filename; maprot.init( scl.maprot ); return 0; } LUA_FUNCTION (setkickthres) { lua_checkstack( L, 1 ); if ( !lua_isnumber( L, 1 ) ) return 0; scl.kickthreshold = (int) lua_tonumber( L, 1 ); return 0; } LUA_FUNCTION (setbanthres) { lua_checkstack( L, 1 ); if ( !lua_isnumber( L, 1 ) ) return 0; scl.banthreshold = (int) lua_tonumber( L, 1 ); return 0; } LUA_FUNCTION (getmapname) { lua_pushstring( L, behindpath( smapname ) ); return 1; } LUA_FUNCTION (gettimeleft) { lua_pushinteger( L, ( gamelimit - gamemillis + 60000 - 1 ) / 60000 ); return 1; } LUA_FUNCTION (getgamemode) { lua_pushinteger( L, smode ); return 1; } LUA_FUNCTION (getsvtick) { lua_pushinteger( L, servmillis ); return 1; } LUA_FUNCTION (maxclient) { lua_pushinteger( L, scl.maxclients ); return 1; } LUA_FUNCTION (changemap) { lua_checkstack( L, 3 ); if ( !lua_isstring( L, 1 ) ) return 0; const char *map = lua_tostring( L, 1 ); if ( !lua_isnumber( L, 2 ) ) return 0; int mode = (int) lua_tonumber( L, 2 ); if ( !( mode >= 0 && mode < GMODE_NUM ) || !lua_isnumber( L, 3 ) ) return 0; int time = (int) lua_tonumber( L, 3 ); startgame( map, mode, time, true ); return 0; } LUA_FUNCTION (flagaction) { lua_checkstack( L, 3 ); for ( int i = 1; i <= 3; i++ ) if ( !lua_isnumber( L, i ) ) return 0; int actor_cn = (int) lua_tonumber( L, 1 ); if ( !valid_client( actor_cn ) ) return 0; int action = (int) lua_tonumber( L, 2 ); int flag = (int) lua_tonumber( L, 3 ); flagaction( flag, action, actor_cn, true ); return 0; } LUA_FUNCTION (setnextmode) { lua_checkstack( L, 1 ); if ( !lua_isnumber( L, 1 ) ) return 0; int mode = (int) lua_tonumber( L, 1 ); if ( !( mode >= 0 && mode < GMODE_NUM ) ) return 0; nextgamemode = mode; return 0; } LUA_FUNCTION (setnextmap) { lua_checkstack( L, 1 ); if ( !lua_isstring( L, 1 ) ) return 0; copystring( nextmapname, lua_tostring( L, 1 ) ); return 0; } LUA_FUNCTION (setmastermode) { lua_checkstack( L, 1 ); if ( !lua_isnumber( L, 1 ) ) return 0; int master_mode = (int) lua_tonumber( L, 1 ); if ( !( master_mode >= 0 && master_mode < MM_NUM ) ) return 0; changemastermode( master_mode ); return 0; } LUA_FUNCTION (forcearenawin) { if ( !m_arena ) return 0; lua_checkstack( L, 1 ); if ( !lua_isnumber( L, 1 ) ) return 0; int alive = (int) lua_tonumber( L, 1 ); if ( !( alive == -1 || valid_client( alive ) ) ) return 0; items_blocked = true; sendf( -1, 1, "ri2", SV_ARENAWIN, alive ); arenaround = gamemillis + 5000; if ( autoteam && m_teammode ) refillteams( true ); return 0; } LUA_FUNCTION (forcemapend) { forceintermission = true; return 0; } LUA_FUNCTION (getmastermode) { lua_pushinteger( L, mastermode ); return 1; } LUA_FUNCTION (settimeleft) { lua_checkstack( L, 1 ); if ( !lua_isnumber( L, 1 ) ) return 0; int remaining_minutes = (int) lua_tonumber( L, 1 ); intermission_check_shear = 60 * 1000 - gamemillis % (60 * 1000) + framemillis; gamelimit = gamemillis + remaining_minutes * 60 * 1000; checkintermission(); return 0; } LUA_FUNCTION (getautoteam) { lua_pushboolean( L, autoteam ); return 1; } LUA_FUNCTION (setautoteam) { lua_checkstack( L, 1 ); if ( !lua_isboolean( L, 1 ) ) return 0; autoteam = (bool) lua_toboolean( L, 1 ); sendservermode(); if ( m_teammode && autoteam ) refillteams( true ); return 0; } LUA_FUNCTION (disconnect) { lua_checkstack( L, 2 ); for ( int i = 1; i <= 2; i++ ) if ( !lua_isnumber( L, i ) ) return 0; int target_cn = (int) lua_tonumber( L, 1 ); if ( !valid_client( target_cn ) ) return 0; int reason = (int) lua_tonumber( L, 2 ); if ( !( reason >= 0 && reason < DISC_NUM ) && reason != -1 ) return 0; disconnect_client( target_cn, reason, true ); return 0; } LUA_FUNCTION (ban) { lua_checkstack( L, 3 ); if ( !lua_isnumber( L, 1 ) ) return 0; int target_cn = (int) lua_tonumber( L, 1 ); if ( !valid_client( target_cn ) ) return 0; int ban_time = scl.ban_time; if ( lua_isnumber( L, 2 ) ) ban_time = (int) lua_tonumber( L, 2 ); int ban_type = BAN_AUTO; if ( lua_isnumber( L, 3 ) ) ban_type = (int) lua_tonumber( L, 3 ); ban ban = { .address = clients[target_cn]->peer->address, .millis = servmillis + ban_time, .type = ban_type }; bans.add( ban ); disconnect_client( target_cn, DISC_MBAN, true ); return 0; } LUA_FUNCTION (setvelocity) { lua_checkstack( L, 5 ); for ( int i = 1; i <= 5; i++ ) if ( !lua_isnumber( L, i ) ) return 0; int target_cn = (int) lua_tonumber( L, 1 ); if ( !valid_client( target_cn ) ) return 0; sendf( target_cn, 1, "ri6", SV_HITPUSH, GUN_GRENADE, (int) lua_tonumber( L, 5 ), int( lua_tonumber( L, 2 ) * DNF ), int( lua_tonumber( L, 3 ) * DNF ), int( lua_tonumber( L, 4 ) * DNF ) ); return 0; } LUA_FUNCTION (getdefaultammo) { lua_checkstack( L, 1 ); if ( !lua_isnumber( L, 1 ) ) return 0; int weapon = (int) lua_tonumber( L, 1 ); if ( !( weapon >= 0 && weapon < NUMGUNS ) ) return 0; int mag = guns[weapon].magsize, ammo = ( ( weapon == GUN_PISTOL ) ? ammostats[weapon].max : ammostats[weapon].start ) - mag; lua_pushinteger( L, ammo ); lua_pushinteger( L, mag ); return 2; } static int stringsort( const char **x, const char **y ) { return strcmp( *x, *y ); } LUA_FUNCTION (getservermaps) { lua_checkstack( L, 1 ); vector<char*> maps; if ( lua_toboolean( L, 1 ) ) listfiles( SERVERMAP_PATH_BUILTIN, "cgz", maps ); listfiles( SERVERMAP_PATH, "cgz", maps ); listfiles( SERVERMAP_PATH_INCOMING, "cgz", maps ); maps.sort( stringsort ); lua_newtable( L ); loopv( maps ) { lua_pushinteger( L, i + 1 ); lua_pushstring( L, behindpath( maps[i] ) ); lua_settable( L, 1 ); } return 1; } LUA_FUNCTION (giveitem) { lua_checkstack( L, 2 ); for ( int i = 1; i <= 2; i++ ) if ( !lua_isnumber( L, i ) ) return 0; int target_cn = (int) lua_tonumber( L, 1 ); if ( !valid_client( target_cn ) ) return 0; int item_type = (int) lua_tonumber( L, 2 ); int item_id = sents.length(); sendf( target_cn, 1, "ri9", SV_EDITENT, item_id, item_type, 0, 0, 0, 0, 0, 0, 0 ); sendf( target_cn, 1, "ri3", SV_ITEMACC, item_id, target_cn ); clients[target_cn]->state.pickup( item_type ); return 0; } LUA_FUNCTION (shuffleteams) { sendf( -1, 1, "ri2", SV_SERVERMODE, sendservermode( false ) | AT_SHUFFLE ); shuffleteams(); return 0; } LUA_FUNCTION (getprotocol) { lua_pushinteger( L, server_protocol_version ); return 1; } LUA_FUNCTION (getdefaultprotocol) { lua_pushinteger( L, PROTOCOL_VERSION ); return 1; } LUA_FUNCTION (setprotocol) { lua_checkstack( L, 1 ); if ( !lua_isnumber( L, 1 ) ) return 0; server_protocol_version = (int) lua_tonumber( L, 1 ); return 0; } LUA_FUNCTION (luanotice) { lua_checkstack( L, 2 ); if ( !lua_isstring( L, 2 ) ) return 0; int origin = lua_gettop( L ) + 1; lua_pushvalue( L, 1 ); // копируем объект, посылаемый в скрипты как первый аргумент функции onLuaNotice; выталкивается в методе callHandler Lua::callHandler( LUA_ON_NOTICE, "os", L,origin, lua_tostring( L, 2 ) ); return 0; } LUA_FUNCTION (getnextmode) { lua_pushinteger( L, nextgamemode ); return 1; } LUA_FUNCTION (getnextmap) { lua_pushstring( L, nextmapname ); return 1; } LUA_FUNCTION (getmapitems) { lua_newtable( L ); loopv( sents ) { lua_pushinteger( L, i ); lua_pushinteger( L, sents[i].type ); lua_settable( L, 1 ); } return 1; } LUA_FUNCTION (spawnitem) { lua_checkstack( L, 2 ); if ( !lua_isnumber( L, 1 ) ) return 0; int item_id = (int) lua_tonumber( L, 1 ); if ( !sents.inrange( item_id ) ) return 0; sents[item_id].spawntime = 0; sents[item_id].spawned = true; vector<int> receiver_client_numbers; if ( lua_istable(L, 2)) { int n = luaL_getn( L, 2 ); for ( int i = 1; i <= n; i++ ) { lua_pushinteger( L, i ); lua_gettable( L, 2 ); receiver_client_numbers.add((int) lua_tonumber( L, lua_gettop( L ) )); } } else { // Default value: -1 = all connected clients receiver_client_numbers.add(-1); } loopv(receiver_client_numbers) { sendf( receiver_client_numbers[i], 1, "ri2", SV_ITEMSPAWN, item_id ); } return 0; } LUA_FUNCTION (removebans) { bans.shrink( 0 ); return 0; } LUA_FUNCTION (getscore) { lua_checkstack( L, 1 ); if ( !lua_isnumber( L, 1 ) ) return 0; int player_cn = (int) lua_tonumber( L, 1 ); if ( !valid_client( player_cn ) ) return 0; lua_pushinteger( L, clients[player_cn]->state.points ); return 1; } LUA_FUNCTION (setscore) { lua_checkstack( L, 2 ); for ( int i = 1; i <= 2; i++ ) if ( !lua_isnumber( L, i ) ) return 0; int target_cn = (int) lua_tonumber( L, 1 ); if ( !valid_client( target_cn ) ) return 0; clients[target_cn]->state.points = (int) lua_tonumber( L, 2 ); sendresume( *clients[target_cn], true ); return 0; } LUA_FUNCTION (getadminpwd) { lua_checkstack( L, 1 ); int line = 0; if ( lua_isnumber( L, 1 ) ) line = (int) lua_tonumber( L, 1 ); for ( int i = 0; i < passwords.adminpwds.length(); i++ ) if ( passwords.adminpwds[i].line == line ) { lua_pushstring( L, passwords.adminpwds[i].pwd ); return 1; } return 0; } LUA_FUNCTION (removeadminpwd) { lua_checkstack( L, 1 ); int line = -1; bool byLine = false; string adminpwd; bool byPassword = false; if ( lua_isnumber( L, 1 ) ) { line = (int) lua_tonumber( L, 1 ); byLine = true; } else if ( lua_isstring( L, 1 ) ) { copystring( adminpwd, lua_tostring( L, 1 ) ); byPassword = true; } if ( byLine || byPassword ) for ( int i = 0; i < passwords.adminpwds.length(); i++ ) if ( ( byPassword && strcmp( adminpwd, passwords.adminpwds[i].pwd ) == 0 ) || ( byLine && passwords.adminpwds[i].line == line ) ) { passwords.adminpwds.remove( i ); if ( i < passwords.staticpasses ) passwords.staticpasses--; break; } return 0; } LUA_FUNCTION (setmasterserver) { static string master = { '\0' }; lua_checkstack( L, 1 ); if ( !lua_isstring( L, 1 ) ) return 0; copystring( master, lua_tostring( L, 1 ) ); scl.master = master; return 0; } LUA_FUNCTION (getmaprotnextmap) { configset *cs = maprot.get( maprot.get_next() ); if ( cs ) { lua_pushstring( L, cs->mapname ); return 1; } return 0; } LUA_FUNCTION (getmaprotnextmode) { configset *cs = maprot.get( maprot.get_next() ); if ( cs ) { lua_pushinteger( L, cs->mode ); return 1; } return 0; } LUA_FUNCTION (getadminpwds) { lua_newtable( L ); for ( int i = 0; i < passwords.adminpwds.length(); i++ ) { lua_pushinteger( L, passwords.adminpwds[i].line ); lua_pushstring( L, passwords.adminpwds[i].pwd ); lua_settable( L, 1 ); } return 1; } LUA_FUNCTION (getwholemaprot) { lua_newtable( L ); loopv ( maprot.configsets ) { lua_pushinteger( L, i + 1 ); lua_newtable( L ); int table = lua_gettop( L ); lua_pushstring( L, maprot.configsets[i].mapname ); lua_setfield( L, table, "map" ); lua_pushinteger( L, maprot.configsets[i].mode ); lua_setfield( L, table, "mode" ); lua_pushinteger( L, maprot.configsets[i].time ); lua_setfield( L, table, "time" ); lua_pushinteger( L, maprot.configsets[i].vote ); lua_setfield( L, table, "allowVote" ); lua_pushinteger( L, maprot.configsets[i].minplayer ); lua_setfield( L, table, "minplayer" ); lua_pushinteger( L, maprot.configsets[i].maxplayer ); lua_setfield( L, table, "maxplayer" ); lua_pushinteger( L, maprot.configsets[i].skiplines ); lua_setfield( L, table, "skiplines" ); lua_settable( L, 1 ); } return 1; } /** * Converts a lua table to a configset that can be added to the active map rotation. * * @param lua_State L The Lua state to fetch the lua table from * @param int table The stack index of the lua table that should be fetched * * @return configset The generated configset */ configset convertLuaMapRotEntryToConfigSet(lua_State *L, int table) { configset cs; lua_getfield( L, table, "map" ); copystring( cs.mapname, lua_tostring( L, lua_gettop( L ) ) ); lua_getfield( L, table, "mode" ); cs.mode = (int) lua_tonumber( L, lua_gettop( L ) ); lua_getfield( L, table, "time" ); cs.time = (int) lua_tonumber( L, lua_gettop( L ) ); lua_getfield( L, table, "allowVote" ); if ( lua_isnumber( L, lua_gettop( L ) ) ) cs.vote = (int) lua_tonumber( L, lua_gettop( L ) ); else cs.vote = 1; lua_getfield( L, table, "minplayer" ); if ( lua_isnumber( L, lua_gettop( L ) ) ) cs.minplayer = (int) lua_tonumber( L, lua_gettop( L ) ); else cs.minplayer = 0; lua_getfield( L, table, "maxplayer" ); if ( lua_isnumber( L, lua_gettop( L ) ) ) cs.maxplayer = (int) lua_tonumber( L, lua_gettop( L ) ); else cs.maxplayer = 0; lua_getfield( L, table, "skiplines" ); if ( lua_isnumber( L, lua_gettop( L ) ) ) cs.skiplines = (int) lua_tonumber( L, lua_gettop( L ) ); else cs.skiplines = 0; lua_pop( L, 7 ); // the values lua_pop( L, 1 ); // the table return cs; } LUA_FUNCTION (setwholemaprot) { lua_checkstack( L, 1 ); if ( !lua_istable( L, 1 ) ) return 0; maprot.configsets.shrink( 0 ); int n = luaL_getn( L, 1 ); for ( int i = 1; i <= n; i++ ) { lua_pushinteger( L, i ); lua_gettable( L, 1 ); int table = lua_gettop( L ); configset cs = convertLuaMapRotEntryToConfigSet(L, table); maprot.configsets.add( cs ); } return 0; } LUA_FUNCTION (addmaprotentry) { lua_checkstack( L, 1 ); if ( !lua_istable( L, 1 ) ) return 0; configset cs = convertLuaMapRotEntryToConfigSet(L, 1); maprot.configsets.add( cs ); return 0; } LUA_FUNCTION (getwholebl) { lua_newtable( L ); loopv ( ipblacklist.ipranges ) { lua_pushinteger( L, i + 1 ); lua_newtable( L ); int table = lua_gettop( L ); lua_pushinteger( L, 1 ); lua_pushstring( L, iptoa( ipblacklist.ipranges[i].lr ) ); lua_settable( L, table ); lua_pushinteger( L, 2 ); lua_pushstring( L, iptoa( ipblacklist.ipranges[i].ur ) ); lua_settable( L, table ); lua_settable( L, 1 ); } return 1; } LUA_FUNCTION (setwholebl) { lua_checkstack( L, 1 ); if ( !lua_istable( L, 1 ) ) return 0; ipblacklist.ipranges.shrink( 0 ); int n = luaL_getn( L, 1 ); for ( int i = 1; i <= n; i++ ) { iprange ir; lua_pushinteger( L, i ); lua_gettable( L, 1 ); int table = lua_gettop( L ); lua_pushinteger( L, 1 ); lua_gettable( L, table ); atoip( lua_tostring( L, lua_gettop( L ) ), &ir.lr ); lua_pushinteger( L, 2 ); lua_gettable( L, table ); atoip( lua_tostring( L, lua_gettop( L ) ), &ir.ur ); lua_pop( L, 2 ); // the values lua_pop( L, 1 ); // the table ipblacklist.ipranges.add( ir ); } return 0; } LUA_FUNCTION (strtoiprange) { lua_checkstack( L, 1 ); if ( !lua_isstring( L, 1 ) ) return 0; iprange ir; if ( atoipr( lua_tostring( L, 1 ), &ir ) == NULL ) return 0; lua_newtable( L ); lua_pushinteger( L, 1 ); lua_pushstring( L, iptoa( ir.lr ) ); lua_settable( L, 2 ); lua_pushinteger( L, 2 ); lua_pushstring( L, iptoa( ir.ur ) ); lua_settable( L, 2 ); return 1; } LUA_FUNCTION (setsockettype) { lua_checkstack( L, 2 ); for ( int i = 1; i <= 2; i++ ) if ( !lua_isnumber( L, i ) ) return 0; int target_cn = (int) lua_tonumber( L, 1 ); if ( !clients.inrange( target_cn ) ) return 0; int socket_type = (int) lua_tonumber( L, 2 ); clients[target_cn]->type = socket_type; return 0; } LUA_FUNCTION (addclient) { client& cl = addclient(); lua_pushinteger( L, cl.clientnum ); return 1; } LUA_FUNCTION (initclient) { lua_checkstack( L, 1 ); if ( !lua_isnumber( L, 1 ) ) return 0; int target_cn = (int) lua_tonumber( L, 1 ); if ( !clients.inrange( target_cn ) ) return 0; clients[target_cn]->isauthed = true; clients[target_cn]->haswelcome = true; sendinitclient( *clients[target_cn] ); return 0; } LUA_FUNCTION (delclient) { lua_checkstack( L, 1 ); if ( !lua_isnumber( L, 1 ) ) return 0; int target_cn = (int) lua_tonumber( L, 1 ); if ( !clients.inrange( target_cn ) ) return 0; clients[target_cn]->zap(); sendf( -1, 1, "ri2", SV_CDIS, target_cn ); return 0; } LUA_FUNCTION (sethostname) { lua_checkstack( L, 2 ); if ( !lua_isnumber( L, 1 ) || !lua_isstring( L, 2 ) ) return 0; int target_cn = (int) lua_tonumber( L, 1 ); if ( !clients.inrange( target_cn ) ) return 0; copystring( clients[target_cn]->hostname, lua_tostring( L, 2 ) ); return 0; } LUA_FUNCTION (sayas) { lua_checkstack( L, 4 ); if ( !lua_isstring( L, 1 ) || !lua_isnumber( L, 2 ) ) return 0; bool team = false; if ( lua_isboolean( L, 3 ) ) team = (bool) lua_toboolean( L, 3 ); bool me = false; if ( lua_isboolean( L, 4 ) ) me = (bool) lua_toboolean( L, 4 ); int player_cn = (int) lua_tonumber( L, 2 ); if ( !valid_client( player_cn ) ) return 0; char text[MAXTRANS]; copystring( text, lua_tostring( L, 1 ) ); filtertext( text, text ); trimtrailingwhitespace( text ); if ( team ) sendteamtext( text, player_cn, me ? SV_TEAMTEXTME : SV_TEAMTEXT ); else as_player( player_cn, "isx", me ? SV_TEXTME : SV_TEXT, text, player_cn ); return 0; } LUA_FUNCTION (voiceas) { lua_checkstack( L, 3 ); for ( int i = 1; i <= 2; i++ ) if ( !lua_isnumber( L, i ) ) return 0; bool team = false; if ( lua_isboolean( L, 3 ) ) team = (bool) lua_toboolean( L, 3 ); int player_cn = (int) lua_tonumber( L, 2 ); if ( !valid_client( player_cn ) ) return 0; int sound = (int) lua_tonumber( L, 1 ); if ( sound < 0 || sound >= S_NULL ) return 0; if ( team ) sendvoicecomteam( sound, player_cn ); else as_player( player_cn, "iix", SV_VOICECOM, sound, player_cn ); return 0; } LUA_FUNCTION (getgamemillis) { lua_pushinteger( L, gamemillis ); return 1; } LUA_FUNCTION (getgamelimit) { lua_pushinteger( L, gamelimit ); return 1; } LUA_FUNCTION (gettimeleftmillis) { lua_pushinteger( L, gamelimit - gamemillis ); return 1; } LUA_FUNCTION (settimeleftmillis) { lua_checkstack( L, 1 ); if ( !lua_isnumber( L, 1 ) ) return 0; int remaining_millis = (int) lua_tonumber( L, 1 ); intermission_check_shear = 60 * 1000 - gamemillis % (60 * 1000) + framemillis; gamelimit = gamemillis + remaining_millis; checkintermission(); return 0; } LUA_FUNCTION (setping) { lua_checkstack( L, 2 ); for ( int i = 1; i <= 2; i++ ) if ( !lua_isnumber( L, i ) ) return 0; int target_cn = (int) lua_tonumber( L, 1 ); if ( !valid_client( target_cn ) ) return 0; int ping = (int) lua_tonumber( L, 2 ); clients[target_cn]->ping = ping; return 0; } LUA_FUNCTION (setangle) { lua_checkstack( L, 3 ); for ( int i = 1; i <= 3; i++ ) if ( !lua_isnumber( L, i ) ) return 0; int target_cn = (int) lua_tonumber( L, 1 ); if ( !valid_client( target_cn ) ) return 0; clients[target_cn]->y = (int) lua_tonumber( L, 2 ); // hor clients[target_cn]->p = (int) lua_tonumber( L, 3 ); // ver return 0; } LUA_FUNCTION (removeban) { lua_checkstack( L, 1 ); if ( !lua_isstring( L, 1 ) ) return 0; enet_uint32 ip; if ( atoip( lua_tostring( L, 1 ), &ip ) == NULL ) return 0; loopv( bans ) { ban &ban = bans[i]; if ( ban.address.host == ip ) { bans.remove( i ); break; } } return 0; } LUA_FUNCTION (getbans) { lua_newtable( L ); loopv ( bans ) { lua_pushinteger( L, i + 1 ); lua_newtable( L ); int table = lua_gettop( L ); lua_pushinteger( L, 1 ); lua_pushstring( L, iptoa( bans[i].address.host ) ); lua_settable( L, table ); lua_pushinteger( L, 2 ); lua_pushinteger( L, bans[i].millis ); lua_settable( L, table ); lua_pushinteger( L, 3 ); lua_pushinteger( L, bans[i].type ); lua_settable( L, table ); lua_settable( L, 1 ); } return 1; } LUA_FUNCTION (getmaprotnexttimeleft) { configset *cs = maprot.get( maprot.get_next() ); if ( cs ) { lua_pushinteger( L, cs->time ); return 1; } return 0; } LUA_FUNCTION (getmaprotnextentry) { configset *cs = maprot.get( maprot.get_next() ); if ( cs ) { lua_newtable( L ); int table = lua_gettop( L ); lua_pushstring( L, cs->mapname ); lua_setfield( L, table, "map" ); lua_pushinteger( L, cs->mode ); lua_setfield( L, table, "mode" ); lua_pushinteger( L, cs->time ); lua_setfield( L, table, "time" ); lua_pushinteger( L, cs->vote ); lua_setfield( L, table, "allowVote" ); lua_pushinteger( L, cs->minplayer ); lua_setfield( L, table, "minplayer" ); lua_pushinteger( L, cs->maxplayer ); lua_setfield( L, table, "maxplayer" ); lua_pushinteger( L, cs->skiplines ); lua_setfield( L, table, "skiplines" ); return 1; } return 0; } LUA_FUNCTION (getspawnmillis) { lua_checkstack( L, 1 ); if ( !lua_isnumber( L, 1 ) ) return 0; int player_cn = (int) lua_tonumber( L, 1 ); if ( !valid_client( player_cn ) ) return 0; lua_pushinteger( L, clients[player_cn]->state.spawn ); return 1; } LUA_FUNCTION (cla_iterator) { IteratorData &it = *(IteratorData*) lua_touserdata( L, lua_upvalueindex( 1 ) ); for ( ; it.player_cn < clients.length(); it.player_cn++ ) { if ( valid_client( it.player_cn ) && ( clients[it.player_cn]->team == TEAM_CLA || clients[it.player_cn]->team == TEAM_CLA_SPECT ) && ( !it.alive_only || clients[it.player_cn]->state.state == CS_ALIVE ) ) { lua_pushinteger( L, it.player_cn++ ); return 1; } } return 0; } LUA_FUNCTION (cla) { lua_checkstack( L, 1 ); bool alive_only = false; if ( lua_isboolean( L, 1 ) ) alive_only = (bool) lua_toboolean( L, 1 ); IteratorData &it = *(IteratorData*) lua_newuserdata( L, sizeof( IteratorData ) ); it.alive_only = alive_only; it.player_cn = 0; luaL_getmetatable( L, "IteratorData" ); lua_setmetatable( L, -2 ); lua_pushcclosure( L, __cla_iterator, 1 ); return 1; } LUA_FUNCTION (rvsf_iterator) { IteratorData &it = *(IteratorData*) lua_touserdata( L, lua_upvalueindex( 1 ) ); for ( ; it.player_cn < clients.length(); it.player_cn++ ) { if ( valid_client( it.player_cn ) && ( clients[it.player_cn]->team == TEAM_RVSF || clients[it.player_cn]->team == TEAM_RVSF_SPECT ) && ( !it.alive_only || clients[it.player_cn]->state.state == CS_ALIVE ) ) { lua_pushinteger( L, it.player_cn++ ); return 1; } } return 0; } LUA_FUNCTION (rvsf) { lua_checkstack( L, 1 ); bool alive_only = false; if ( lua_isboolean( L, 1 ) ) alive_only = (bool) lua_toboolean( L, 1 ); IteratorData &it = *(IteratorData*) lua_newuserdata( L, sizeof( IteratorData ) ); it.alive_only = alive_only; it.player_cn = 0; luaL_getmetatable( L, "IteratorData" ); lua_setmetatable( L, -2 ); lua_pushcclosure( L, __rvsf_iterator, 1 ); return 1; } LUA_FUNCTION (spectators_iterator) { IteratorData &it = *(IteratorData*) lua_touserdata( L, lua_upvalueindex( 1 ) ); for ( ; it.player_cn < clients.length(); it.player_cn++ ) { if ( valid_client( it.player_cn ) && ( clients[it.player_cn]->team == TEAM_SPECT || clients[it.player_cn]->team == TEAM_RVSF_SPECT || clients[it.player_cn]->team == TEAM_CLA_SPECT ) ) { lua_pushinteger( L, it.player_cn++ ); return 1; } } return 0; } LUA_FUNCTION (spectators) { IteratorData &it = *(IteratorData*) lua_newuserdata( L, sizeof( IteratorData ) ); it.player_cn = 0; luaL_getmetatable( L, "IteratorData" ); lua_setmetatable( L, -2 ); lua_pushcclosure( L, __spectators_iterator, 1 ); return 1; } LUA_FUNCTION (players_iterator) { IteratorData &it = *(IteratorData*) lua_touserdata( L, lua_upvalueindex( 1 ) ); for ( ; it.player_cn < clients.length(); it.player_cn++ ) { if ( valid_client( it.player_cn ) && ( !it.alive_only || ( clients[it.player_cn]->state.state == CS_ALIVE && clients[it.player_cn]->team != TEAM_SPECT ) ) ) { lua_pushinteger( L, it.player_cn++ ); return 1; } } return 0; } LUA_FUNCTION (players) { lua_checkstack( L, 1 ); bool alive_only = false; if ( lua_isboolean( L, 1 ) ) alive_only = (bool) lua_toboolean( L, 1 ); IteratorData &it = *(IteratorData*) lua_newuserdata( L, sizeof( IteratorData ) ); it.alive_only = alive_only; it.player_cn = 0; luaL_getmetatable( L, "IteratorData" ); lua_setmetatable( L, -2 ); lua_pushcclosure( L, __players_iterator, 1 ); return 1; } LUA_FUNCTION (logline) { lua_checkstack( L, 2 ); if ( !lua_isnumber( L, 1 ) || !lua_isstring( L, 2 ) ) return 0; logline( lua_tonumber( L, 1 ), "%s", lua_tostring( L, 2 ) ); return 0; } LUA_FUNCTION (setmaprotnextentry) { lua_checkstack( L, 1 ); if ( !lua_istable( L, 1 ) ) return 0; configset *cs = maprot.get( maprot.get_next() ); if ( cs ) { lua_getfield( L, 1, "map" ); copystring( cs->mapname, lua_tostring( L, lua_gettop( L ) ) ); lua_getfield( L, 1, "mode" ); cs->mode = (int) lua_tonumber( L, lua_gettop( L ) ); lua_getfield( L, 1, "time" ); cs->time = (int) lua_tonumber( L, lua_gettop( L ) ); lua_getfield( L, 1, "allowVote" ); if ( lua_isnumber( L, lua_gettop( L ) ) ) cs->vote = (int) lua_tonumber( L, lua_gettop( L ) ); else cs->vote = 1; lua_getfield( L, 1, "minplayer" ); if ( lua_isnumber( L, lua_gettop( L ) ) ) cs->minplayer = (int) lua_tonumber( L, lua_gettop( L ) ); else cs->minplayer = 0; lua_getfield( L, 1, "maxplayer" ); if ( lua_isnumber( L, lua_gettop( L ) ) ) cs->maxplayer = (int) lua_tonumber( L, lua_gettop( L ) ); else cs->maxplayer = 0; lua_getfield( L, 1, "skiplines" ); if ( lua_isnumber( L, lua_gettop( L ) ) ) cs->skiplines = (int) lua_tonumber( L, lua_gettop( L ) ); else cs->skiplines = 0; lua_pop( L, 7 ); } return 0; } LUA_FUNCTION (setmaprotnextmap) { lua_checkstack( L, 1 ); if ( !lua_isstring( L, 1 ) ) return 0; configset *cs = maprot.get( maprot.get_next() ); if ( cs ) copystring( cs->mapname, lua_tostring( L, 1 ) ); return 0; } LUA_FUNCTION (setmaprotnextmode) { lua_checkstack( L, 1 ); if ( !lua_isnumber( L, 1 ) ) return 0; configset *cs = maprot.get( maprot.get_next() ); if ( cs ) cs->mode = (int) lua_tonumber( L, 1 ); return 0; } LUA_FUNCTION (setmaprotnexttimeleft) { lua_checkstack( L, 1 ); if ( !lua_isnumber( L, 1 ) ) return 0; configset *cs = maprot.get( maprot.get_next() ); if ( cs ) cs->time = (int) lua_tonumber( L, 1 ); return 0; } LUA_FUNCTION (getreloadtime) { lua_checkstack( L, 1 ); if ( !lua_isnumber( L, 1 ) ) return 0; int gun = (int) lua_tonumber( L, 1 ); if ( !( gun >= 0 && gun < NUMGUNS ) ) return 0; lua_pushinteger( L, reloadtime( gun ) ); return 1; } LUA_FUNCTION (getattackdelay) { lua_checkstack( L, 1 ); if ( !lua_isnumber( L, 1 ) ) return 0; int gun = (int) lua_tonumber( L, 1 ); if ( !( gun >= 0 && gun < NUMGUNS ) ) return 0; lua_pushinteger( L, attackdelay( gun ) ); return 1; } LUA_FUNCTION (getmagsize) { lua_checkstack( L, 1 ); if ( !lua_isnumber( L, 1 ) ) return 0; int gun = (int) lua_tonumber( L, 1 ); if ( !( gun >= 0 && gun < NUMGUNS ) ) return 0; lua_pushinteger( L, magsize( gun ) ); return 1; } LUA_FUNCTION (getsessionid) { lua_checkstack( L, 1 ); if ( !lua_isnumber( L, 1 ) ) return 0; int player_cn = (int) lua_tonumber( L, 1 ); if ( !valid_client( player_cn ) ) return 0; lua_pushinteger( L, clients[player_cn]->salt ); return 1; } LUA_FUNCTION (setscoping) { lua_checkstack( L, 2 ); if ( !lua_isnumber( L, 1 ) || !lua_isboolean( L, 2 ) ) return 0; int target_cn = (int) lua_tonumber( L, 1 ); if ( !valid_client( target_cn ) ) return 0; bool scoping = (bool) lua_toboolean( L, 2 ); clients[target_cn]->g -= clients[target_cn]->g & ( 1 << 4 ); clients[target_cn]->g |= ( ( int ) scoping ) << 4; clients[target_cn]->state.scoping = scoping; return 0; } LUA_FUNCTION (setcrouching) { lua_checkstack( L, 2 ); if ( !lua_isnumber( L, 1 ) || !lua_isboolean( L, 2 ) ) return 0; int target_cn = (int) lua_tonumber( L, 1 ); if ( !valid_client( target_cn ) ) return 0; bool crouching = (bool) lua_toboolean( L, 2 ); clients[target_cn]->f -= clients[target_cn]->f & ( 1 << 7 ); clients[target_cn]->f |= ( ( int ) crouching ) << 7; clients[target_cn]->state.crouching = crouching; return 0; } LUA_FUNCTION (shootas) { lua_checkstack( L, 2 ); if ( !lua_isnumber( L, 1 ) || !lua_istable( L, 2 ) ) return 0; int player_cn = (int) lua_tonumber( L, 1 ); if ( !valid_client( player_cn ) ) return 0; gameevent &event = clients[player_cn]->addevent(); event.type = GE_SHOT; event.shot.id = event.shot.millis = gamemillis; event.shot.gun = clients[player_cn]->state.gunselect; loopk(3) { event.shot.from[k] = clients[player_cn]->state.o.v[k] + ( k == 2 ? (((clients[player_cn]->f>>7)&1)?2.2f:4.2f) : 0); } lua_pushinteger( L, 1 ); lua_gettable( L, 2 ); event.shot.to[0] = (float) lua_tonumber( L, lua_gettop( L ) ); lua_pushinteger( L, 2 ); lua_gettable( L, 2 ); event.shot.to[1] = (float) lua_tonumber( L, lua_gettop( L ) ); lua_pushinteger( L, 3 ); lua_gettable( L, 2 ); event.shot.to[2] = (float) lua_tonumber( L, lua_gettop( L ) ); lua_pop( L, 3 ); return 0; } LUA_FUNCTION (reloadas) { lua_checkstack( L, 1 ); if ( !lua_isnumber( L, 1 ) ) return 0; int player_cn = (int) lua_tonumber( L, 1 ); if ( !valid_client( player_cn ) ) return 0; gameevent &event = clients[player_cn]->addevent(); event.type = GE_RELOAD; event.reload.id = event.reload.millis = gamemillis; event.reload.gun = clients[player_cn]->state.gunselect; return 0; } LUA_FUNCTION (pickupas) { lua_checkstack( L, 2 ); for ( int i = 1; i <= 2; i++ ) if ( !lua_isnumber( L, i ) ) return 0; int player_cn = (int) lua_tonumber( L, 1 ); if ( !valid_client( player_cn ) ) return 0; gameevent &event = clients[player_cn]->addevent(); event.type = GE_PICKUP; event.pickup.ent = (int) lua_tonumber( L, 2 ); return 0; } LUA_FUNCTION (setip) // копия sethostname { /* lua_checkstack( L, 2 ); if ( !lua_isnumber( L, 1 ) || !lua_isstring( L, 2 ) ) return 0; int target_cn = (int) lua_tonumber( L, 1 ); if ( !clients.inrange( target_cn ) ) return 0; copystring( clients[target_cn]->hostname, lua_tostring( L, 2 ) ); return 0; */ return __sethostname( L ); } LUA_FUNCTION (removemap) { lua_checkstack( L, 1 ); string map; copystring( map, lua_tostring( L, 1 ) ); filtertext( map, map ); const char *mapname = behindpath( map ); int mp = findmappath( mapname ); if ( readonlymap( mp ) || mp == MAP_NOTFOUND ) lua_pushboolean( L, 0 ); else { string file; formatstring( file )( SERVERMAP_PATH_INCOMING "%s.cgz", mapname ); remove( file ); formatstring( file )( SERVERMAP_PATH_INCOMING "%s.cfg", mapname ); remove( file ); lua_pushboolean( L, 1 ); } return 1; } LUA_FUNCTION (mapisok) { lua_checkstack( L, 1 ); mapstats *ms; if ( lua_isstring( L, 1 ) ) ms = getservermapstats( lua_tostring( L, 1 ), false, NULL ); else if ( lua_isnil( L, 1 ) ) ms = &smapstats; else return 0; lua_pushboolean( L, ( ms != NULL && mapisok( ms ) ) ); return 1; } LUA_FUNCTION (mapexists) { lua_checkstack( L, 1 ); string map; copystring( map, lua_tostring( L, 1 ) ); filtertext( map, map ); const char *mapname = behindpath( map ); int mp = findmappath( mapname ); lua_pushboolean( L, mp != MAP_NOTFOUND ); return 1; } LUA_FUNCTION (isonfloor) { lua_checkstack( L, 1 ); if ( !lua_isnumber( L, 1 ) ) return 0; int player_cn = (int) lua_tonumber( L, 1 ); if ( !valid_client( player_cn ) ) return 0; lua_pushboolean( L, clients[player_cn]->state.onfloor ); return 1; } LUA_FUNCTION (isonladder) { lua_checkstack( L, 1 ); if ( !lua_isnumber( L, 1 ) ) return 0; int player_cn = (int) lua_tonumber( L, 1 ); if ( !valid_client( player_cn ) ) return 0; lua_pushboolean( L, clients[player_cn]->state.onladder ); return 1; } LUA_FUNCTION (isscoping) { lua_checkstack( L, 1 ); if ( !lua_isnumber( L, 1 ) ) return 0; int player_cn = (int) lua_tonumber( L, 1 ); if ( !valid_client( player_cn ) ) return 0; lua_pushboolean( L, clients[player_cn]->state.scoping ); return 1; } LUA_FUNCTION (iscrouching) { lua_checkstack( L, 1 ); if ( !lua_isnumber( L, 1 ) ) return 0; int player_cn = (int) lua_tonumber( L, 1 ); if ( !valid_client( player_cn ) ) return 0; lua_pushboolean( L, clients[player_cn]->state.crouching ); return 1; } LUA_FUNCTION (voteas) { lua_checkstack( L, 2 ); for ( int i = 1; i <= 2; i++ ) if ( !lua_isnumber( L, i ) ) return 0; int player_cn = (int) lua_tonumber( L, 1 ); if ( !valid_client( player_cn ) ) return 0; int vote = (int) lua_tonumber( L, 2 ); if ( !curvote || vote < VOTE_YES || vote > VOTE_NO ) return 0; if ( clients[player_cn]->vote == VOTE_NEUTRAL ) { packetbuf packet( MAXTRANS, ENET_PACKET_FLAG_RELIABLE ); putint( packet, SV_VOTE ); putint( packet, vote ); sendpacket( -1, 1, packet.finalize(), player_cn ); clients[player_cn]->vote = vote; Lua_evaluateVote(); } return 0; } LUA_FUNCTION (getitempos) { lua_checkstack( L, 1 ); if ( !lua_isnumber( L, 1 ) ) return 0; int item_id = (int) lua_tonumber( L, 1 ); if ( !sents.inrange( item_id ) ) return 0; lua_pushnumber( L, sents[item_id].x ); lua_pushnumber( L, sents[item_id].y ); lua_pushnumber( L, sents[item_id].z ); return 3; } LUA_FUNCTION (isitemspawned) { lua_checkstack( L, 1 ); if ( !lua_isnumber( L, 1 ) ) return 0; int item_id = (int) lua_tonumber( L, 1 ); if ( !sents.inrange( item_id ) ) return 0; lua_pushboolean( L, sents[item_id].spawned ); return 1; } LUA_FUNCTION (setstate) { lua_checkstack( L, 2 ); for ( int i = 1; i <= 2; i++ ) if ( !lua_isnumber( L, i ) ) return 0; int target_cn = (int) lua_tonumber( L, 1 ); if ( !valid_client( target_cn ) ) return 0; int state = (int) lua_tonumber( L, 2 ); if ( !( state >= CS_ALIVE && state <= CS_SPECTATE ) ) return 0; clients[target_cn]->state.state = state; return 0; } LUA_FUNCTION (sendspawn) { lua_checkstack( L, 1 ); if ( !lua_isnumber( L, 1 ) ) return 0; int target_cn = (int) lua_tonumber( L, 1 ); if ( !valid_client( target_cn ) ) return 0; sendspawn( clients[target_cn], true ); return 0; } LUA_FUNCTION (clienthasflag) { lua_checkstack( L, 1 ); if ( !lua_isnumber( L, 1 ) ) return 0; int player_cn = (int) lua_tonumber( L, 1 ); if ( !valid_client( player_cn ) || !m_flags ) return 0; int flag = clienthasflag( player_cn ); if ( flag == -1 ) return 0; lua_pushnumber( L, flag ); return 1; /* loopi(2) { if ( sflaginfos[i].state == CTFF_STOLEN && sflaginfos[i].actor_cn == player_cn ) { lua_pushnumber( L, i ); return 1; } } return 0; */ } LUA_FUNCTION (getmappath) { lua_checkstack( L, 1 ); string map; copystring( map, lua_tostring( L, 1 ) ); filtertext( map, map ); const char *mapname = behindpath( map ); string mappath; int mp = findmappath( mapname, mappath ); if ( mp == MAP_NOTFOUND ) return 0; lua_pushstring( L, mappath ); return 1; } LUA_FUNCTION (getvote) { lua_checkstack( L, 2 ); if ( !lua_isnumber( L, 1 ) ) return 0; int player_cn = (int) lua_tonumber( L, 1 ); if ( !valid_client( player_cn ) ) return 0; lua_pushnumber( L, clients[player_cn]->vote ); return 1; } LUA_FUNCTION (getpushfactor) { lua_checkstack( L, 1 ); if ( !lua_isnumber( L, 1 ) ) return 0; int weapon = (int) lua_tonumber( L, 1 ); if ( !( weapon >= 0 && weapon < NUMGUNS ) ) return 0; lua_pushnumber( L, guns[weapon].pushfactor ); return 1; } LUA_FUNCTION (genpwdhash) { lua_checkstack( L, 3 ); if ( !lua_isstring( L, 1 ) ) return 0; const char *player_name = lua_tostring( L, 1 ); if ( !lua_isstring( L, 2 ) ) return 0; const char *password = lua_tostring( L, 2 ); if ( !lua_isnumber( L, 3 ) ) return 0; int session_id = (int) lua_tonumber( L, 3 ); lua_pushstring( L, genpwdhash( player_name, password, session_id ) ); return 1; } LUA_FUNCTION (addms) { lua_checkstack( L, 1 ); if ( !lua_isstring( L, 1 ) ) return 0; const char *name = lua_tostring( L, 1 ); servermsappend( name ); servermsinit( masterservers - 1, name, scl.ip, CUBE_SERVINFO_PORT( scl.serverport ), true ); return 0; } LUA_FUNCTION (updatems) { loopi( masterservers ) updatemasterserver( i, servmillis, serverhost->address.port, true ); return 0; } LUA_FUNCTION (getmasterserver) { lua_pushstring( L, scl.master ); return 1; } LUA_FUNCTION (getmasterservers) { lua_newtable( L ); loopi( masterservers ) { lua_pushinteger( L, i + 1 ); lua_pushstring( L, mastername[i].c_str() ); lua_settable( L, 1 ); } return 1; } LUA_FUNCTION (removems) { lua_checkstack( L, 1 ); if ( !lua_isstring( L, 1 ) ) return 0; servermsremove( lua_tostring( L, 1 ) ); return 0; } LUA_FUNCTION (getacversion) { lua_checkstack( L, 1 ); if ( !lua_isnumber( L, 1 ) ) return 0; int player_cn = (int) lua_tonumber( L, 1 ); if ( !valid_client( player_cn ) ) return 0; lua_pushinteger( L, clients[player_cn]->acversion ); return 1; } LUA_FUNCTION (getacbuildtype) { lua_checkstack( L, 1 ); if ( !lua_isnumber( L, 1 ) ) return 0; int player_cn = (int) lua_tonumber( L, 1 ); if ( !valid_client( player_cn ) ) return 0; lua_pushinteger( L, clients[player_cn]->acbuildtype ); return 1; } LUA_FUNCTION (getconnectmillis) { lua_checkstack( L, 1 ); if ( !lua_isnumber( L, 1 ) ) return 0; int player_cn = (int) lua_tonumber( L, 1 ); if ( !valid_client( player_cn ) ) return 0; lua_pushinteger( L, clients[player_cn]->connectmillis ); return 1; } LUA_FUNCTION (gettotalsent) { unsigned long long int totalSent = Lua_totalSent; std::string str; while ( totalSent > 0ull ) { str.insert( 0, 1, char(totalSent % 10ull + '0') ); totalSent /= 10ull; } lua_pushstring( L, str.c_str() ); return 1; } LUA_FUNCTION (gettotalreceived) { unsigned long long int totalReceived = Lua_totalReceived; std::string str; while ( totalReceived > 0ull ) { str.insert( 0, 1, char(totalReceived % 10ull + '0') ); totalReceived /= 10ull; } lua_pushstring( L, str.c_str() ); return 1; } LUA_FUNCTION (cleargbans) { cleargbans(); return 0; } LUA_FUNCTION (addgban) { lua_checkstack( L, 1 ); if ( !lua_isstring( L, 1 ) ) return 0; addgban( lua_tostring( L, 1 ) ); return 0; } LUA_FUNCTION (checkgban) { lua_checkstack( L, 1 ); if ( !lua_isstring( L, 1 ) ) return 0; enet_uint32 ip; if ( atoip( lua_tostring( L, 1 ), &ip ) == NULL ) return 0; lua_pushboolean( L, checkgban( ip ) ); return 1; } LUA_FUNCTION (getteamkills) { lua_checkstack( L, 1 ); if ( !lua_isnumber( L, 1 ) ) return 0; int player_cn = (int) lua_tonumber( L, 1 ); if ( !valid_client( player_cn ) ) return 0; lua_pushinteger( L, clients[player_cn]->state.teamkills ); return 1; } LUA_FUNCTION (setteamkills) { lua_checkstack( L, 2 ); for ( int i = 1; i <= 2; i++ ) if ( !lua_isnumber( L, i ) ) return 0; int target_cn = (int) lua_tonumber( L, 1 ); if ( !valid_client( target_cn ) ) return 0; clients[target_cn]->state.teamkills = (int) lua_tonumber( L, 2 ); return 0; } LUA_FUNCTION (rereadcfgs) { rereadcfgs(); return 0; } LUA_FUNCTION (callhandler) { lua_checkstack( L, 1 ); if ( !lua_isstring( L, 1 ) ) return 0; const char *handler = lua_tostring( L, 1 ); int argc = lua_gettop( L ) - 1; int origin = lua_gettop( L ) + 1; for ( int i = 0; i < argc; ++i ) lua_pushvalue( L, 2 + i ); LuaArg *args = new LuaArg[1]; args[0].type = 'o'; args[0].count = argc; args[0].lsp = L; args[0].origin = origin; lua_pushinteger( L, Lua::callHandler( handler, 1, args ) ); delete[] args; return 1; } LUA_FUNCTION (isediting) { lua_checkstack( L, 1 ); if ( !lua_isnumber( L, 1 ) ) return 0; int player_cn = (int) lua_tonumber( L, 1 ); if ( !valid_client( player_cn ) ) return 0; lua_pushboolean( L, (int) ( clients[player_cn]->state.state == CS_EDITING ) ); return 1; } LUA_FUNCTION (flashonradar) { lua_checkstack( L, 1 ); if ( !lua_isnumber( L, 1 ) ) return 0; int target_cn = (int) lua_tonumber( L, 1 ); if ( !valid_client( target_cn ) ) return 0; as_player( target_cn, "i8", SV_THROWNADE, 0,0,0, 0,0,0, -1 ); return 0; } LUA_FUNCTION (isalive) { lua_checkstack( L, 1 ); if ( !lua_isnumber( L, 1 ) ) return 0; int player_cn = (int) lua_tonumber( L, 1 ); if ( !valid_client( player_cn ) ) return 0; lua_pushboolean( L, (int) ( clients[player_cn]->state.state == CS_ALIVE ) ); return 1; } LUA_FUNCTION (getwaterlevel) { lua_checkstack( L, 1 ); mapstats *ms; if ( lua_isstring( L, 1 ) ) ms = getservermapstats( lua_tostring( L, 1 ), false, NULL ); else if ( lua_isnil( L, 1 ) ) ms = &smapstats; else return 0; if ( ms == NULL ) return 0; lua_pushinteger( L, ms->hdr.waterlevel ); return 1; } LUA_FUNCTION (isinwater) { lua_checkstack( L, 1 ); if ( !lua_isnumber( L, 1 ) ) return 0; int player_cn = (int) lua_tonumber( L, 1 ); if ( !valid_client( player_cn ) ) return 0; lua_pushboolean( L, (int) ( clients[player_cn]->state.o.z < smapstats.hdr.waterlevel ) ); return 1; } LUA_FUNCTION (isunderwater) { lua_checkstack( L, 1 ); if ( !lua_isnumber( L, 1 ) ) return 0; int player_cn = (int) lua_tonumber( L, 1 ); if ( !valid_client( player_cn ) ) return 0; lua_pushboolean( L, (int) ( clients[player_cn]->state.o.z + (((clients[player_cn]->f>>7)&1)?2.2f:4.2f) < smapstats.hdr.waterlevel ) ); return 1; } LUA_FUNCTION (callgenerator) { lua_checkstack( L, 1 ); if ( !lua_isstring( L, 1 ) ) return 0; const char *handler = lua_tostring( L, 1 ); int argc = lua_gettop( L ) - 1; int origin = lua_gettop( L ) + 1; for ( int i = 0; i < argc; ++i ) lua_pushvalue( L, 2 + i ); LuaArg *args = new LuaArg[2]; args[0].type = 'o'; args[0].count = argc; args[0].lsp = L; args[0].origin = origin; args[1].type = 'S'; args[1].lsp = L; args[1].origin = origin; int n = 0; Lua::getFakeVariable( handler, &n, LUA_TNONE, 2, args ); delete[] args; return n; } LUA_FUNCTION (getlastsay) { lua_checkstack( L, 1 ); if ( !lua_isnumber( L, 1 ) ) return 0; int player_cn = (int) lua_tonumber( L, 1 ); if ( !valid_client( player_cn ) ) return 0; lua_pushinteger( L, clients[player_cn]->lastsay ); return 1; } LUA_FUNCTION (getlastsaytext) { lua_checkstack( L, 1 ); if ( !lua_isnumber( L, 1 ) ) return 0; int player_cn = (int) lua_tonumber( L, 1 ); if ( !valid_client( player_cn ) ) return 0; lua_pushstring( L, clients[player_cn]->lastsaytext ); return 1; } LUA_FUNCTION (authclient) { lua_checkstack( L, 2 ); if ( !lua_isnumber( L, 1 ) ) return 0; if ( !lua_isboolean( L, 2 ) ) return 0; int target_cn = (int) lua_tonumber( L, 1 ); if ( !valid_client( target_cn ) ) return 0; int authed = (int) lua_toboolean( L, 2 ); clients[target_cn]->isauthed = authed; return 0; } LUA_FUNCTION (isauthed) { lua_checkstack( L, 1 ); if ( !lua_isnumber( L, 1 ) ) return 0; int player_cn = (int) lua_tonumber( L, 1 ); if ( !valid_client( player_cn ) ) return 0; lua_pushboolean( L, clients[player_cn]->isauthed ); return 1; } LUA_FUNCTION (spawntime) { lua_checkstack( L, 1 ); if ( !lua_isnumber( L, 1 ) ) return 0; int item_type = (int) lua_tonumber( L, 1 ); lua_pushnumber( L, spawntime(item_type) ); return 1; } //END Lua global functions
92,245
42,697
#ifndef CPU_HPP #define CPU_HPP #include "register.hpp" #include <vector> namespace fusion { struct CPU { RegisterFile _regs; std::vector<uint8_t> _ram; CPU(); void loop(); }; } #endif // CPU_HPP
204
89
// Copyright 2019 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/ash/login/ui/oobe_dialog_size_utils.h" #include <stddef.h> #include "base/macros.h" #include "base/test/scoped_feature_list.h" #include "testing/gtest/include/gtest/gtest.h" #include "ui/gfx/geometry/insets.h" #include "ui/gfx/geometry/rect.h" #include "ui/gfx/geometry/size.h" namespace ash { namespace { constexpr int kShelfHeight = 56; constexpr int kVirtualKeyboardHeight = 280; constexpr int kDockedMagnifierHeight = 235; } // namespace class OobeDialogSizeUtilsTest : public testing::Test { public: OobeDialogSizeUtilsTest() = default; OobeDialogSizeUtilsTest(const OobeDialogSizeUtilsTest&) = delete; OobeDialogSizeUtilsTest& operator=(const OobeDialogSizeUtilsTest&) = delete; ~OobeDialogSizeUtilsTest() override = default; void ValidateDialog(const gfx::Rect& display, const gfx::Rect& area, const gfx::Rect& dialog) { // Dialog should fully fit into the area. EXPECT_TRUE(area.Contains(dialog)); // Dialog is centered in area. EXPECT_EQ(area.CenterPoint(), dialog.CenterPoint()); const gfx::Size min_dialog_size = GetMinDialogSize(display); const gfx::Size max_dialog_size = GetMaxDialogSize(display); EXPECT_LE(dialog.width(), max_dialog_size.width()); EXPECT_LE(dialog.height(), max_dialog_size.height()); // If there is at least some space, we should have margins. const gfx::Size margins = ExpectedMargins(display.size()); if (dialog.width() > min_dialog_size.width()) { EXPECT_EQ(dialog.x() + (area.right() - dialog.right()), margins.width()); } if (dialog.height() > min_dialog_size.height()) { EXPECT_EQ(dialog.y() + (area.bottom() - dialog.bottom()), margins.height()); } // If dialog size is lesser than minimum size, there should be no margins if (dialog.width() < min_dialog_size.width()) { EXPECT_EQ(dialog.x(), area.x()); EXPECT_EQ(dialog.right(), area.right()); } if (dialog.height() < min_dialog_size.height()) { EXPECT_EQ(dialog.y(), area.y()); EXPECT_EQ(dialog.bottom(), area.bottom()); } } gfx::Size GetMinDialogSize(const gfx::Rect& display) { if (IsHorizontal(display)) { return kMinLandscapeDialogSize; } return kMinPortraitDialogSize; } gfx::Size GetMaxDialogSize(const gfx::Rect& display) { if (IsHorizontal(display)) { return kMaxLandscapeDialogSize; } return kMaxPortraitDialogSize; } gfx::Size ExpectedMargins(const gfx::Size& display_size) { gfx::Size margin = ScaleToCeiledSize(display_size, 0.08); gfx::Size margins = margin + margin; margins.SetToMax(kMinMargins.size()); return margins; } gfx::Rect SizeWithoutShelf(const gfx::Rect& area) const { return gfx::Rect(area.width(), area.height() - kShelfHeight); } gfx::Rect SizeWithoutKeyboard(const gfx::Rect& area) const { return gfx::Rect(area.width(), area.height() - kVirtualKeyboardHeight); } gfx::Rect SizeWithoutDockedMagnifier(const gfx::Rect& area) const { return gfx::Rect(area.width(), area.height() - kDockedMagnifierHeight); } bool IsHorizontal(const gfx::Rect& area) const { return area.width() > area.height(); } private: base::test::ScopedFeatureList feature_list_; }; // We have plenty of space on the screen. TEST_F(OobeDialogSizeUtilsTest, Chromebook) { gfx::Rect usual_device(1200, 800); gfx::Rect dialog; OobeDialogPaddingMode padding; CalculateOobeDialogBounds(usual_device, kShelfHeight, IsHorizontal(usual_device), &dialog, &padding); ValidateDialog(usual_device, SizeWithoutShelf(usual_device), dialog); } // We have plenty of space on the screen, but virtual keyboard takes some space. TEST_F(OobeDialogSizeUtilsTest, ChromebookVirtualKeyboard) { gfx::Rect usual_device(1200, 800); gfx::Rect dialog; OobeDialogPaddingMode padding; CalculateOobeDialogBounds(SizeWithoutKeyboard(usual_device), 0, IsHorizontal(usual_device), &dialog, &padding); ValidateDialog(usual_device, SizeWithoutKeyboard(usual_device), dialog); } // Tablet device can have smaller screen size. TEST_F(OobeDialogSizeUtilsTest, TabletHorizontal) { gfx::Rect tablet_device(1080, 675); gfx::Rect dialog; OobeDialogPaddingMode padding; CalculateOobeDialogBounds(tablet_device, kShelfHeight, IsHorizontal(tablet_device), &dialog, &padding); ValidateDialog(tablet_device, SizeWithoutShelf(tablet_device), dialog); } // Tablet device in horizontal mode with virtual keyboard have restricted // vertical space. TEST_F(OobeDialogSizeUtilsTest, TabletHorizontalVirtualKeyboard) { gfx::Rect tablet_device(1080, 675); gfx::Rect dialog; OobeDialogPaddingMode padding; CalculateOobeDialogBounds(SizeWithoutKeyboard(tablet_device), 0, IsHorizontal(tablet_device), &dialog, &padding); ValidateDialog(tablet_device, SizeWithoutKeyboard(tablet_device), dialog); } // Tablet device in horizontal mode with docked magnifier have restricted // vertical space. TEST_F(OobeDialogSizeUtilsTest, TabletHorizontalDockedMagnifier) { gfx::Rect tablet_device(1080, 675); gfx::Rect dialog; OobeDialogPaddingMode padding; CalculateOobeDialogBounds(SizeWithoutDockedMagnifier(tablet_device), 0, IsHorizontal(tablet_device), &dialog, &padding); ValidateDialog(tablet_device, SizeWithoutDockedMagnifier(tablet_device), dialog); } // Tablet device in horizontal mode with virtual keyboard and docked // magnifier results in very few vertical space. TEST_F(OobeDialogSizeUtilsTest, TabletHorizontalVirtualKeyboardMagnifier) { gfx::Rect tablet_device(1080, 675); gfx::Rect dialog; OobeDialogPaddingMode padding; CalculateOobeDialogBounds( SizeWithoutDockedMagnifier(SizeWithoutKeyboard(tablet_device)), 0, IsHorizontal(tablet_device), &dialog, &padding); ValidateDialog(tablet_device, SizeWithoutDockedMagnifier(SizeWithoutKeyboard(tablet_device)), dialog); } // Tablet in vertical mode puts some strain on dialog width. TEST_F(OobeDialogSizeUtilsTest, ChromeTabVertical) { gfx::Rect tablet_device(461, 738); gfx::Rect dialog; OobeDialogPaddingMode padding; CalculateOobeDialogBounds(tablet_device, kShelfHeight, IsHorizontal(tablet_device), &dialog, &padding); ValidateDialog(tablet_device, SizeWithoutShelf(tablet_device), dialog); } // Tablet in horizontal mode puts some strain on dialog width. TEST_F(OobeDialogSizeUtilsTest, ChromeTabHorizontal) { gfx::Rect tablet_device(738, 461); gfx::Rect dialog; OobeDialogPaddingMode padding; CalculateOobeDialogBounds(tablet_device, kShelfHeight, IsHorizontal(tablet_device), &dialog, &padding); ValidateDialog(tablet_device, SizeWithoutShelf(tablet_device), dialog); } } // namespace ash
7,137
2,348
#include<iostream> #include<iomanip> using namespace std; int main(){ double Poly[1001] = {0}; //多项式A int k; scanf("%d", &k); for (int i = 0; i < k;i++){ int exp; double coef; scanf("%d%lf", &exp, &coef); Poly[exp] = coef; } //多项式B scanf("%d", &k); for (int i = 0; i < k;i++){ int exp; double coef; scanf("%d%lf", &exp, &coef); Poly[exp] += coef; } //统计多项式非零项 int num = 0; for (int i = 0; i <1001;i++){ if(Poly[i]!=0){ num++; } } printf("%d", num); //打印 for (int i = 1000; i >=0;i--){ if(Poly[i]!=0){ printf(" %d %0.1f", i,Poly[i]); } } return 0; }
754
337
/* * tuning.cpp * ---------- * Purpose: Alternative sample tuning. * Notes : (currently none) * Authors: OpenMPT Devs * The OpenMPT source code is released under the BSD license. Read LICENSE for more details. */ #include "stdafx.h" #include "tuning.h" #include "../common/mptIO.h" #include "../common/serialization_utils.h" #include "../common/misc_util.h" #include <string> #include <cmath> OPENMPT_NAMESPACE_BEGIN namespace Tuning { namespace CTuningS11n { void ReadStr(std::istream& iStrm, std::string& str, const size_t); void ReadNoteMap(std::istream& iStrm, std::map<NOTEINDEXTYPE, std::string>& m, const size_t); void ReadRatioTable(std::istream& iStrm, std::vector<RATIOTYPE>& v, const size_t); void WriteNoteMap(std::ostream& oStrm, const std::map<NOTEINDEXTYPE, std::string>& m); void WriteStr(std::ostream& oStrm, const std::string& str); struct RatioWriter { RatioWriter(uint16 nWriteCount = s_nDefaultWriteCount) : m_nWriteCount(nWriteCount) {} void operator()(std::ostream& oStrm, const std::vector<float>& v); uint16 m_nWriteCount; enum : uint16 { s_nDefaultWriteCount = (uint16_max >> 2) }; }; } using namespace CTuningS11n; /* Version changes: 3->4: Finetune related internal structure and serialization revamp. 2->3: The type for the size_type in the serialisation changed from default(size_t, uint32) to unsigned STEPTYPE. (March 2007) */ MPT_STATIC_ASSERT(CTuningRTI::s_RatioTableFineSizeMaxDefault < static_cast<USTEPINDEXTYPE>(FINESTEPCOUNT_MAX)); CTuningRTI::CTuningRTI() : m_TuningType(TT_GENERAL) , m_FineStepCount(0) { { m_RatioTable.clear(); m_StepMin = s_StepMinDefault; m_RatioTable.resize(s_RatioTableSizeDefault, 1); m_GroupSize = 0; m_GroupRatio = 0; m_RatioTableFine.clear(); } } bool CTuningRTI::ProCreateGroupGeometric(const std::vector<RATIOTYPE>& v, const RATIOTYPE& r, const VRPAIR& vr, const NOTEINDEXTYPE& ratiostartpos) { if(v.size() == 0 || r <= 0 || vr.second < vr.first || ratiostartpos < vr.first) { return true; } m_StepMin = vr.first; m_GroupSize = mpt::saturate_cast<NOTEINDEXTYPE>(v.size()); m_GroupRatio = std::fabs(r); m_RatioTable.resize(vr.second-vr.first+1); std::copy(v.begin(), v.end(), m_RatioTable.begin() + (ratiostartpos - vr.first)); for(int32 i = ratiostartpos-1; i>=m_StepMin && ratiostartpos > NOTEINDEXTYPE_MIN; i--) { m_RatioTable[i-m_StepMin] = m_RatioTable[i - m_StepMin + m_GroupSize] / m_GroupRatio; } for(int32 i = ratiostartpos+m_GroupSize; i<=vr.second && ratiostartpos <= (NOTEINDEXTYPE_MAX - m_GroupSize); i++) { m_RatioTable[i-m_StepMin] = m_GroupRatio * m_RatioTable[i - m_StepMin - m_GroupSize]; } return false; } bool CTuningRTI::ProCreateGeometric(const UNOTEINDEXTYPE& s, const RATIOTYPE& r, const VRPAIR& vr) { if(vr.second - vr.first + 1 > NOTEINDEXTYPE_MAX) return true; //Note: Setting finestep is handled by base class when CreateGeometric is called. { m_RatioTable.clear(); m_StepMin = s_StepMinDefault; m_RatioTable.resize(s_RatioTableSizeDefault, static_cast<RATIOTYPE>(1.0)); m_GroupSize = 0; m_GroupRatio = 0; m_RatioTableFine.clear(); } m_StepMin = vr.first; m_GroupSize = mpt::saturate_cast<NOTEINDEXTYPE>(s); m_GroupRatio = std::fabs(r); const RATIOTYPE stepRatio = std::pow(m_GroupRatio, static_cast<RATIOTYPE>(1.0)/ static_cast<RATIOTYPE>(m_GroupSize)); m_RatioTable.resize(vr.second - vr.first + 1); for(int32 i = vr.first; i<=vr.second; i++) { m_RatioTable[i-m_StepMin] = std::pow(stepRatio, static_cast<RATIOTYPE>(i)); } return false; } std::string CTuningRTI::GetNoteName(const NOTEINDEXTYPE& x, bool addOctave) const { if(!IsValidNote(x)) { return std::string(); } if(GetGroupSize() < 1) { const auto i = m_NoteNameMap.find(x); if(i != m_NoteNameMap.end()) return i->second; else return mpt::fmt::val(x); } else { const NOTEINDEXTYPE pos = static_cast<NOTEINDEXTYPE>(mpt::wrapping_modulo(x, m_GroupSize)); const NOTEINDEXTYPE middlePeriodNumber = 5; std::string rValue; const auto nmi = m_NoteNameMap.find(pos); if(nmi != m_NoteNameMap.end()) { rValue = nmi->second; if(addOctave) { rValue += mpt::fmt::val(middlePeriodNumber + mpt::wrapping_divide(x, m_GroupSize)); } } else { //By default, using notation nnP for notes; nn <-> note character starting //from 'A' with char ':' as fill char, and P is period integer. For example: //C:5, D:3, R:7 if(m_GroupSize <= 26) { rValue = std::string(1, static_cast<char>(pos + 'A')); rValue += ":"; } else { rValue = mpt::fmt::HEX0<1>(pos % 16) + mpt::fmt::HEX0<1>((pos / 16) % 16); if(pos > 0xff) { rValue = mpt::ToLowerCaseAscii(rValue); } } if(addOctave) { rValue += mpt::fmt::val(middlePeriodNumber + mpt::wrapping_divide(x, m_GroupSize)); } } return rValue; } } const RATIOTYPE CTuningRTI::s_DefaultFallbackRatio = 1.0f; //Without finetune RATIOTYPE CTuningRTI::GetRatio(const NOTEINDEXTYPE& stepsFromCentre) const { if(stepsFromCentre < m_StepMin) return s_DefaultFallbackRatio; if(stepsFromCentre >= m_StepMin + static_cast<NOTEINDEXTYPE>(m_RatioTable.size())) return s_DefaultFallbackRatio; return m_RatioTable[stepsFromCentre - m_StepMin]; } //With finetune RATIOTYPE CTuningRTI::GetRatio(const NOTEINDEXTYPE& baseNote, const STEPINDEXTYPE& baseStepDiff) const { const STEPINDEXTYPE fsCount = static_cast<STEPINDEXTYPE>(GetFineStepCount()); if(fsCount < 0 || fsCount > FINESTEPCOUNT_MAX) { return s_DefaultFallbackRatio; } if(fsCount == 0 || baseStepDiff == 0) { return GetRatio(static_cast<NOTEINDEXTYPE>(baseNote + baseStepDiff)); } //If baseStepDiff is more than the number of finesteps between notes, //note is increased. So first figuring out what step and fineStep values to //actually use. Interpreting finestep -1 on note x so that it is the same as //finestep GetFineStepCount() on note x-1. //Note: If finestepcount is n, n+1 steps are needed to get to //next note. NOTEINDEXTYPE note; STEPINDEXTYPE fineStep; note = static_cast<NOTEINDEXTYPE>(baseNote + mpt::wrapping_divide(baseStepDiff, (fsCount+1))); fineStep = mpt::wrapping_modulo(baseStepDiff, (fsCount+1)); if(note < m_StepMin) return s_DefaultFallbackRatio; if(note >= m_StepMin + static_cast<NOTEINDEXTYPE>(m_RatioTable.size())) return s_DefaultFallbackRatio; if(fineStep) return m_RatioTable[note - m_StepMin] * GetRatioFine(note, fineStep); else return m_RatioTable[note - m_StepMin]; } RATIOTYPE CTuningRTI::GetRatioFine(const NOTEINDEXTYPE& note, USTEPINDEXTYPE sd) const { if(GetFineStepCount() <= 0 || GetFineStepCount() > static_cast<USTEPINDEXTYPE>(FINESTEPCOUNT_MAX)) { return s_DefaultFallbackRatio; } //Neither of these should happen. if(sd <= 0) sd = 1; if(sd > GetFineStepCount()) sd = GetFineStepCount(); if(GetType() != TT_GENERAL && m_RatioTableFine.size() > 0) //Taking fineratio from table { if(GetType() == TT_GEOMETRIC) { return m_RatioTableFine[sd-1]; } if(GetType() == TT_GROUPGEOMETRIC) return m_RatioTableFine[GetRefNote(note) * GetFineStepCount() + sd - 1]; MPT_ASSERT_NOTREACHED(); return m_RatioTableFine[0]; //Shouldn't happen. } else //Calculating ratio 'on the fly'. { //'Geometric finestepping'. return std::pow(GetRatio(note+1) / GetRatio(note), static_cast<RATIOTYPE>(sd)/(GetFineStepCount()+1)); } } bool CTuningRTI::SetRatio(const NOTEINDEXTYPE& s, const RATIOTYPE& r) { if(GetType() != TT_GROUPGEOMETRIC && GetType() != TT_GENERAL) { return false; } //Creating ratio table if doesn't exist. if(m_RatioTable.empty()) { m_RatioTable.assign(s_RatioTableSizeDefault, 1); m_StepMin = s_StepMinDefault; } if(!IsNoteInTable(s)) { return false; } m_RatioTable[s - m_StepMin] = std::fabs(r); if(GetType() == TT_GROUPGEOMETRIC) { // update other groups for(NOTEINDEXTYPE n = m_StepMin; n < m_StepMin + static_cast<NOTEINDEXTYPE>(m_RatioTable.size()); ++n) { if(n == s) { // nothing } else if(mpt::abs(n - s) % m_GroupSize == 0) { m_RatioTable[n - m_StepMin] = std::pow(m_GroupRatio, static_cast<RATIOTYPE>(n - s) / static_cast<RATIOTYPE>(m_GroupSize)) * m_RatioTable[s - m_StepMin]; } } UpdateFineStepTable(); } return true; } void CTuningRTI::SetFineStepCount(const USTEPINDEXTYPE& fs) { m_FineStepCount = mpt::clamp(mpt::saturate_cast<STEPINDEXTYPE>(fs), STEPINDEXTYPE(0), FINESTEPCOUNT_MAX); UpdateFineStepTable(); } void CTuningRTI::UpdateFineStepTable() { if(m_FineStepCount <= 0) { m_RatioTableFine.clear(); return; } if(GetType() == TT_GEOMETRIC) { if(m_FineStepCount > s_RatioTableFineSizeMaxDefault) { m_RatioTableFine.clear(); return; } m_RatioTableFine.resize(m_FineStepCount); const RATIOTYPE q = GetRatio(GetValidityRange().first + 1) / GetRatio(GetValidityRange().first); const RATIOTYPE rFineStep = std::pow(q, static_cast<RATIOTYPE>(1)/(m_FineStepCount+1)); for(USTEPINDEXTYPE i = 1; i<=m_FineStepCount; i++) m_RatioTableFine[i-1] = std::pow(rFineStep, static_cast<RATIOTYPE>(i)); return; } if(GetType() == TT_GROUPGEOMETRIC) { const UNOTEINDEXTYPE p = GetGroupSize(); if(p > s_RatioTableFineSizeMaxDefault / m_FineStepCount) { //In case fineratiotable would become too large, not using //table for it. m_RatioTableFine.clear(); return; } else { //Creating 'geometric' finestepping between notes. m_RatioTableFine.resize(p * m_FineStepCount); const NOTEINDEXTYPE startnote = GetRefNote(GetValidityRange().first); for(UNOTEINDEXTYPE i = 0; i<p; i++) { const NOTEINDEXTYPE refnote = GetRefNote(startnote+i); const RATIOTYPE rFineStep = std::pow(GetRatio(refnote+1) / GetRatio(refnote), static_cast<RATIOTYPE>(1)/(m_FineStepCount+1)); for(UNOTEINDEXTYPE j = 1; j<=m_FineStepCount; j++) { m_RatioTableFine[m_FineStepCount * refnote + (j-1)] = std::pow(rFineStep, static_cast<RATIOTYPE>(j)); } } return; } } if(GetType() == TT_GENERAL) { //Not using table with tuning of type general. m_RatioTableFine.clear(); return; } //Should not reach here. m_RatioTableFine.clear(); m_FineStepCount = 0; } NOTEINDEXTYPE CTuningRTI::GetRefNote(const NOTEINDEXTYPE note) const { if((GetType() != TT_GROUPGEOMETRIC) && (GetType() != TT_GEOMETRIC)) return 0; return static_cast<NOTEINDEXTYPE>(mpt::wrapping_modulo(note, GetGroupSize())); } SerializationResult CTuningRTI::InitDeserialize(std::istream& iStrm) { // Note: OpenMPT since at least r323 writes version number (4<<24)+4 while it // reads version number (5<<24)+4 or earlier. // We keep this behaviour. if(iStrm.fail()) return SerializationResult::Failure; srlztn::SsbRead ssb(iStrm); ssb.BeginRead("CTB244RTI", (5 << 24) + 4); // version ssb.ReadItem(m_TuningName, "0", ReadStr); uint16 dummyEditMask = 0xffff; ssb.ReadItem(dummyEditMask, "1"); ssb.ReadItem(m_TuningType, "2"); ssb.ReadItem(m_NoteNameMap, "3", ReadNoteMap); ssb.ReadItem(m_FineStepCount, "4"); // RTI entries. ssb.ReadItem(m_RatioTable, "RTI0", ReadRatioTable); ssb.ReadItem(m_StepMin, "RTI1"); ssb.ReadItem(m_GroupSize, "RTI2"); ssb.ReadItem(m_GroupRatio, "RTI3"); UNOTEINDEXTYPE ratiotableSize = 0; ssb.ReadItem(ratiotableSize, "RTI4"); // If reader status is ok and m_StepMin is somewhat reasonable, process data. if(!((ssb.GetStatus() & srlztn::SNT_FAILURE) == 0 && m_StepMin >= -300 && m_StepMin <= 300)) { return SerializationResult::Failure; } // reject unknown types if(m_TuningType != TT_GENERAL && m_TuningType != TT_GROUPGEOMETRIC && m_TuningType != TT_GEOMETRIC) { return SerializationResult::Failure; } if(m_GroupSize < 0) { return SerializationResult::Failure; } m_FineStepCount = mpt::clamp(mpt::saturate_cast<STEPINDEXTYPE>(m_FineStepCount), STEPINDEXTYPE(0), FINESTEPCOUNT_MAX); if(m_RatioTable.size() > static_cast<size_t>(NOTEINDEXTYPE_MAX)) { return SerializationResult::Failure; } if((GetType() == TT_GROUPGEOMETRIC) || (GetType() == TT_GEOMETRIC)) { if(ratiotableSize < 1 || ratiotableSize > NOTEINDEXTYPE_MAX) { return SerializationResult::Failure; } if(GetType() == TT_GEOMETRIC) { if(CreateGeometric(GetGroupSize(), GetGroupRatio(), VRPAIR(m_StepMin, static_cast<NOTEINDEXTYPE>(m_StepMin + ratiotableSize - 1))) != false) { return SerializationResult::Failure; } } else { if(CreateGroupGeometric(m_RatioTable, GetGroupRatio(), VRPAIR(m_StepMin, static_cast<NOTEINDEXTYPE>(m_StepMin+ratiotableSize-1)), m_StepMin) != false) { return SerializationResult::Failure; } } } else { UpdateFineStepTable(); } return SerializationResult::Success; } template<class T, class SIZETYPE, class Tdst> static bool VectorFromBinaryStream(std::istream& inStrm, std::vector<Tdst>& v, const SIZETYPE maxSize = (std::numeric_limits<SIZETYPE>::max)()) { if(!inStrm.good()) return true; SIZETYPE size = 0; mpt::IO::ReadIntLE<SIZETYPE>(inStrm, size); if(size > maxSize) return true; v.resize(size); for(std::size_t i = 0; i<size; i++) { T tmp = T(); mpt::IO::Read(inStrm, tmp); v[i] = tmp; } if(inStrm.good()) return false; else return true; } SerializationResult CTuningRTI::InitDeserializeOLD(std::istream& inStrm) { if(!inStrm.good()) return SerializationResult::Failure; const std::streamoff startPos = inStrm.tellg(); //First checking is there expected begin sequence. char begin[8]; MemsetZero(begin); inStrm.read(begin, sizeof(begin)); if(std::memcmp(begin, "CTRTI_B.", 8)) { //Returning stream position if beginmarker was not found. inStrm.seekg(startPos); return SerializationResult::Failure; } //Version int16 version = 0; mpt::IO::ReadIntLE<int16>(inStrm, version); if(version != 2 && version != 3) return SerializationResult::Failure; char begin2[8]; MemsetZero(begin2); inStrm.read(begin2, sizeof(begin2)); if(std::memcmp(begin2, "CT<sfs>B", 8)) { return SerializationResult::Failure; } int16 version2 = 0; mpt::IO::ReadIntLE<int16>(inStrm, version2); if(version2 != 3 && version2 != 4) { return SerializationResult::Failure; } //Tuning name if(version2 <= 3) { if(!mpt::IO::ReadSizedStringLE<uint32>(inStrm, m_TuningName, 0xffff)) { return SerializationResult::Failure; } } else { if(!mpt::IO::ReadSizedStringLE<uint8>(inStrm, m_TuningName)) { return SerializationResult::Failure; } } //Const mask int16 em = 0; mpt::IO::ReadIntLE<int16>(inStrm, em); //Tuning type int16 tt = 0; mpt::IO::ReadIntLE<int16>(inStrm, tt); m_TuningType = tt; //Notemap uint16 size = 0; if(version2 <= 3) { uint32 tempsize = 0; mpt::IO::ReadIntLE<uint32>(inStrm, tempsize); if(tempsize > 0xffff) { return SerializationResult::Failure; } size = mpt::saturate_cast<uint16>(tempsize); } else { mpt::IO::ReadIntLE<uint16>(inStrm, size); } for(UNOTEINDEXTYPE i = 0; i<size; i++) { std::string str; int16 n = 0; mpt::IO::ReadIntLE<int16>(inStrm, n); if(version2 <= 3) { if(!mpt::IO::ReadSizedStringLE<uint32>(inStrm, str, 0xffff)) { return SerializationResult::Failure; } } else { if(!mpt::IO::ReadSizedStringLE<uint8>(inStrm, str)) { return SerializationResult::Failure; } } m_NoteNameMap[n] = str; } //End marker char end2[8]; MemsetZero(end2); inStrm.read(end2, sizeof(end2)); if(std::memcmp(end2, "CT<sfs>E", 8)) { return SerializationResult::Failure; } // reject unknown types if(m_TuningType != TT_GENERAL && m_TuningType != TT_GROUPGEOMETRIC && m_TuningType != TT_GEOMETRIC) { return SerializationResult::Failure; } //Ratiotable if(version <= 2) { if(VectorFromBinaryStream<IEEE754binary32LE, uint32>(inStrm, m_RatioTable, 0xffff)) { return SerializationResult::Failure; } } else { if(VectorFromBinaryStream<IEEE754binary32LE, uint16>(inStrm, m_RatioTable)) { return SerializationResult::Failure; } } //Fineratios if(version <= 2) { if(VectorFromBinaryStream<IEEE754binary32LE, uint32>(inStrm, m_RatioTableFine, 0xffff)) { return SerializationResult::Failure; } } else { if(VectorFromBinaryStream<IEEE754binary32LE, uint16>(inStrm, m_RatioTableFine)) { return SerializationResult::Failure; } } m_FineStepCount = mpt::saturate_cast<USTEPINDEXTYPE>(m_RatioTableFine.size()); //m_StepMin int16 stepmin = 0; mpt::IO::ReadIntLE<int16>(inStrm, stepmin); m_StepMin = stepmin; if(m_StepMin < -200 || m_StepMin > 200) { return SerializationResult::Failure; } //m_GroupSize int16 groupsize = 0; mpt::IO::ReadIntLE<int16>(inStrm, groupsize); m_GroupSize = groupsize; if(m_GroupSize < 0) { return SerializationResult::Failure; } //m_GroupRatio IEEE754binary32LE groupratio = IEEE754binary32LE(0.0f); mpt::IO::Read(inStrm, groupratio); m_GroupRatio = groupratio; if(m_GroupRatio < 0) { return SerializationResult::Failure; } char end[8]; MemsetZero(end); inStrm.read(reinterpret_cast<char*>(&end), sizeof(end)); if(std::memcmp(end, "CTRTI_E.", 8)) { return SerializationResult::Failure; } // reject corrupt tunings if(m_RatioTable.size() > static_cast<std::size_t>(NOTEINDEXTYPE_MAX)) { return SerializationResult::Failure; } if((m_GroupSize <= 0 || m_GroupRatio <= 0) && m_TuningType != TT_GENERAL) { return SerializationResult::Failure; } if(m_TuningType == TT_GROUPGEOMETRIC || m_TuningType == TT_GEOMETRIC) { if(m_RatioTable.size() < static_cast<std::size_t>(m_GroupSize)) { return SerializationResult::Failure; } } // convert old finestepcount if(m_FineStepCount > 0) { m_FineStepCount -= 1; } m_FineStepCount = mpt::clamp(mpt::saturate_cast<STEPINDEXTYPE>(m_FineStepCount), STEPINDEXTYPE(0), FINESTEPCOUNT_MAX); UpdateFineStepTable(); if(m_TuningType == TT_GEOMETRIC) { // Convert old geometric to new groupgeometric because old geometric tunings // can have ratio(0) != 1.0, which would get lost when saving nowadays. if(mpt::saturate_cast<NOTEINDEXTYPE>(m_RatioTable.size()) >= m_GroupSize - m_StepMin) { std::vector<RATIOTYPE> ratios; for(NOTEINDEXTYPE n = 0; n < m_GroupSize; ++n) { ratios.push_back(m_RatioTable[n - m_StepMin]); } CreateGroupGeometric(ratios, m_GroupRatio, GetValidityRange(), 0); } } return SerializationResult::Success; } Tuning::SerializationResult CTuningRTI::Serialize(std::ostream& outStrm) const { // Note: OpenMPT since at least r323 writes version number (4<<24)+4 while it // reads version number (5<<24)+4. // We keep this behaviour. srlztn::SsbWrite ssb(outStrm); ssb.BeginWrite("CTB244RTI", (4 << 24) + 4); // version if (m_TuningName.length() > 0) ssb.WriteItem(m_TuningName, "0", WriteStr); uint16 dummyEditMask = 0xffff; ssb.WriteItem(dummyEditMask, "1"); ssb.WriteItem(m_TuningType, "2"); if (m_NoteNameMap.size() > 0) ssb.WriteItem(m_NoteNameMap, "3", WriteNoteMap); if (GetFineStepCount() > 0) ssb.WriteItem(m_FineStepCount, "4"); const TUNINGTYPE tt = GetType(); if (GetGroupRatio() > 0) ssb.WriteItem(m_GroupRatio, "RTI3"); if (tt == TT_GROUPGEOMETRIC) ssb.WriteItem(m_RatioTable, "RTI0", RatioWriter(GetGroupSize())); if (tt == TT_GENERAL) ssb.WriteItem(m_RatioTable, "RTI0", RatioWriter()); if (tt == TT_GEOMETRIC) ssb.WriteItem(m_GroupSize, "RTI2"); if(tt == TT_GEOMETRIC || tt == TT_GROUPGEOMETRIC) { //For Groupgeometric this data is the number of ratios in ratiotable. UNOTEINDEXTYPE ratiotableSize = static_cast<UNOTEINDEXTYPE>(m_RatioTable.size()); ssb.WriteItem(ratiotableSize, "RTI4"); } //m_StepMin ssb.WriteItem(m_StepMin, "RTI1"); ssb.FinishWrite(); return ((ssb.GetStatus() & srlztn::SNT_FAILURE) != 0) ? Tuning::SerializationResult::Failure : Tuning::SerializationResult::Success; } #ifdef MODPLUG_TRACKER bool CTuningRTI::WriteSCL(std::ostream &f, const mpt::PathString &filename) const { mpt::IO::WriteTextCRLF(f, mpt::format("! %1")(mpt::ToCharset(mpt::CharsetISO8859_1, (filename.GetFileName() + filename.GetFileExt()).ToUnicode()))); mpt::IO::WriteTextCRLF(f, "!"); std::string name = mpt::ToCharset(mpt::CharsetISO8859_1, mpt::CharsetLocale, GetName()); for(auto & c : name) { if(static_cast<uint8>(c) < 32) c = ' '; } // remove control characters if(name.length() >= 1 && name[0] == '!') name[0] = '?'; // do not confuse description with comment mpt::IO::WriteTextCRLF(f, name); if(GetType() == TT_GEOMETRIC) { mpt::IO::WriteTextCRLF(f, mpt::format(" %1")(m_GroupSize)); mpt::IO::WriteTextCRLF(f, "!"); for(NOTEINDEXTYPE n = 0; n < m_GroupSize; ++n) { double ratio = std::pow(static_cast<double>(m_GroupRatio), static_cast<double>(n + 1) / static_cast<double>(m_GroupSize)); double cents = std::log2(ratio) * 1200.0; mpt::IO::WriteTextCRLF(f, mpt::format(" %1 ! %2")( mpt::fmt::fix(cents), mpt::ToCharset(mpt::CharsetISO8859_1, mpt::CharsetLocale, GetNoteName((n + 1) % m_GroupSize, false)) )); } } else if(GetType() == TT_GROUPGEOMETRIC) { mpt::IO::WriteTextCRLF(f, mpt::format(" %1")(m_GroupSize)); mpt::IO::WriteTextCRLF(f, "!"); for(NOTEINDEXTYPE n = 0; n < m_GroupSize; ++n) { bool last = (n == (m_GroupSize - 1)); double baseratio = static_cast<double>(GetRatio(0)); double ratio = static_cast<double>(last ? m_GroupRatio : GetRatio(n + 1)) / baseratio; double cents = std::log2(ratio) * 1200.0; mpt::IO::WriteTextCRLF(f, mpt::format(" %1 ! %2")( mpt::fmt::fix(cents), mpt::ToCharset(mpt::CharsetISO8859_1, mpt::CharsetLocale, GetNoteName((n + 1) % m_GroupSize, false)) )); } } else if(GetType() == TT_GENERAL) { mpt::IO::WriteTextCRLF(f, mpt::format(" %1")(m_RatioTable.size() + 1)); mpt::IO::WriteTextCRLF(f, "!"); double baseratio = 1.0; for(NOTEINDEXTYPE n = 0; n < mpt::saturate_cast<NOTEINDEXTYPE>(m_RatioTable.size()); ++n) { baseratio = std::min(baseratio, static_cast<double>(m_RatioTable[n])); } for(NOTEINDEXTYPE n = 0; n < mpt::saturate_cast<NOTEINDEXTYPE>(m_RatioTable.size()); ++n) { double ratio = static_cast<double>(m_RatioTable[n]) / baseratio; double cents = std::log2(ratio) * 1200.0; mpt::IO::WriteTextCRLF(f, mpt::format(" %1 ! %2")( mpt::fmt::fix(cents), mpt::ToCharset(mpt::CharsetISO8859_1, mpt::CharsetLocale, GetNoteName(n + m_StepMin, false)) )); } mpt::IO::WriteTextCRLF(f, mpt::format(" %1 ! %2")( mpt::fmt::val(1), std::string() )); } else { return false; } return true; } #endif namespace CTuningS11n { void RatioWriter::operator()(std::ostream& oStrm, const std::vector<float>& v) { const size_t nWriteCount = MIN(v.size(), m_nWriteCount); mpt::IO::WriteAdaptiveInt64LE(oStrm, nWriteCount); for(size_t i = 0; i < nWriteCount; i++) mpt::IO::Write(oStrm, IEEE754binary32LE(v[i])); } void ReadNoteMap(std::istream& iStrm, std::map<NOTEINDEXTYPE,std::string>& m, const size_t) { uint64 val; mpt::IO::ReadAdaptiveInt64LE(iStrm, val); LimitMax(val, 256u); // Read 256 at max. for(size_t i = 0; i < val; i++) { int16 key; mpt::IO::ReadIntLE<int16>(iStrm, key); std::string str; mpt::IO::ReadSizedStringLE<uint8>(iStrm, str); m[key] = str; } } void ReadRatioTable(std::istream& iStrm, std::vector<RATIOTYPE>& v, const size_t) { uint64 val; mpt::IO::ReadAdaptiveInt64LE(iStrm, val); v.resize( static_cast<size_t>(MIN(val, 256u))); // Read 256 vals at max. for(size_t i = 0; i < v.size(); i++) { IEEE754binary32LE tmp(0.0f); mpt::IO::Read(iStrm, tmp); v[i] = tmp; } } void ReadStr(std::istream& iStrm, std::string& str, const size_t) { uint64 val; mpt::IO::ReadAdaptiveInt64LE(iStrm, val); size_t nSize = (val > 255) ? 255 : static_cast<size_t>(val); // Read 255 characters at max. str.clear(); str.resize(nSize); for(size_t i = 0; i < nSize; i++) mpt::IO::ReadIntLE(iStrm, str[i]); if(str.find_first_of('\0') != std::string::npos) { // trim \0 at the end str.resize(str.find_first_of('\0')); } } void WriteNoteMap(std::ostream& oStrm, const std::map<NOTEINDEXTYPE, std::string>& m) { mpt::IO::WriteAdaptiveInt64LE(oStrm, m.size()); for(auto &mi : m) { mpt::IO::WriteIntLE<int16>(oStrm, mi.first); mpt::IO::WriteSizedStringLE<uint8>(oStrm, mi.second); } } void WriteStr(std::ostream& oStrm, const std::string& str) { mpt::IO::WriteAdaptiveInt64LE(oStrm, str.size()); oStrm.write(str.c_str(), str.size()); } } // namespace CTuningS11n. } // namespace Tuning OPENMPT_NAMESPACE_END
24,379
10,842
/* * Copyright (c) 2014-2021, NVIDIA CORPORATION. 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. * * SPDX-FileCopyrightText: Copyright (c) 2014-2021 NVIDIA CORPORATION * SPDX-License-Identifier: Apache-2.0 */ #ifndef NV_WINDOWPROFILER_GL_INCLUDED #define NV_WINDOWPROFILER_GL_INCLUDED #include "contextwindow_gl.hpp" #include "profiler_gl.hpp" #include <nvh/appwindowprofiler.hpp> ////////////////////////////////////////////////////////////////////////// /** \class nvgl::AppWindowProfilerGL nvgl::AppWindowProfilerGL derives from nvh::AppWindowProfiler and overrides the context and swapbuffer functions. To influence the context creation modify `m_contextInfo` prior running AppWindowProfiler::run, which triggers window, and context creation etc. The class comes with a nvgl::ProfilerGL instance that references the AppWindowProfiler::m_profiler's data. */ namespace nvgl { #define NV_PROFILE_GL_SECTION(name) nvgl::ProfilerGL::Section _tempTimer(m_profilerGL, name) #define NV_PROFILE_GL_SPLIT() m_profilerGL.accumulationSplit() class AppWindowProfilerGL : public nvh::AppWindowProfiler { public: AppWindowProfilerGL(bool singleThreaded = true) : nvh::AppWindowProfiler(singleThreaded) , m_profilerGL(&m_profiler) { m_contextInfo.robust = false; m_contextInfo.core = false; #ifdef NDEBUG m_contextInfo.debug = false; #else m_contextInfo.debug = true; #endif m_contextInfo.share = NULL; m_contextInfo.major = 4; m_contextInfo.minor = 5; } nvgl::ContextWindowCreateInfo m_contextInfo; ContextWindow m_contextWindow; nvgl::ProfilerGL m_profilerGL; int run(const std::string& name, int argc, const char** argv, int width, int height) { return AppWindowProfiler::run(name, argc, argv, width, height, true); } virtual void contextInit() override; virtual void contextDeinit() override; virtual void swapResize(int width, int height) override { m_windowState.m_swapSize[0] = width; m_windowState.m_swapSize[1] = height; } virtual void swapPrepare() override {} virtual void swapBuffers() override { m_contextWindow.swapBuffers(); } virtual void swapVsync(bool state) override { m_contextWindow.swapInterval(state ? 1 : 0); } virtual const char* contextGetDeviceName() override { return m_contextWindow.m_deviceName.c_str(); } }; } // namespace nvgl #endif
2,957
1,010
typedef struct static_queue_0; typedef struct RwObjectHasFrame; typedef struct RxPipelineNode; typedef struct zEntHangable; typedef struct static_queue_1; typedef enum _zPlayerWallJumpState; typedef struct RpPolygon; typedef struct xVec3; typedef struct xLaserBoltEmitter; typedef struct xEnv; typedef struct bolt; typedef struct xMovePointAsset; typedef struct RwV3d; typedef struct xEnt; typedef struct effect_data; typedef struct RpGeometry; typedef struct xAnimTable; typedef struct xAnimPlay; typedef struct xModelInstance; typedef struct RpVertexNormal; typedef struct zPlatform; typedef struct rxHeapFreeBlock; typedef struct xMovePoint; typedef struct RwRaster; typedef struct iEnv; typedef struct RxPipelineNodeTopSortData; typedef struct xAnimEffect; typedef struct RwV2d; typedef struct RwTexCoords; typedef struct xBase; typedef struct xGridBound; typedef struct iterator; typedef enum _tagRumbleType; typedef struct RxNodeDefinition; typedef struct _class_0; typedef struct tagiRenderInput; typedef enum _zPlayerType; typedef struct xLightKit; typedef struct xUpdateCullGroup; typedef struct zCutsceneMgr; typedef struct zEnt; typedef struct xAnimSingle; typedef struct RwRGBA; typedef struct rxHeapSuperBlockDescriptor; typedef struct xJSPNodeInfo; typedef struct RwTexture; typedef struct _tagEmitSphere; typedef struct xAnimState; typedef struct xEntMechData; typedef struct RwResEntry; typedef struct RxPipeline; typedef struct xMat4x3; typedef struct RxPipelineCluster; typedef struct RxObjSpace3DVertex; typedef struct xEntMotionSplineData; typedef struct RxPipelineNodeParam; typedef struct zAssetPickupTable; typedef struct analog_data; typedef struct RpMeshHeader; typedef struct xSpline3; typedef struct RxHeap; typedef struct RwBBox; typedef struct xMemPool; typedef struct curve_node; typedef struct xQuat; typedef struct xGroup; typedef struct RpTriangle; typedef struct xEntBoulder; typedef struct RpAtomic; typedef struct xClumpCollBSPBranchNode; typedef struct xEntShadow; typedef struct rxHeapBlockHeader; typedef struct xCollis; typedef struct zCheckPoint; typedef struct zPlayerGlobals; typedef struct xModelPool; typedef struct RxPipelineRequiresCluster; typedef struct _tagEmitRect; typedef struct xEntMotionMPData; typedef struct xJSPHeader; typedef struct xEntAsset; typedef struct xEntERData; typedef struct xUpdateCullMgr; typedef struct zPlayerCarryInfo; typedef struct xPortalAsset; typedef enum fx_when_enum; typedef struct zPlayerSettings; typedef struct xScene; typedef struct xCamera; typedef struct xAnimFile; typedef struct _zEnv; typedef struct RpClump; typedef struct xVec4; typedef struct xSurface; typedef struct xQCData; typedef struct xCoef; typedef struct RwSurfaceProperties; typedef struct xClumpCollBSPTree; typedef struct RwCamera; typedef struct RwMatrixTag; typedef struct xAnimTransition; typedef struct xAnimTransitionList; typedef struct xUpdateCullEnt; typedef struct rxReq; typedef struct xPEEntBound; typedef struct xEnvAsset; typedef struct xLinkAsset; typedef struct xModelTag; typedef struct zLasso; typedef struct xEntMotionMechData; typedef struct _tagEmitLine; typedef enum RxClusterValidityReq; typedef enum RpWorldRenderOrder; typedef struct xRay3; typedef struct xEntPenData; typedef struct _tagxRumble; typedef struct iFogParams; typedef struct xCoef3; typedef struct xEntDrive; typedef enum RxNodeDefEditable; typedef struct xBound; typedef struct RpMaterial; typedef struct RpSector; typedef struct xModelBucket; typedef enum RxClusterValid; typedef enum fx_type_enum; typedef struct xEntCollis; typedef struct xAnimMultiFile; typedef struct xRot; typedef struct xEntOrbitData; typedef struct xVec2; typedef struct RpWorld; typedef struct RpWorldSector; typedef struct RpMorphTarget; typedef struct xParEmitterAsset; typedef enum rxEmbeddedPacketState; typedef struct zPlatFMRunTime; typedef struct xSphere; typedef struct _tagEmitVolume; typedef struct _zPortal; typedef struct RpLight; typedef struct xEntMotion; typedef struct unit_data; typedef struct xParGroup; typedef struct xEntFrame; typedef struct xFFX; typedef enum RwCameraProjection; typedef struct xPlatformAsset; typedef enum _tagPadState; typedef enum RxClusterForcePresent; typedef struct xParEmitterPropsAsset; typedef struct xEntMotionAsset; typedef struct xCylinder; typedef enum fx_orient_enum; typedef struct RxColorUnion; typedef struct xGlobals; typedef struct RwFrame; typedef struct xBox; typedef struct RxClusterDefinition; typedef struct xShadowSimplePoly; typedef struct _tagxPad; typedef struct xEntSplineData; typedef struct _tagEmitOffsetPoint; typedef struct RwSphere; typedef struct xParEmitter; typedef struct RwLLLink; typedef struct tri_data_0; typedef struct xGroupAsset; typedef struct _tagPadAnalog; typedef struct RwTexDictionary; typedef struct xEntMotionPenData; typedef struct RxOutputSpec; typedef struct xDecalEmitter; typedef struct _tagiPad; typedef struct xLightKitLight; typedef struct tri_data_1; typedef struct xMat3x3; typedef struct xAnimMultiFileEntry; typedef struct xAnimActiveEffect; typedef struct _class_1; typedef struct xShadowSimpleCache; typedef struct RxClusterRef; typedef struct xEntMPData; typedef struct xParSys; typedef struct RwObject; typedef struct xPEVCyl; typedef struct config_0; typedef struct RxIoSpec; typedef enum texture_mode; typedef struct RpInterpolator; typedef struct xParInterp; typedef struct xClumpCollBSPVertInfo; typedef struct RxNodeMethods; typedef struct xEntMotionERData; typedef struct _class_2; typedef struct xClumpCollBSPTriangle; typedef struct xAnimMultiFileBase; typedef struct _class_3; typedef struct RwFrustumPlane; typedef struct xBaseAsset; typedef struct xPEEntBone; typedef struct RwPlane; typedef struct config_1; typedef struct zGlobals; typedef struct _class_4; typedef struct RxCluster; typedef struct zGlobalSettings; typedef struct RpMaterialList; typedef struct RxPacket; typedef struct zPlayerLassoInfo; typedef struct zScene; typedef struct _class_5; typedef struct xBBox; typedef struct anim_coll_data; typedef enum RwFogType; typedef struct iColor_tag; typedef struct _class_6; typedef struct zLedgeGrabParams; typedef struct RwRGBAReal; typedef struct xPECircle; typedef struct zJumpParam; typedef struct xEntMotionOrbitData; typedef struct RwLinkList; typedef RwCamera*(*type_0)(RwCamera*); typedef RpClump*(*type_1)(RpClump*, void*); typedef int32(*type_2)(RxPipelineNode*); typedef RwCamera*(*type_4)(RwCamera*); typedef RwObjectHasFrame*(*type_5)(RwObjectHasFrame*); typedef void(*type_7)(xEnt*, xScene*, float32, xEntCollis*); typedef xBase*(*type_8)(uint32); typedef void(*type_9)(RxPipelineNode*); typedef uint32(*type_13)(xEnt*, xEnt*, xScene*, float32, xCollis*); typedef int8*(*type_14)(xBase*); typedef int8*(*type_16)(uint32); typedef void(*type_19)(xAnimPlay*, xAnimState*); typedef int32(*type_20)(RxPipelineNode*, RxPipeline*); typedef void(*type_21)(xEnt*, xVec3*, xMat4x3*); typedef uint32(*type_23)(uint32, xAnimActiveEffect*, xAnimSingle*, void*); typedef void(*type_26)(xAnimPlay*, xQuat*, xVec3*, int32); typedef uint32(*type_29)(RxPipelineNode*, uint32, uint32, void*); typedef RpAtomic*(*type_30)(RpAtomic*); typedef int32(*type_32)(RxPipelineNode*, RxPipelineNodeParam*); typedef int32(*type_36)(RxNodeDefinition*); typedef void(*type_40)(RxNodeDefinition*); typedef uint32(*type_45)(xAnimTransition*, xAnimSingle*, void*); typedef void(*type_52)(void*); typedef void(*type_60)(xAnimState*, xAnimSingle*, void*); typedef RpWorldSector*(*type_63)(RpWorldSector*); typedef int32(*type_79)(xBase*, xBase*, uint32, float32*, xBase*); typedef void(*type_80)(xEnt*, xScene*, float32); typedef void(*type_84)(bolt&, void*); typedef void(*type_86)(xEnt*, xVec3*); typedef void(*type_89)(xEnt*, xScene*, float32, xEntFrame*); typedef void(*type_90)(xEnt*); typedef void(*type_94)(xMemPool*, void*); typedef uint32(*type_95)(void*, void*); typedef void(*type_103)(RwResEntry*); typedef xVec3 type_3[60]; typedef xCollis type_6[18]; typedef int8 type_10[16]; typedef RwTexCoords* type_11[8]; typedef float32 type_12[22]; typedef xParInterp type_15[1]; typedef float32 type_17[22]; typedef uint8 type_18[2]; typedef int8 type_22[16]; typedef uint32 type_24[15]; typedef uint32 type_25[15]; typedef RwFrustumPlane type_27[6]; typedef uint16 type_28[3]; typedef uint32 type_31[15]; typedef xParInterp type_33[4]; typedef RwV3d type_34[8]; typedef uint32 type_35[72]; typedef int8 type_37[4]; typedef analog_data type_38[2]; typedef xParInterp type_39[4]; typedef xBase* type_41[72]; typedef uint8 type_42[3]; typedef float32 type_43[4]; typedef float32 type_44[2]; typedef uint8 type_46[2]; typedef xVec4 type_47[12]; typedef uint32 type_48[2]; typedef RwTexCoords* type_49[8]; typedef uint8 type_50[2]; typedef float32 type_51[6]; typedef uint8 type_53[3]; typedef float32 type_54[3]; typedef float32 type_55[3]; typedef effect_data* type_56[7]; typedef xModelTag type_57[2]; typedef uint32 type_58[7]; typedef float32 type_59[4]; typedef float32 type_61[4]; typedef float32 type_62[3]; typedef float32 type_64[12]; typedef RpLight* type_65[2]; typedef float32 type_66[12]; typedef RwFrame* type_67[2]; typedef float32 type_68[12]; typedef xEnt* type_69[111]; typedef float32 type_70[12]; typedef float32 type_71[12]; typedef xVec3 type_72[3]; typedef uint32 type_73[4]; typedef float32 type_74[12]; typedef uint8 type_75[3]; typedef uint8 type_76[3]; typedef int8 type_77[128]; typedef int8 type_78[128][6]; typedef uint8 type_81[2]; typedef uint8 type_82[14]; typedef xModelTag type_83[4]; typedef int8 type_85[32]; typedef xModelInstance* type_87[14]; typedef float32 type_88[16]; typedef uint8 type_91[4]; typedef float32 type_92[2]; typedef float32 type_93[2]; typedef uint8 type_96[22]; typedef int8 type_97[32]; typedef uint8 type_98[22]; typedef int8 type_99[32]; typedef xVec3 type_100[4]; typedef uint16 type_101[3]; typedef xVec2 type_102[2]; typedef uint8 type_104[2]; typedef xVec2 type_105[2]; typedef xAnimMultiFileEntry type_106[1]; typedef xVec3 type_107[5]; typedef RxCluster type_108[1]; typedef uint8 type_109[5]; struct static_queue_0 { uint32 _first; uint32 _size; uint32 _max_size; uint32 _max_size_mask; bolt* _buffer; }; struct RwObjectHasFrame { RwObject object; RwLLLink lFrame; RwObjectHasFrame*(*sync)(RwObjectHasFrame*); }; struct RxPipelineNode { RxNodeDefinition* nodeDef; uint32 numOutputs; uint32* outputs; RxPipelineCluster** slotClusterRefs; uint32* slotsContinue; void* privateData; uint32* inputToClusterSlot; RxPipelineNodeTopSortData* topSortData; void* initializationData; uint32 initializationDataSize; }; struct zEntHangable { }; struct static_queue_1 { uint32 _first; uint32 _size; uint32 _max_size; uint32 _max_size_mask; unit_data* _buffer; }; enum _zPlayerWallJumpState { k_WALLJUMP_NOT, k_WALLJUMP_LAUNCH, k_WALLJUMP_FLIGHT, k_WALLJUMP_LAND }; struct RpPolygon { uint16 matIndex; uint16 vertIndex[3]; }; struct xVec3 { float32 x; float32 y; float32 z; }; struct xLaserBoltEmitter { config_0 cfg; static_queue_0 bolts; float32 ialpha; RwRaster* bolt_raster; int32 start_collide; effect_data* fx[7]; uint32 fxsize[7]; void update_fx(bolt& b, float32 prev_dist, float32 dt); RxObjSpace3DVertex* render(bolt& b, RxObjSpace3DVertex* vert); void collide_update(bolt& b); void attach_effects(fx_when_enum when, effect_data* fx, uint32 fxsize); void render(); void update(float32 dt); void emit(xVec3& loc, xVec3& dir); void refresh_config(); void reset(); void set_texture(int8* name); void init(uint32 max_bolts); }; struct xEnv { iEnv* geom; iEnv ienv; xLightKit* lightKit; }; struct bolt { xVec3 origin; xVec3 dir; xVec3 loc; xVec3 hit_norm; float32 dist; float32 hit_dist; float32 prev_dist; float32 prev_check_dist; xEnt* hit_ent; float32 emitted; void* context; }; struct xMovePointAsset : xBaseAsset { xVec3 pos; uint16 wt; uint8 on; uint8 bezIndex; uint8 flg_props; uint8 pad; uint16 numPoints; float32 delay; float32 zoneRadius; float32 arenaRadius; }; struct RwV3d { float32 x; float32 y; float32 z; }; struct xEnt : xBase { xEntAsset* asset; uint16 idx; uint16 num_updates; uint8 flags; uint8 miscflags; uint8 subType; uint8 pflags; uint8 moreFlags; uint8 isCulled; uint8 driving_count; uint8 num_ffx; uint8 collType; uint8 collLev; uint8 chkby; uint8 penby; xModelInstance* model; xModelInstance* collModel; xModelInstance* camcollModel; xLightKit* lightKit; void(*update)(xEnt*, xScene*, float32); void(*endUpdate)(xEnt*, xScene*, float32); void(*bupdate)(xEnt*, xVec3*); void(*move)(xEnt*, xScene*, float32, xEntFrame*); void(*render)(xEnt*); xEntFrame* frame; xEntCollis* collis; xGridBound gridb; xBound bound; void(*transl)(xEnt*, xVec3*, xMat4x3*); xFFX* ffx; xEnt* driver; int32 driveMode; xShadowSimpleCache* simpShadow; xEntShadow* entShadow; anim_coll_data* anim_coll; void* user_data; }; struct effect_data { fx_type_enum type; fx_orient_enum orient; float32 rate; _class_2 data; float32 irate; }; struct RpGeometry { RwObject object; uint32 flags; uint16 lockedSinceLastInst; int16 refCount; int32 numTriangles; int32 numVertices; int32 numMorphTargets; int32 numTexCoordSets; RpMaterialList matList; RpTriangle* triangles; RwRGBA* preLitLum; RwTexCoords* texCoords[8]; RpMeshHeader* mesh; RwResEntry* repEntry; RpMorphTarget* morphTarget; }; struct xAnimTable { xAnimTable* Next; int8* Name; xAnimTransition* TransitionList; xAnimState* StateList; uint32 AnimIndex; uint32 MorphIndex; uint32 UserFlags; }; struct xAnimPlay { xAnimPlay* Next; uint16 NumSingle; uint16 BoneCount; xAnimSingle* Single; void* Object; xAnimTable* Table; xMemPool* Pool; xModelInstance* ModelInst; void(*BeforeAnimMatrices)(xAnimPlay*, xQuat*, xVec3*, int32); }; struct xModelInstance { xModelInstance* Next; xModelInstance* Parent; xModelPool* Pool; xAnimPlay* Anim; RpAtomic* Data; uint32 PipeFlags; float32 RedMultiplier; float32 GreenMultiplier; float32 BlueMultiplier; float32 Alpha; float32 FadeStart; float32 FadeEnd; xSurface* Surf; xModelBucket** Bucket; xModelInstance* BucketNext; xLightKit* LightKit; void* Object; uint16 Flags; uint8 BoneCount; uint8 BoneIndex; uint8* BoneRemap; RwMatrixTag* Mat; xVec3 Scale; uint32 modelID; uint32 shadowID; RpAtomic* shadowmapAtomic; _class_1 anim_coll; }; struct RpVertexNormal { int8 x; int8 y; int8 z; uint8 pad; }; struct zPlatform : zEnt { xPlatformAsset* passet; xEntMotion motion; uint16 state; uint16 plat_flags; float32 tmr; int32 ctr; xMovePoint* src; xModelInstance* am; xModelInstance* bm; int32 moving; xEntDrive drv; zPlatFMRunTime* fmrt; float32 pauseMult; float32 pauseDelta; }; struct rxHeapFreeBlock { uint32 size; rxHeapBlockHeader* ptr; }; struct xMovePoint : xBase { xMovePointAsset* asset; xVec3* pos; xMovePoint** nodes; xMovePoint* prev; uint32 node_wt_sum; uint8 on; uint8 pad[2]; float32 delay; xSpline3* spl; }; struct RwRaster { RwRaster* parent; uint8* cpPixels; uint8* palette; int32 width; int32 height; int32 depth; int32 stride; int16 nOffsetX; int16 nOffsetY; uint8 cType; uint8 cFlags; uint8 privateFlags; uint8 cFormat; uint8* originalPixels; int32 originalWidth; int32 originalHeight; int32 originalStride; }; struct iEnv { RpWorld* world; RpWorld* collision; RpWorld* fx; RpWorld* camera; xJSPHeader* jsp; RpLight* light[2]; RwFrame* light_frame[2]; int32 memlvl; }; struct RxPipelineNodeTopSortData { uint32 numIns; uint32 numInsVisited; rxReq* req; }; struct xAnimEffect { xAnimEffect* Next; uint32 Flags; float32 StartTime; float32 EndTime; uint32(*Callback)(uint32, xAnimActiveEffect*, xAnimSingle*, void*); }; struct RwV2d { float32 x; float32 y; }; struct RwTexCoords { float32 u; float32 v; }; struct xBase { uint32 id; uint8 baseType; uint8 linkCount; uint16 baseFlags; xLinkAsset* link; int32(*eventFunc)(xBase*, xBase*, uint32, float32*, xBase*); }; struct xGridBound { void* data; uint16 gx; uint16 gz; uint8 ingrid; uint8 oversize; uint8 deleted; uint8 gpad; xGridBound** head; xGridBound* next; }; struct iterator { uint32 _it; static_queue_0* _owner; }; enum _tagRumbleType { eRumble_Off, eRumble_Hi, eRumble_VeryLightHi, eRumble_VeryLight, eRumble_LightHi, eRumble_Light, eRumble_MediumHi, eRumble_Medium, eRumble_HeavyHi, eRumble_Heavy, eRumble_VeryHeavyHi, eRumble_VeryHeavy, eRumble_Total, eRumbleForceU32 = 0x7fffffff }; struct RxNodeDefinition { int8* name; RxNodeMethods nodeMethods; RxIoSpec io; uint32 pipelineNodePrivateDataSize; RxNodeDefEditable editable; int32 InputPipesCnt; }; struct _class_0 { RwTexture* asset; uint32 units; xVec2 size; xVec2 isize; int32 prev; }; struct tagiRenderInput { uint16* m_index; RxObjSpace3DVertex* m_vertex; float32* m_vertexTZ; uint32 m_mode; int32 m_vertexType; int32 m_vertexTypeSize; int32 m_indexCount; int32 m_vertexCount; xMat4x3 m_camViewMatrix; xVec4 m_camViewR; xVec4 m_camViewU; }; enum _zPlayerType { ePlayer_SB, ePlayer_Patrick, ePlayer_Sandy, ePlayer_MAXTYPES }; struct xLightKit { uint32 tagID; uint32 groupID; uint32 lightCount; xLightKitLight* lightList; }; struct xUpdateCullGroup { uint32 active; uint16 startIndex; uint16 endIndex; xGroup* groupObject; }; struct zCutsceneMgr { }; struct zEnt : xEnt { xAnimTable* atbl; }; struct xAnimSingle { uint32 SingleFlags; xAnimState* State; float32 Time; float32 CurrentSpeed; float32 BilinearLerp[2]; xAnimEffect* Effect; uint32 ActiveCount; float32 LastTime; xAnimActiveEffect* ActiveList; xAnimPlay* Play; xAnimTransition* Sync; xAnimTransition* Tran; xAnimSingle* Blend; float32 BlendFactor; uint32 pad; }; struct RwRGBA { uint8 red; uint8 green; uint8 blue; uint8 alpha; }; struct rxHeapSuperBlockDescriptor { void* start; uint32 size; rxHeapSuperBlockDescriptor* next; }; struct xJSPNodeInfo { int32 originalMatIndex; int32 nodeFlags; }; struct RwTexture { RwRaster* raster; RwTexDictionary* dict; RwLLLink lInDictionary; int8 name[32]; int8 mask[32]; uint32 filterAddressing; int32 refCount; }; struct _tagEmitSphere { float32 radius; }; struct xAnimState { xAnimState* Next; int8* Name; uint32 ID; uint32 Flags; uint32 UserFlags; float32 Speed; xAnimFile* Data; xAnimEffect* Effects; xAnimTransitionList* Default; xAnimTransitionList* List; float32* BoneBlend; float32* TimeSnap; float32 FadeRecip; uint16* FadeOffset; void* CallbackData; xAnimMultiFile* MultiFile; void(*BeforeEnter)(xAnimPlay*, xAnimState*); void(*StateCallback)(xAnimState*, xAnimSingle*, void*); void(*BeforeAnimMatrices)(xAnimPlay*, xQuat*, xVec3*, int32); }; struct xEntMechData { xVec3 apos; xVec3 bpos; xVec3 dir; float32 arot; float32 brot; float32 ss; float32 sr; int32 state; float32 tsfd; float32 trfd; float32 tsbd; float32 trbd; float32* rotptr; }; struct RwResEntry { RwLLLink link; int32 size; void* owner; RwResEntry** ownerRef; void(*destroyNotify)(RwResEntry*); }; struct RxPipeline { int32 locked; uint32 numNodes; RxPipelineNode* nodes; uint32 packetNumClusterSlots; rxEmbeddedPacketState embeddedPacketState; RxPacket* embeddedPacket; uint32 numInputRequirements; RxPipelineRequiresCluster* inputRequirements; void* superBlock; uint32 superBlockSize; uint32 entryPoint; uint32 pluginId; uint32 pluginData; }; struct xMat4x3 : xMat3x3 { xVec3 pos; uint32 pad3; }; struct RxPipelineCluster { RxClusterDefinition* clusterRef; uint32 creationAttributes; }; struct RxObjSpace3DVertex { RwV3d objVertex; RxColorUnion c; RwV3d objNormal; float32 u; float32 v; }; struct xEntMotionSplineData { int32 unknown; }; struct RxPipelineNodeParam { void* dataParam; RxHeap* heap; }; struct zAssetPickupTable { }; struct analog_data { xVec2 offset; xVec2 dir; float32 mag; float32 ang; }; struct RpMeshHeader { uint32 flags; uint16 numMeshes; uint16 serialNum; uint32 totalIndicesInMesh; uint32 firstMeshOffset; }; struct xSpline3 { uint16 type; uint16 flags; uint32 N; uint32 allocN; xVec3* points; float32* time; xVec3* p12; xVec3* bctrl; float32* knot; xCoef3* coef; uint32 arcSample; float32* arcLength; }; struct RxHeap { uint32 superBlockSize; rxHeapSuperBlockDescriptor* head; rxHeapBlockHeader* headBlock; rxHeapFreeBlock* freeBlocks; uint32 entriesAlloced; uint32 entriesUsed; int32 dirty; }; struct RwBBox { RwV3d sup; RwV3d inf; }; struct xMemPool { void* FreeList; uint16 NextOffset; uint16 Flags; void* UsedList; void(*InitCB)(xMemPool*, void*); void* Buffer; uint16 Size; uint16 NumRealloc; uint32 Total; }; struct curve_node { float32 time; iColor_tag color; float32 scale; }; struct xQuat { xVec3 v; float32 s; }; struct xGroup : xBase { xGroupAsset* asset; xBase** item; uint32 last_index; int32 flg_group; }; struct RpTriangle { uint16 vertIndex[3]; int16 matIndex; }; struct xEntBoulder { }; struct RpAtomic { RwObjectHasFrame object; RwResEntry* repEntry; RpGeometry* geometry; RwSphere boundingSphere; RwSphere worldBoundingSphere; RpClump* clump; RwLLLink inClumpLink; RpAtomic*(*renderCallBack)(RpAtomic*); RpInterpolator interpolator; uint16 renderFrame; uint16 pad; RwLinkList llWorldSectorsInAtomic; RxPipeline* pipeline; }; struct xClumpCollBSPBranchNode { uint32 leftInfo; uint32 rightInfo; float32 leftValue; float32 rightValue; }; struct xEntShadow { xVec3 pos; xVec3 vec; RpAtomic* shadowModel; float32 dst_cast; float32 radius[2]; }; struct rxHeapBlockHeader { rxHeapBlockHeader* prev; rxHeapBlockHeader* next; uint32 size; rxHeapFreeBlock* freeEntry; uint32 pad[4]; }; struct xCollis { uint32 flags; uint32 oid; void* optr; xModelInstance* mptr; float32 dist; xVec3 norm; xVec3 tohit; xVec3 depen; xVec3 hdng; union { _class_3 tuv; tri_data_1 tri; }; }; struct zCheckPoint { xVec3 pos; float32 rot; uint32 initCamID; }; struct zPlayerGlobals { zEnt ent; xEntShadow entShadow_embedded; xShadowSimpleCache simpShadow_embedded; zGlobalSettings g; zPlayerSettings* s; zPlayerSettings sb; zPlayerSettings patrick; zPlayerSettings sandy; xModelInstance* model_spongebob; xModelInstance* model_patrick; xModelInstance* model_sandy; uint32 Visible; uint32 Health; int32 Speed; float32 SpeedMult; int32 Sneak; int32 Teeter; float32 SlipFadeTimer; int32 Slide; float32 SlideTimer; int32 Stepping; int32 JumpState; int32 LastJumpState; float32 JumpTimer; float32 LookAroundTimer; uint32 LookAroundRand; uint32 LastProjectile; float32 DecelRun; float32 DecelRunSpeed; float32 HotsauceTimer; float32 LeanLerp; float32 ScareTimer; xBase* ScareSource; float32 CowerTimer; float32 DamageTimer; float32 SundaeTimer; float32 ControlOffTimer; float32 HelmetTimer; uint32 WorldDisguise; uint32 Bounced; float32 FallDeathTimer; float32 HeadbuttVel; float32 HeadbuttTimer; uint32 SpecialReceived; xEnt* MountChimney; float32 MountChimOldY; uint32 MaxHealth; uint32 DoMeleeCheck; float32 VictoryTimer; float32 BadGuyNearTimer; float32 ForceSlipperyTimer; float32 ForceSlipperyFriction; float32 ShockRadius; float32 ShockRadiusOld; float32 Face_ScareTimer; uint32 Face_ScareRandom; uint32 Face_Event; float32 Face_EventTimer; float32 Face_PantTimer; uint32 Face_AnimSpecific; uint32 IdleRand; float32 IdleMinorTimer; float32 IdleMajorTimer; float32 IdleSitTimer; int32 Transparent; zEnt* FireTarget; uint32 ControlOff; uint32 ControlOnEvent; uint32 AutoMoveSpeed; float32 AutoMoveDist; xVec3 AutoMoveTarget; xBase* AutoMoveObject; zEnt* Diggable; float32 DigTimer; zPlayerCarryInfo carry; zPlayerLassoInfo lassoInfo; xModelTag BubbleWandTag[2]; xModelInstance* model_wand; xEntBoulder* bubblebowl; float32 bbowlInitVel; zEntHangable* HangFound; zEntHangable* HangEnt; zEntHangable* HangEntLast; xVec3 HangPivot; xVec3 HangVel; float32 HangLength; xVec3 HangStartPos; float32 HangStartLerp; xModelTag HangPawTag[4]; float32 HangPawOffset; float32 HangElapsed; float32 Jump_CurrGravity; float32 Jump_HoldTimer; float32 Jump_ChangeTimer; int32 Jump_CanDouble; int32 Jump_CanFloat; int32 Jump_SpringboardStart; zPlatform* Jump_Springboard; int32 CanJump; int32 CanBubbleSpin; int32 CanBubbleBounce; int32 CanBubbleBash; int32 IsJumping; int32 IsDJumping; int32 IsBubbleSpinning; int32 IsBubbleBouncing; int32 IsBubbleBashing; int32 IsBubbleBowling; int32 WasDJumping; int32 IsCoptering; _zPlayerWallJumpState WallJumpState; int32 cheat_mode; uint32 Inv_Shiny; uint32 Inv_Spatula; uint32 Inv_PatsSock[15]; uint32 Inv_PatsSock_Max[15]; uint32 Inv_PatsSock_CurrentLevel; uint32 Inv_LevelPickups[15]; uint32 Inv_LevelPickups_CurrentLevel; uint32 Inv_PatsSock_Total; xModelTag BubbleTag; xEntDrive drv; xSurface* floor_surf; xVec3 floor_norm; int32 slope; xCollis earc_coll; xSphere head_sph; xModelTag center_tag; xModelTag head_tag; uint32 TongueFlags[2]; xVec3 RootUp; xVec3 RootUpTarget; zCheckPoint cp; uint32 SlideTrackSliding; uint32 SlideTrackCount; xEnt* SlideTrackEnt[111]; uint32 SlideNotGroundedSinceSlide; xVec3 SlideTrackDir; xVec3 SlideTrackVel; float32 SlideTrackDecay; float32 SlideTrackLean; float32 SlideTrackLand; uint8 sb_model_indices[14]; xModelInstance* sb_models[14]; uint32 currentPlayer; xVec3 PredictRotate; xVec3 PredictTranslate; float32 PredictAngV; xVec3 PredictCurrDir; float32 PredictCurrVel; float32 KnockBackTimer; float32 KnockIntoAirTimer; }; struct xModelPool { xModelPool* Next; uint32 NumMatrices; xModelInstance* List; }; struct RxPipelineRequiresCluster { RxClusterDefinition* clusterDef; RxClusterValidityReq rqdOrOpt; uint32 slotIndex; }; struct _tagEmitRect { float32 x_len; float32 z_len; }; struct xEntMotionMPData { uint32 flags; uint32 mp_id; float32 speed; }; struct xJSPHeader { int8 idtag[4]; uint32 version; uint32 jspNodeCount; RpClump* clump; xClumpCollBSPTree* colltree; xJSPNodeInfo* jspNodeList; }; struct xEntAsset : xBaseAsset { uint8 flags; uint8 subtype; uint8 pflags; uint8 moreFlags; uint8 pad; uint32 surfaceID; xVec3 ang; xVec3 pos; xVec3 scale; float32 redMult; float32 greenMult; float32 blueMult; float32 seeThru; float32 seeThruSpeed; uint32 modelInfoID; uint32 animListID; }; struct xEntERData { xVec3 a; xVec3 b; xVec3 dir; float32 et; float32 wet; float32 rt; float32 wrt; float32 p; float32 brt; float32 ert; int32 state; }; struct xUpdateCullMgr { uint32 entCount; uint32 entActive; void** ent; xUpdateCullEnt** mgr; uint32 mgrCount; uint32 mgrCurr; xUpdateCullEnt* mgrList; uint32 grpCount; xUpdateCullGroup* grpList; void(*activateCB)(void*); void(*deactivateCB)(void*); }; struct zPlayerCarryInfo { xEnt* grabbed; uint32 grabbedModelID; xMat4x3 spin; xEnt* throwTarget; xEnt* flyingToTarget; float32 minDist; float32 maxDist; float32 minHeight; float32 maxHeight; float32 maxCosAngle; float32 throwMinDist; float32 throwMaxDist; float32 throwMinHeight; float32 throwMaxHeight; float32 throwMaxStack; float32 throwMaxCosAngle; float32 throwTargetRotRate; float32 targetRot; uint32 grabTarget; xVec3 grabOffset; float32 grabLerpMin; float32 grabLerpMax; float32 grabLerpLast; uint32 grabYclear; float32 throwGravity; float32 throwHeight; float32 throwDistance; float32 fruitFloorDecayMin; float32 fruitFloorDecayMax; float32 fruitFloorBounce; float32 fruitFloorFriction; float32 fruitCeilingBounce; float32 fruitWallBounce; float32 fruitLifetime; xEnt* patLauncher; }; struct xPortalAsset : xBaseAsset { uint32 assetCameraID; uint32 assetMarkerID; float32 ang; uint32 sceneID; }; enum fx_when_enum { FX_WHEN_LAUNCH, FX_WHEN_IMPACT, FX_WHEN_BIRTH, FX_WHEN_DEATH, FX_WHEN_HEAD, FX_WHEN_TAIL, FX_WHEN_KILL, MAX_FX_WHEN }; struct zPlayerSettings { _zPlayerType pcType; float32 MoveSpeed[6]; float32 AnimSneak[3]; float32 AnimWalk[3]; float32 AnimRun[3]; float32 JumpGravity; float32 GravSmooth; float32 FloatSpeed; float32 ButtsmashSpeed; zJumpParam Jump; zJumpParam Bounce; zJumpParam Spring; zJumpParam Wall; zJumpParam Double; zJumpParam SlideDouble; zJumpParam SlideJump; float32 WallJumpVelocity; zLedgeGrabParams ledge; float32 spin_damp_xz; float32 spin_damp_y; uint8 talk_anims; uint8 talk_filter_size; uint8 talk_filter[4]; }; struct xScene { uint32 sceneID; uint16 flags; uint16 num_ents; uint16 num_trigs; uint16 num_stats; uint16 num_dyns; uint16 num_npcs; uint16 num_act_ents; uint16 num_nact_ents; float32 gravity; float32 drag; float32 friction; uint16 num_ents_allocd; uint16 num_trigs_allocd; uint16 num_stats_allocd; uint16 num_dyns_allocd; uint16 num_npcs_allocd; xEnt** trigs; xEnt** stats; xEnt** dyns; xEnt** npcs; xEnt** act_ents; xEnt** nact_ents; xEnv* env; xMemPool mempool; xBase*(*resolvID)(uint32); int8*(*base2Name)(xBase*); int8*(*id2Name)(uint32); }; struct xCamera : xBase { RwCamera* lo_cam; xMat4x3 mat; xMat4x3 omat; xMat3x3 mbasis; xBound bound; xMat4x3* tgt_mat; xMat4x3* tgt_omat; xBound* tgt_bound; xVec3 focus; xScene* sc; xVec3 tran_accum; float32 fov; uint32 flags; float32 tmr; float32 tm_acc; float32 tm_dec; float32 ltmr; float32 ltm_acc; float32 ltm_dec; float32 dmin; float32 dmax; float32 dcur; float32 dgoal; float32 hmin; float32 hmax; float32 hcur; float32 hgoal; float32 pmin; float32 pmax; float32 pcur; float32 pgoal; float32 depv; float32 hepv; float32 pepv; float32 orn_epv; float32 yaw_epv; float32 pitch_epv; float32 roll_epv; xQuat orn_cur; xQuat orn_goal; xQuat orn_diff; float32 yaw_cur; float32 yaw_goal; float32 pitch_cur; float32 pitch_goal; float32 roll_cur; float32 roll_goal; float32 dct; float32 dcd; float32 dccv; float32 dcsv; float32 hct; float32 hcd; float32 hccv; float32 hcsv; float32 pct; float32 pcd; float32 pccv; float32 pcsv; float32 orn_ct; float32 orn_cd; float32 orn_ccv; float32 orn_csv; float32 yaw_ct; float32 yaw_cd; float32 yaw_ccv; float32 yaw_csv; float32 pitch_ct; float32 pitch_cd; float32 pitch_ccv; float32 pitch_csv; float32 roll_ct; float32 roll_cd; float32 roll_ccv; float32 roll_csv; xVec4 frustplane[12]; }; struct xAnimFile { xAnimFile* Next; int8* Name; uint32 ID; uint32 FileFlags; float32 Duration; float32 TimeOffset; uint16 BoneCount; uint8 NumAnims[2]; void** RawData; }; struct _zEnv : xBase { xEnvAsset* easset; }; struct RpClump { RwObject object; RwLinkList atomicList; RwLinkList lightList; RwLinkList cameraList; RwLLLink inWorldLink; RpClump*(*callback)(RpClump*, void*); }; struct xVec4 { float32 x; float32 y; float32 z; float32 w; }; struct xSurface : xBase { uint32 idx; uint32 type; union { uint32 mat_idx; xEnt* ent; void* obj; }; float32 friction; uint8 state; uint8 pad[3]; void* moprops; }; struct xQCData { int8 xmin; int8 ymin; int8 zmin; int8 zmin_dup; int8 xmax; int8 ymax; int8 zmax; int8 zmax_dup; xVec3 min; xVec3 max; }; struct xCoef { float32 a[4]; }; struct RwSurfaceProperties { float32 ambient; float32 specular; float32 diffuse; }; struct xClumpCollBSPTree { uint32 numBranchNodes; xClumpCollBSPBranchNode* branchNodes; uint32 numTriangles; xClumpCollBSPTriangle* triangles; }; struct RwCamera { RwObjectHasFrame object; RwCameraProjection projectionType; RwCamera*(*beginUpdate)(RwCamera*); RwCamera*(*endUpdate)(RwCamera*); RwMatrixTag viewMatrix; RwRaster* frameBuffer; RwRaster* zBuffer; RwV2d viewWindow; RwV2d recipViewWindow; RwV2d viewOffset; float32 nearPlane; float32 farPlane; float32 fogPlane; float32 zScale; float32 zShift; RwFrustumPlane frustumPlanes[6]; RwBBox frustumBoundBox; RwV3d frustumCorners[8]; }; struct RwMatrixTag { RwV3d right; uint32 flags; RwV3d up; uint32 pad1; RwV3d at; uint32 pad2; RwV3d pos; uint32 pad3; }; struct xAnimTransition { xAnimTransition* Next; xAnimState* Dest; uint32(*Conditional)(xAnimTransition*, xAnimSingle*, void*); uint32(*Callback)(xAnimTransition*, xAnimSingle*, void*); uint32 Flags; uint32 UserFlags; float32 SrcTime; float32 DestTime; uint16 Priority; uint16 QueuePriority; float32 BlendRecip; uint16* BlendOffset; }; struct xAnimTransitionList { xAnimTransitionList* Next; xAnimTransition* T; }; struct xUpdateCullEnt { uint16 index; int16 groupIndex; uint32(*cb)(void*, void*); void* cbdata; xUpdateCullEnt* nextInGroup; }; struct rxReq { }; struct xPEEntBound { uint8 flags; uint8 type; uint8 pad1; uint8 pad2; float32 expand; float32 deflection; }; struct xEnvAsset : xBaseAsset { uint32 bspAssetID; uint32 startCameraAssetID; uint32 climateFlags; float32 climateStrengthMin; float32 climateStrengthMax; uint32 bspLightKit; uint32 objectLightKit; float32 padF1; uint32 bspCollisionAssetID; uint32 bspFXAssetID; uint32 bspCameraAssetID; uint32 bspMapperID; uint32 bspMapperCollisionID; uint32 bspMapperFXID; float32 loldHeight; }; struct xLinkAsset { uint16 srcEvent; uint16 dstEvent; uint32 dstAssetID; float32 param[4]; uint32 paramWidgetAssetID; uint32 chkAssetID; }; struct xModelTag { xVec3 v; uint32 matidx; float32 wt[4]; }; struct zLasso { uint32 flags; float32 secsTotal; float32 secsLeft; float32 stRadius; float32 tgRadius; float32 crRadius; xVec3 stCenter; xVec3 tgCenter; xVec3 crCenter; xVec3 stNormal; xVec3 tgNormal; xVec3 crNormal; xVec3 honda; float32 stSlack; float32 stSlackDist; float32 tgSlack; float32 tgSlackDist; float32 crSlack; float32 currDist; float32 lastDist; xVec3 lastRefs[5]; uint8 reindex[5]; xVec3 anchor; xModelTag tag; xModelInstance* model; }; struct xEntMotionMechData { uint8 type; uint8 flags; uint8 sld_axis; uint8 rot_axis; float32 sld_dist; float32 sld_tm; float32 sld_acc_tm; float32 sld_dec_tm; float32 rot_dist; float32 rot_tm; float32 rot_acc_tm; float32 rot_dec_tm; float32 ret_delay; float32 post_ret_delay; }; struct _tagEmitLine { xVec3 pos1; xVec3 pos2; float32 radius; }; enum RxClusterValidityReq { rxCLREQ_DONTWANT, rxCLREQ_REQUIRED, rxCLREQ_OPTIONAL, rxCLUSTERVALIDITYREQFORCEENUMSIZEINT = 0x7fffffff }; enum RpWorldRenderOrder { rpWORLDRENDERNARENDERORDER, rpWORLDRENDERFRONT2BACK, rpWORLDRENDERBACK2FRONT, rpWORLDRENDERORDERFORCEENUMSIZEINT = 0x7fffffff }; struct xRay3 { xVec3 origin; xVec3 dir; float32 min_t; float32 max_t; int32 flags; }; struct xEntPenData { xVec3 top; float32 w; xMat4x3 omat; }; struct _tagxRumble { _tagRumbleType type; float32 seconds; _tagxRumble* next; int16 active; uint16 fxflags; }; struct iFogParams { RwFogType type; float32 start; float32 stop; float32 density; RwRGBA fogcolor; RwRGBA bgcolor; uint8* table; }; struct xCoef3 { xCoef x; xCoef y; xCoef z; }; struct xEntDrive { uint32 flags; float32 otm; float32 otmr; float32 os; float32 tm; float32 tmr; float32 s; xEnt* odriver; xEnt* driver; xEnt* driven; xVec3 op; xVec3 p; xVec3 q; float32 yaw; xVec3 dloc; tri_data_0 tri; }; enum RxNodeDefEditable { rxNODEDEFCONST, rxNODEDEFEDITABLE, rxNODEDEFEDITABLEFORCEENUMSIZEINT = 0x7fffffff }; struct xBound { xQCData qcd; uint8 type; uint8 pad[3]; union { xSphere sph; xBBox box; xCylinder cyl; }; xMat4x3* mat; }; struct RpMaterial { RwTexture* texture; RwRGBA color; RxPipeline* pipeline; RwSurfaceProperties surfaceProps; int16 refCount; int16 pad; }; struct RpSector { int32 type; }; struct xModelBucket { RpAtomic* Data; RpAtomic* OriginalData; xModelInstance* List; int32 ClipFlags; uint32 PipeFlags; }; enum RxClusterValid { rxCLVALID_NOCHANGE, rxCLVALID_VALID, rxCLVALID_INVALID, rxCLUSTERVALIDFORCEENUMSIZEINT = 0x7fffffff }; enum fx_type_enum { FX_TYPE_PARTICLE, FX_TYPE_DECAL, FX_TYPE_DECAL_DIST, FX_TYPE_CALLBACK }; struct xEntCollis { uint8 chk; uint8 pen; uint8 env_sidx; uint8 env_eidx; uint8 npc_sidx; uint8 npc_eidx; uint8 dyn_sidx; uint8 dyn_eidx; uint8 stat_sidx; uint8 stat_eidx; uint8 idx; xCollis colls[18]; void(*post)(xEnt*, xScene*, float32, xEntCollis*); uint32(*depenq)(xEnt*, xEnt*, xScene*, float32, xCollis*); }; struct xAnimMultiFile : xAnimMultiFileBase { xAnimMultiFileEntry Files[1]; }; struct xRot { xVec3 axis; float32 angle; }; struct xEntOrbitData { xVec3 orig; xVec3 c; float32 a; float32 b; float32 p; float32 w; }; struct xVec2 { float32 x; float32 y; }; struct RpWorld { RwObject object; uint32 flags; RpWorldRenderOrder renderOrder; RpMaterialList matList; RpSector* rootSector; int32 numTexCoordSets; int32 numClumpsInWorld; RwLLLink* currentClumpLink; RwLinkList clumpList; RwLinkList lightList; RwLinkList directionalLightList; RwV3d worldOrigin; RwBBox boundingBox; RpWorldSector*(*renderCallBack)(RpWorldSector*); RxPipeline* pipeline; }; struct RpWorldSector { int32 type; RpPolygon* polygons; RwV3d* vertices; RpVertexNormal* normals; RwTexCoords* texCoords[8]; RwRGBA* preLitLum; RwResEntry* repEntry; RwLinkList collAtomicsInWorldSector; RwLinkList noCollAtomicsInWorldSector; RwLinkList lightsInWorldSector; RwBBox boundingBox; RwBBox tightBoundingBox; RpMeshHeader* mesh; RxPipeline* pipeline; uint16 matListWindowBase; uint16 numVertices; uint16 numPolygons; uint16 pad; }; struct RpMorphTarget { RpGeometry* parentGeom; RwSphere boundingSphere; RwV3d* verts; RwV3d* normals; }; struct xParEmitterAsset : xBaseAsset { uint8 emit_flags; uint8 emit_type; uint16 pad; uint32 propID; union { xPECircle e_circle; _tagEmitSphere e_sphere; _tagEmitRect e_rect; _tagEmitLine e_line; _tagEmitVolume e_volume; _tagEmitOffsetPoint e_offsetp; xPEVCyl e_vcyl; xPEEntBone e_entbone; xPEEntBound e_entbound; }; uint32 attachToID; xVec3 pos; xVec3 vel; float32 vel_angle_variation; uint32 cull_mode; float32 cull_dist_sqr; }; enum rxEmbeddedPacketState { rxPKST_PACKETLESS, rxPKST_UNUSED, rxPKST_INUSE, rxPKST_PENDING, rxEMBEDDEDPACKETSTATEFORCEENUMSIZEINT = 0x7fffffff }; struct zPlatFMRunTime { uint32 flags; float32 tmrs[12]; float32 ttms[12]; float32 atms[12]; float32 dtms[12]; float32 vms[12]; float32 dss[12]; }; struct xSphere { xVec3 center; float32 r; }; struct _tagEmitVolume { uint32 emit_volumeID; }; struct _zPortal : xBase { xPortalAsset* passet; }; struct RpLight { RwObjectHasFrame object; float32 radius; RwRGBAReal color; float32 minusCosAngle; RwLinkList WorldSectorsInLight; RwLLLink inWorld; uint16 lightFrame; uint16 pad; }; struct xEntMotion { xEntMotionAsset* asset; uint8 type; uint8 pad; uint16 flags; float32 t; float32 tmr; float32 d; union { xEntERData er; xEntOrbitData orb; xEntSplineData spl; xEntMPData mp; xEntMechData mech; xEntPenData pen; }; xEnt* owner; xEnt* target; }; struct unit_data { uint8 flags; uint8 curve_index; uint8 u; uint8 v; float32 frac; float32 age; float32 cull_size; xMat4x3 mat; }; struct xParGroup { }; struct xEntFrame { xMat4x3 mat; xMat4x3 oldmat; xVec3 oldvel; xRot oldrot; xRot drot; xRot rot; xVec3 dpos; xVec3 dvel; xVec3 vel; uint32 mode; }; struct xFFX { }; enum RwCameraProjection { rwNACAMERAPROJECTION, rwPERSPECTIVE, rwPARALLEL, rwCAMERAPROJECTIONFORCEENUMSIZEINT = 0x7fffffff }; struct xPlatformAsset { }; enum _tagPadState { ePad_Disabled, ePad_DisabledError, ePad_Enabled, ePad_Missing, ePad_Total }; enum RxClusterForcePresent { rxCLALLOWABSENT, rxCLFORCEPRESENT, rxCLUSTERFORCEPRESENTFORCEENUMSIZEINT = 0x7fffffff }; struct xParEmitterPropsAsset : xBaseAsset { uint32 parSysID; union { xParInterp rate; xParInterp value[1]; }; xParInterp life; xParInterp size_birth; xParInterp size_death; xParInterp color_birth[4]; xParInterp color_death[4]; xParInterp vel_scale; xParInterp vel_angle; xVec3 vel; uint32 emit_limit; float32 emit_limit_reset_time; }; struct xEntMotionAsset { uint8 type; uint8 use_banking; uint16 flags; union { xEntMotionERData er; xEntMotionOrbitData orb; xEntMotionSplineData spl; xEntMotionMPData mp; xEntMotionMechData mech; xEntMotionPenData pen; }; }; struct xCylinder { xVec3 center; float32 r; float32 h; }; enum fx_orient_enum { FX_ORIENT_DEFAULT, FX_ORIENT_PATH, FX_ORIENT_IPATH, FX_ORIENT_HIT_NORM, FX_ORIENT_HIT_REFLECT, MAX_FX_ORIENT, FORCE_INT_FX_ORIENT = 0xffffffff }; struct RxColorUnion { union { RwRGBA preLitColor; RwRGBA color; }; }; struct xGlobals { xCamera camera; _tagxPad* pad0; _tagxPad* pad1; _tagxPad* pad2; _tagxPad* pad3; int32 profile; int8 profFunc[128][6]; xUpdateCullMgr* updateMgr; int32 sceneFirst; int8 sceneStart[32]; RpWorld* currWorld; iFogParams fog; iFogParams fogA; iFogParams fogB; long32 fog_t0; long32 fog_t1; int32 option_vibration; uint32 QuarterSpeed; float32 update_dt; int32 useHIPHOP; uint8 NoMusic; int8 currentActivePad; uint8 firstStartPressed; uint32 minVSyncCnt; uint8 dontShowPadMessageDuringLoadingOrCutScene; uint8 autoSaveFeature; }; struct RwFrame { RwObject object; RwLLLink inDirtyListLink; RwMatrixTag modelling; RwMatrixTag ltm; RwLinkList objectList; RwFrame* child; RwFrame* next; RwFrame* root; }; struct xBox { xVec3 upper; xVec3 lower; }; struct RxClusterDefinition { int8* name; uint32 defaultStride; uint32 defaultAttributes; int8* attributeSet; }; struct xShadowSimplePoly { xVec3 vert[3]; xVec3 norm; }; struct _tagxPad { uint8 value[22]; uint8 last_value[22]; uint32 on; uint32 pressed; uint32 released; _tagPadAnalog analog1; _tagPadAnalog analog2; _tagPadState state; uint32 flags; _tagxRumble rumble_head; int16 port; int16 slot; _tagiPad context; float32 al2d_timer; float32 ar2d_timer; float32 d_timer; float32 up_tmr[22]; float32 down_tmr[22]; analog_data analog[2]; }; struct xEntSplineData { int32 unknown; }; struct _tagEmitOffsetPoint { xVec3 offset; }; struct RwSphere { RwV3d center; float32 radius; }; struct xParEmitter : xBase { xParEmitterAsset* tasset; xParGroup* group; xParEmitterPropsAsset* prop; uint8 rate_mode; float32 rate; float32 rate_time; float32 rate_fraction; float32 rate_fraction_cull; uint8 emit_flags; uint8 emit_pad[3]; uint8 rot[3]; xModelTag tag; float32 oocull_distance_sqr; float32 distance_to_cull_sqr; void* attachTo; xParSys* parSys; void* emit_volume; xVec3 last_attach_loc; }; struct RwLLLink { RwLLLink* next; RwLLLink* prev; }; struct tri_data_0 : tri_data_1 { xVec3 loc; float32 yaw; xCollis* coll; }; struct xGroupAsset : xBaseAsset { uint16 itemCount; uint16 groupFlags; }; struct _tagPadAnalog { int8 x; int8 y; }; struct RwTexDictionary { RwObject object; RwLinkList texturesInDict; RwLLLink lInInstance; }; struct xEntMotionPenData { uint8 flags; uint8 plane; uint8 pad[2]; float32 len; float32 range; float32 period; float32 phase; }; struct RxOutputSpec { int8* name; RxClusterValid* outputClusters; RxClusterValid allOtherClusters; }; struct xDecalEmitter { config_1 cfg; _class_0 texture; static_queue_1 units; curve_node* curve; uint32 curve_size; uint32 curve_index; float32 ilife; }; struct _tagiPad { int32 port; }; struct xLightKitLight { uint32 type; RwRGBAReal color; float32 matrix[16]; float32 radius; float32 angle; RpLight* platLight; }; struct tri_data_1 { uint32 index; float32 r; float32 d; }; struct xMat3x3 { xVec3 right; int32 flags; xVec3 up; uint32 pad1; xVec3 at; uint32 pad2; }; struct xAnimMultiFileEntry { uint32 ID; xAnimFile* File; }; struct xAnimActiveEffect { xAnimEffect* Effect; uint32 Handle; }; struct _class_1 { xVec3* verts; }; struct xShadowSimpleCache { uint16 flags; uint8 alpha; uint8 pad; uint32 collPriority; xVec3 pos; xVec3 at; xEnt* castOnEnt; xShadowSimplePoly poly; float32 envHeight; float32 shadowHeight; uint32 raster; float32 dydx; float32 dydz; xVec3 corner[4]; }; struct RxClusterRef { RxClusterDefinition* clusterDef; RxClusterForcePresent forcePresent; uint32 reserved; }; struct xEntMPData { float32 curdist; float32 speed; xMovePoint* dest; xMovePoint* src; xSpline3* spl; float32 dist; uint32 padalign; xQuat aquat; xQuat bquat; }; struct xParSys { }; struct RwObject { uint8 type; uint8 subType; uint8 flags; uint8 privateFlags; void* parent; }; struct xPEVCyl { float32 height; float32 radius; float32 deflection; }; struct config_0 { float32 radius; float32 length; float32 vel; float32 fade_dist; float32 kill_dist; float32 safe_dist; float32 hit_radius; float32 rand_ang; float32 scar_life; xVec2 bolt_uv[2]; int32 hit_interval; float32 damage; }; struct RxIoSpec { uint32 numClustersOfInterest; RxClusterRef* clustersOfInterest; RxClusterValidityReq* inputRequirements; uint32 numOutputs; RxOutputSpec* outputs; }; enum texture_mode { TM_DEFAULT, TM_RANDOM, TM_CYCLE, MAX_TM, FORCE_INT_TM = 0xffffffff }; struct RpInterpolator { int32 flags; int16 startMorphTarget; int16 endMorphTarget; float32 time; float32 recipTime; float32 position; }; struct xParInterp { float32 val[2]; uint32 interp; float32 freq; float32 oofreq; }; struct xClumpCollBSPVertInfo { uint16 atomIndex; uint16 meshVertIndex; }; struct RxNodeMethods { int32(*nodeBody)(RxPipelineNode*, RxPipelineNodeParam*); int32(*nodeInit)(RxNodeDefinition*); void(*nodeTerm)(RxNodeDefinition*); int32(*pipelineNodeInit)(RxPipelineNode*); void(*pipelineNodeTerm)(RxPipelineNode*); int32(*pipelineNodeConfig)(RxPipelineNode*, RxPipeline*); uint32(*configMsgHandler)(RxPipelineNode*, uint32, uint32, void*); }; struct xEntMotionERData { xVec3 ret_pos; xVec3 ext_dpos; float32 ext_tm; float32 ext_wait_tm; float32 ret_tm; float32 ret_wait_tm; }; struct _class_2 { union { xParEmitter* par; xDecalEmitter* decal; _class_4 callback; }; }; struct xClumpCollBSPTriangle { _class_6 v; uint8 flags; uint8 platData; uint16 matIndex; }; struct xAnimMultiFileBase { uint32 Count; }; struct _class_3 { float32 t; float32 u; float32 v; }; struct RwFrustumPlane { RwPlane plane; uint8 closestX; uint8 closestY; uint8 closestZ; uint8 pad; }; struct xBaseAsset { uint32 id; uint8 baseType; uint8 linkCount; uint16 baseFlags; }; struct xPEEntBone { uint8 flags; uint8 type; uint8 bone; uint8 pad1; xVec3 offset; float32 radius; float32 deflection; }; struct RwPlane { RwV3d normal; float32 distance; }; struct config_1 { uint32 flags; float32 life_time; uint32 blend_src; uint32 blend_dst; _class_5 texture; }; struct zGlobals : xGlobals { zPlayerGlobals player; zAssetPickupTable* pickupTable; zCutsceneMgr* cmgr; zScene* sceneCur; zScene* scenePreload; }; struct _class_4 { void(*fp)(bolt&, void*); void* context; }; struct RxCluster { uint16 flags; uint16 stride; void* data; void* currentData; uint32 numAlloced; uint32 numUsed; RxPipelineCluster* clusterRef; uint32 attributes; }; struct zGlobalSettings { uint16 AnalogMin; uint16 AnalogMax; float32 SundaeTime; float32 SundaeMult; uint32 InitialShinyCount; uint32 InitialSpatulaCount; int32 ShinyValuePurple; int32 ShinyValueBlue; int32 ShinyValueGreen; int32 ShinyValueYellow; int32 ShinyValueRed; int32 ShinyValueCombo0; int32 ShinyValueCombo1; int32 ShinyValueCombo2; int32 ShinyValueCombo3; int32 ShinyValueCombo4; int32 ShinyValueCombo5; int32 ShinyValueCombo6; int32 ShinyValueCombo7; int32 ShinyValueCombo8; int32 ShinyValueCombo9; int32 ShinyValueCombo10; int32 ShinyValueCombo11; int32 ShinyValueCombo12; int32 ShinyValueCombo13; int32 ShinyValueCombo14; int32 ShinyValueCombo15; float32 ComboTimer; uint32 Initial_Specials; uint32 TakeDamage; float32 DamageTimeHit; float32 DamageTimeSurface; float32 DamageTimeEGen; float32 DamageSurfKnock; float32 DamageGiveHealthKnock; uint32 CheatSpongeball; uint32 CheatPlayerSwitch; uint32 CheatAlwaysPortal; uint32 CheatFlyToggle; uint32 DisableForceConversation; float32 StartSlideAngle; float32 StopSlideAngle; float32 RotMatchMaxAngle; float32 RotMatchMatchTime; float32 RotMatchRelaxTime; float32 Gravity; float32 BBashTime; float32 BBashHeight; float32 BBashDelay; float32 BBashCVTime; float32 BBounceSpeed; float32 BSpinMinFrame; float32 BSpinMaxFrame; float32 BSpinRadius; float32 SandyMeleeMinFrame; float32 SandyMeleeMaxFrame; float32 SandyMeleeRadius; float32 BubbleBowlTimeDelay; float32 BubbleBowlLaunchPosLeft; float32 BubbleBowlLaunchPosUp; float32 BubbleBowlLaunchPosAt; float32 BubbleBowlLaunchVelLeft; float32 BubbleBowlLaunchVelUp; float32 BubbleBowlLaunchVelAt; float32 BubbleBowlPercentIncrease; float32 BubbleBowlMinSpeed; float32 BubbleBowlMinRecoverTime; float32 SlideAccelVelMin; float32 SlideAccelVelMax; float32 SlideAccelStart; float32 SlideAccelEnd; float32 SlideAccelPlayerFwd; float32 SlideAccelPlayerBack; float32 SlideAccelPlayerSide; float32 SlideVelMaxStart; float32 SlideVelMaxEnd; float32 SlideVelMaxIncTime; float32 SlideVelMaxIncAccel; float32 SlideAirHoldTime; float32 SlideAirSlowTime; float32 SlideAirDblHoldTime; float32 SlideAirDblSlowTime; float32 SlideVelDblBoost; uint8 SlideApplyPhysics; uint8 PowerUp[2]; uint8 InitialPowerUp[2]; }; struct RpMaterialList { RpMaterial** materials; int32 numMaterials; int32 space; }; struct RxPacket { uint16 flags; uint16 numClusters; RxPipeline* pipeline; uint32* inputToClusterSlot; uint32* slotsContinue; RxPipelineCluster** slotClusterRefs; RxCluster clusters[1]; }; struct zPlayerLassoInfo { xEnt* target; float32 dist; uint8 destroy; uint8 targetGuide; float32 lassoRot; xEnt* swingTarget; xEnt* releasedSwing; float32 copterTime; int32 canCopter; zLasso lasso; xAnimState* zeroAnim; }; struct zScene : xScene { _zPortal* pendingPortal; union { uint32 num_ents; uint32 num_base; }; union { xBase** base; zEnt** ents; }; uint32 num_update_base; xBase** update_base; uint32 baseCount[72]; xBase* baseList[72]; _zEnv* zen; }; struct _class_5 { xVec2 uv[2]; uint8 rows; uint8 cols; texture_mode mode; }; struct xBBox { xVec3 center; xBox box; }; struct anim_coll_data { }; enum RwFogType { rwFOGTYPENAFOGTYPE, rwFOGTYPELINEAR, rwFOGTYPEEXPONENTIAL, rwFOGTYPEEXPONENTIAL2, rwFOGTYPEFORCEENUMSIZEINT = 0x7fffffff }; struct iColor_tag { uint8 r; uint8 g; uint8 b; uint8 a; }; struct _class_6 { union { xClumpCollBSPVertInfo i; RwV3d* p; }; }; struct zLedgeGrabParams { float32 animGrab; float32 zdist; xVec3 tranTable[60]; int32 tranCount; xEnt* optr; xMat4x3 omat; float32 y0det; float32 dydet; float32 r0det; float32 drdet; float32 thdet; float32 rtime; float32 ttime; float32 tmr; xVec3 spos; xVec3 epos; xVec3 tpos; int32 nrays; int32 rrand; float32 startrot; float32 endrot; }; struct RwRGBAReal { float32 red; float32 green; float32 blue; float32 alpha; }; struct xPECircle { float32 radius; float32 deflection; xVec3 dir; }; struct zJumpParam { float32 PeakHeight; float32 TimeGravChange; float32 TimeHold; float32 ImpulseVel; }; struct xEntMotionOrbitData { xVec3 center; float32 w; float32 h; float32 period; }; struct RwLinkList { RwLLLink link; }; int8 buffer[16]; int8 buffer[16]; xMat4x3 g_I3; tagiRenderInput gRenderBuffer; zGlobals globals; uint32 gActiveHeap; void emit_decal_dist(effect_data& effect, bolt& b, float32 from_dist, float32 to_dist); void emit_decal(effect_data& effect, bolt& b, float32 to_dist); void emit_particle(effect_data& effect, bolt& b, float32 from_dist, float32 to_dist, float32 dt); void update_fx(bolt& b, float32 prev_dist, float32 dt); RxObjSpace3DVertex* render(bolt& b, RxObjSpace3DVertex* vert); void collide_update(bolt& b); void attach_effects(fx_when_enum when, effect_data* fx, uint32 fxsize); void render(); void update(float32 dt); void emit(xVec3& loc, xVec3& dir); void refresh_config(); void reset(); void set_texture(int8* name); void init(uint32 max_bolts); // emit_decal_dist__17xLaserBoltEmitterFRQ217xLaserBoltEmitter11effect_dataRQ217xLaserBoltEmitter4boltfff // Start address: 0x3b08d0 void emit_decal_dist(effect_data& effect, bolt& b, float32 from_dist, float32 to_dist) { float32 start_dist; int32 total; xMat4x3 mat; xVec3 dloc; int32 i; // Line 403, Address: 0x3b08d0, Func Offset: 0 // Line 408, Address: 0x3b08d4, Func Offset: 0x4 // Line 403, Address: 0x3b08d8, Func Offset: 0x8 // Line 409, Address: 0x3b08dc, Func Offset: 0xc // Line 403, Address: 0x3b08e0, Func Offset: 0x10 // Line 408, Address: 0x3b08f8, Func Offset: 0x28 // Line 403, Address: 0x3b08fc, Func Offset: 0x2c // Line 409, Address: 0x3b0914, Func Offset: 0x44 // Line 408, Address: 0x3b0918, Func Offset: 0x48 // Line 409, Address: 0x3b0920, Func Offset: 0x50 // Line 410, Address: 0x3b0928, Func Offset: 0x58 // Line 408, Address: 0x3b092c, Func Offset: 0x5c // Line 410, Address: 0x3b0930, Func Offset: 0x60 // Line 408, Address: 0x3b0934, Func Offset: 0x64 // Line 411, Address: 0x3b0938, Func Offset: 0x68 // Line 409, Address: 0x3b0940, Func Offset: 0x70 // Line 408, Address: 0x3b0944, Func Offset: 0x74 // Line 412, Address: 0x3b0948, Func Offset: 0x78 // Line 415, Address: 0x3b0950, Func Offset: 0x80 // Line 419, Address: 0x3b098c, Func Offset: 0xbc // Line 420, Address: 0x3b0990, Func Offset: 0xc0 // Line 421, Address: 0x3b0aec, Func Offset: 0x21c // Line 422, Address: 0x3b0af4, Func Offset: 0x224 // Line 423, Address: 0x3b0af8, Func Offset: 0x228 // Line 429, Address: 0x3b0c54, Func Offset: 0x384 // Line 431, Address: 0x3b0c58, Func Offset: 0x388 // Line 432, Address: 0x3b0c70, Func Offset: 0x3a0 // Line 431, Address: 0x3b0c74, Func Offset: 0x3a4 // Line 432, Address: 0x3b0c78, Func Offset: 0x3a8 // Line 433, Address: 0x3b0c90, Func Offset: 0x3c0 // Line 431, Address: 0x3b0c98, Func Offset: 0x3c8 // Line 432, Address: 0x3b0ce8, Func Offset: 0x418 // Line 433, Address: 0x3b0d98, Func Offset: 0x4c8 // Line 435, Address: 0x3b0dac, Func Offset: 0x4dc // Line 436, Address: 0x3b0dc0, Func Offset: 0x4f0 // Line 437, Address: 0x3b0dc8, Func Offset: 0x4f8 // Line 438, Address: 0x3b0e00, Func Offset: 0x530 // Func End, Address: 0x3b0e34, Func Offset: 0x564 } // emit_decal__17xLaserBoltEmitterFRQ217xLaserBoltEmitter11effect_dataRQ217xLaserBoltEmitter4boltfff // Start address: 0x3b0e40 void emit_decal(effect_data& effect, bolt& b, float32 to_dist) { xMat4x3 mat; // Line 378, Address: 0x3b0e40, Func Offset: 0 // Line 382, Address: 0x3b0e44, Func Offset: 0x4 // Line 378, Address: 0x3b0e48, Func Offset: 0x8 // Line 382, Address: 0x3b0e74, Func Offset: 0x34 // Line 387, Address: 0x3b0eb0, Func Offset: 0x70 // Line 388, Address: 0x3b100c, Func Offset: 0x1cc // Line 389, Address: 0x3b1014, Func Offset: 0x1d4 // Line 390, Address: 0x3b1018, Func Offset: 0x1d8 // Line 396, Address: 0x3b1174, Func Offset: 0x334 // Line 397, Address: 0x3b1178, Func Offset: 0x338 // Line 398, Address: 0x3b1194, Func Offset: 0x354 // Line 397, Address: 0x3b1198, Func Offset: 0x358 // Line 398, Address: 0x3b1248, Func Offset: 0x408 // Line 399, Address: 0x3b1254, Func Offset: 0x414 // Func End, Address: 0x3b1280, Func Offset: 0x440 } // emit_particle__17xLaserBoltEmitterFRQ217xLaserBoltEmitter11effect_dataRQ217xLaserBoltEmitter4boltfff // Start address: 0x3b1280 void emit_particle(effect_data& effect, bolt& b, float32 from_dist, float32 to_dist, float32 dt) { xParEmitter& pe; xParEmitterAsset& pea; float32 velmag; xVec3 oldloc; // Line 327, Address: 0x3b1280, Func Offset: 0 // Line 336, Address: 0x3b1284, Func Offset: 0x4 // Line 327, Address: 0x3b1288, Func Offset: 0x8 // Line 330, Address: 0x3b1294, Func Offset: 0x14 // Line 336, Address: 0x3b1298, Func Offset: 0x18 // Line 331, Address: 0x3b129c, Func Offset: 0x1c // Line 336, Address: 0x3b12a0, Func Offset: 0x20 // Line 339, Address: 0x3b12d0, Func Offset: 0x50 // Line 340, Address: 0x3b1338, Func Offset: 0xb8 // Line 342, Address: 0x3b1340, Func Offset: 0xc0 // Line 343, Address: 0x3b13ac, Func Offset: 0x12c // Line 344, Address: 0x3b13b4, Func Offset: 0x134 // Line 346, Address: 0x3b13b8, Func Offset: 0x138 // Line 355, Address: 0x3b1424, Func Offset: 0x1a4 // Line 358, Address: 0x3b1428, Func Offset: 0x1a8 // Line 360, Address: 0x3b1438, Func Offset: 0x1b8 // Line 361, Address: 0x3b1454, Func Offset: 0x1d4 // Line 360, Address: 0x3b1464, Func Offset: 0x1e4 // Line 362, Address: 0x3b149c, Func Offset: 0x21c // Line 360, Address: 0x3b14a0, Func Offset: 0x220 // Line 361, Address: 0x3b1518, Func Offset: 0x298 // Line 362, Address: 0x3b155c, Func Offset: 0x2dc // Line 361, Address: 0x3b1560, Func Offset: 0x2e0 // Line 362, Address: 0x3b15d4, Func Offset: 0x354 // Line 363, Address: 0x3b15dc, Func Offset: 0x35c // Line 366, Address: 0x3b15e8, Func Offset: 0x368 // Line 367, Address: 0x3b15f0, Func Offset: 0x370 // Line 366, Address: 0x3b15f4, Func Offset: 0x374 // Line 367, Address: 0x3b15f8, Func Offset: 0x378 // Line 366, Address: 0x3b15fc, Func Offset: 0x37c // Line 367, Address: 0x3b1600, Func Offset: 0x380 // Line 368, Address: 0x3b1608, Func Offset: 0x388 // Line 366, Address: 0x3b160c, Func Offset: 0x38c // Line 367, Address: 0x3b1618, Func Offset: 0x398 // Line 368, Address: 0x3b165c, Func Offset: 0x3dc // Line 367, Address: 0x3b1660, Func Offset: 0x3e0 // Line 368, Address: 0x3b16ec, Func Offset: 0x46c // Line 369, Address: 0x3b16f4, Func Offset: 0x474 // Line 370, Address: 0x3b170c, Func Offset: 0x48c // Line 373, Address: 0x3b1710, Func Offset: 0x490 // Line 374, Address: 0x3b1714, Func Offset: 0x494 // Func End, Address: 0x3b1728, Func Offset: 0x4a8 } // update_fx__17xLaserBoltEmitterFRQ217xLaserBoltEmitter4boltff // Start address: 0x3b1730 void xLaserBoltEmitter::update_fx(bolt& b, float32 prev_dist, float32 dt) { float32 tail_dist; effect_data* itfx; effect_data* endfx; effect_data* itfx; effect_data* endfx; float32 from_dist; float32 to_dist; effect_data* itfx; effect_data* endfx; effect_data* itfx; effect_data* endfx; // Line 297, Address: 0x3b1730, Func Offset: 0 // Line 300, Address: 0x3b1770, Func Offset: 0x40 // Line 302, Address: 0x3b177c, Func Offset: 0x4c // Line 303, Address: 0x3b1794, Func Offset: 0x64 // Line 304, Address: 0x3b186c, Func Offset: 0x13c // Line 305, Address: 0x3b1878, Func Offset: 0x148 // Line 307, Address: 0x3b1888, Func Offset: 0x158 // Line 308, Address: 0x3b188c, Func Offset: 0x15c // Line 307, Address: 0x3b1890, Func Offset: 0x160 // Line 309, Address: 0x3b1894, Func Offset: 0x164 // Line 307, Address: 0x3b1898, Func Offset: 0x168 // Line 309, Address: 0x3b18a4, Func Offset: 0x174 // Line 310, Address: 0x3b18b0, Func Offset: 0x180 // Line 313, Address: 0x3b198c, Func Offset: 0x25c // Line 315, Address: 0x3b199c, Func Offset: 0x26c // Line 316, Address: 0x3b19b4, Func Offset: 0x284 // Line 317, Address: 0x3b1a74, Func Offset: 0x344 // Line 318, Address: 0x3b1a80, Func Offset: 0x350 // Line 320, Address: 0x3b1a8c, Func Offset: 0x35c // Line 321, Address: 0x3b1aa4, Func Offset: 0x374 // Line 322, Address: 0x3b1b64, Func Offset: 0x434 // Line 323, Address: 0x3b1b68, Func Offset: 0x438 // Func End, Address: 0x3b1b94, Func Offset: 0x464 } // render__17xLaserBoltEmitterFRQ217xLaserBoltEmitter4boltP18RxObjSpace3DVertex // Start address: 0x3b1ba0 RxObjSpace3DVertex* xLaserBoltEmitter::render(bolt& b, RxObjSpace3DVertex* vert) { float32 dist0; xVec3 loc0; xVec3 loc1; xMat4x3& cam_mat; xVec3 dir; xVec3 right; xVec3 half_right; // Line 242, Address: 0x3b1ba0, Func Offset: 0 // Line 245, Address: 0x3b1ba8, Func Offset: 0x8 // Line 242, Address: 0x3b1bac, Func Offset: 0xc // Line 244, Address: 0x3b1bcc, Func Offset: 0x2c // Line 245, Address: 0x3b1bd8, Func Offset: 0x38 // Line 246, Address: 0x3b1bf0, Func Offset: 0x50 // Line 247, Address: 0x3b1c08, Func Offset: 0x68 // Line 253, Address: 0x3b1c20, Func Offset: 0x80 // Line 250, Address: 0x3b1c24, Func Offset: 0x84 // Line 252, Address: 0x3b1c28, Func Offset: 0x88 // Line 250, Address: 0x3b1c2c, Func Offset: 0x8c // Line 253, Address: 0x3b1c3c, Func Offset: 0x9c // Line 250, Address: 0x3b1c40, Func Offset: 0xa0 // Line 251, Address: 0x3b1c48, Func Offset: 0xa8 // Line 253, Address: 0x3b1c58, Func Offset: 0xb8 // Line 250, Address: 0x3b1c64, Func Offset: 0xc4 // Line 254, Address: 0x3b1c68, Func Offset: 0xc8 // Line 250, Address: 0x3b1c6c, Func Offset: 0xcc // Line 252, Address: 0x3b1c70, Func Offset: 0xd0 // Line 250, Address: 0x3b1c74, Func Offset: 0xd4 // Line 254, Address: 0x3b1c78, Func Offset: 0xd8 // Line 250, Address: 0x3b1c7c, Func Offset: 0xdc // Line 251, Address: 0x3b1d08, Func Offset: 0x168 // Line 253, Address: 0x3b1dac, Func Offset: 0x20c // Line 254, Address: 0x3b1e50, Func Offset: 0x2b0 // Line 256, Address: 0x3b1e74, Func Offset: 0x2d4 // Line 254, Address: 0x3b1e78, Func Offset: 0x2d8 // Line 256, Address: 0x3b1e7c, Func Offset: 0x2dc // Line 254, Address: 0x3b1e80, Func Offset: 0x2e0 // Line 256, Address: 0x3b1e94, Func Offset: 0x2f4 // Line 254, Address: 0x3b1e98, Func Offset: 0x2f8 // Line 255, Address: 0x3b1ee0, Func Offset: 0x340 // Line 254, Address: 0x3b1ee4, Func Offset: 0x344 // Line 255, Address: 0x3b1ee8, Func Offset: 0x348 // Line 256, Address: 0x3b1ef8, Func Offset: 0x358 // Line 257, Address: 0x3b1f30, Func Offset: 0x390 // Line 258, Address: 0x3b1f68, Func Offset: 0x3c8 // Line 261, Address: 0x3b1fd0, Func Offset: 0x430 // Line 265, Address: 0x3b2040, Func Offset: 0x4a0 // Line 261, Address: 0x3b2044, Func Offset: 0x4a4 // Line 265, Address: 0x3b2048, Func Offset: 0x4a8 // Line 266, Address: 0x3b211c, Func Offset: 0x57c // Line 267, Address: 0x3b2120, Func Offset: 0x580 // Func End, Address: 0x3b2148, Func Offset: 0x5a8 } // collide_update__17xLaserBoltEmitterFRQ217xLaserBoltEmitter4bolt // Start address: 0x3b2200 void xLaserBoltEmitter::collide_update(bolt& b) { xScene& scene; xRay3 ray; xCollis player_coll; xCollis scene_coll; // Line 200, Address: 0x3b2200, Func Offset: 0 // Line 201, Address: 0x3b2204, Func Offset: 0x4 // Line 200, Address: 0x3b2208, Func Offset: 0x8 // Line 205, Address: 0x3b220c, Func Offset: 0xc // Line 200, Address: 0x3b2210, Func Offset: 0x10 // Line 208, Address: 0x3b2214, Func Offset: 0x14 // Line 200, Address: 0x3b2218, Func Offset: 0x18 // Line 204, Address: 0x3b2220, Func Offset: 0x20 // Line 201, Address: 0x3b2224, Func Offset: 0x24 // Line 206, Address: 0x3b2228, Func Offset: 0x28 // Line 204, Address: 0x3b222c, Func Offset: 0x2c // Line 205, Address: 0x3b2240, Func Offset: 0x40 // Line 206, Address: 0x3b2258, Func Offset: 0x58 // Line 207, Address: 0x3b2268, Func Offset: 0x68 // Line 208, Address: 0x3b2270, Func Offset: 0x70 // Line 209, Address: 0x3b2278, Func Offset: 0x78 // Line 213, Address: 0x3b2290, Func Offset: 0x90 // Line 214, Address: 0x3b2294, Func Offset: 0x94 // Line 213, Address: 0x3b2298, Func Offset: 0x98 // Line 214, Address: 0x3b229c, Func Offset: 0x9c // Line 216, Address: 0x3b22ac, Func Offset: 0xac // Line 219, Address: 0x3b22c8, Func Offset: 0xc8 // Line 220, Address: 0x3b22cc, Func Offset: 0xcc // Line 219, Address: 0x3b22d4, Func Offset: 0xd4 // Line 220, Address: 0x3b22d8, Func Offset: 0xd8 // Line 223, Address: 0x3b22e8, Func Offset: 0xe8 // Line 225, Address: 0x3b22f8, Func Offset: 0xf8 // Line 226, Address: 0x3b2300, Func Offset: 0x100 // Line 227, Address: 0x3b2318, Func Offset: 0x118 // Line 228, Address: 0x3b231c, Func Offset: 0x11c // Line 229, Address: 0x3b2328, Func Offset: 0x128 // Line 231, Address: 0x3b2338, Func Offset: 0x138 // Line 233, Address: 0x3b233c, Func Offset: 0x13c // Line 231, Address: 0x3b2344, Func Offset: 0x144 // Line 232, Address: 0x3b2348, Func Offset: 0x148 // Line 233, Address: 0x3b2360, Func Offset: 0x160 // Line 234, Address: 0x3b2364, Func Offset: 0x164 // Line 236, Address: 0x3b2368, Func Offset: 0x168 // Line 239, Address: 0x3b2370, Func Offset: 0x170 // Func End, Address: 0x3b2388, Func Offset: 0x188 } // attach_effects__17xLaserBoltEmitterFQ217xLaserBoltEmitter12fx_when_enumPQ217xLaserBoltEmitter11effect_dataUi // Start address: 0x3b2390 void xLaserBoltEmitter::attach_effects(fx_when_enum when, effect_data* fx, uint32 fxsize) { // Line 167, Address: 0x3b2398, Func Offset: 0x8 // Line 168, Address: 0x3b239c, Func Offset: 0xc // Line 169, Address: 0x3b23a0, Func Offset: 0x10 // Line 171, Address: 0x3b2408, Func Offset: 0x78 // Func End, Address: 0x3b2410, Func Offset: 0x80 } // render__17xLaserBoltEmitterFv // Start address: 0x3b2410 void xLaserBoltEmitter::render() { RxObjSpace3DVertex* verts; RxObjSpace3DVertex* v; iterator it; int32 used; // Line 139, Address: 0x3b2410, Func Offset: 0 // Line 144, Address: 0x3b2414, Func Offset: 0x4 // Line 139, Address: 0x3b2418, Func Offset: 0x8 // Line 150, Address: 0x3b242c, Func Offset: 0x1c // Line 139, Address: 0x3b2430, Func Offset: 0x20 // Line 144, Address: 0x3b2438, Func Offset: 0x28 // Line 150, Address: 0x3b243c, Func Offset: 0x2c // Line 151, Address: 0x3b2448, Func Offset: 0x38 // Line 156, Address: 0x3b2458, Func Offset: 0x48 // Line 151, Address: 0x3b2464, Func Offset: 0x54 // Line 156, Address: 0x3b2474, Func Offset: 0x64 // Line 153, Address: 0x3b24a8, Func Offset: 0x98 // Line 156, Address: 0x3b24ac, Func Offset: 0x9c // Line 153, Address: 0x3b24b0, Func Offset: 0xa0 // Line 154, Address: 0x3b24bc, Func Offset: 0xac // Line 153, Address: 0x3b24c0, Func Offset: 0xb0 // Line 156, Address: 0x3b24c8, Func Offset: 0xb8 // Line 154, Address: 0x3b24dc, Func Offset: 0xcc // Line 156, Address: 0x3b24e0, Func Offset: 0xd0 // Line 154, Address: 0x3b24f8, Func Offset: 0xe8 // Line 156, Address: 0x3b2500, Func Offset: 0xf0 // Line 155, Address: 0x3b2508, Func Offset: 0xf8 // Line 156, Address: 0x3b2510, Func Offset: 0x100 // Line 155, Address: 0x3b2514, Func Offset: 0x104 // Line 156, Address: 0x3b2518, Func Offset: 0x108 // Line 155, Address: 0x3b251c, Func Offset: 0x10c // Line 156, Address: 0x3b2520, Func Offset: 0x110 // Line 155, Address: 0x3b2524, Func Offset: 0x114 // Line 156, Address: 0x3b2528, Func Offset: 0x118 // Line 157, Address: 0x3b2588, Func Offset: 0x178 // Line 160, Address: 0x3b2590, Func Offset: 0x180 // Line 163, Address: 0x3b25d0, Func Offset: 0x1c0 // Func End, Address: 0x3b25f0, Func Offset: 0x1e0 } // update__17xLaserBoltEmitterFf // Start address: 0x3b25f0 void xLaserBoltEmitter::update(float32 dt) { int32 ci; iterator it; bolt& b; uint8 collided; float32 prev_dist; effect_data* itfx; effect_data* endfx; effect_data* itfx; effect_data* endfx; // Line 85, Address: 0x3b25f0, Func Offset: 0 // Line 89, Address: 0x3b2628, Func Offset: 0x38 // Line 90, Address: 0x3b2654, Func Offset: 0x64 // Line 133, Address: 0x3b2664, Func Offset: 0x74 // Line 90, Address: 0x3b2670, Func Offset: 0x80 // Line 133, Address: 0x3b2680, Func Offset: 0x90 // Line 92, Address: 0x3b26c4, Func Offset: 0xd4 // Line 133, Address: 0x3b26c8, Func Offset: 0xd8 // Line 92, Address: 0x3b26cc, Func Offset: 0xdc // Line 133, Address: 0x3b26d0, Func Offset: 0xe0 // Line 92, Address: 0x3b26d4, Func Offset: 0xe4 // Line 133, Address: 0x3b26d8, Func Offset: 0xe8 // Line 93, Address: 0x3b26e8, Func Offset: 0xf8 // Line 133, Address: 0x3b26f8, Func Offset: 0x108 // Line 96, Address: 0x3b2708, Func Offset: 0x118 // Line 133, Address: 0x3b2710, Func Offset: 0x120 // Line 98, Address: 0x3b271c, Func Offset: 0x12c // Line 133, Address: 0x3b2720, Func Offset: 0x130 // Line 98, Address: 0x3b2728, Func Offset: 0x138 // Line 133, Address: 0x3b2734, Func Offset: 0x144 // Line 99, Address: 0x3b2760, Func Offset: 0x170 // Line 133, Address: 0x3b2764, Func Offset: 0x174 // Line 99, Address: 0x3b276c, Func Offset: 0x17c // Line 133, Address: 0x3b2770, Func Offset: 0x180 // Line 99, Address: 0x3b2778, Func Offset: 0x188 // Line 133, Address: 0x3b277c, Func Offset: 0x18c // Line 99, Address: 0x3b27b4, Func Offset: 0x1c4 // Line 133, Address: 0x3b27b8, Func Offset: 0x1c8 // Line 99, Address: 0x3b27c8, Func Offset: 0x1d8 // Line 133, Address: 0x3b27cc, Func Offset: 0x1dc // Line 99, Address: 0x3b27e4, Func Offset: 0x1f4 // Line 133, Address: 0x3b27e8, Func Offset: 0x1f8 // Line 101, Address: 0x3b2828, Func Offset: 0x238 // Line 133, Address: 0x3b282c, Func Offset: 0x23c // Line 103, Address: 0x3b283c, Func Offset: 0x24c // Line 133, Address: 0x3b2840, Func Offset: 0x250 // Line 103, Address: 0x3b2844, Func Offset: 0x254 // Line 133, Address: 0x3b2848, Func Offset: 0x258 // Line 104, Address: 0x3b2854, Func Offset: 0x264 // Line 133, Address: 0x3b2858, Func Offset: 0x268 // Line 105, Address: 0x3b285c, Func Offset: 0x26c // Line 133, Address: 0x3b2860, Func Offset: 0x270 // Line 105, Address: 0x3b2868, Func Offset: 0x278 // Line 133, Address: 0x3b286c, Func Offset: 0x27c // Line 105, Address: 0x3b2884, Func Offset: 0x294 // Line 133, Address: 0x3b28a0, Func Offset: 0x2b0 // Line 105, Address: 0x3b28a8, Func Offset: 0x2b8 // Line 133, Address: 0x3b28c0, Func Offset: 0x2d0 // Line 105, Address: 0x3b28c8, Func Offset: 0x2d8 // Line 133, Address: 0x3b28e0, Func Offset: 0x2f0 // Line 105, Address: 0x3b28e8, Func Offset: 0x2f8 // Line 133, Address: 0x3b28f0, Func Offset: 0x300 // Line 106, Address: 0x3b2918, Func Offset: 0x328 // Line 133, Address: 0x3b291c, Func Offset: 0x32c // Line 106, Address: 0x3b2970, Func Offset: 0x380 // Line 133, Address: 0x3b2978, Func Offset: 0x388 // Line 107, Address: 0x3b298c, Func Offset: 0x39c // Line 108, Address: 0x3b2994, Func Offset: 0x3a4 // Line 110, Address: 0x3b2998, Func Offset: 0x3a8 // Line 133, Address: 0x3b29a0, Func Offset: 0x3b0 // Line 112, Address: 0x3b29b0, Func Offset: 0x3c0 // Line 133, Address: 0x3b29b4, Func Offset: 0x3c4 // Line 114, Address: 0x3b29cc, Func Offset: 0x3dc // Line 133, Address: 0x3b29d0, Func Offset: 0x3e0 // Line 114, Address: 0x3b29dc, Func Offset: 0x3ec // Line 133, Address: 0x3b29e4, Func Offset: 0x3f4 // Line 114, Address: 0x3b29f0, Func Offset: 0x400 // Line 133, Address: 0x3b29fc, Func Offset: 0x40c // Line 114, Address: 0x3b2a0c, Func Offset: 0x41c // Line 133, Address: 0x3b2a1c, Func Offset: 0x42c // Line 114, Address: 0x3b2a20, Func Offset: 0x430 // Line 133, Address: 0x3b2a2c, Func Offset: 0x43c // Line 114, Address: 0x3b2a34, Func Offset: 0x444 // Line 133, Address: 0x3b2a38, Func Offset: 0x448 // Line 116, Address: 0x3b2a3c, Func Offset: 0x44c // Line 133, Address: 0x3b2a40, Func Offset: 0x450 // Line 123, Address: 0x3b2a5c, Func Offset: 0x46c // Line 133, Address: 0x3b2a60, Func Offset: 0x470 // Line 123, Address: 0x3b2a6c, Func Offset: 0x47c // Line 133, Address: 0x3b2a70, Func Offset: 0x480 // Line 127, Address: 0x3b2a90, Func Offset: 0x4a0 // Line 133, Address: 0x3b2a94, Func Offset: 0x4a4 // Line 129, Address: 0x3b2aa4, Func Offset: 0x4b4 // Line 133, Address: 0x3b2aa8, Func Offset: 0x4b8 // Line 129, Address: 0x3b2aac, Func Offset: 0x4bc // Line 133, Address: 0x3b2ab0, Func Offset: 0x4c0 // Line 130, Address: 0x3b2abc, Func Offset: 0x4cc // Line 133, Address: 0x3b2ac0, Func Offset: 0x4d0 // Line 131, Address: 0x3b2ac4, Func Offset: 0x4d4 // Line 133, Address: 0x3b2ac8, Func Offset: 0x4d8 // Line 131, Address: 0x3b2ad0, Func Offset: 0x4e0 // Line 133, Address: 0x3b2ad4, Func Offset: 0x4e4 // Line 131, Address: 0x3b2aec, Func Offset: 0x4fc // Line 133, Address: 0x3b2b08, Func Offset: 0x518 // Line 131, Address: 0x3b2b10, Func Offset: 0x520 // Line 133, Address: 0x3b2b28, Func Offset: 0x538 // Line 131, Address: 0x3b2b30, Func Offset: 0x540 // Line 133, Address: 0x3b2b48, Func Offset: 0x558 // Line 131, Address: 0x3b2b50, Func Offset: 0x560 // Line 133, Address: 0x3b2b58, Func Offset: 0x568 // Line 135, Address: 0x3b2bd0, Func Offset: 0x5e0 // Line 136, Address: 0x3b2bdc, Func Offset: 0x5ec // Func End, Address: 0x3b2c10, Func Offset: 0x620 } // emit__17xLaserBoltEmitterFRC5xVec3RC5xVec3 // Start address: 0x3b2c10 void xLaserBoltEmitter::emit(xVec3& loc, xVec3& dir) { bolt& b; effect_data* itfx; effect_data* endfx; // Line 63, Address: 0x3b2c10, Func Offset: 0 // Line 64, Address: 0x3b2c2c, Func Offset: 0x1c // Line 65, Address: 0x3b2c50, Func Offset: 0x40 // Line 68, Address: 0x3b2c60, Func Offset: 0x50 // Line 65, Address: 0x3b2c64, Func Offset: 0x54 // Line 66, Address: 0x3b2c98, Func Offset: 0x88 // Line 65, Address: 0x3b2c9c, Func Offset: 0x8c // Line 66, Address: 0x3b2cbc, Func Offset: 0xac // Line 67, Address: 0x3b2ce8, Func Offset: 0xd8 // Line 68, Address: 0x3b2d00, Func Offset: 0xf0 // Line 69, Address: 0x3b2d0c, Func Offset: 0xfc // Line 70, Address: 0x3b2d14, Func Offset: 0x104 // Line 71, Address: 0x3b2d18, Func Offset: 0x108 // Line 72, Address: 0x3b2d1c, Func Offset: 0x10c // Line 73, Address: 0x3b2d24, Func Offset: 0x114 // Line 74, Address: 0x3b2dc0, Func Offset: 0x1b0 // Line 77, Address: 0x3b2e70, Func Offset: 0x260 // Line 80, Address: 0x3b2e7c, Func Offset: 0x26c // Line 81, Address: 0x3b2e94, Func Offset: 0x284 // Line 82, Address: 0x3b2f88, Func Offset: 0x378 // Func End, Address: 0x3b2fa8, Func Offset: 0x398 } // refresh_config__17xLaserBoltEmitterFv // Start address: 0x3b2fb0 void xLaserBoltEmitter::refresh_config() { // Line 57, Address: 0x3b2fb0, Func Offset: 0 // Line 58, Address: 0x3b2fb8, Func Offset: 0x8 // Line 60, Address: 0x3b2fe8, Func Offset: 0x38 // Func End, Address: 0x3b2ff0, Func Offset: 0x40 } // reset__17xLaserBoltEmitterFv // Start address: 0x3b2ff0 void xLaserBoltEmitter::reset() { iterator it; bolt& b; effect_data* itfx; effect_data* endfx; int32 i; // Line 41, Address: 0x3b2ff0, Func Offset: 0 // Line 42, Address: 0x3b2ff8, Func Offset: 0x8 // Line 41, Address: 0x3b2ffc, Func Offset: 0xc // Line 42, Address: 0x3b3000, Func Offset: 0x10 // Line 41, Address: 0x3b3004, Func Offset: 0x14 // Line 42, Address: 0x3b3010, Func Offset: 0x20 // Line 41, Address: 0x3b3014, Func Offset: 0x24 // Line 48, Address: 0x3b3018, Func Offset: 0x28 // Line 41, Address: 0x3b301c, Func Offset: 0x2c // Line 48, Address: 0x3b3020, Func Offset: 0x30 // Line 41, Address: 0x3b3024, Func Offset: 0x34 // Line 42, Address: 0x3b3028, Func Offset: 0x38 // Line 48, Address: 0x3b302c, Func Offset: 0x3c // Line 42, Address: 0x3b3030, Func Offset: 0x40 // Line 48, Address: 0x3b3040, Func Offset: 0x50 // Line 44, Address: 0x3b307c, Func Offset: 0x8c // Line 48, Address: 0x3b3080, Func Offset: 0x90 // Line 44, Address: 0x3b308c, Func Offset: 0x9c // Line 48, Address: 0x3b3090, Func Offset: 0xa0 // Line 44, Address: 0x3b3094, Func Offset: 0xa4 // Line 48, Address: 0x3b3098, Func Offset: 0xa8 // Line 45, Address: 0x3b309c, Func Offset: 0xac // Line 48, Address: 0x3b30a0, Func Offset: 0xb0 // Line 45, Address: 0x3b30a4, Func Offset: 0xb4 // Line 48, Address: 0x3b30a8, Func Offset: 0xb8 // Line 46, Address: 0x3b30b4, Func Offset: 0xc4 // Line 48, Address: 0x3b30b8, Func Offset: 0xc8 // Line 47, Address: 0x3b30bc, Func Offset: 0xcc // Line 48, Address: 0x3b30c0, Func Offset: 0xd0 // Line 47, Address: 0x3b30c8, Func Offset: 0xd8 // Line 48, Address: 0x3b30cc, Func Offset: 0xdc // Line 47, Address: 0x3b30e4, Func Offset: 0xf4 // Line 48, Address: 0x3b3108, Func Offset: 0x118 // Line 47, Address: 0x3b3110, Func Offset: 0x120 // Line 48, Address: 0x3b3130, Func Offset: 0x140 // Line 47, Address: 0x3b3138, Func Offset: 0x148 // Line 48, Address: 0x3b3158, Func Offset: 0x168 // Line 47, Address: 0x3b3160, Func Offset: 0x170 // Line 48, Address: 0x3b3168, Func Offset: 0x178 // Line 50, Address: 0x3b31e0, Func Offset: 0x1f0 // Line 52, Address: 0x3b31e8, Func Offset: 0x1f8 // Line 51, Address: 0x3b31ec, Func Offset: 0x1fc // Line 53, Address: 0x3b31f0, Func Offset: 0x200 // Line 52, Address: 0x3b31fc, Func Offset: 0x20c // Line 53, Address: 0x3b3200, Func Offset: 0x210 // Line 54, Address: 0x3b3270, Func Offset: 0x280 // Func End, Address: 0x3b3294, Func Offset: 0x2a4 } // set_texture__17xLaserBoltEmitterFPCc // Start address: 0x3b32a0 void xLaserBoltEmitter::set_texture(int8* name) { // Line 24, Address: 0x3b32a0, Func Offset: 0 // Func End, Address: 0x3b32f0, Func Offset: 0x50 } // init__17xLaserBoltEmitterFUiPCc // Start address: 0x3b32f0 void xLaserBoltEmitter::init(uint32 max_bolts) { // Line 16, Address: 0x3b32f0, Func Offset: 0 // Line 18, Address: 0x3b32f4, Func Offset: 0x4 // Line 16, Address: 0x3b32f8, Func Offset: 0x8 // Line 17, Address: 0x3b3308, Func Offset: 0x18 // Line 18, Address: 0x3b3310, Func Offset: 0x20 // Line 19, Address: 0x3b331c, Func Offset: 0x2c // Line 21, Address: 0x3b3390, Func Offset: 0xa0 // Func End, Address: 0x3b33a4, Func Offset: 0xb4 }
76,927
38,181
#include "createBoundingBox.h" #include <Inventor/So.h> /////////////////////////////////////////////////////////////////////////////// // SoSeparator * drawLine(SbVec3f pointS, SbVec3f pointE, SbVec3f color, float thickness, bool ticker, bool text, int dir) // /////////////////////////////////////////////////////////////////////////////// { SoSeparator * aSep = new SoSeparator; SoCylinder * aCylinder = new SoCylinder; aCylinder->radius = thickness; aCylinder->height = (pointS-pointE).length(); SoMaterial *aMtl = new SoMaterial; aMtl->ambientColor.setValue(0.8,0.8,0.8); aMtl->diffuseColor.setValue(0.8,0.8,0.8); aMtl->specularColor.setValue(0.5,0.5,0.5); aMtl->shininess = 0.9; aMtl->transparency = 0.0; SoTransform * xTrans = new SoTransform; if(dir==1) xTrans->rotation.setValue(SbVec3f(0, 0, 1), M_PI_2); else if(dir == 2) xTrans->rotation.setValue(SbVec3f(0, 1, 0), M_PI_2); else if(dir == 3) xTrans->rotation.setValue(SbVec3f(1, 0, 0), M_PI_2); xTrans->translation.setValue((pointE+pointS)/2); aSep->addChild(xTrans); aSep->addChild(aMtl); aSep->addChild(aCylinder); return aSep; } /////////////////////////////////////////////////////////////////////////////// // SoSeparator * createBoundingBox() // /////////////////////////////////////////////////////////////////////////////// { SbVec3f pointS, pointE, color; float thickness = 0.003; float xMin, yMin, zMin, xMax, yMax, zMax; xMin = yMin = zMin = -1; xMax = yMax = zMax = 1; SoSeparator *bdBoxSep = new SoSeparator; bdBoxSep->setName("bdBox"); color.setValue(1,1,1); pointS.setValue(xMin,yMin,zMin); pointE.setValue(xMax, yMin, zMin); bdBoxSep->addChild(drawLine(pointS, pointE, color, thickness, false, false, 1)); pointS.setValue(xMin, yMax, zMin); pointE.setValue(xMax, yMax, zMin); bdBoxSep->addChild(drawLine(pointS, pointE, color, thickness, false, false, 1)); pointS.setValue(xMin, yMax, zMax); pointE.setValue(xMax, yMax, zMax); bdBoxSep->addChild(drawLine(pointS, pointE, color, thickness, false, false, 1)); pointS.setValue(xMin, yMin, zMax); pointE.setValue(xMax, yMin, zMax); bdBoxSep->addChild(drawLine(pointS, pointE, color, thickness, false, false, 1)); pointS.setValue(xMin, yMin, zMin); pointE.setValue(xMin, yMin, zMax); bdBoxSep->addChild(drawLine(pointS, pointE, color, thickness, false, false, 3)); pointS.setValue(xMax, yMin, zMin); pointE.setValue(xMax, yMin, zMax); bdBoxSep->addChild(drawLine(pointS, pointE, color, thickness, false, false, 3)); pointS.setValue(xMax, yMax, zMin); pointE.setValue(xMax, yMax, zMax); bdBoxSep->addChild(drawLine(pointS, pointE, color, thickness, false, false, 3)); pointS.setValue(xMin, yMax, zMin); pointE.setValue(xMin, yMax, zMax); bdBoxSep->addChild(drawLine(pointS, pointE, color, thickness, false, false, 3)); pointS.setValue(xMin, yMin, zMin); pointE.setValue(xMin, yMax, zMin); bdBoxSep->addChild(drawLine(pointS, pointE, color, thickness, false, false, 2)); pointS.setValue(xMax, yMin, zMin); pointE.setValue(xMax, yMax, zMin); bdBoxSep->addChild(drawLine(pointS, pointE, color, thickness, false, false, 2)); pointS.setValue(xMax, yMin, zMax); pointE.setValue(xMax, yMax, zMax); bdBoxSep->addChild(drawLine(pointS, pointE, color, thickness, false, false, 2)); pointS.setValue(xMin, yMin, zMax); pointE.setValue(xMin, yMax, zMax); bdBoxSep->addChild(drawLine(pointS, pointE, color, thickness, false, false, 2)); return bdBoxSep; }
3,669
1,453
/* Sưu tầm bởi @nguyenvanhieuvn Thực hành nhiều bài tập hơn tại https://luyencode.net/ */ void Xuat(LIST l) { for(NODE* p = l.pHead; p != NULL; p = p->pNext) { printf("%4d", p->info); } }
212
114
// Copyright 2017 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. #include <vespa/searchcore/proton/server/i_blockable_maintenance_job.h> #include <vespa/searchcore/proton/server/move_operation_limiter.h> #include <vespa/vespalib/testkit/testapp.h> #include <queue> #include <vespa/log/log.h> LOG_SETUP("move_operation_limiter_test"); using namespace proton; struct MyBlockableMaintenanceJob : public IBlockableMaintenanceJob { bool blocked; MyBlockableMaintenanceJob() : IBlockableMaintenanceJob("my_job", 1s, 1s), blocked(false) {} void setBlocked(BlockedReason reason) override { ASSERT_TRUE(reason == BlockedReason::OUTSTANDING_OPS); EXPECT_FALSE(blocked); blocked = true; } void unBlock(BlockedReason reason) override { ASSERT_TRUE(reason == BlockedReason::OUTSTANDING_OPS); EXPECT_TRUE(blocked); blocked = false; } bool run() override { return true; } void onStop() override { } }; struct Fixture { using OpsQueue = std::queue<std::shared_ptr<vespalib::IDestructorCallback>>; using MoveOperationLimiterSP = std::shared_ptr<MoveOperationLimiter>; MyBlockableMaintenanceJob job; MoveOperationLimiterSP limiter; OpsQueue ops; Fixture(uint32_t maxOutstandingOps = 2) : job(), limiter(std::make_shared<MoveOperationLimiter>(&job, maxOutstandingOps)), ops() {} void beginOp() { ops.push(limiter->beginOperation()); } void endOp() { ops.pop(); } void clearJob() { limiter->clearJob(); } void clearLimiter() { limiter = MoveOperationLimiterSP(); } void assertAboveLimit() const { EXPECT_TRUE(limiter->isAboveLimit()); EXPECT_TRUE(job.blocked); } void assertBelowLimit() const { EXPECT_FALSE(limiter->isAboveLimit()); EXPECT_FALSE(job.blocked); } }; TEST_F("require that hasPending reflects if any jobs are outstanding", Fixture) { EXPECT_FALSE(f.limiter->hasPending()); f.beginOp(); EXPECT_TRUE(f.limiter->hasPending()); f.endOp(); EXPECT_FALSE(f.limiter->hasPending()); } TEST_F("require that job is blocked / unblocked when crossing max outstanding ops boundaries", Fixture) { f.beginOp(); TEST_DO(f.assertBelowLimit()); f.beginOp(); TEST_DO(f.assertAboveLimit()); f.beginOp(); TEST_DO(f.assertAboveLimit()); f.endOp(); TEST_DO(f.assertAboveLimit()); f.endOp(); TEST_DO(f.assertBelowLimit()); f.endOp(); TEST_DO(f.assertBelowLimit()); } TEST_F("require that cleared job is not blocked when crossing max ops boundary", Fixture) { f.beginOp(); f.clearJob(); f.beginOp(); EXPECT_FALSE(f.job.blocked); EXPECT_TRUE(f.limiter->isAboveLimit()); } TEST_F("require that cleared job is not unblocked when crossing max ops boundary", Fixture) { f.beginOp(); f.beginOp(); TEST_DO(f.assertAboveLimit()); f.clearJob(); f.endOp(); EXPECT_TRUE(f.job.blocked); EXPECT_FALSE(f.limiter->isAboveLimit()); } TEST_F("require that destructor callback has reference to limiter via shared ptr", Fixture) { f.beginOp(); f.beginOp(); TEST_DO(f.assertAboveLimit()); f.clearLimiter(); f.endOp(); EXPECT_FALSE(f.job.blocked); } TEST_MAIN() { TEST_RUN_ALL(); }
3,361
1,194
#include "test.h" #include <inner/type_traits.h> class A {}; enum E : unsigned {}; enum class Ec : unsigned {}; enum Ecs : signed int {}; int main() { assert(is_unsigned_v<A> == false); assert(is_unsigned_v<float> == false); assert(is_unsigned_v<signed int> == false); assert(is_unsigned_v<unsigned int> == true); assert(is_unsigned_v<E> == false); assert(is_unsigned_v<Ec> == false); assert(is_unsigned_v<Ecs> == false); return 0; }
489
181
#pragma once #include <SDL2/SDL.h> #include <SDL2/SDL_image.h> #include "entity.hpp" class Graphic { public: Graphic(const char* title, const int& SCREEN_WIDTH, const int& SCREEN_HEIGHT); SDL_Texture* loadTexture(const char* p_filePath); void cleanUp(); //Destroy window and renderer memory void clear(); //RenderClear void render(Entity& p_entity); void display(); //RenderPresent private: SDL_Window* window; SDL_Renderer* renderer; };
587
176
// This file is part of MLDB. Copyright 2015 mldb.ai inc. All rights reserved. /* rest_collection_test.cc Jeremy Barnes, 25 March 2014 Copyright (c) 2014 mldb.ai inc. All rights reserved. */ #include "mldb/utils/runner.h" #include "mldb/utils/vector_utils.h" #include "mldb/rest/rest_collection.h" #include "mldb/rest/rest_collection_impl.h" #include "mldb/types/value_description.h" #include "mldb/types/structure_description.h" #include "mldb/types/tuple_description.h" #include "mldb/types/map_description.h" #include "mldb/rest/cancellation_exception.h" #include <thread> #define BOOST_TEST_MAIN #define BOOST_TEST_DYN_LINK #include <boost/test/unit_test.hpp> using namespace std; using namespace MLDB; struct TestConfig { std::string id; std::map<std::string, std::string> params; }; DECLARE_STRUCTURE_DESCRIPTION(TestConfig); DEFINE_STRUCTURE_DESCRIPTION(TestConfig); TestConfigDescription:: TestConfigDescription() { addField("id", &TestConfig::id, ""); addField("params", &TestConfig::params, ""); } struct TestStatus { std::string id; std::string state; Json::Value progress; }; DECLARE_STRUCTURE_DESCRIPTION(TestStatus); DEFINE_STRUCTURE_DESCRIPTION(TestStatus); TestStatusDescription:: TestStatusDescription() { addField("id", &TestStatus::id, ""); addField("state", &TestStatus::state, ""); addField("progress", &TestStatus::progress, ""); } struct TestObject { std::shared_ptr<TestConfig> config; }; struct TestCollection : public RestConfigurableCollection<std::string, TestObject, TestConfig, TestStatus> { typedef RestConfigurableCollection<std::string, TestObject, TestConfig, TestStatus> Base; TestCollection(RestEntity * owner = nullptr) : Base("object", "objects", owner ? owner : this) { } TestStatus getStatusFinished(std::string key, const TestObject & obj) const { TestStatus result; result.state = "ok"; result.id = key; return result; } TestStatus getStatusLoading(std::string key, const BackgroundTask & task) const { TestStatus result; result.state = "initializing"; result.id = key; result.progress = task.progress; return result; } std::string getKey(TestConfig & config) { return config.id; } std::shared_ptr<TestObject> construct(TestConfig config, const OnProgress & onProgress) const { auto result = std::make_shared<TestObject>(); result->config.reset(new TestConfig(std::move(config))); return result; } }; #if 0 BOOST_AUTO_TEST_CASE( test_s3_collection_store ) { S3CollectionConfigStore config("s3://tests.datacratic.com/unit_tests/rest_collection_test"); cerr << jsonEncode(config.getAll()); config.clear(); BOOST_CHECK_EQUAL(config.keys(), vector<string>()); config.set("hello", "world"); cerr << jsonEncode(config.get("hello")) << endl; BOOST_CHECK_EQUAL(config.get("hello"), "world"); } BOOST_AUTO_TEST_CASE( test_s3_collection_config_persistence ) { // This test makes sure that if we set peristent configuration, create // an object and then destroy the collection, when we recreate the // collection the same objects are still there. auto config = std::make_shared<S3CollectionConfigStore>("s3://tests.datacratic.com/unit_tests/rest_collection_test2"); // Get rid of anything that was hanging around config->clear(); TestConfig config1{"item1", { { "key1", "value1" } } }; { TestCollection collection; collection.attachConfig(config); collection.handlePost(config1); // Check that it got correctly into the config store BOOST_CHECK_EQUAL(collection.getKeys(), vector<string>({"item1"})); BOOST_CHECK_EQUAL(config->keys(), vector<string>({"item1"})); BOOST_CHECK_EQUAL(config->get("item1"), jsonEncode(config1)); } { TestCollection collection; collection.attachConfig(config); // Check that it correctly loaded up its objects from the config // store BOOST_CHECK_EQUAL(collection.getKeys(), vector<string>({"item1"})); BOOST_CHECK_EQUAL(config->keys(), vector<string>({"item1"})); BOOST_CHECK_EQUAL(config->get("item1"), jsonEncode(config1)); } } #endif BOOST_AUTO_TEST_CASE( test_watching ) { typedef RestCollection<std::string, std::string> Coll; RestDirectory dir(&dir, "dir"); Coll collection("item", "items", &dir); dir.addEntity("items", collection); WatchT<Coll::ChildEvent> w = dir.watch({"items", "elements:*"}, true /* catchUp */, string("w1")); WatchT<Coll::ChildEvent> w2 = dir.watch({"items", "elements:test2"}, true /* catchUp */, string("w2")); WatchT<std::vector<Utf8String>, Coll::ChildEvent> w3 = dir.watchWithPathT<Coll::ChildEvent>({"items", "elements:*"}, true /* catchUp */, string("w3")); // Wrong watch type should throw immediately { MLDB_TRACE_EXCEPTIONS(false); BOOST_CHECK_THROW(WatchT<int> w4 = dir.watch({"items", "elements:*"}, true /* catchUp */, string("w4")), std::exception); } BOOST_CHECK(!w.any()); collection.addEntry("test1", std::make_shared<std::string>("hello1")); BOOST_CHECK(w.any()); BOOST_CHECK(!w2.any()); auto val = w.pop(); BOOST_CHECK_EQUAL(val.key, "test1"); BOOST_CHECK_EQUAL(val.event, CE_NEW); BOOST_REQUIRE(val.value); BOOST_CHECK_EQUAL(*val.value, "hello1"); BOOST_CHECK(!w.any()); std::vector<Utf8String> path; Coll::ChildEvent ev; std::tie(path, ev) = w3.pop(); BOOST_CHECK_EQUAL(path.size(), 1); BOOST_CHECK_EQUAL(path, vector<Utf8String>({"items"})); collection.deleteEntry("test1"); BOOST_CHECK(w.any()); BOOST_CHECK(!w2.any()); val = w.pop(); BOOST_CHECK_EQUAL(val.key, "test1"); BOOST_CHECK_EQUAL(val.event, CE_DELETED); BOOST_REQUIRE(val.value); BOOST_CHECK_EQUAL(*val.value, "hello1"); collection.addEntry("test2", std::make_shared<std::string>("hello2")); BOOST_CHECK(w.any()); BOOST_CHECK(w2.any()); val = w2.pop(); BOOST_CHECK_EQUAL(val.key, "test2"); BOOST_CHECK_EQUAL(val.event, CE_NEW); BOOST_REQUIRE(val.value); BOOST_CHECK_EQUAL(*val.value, "hello2"); } struct ConfigColl: public RestConfigurableCollection<std::string, std::string, std::string, std::string> { ConfigColl(RestEntity * parent) : RestConfigurableCollection<std::string, std::string, std::string, std::string>("item", "items", parent) { } virtual std::string getStatusFinished(std::string key, const std::string & value) const { return value; } virtual std::string getKey(string & config) { return config; } virtual std::shared_ptr<std::string> construct(string config, const OnProgress & onProgress) const { return std::make_shared<std::string>(config); } }; BOOST_AUTO_TEST_CASE( test_watching_config ) { ConfigColl collection(&collection); WatchT<std::string, std::shared_ptr<std::string> > w = collection.watch({"config:*"}, true /* catchUp */, string("w")); #if 0 WatchT<Coll::ChildEvent> w2 = dir.watch({"items", "elements:test2"}, true /* catchUp */); // Wrong watch type should throw immediately { MLDB_TRACE_EXCEPTIONS(false); BOOST_CHECK_THROW(WatchT<int> w3 = dir.watch({"items", "elements:*"}, true /* catchUp */), std::exception); } BOOST_CHECK(!w.any()); collection.addEntry("test1", std::make_shared<std::string>("hello1")); BOOST_CHECK(w.any()); BOOST_CHECK(!w2.any()); auto val = w.pop(); BOOST_CHECK_EQUAL(val.key, "test1"); BOOST_CHECK_EQUAL(val.event, CE_NEW); BOOST_REQUIRE(val.value); BOOST_CHECK_EQUAL(*val.value, "hello1"); BOOST_CHECK(!w.any()); collection.deleteEntry("test1"); BOOST_CHECK(w.any()); BOOST_CHECK(!w2.any()); val = w.pop(); BOOST_CHECK_EQUAL(val.key, "test1"); BOOST_CHECK_EQUAL(val.event, CE_DELETED); BOOST_REQUIRE(val.value); BOOST_CHECK_EQUAL(*val.value, "hello1"); collection.addEntry("test2", std::make_shared<std::string>("hello2")); BOOST_CHECK(w.any()); BOOST_CHECK(w2.any()); val = w2.pop(); BOOST_CHECK_EQUAL(val.key, "test2"); BOOST_CHECK_EQUAL(val.event, CE_NEW); BOOST_REQUIRE(val.value); BOOST_CHECK_EQUAL(*val.value, "hello2"); #endif } struct RecursiveCollection: public RestCollection<std::string, RecursiveCollection> { RecursiveCollection(const std::string & name, RestEntity * parent) : RestCollection<std::string, RecursiveCollection>("item", "items", parent), name(name) { } ~RecursiveCollection() { //cerr << "destroying recursive collection " << name << endl; } std::pair<const std::type_info *, std::shared_ptr<const ValueDescription> > getWatchBoundType(const ResourceSpec & spec) { if (spec.size() > 1) { if (spec[0].channel == "children") return getWatchBoundType(ResourceSpec(spec.begin() + 1, spec.end())); throw MLDB::Exception("only children channel known"); } if (spec[0].channel == "children") return make_pair(&typeid(std::tuple<RestEntityChildEvent>), nullptr); else if (spec[0].channel == "elements") return make_pair(&typeid(std::tuple<ChildEvent>), nullptr); else throw MLDB::Exception("unknown channel"); } std::string name; }; BOOST_AUTO_TEST_CASE( test_watching_multi_level ) { RecursiveCollection coll("coll", &coll); WatchT<RecursiveCollection::ChildEvent> w = coll.watch({"*", "elements:*"}, true /* catchUp */, string("w")); BOOST_CHECK(!w.any()); WatchT<std::string> w2; // watch is wrong type { MLDB_TRACE_EXCEPTIONS(false); BOOST_CHECK_THROW(w2 = coll.watch({"*", "elements:*"}, true /* catchUp */, string("w2")), std::exception); } auto coll1 = std::make_shared<RecursiveCollection>("coll1", nullptr); auto coll2 = std::make_shared<RecursiveCollection>("coll2", nullptr); auto coll11 = std::make_shared<RecursiveCollection>("coll11", coll1.get()); auto coll12 = std::make_shared<RecursiveCollection>("coll12", coll1.get()); auto coll21 = std::make_shared<RecursiveCollection>("coll21", coll2.get()); auto coll22 = std::make_shared<RecursiveCollection>("coll22", coll2.get()); coll.addEntry("coll1", coll1); BOOST_CHECK(!w.any()); BOOST_CHECK(!w2.any()); coll1->addEntry("coll11", coll11); BOOST_CHECK(w.any()); auto val = w.pop(); BOOST_CHECK_EQUAL(val.key, "coll11"); BOOST_CHECK_EQUAL(val.event, CE_NEW); BOOST_CHECK_EQUAL(val.value, coll11); coll1->addEntry("coll12", coll12); BOOST_CHECK(w.any()); val = w.pop(); BOOST_CHECK_EQUAL(val.key, "coll12"); BOOST_CHECK_EQUAL(val.event, CE_NEW); BOOST_CHECK_EQUAL(val.value, coll12); BOOST_CHECK(!w.any()); coll1->deleteEntry("coll11"); BOOST_CHECK(w.any()); val = w.pop(); BOOST_CHECK_EQUAL(val.key, "coll11"); BOOST_CHECK_EQUAL(val.event, CE_DELETED); BOOST_CHECK_EQUAL(val.value, coll11); BOOST_CHECK(!w.any()); // Now delete the parent entry. This should notify us of our child // entries disappearing. BOOST_CHECK(coll.deleteEntry("coll1")); BOOST_CHECK(w.any()); val = w.pop(); BOOST_CHECK_EQUAL(val.key, "coll12"); BOOST_CHECK_EQUAL(val.event, CE_DELETED); BOOST_CHECK_EQUAL(val.value, coll12); BOOST_CHECK(!w.any()); // Add a new entry that already has children. We should get notified // of those children immediately that we add it. coll2->addEntry("coll21", coll21); coll2->addEntry("coll22", coll22); coll.addEntry("coll2", coll2); BOOST_CHECK(w.any()); val = w.pop(); BOOST_CHECK_EQUAL(val.key, "coll21"); BOOST_CHECK_EQUAL(val.event, CE_NEW); BOOST_CHECK_EQUAL(val.value, coll21); val = w.pop(); BOOST_CHECK_EQUAL(val.key, "coll22"); BOOST_CHECK_EQUAL(val.event, CE_NEW); BOOST_CHECK_EQUAL(val.value, coll22); BOOST_CHECK(!w.any()); } struct SlowToCreateTestCollection: public TestCollection { ~SlowToCreateTestCollection() { // don't do this to test that we can shutdown from the // base class without a pure virtual method call //this->shutdown(); } std::shared_ptr<TestObject> construct(TestConfig config, const OnProgress & onProgress) const { std::this_thread::sleep_for(std::chrono::milliseconds(10)); auto result = std::make_shared<TestObject>(); result->config.reset(new TestConfig(std::move(config))); return result; } }; // Stress test for MLDB-1259 BOOST_AUTO_TEST_CASE ( test_destroying_while_creating ) { int numTests = 100; for (unsigned i = 0; i < numTests; ++i) { cerr << "test " << i << " of " << numTests << endl; SlowToCreateTestCollection collection; TestConfig config{"item1", {}}; collection.handlePost("item1", config, true /* must be true */); // Destroy it while still being created, to test that we // don't crash } } // Stress test for MLDB-408 BOOST_AUTO_TEST_CASE ( test_cancelling_while_creating ) { int numTests = 100; for (unsigned i = 0; i < numTests; ++i) { SlowToCreateTestCollection collection; TestConfig config{"item1", {}}; collection.handlePost("item1", config, true /* must be true */); auto entry = collection.getEntry("item1"); if (entry.second) { entry.second->cancel(); cerr << entry.second->getState() << endl; } else { BOOST_CHECK(false); } } } struct SlowToCreateTestCollectionWithCancellation: public TestCollection { ~SlowToCreateTestCollectionWithCancellation() { this->shutdown(); } std::shared_ptr<TestObject> construct(TestConfig config, const OnProgress & onProgress) const { Json::Value progress; for (int i = 0; i < 5; ++i) { std::this_thread::sleep_for(std::chrono::milliseconds(1)); if (!onProgress(progress)) { cerr << "cancelledddddd" << endl; throw CancellationException("cancellation"); } } auto result = std::make_shared<TestObject>(); result->config.reset(new TestConfig(std::move(config))); return result; } }; /** This is a stress test of the RestCollection, to ensure that cancelling entries does not crash MLDB. */ BOOST_AUTO_TEST_CASE( stress_test_collection_cancellation ) { SlowToCreateTestCollectionWithCancellation collection; std::atomic<bool> shutdown(false); std::atomic<unsigned int> cancelled(0); std::atomic<unsigned int> lateCancellation(0); std::atomic<unsigned int> created(0); std::atomic<unsigned int> underConstruction(0); std::atomic<unsigned int> deletedAfterCreation(0); std::atomic<unsigned int> cancelledBeforeCreation(0); auto addThread = [&] () { while (!shutdown) { string key = "item2"; TestConfig config{key, {}}; try { collection.handlePost(key, config, true /* must be new entry */); auto entry = collection.getEntry(key); if (entry.first) { cerr << "entry created" << endl; created++; } else { cerr << "entry is under construction" << endl; underConstruction++; } } catch (AnnotatedException & ex) { BOOST_ERROR("failed creating an entry or to get " "the entry while under construction"); } std::this_thread::sleep_for(std::chrono::milliseconds(1)); auto deletedEntry = collection.deleteEntry(key); if (deletedEntry) deletedAfterCreation++; else cancelledBeforeCreation++; }; }; auto cancelThread = [&] () { while (!shutdown) { std::string key = "item2"; try { auto entry = collection.getEntry(key); if (entry.second) { if (entry.second->cancel()) cancelled++; } else { cerr << "failed to cancel the entry because the entry was created" << endl; lateCancellation++; } } catch (AnnotatedException & ex) { cerr << "failed to get the entry" << endl; } std::this_thread::sleep_for(std::chrono::milliseconds(1)); }; }; std::vector<std::thread> threads; std::thread creater(addThread); unsigned int numCancellationThreads = 10; for (unsigned i = 0; i < numCancellationThreads; ++i) { threads.emplace_back(cancelThread); } std::this_thread::sleep_for(std::chrono::seconds(1)); shutdown = true; for (auto & t: threads) t.join(); creater.join(); cerr << "created " << created << " under construction " << underConstruction << " deleted after creation " << deletedAfterCreation << " cancelled before creation " << cancelledBeforeCreation << " cancelled " << cancelled << " late cancellation " << lateCancellation << endl; BOOST_CHECK_EQUAL(created + underConstruction, deletedAfterCreation + cancelledBeforeCreation); }
18,893
6,064
/** * Copyright 2020-2021 Huawei Technologies Co., Ltd * * 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 "poly/isl_util.h" #include "poly/log_util.h" namespace akg { namespace ir { namespace poly { //////////////////////////////////////////////////////////////////////////////// // local types //////////////////////////////////////////////////////////////////////////////// enum isl_schedule_node_fine_adjustment_type { FINE_ADJUSTMENT_NONE = 0, FINE_ADJUSTMENT_MOD, FINE_ADJUSTMENT_SCALE, FINE_ADJUSTMENT_SCALE_DOWN, }; struct isl_schedule_node_fine_adjustment_data { isl_union_pw_aff *result; const char *name; isl_val *value; enum isl_schedule_node_fine_adjustment_type type; }; //////////////////////////////////////////////////////////////////////////////// // local declarations //////////////////////////////////////////////////////////////////////////////// static inline __isl_give isl_multi_union_pw_aff *isl_multi_union_pw_aff_collapse(__isl_take isl_multi_union_pw_aff *aff, int dim, __isl_take isl_val *val); static inline __isl_give isl_val *isl_schedule_node_band_find_collapse_coeff(__isl_take isl_schedule_node *band, int dim); static inline isl_stat isl_pw_aff_fine_adjustment(__isl_take isl_pw_aff *pa, void *user); static inline isl::multi_union_pw_aff isl_multi_union_pw_aff_collapse(const isl::multi_union_pw_aff &aff, int dim, const isl::val &value) { return isl::manage(isl_multi_union_pw_aff_collapse(aff.copy(), dim, value.copy())); } static inline isl::val isl_schedule_node_band_find_collapse_coeff(const isl::schedule_node_band &band, int dim) { return isl::manage(isl_schedule_node_band_find_collapse_coeff(band.copy(), dim)); } //////////////////////////////////////////////////////////////////////////////// // C++ wrappers for unexposed isl functions //////////////////////////////////////////////////////////////////////////////// bool isl_aff_is_cst(const isl::aff &a) { isl_aff *const internal = a.get(); return isl_aff_is_cst(internal); } std::string isl_set_get_dim_name(const isl::set &s, enum isl_dim_type type, unsigned int pos) { const isl::id &id = isl_set_get_dim_id(s, type, pos); return id.name(); } isl::id isl_set_get_dim_id(const isl::set &s, enum isl_dim_type type, unsigned int pos) { isl_id *const id = isl_set_get_dim_id(s.get(), type, pos); return isl::manage(id); } int isl_set_find_dim_by_id(const isl::set &s, enum isl_dim_type type, const isl::id &id) { return isl_set_find_dim_by_id(s.get(), type, id.get()); } int isl_set_find_dim_by_name(const isl::set &s, enum isl_dim_type type, const std::string &name) { return isl_set_find_dim_by_name(s.get(), type, name.c_str()); } unsigned isl_set_dim(const isl::set &s, enum isl_dim_type type) { isl_set *const internal = s.get(); const isl_size size = isl_set_dim(internal, type); return size; } long isl_set_plain_get_num_si(const isl::set &s, unsigned int pos) { const isl::val &value = isl_set_plain_get_val_if_fixed(s, isl_dim_set, pos); const long result = value.get_num_si(); return result; } isl::val isl_set_plain_get_val_if_fixed(const isl::set &s, enum isl_dim_type type, unsigned int pos) { isl_set *const internal = s.get(); isl_val *const value = isl_set_plain_get_val_if_fixed(internal, type, pos); return isl::manage(value); } isl::set isl_set_move_dims(const isl::set &s, enum isl_dim_type dst_type, unsigned int dst_pos, enum isl_dim_type src_type, unsigned int src_pos, unsigned int n) { isl_set *const internal = isl_set_move_dims(s.copy(), dst_type, dst_pos, src_type, src_pos, n); return isl::manage(internal); } std::string isl_map_get_dim_name(const isl::map &m, enum isl_dim_type type, unsigned int pos) { const isl::id &id = isl_map_get_dim_id(m, type, pos); return id.name(); } isl::id isl_map_get_dim_id(const isl::map &m, enum isl_dim_type type, unsigned int pos) { isl_map *const internal = m.get(); isl_id *const id = isl_map_get_dim_id(internal, type, pos); return isl::manage(id); } bool isl_map_involves_dims(const isl::map &m, enum isl_dim_type type, unsigned int first, unsigned n) { isl_map *const internal = m.get(); return isl_map_involves_dims(internal, type, first, n); } isl::map isl_map_drop_constraints_not_involving_dims(const isl::map &m, enum isl_dim_type type, unsigned int first, unsigned n) { isl_map *const internal = isl_map_copy(m.get()); isl_map *const drop = isl_map_drop_constraints_not_involving_dims(internal, type, first, n); return isl::manage(drop); } isl::union_map isl_union_map_align_params(const isl::union_map &map, const isl::space &space) { isl_union_map *const aligned = isl_union_map_align_params(map.copy(), space.copy()); return isl::manage(aligned); } isl::union_pw_aff_list isl_union_pw_aff_list_insert(const isl::union_pw_aff_list &list, unsigned int pos, const isl::union_pw_aff &aff) { isl_union_pw_aff *const element = aff.copy(); isl_union_pw_aff_list *result = list.copy(); result = isl_union_pw_aff_list_insert(result, pos, element); return isl::manage(result); } isl::space isl_space_set_alloc(isl::ctx ctx, unsigned int nparam, unsigned int dim) { isl_space *const internal = isl_space_set_alloc(ctx.get(), nparam, dim); return isl::manage(internal); } isl::id isl_space_get_dim_id(const isl::space &space, enum isl_dim_type type, unsigned int pos) { isl_space *const internal = space.get(); isl_id *const id = isl_space_get_dim_id(internal, type, pos); return isl::manage(id); } isl::space isl_space_set_dim_id(const isl::space &space, enum isl_dim_type type, unsigned int pos, const isl::id &id) { isl_id *const internal_id = id.copy(); isl_space *internal_space = space.copy(); internal_space = isl_space_set_dim_id(internal_space, type, pos, internal_id); return isl::manage(internal_space); } //////////////////////////////////////////////////////////////////////////////// // Misc. //////////////////////////////////////////////////////////////////////////////// std::vector<std::string> isl_set_dim_names(const isl::set &set, enum isl_dim_type type) { std::vector<std::string> result; const unsigned int count = isl_set_dim(set, type); for (unsigned int i = 0; i < count; ++i) { const std::string &current = isl_set_get_dim_name(set, type, i); result.push_back(current); } return result; } std::vector<std::string> isl_set_all_names(const isl::set &set) { std::vector<std::string> result; const unsigned int set_dimensions = isl_set_dim(set, isl_dim_set); for (unsigned int i = 0; i < set_dimensions; ++i) { const std::string &current = isl_set_get_dim_name(set, isl_dim_set, i); result.push_back(current); } const unsigned int parameters = isl_set_dim(set, isl_dim_param); for (unsigned int i = 0; i < parameters; ++i) { const std::string &current = isl_set_get_dim_name(set, isl_dim_param, i); result.push_back(current); } return result; } std::vector<int> isl_set_lexmax_extract_upper_bounds(const isl::set &set, const std::vector<std::string> &names) { std::vector<int> result; const std::size_t count = names.size(); for (std::size_t i = 0; i < count; ++i) { const int position = isl_set_find_dim_by_name(set, isl_dim_set, names[i]); if (position >= 0) { // The input set is supposed to be a lexmax const isl::val &lexmax = isl_set_plain_get_val_if_fixed(set, isl_dim_set, position); const isl::val &upper_bound = lexmax.add(1); const int value = static_cast<int>(upper_bound.get_num_si()); result.push_back(value); } } return result; } std::vector<int> isl_set_lexmax_extract_upper_bounds(const isl::set &s, const std::vector<int> &dimensions) { std::vector<int> result; const int size = static_cast<int>(isl_set_dim(s, isl_dim_set)); for (auto dimension : dimensions) { if (dimension < size) { // We need to add 1 because the input set is a lexmax const isl::val &lexmax = isl_set_plain_get_val_if_fixed(s, isl_dim_set, dimension); const isl::val &upper_bound = lexmax.add(1); const int value = static_cast<int>(upper_bound.get_num_si()); result.push_back(value); } else { log::Warn("cannot retrieve size for dimension " + std::to_string(dimension)); } } return result; } isl::space isl_space_copy_param_names(const isl::space &space, const isl::space &source) { isl::space result = space; const unsigned int params = source.dim(isl_dim_param); const unsigned int limit = std::min(params, result.dim(isl_dim_param)); if (params > limit) { log::Warn("destination space is smaller than source space"); } for (unsigned int i = 0; i < limit; ++i) { const isl::id &name = isl_space_get_dim_id(source, isl_dim_param, i); result = isl_space_set_dim_id(result, isl_dim_param, i, name); } return result; } isl::space isl_space_set_cat(const isl::space &left, const isl::space &right) { const unsigned int params = left.dim(isl_dim_param); const unsigned int out = left.dim(isl_dim_out) + right.dim(isl_dim_out); // No constructor that takes both isl_dim_params and isl_dim_out sizes in the C++ wrapper! isl_ctx *const ctx = left.ctx().get(); isl_space *const result = isl_space_set_alloc(ctx, params, out); // Note: we currently do not need to extract dim names if they were named in the input spaces. return isl::manage(result); } isl::multi_union_pw_aff isl_multi_union_pw_aff_cat(const isl::multi_union_pw_aff &left, const isl::multi_union_pw_aff &right) { const unsigned int left_count = left.size(); const unsigned int right_count = right.size(); if (!left_count) { return right; } else if (!right_count) { return left; } const isl::union_pw_aff_list &left_list = left.union_pw_aff_list(); const isl::union_pw_aff_list &right_list = right.union_pw_aff_list(); const isl::union_pw_aff_list &list = left_list.concat(right_list); const isl::space &left_space = left.space(); const isl::space &right_space = right.space(); const isl::space &space = isl_space_set_cat(left_space, right_space); const isl::multi_union_pw_aff &result = isl::multi_union_pw_aff(space, list); return result; } __isl_give isl_multi_union_pw_aff *isl_multi_union_pw_aff_cat(__isl_take isl_multi_union_pw_aff *left, __isl_take isl_multi_union_pw_aff *right) { const isl::multi_union_pw_aff &wrapped = isl_multi_union_pw_aff_cat(isl::manage(left), isl::manage(right)); isl_multi_union_pw_aff *const result = isl_multi_union_pw_aff_copy(wrapped.get()); return result; } isl::multi_union_pw_aff isl_multi_union_pw_aff_insert(const isl::multi_union_pw_aff &aff, unsigned pos, const isl::union_pw_aff &el) { const isl::space &initial_space = aff.space(); const isl::space &space = initial_space.add_dims(isl_dim_out, 1); const isl::union_pw_aff_list &initial_list = aff.union_pw_aff_list(); const isl::union_pw_aff_list &list = isl_union_pw_aff_list_insert(initial_list, pos, el); const isl::multi_union_pw_aff &result = isl::multi_union_pw_aff(space, list); return result; } //////////////////////////////////////////////////////////////////////////////// // isl_schedule_node utilities //////////////////////////////////////////////////////////////////////////////// bool isl_schedule_node_is_band(const isl::schedule_node &node) { return node.isa<isl::schedule_node_band>(); } bool isl_schedule_node_is_sequence(const isl::schedule_node &node) { return node.isa<isl::schedule_node_sequence>(); } bool isl_schedule_node_has_single_child(const isl::schedule_node &node) { return node.n_children() == 1; } bool isl_schedule_node_band_can_unsplit(const isl::schedule_node_band &band) { return isl_schedule_node_has_single_child(band) && band.child(0).isa<isl::schedule_node_band>(); } //////////////////////////////////////////////////////////////////////////////// // isl_schedule_node_band utilities //////////////////////////////////////////////////////////////////////////////// std::vector<bool> isl_schedule_node_band_get_coincidence(const isl::schedule_node_band &band) { std::vector<bool> result; const unsigned int members = band.n_member(); if (!members) { return result; } for (unsigned int i = 0; i < members; ++i) { const bool coincident = band.member_get_coincident(static_cast<int>(i)); result.push_back(coincident); } return result; } isl::schedule_node_band isl_schedule_node_band_set_coincidence(const isl::schedule_node_band &band, const std::vector<bool> &coincidence) { const std::size_t members = static_cast<size_t>(band.n_member()); const std::size_t size = coincidence.size(); const std::size_t limit = std::min(members, size); if (members != size) { log::Warn("band size differs from coincidence vector!"); } isl::schedule_node_band result = band; for (std::size_t i = 0; i < limit; ++i) { const int pos = static_cast<int>(i); const bool coincident = coincidence[i]; result = result.member_set_coincident(pos, coincident); } return result; } isl::schedule_node_band isl_schedule_node_band_member_copy_properties(const isl::schedule_node_band &band, int pos, const isl::schedule_node_band &wrapped_original) { isl_schedule_node *const original = wrapped_original.get(); const isl_bool coincident = isl_schedule_node_band_member_get_coincident(original, pos); const enum isl_ast_loop_type loop_type = isl_schedule_node_band_member_get_ast_loop_type(original, pos); const enum isl_ast_loop_type isolate_type = isl_schedule_node_band_member_get_isolate_ast_loop_type(original, pos); isl_schedule_node *internal = isl_schedule_node_copy(band.get()); internal = isl_schedule_node_band_member_set_coincident(internal, pos, coincident); internal = isl_schedule_node_band_member_set_ast_loop_type(internal, pos, loop_type); internal = isl_schedule_node_band_member_set_isolate_ast_loop_type(internal, pos, isolate_type); const isl::schedule_node &node = isl::manage(internal); return node.as<isl::schedule_node_band>(); } isl::schedule_node_band isl_schedule_node_band_copy_properties(const isl::schedule_node &node, const isl::schedule_node &original) { return isl_schedule_node_band_copy_properties(node.as<isl::schedule_node_band>(), original.as<isl::schedule_node_band>()); } isl::schedule_node_band isl_schedule_node_band_copy_properties(const isl::schedule_node &node, const isl::schedule_node_band &original) { return isl_schedule_node_band_copy_properties(node.as<isl::schedule_node_band>(), original); } isl::schedule_node_band isl_schedule_node_band_copy_properties(const isl::schedule_node_band &band, const isl::schedule_node &original) { return isl_schedule_node_band_copy_properties(band, original.as<isl::schedule_node_band>()); } isl::schedule_node_band isl_schedule_node_band_copy_properties(const isl::schedule_node_band &band, const isl::schedule_node_band &original) { isl::schedule_node_band result = band; const bool permutable = original.permutable(); const isl::union_set &ast_build_options = original.ast_build_options(); result = result.set_permutable(permutable); result = result.set_ast_build_options(ast_build_options); const int limit = static_cast<int>(std::min(band.n_member(), original.n_member())); for (int i = 0; i < limit; ++i) { result = isl_schedule_node_band_member_copy_properties(result, i, original); } return result; } isl::schedule_node_band isl_schedule_node_band_replace_partial_schedule(const isl::schedule_node &node, const isl::multi_union_pw_aff &partial, bool keep_properties) { return isl_schedule_node_band_replace_partial_schedule(node.as<isl::schedule_node_band>(), partial, keep_properties); } isl::schedule_node_band isl_schedule_node_band_replace_partial_schedule(const isl::schedule_node_band &band, const isl::multi_union_pw_aff &partial, bool keep_properties) { // The new schedule will be inserted above the current band isl::schedule_node_band result = band.insert_partial_schedule(partial).as<isl::schedule_node_band>(); if (keep_properties) { const isl::schedule_node_band &original = result.child(0).as<isl::schedule_node_band>(); result = isl_schedule_node_band_copy_properties(result, original); } // Do not forget to delete the previous band node and then move back to the "new" current position! result = result.child(0).del().parent().as<isl::schedule_node_band>(); return result; } isl::set isl_schedule_node_band_lexmax(const isl::schedule_node &node) { return isl_schedule_node_band_lexmax(node.as<isl::schedule_node_band>()); } isl::set isl_schedule_node_band_lexmax(const isl::schedule_node_band &band) { const isl::union_set &domain = band.domain(); const isl::union_map &schedule = band.partial_schedule_union_map(); const isl::union_set &application = domain.apply(schedule); const isl::union_set &lexmax = application.lexmax(); return isl::set::from_union_set(lexmax); } //////////////////////////////////////////////////////////////////////////////// // isl_schedule_node_band transformations //////////////////////////////////////////////////////////////////////////////// isl::schedule_node_band isl_schedule_node_band_interchange(const isl::schedule_node_band &band, unsigned int first, unsigned int second) { isl::multi_union_pw_aff partial = band.get_partial_schedule(); const unsigned int dims = partial.size(); if (first >= dims || second >= dims) { log::Warn(std::string(__func__) + ": target dimension out of bounds"); return band; } const isl::union_pw_aff &aff_1 = partial.at(first); const isl::union_pw_aff &aff_2 = partial.at(second); partial = partial.set_at(first, aff_2); partial = partial.set_at(second, aff_1); // Save the properties const bool permutable = band.permutable(); std::vector<bool> coincidence = isl_schedule_node_band_get_coincidence(band); // Interchange the coincidences const bool tmp = coincidence[first]; coincidence[first] = coincidence[second]; coincidence[second] = tmp; isl::schedule_node_band result = isl_schedule_node_band_replace_partial_schedule(band, partial, false); result = result.set_permutable(permutable); result = isl_schedule_node_band_set_coincidence(band, coincidence); return result; } isl::schedule_node_band isl_schedule_node_band_stripmine(const isl::schedule_node_band &band, unsigned int dim, int value) { isl::ctx ctx = band.ctx(); const isl::val &val = isl::val(ctx, value); return isl_schedule_node_band_stripmine(band, dim, val); } isl::schedule_node_band isl_schedule_node_band_stripmine(const isl::schedule_node_band &band, unsigned int dim, const isl::val &value) { const unsigned int members = band.n_member(); if (dim >= members) { log::Warn(std::string(__func__) + ": cannot stripmine out of bounds dimension"); return band; } isl::multi_union_pw_aff schedule = band.partial_schedule(); const isl::union_pw_aff &div = schedule.at(dim).scale_down(value); const isl::union_pw_aff &mod = schedule.at(dim).mod(value); schedule = schedule.set_at(dim, div); schedule = isl_multi_union_pw_aff_insert(schedule, dim + 1, mod); const bool permutable = band.permutable(); std::vector<bool> coincidence = isl_schedule_node_band_get_coincidence(band); auto position = coincidence.begin() + dim + 1; coincidence.insert(position, coincidence[dim]); isl::schedule_node_band result = isl_schedule_node_band_replace_partial_schedule(band, schedule, true); result = result.set_permutable(permutable); result = isl_schedule_node_band_set_coincidence(result, coincidence); return result; } isl::schedule_node_band isl_schedule_node_band_collapse(const isl::schedule_node_band &band, unsigned int dim) { const unsigned int members = band.n_member(); if (dim >= members) { return band; } const isl::val &coeff = isl_schedule_node_band_find_collapse_coeff(band, dim); isl::multi_union_pw_aff partial = band.partial_schedule(); partial = isl_multi_union_pw_aff_collapse(partial, dim, coeff); const bool permutable = band.permutable(); std::vector<bool> coincidence = isl_schedule_node_band_get_coincidence(band); const bool collapsed_coincidence = coincidence[dim] && coincidence[dim + 1]; coincidence[dim] = collapsed_coincidence; auto position = coincidence.begin() + dim + 1; coincidence.erase(position); isl::schedule_node_band result = isl_schedule_node_band_replace_partial_schedule(band, partial, false); result = result.set_permutable(permutable); result = isl_schedule_node_band_set_coincidence(result, coincidence); return result; } isl::schedule_node_band isl_schedule_node_band_fine_adjustment(const isl::schedule_node_band &band, enum isl_schedule_node_fine_adjustment_type type, const std::string &name, unsigned int dimension, const isl::val &value) { isl::multi_union_pw_aff partial = band.partial_schedule(); const unsigned int dims = partial.size(); if (dimension >= dims) { log::Warn(std::string(__func__) + ": target dimension out of bounds"); return band; } // Save the properties const bool permutable = band.permutable(); std::vector<bool> coincidence = isl_schedule_node_band_get_coincidence(band); const isl::union_pw_aff &target = partial.at(dimension); struct isl_schedule_node_fine_adjustment_data arg = { .result = NULL, .name = name.c_str(), .value = value.get(), .type = type, }; isl_union_pw_aff_foreach_pw_aff(target.get(), isl_pw_aff_fine_adjustment, &arg); isl::union_pw_aff adjusted = isl::manage(arg.result); // Replace the target in the partial schedule partial = partial.set_at(dimension, adjusted); // Insert the new schedule and delete the previous one. isl::schedule_node_band result = isl_schedule_node_band_replace_partial_schedule(band, partial, false); result = result.set_permutable(permutable); result = isl_schedule_node_band_set_coincidence(result, coincidence); return result; } isl::schedule_node_band isl_schedule_node_band_fine_adjustment(const isl::schedule_node_band &band, enum isl_schedule_node_fine_adjustment_type type, const std::string &name, unsigned int dimension, int value) { isl::ctx ctx = band.ctx(); const isl::val &val = isl::val(ctx, value); return isl_schedule_node_band_fine_adjustment(band, type, name, dimension, val); } //////////////////////////////////////////////////////////////////////////////// // schedule tree transformations (on a schedule_node) //////////////////////////////////////////////////////////////////////////////// isl::schedule_node_band isl_schedule_node_band_unsplit(const isl::schedule_node_band &band) { // We assume isl_schedule_node_band_can_unsplit() has been checked isl::schedule_node_band result = band; // Insert the new partial schedule at the current position { const isl::schedule_node_band &child = result.child(0).as<isl::schedule_node_band>(); const isl::multi_union_pw_aff &top = result.partial_schedule(); const isl::multi_union_pw_aff &bottom = child.partial_schedule(); const isl::multi_union_pw_aff &partial = isl_multi_union_pw_aff_cat(top, bottom); result = result.insert_partial_schedule(partial).as<isl::schedule_node_band>(); } // Set the band's properties // NOTE: we do not set AST loop type or AST build options! { const isl::schedule_node_band &first = result.child(0).as<isl::schedule_node_band>(); const isl::schedule_node_band &second = first.child(0).as<isl::schedule_node_band>(); const bool permutable = first.permutable() && second.permutable(); result = result.set_permutable(permutable); const unsigned int first_size = first.n_member(); for (unsigned int i = 0; i < first_size; ++i) { const bool coincident = first.member_get_coincident(i); result = result.member_set_coincident(i, coincident); } const unsigned int second_size = second.n_member(); for (unsigned int i = 0; i < second_size; ++i) { const bool coincident = second.member_get_coincident(i); const unsigned int member = first_size + i; result = result.member_set_coincident(member, coincident); } } // Remove the two successive children we merged { isl::schedule_node node = result.child(0); node = node.del(); node = node.del(); result = node.parent().as<isl::schedule_node_band>(); } return result; } isl::schedule_node_band isl_schedule_node_band_fully_unsplit(const isl::schedule_node_band &band) { isl::schedule_node_band result = band; while (isl_schedule_node_band_can_unsplit(result)) { result = isl_schedule_node_band_unsplit(result); } return result; } isl::schedule_node isl_schedule_node_band_fully_split(const isl::schedule_node_band &band) { isl::schedule_node_band result = band; while (result.n_member() > 1) { const int kept = result.n_member() - 1; result = result.split(kept); } return result; } //////////////////////////////////////////////////////////////////////////////// // isl_schedule transformations //////////////////////////////////////////////////////////////////////////////// isl::schedule isl_schedule_collapse(const isl::schedule &schedule, unsigned int first, unsigned int last) { if (last < first) { return schedule; } const isl::schedule_node &root = schedule.root(); isl::schedule_node_band band = root.child(0).as<isl::schedule_node_band>(); for (unsigned int dim = last; dim-- > first;) { band = isl_schedule_node_band_collapse(band, dim); } const isl::schedule &result = band.schedule(); return result; } //////////////////////////////////////////////////////////////////////////////// // String conversions for wrapped isl objects //////////////////////////////////////////////////////////////////////////////// std::string to_c_code_string(const isl::schedule &s) { return to_c_code_string(s.get()); } std::string to_c_code_string(const isl::schedule_constraints &c) { return to_c_code_string(c.get()); } std::string to_block_string(const isl::schedule &s) { return to_block_string(s.get()); } std::string to_block_string(const isl::union_map &map) { return to_block_string(map.get()); } std::string to_block_string(const isl::schedule_constraints &constraints) { return to_block_string(constraints.get()); } //////////////////////////////////////////////////////////////////////////////// // "Simple" C code string //////////////////////////////////////////////////////////////////////////////// std::string to_c_code_string(__isl_keep isl_schedule *const schedule) { isl_ctx *const ctx = isl_schedule_get_ctx(schedule); isl_ast_build *const build = isl_ast_build_alloc(ctx); isl_ast_node *const ast = isl_ast_build_node_from_schedule(build, isl_schedule_copy(schedule)); isl_printer *printer = isl_printer_to_str(ctx); printer = isl_printer_set_output_format(printer, ISL_FORMAT_C); printer = isl_printer_print_ast_node(printer, ast); char *const s = isl_printer_get_str(printer); std::string result(s); isl_printer_free(printer); isl_ast_build_free(build); isl_ast_node_free(ast); free(s); return result; } std::string to_c_code_string(__isl_keep isl_schedule_constraints *const input) { isl_schedule_constraints *const constraints = isl_schedule_constraints_copy(input); isl_ctx *const ctx = isl_schedule_constraints_get_ctx(constraints); const int previous_behaviour = isl_options_get_on_error(ctx); isl_options_set_on_error(ctx, ISL_ON_ERROR_CONTINUE); isl_schedule *const schedule = isl_schedule_constraints_compute_schedule(constraints); isl_options_set_on_error(ctx, previous_behaviour); const std::string result = to_c_code_string(schedule); isl_schedule_free(schedule); return result; } //////////////////////////////////////////////////////////////////////////////// // Strings //////////////////////////////////////////////////////////////////////////////// template <typename T, __isl_keep isl_ctx *(*ctx_getter)(__isl_keep T), __isl_give isl_printer *(*printer_function)(__isl_give isl_printer *, __isl_keep T)> std::string isl_to_block_str(T t) { isl_ctx *const ctx = ctx_getter(t); isl_printer *printer = isl_printer_to_str(ctx); printer = isl_printer_set_yaml_style(printer, ISL_YAML_STYLE_BLOCK); printer = printer_function(printer, t); char *const block = isl_printer_get_str(printer); const std::string result(block); isl_printer_free(printer); free(block); return result; } std::string to_block_string(__isl_keep isl_schedule *const schedule) { return isl_to_block_str<isl_schedule *, isl_schedule_get_ctx, isl_printer_print_schedule>(schedule); } static inline isl_stat isl_println_basic_map(__isl_take isl_basic_map *const map, void *user) { isl_printer **printer = (isl_printer **)user; *printer = isl_printer_print_basic_map(*printer, map); *printer = isl_printer_print_str(*printer, "\n"); isl_basic_map_free(map); return isl_stat_ok; } static inline __isl_give isl_printer *isl_printer_print_map_as_block(__isl_give isl_printer *printer, __isl_keep isl_map *const map) { isl_map_foreach_basic_map(map, isl_println_basic_map, (void *)&printer); return printer; } static inline isl_stat isl_println_map(__isl_take isl_map *const map, void *user) { isl_printer **printer = (isl_printer **)user; *printer = isl_printer_print_map_as_block(*printer, map); isl_map_free(map); return isl_stat_ok; } static inline __isl_give isl_printer *isl_printer_print_union_map_as_block(__isl_give isl_printer *printer, __isl_keep isl_union_map *const map) { isl_union_map_foreach_map(map, isl_println_map, (void *)&printer); return printer; } std::string to_block_string(__isl_keep isl_union_map *const map) { return isl_to_block_str<isl_union_map *, isl_union_map_get_ctx, isl_printer_print_union_map_as_block>(map); } static inline __isl_give isl_printer *isl_printer_print_schedule_constraints_as_block( __isl_give isl_printer *printer, __isl_keep isl_schedule_constraints *const constraints) { isl_union_set *const domain = isl_schedule_constraints_get_domain(constraints); if (domain) { printer = isl_printer_print_str(printer, "domain:\n"); printer = isl_printer_print_union_set(printer, domain); printer = isl_printer_print_str(printer, "\n"); isl_union_set_free(domain); } isl_set *const context = isl_schedule_constraints_get_context(constraints); if (context) { if (!isl_set_plain_is_empty(context)) { printer = isl_printer_print_str(printer, "context:\n"); printer = isl_printer_print_set(printer, context); printer = isl_printer_print_str(printer, "\n"); } isl_set_free(context); } #define _print_constraints_union_map(getter, title) \ do { \ isl_union_map *const _target_map = getter(constraints); \ if (_target_map) { \ if (!isl_union_map_plain_is_empty(_target_map)) { \ const std::string &_target_string = to_block_string(_target_map); \ printer = isl_printer_print_str(printer, title ":\n"); \ printer = isl_printer_print_str(printer, _target_string.c_str()); \ } \ isl_union_map_free(_target_map); \ } \ } while (0) _print_constraints_union_map(isl_schedule_constraints_get_validity, "validity"); _print_constraints_union_map(isl_schedule_constraints_get_proximity, "proximity"); _print_constraints_union_map(isl_schedule_constraints_get_coincidence, "coincidence"); _print_constraints_union_map(isl_schedule_constraints_get_conditional_validity, "conditional validity"); _print_constraints_union_map(isl_schedule_constraints_get_conditional_validity_condition, "conditional validity condition"); #undef _print_constraints_union_map return printer; } std::string to_block_string(__isl_keep isl_schedule_constraints *const constraints) { const std::string result = isl_to_block_str<isl_schedule_constraints *, isl_schedule_constraints_get_ctx, isl_printer_print_schedule_constraints_as_block>(constraints); return result; } //////////////////////////////////////////////////////////////////////////////// // local definitions //////////////////////////////////////////////////////////////////////////////// __isl_give isl_multi_union_pw_aff *isl_multi_union_pw_aff_collapse(__isl_take isl_multi_union_pw_aff *aff, int dim, __isl_take isl_val *val) { if (!aff) { return aff; } const isl_size count = isl_multi_union_pw_aff_size(aff); if (!count || dim >= count - 1) { return aff; } isl_union_pw_aff *const target_1 = isl_multi_union_pw_aff_get_at(aff, dim); isl_union_pw_aff *const target_2 = isl_multi_union_pw_aff_get_at(aff, dim + 1); isl_union_pw_aff_dump(target_1); isl_union_pw_aff_dump(target_2); isl_union_pw_aff *const scaled = isl_union_pw_aff_scale_val(target_1, val); isl_union_pw_aff *const collapsed = isl_union_pw_aff_add(scaled, target_2); isl_union_pw_aff_dump(collapsed); const isl_size size = isl_multi_union_pw_aff_size(aff); isl_union_pw_aff_list *list = NULL; if (dim != 0) { isl_union_pw_aff *const first = isl_multi_union_pw_aff_get_at(aff, 0); list = isl_union_pw_aff_list_from_union_pw_aff(first); for (isl_size i = 1; i < dim; ++i) { isl_union_pw_aff *const current = isl_multi_union_pw_aff_get_at(aff, i); list = isl_union_pw_aff_list_add(list, current); } list = isl_union_pw_aff_list_add(list, collapsed); } else { list = isl_union_pw_aff_list_from_union_pw_aff(collapsed); } for (isl_size i = dim + 2; i < size; ++i) { isl_union_pw_aff *const current = isl_multi_union_pw_aff_get_at(aff, i); list = isl_union_pw_aff_list_add(list, current); } isl_ctx *const ctx = isl_multi_union_pw_aff_get_ctx(aff); isl_space *const original_space = isl_multi_union_pw_aff_get_space(aff); const isl_size params = isl_space_dim(original_space, isl_dim_param); const isl_size new_size = isl_union_pw_aff_list_size(list); isl_space *const space = isl_space_set_alloc(ctx, params, new_size); isl_multi_union_pw_aff *const result = isl_multi_union_pw_aff_from_union_pw_aff_list(space, list); isl_space_free(original_space); isl_multi_union_pw_aff_free(aff); return result; } __isl_give isl_val *isl_schedule_node_band_find_collapse_coeff(__isl_take isl_schedule_node *band, int dim) { isl_union_set *domain = isl_schedule_node_get_domain(band); isl_multi_union_pw_aff *const prefix = isl_schedule_node_get_prefix_schedule_multi_union_pw_aff(band); const isl_size prefix_size = isl_multi_union_pw_aff_size(prefix); isl_multi_union_pw_aff *partial = isl_schedule_node_band_get_partial_schedule(band); isl_multi_union_pw_aff *const schedule = isl_multi_union_pw_aff_cat(prefix, partial); isl_union_map *const map = isl_union_map_from_multi_union_pw_aff(schedule); domain = isl_union_set_apply(domain, map); isl_union_set *const union_lexmax = isl_union_set_lexmax(domain); isl_set *const lexmax = isl_set_from_union_set(union_lexmax); const isl_size target = prefix_size + dim + 1; isl_val *coeff = isl_set_plain_get_val_if_fixed(lexmax, isl_dim_set, target); coeff = isl_val_add_ui(coeff, 1); isl_set_free(lexmax); return coeff; } isl_stat isl_pw_aff_fine_adjustment(__isl_take isl_pw_aff *pa, void *user) { struct isl_schedule_node_fine_adjustment_data *arg = (struct isl_schedule_node_fine_adjustment_data *)user; isl_id *const id = isl_pw_aff_get_tuple_id(pa, isl_dim_in); const char *const name = isl_id_get_name(id); if (!strcmp(name, arg->name)) { isl_val *const val = isl_val_copy(arg->value); if (arg->type == FINE_ADJUSTMENT_SCALE_DOWN) { pa = isl_pw_aff_scale_down_val(pa, val); } else if (arg->type == FINE_ADJUSTMENT_MOD) { pa = isl_pw_aff_mod_val(pa, val); } else if (arg->type == FINE_ADJUSTMENT_SCALE) { pa = isl_pw_aff_scale_val(pa, val); } else { fprintf(stderr, "%s: unknown adjustment operation!\n", __func__); } } isl_id_free(id); if (arg->result) { arg->result = isl_union_pw_aff_add_pw_aff(arg->result, pa); } else { arg->result = isl_union_pw_aff_from_pw_aff(pa); } return isl_stat_ok; } //////////////////////////////////////////////////////////////////////////////// // "special" definitions //////////////////////////////////////////////////////////////////////////////// // clang-format off #define _define_isl_schedule_node_band_fine(name, type) \ isl::schedule_node_band isl_schedule_node_band_fine_##name( \ const isl::schedule_node_band &band, const std::string &name, unsigned int dim, int value) { \ const isl::schedule_node_band &result = isl_schedule_node_band_fine_adjustment(band, type, name, dim, value); \ return result; \ } \ \ isl::schedule_node_band isl_schedule_node_band_fine_##name( \ const isl::schedule_node_band &band, const std::string &name, unsigned int dim, const isl::val &value) { \ const isl::schedule_node_band &result = isl_schedule_node_band_fine_adjustment(band, type, name, dim, value); \ return result; \ } _define_isl_schedule_node_band_fine(mod, FINE_ADJUSTMENT_MOD) _define_isl_schedule_node_band_fine(scale, FINE_ADJUSTMENT_SCALE) _define_isl_schedule_node_band_fine(scale_down, FINE_ADJUSTMENT_SCALE_DOWN) #undef _define_isl_schedule_node_band_fine } // namespace poly } // namespace ir } // namespace akg
40,874
13,824
#include "stdafx.h" // General #include "DX11_Creator.h" // Additional #include "DX11\\RenderDeviceDX11.h" #include "DX11\\RenderWindowDX11.h" RenderDevice* DX11_Creator::CreateRenderDevice() { return new RenderDeviceDX11(); } RenderWindow* DX11_Creator::CreateRenderWindow(HWND hWnd, RenderDevice* device, cstring windowName, int windowWidth, int windowHeight, bool vSync) { RenderDeviceDX11* pDevice = dynamic_cast<RenderDeviceDX11*>(device); return new RenderWindowDX11(hWnd, pDevice, windowName, windowWidth, windowHeight, vSync); }
545
209
#include "cbase.h" #include "neo_controlpoint.h" #include "neo_gamerules.h" IMPLEMENT_NETWORKCLASS_ALIASED( NeoControlPoint, DT_NeoControlPoint ) BEGIN_NETWORK_TABLE( CNeoControlPoint, DT_NeoControlPoint ) #ifdef CLIENT_DLL //RecvPropStringT( RECVINFO( m_Name ) ), RecvPropInt( RECVINFO( m_ID ) ), RecvPropVector( RECVINFO( m_Position ) ), RecvPropInt( RECVINFO( m_Icon ) ), RecvPropInt( RECVINFO( m_Status ) ), RecvPropInt( RECVINFO( m_Owner ) ), RecvPropInt( RECVINFO( m_Radius ) ), #else //SendPropStringT( SENDINFO( m_Name ) ), SendPropInt( SENDINFO( m_ID ) ), SendPropVector( SENDINFO( m_Position ) ), SendPropInt( SENDINFO( m_Icon ) ), SendPropInt( SENDINFO( m_Status ) ), SendPropInt( SENDINFO( m_Owner ) ), SendPropInt( SENDINFO( m_Radius ) ), #endif END_NETWORK_TABLE() LINK_ENTITY_TO_CLASS( neo_controlpoint, CNeoControlPoint ); #ifdef GAME_DLL BEGIN_DATADESC( CNeoControlPoint ) END_DATADESC() #endif CNeoControlPoint::CNeoControlPoint() { m_Status = 0; m_Owner = 0; } #ifdef GAME_DLL int CNeoControlPoint::UpdateTransmitState() { return SetTransmitState( FL_EDICT_ALWAYS ); } #endif void CNeoControlPoint::Activate() { #ifdef CLIENT_DLL DevMsg( "Client CP %s Activated\n", m_Name ); #else DevMsg( "Server CP %s Activated\n", m_Name ); #endif #ifdef GAME_DLL m_Position = GetAbsOrigin(); if ( m_Icon < 0 || m_Icon > 11 ) m_Icon = 0; #endif NEOGameRules()->AddControlPoint( this ); BaseClass::Activate(); } bool CNeoControlPoint::UpdatePointOwner() { #ifdef GAME_DLL CBaseEntity* pEntities[ 256 ]; int count = UTIL_EntitiesInBox( pEntities, 256, GetAbsOrigin(), m_Position, 0 ); for ( int i = 0; i < count; i++ ) { CNEOPlayer* pPlayer = (CNEOPlayer*) pEntities[ i ]; if ( !pPlayer || !pPlayer->IsPlayer() ) continue; m_Owner = pPlayer->GetTeamNumber(); return true; } #endif return false; }
1,883
823
#pragma once #include <boost/optional.hpp> #include <common/Singleton.hpp> #include "common/Aliases.hpp" #include "util/QStringHash.hpp" #include <map> #include <memory> #include <shared_mutex> #include <unordered_map> #include <vector> #include <QColor> namespace chatterino { struct Emote; using EmotePtr = std::shared_ptr<const Emote>; class FfzBadges : public Singleton { public: virtual void initialize(Settings &settings, Paths &paths) override; FfzBadges() = default; boost::optional<EmotePtr> getBadge(const UserId &id); boost::optional<QColor> getBadgeColor(const UserId &id); private: void loadFfzBadges(); std::shared_mutex mutex_; std::unordered_map<QString, int> badgeMap; std::vector<EmotePtr> badges; std::unordered_map<int, QColor> colorMap; }; } // namespace chatterino
836
298
// Created on: 2016-03-30 // Created by: Irina KRYLOVA // Copyright (c) 2016 OPEN CASCADE SAS // // This file is part of Open CASCADE Technology software library. // // This library is free software; you can redistribute it and/or modify it under // the terms of the GNU Lesser General Public License version 2.1 as published // by the Free Software Foundation, with special exception defined in the file // OCCT_LGPL_EXCEPTION.txt. Consult the file LICENSE_LGPL_21.txt included in OCCT // distribution for complete text of the license and disclaimer of any warranty. // // Alternatively, this file may be used under the terms of Open CASCADE // commercial license or contractual agreement. #ifndef _StepBasic_ProductDefinitionReference_HeaderFile #define _StepBasic_ProductDefinitionReference_HeaderFile #include <Standard.hxx> #include <Standard_Type.hxx> #include <Standard_Boolean.hxx> #include <Standard_Transient.hxx> class TCollection_HAsciiString; class StepBasic_ExternalSource; class StepBasic_ProductDefinitionReference; DEFINE_STANDARD_HANDLE(StepBasic_ProductDefinitionReference, Standard_Transient) //! Representation of STEP entity Product_Definition_Reference class StepBasic_ProductDefinitionReference : public Standard_Transient { public: //! Empty constructor Standard_EXPORT StepBasic_ProductDefinitionReference(); //! Initialize all fields (own and inherited) Standard_EXPORT void Init (const Handle(StepBasic_ExternalSource)& theSource, const Handle(TCollection_HAsciiString)& theProductId, const Handle(TCollection_HAsciiString)& theProductDefinitionFormationId, const Handle(TCollection_HAsciiString)& theProductDefinitionId, const Handle(TCollection_HAsciiString)& theIdOwningOrganizationName); //! Initialize all fields (own and inherited) Standard_EXPORT void Init (const Handle(StepBasic_ExternalSource)& theSource, const Handle(TCollection_HAsciiString)& theProductId, const Handle(TCollection_HAsciiString)& theProductDefinitionFormationId, const Handle(TCollection_HAsciiString)& theProductDefinitionId); //! Returns field Source inline Handle(StepBasic_ExternalSource) Source() const { return mySource; } //! Set field Source inline void SetSource (const Handle(StepBasic_ExternalSource)& theSource) { mySource = theSource; } //! Returns field ProductId inline Handle(TCollection_HAsciiString) ProductId() const { return myProductId; } //! Set field ProductId inline void SetProductId (const Handle(TCollection_HAsciiString)& theProductId) { myProductId = theProductId; } //! Returns field ProductDefinitionFormationId inline Handle(TCollection_HAsciiString) ProductDefinitionFormationId() const { return myProductDefinitionFormationId; } //! Set field ProductDefinitionFormationId inline void SetProductDefinitionFormationId (const Handle(TCollection_HAsciiString)& theProductDefinitionFormationId) { myProductDefinitionFormationId = theProductDefinitionFormationId; } //! Returns field ProductDefinitionId inline Handle(TCollection_HAsciiString) ProductDefinitionId() const { return myProductDefinitionId; } //! Set field ProductDefinitionId inline void SetProductDefinitionId (const Handle(TCollection_HAsciiString)& theProductDefinitionId) { myProductDefinitionId = theProductDefinitionId; } //! Returns field IdOwningOrganizationName inline Handle(TCollection_HAsciiString) IdOwningOrganizationName() const { return myIdOwningOrganizationName; } //! Set field IdOwningOrganizationName inline void SetIdOwningOrganizationName (const Handle(TCollection_HAsciiString)& theIdOwningOrganizationName) { myIdOwningOrganizationName = theIdOwningOrganizationName; hasIdOwningOrganizationName = (!theIdOwningOrganizationName.IsNull()); } //! Returns true if IdOwningOrganizationName exists inline Standard_Boolean HasIdOwningOrganizationName() const { return hasIdOwningOrganizationName; } DEFINE_STANDARD_RTTIEXT(StepBasic_ProductDefinitionReference, Standard_Transient) private: Handle(StepBasic_ExternalSource) mySource; Handle(TCollection_HAsciiString) myProductId; Handle(TCollection_HAsciiString) myProductDefinitionFormationId; Handle(TCollection_HAsciiString) myProductDefinitionId; Handle(TCollection_HAsciiString) myIdOwningOrganizationName; Standard_Boolean hasIdOwningOrganizationName; }; #endif // _StepBasic_ProductDefinitionReference_HeaderFile
4,728
1,332
// timer.cpp // E64 // // Copyright © 2019-2022 elmerucr. All rights reserved. #include "timer.hpp" #include "common.hpp" E64::timer_ic::timer_ic(exceptions_ic *unit) { exceptions = unit; irq_number = exceptions->connect_device(); } void E64::timer_ic::reset() { registers[0] = 0x00; // No pending irq's registers[1] = 0x00; // All timers turned off // load data register with value 1 bpm (may never be zero) registers[2] = 0x00; // high byte registers[3] = 0x01; // low byte for (int i=0; i<8; i++) { timers[i].bpm = (registers[2] << 8) | registers[3]; timers[i].clock_interval = bpm_to_clock_interval(timers[i].bpm); timers[i].counter = 0; } exceptions->release(irq_number); } void E64::timer_ic::run(uint32_t number_of_cycles) { for (int i=0; i<8; i++) { timers[i].counter += number_of_cycles; if ((timers[i].counter >= timers[i].clock_interval) && (registers[1] & (0b1 << i))) { timers[i].counter -= timers[i].clock_interval; exceptions->pull(irq_number); registers[0] |= (0b1 << i); } } } uint32_t E64::timer_ic::bpm_to_clock_interval(uint16_t bpm) { return (60.0 / bpm) * VICV_CLOCK_SPEED; } uint8_t E64::timer_ic::read_byte(uint8_t address) { return registers[address & 0x03]; } void E64::timer_ic::write_byte(uint8_t address, uint8_t byte) { switch (address & 0x03) { case 0x00: /* * b s r * 0 0 = 0 * 0 1 = 1 * 1 0 = 0 * 1 1 = 0 * * b = bit that's written * s = status (on if an interrupt was caused) * r = boolean result (acknowledge an interrupt (s=1) if b=1 * r = (~b) & s */ registers[0] = (~byte) & registers[0]; if ((registers[0] & 0xff) == 0) { // no timers left causing interrupts exceptions->release(irq_number); } break; case 0x01: { uint8_t turned_on = byte & (~registers[1]); for (int i=0; i<8; i++) { if (turned_on & (0b1 << i)) { timers[i].bpm = (uint16_t)registers[3] | (registers[2] << 8); if (timers[i].bpm == 0) timers[i].bpm = 1; timers[i].clock_interval = bpm_to_clock_interval(timers[i].bpm); timers[i].counter = 0; } } registers[0x01] = byte; break; } default: registers[address & 0x03] = byte; break; } } uint64_t E64::timer_ic::get_timer_counter(uint8_t timer_number) { return timers[timer_number & 0x07].counter; } uint64_t E64::timer_ic::get_timer_clock_interval(uint8_t timer_number) { return timers[timer_number & 0x07].clock_interval; } void E64::timer_ic::set(uint8_t timer_no, uint16_t bpm) { timer_no &= 0b111; // limit to max 7 write_byte(0x03, bpm & 0xff); write_byte(0x02, (bpm & 0xff00) >> 8); uint8_t byte = read_byte(0x01); write_byte(0x01, (0b1 << timer_no) | byte); } void E64::timer_ic::status(char *buffer, uint8_t timer_no) { timer_no &= 0b00000111; snprintf(buffer, 64, "\n%02x:%s/%5u/%08x/%08x", timer_no, registers[0x01] & (0b1 << timer_no) ? " on" : "off", timers[timer_no].bpm, timers[timer_no].counter, timers[timer_no].clock_interval); }
3,047
1,538
#include "pch.h" #include "Component.h" #include "GameObject.h" #include "avancezlib.h" void CollideComponent::Create(AvancezLib* engine, GameObject* go, std::set<GameObject*>* game_objects, ObjectPool<GameObject>* coll_objects){ Component::Create(engine, go, game_objects); this->coll_objects = coll_objects; } void CollideComponent::Update(float dt){ for (auto i = 0; i < coll_objects->pool.size(); i++){ GameObject * coll_go = coll_objects->pool[i]; if (coll_go->enabled){ if ((go->verticalPos - go->radius) <= coll_go->verticalPos){ if (circleCollide(go, coll_go)){ go->Receive(HIT); coll_go->Receive(HIT); } } } } } //Check if 2 boxes overlap bool CollideComponent::boxCollide(GameObject * go, GameObject * coll_go){ return ((coll_go->horizontalPos > go->horizontalPos - 10) && (coll_go->horizontalPos < go->horizontalPos + 10) && (coll_go->verticalPos > go->verticalPos - 10) && (coll_go->verticalPos < go->verticalPos + 10)); } //Check if point is iside the circle bool CollideComponent::circleCollide(GameObject * go, GameObject * coll_go){ double x_diff = (go->horizontalPos + go->radius) - coll_go->horizontalPos; double y_diff = (go->verticalPos + go->radius) - coll_go->verticalPos; return (std::sqrt(x_diff * x_diff + y_diff * y_diff) <= go->radius); }
1,459
472
#include "blink.hpp" #include "lcd.hpp" #include <avr/io.h> #include <avr/interrupt.h> namespace Blink { namespace { volatile bool blink = false; volatile uint8_t timeout = 0; volatile uint8_t delay = 0; } void init(uint8_t delay) { speed(delay); OCR0A = 0xFF; TCCR0A |= _BV(WGM01); TCCR0B |= _BV(CS02) | _BV(CS00); } void start() { TIMSK0 |= _BV(OCIE0A); blink = true; timeout = 0; } void stop() { TIMSK0 &= ~_BV(OCIE0A); } void speed(uint8_t delay) { Blink::delay = delay; } } ISR (TIMER0_COMPA_vect) { if (Blink::timeout++ == Blink::delay) { LCD::mode(true, Blink::blink = !Blink::blink); Blink::timeout = 0; } }
734
335
#include <iostream> #include <vector> #include <algorithm> #include <string> #include <functional> using namespace std; using std::placeholders::_1; bool check_size(const string& s, int i) { return s.size() < i; } int main() { vector<int> ivec{0, 1, 2, 3, 4, 5, 6}; auto result = find_if(ivec.begin(), ivec.end(), bind(check_size, "01234567", _1)); if (result != ivec.end()) { cout << *result << endl; } else { cout << "Not found" << endl; } return 0; }
511
202
/// /// Copyright (c) 2013, Intel Corporation /// /// Redistribution and use in source and binary forms, with or without /// modification, are permitted provided that the following conditions /// are met: /// /// * Redistributions of source code must retain the above copyright /// notice, this list of conditions and the following disclaimer. /// * Redistributions in binary form must reproduce the above /// copyright notice, this list of conditions and the following /// disclaimer in the documentation and/or other materials provided /// with the distribution. /// * Neither the name of Intel Corporation nor the names of its /// contributors may be used to endorse or promote products /// derived from this software without specific prior written /// permission. /// /// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS 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. ////////////////////////////////////////////////////////////////////// /// /// NAME: transpose /// /// PURPOSE: This program measures the time for the transpose of a /// column-major stored matrix into a row-major stored matrix. /// /// USAGE: Program input is the matrix order and the number of times to /// repeat the operation: /// /// transpose <matrix_size> <# iterations> <variant> /// /// The output consists of diagnostics to make sure the /// transpose worked and timing statistics. /// /// HISTORY: Written by Rob Van der Wijngaart, February 2009. /// Converted to C++11 by Jeff Hammond, February 2016 and May 2017. /// ////////////////////////////////////////////////////////////////////// #include "prk_util.h" const int tile_size = 32; typedef RAJA::Index_type indx; typedef RAJA::RangeSegment range; typedef RAJA::TileList<RAJA::tile_fixed<tile_size>, RAJA::tile_fixed<tile_size>> tile; typedef RAJA::Tile<tile> tiling; typedef RAJA::Tile<tile,RAJA::Permute<RAJA::PERM_IJ>> tiling_ij; typedef RAJA::Tile<tile,RAJA::Permute<RAJA::PERM_JI>> tiling_ji; typedef RAJA::NestedPolicy<RAJA::ExecList<RAJA::seq_exec, RAJA::simd_exec>> seq_for_simd; typedef RAJA::NestedPolicy<RAJA::ExecList<RAJA::seq_exec, RAJA::seq_exec>> seq_for_seq; typedef RAJA::NestedPolicy<RAJA::ExecList<RAJA::seq_exec, RAJA::seq_exec>, tiling> seq_for_seq_tiled; typedef RAJA::NestedPolicy<RAJA::ExecList<RAJA::seq_exec, RAJA::simd_exec>, tiling> seq_for_simd_tiled; typedef RAJA::NestedPolicy<RAJA::ExecList<RAJA::seq_exec, RAJA::seq_exec>, tiling_ij> seq_for_seq_tiled_ij; typedef RAJA::NestedPolicy<RAJA::ExecList<RAJA::seq_exec, RAJA::simd_exec>, tiling_ij> seq_for_simd_tiled_ij; typedef RAJA::NestedPolicy<RAJA::ExecList<RAJA::seq_exec, RAJA::seq_exec>, tiling_ji> seq_for_seq_tiled_ji; typedef RAJA::NestedPolicy<RAJA::ExecList<RAJA::seq_exec, RAJA::simd_exec>, tiling_ji> seq_for_simd_tiled_ji; #ifdef RAJA_ENABLE_OPENMP typedef RAJA::NestedPolicy<RAJA::ExecList<RAJA::omp_parallel_for_exec, RAJA::seq_exec>> omp_for_seq; typedef RAJA::NestedPolicy<RAJA::ExecList<RAJA::omp_parallel_for_exec, RAJA::simd_exec>> omp_for_simd; typedef RAJA::NestedPolicy<RAJA::ExecList<RAJA::omp_parallel_for_exec, RAJA::seq_exec>, tiling> omp_for_seq_tiled; typedef RAJA::NestedPolicy<RAJA::ExecList<RAJA::omp_parallel_for_exec, RAJA::simd_exec>, tiling> omp_for_simd_tiled; typedef RAJA::NestedPolicy<RAJA::ExecList<RAJA::omp_parallel_for_exec, RAJA::seq_exec>, tiling_ij> omp_for_seq_tiled_ij; typedef RAJA::NestedPolicy<RAJA::ExecList<RAJA::omp_parallel_for_exec, RAJA::simd_exec>, tiling_ij> omp_for_simd_tiled_ij; typedef RAJA::NestedPolicy<RAJA::ExecList<RAJA::omp_parallel_for_exec, RAJA::seq_exec>, tiling_ji> omp_for_seq_tiled_ji; typedef RAJA::NestedPolicy<RAJA::ExecList<RAJA::omp_parallel_for_exec, RAJA::simd_exec>, tiling_ji> omp_for_simd_tiled_ji; #endif #ifdef RAJA_ENABLE_TBB typedef RAJA::NestedPolicy<RAJA::ExecList<RAJA::tbb_for_exec, RAJA::seq_exec>> tbb_for_seq; typedef RAJA::NestedPolicy<RAJA::ExecList<RAJA::tbb_for_exec, RAJA::simd_exec>> tbb_for_simd; typedef RAJA::NestedPolicy<RAJA::ExecList<RAJA::tbb_for_exec, RAJA::seq_exec>, tiling> tbb_for_seq_tiled; typedef RAJA::NestedPolicy<RAJA::ExecList<RAJA::tbb_for_exec, RAJA::simd_exec>, tiling> tbb_for_simd_tiled; typedef RAJA::NestedPolicy<RAJA::ExecList<RAJA::tbb_for_exec, RAJA::seq_exec>, tiling_ij> tbb_for_seq_tiled_ij; typedef RAJA::NestedPolicy<RAJA::ExecList<RAJA::tbb_for_exec, RAJA::simd_exec>, tiling_ij> tbb_for_simd_tiled_ij; typedef RAJA::NestedPolicy<RAJA::ExecList<RAJA::tbb_for_exec, RAJA::seq_exec>, tiling_ji> tbb_for_seq_tiled_ji; typedef RAJA::NestedPolicy<RAJA::ExecList<RAJA::tbb_for_exec, RAJA::simd_exec>, tiling_ji> tbb_for_simd_tiled_ji; typedef RAJA::NestedPolicy<RAJA::ExecList<RAJA::tbb_for_dynamic, RAJA::seq_exec>> tbb_for_dynamic_seq; typedef RAJA::NestedPolicy<RAJA::ExecList<RAJA::tbb_for_dynamic, RAJA::simd_exec>> tbb_for_dynamic_simd; typedef RAJA::NestedPolicy<RAJA::ExecList<RAJA::tbb_for_dynamic, RAJA::seq_exec>, tiling> tbb_for_dynamic_seq_tiled; typedef RAJA::NestedPolicy<RAJA::ExecList<RAJA::tbb_for_dynamic, RAJA::simd_exec>, tiling> tbb_for_dynamic_simd_tiled; #endif template <typename exec_policy, typename LoopBody> void Lambda(int order, LoopBody body) { RAJA::forallN<exec_policy>( range(0, order), range(0, order), body); } template <typename exec_policy> void Initialize(int order, std::vector<double> & A, std::vector<double> & B) { Lambda<exec_policy>(order, [=,&A,&B](int i, int j) { A[i*order+j] = static_cast<double>(i*order+j); B[i*order+j] = 0.0; }); } template <typename exec_policy> void Transpose(int order, std::vector<double> & A, std::vector<double> & B) { Lambda<exec_policy>(order, [=,&A,&B](int i, int j) { B[i*order+j] += A[j*order+i]; A[j*order+i] += 1.0; }); } template <typename outer_policy, typename inner_policy> void Initialize(int order, std::vector<double> & A, std::vector<double> & B) { RAJA::forall<outer_policy>(0, order, [=,&A,&B](int i) { RAJA::forall<inner_policy>(0, order, [=,&A,&B](int j) { A[i*order+j] = static_cast<double>(i*order+j); B[i*order+j] = 0.0; }); }); } template <typename outer_policy, typename inner_policy> void Transpose(int order, std::vector<double> & A, std::vector<double> & B) { RAJA::forall<outer_policy>(0, order, [=,&A,&B](int i) { RAJA::forall<inner_policy>(0, order, [=,&A,&B](int j) { B[i*order+j] += A[j*order+i]; A[j*order+i] += 1.0; }); }); } template <typename loop_policy, typename reduce_policy> double Error(int iterations, int order, std::vector<double> & B) { RAJA::ReduceSum<reduce_policy, double> abserr(0.0); typedef RAJA::NestedPolicy<RAJA::ExecList<loop_policy, RAJA::seq_exec>> exec_policy; RAJA::forallN<exec_policy>( range(0, order), range(0, order), [=,&B](int i, int j) { const auto dij = static_cast<double>(i*order+j); const auto addit = (iterations+1.) * (0.5*iterations); const auto reference = dij*(1.+iterations)+addit; abserr += std::fabs(B[j*order+i] - reference); }); return abserr; } int main(int argc, char * argv[]) { std::cout << "Parallel Research Kernels version " << PRKVERSION << std::endl; std::cout << "C++11/RAJA Matrix transpose: B = A^T" << std::endl; ////////////////////////////////////////////////////////////////////// /// Read and test input parameters ////////////////////////////////////////////////////////////////////// if (argc < 3) { std::cerr << "Usage: <# iterations> <matrix order> "; std::cerr << "<for={seq,omp,tbb,tbbdyn} nested={y,n} tiled={y,n} permute={no,ij,ji} simd={y,n}>\n"; std::cerr << "Caveat: tiled/permute only supported for nested=y.\n"; std::cerr << "Feature: RAJA args (foo=bar) can be given in any order.\n"; return argc; } int iterations, order; std::string use_for="seq", use_permute="no"; auto use_simd=true, use_nested=true, use_tiled=false; try { // number of times to do the transpose iterations = std::atoi(argv[1]); if (iterations < 1) { throw "ERROR: iterations must be >= 1"; } // order of a the matrix order = std::atoi(argv[2]); if (order <= 0) { throw "ERROR: Matrix Order must be greater than 0"; } else if (order > std::floor(std::sqrt(INT_MAX))) { throw "ERROR: matrix dimension too large - overflow risk"; } // RAJA implementation variant for (int i=3; i<argc; ++i) { //std::cout << "argv[" << i << "] = " << argv[i] << "\n"; auto s = std::string(argv[i]); auto pf = s.find("for="); if (pf != std::string::npos) { auto sf = s.substr(4,s.size()); //std::cout << pf << "," << sf << "\n"; if (sf=="omp" || sf=="openmp") { #ifdef RAJA_ENABLE_OPENMP use_for="omp"; #else std::cerr << "You are trying to use OpenMP but RAJA does not support it!" << std::endl; #endif } if (sf=="tbb") { #ifdef RAJA_ENABLE_TBB use_for="tbb"; #else std::cerr << "You are trying to use TBB but RAJA does not support it!" << std::endl; #endif } if (sf=="tbbdyn") { #ifdef RAJA_ENABLE_TBB use_for="tbbdyn"; #else std::cerr << "You are trying to use TBB but RAJA does not support it!" << std::endl; #endif } } auto ps = s.find("simd="); if (ps != std::string::npos) { auto ss = s.substr(5,s.size()); //std::cout << ps << "," << ss[0] << "\n"; if (ss=="n") use_simd=false; if (ss=="np") use_simd=false; } auto pn = s.find("nested="); if (pn != std::string::npos) { auto sn = s.substr(7,s.size()); //std::cout << pn << "," << sn[0] << "\n"; if (sn=="n") use_nested=false; if (sn=="no") use_nested=false; } auto pt = s.find("tiled="); if (pt != std::string::npos) { auto st = s.substr(6,s.size()); //std::cout << pt << "," << st[0] << "\n"; if (st=="y") use_tiled=true; if (st=="yes") use_tiled=true; } auto pp = s.find("permute="); if (pp != std::string::npos) { auto sp = s.substr(8,s.size()); //std::cout << pp << "," << pp[0] << "\n"; if (sp=="ij") use_permute="ij"; if (sp=="ji") use_permute="ji"; } } } catch (const char * e) { std::cout << e << std::endl; return 1; } std::string for_name = "Sequential"; if (use_for=="omp") for_name = "OpenMP"; if (use_for=="tbb") for_name = "TBB (static)"; if (use_for=="tbbdyn") for_name = "TBB (dynamic)"; std::cout << "Number of iterations = " << iterations << std::endl; std::cout << "Matrix order = " << order << std::endl; std::cout << "Tile size = " << tile_size << "(compile-time constant, unlike other impls)" << std::endl; std::cout << "RAJA threading = " << for_name << std::endl; std::cout << "RAJA forallN = " << (use_nested ? "yes" : "no") << std::endl; std::cout << "RAJA use tiling = " << (use_tiled ? "yes" : "no") << std::endl; std::cout << "RAJA use permute = " << use_permute << std::endl; std::cout << "RAJA use simd = " << (use_simd ? "yes" : "no") << std::endl; ////////////////////////////////////////////////////////////////////// /// Allocate space for the input and transpose matrix ////////////////////////////////////////////////////////////////////// std::vector<double> A(order*order); std::vector<double> B(order*order); if (use_for=="seq") { if (use_nested) { if (use_tiled) { if (use_permute=="no") { if (use_simd) { Initialize<seq_for_simd_tiled>(order, A, B); } else { Initialize<seq_for_seq_tiled>(order, A, B); } } else if (use_permute=="ij") { if (use_simd) { Initialize<seq_for_simd_tiled_ij>(order, A, B); } else { Initialize<seq_for_seq_tiled_ij>(order, A, B); } } else if (use_permute=="ji") { if (use_simd) { Initialize<seq_for_simd_tiled_ji>(order, A, B); } else { Initialize<seq_for_seq_tiled_ji>(order, A, B); } } } else { if (use_simd) { Initialize<seq_for_simd>(order, A, B); } else { Initialize<seq_for_seq>(order, A, B); } } } else /* !use_nested */ { if (use_simd) { Initialize<RAJA::seq_exec,RAJA::simd_exec>(order, A, B); } else { Initialize<RAJA::seq_exec,RAJA::seq_exec>(order, A, B); } } } #ifdef RAJA_ENABLE_OPENMP else if (use_for=="omp") { if (use_nested) { if (use_tiled) { if (use_permute=="no") { if (use_simd) { Initialize<omp_for_simd_tiled>(order, A, B); } else { Initialize<omp_for_seq_tiled>(order, A, B); } } else if (use_permute=="ij") { if (use_simd) { Initialize<omp_for_simd_tiled_ij>(order, A, B); } else { Initialize<omp_for_seq_tiled_ij>(order, A, B); } } else if (use_permute=="ji") { if (use_simd) { Initialize<omp_for_simd_tiled_ji>(order, A, B); } else { Initialize<omp_for_seq_tiled_ji>(order, A, B); } } } else { if (use_simd) { Initialize<omp_for_simd>(order, A, B); } else { Initialize<omp_for_seq>(order, A, B); } } } else /* !use_nested */ { if (use_simd) { Initialize<RAJA::omp_parallel_for_exec,RAJA::simd_exec>(order, A, B); } else { Initialize<RAJA::omp_parallel_for_exec,RAJA::seq_exec>(order, A, B); } } } #endif #ifdef RAJA_ENABLE_TBB else if (use_for=="tbb") { if (use_nested) { if (use_tiled) { if (use_permute=="no") { if (use_simd) { Initialize<tbb_for_simd_tiled>(order, A, B); } else { Initialize<tbb_for_seq_tiled>(order, A, B); } } else if (use_permute=="ij") { if (use_simd) { Initialize<tbb_for_simd_tiled_ij>(order, A, B); } else { Initialize<tbb_for_seq_tiled_ij>(order, A, B); } } else if (use_permute=="ji") { if (use_simd) { Initialize<tbb_for_simd_tiled_ji>(order, A, B); } else { Initialize<tbb_for_seq_tiled_ji>(order, A, B); } } } else { if (use_simd) { Initialize<tbb_for_simd>(order, A, B); } else { Initialize<tbb_for_seq>(order, A, B); } } } else /* !use_nested */ { if (use_simd) { Initialize<RAJA::tbb_for_exec,RAJA::simd_exec>(order, A, B); } else { Initialize<RAJA::tbb_for_exec,RAJA::seq_exec>(order, A, B); } } } else if (use_for=="tbbdyn") { if (use_nested) { if (use_tiled) { if (use_simd) { Initialize<tbb_for_dynamic_simd_tiled>(order, A, B); } else { Initialize<tbb_for_dynamic_seq_tiled>(order, A, B); } } else { if (use_simd) { Initialize<tbb_for_dynamic_simd>(order, A, B); } else { Initialize<tbb_for_dynamic_seq>(order, A, B); } } } else /* !use_nested */ { if (use_simd) { Initialize<RAJA::tbb_for_dynamic,RAJA::simd_exec>(order, A, B); } else { Initialize<RAJA::tbb_for_dynamic,RAJA::seq_exec>(order, A, B); } } } #endif auto trans_time = 0.0; for (auto iter = 0; iter<=iterations; iter++) { if (iter==1) trans_time = prk::wtime(); // transpose if (use_for=="seq") { if (use_nested) { if (use_tiled) { if (use_permute=="no") { if (use_simd) { Transpose<seq_for_simd_tiled>(order, A, B); } else { Transpose<seq_for_seq_tiled>(order, A, B); } } else if (use_permute=="ij") { if (use_simd) { Transpose<seq_for_simd_tiled_ij>(order, A, B); } else { Transpose<seq_for_seq_tiled_ij>(order, A, B); } } else if (use_permute=="ji") { if (use_simd) { Transpose<seq_for_simd_tiled_ji>(order, A, B); } else { Transpose<seq_for_seq_tiled_ji>(order, A, B); } } } else { if (use_simd) { Transpose<seq_for_simd>(order, A, B); } else { Transpose<seq_for_seq>(order, A, B); } } } else /* !use_nested */ { if (use_simd) { Transpose<RAJA::seq_exec,RAJA::simd_exec>(order, A, B); } else { Transpose<RAJA::seq_exec,RAJA::seq_exec>(order, A, B); } } } #ifdef RAJA_ENABLE_OPENMP else if (use_for=="omp") { if (use_nested) { if (use_tiled) { if (use_permute=="no") { if (use_simd) { Transpose<omp_for_simd_tiled>(order, A, B); } else { Transpose<omp_for_seq_tiled>(order, A, B); } } else if (use_permute=="ij") { if (use_simd) { Transpose<omp_for_simd_tiled_ij>(order, A, B); } else { Transpose<omp_for_seq_tiled_ij>(order, A, B); } } else if (use_permute=="ji") { if (use_simd) { Transpose<omp_for_simd_tiled_ji>(order, A, B); } else { Transpose<omp_for_seq_tiled_ji>(order, A, B); } } } else { if (use_simd) { Transpose<omp_for_simd>(order, A, B); } else { Transpose<omp_for_seq>(order, A, B); } } } else /* !use_nested */ { if (use_simd) { Transpose<RAJA::omp_parallel_for_exec,RAJA::simd_exec>(order, A, B); } else { Transpose<RAJA::omp_parallel_for_exec,RAJA::seq_exec>(order, A, B); } } } #endif #ifdef RAJA_ENABLE_TBB else if (use_for=="tbb") { if (use_nested) { if (use_tiled) { if (use_permute=="no") { if (use_simd) { Transpose<tbb_for_simd_tiled>(order, A, B); } else { Transpose<tbb_for_seq_tiled>(order, A, B); } } else if (use_permute=="ij") { if (use_simd) { Transpose<tbb_for_simd_tiled_ij>(order, A, B); } else { Transpose<tbb_for_seq_tiled_ij>(order, A, B); } } else if (use_permute=="ji") { if (use_simd) { Transpose<tbb_for_simd_tiled_ji>(order, A, B); } else { Transpose<tbb_for_seq_tiled_ji>(order, A, B); } } } else { if (use_simd) { Transpose<tbb_for_simd>(order, A, B); } else { Transpose<tbb_for_seq>(order, A, B); } } } else /* !use_nested */ { if (use_simd) { Transpose<RAJA::tbb_for_exec,RAJA::simd_exec>(order, A, B); } else { Transpose<RAJA::tbb_for_exec,RAJA::seq_exec>(order, A, B); } } } else if (use_for=="tbbdyn") { if (use_nested) { if (use_tiled) { if (use_simd) { Transpose<tbb_for_dynamic_simd_tiled>(order, A, B); } else { Transpose<tbb_for_dynamic_seq_tiled>(order, A, B); } } else { if (use_simd) { Transpose<tbb_for_dynamic_simd>(order, A, B); } else { Transpose<tbb_for_dynamic_seq>(order, A, B); } } } else /* !use_nested */ { if (use_simd) { Transpose<RAJA::tbb_for_dynamic,RAJA::simd_exec>(order, A, B); } else { Transpose<RAJA::tbb_for_dynamic,RAJA::seq_exec>(order, A, B); } } } #endif } trans_time = prk::wtime() - trans_time; ////////////////////////////////////////////////////////////////////// /// Analyze and output results ////////////////////////////////////////////////////////////////////// double abserr = 1.0; if (use_for=="seq") { abserr = Error<RAJA::seq_exec,RAJA::seq_reduce>(iterations,order,B); } #if defined(RAJA_ENABLE_OPENMP) else if (use_for=="omp") { abserr = Error<RAJA::omp_parallel_for_exec,RAJA::omp_reduce>(iterations,order,B); } #endif #if defined(RAJA_ENABLE_TBB) else if (use_for=="tbb") { abserr = Error<RAJA::tbb_for_exec,RAJA::tbb_reduce>(iterations,order,B); } else if (use_for=="tbbdyn") { abserr = Error<RAJA::tbb_for_dynamic,RAJA::tbb_reduce>(iterations,order,B); } #endif #ifdef VERBOSE std::cout << "Sum of absolute differences: " << abserr << std::endl; #endif const auto epsilon = 1.0e-8; if (abserr < epsilon) { std::cout << "Solution validates" << std::endl; auto avgtime = trans_time/iterations; auto bytes = (size_t)order * (size_t)order * sizeof(double); std::cout << "Rate (MB/s): " << 1.0e-6 * (2L*bytes)/avgtime << " Avg time (s): " << avgtime << std::endl; } else { std::cout << "ERROR: Aggregate squared error " << abserr << " exceeds threshold " << epsilon << std::endl; return 1; } return 0; } #if 0 RAJA::forallN< RAJA::NestedPolicy< RAJA::ExecList<RAJA::seq_exec, RAJA::seq_exec>, RAJA::Permute<RAJA::PERM_JI> > > ( range(0, order), range(0, order), [=,&A,&B](indx i, indx j) { B[i*order+j] += A[j*order+i]; A[j*order+i] += 1.0; }); RAJA::forallN< RAJA::NestedPolicy< RAJA::ExecList<RAJA::simd_exec, RAJA::simd_exec>, RAJA::Tile< RAJA::TileList<RAJA::tile_fixed<tile_size>, RAJA::tile_fixed<tile_size>>, RAJA::Permute<RAJA::PERM_IJ> > > > ( range(0, order), range(0, order), [=,&A,&B](indx i, indx j) { B[i*order+j] += A[j*order+i]; A[j*order+i] += 1.0; }); RAJA::forallN< RAJA::NestedPolicy< RAJA::ExecList<RAJA::simd_exec, RAJA::simd_exec>, RAJA::Tile< RAJA::TileList<RAJA::tile_fixed<tile_size>, RAJA::tile_fixed<tile_size>>, RAJA::Permute<RAJA::PERM_JI> > > > ( range(0, order), range(0, order), [=,&A,&B](indx i, indx j) { B[i*order+j] += A[j*order+i]; A[j*order+i] += 1.0; }); #endif
24,101
8,941
/* * (C) Copyright 1996-2016 ECMWF. * * This software is licensed under the terms of the Apache Licence Version 2.0 * which can be obtained at http://www.apache.org/licenses/LICENSE-2.0. * In applying this licence, ECMWF does not waive the privileges and immunities * granted to it by virtue of its status as an intergovernmental organisation nor * does it submit to any jurisdiction. */ #include <iostream> #include <ParameterManager.h> #include <XmlMagics.h> #include <XmlReader.h> using namespace std; using namespace magics; class MagicsService { public: MagicsService() : manager_() {} void execute(const string& xml) { try { manager_.execute(xml); } catch (MagicsException& e) { MagLog::error() << e << endl; } } private: XmlMagics manager_; }; static void substitute(string& xml, const string& var, const string& val) { string name = "$" + var; string::size_type index = xml.find(name); int last = 0; while (index != string::npos) { xml.replace(index, name.length(), val); last = index + val.length(); index = xml.find(name, last); } } char nospace(char c) { if (c == ' ') return '_'; return c; } class TempFile { public: TempFile() : filename(tmpnam(0)), ofs(filename) { if (!ofs) return; } ~TempFile() { ofs.close(); remove(filename); } ofstream& operator()() { return ofs; } string name() { return filename; } private: const char* filename; ofstream ofs; }; class Station : public XmlNodeVisitor { public: Station(const XmlNode& node) { date_ = node.getAttribute("date"); time_ = node.getAttribute("time"); template_ = node.getAttribute("template"); if (template_.empty()) template_ = string(getenv("MAGPLUS_HOME")) + "/share/templates/10_days_epsgram.xml"; database_ = node.getAttribute("database"); format_ = node.getAttribute("format"); if (format_.empty()) format_ = "a4"; deterministic_ = node.getAttribute("deterministic"); if (deterministic_.empty()) deterministic_ = "on"; whisker_ = node.getAttribute("whisker"); if (whisker_.empty()) whisker_ = "on"; parameters_ = node.attributes(); } ~Station() {} void visit(const XmlNode& node) { if (node.name() == "station") { ostringstream station; for (XmlNode::DataIterator data = node.firstData(); data != node.lastData(); ++data) station << *data; MagLog::dev() << "title-->" << station.str() << endl; MagLog::dev() << "Plot Station-->" << node.getAttribute("name") << endl; MagLog::dev() << "Template-->" << template_ << endl; try { ifstream test(template_.c_str()); if (!test.good()) { // Try to look in ethe default template directory : template_ = string(getenv("MAGPLUS_HOME")) + "/share/templates/" + template_; MagLog::dev() << "try to find template in system directory-> " << template_ << endl; ifstream defaut(template_.c_str()); if (!defaut.good()) { MagLog::error() << "Can not open template file " << template_ << endl; return; } defaut.close(); } test.close(); ifstream in(template_.c_str()); TempFile file; ofstream& out = file(); static string s; s = ""; char c; while (in.get(c)) { s += c; } ostringstream def; def << INT_MAX; string meta = node.getAttribute("metafile"); #ifdef MAGICS_AIX_XLC meta = ""; #endif meta = (meta.empty()) ? "nometada" : "meta path=\'" + meta + "\'"; MagLog::dev() << "Meta-->" << meta; substitute(s, "meta", meta); string height = (node.getAttribute("height") == "") ? def.str() : node.getAttribute("height"); substitute(s, "height", height); substitute(s, "latitude", node.getAttribute("latitude")); substitute(s, "longitude", node.getAttribute("longitude")); substitute(s, "station", node.getAttribute("name")); substitute(s, "title", station.str()); substitute(s, "date", date_); substitute(s, "time", time_); substitute(s, "format", format_); substitute(s, "deterministic", deterministic_); substitute(s, "whisker", whisker_); for (map<string, string>::iterator param = parameters_.begin(); param != parameters_.end(); ++param) substitute(s, param->first, param->second); string ps = node.getAttribute("psfile"); ps = ps.empty() ? "nops" : "ps fullname=\'" + ps + "\'"; substitute(s, "ps", ps); string pdf = node.getAttribute("pdffile"); pdf = pdf.empty() ? "nopdf" : "pdf fullname=\'" + pdf + "\'"; substitute(s, "pdf", pdf); string gif = node.getAttribute("giffile"); gif = gif.empty() ? "nogif" : "gif fullname=\'" + gif + "\'"; substitute(s, "gif", gif); string png = node.getAttribute("pngfile"); png = png.empty() ? "nopng" : "png fullname=\'" + png + "\'"; substitute(s, "png", png); string svg = node.getAttribute("svgfile"); svg = svg.empty() ? "nosvg" : "svg fullname=\'" + svg + "\'"; substitute(s, "svg", svg); out << s; in.close(); out.flush(); magics_.execute(file.name()); } catch (exception e) { } } } protected: string date_; string time_; string template_; string directory_; string database_; string format_; string deterministic_; string whisker_; MagicsService magics_; map<string, string> parameters_; }; class Eps : public XmlNodeVisitor { public: Eps() {} ~Eps() {} void visit(const XmlNode& node) { MagLog::dev() << "node-->" << node.name() << endl; if (node.name() == "eps") { Station station(node); node.visit(station); } } }; int main(int argc, char** argv) { if (argc < 2) { cout << "Usage: " << argv[0] << " <file.epsml>\n"; exit(1); } string xml = argv[1]; XmlReader reader; XmlTree tree; try { reader.interpret(xml, &tree); } catch (...) { cerr << "metgram : error interpreting file " << xml << "\n"; } Eps metgram; tree.visit(metgram); }
7,221
2,078
// file : xsde/cxx/parser/validating/inheritance-map.hxx // author : Boris Kolpackov <boris@codesynthesis.com> // copyright : Copyright (c) 2005-2011 Code Synthesis Tools CC // license : GNU GPL v2 + exceptions; see accompanying LICENSE file #ifndef XSDE_CXX_PARSER_VALIDATING_INHERITANCE_MAP_HXX #define XSDE_CXX_PARSER_VALIDATING_INHERITANCE_MAP_HXX #include <stddef.h> // size_t #include <xsde/cxx/config.hxx> #include <xsde/cxx/ro-string.hxx> #include <xsde/cxx/hashmap.hxx> namespace xsde { namespace cxx { namespace parser { namespace validating { struct inheritance_map: hashmap { inheritance_map (size_t buckets); void insert (const char* derived, const char* base); bool check (const char* derived, const char* base) const; }; // Translation unit initializer. // struct inheritance_map_init { static inheritance_map* map; static size_t count; inheritance_map_init (); ~inheritance_map_init (); }; inline inheritance_map& inheritance_map_instance (); // Map entry initializer. // struct inheritance_map_entry { inheritance_map_entry (const char* derived, const char* base); }; } } } } #include <xsde/cxx/parser/validating/inheritance-map.ixx> #endif // XSDE_CXX_PARSER_VALIDATING_INHERITANCE_MAP_HXX
1,488
495
/* * Copyright 2021 Oleg Zharkov * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://www.apache.org/licenses/LICENSE-2.0 * * or in the "license" file accompanying this file. This file 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 "nids.h" boost::lockfree::spsc_queue<string> q_logs_nids{LOG_QUEUE_SIZE}; int Nids::Open() { char level[OS_HEADER_SIZE]; if (!sk.Open()) return 0; if (surilog_status == 1) { fp = fopen(suri_log, "r"); if(fp == NULL) { SysLog("failed open suricata log file"); return status = 0; } fseek(fp,0,SEEK_END); stat(suri_log, &buf); file_size = (unsigned long) buf.st_size; if (redis_status == 1) { c = redisConnect(sk.redis_host, sk.redis_port); if (c != NULL && c->err) { // handle error sprintf(level, "failed open redis server interface: %s\n", c->errstr); SysLog(level); redis_status = 0; status = 1; } else status = 2; } } else { if (redis_status == 1) { c = redisConnect(sk.redis_host, sk.redis_port); if (c != NULL && c->err) { // handle error sprintf(level, "failed open redis server interface: %s\n", c->errstr); SysLog(level); status = 0; } } else status = 0; } if (maxmind_status) { gi = GeoIP_open(maxmind_path, GEOIP_INDEX_CACHE); if (gi == NULL) { SysLog("error opening maxmind database\n"); maxmind_status = false; } } return status; } void Nids::Close() { sk.Close(); if (status > 0) { if (surilog_status == 1) { if (fp != NULL) fclose(fp); } if (redis_status == 1) redisFree(c); status = 0; } } void Nids::IsFileModified() { int ret = stat(suri_log, &buf); if (ret == 0) { unsigned long current_size = (unsigned long) buf.st_size; if (current_size < file_size) { if (fp != NULL) fclose(fp); fp = fopen(suri_log, "r"); if (fp == NULL) return; else { fseek(fp,0,SEEK_SET); int ret = stat(suri_log, &buf); if (ret != 0) { fp = NULL; return; } file_size = (unsigned long) buf.st_size; return; } } file_size = current_size; return; } fp = NULL; } int Nids::ReadFile() { if (fp == NULL) IsFileModified(); else { if (fgets(file_payload, OS_PAYLOAD_SIZE, fp) != NULL) { ferror_counter = 0; return 1; } else ferror_counter++; if(ferror_counter > EOF_COUNTER) { IsFileModified(); ferror_counter = 0; } } return 0; } int Nids::Go(void) { int read_res = 0; int pars_res = 0; ClearRecords(); if (status) { if (surilog_status == 1) { read_res = ReadFile(); if (read_res == -1) { SysLog("failed reading suricata events from log"); return 1; } if (read_res > 0) { pars_res = ParsJson(1); if (pars_res > 0) ProcessEvent(pars_res); } } if (redis_status == 1) { if (read_res > 0) ClearRecords(); // read Suricata data reply = (redisReply *) redisCommand( c, (const char *) redis_key.c_str()); if (!reply) { SysLog("failed reading suricata events from redis"); freeReplyObject(reply); return 1; } if (reply->type == REDIS_REPLY_STRING) { read_res = 1; pars_res = ParsJson(2); if (pars_res > 0) ProcessEvent(pars_res); } freeReplyObject(reply); } if (read_res == 0) { usleep(GetGosleepTimer()*60); alerts_counter = 0; return 1; } } else usleep(GetGosleepTimer()*60); return 1; } void Nids::ProcessEvent(int pars_res) { GrayList* gl; int severity; IncrementEventsCounter(); boost::shared_lock<boost::shared_mutex> lock(fs.filters_update); if (fs.filter.nids.log) CreateLogPayload(pars_res); if (pars_res == 1 && alerts_counter <= sk.alerts_threshold) { gl = CheckGrayList(); severity = PushIdsRecord(gl); if (gl != NULL) { if (gl->rsp.profile.compare("suppress") != 0) { SendAlert(severity, gl); } } else { if (fs.filter.nids.severity.threshold <= severity) SendAlert(severity, NULL); } if (sk.alerts_threshold != 0) { if (alerts_counter < sk.alerts_threshold) alerts_counter++; else { SendAlertMultiple(2); alerts_counter++; } } } } GrayList* Nids::CheckGrayList() { if (fs.filter.nids.gl.size() != 0) { std::vector<GrayList*>::iterator i, end; for (i = fs.filter.nids.gl.begin(), end = fs.filter.nids.gl.end(); i != end; ++i) { int event_id = std::stoi((*i)->event); if (event_id == rec.alert.signature_id) { string host = (*i)->host; if (host.compare("indef") == 0 || host.compare(rec.dst_ip) == 0 || host.compare(rec.src_ip) == 0) { string match = (*i)->match; if (match.compare("indef") == 0) return (*i); else { size_t found = jsonPayload.find(match); if (found != std::string::npos) return (*i); } } } } } return NULL; } int Nids::ParsJson (int output_type) { if (output_type == 1) { jsonPayload.assign(file_payload, GetBufferSize(file_payload)); } else { jsonPayload.assign(reply->str, GetBufferSize(reply->str)); } try { ss << jsonPayload; bpt::read_json(ss, pt); } catch (const std::exception & ex) { ResetStream(); SysLog((char*) ex.what()); return 0; } bool is_aws_firewall = false; string firewall_name = "indef"; if (output_type == 2) { firewall_name = pt.get<string>("firewall_name","indef"); if (firewall_name.compare("indef") != 0) { is_aws_firewall = true; ss1 << jsonPayload; bpt::read_json(ss1, pt1); pt = pt1.get_child("event"); } if (!is_aws_firewall) firewall_name = pt.get<string>("sensor-name","indef"); rec.sensor = probe_id + "." + firewall_name; } else { rec.sensor = probe_id + ".nids"; } string event_type = pt.get<string>("event_type",""); if (event_type.compare("alert") == 0) { rec.event_type = 1; rec.time_stamp = pt.get<string>("timestamp",""); rec.iface = pt.get<string>("in_iface",""); rec.flow_id = pt.get<long>("flow_id",0); rec.src_ip = pt.get<string>("src_ip",""); rec.src_hostname = GetHostname(rec.src_ip); SetGeoBySrcIp(rec.src_ip); rec.src_port = pt.get<int>("src_port",0); rec.dst_ip = pt.get<string>("dest_ip",""); rec.dst_hostname = GetHostname(rec.dst_ip); SetGeoByDstIp(rec.dst_ip); rec.dst_port = pt.get<int>("dest_port",0); rec.protocol = pt.get<string>("proto",""); // alert record rec.alert.action = pt.get<string>("alert.action",""); rec.alert.gid = pt.get<int>("alert.gid",0); rec.alert.signature_id = pt.get<long>("alert.signature_id",0); rec.alert.signature = pt.get<string>("alert.signature",""); rec.alert.category = pt.get<string>("alert.category",""); rec.alert.severity = pt.get<int>("alert.severity",0); ResetStream(); if(SuppressAlert(rec.src_ip)) return 0; if(SuppressAlert(rec.dst_ip)) return 0; return rec.event_type; } if (event_type.compare("dns") == 0) { rec.event_type = 2; rec.time_stamp = pt.get<string>("timestamp",""); rec.iface = pt.get<string>("in_iface",""); rec.flow_id = pt.get<long>("flow_id",0); rec.src_ip = pt.get<string>("src_ip",""); rec.src_hostname = GetHostname(rec.src_ip); SetGeoBySrcIp(rec.src_ip); rec.src_port = pt.get<int>("src_port",0); rec.dst_ip = pt.get<string>("dest_ip",""); rec.dst_hostname = GetHostname(rec.dst_ip); SetGeoByDstIp(rec.dst_ip); rec.dst_port = pt.get<int>("dest_port",0); rec.protocol = pt.get<string>("proto",""); // dns record rec.dns.type = pt.get<string>("dns.type",""); rec.dns.id = pt.get<int>("dns.id",0); rec.dns.rrname = pt.get<string>("dns.rrname",""); rec.dns.rrtype = pt.get<string>("dns.rrtype",""); if (!rec.dns.type.compare("answer")) { rec.dns.ttl = pt.get<int>("dns.ttl",0); rec.dns.rcode = pt.get<string>("dns.rcode",""); rec.dns.rdata = pt.get<string>("dns.rdata",""); } else rec.dns.tx_id = pt.get<int>("dns.tx_id",0); ResetStream(); return rec.event_type; } if (event_type.compare("http") == 0) { rec.event_type = 3; rec.time_stamp = pt.get<string>("timestamp",""); rec.iface = pt.get<string>("in_iface",""); rec.flow_id = pt.get<long>("flow_id",0); rec.src_ip = pt.get<string>("src_ip",""); rec.src_hostname = GetHostname(rec.src_ip); SetGeoBySrcIp(rec.src_ip); rec.src_port = pt.get<int>("src_port",0); rec.dst_ip = pt.get<string>("dest_ip",""); rec.dst_hostname = GetHostname(rec.dst_ip); SetGeoByDstIp(rec.dst_ip); rec.dst_port = pt.get<int>("dest_port",0); rec.protocol = pt.get<string>("proto",""); rec.http.hostname = pt.get<string>("http.hostname","indef"); rec.http.url = pt.get<string>("http.url","indef"); rec.http.http_user_agent = pt.get<string>("http.http_user_agent","indef"); rec.http.http_content_type = pt.get<string>("http.http_content_type","indef"); ResetStream(); return rec.event_type; } if (event_type.compare("netflow") == 0) { rec.ref_id = fs.filter.ref_id; rec.event_type = 4; rec.time_stamp = pt.get<string>("timestamp",""); rec.iface = pt.get<string>("in_iface",""); rec.flow_id = pt.get<long>("flow_id",0); rec.src_ip = pt.get<string>("src_ip",""); rec.src_hostname = GetHostname(rec.src_ip); SetGeoBySrcIp(rec.src_ip); rec.src_port = pt.get<int>("src_port",0); rec.dst_ip = pt.get<string>("dest_ip",""); rec.dst_hostname = GetHostname(rec.dst_ip); SetGeoByDstIp(rec.dst_ip); rec.dst_port = pt.get<int>("dest_port",0); rec.protocol = pt.get<string>("proto",""); rec.netflow.app_proto = pt.get<string>("app_proto","indef"); if (rec.netflow.app_proto.compare("") == 0) rec.netflow.app_proto = "indef"; if (rec.netflow.app_proto.compare("failed") == 0) rec.netflow.app_proto = "indef"; rec.netflow.bytes = pt.get<int>("netflow.bytes",0); rec.netflow.pkts = pt.get<int>("netflow.pkts",0); rec.netflow.start = pt.get<string>("netflow.start",""); rec.netflow.end = pt.get<string>("netflow.end",""); rec.netflow.age = pt.get<int>("netflow.age",0); if (fs.filter.netflow.log) { net_flow.ref_id = rec.ref_id; net_flow.sensor = rec.sensor; net_flow.dst_ip = rec.dst_ip; net_flow.src_ip = rec.src_ip; net_flow.dst_country = dst_cc; net_flow.src_country = src_cc; net_flow.dst_hostname = rec.dst_hostname; net_flow.src_hostname = rec.src_hostname; net_flow.bytes = rec.netflow.bytes; net_flow.sessions = 1; if (is_aws_firewall) net_flow.type = 1; else net_flow.type = 0; q_netflow.push(net_flow); } ResetStream(); return rec.event_type; } if (event_type.compare("fileinfo") == 0) { rec.event_type = 5; rec.time_stamp = pt.get<string>("timestamp",""); rec.iface = pt.get<string>("in_iface",""); rec.flow_id = pt.get<long>("flow_id",0); rec.src_ip = pt.get<string>("src_ip",""); rec.src_hostname = GetHostname(rec.src_ip); SetGeoBySrcIp(rec.src_ip); rec.src_port = pt.get<int>("src_port",0); rec.dst_ip = pt.get<string>("dest_ip",""); SetGeoByDstIp(rec.dst_ip); rec.dst_hostname = GetHostname(rec.dst_ip); rec.dst_port = pt.get<int>("dest_port",0); rec.protocol = pt.get<string>("proto",""); rec.file.app_proto = pt.get<string>("app_proto","indef"); if (rec.file.app_proto.compare("") == 0) rec.netflow.app_proto = "indef"; if (rec.file.app_proto.compare("failed") == 0) rec.netflow.app_proto = "indef"; rec.file.name = pt.get<string>("fileinfo.filename",""); rec.file.size = pt.get<int>("fileinfo.size",0); rec.file.state = pt.get<string>("fileinfo.state",""); rec.file.md5 = pt.get<string>("fileinfo.md5",""); ResetStream(); return rec.event_type; } if (event_type.compare("stats") == 0) { net_stat.ids = rec.sensor; net_stat.ref_id = fs.filter.ref_id; net_stat.invalid = pt.get<long>("stats.decoder.invalid",0); net_stat.pkts = pt.get<long>("stats.decoder.pkts",0); net_stat.bytes = pt.get<long>("stats.decoder.bytes",0); net_stat.ipv4 = pt.get<long>("stats.decoder.ipv4",0); net_stat.ipv6 = pt.get<long>("stats.decoder.ipv6",0); net_stat.ethernet = pt.get<long>("stats.decoder.ethernet",0); net_stat.tcp = pt.get<long>("stats.decoder.tcp",0); net_stat.udp = pt.get<long>("stats.decoder.udp",0); net_stat.sctp = pt.get<long>("stats.decoder.sctp",0); net_stat.icmpv4 = pt.get<long>("stats.decoder.icmp4",0); net_stat.icmpv6 = pt.get<long>("stats.decoder.icmp6",0); net_stat.ppp = pt.get<long>("stats.decoder.ppp",0); net_stat.pppoe = pt.get<long>("stats.decoder.pppoe",0); net_stat.gre = pt.get<long>("stats.decoder.gre",0); net_stat.vlan = pt.get<long>("stats.decoder.vlan",0); net_stat.vlan_qinq = pt.get<long>("stats.decoder.vlan_qinq",0); net_stat.teredo = pt.get<long>("stats.decoder.teredo",0); net_stat.ipv4_in_ipv6 = pt.get<long>("stats.decoder.ipv4_in_ipv6",0); net_stat.ipv6_in_ipv6 = pt.get<long>("stats.decoder.ipv6_in_ipv6",0); net_stat.mpls = pt.get<long>("stats.decoder.mpls",0); q_netstat.push(net_stat); } ResetStream(); return 0; } void Nids::CreateLogPayload(int r) { switch (r) { case 1: // alert record report = "{\"version\": \"1.1\",\"node\":\""; report += node_id; report += "\",\"short_message\":\"alert-nids\""; report += ",\"full_message\":\"Alert from Suricata NIDS\""; report += ",\"level\":"; report += std::to_string(7); report += ",\"source_type\":\"NET\""; report += ",\"source_name\":\"Suricata\""; report += ",\"project_id\":\""; report += fs.filter.ref_id; report += "\",\"sensor\":\""; report += rec.sensor; report += "\",\"event_time\":\""; report += rec.time_stamp; report += "\",\"collected_time\":\""; report += GetGraylogFormat(); report += "\",\"severity\":"; report += std::to_string(rec.alert.severity); report += ",\"category\":\""; report += rec.alert.category; report += "\",\"signature\":\""; report += rec.alert.signature; report += "\",\"iface\":\""; report += rec.iface; report += "\",\"flow_id\":"; report += std::to_string(rec.flow_id); report += ",\"srcip\":\""; report += rec.src_ip; report += "\",\"dstip\":\""; report += rec.dst_ip; report += "\",\"src_ip_geo_country\":\""; report += src_cc; report += "\",\"dst_ip_geo_country\":\""; report += dst_cc; report += "\",\"src_ip_geo_location\":\""; report += src_latitude + "," + src_longitude; report += "\",\"dst_ip_geo_location\":\""; report += dst_latitude + "," + dst_longitude; report += "\",\"srchostname\":\""; report += rec.src_hostname; report += "\",\"dsthostname\":\""; report += rec.dst_hostname; report += "\",\"srcport\":"; report += std::to_string(rec.src_port); report += ",\"dstport\":"; report += std::to_string(rec.dst_port); report += ",\"gid\":"; report += std::to_string(rec.alert.gid); report += ",\"signature_id\":"; report += std::to_string(rec.alert.signature_id); report += ",\"action\":\""; report += rec.alert.action; report += "\"}"; //SysLog((char*) report.str().c_str()); break; case 2: // dns record report = "{\"version\": \"1.1\",\"node\":\""; report += node_id; report += "\",\"short_message\":\"dns-nids\""; report += ",\"full_message\":\"DNS event from Suricata NIDS\""; report += ",\"level\":"; report += std::to_string(7); report += ",\"source_type\":\"NET\""; report += ",\"source_name\":\"Suricata\""; report += ",\"project_id\":\""; report += fs.filter.ref_id; report += "\",\"sensor\":\""; report += rec.sensor; report += "\",\"event_time\":\""; report += rec.time_stamp; report += "\",\"collected_time\":\""; report += GetGraylogFormat(); report += "\",\"dns_type\":\""; report += rec.dns.type; report += "\",\"iface\":\""; report += rec.iface; report += "\",\"flow_id\":"; report += std::to_string(rec.flow_id); report += ",\"srcip\":\""; report += rec.src_ip; report += "\",\"dstip\":\""; report += rec.dst_ip; report += "\",\"src_ip_geo_country\":\""; report += src_cc; report += "\",\"dst_ip_geo_country\":\""; report += dst_cc; report += "\",\"src_ip_geo_location\":\""; report += src_latitude + "," + src_longitude; report += "\",\"dst_ip_geo_location\":\""; report += dst_latitude + "," + dst_longitude; report += "\",\"srchostname\":\""; report += rec.src_hostname; report += "\",\"dsthostname\":\""; report += rec.dst_hostname; report += "\",\"srcport\":"; report += std::to_string(rec.src_port); report += ",\"dstport\":"; report += std::to_string(rec.dst_port); report += ",\"id\":"; report += std::to_string(rec.dns.id); report += ",\"rrname\":\""; report += rec.dns.rrname; report += "\",\"rrtype\":\""; report += rec.dns.rrtype; if (!rec.dns.type.compare("answer")) { report += "\",\"rcode\":\""; report += rec.dns.rcode; report += "\",\"rdata\":\""; report += rec.dns.rdata; report += "\",\"ttl\":"; report += std::to_string(rec.dns.ttl); } else { report += "\",\"tx_id\":"; report += std::to_string(rec.dns.tx_id); } report += "}"; // SysLog((char*) report.c_str()); break; case 3: // http record report = "{\"version\": \"1.1\",\"node\":\""; report += node_id; report += "\",\"short_message\":\"http-nids\""; report += ",\"full_message\":\"HTTP event from Suricata NIDS\""; report += ",\"level\":"; report += std::to_string(7); report += ",\"source_type\":\"NET\""; report += ",\"source_name\":\"Suricata\""; report += ",\"project_id\":\""; report += fs.filter.ref_id; report += "\",\"sensor\":\""; report += rec.sensor; report += "\",\"event_time\":\""; report += rec.time_stamp; report += "\",\"collected_time\":\""; report += GetGraylogFormat(); report += "\",\"flow_id\":"; report += std::to_string(rec.flow_id); report += ",\"srcip\":\""; report += rec.src_ip; report += "\",\"dstip\":\""; report += rec.dst_ip; report += "\",\"src_ip_geo_country\":\""; report += src_cc; report += "\",\"dst_ip_geo_country\":\""; report += dst_cc; report += "\",\"src_ip_geo_location\":\""; report += src_latitude + "," + src_longitude; report += "\",\"dst_ip_geo_location\":\""; report += dst_latitude + "," + dst_longitude; report += "\",\"srchostname\":\""; report += rec.src_hostname; report += "\",\"dsthostname\":\""; report += rec.dst_hostname; report += "\",\"srcport\":"; report += std::to_string(rec.src_port); report += ",\"dstport\":"; report += std::to_string(rec.dst_port); report += ",\"url_hostname\":\""; report += rec.http.hostname; report += "\",\"url_path\":\""; report += rec.http.url; report += "\",\"http_user_agent\":\""; report += rec.http.http_user_agent; report += "\",\"http_content_type\":\""; report += rec.http.http_content_type; report += "\"}"; break; case 4: // flow record report = "{\"version\": \"1.1\",\"node\":\""; report += node_id; report += "\",\"short_message\":\"netflow-nids\""; report += ",\"full_message\":\"Netflow event from Suricata NIDS\""; report += ",\"level\":"; report += std::to_string(7); report += ",\"source_type\":\"NET\""; report += ",\"source_name\":\"Suricata\""; report += ",\"project_id\":\""; report += fs.filter.ref_id; report += "\",\"sensor\":\""; report += rec.sensor; report += "\",\"event_time\":\""; report += rec.time_stamp; report += "\",\"collected_time\":\""; report += GetGraylogFormat(); report += "\",\"protocol\":\""; report += rec.protocol; report += "\",\"process\":\""; report += rec.netflow.app_proto; report += "\",\"srcip\":\""; report += rec.src_ip; report += "\",\"src_ip_geo_country\":\""; report += src_cc; report += "\",\"src_ip_geo_location\":\""; report += src_latitude + "," + src_longitude; report += "\",\"srchostname\":\""; report += rec.src_hostname; report += "\",\"srcport\":"; report += std::to_string(rec.src_port); report += ",\"dstip\":\""; report += rec.dst_ip; report += "\",\"dst_ip_geo_country\":\""; report += dst_cc; report += "\",\"dst_ip_geo_location\":\""; report += dst_latitude + "," + dst_longitude; report += "\",\"dsthostname\":\""; report += rec.dst_hostname; report += "\",\"dstport\":"; report += std::to_string(rec.dst_port); report += ",\"bytes\":"; report += std::to_string(rec.netflow.bytes); report += ",\"packets\":"; report += std::to_string(rec.netflow.pkts); report += "}"; break; case 5: // file record report = "{\"version\": \"1.1\",\"node\":\""; report += node_id; report += "\",\"short_message\":\"file-nids\""; report += ",\"full_message\":\"File event from Suricata NIDS\""; report += ",\"level\":"; report += std::to_string(7); report += ",\"source_type\":\"NET\""; report += ",\"source_name\":\"Suricata\""; report += ",\"project_id\":\""; report += fs.filter.ref_id; report += "\",\"sensor\":\""; report += rec.sensor; report += "\",\"event_time\":\""; report += rec.time_stamp; report += "\",\"collected_time\":\""; report += GetGraylogFormat(); report += "\",\"protocol\":\""; report += rec.protocol; report += "\",\"process\":\""; report += rec.file.app_proto; report += "\",\"srcip\":\""; report += rec.src_ip; report += "\",\"src_ip_geo_country\":\""; report += src_cc; report += "\",\"src_ip_geo_location\":\""; report += src_latitude + "," + src_longitude; report += "\",\"srchostname\":\""; report += rec.src_hostname; report += "\",\"srcport\":"; report += std::to_string(rec.src_port); report += ",\"dstip\":\""; report += rec.dst_ip; report += "\",\"dst_ip_geo_country\":\""; report += dst_cc; report += "\",\"dst_ip_geo_location\":\""; report += dst_latitude + "," + dst_longitude; report += "\",\"dsthostname\":\""; report += rec.dst_hostname; report += "\",\"dstport\":"; report += std::to_string(rec.dst_port); report += ",\"filename\":\""; report += rec.file.name; report += "\",\"size\":"; report += std::to_string(rec.file.size); report += ",\"state\":\""; report += rec.file.state; report += "\",\"md5\":\""; report += rec.file.md5; report += "\"}"; break; } q_logs_nids.push(report); report.clear(); } void Nids::SendAlert(int s, GrayList* gl) { sk.alert.ref_id = fs.filter.ref_id; sk.alert.sensor_id = rec.sensor; sk.alert.alert_severity = s; sk.alert.alert_source = "Suricata"; sk.alert.alert_type = "NET"; sk.alert.event_severity = rec.alert.severity; sk.alert.event_id = std::to_string(rec.alert.signature_id); sk.alert.description = rec.alert.signature; sk.alert.action = "indef"; sk.alert.location = std::to_string(rec.flow_id); sk.alert.info = "{\"artifacts\": [{\"dataType\": \"ip\",\"data\":\""; sk.alert.info += rec.src_ip; sk.alert.info += "\",\"message\":\"src ip\" }, {\"dataType\": \"ip\",\"data\":\""; sk.alert.info += rec.dst_ip; sk.alert.info += "\",\"message\":\"dst ip\" }]}"; sk.alert.status = "processed"; sk.alert.user_name = "indef"; sk.alert.agent_name = probe_id; sk.alert.filter = fs.filter.name; sk.alert.list_cats.push_back(rec.alert.category); sk.alert.event_time = rec.time_stamp; if (gl != NULL) { if (gl->rsp.profile.compare("indef") != 0) { sk.alert.action = gl->rsp.profile; sk.alert.status = "modified"; } if (gl->rsp.new_type.compare("indef") != 0) { sk.alert.alert_type = gl->rsp.new_type; sk.alert.status = "modified"; } if (gl->rsp.new_source.compare("indef") != 0) { sk.alert.alert_source = gl->rsp.new_source; sk.alert.status = "modified"; } if (gl->rsp.new_event.compare("indef") != 0) { sk.alert.event_id = gl->rsp.new_event; sk.alert.status = "modified"; } if (gl->rsp.new_severity != 0) { sk.alert.alert_severity = gl->rsp.new_severity; sk.alert.status = "modified"; } if (gl->rsp.new_category.compare("indef") != 0) { sk.alert.list_cats.push_back(gl->rsp.new_category); sk.alert.status = "modified"; } if (gl->rsp.new_description.compare("indef") != 0) { sk.alert.description = gl->rsp.new_description; sk.alert.status = "modified"; } } sk.alert.src_ip = rec.src_ip; sk.alert.dst_ip = rec.dst_ip; sk.alert.src_port = rec.src_port; sk.alert.dst_port = rec.dst_port; sk.alert.src_hostname = rec.src_hostname; sk.alert.dst_hostname = rec.dst_hostname; sk.alert.reg_value = "indef"; sk.alert.file_name = "indef"; sk.alert.hash_md5 = "indef"; sk.alert.hash_sha1 = "indef"; sk.alert.hash_sha256 = "indef"; sk.alert.process_id = 0; sk.alert.process_name = "indef"; sk.alert.process_cmdline = "indef"; sk.alert.process_path = "indef"; sk.alert.url_hostname = "indef"; sk.alert.url_path = "indef"; sk.alert.container_id = "indef"; sk.alert.container_name = "indef"; sk.alert.cloud_instance = "indef"; sk.SendAlert(); } int Nids::PushIdsRecord(GrayList* gl) { // create new ids record IdsRecord ids_rec; ids_rec.ref_id = fs.filter.ref_id; ids_rec.list_cats.push_back(rec.alert.category); ids_rec.event = std::to_string(rec.alert.signature_id); ids_rec.desc = rec.alert.signature; ids_rec.severity = rec.alert.severity; switch (rec.alert.severity) { case 1 : ids_rec.severity = 3; break; case 2 : ids_rec.severity = 2; break; case 3 : ids_rec.severity = 1; break; default : ids_rec.severity = 0; break; } ids_rec.src_ip = rec.src_ip; ids_rec.dst_ip = rec.dst_ip; ids_rec.agent = probe_id; ids_rec.ids = rec.sensor; ids_rec.location = rec.dst_hostname; if (gl != NULL) { ids_rec.filter = true; if (gl->agr.reproduced > 0) { ids_rec.host = gl->host; ids_rec.match = gl->match; ids_rec.agr.in_period = gl->agr.in_period; ids_rec.agr.reproduced = gl->agr.reproduced; ids_rec.rsp.profile = gl->rsp.profile; ids_rec.rsp.new_category = gl->rsp.new_category; ids_rec.rsp.new_description = gl->rsp.new_description; ids_rec.rsp.new_event = gl->rsp.new_event; ids_rec.rsp.new_severity = gl->rsp.new_severity; ids_rec.rsp.new_type = gl->rsp.new_type; ids_rec.rsp.new_source = gl->rsp.new_source; } } q_nids.push(ids_rec); return ids_rec.severity; }
34,900
11,625
/* Copyright (C) 2017 BARBOTIN Nicolas * * Permission is hereby granted, free of charge, to any person obtaining a copy of this * software and associated documentation files (the "Software"), to deal in the Software * without restriction, including without limitation the rights to use, copy, modify, * merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit * persons to whom the Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all copies * or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR * PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE * OR OTHER DEALINGS IN THE SOFTWARE. */ #include "mgpcl/GUI.h" #include "mgpcl/Config.h" #if defined(MGPCL_NO_GUI) void m::gui::initialize() { } bool m::gui::hasBeenInitialized() { return false; } #elif defined(MGPCL_WIN) void m::gui::initialize() { } bool m::gui::hasBeenInitialized() { return true; } #else #include "mgpcl/Mutex.h" #include <gtk/gtk.h> static volatile bool g_guiInit = false; static m::Mutex g_guiLock; void m::gui::initialize() { g_guiLock.lock(); gtk_init(nullptr, nullptr); g_guiInit = true; g_guiLock.unlock(); } bool m::gui::hasBeenInitialized() { volatile bool ret; g_guiLock.lock(); ret = g_guiInit; g_guiLock.unlock(); return ret; } #endif
1,797
655
#include <iostream> int main() { int n; std::cin >> n; int thousands = n / 1000; int hundreds = n / 100 % 10; int tens = n / 10 % 10; int ones = n % 10; std::string is_good_integer; if (thousands == hundreds && hundreds == tens || hundreds == tens && tens == ones) { is_good_integer = "Yes"; } else { is_good_integer = "No"; } std::cout << is_good_integer << std::endl; }
408
166
#include<bits/stdc++.h> using namespace std; #define int long long #define M 1000000007 #define N 300010 signed main(){ ios_base::sync_with_stdio(false); cin.tie(NULL); int n; cin >> n; int dp[n+1]; for(int i=0;i<=n;i++) dp[i]=INT_MAX; dp[0]=0; for(int i=1;i<=n;i++){ int num=i; while(num>0){ int val=num%10; num/=10; dp[i]=min(dp[i],dp[i-val]+1); } } cout << dp[n] << endl; }
416
238
// // Created by xiodine on 4/19/15. // #include <sstream> #include "ControllerAdaugaRefill.h" #include "../views/ViewConsole.h" ControllerAdaugaRefill::ControllerAdaugaRefill() : Controller() { } ControllerAdaugaRefill::~ControllerAdaugaRefill() { } std::size_t ControllerAdaugaRefill::showOptions(ModelStoc &stoc) { ViewConsole &con = ViewConsole::getSingleton(); // typedefs typedef ModelBun::trasaturi_t trasaturi_t; // for each bun ModelStoc::bunuri_pointer_t bunuri = stoc.getBunuriPointer(); std::size_t nrProduse = 0; for (ModelStoc::bunuri_pointer_t::const_iterator i = bunuri.begin(); i != bunuri.end(); ++i) { const ModelBun &bun = **i; nrProduse++; con << nrProduse << ". " << bun.getNume() << " ("; const trasaturi_t &trasaturi = bun.getTrasaturi(); for (trasaturi_t::const_iterator j = trasaturi.begin(); j != trasaturi.end(); ++j) { if (j != trasaturi.begin()) con << ", "; con << '\'' << *j << '\''; } con << ") - " << bun.getStoc() << " in stoc"; } return nrProduse; } void ControllerAdaugaRefill::run(ModelStoc &stoc) { std::size_t maxSize = showOptions(stoc); ViewConsole &con = ViewConsole::getSingleton(); std::size_t nr; do { con << "\nIntroduceti numarul produsului (0 pentru stop): "; std::stringstream str(con.getLine()); str >> nr; if (nr) { // test for validity if (nr > maxSize) { con << "Numar invalid!"; } else { con << "Numarul de produse de adaugat (numar): "; std::stringstream nrProdStr(con.getLine()); int nrProd; nrProdStr >> nrProd; ModelStoc::bunuri_pointer_t bunuri = stoc.getBunuriPointer(); stoc.addStocToBun(bunuri[nr - 1], nrProd); } } // else nr == 0 } while (nr != 0); }
1,985
693
/* Starshatter OpenSource Distribution Copyright (c) 1997-2004, Destroyer Studios LLC. All Rights Reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name "Destroyer Studios" nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. SUBSYSTEM: Stars.exe FILE: MsnPkgDlg.cpp AUTHOR: John DiCamillo OVERVIEW ======== Mission Briefing Dialog Active Window class */ #include "MemDebug.h" #include "MsnPkgDlg.h" #include "PlanScreen.h" #include "Campaign.h" #include "Mission.h" #include "Instruction.h" #include "Ship.h" #include "ShipDesign.h" #include "StarSystem.h" #include "Game.h" #include "Mouse.h" #include "Button.h" #include "ListBox.h" #include "Slider.h" #include "ParseUtil.h" #include "FormatUtil.h" #include "Keyboard.h" // +--------------------------------------------------------------------+ // DECLARE MAPPING FUNCTIONS: DEF_MAP_CLIENT(MsnPkgDlg, OnPackage); DEF_MAP_CLIENT(MsnPkgDlg, OnCommit); DEF_MAP_CLIENT(MsnPkgDlg, OnCancel); DEF_MAP_CLIENT(MsnPkgDlg, OnTabButton); // +--------------------------------------------------------------------+ MsnPkgDlg::MsnPkgDlg(Screen* s, FormDef& def, PlanScreen* mgr) : FormWindow(s, 0, 0, s->Width(), s->Height()), MsnDlg(mgr) { campaign = Campaign::GetCampaign(); if (campaign) mission = campaign->GetMission(); Init(def); } MsnPkgDlg::~MsnPkgDlg() { } // +--------------------------------------------------------------------+ void MsnPkgDlg::RegisterControls() { pkg_list = (ListBox*) FindControl(320); nav_list = (ListBox*) FindControl(330); for (int i = 0; i < 5; i++) threat[i] = FindControl(251 + i); RegisterMsnControls(this); if (pkg_list) REGISTER_CLIENT(EID_SELECT, pkg_list, MsnPkgDlg, OnPackage); if (commit) REGISTER_CLIENT(EID_CLICK, commit, MsnPkgDlg, OnCommit); if (cancel) REGISTER_CLIENT(EID_CLICK, cancel, MsnPkgDlg, OnCancel); if (sit_button) REGISTER_CLIENT(EID_CLICK, sit_button, MsnPkgDlg, OnTabButton); if (pkg_button) REGISTER_CLIENT(EID_CLICK, pkg_button, MsnPkgDlg, OnTabButton); if (nav_button) REGISTER_CLIENT(EID_CLICK, nav_button, MsnPkgDlg, OnTabButton); if (wep_button) REGISTER_CLIENT(EID_CLICK, wep_button, MsnPkgDlg, OnTabButton); } // +--------------------------------------------------------------------+ void MsnPkgDlg::Show() { FormWindow::Show(); ShowMsnDlg(); DrawPackages(); DrawNavPlan(); DrawThreats(); } // +--------------------------------------------------------------------+ void MsnPkgDlg::DrawPackages() { if (mission) { if (pkg_list) { pkg_list->ClearItems(); int i = 0; int elem_index = 0; ListIter<MissionElement> elem = mission->GetElements(); while (++elem) { // display this element? if (elem->GetIFF() == mission->Team() && !elem->IsSquadron() && elem->Region() == mission->GetRegion() && elem->GetDesign()->type < Ship::STATION) { char txt[256]; if (elem->Player() > 0) { sprintf_s(txt, "==>"); if (pkg_index < 0) pkg_index = elem_index; } else { strcpy_s(txt, " "); } pkg_list->AddItemWithData(txt, elem->ElementID()); pkg_list->SetItemText(i, 1, elem->Name()); pkg_list->SetItemText(i, 2, elem->RoleName()); const ShipDesign* design = elem->GetDesign(); if (elem->Count() > 1) sprintf_s(txt, "%d %s", elem->Count(), design->abrv); else sprintf_s(txt, "%s %s", design->abrv, design->name); pkg_list->SetItemText(i, 3, txt); i++; } elem_index++; } } } } // +--------------------------------------------------------------------+ void MsnPkgDlg::DrawNavPlan() { if (mission) { if (pkg_index < 0 || pkg_index >= mission->GetElements().size()) pkg_index = 0; MissionElement* element = mission->GetElements()[pkg_index]; if (nav_list && element) { nav_list->ClearItems(); Point loc = element->Location(); int i = 0; ListIter<Instruction> navpt = element->NavList(); while (++navpt) { char txt[256]; sprintf_s(txt, "%d", i + 1); nav_list->AddItem(txt); nav_list->SetItemText(i, 1, Instruction::ActionName(navpt->Action())); nav_list->SetItemText(i, 2, navpt->RegionName()); double dist = Point(loc - navpt->Location()).length(); FormatNumber(txt, dist); nav_list->SetItemText(i, 3, txt); sprintf_s(txt, "%d", navpt->Speed()); nav_list->SetItemText(i, 4, txt); loc = navpt->Location(); i++; } } } } // +--------------------------------------------------------------------+ void MsnPkgDlg::DrawThreats() { for (int i = 0; i < 5; i++) if (threat[i]) threat[i]->SetText(""); if (!mission) return; MissionElement* player = mission->GetPlayer(); if (!player) return; Text rgn0 = player->Region(); Text rgn1; int iff = player->GetIFF(); ListIter<Instruction> nav = player->NavList(); while (++nav) { if (rgn0 != nav->RegionName()) rgn1 = nav->RegionName(); } if (threat[0]) { Point base_loc = mission->GetElements()[0]->Location(); int i = 0; ListIter<MissionElement> iter = mission->GetElements(); while (++iter) { MissionElement* elem = iter.value(); if (elem->GetIFF() == 0 || elem->GetIFF() == iff || elem->IntelLevel() <= Intel::SECRET) continue; if (elem->IsSquadron()) continue; if (elem->IsGroundUnit()) { if (!elem->GetDesign() || elem->GetDesign()->type != Ship::SAM) continue; if (elem->Region() != rgn0 && elem->Region() != rgn1) continue; } int mission_role = elem->MissionRole(); if (mission_role == Mission::STRIKE || mission_role == Mission::INTEL || mission_role >= Mission::TRANSPORT) continue; char rng[32]; char role[32]; char txt[256]; if (mission_role == Mission::SWEEP || mission_role == Mission::INTERCEPT || mission_role == Mission::FLEET || mission_role == Mission::BOMBARDMENT) strcpy_s(role, Game::GetText("MsnDlg.ATTACK").data()); else strcpy_s(role, Game::GetText("MsnDlg.PATROL").data()); double dist = Point(base_loc - elem->Location()).length(); FormatNumber(rng, dist); sprintf_s(txt, "%s - %d %s - %s", role, elem->Count(), elem->GetDesign()->abrv, rng); if (threat[i]) threat[i]->SetText(txt); i++; if (i >= 5) break; } } } // +--------------------------------------------------------------------+ void MsnPkgDlg::ExecFrame() { if (Keyboard::KeyDown(VK_RETURN)) { OnCommit(0); } } // +--------------------------------------------------------------------+ void MsnPkgDlg::OnPackage(AWEvent* event) { if (!pkg_list || !mission) return; int seln = pkg_list->GetListIndex(); int pkg = pkg_list->GetItemData(seln); int i = 0; ListIter<MissionElement> elem = mission->GetElements(); while (++elem) { if (elem->ElementID() == pkg) { pkg_index = i; //mission->SetPlayer(elem.value()); } i++; } //DrawPackages(); DrawNavPlan(); } // +--------------------------------------------------------------------+ void MsnPkgDlg::OnCommit(AWEvent* event) { MsnDlg::OnCommit(event); } void MsnPkgDlg::OnCancel(AWEvent* event) { MsnDlg::OnCancel(event); } void MsnPkgDlg::OnTabButton(AWEvent* event) { MsnDlg::OnTabButton(event); }
10,168
3,297
/** \class DTDigiAnalyzer * Analyse the the muon-drift-tubes digitizer. * * \authors: R. Bellan */ #include "DataFormats/MuonDetId/interface/DTLayerId.h" #include "SimMuon/DTDigitizer/test/DTDigiAnalyzer.h" #include <DataFormats/DTDigi/interface/DTDigiCollection.h> #include <FWCore/Framework/interface/Event.h> // #include "SimMuon/DTDigitizer/test/analysis/DTMCStatistics.h" // #include "SimMuon/DTDigitizer/test/analysis/DTMuonDigiStatistics.h" // #include "SimMuon/DTDigitizer/test/analysis/DTHitsAnalysis.h" #include "DataFormats/Common/interface/Handle.h" #include "FWCore/Framework/interface/ESHandle.h" #include "FWCore/Framework/interface/EventSetup.h" #include "FWCore/ParameterSet/interface/ParameterSet.h" #include "DataFormats/GeometryVector/interface/LocalPoint.h" #include "Geometry/DTGeometry/interface/DTGeometry.h" #include "Geometry/DTGeometry/interface/DTLayer.h" #include "Geometry/Records/interface/MuonGeometryRecord.h" #include "DataFormats/MuonDetId/interface/DTLayerId.h" #include "DataFormats/MuonDetId/interface/DTWireId.h" #include <iostream> #include <string> #include "TFile.h" #include "SimMuon/DTDigitizer/test/Histograms.h" using namespace edm; using namespace std; DTDigiAnalyzer::DTDigiAnalyzer(const ParameterSet &pset) : hDigis_global("Global"), hDigis_W0("Wheel0"), hDigis_W1("Wheel1"), hDigis_W2("Wheel2"), hAllHits("AllHits") { // MCStatistics = new DTMCStatistics(); // MuonDigiStatistics = new DTMuonDigiStatistics(); // HitsAnalysis = new DTHitsAnalysis(); label = pset.getUntrackedParameter<string>("label"); file = new TFile("DTDigiPlots.root", "RECREATE"); file->cd(); DigiTimeBox = new TH1F("DigiTimeBox", "Digi Time Box", 2048, 0, 1600); if (file->IsOpen()) cout << "file open!" << endl; else cout << "*** Error in opening file ***" << endl; psim_token = consumes<PSimHitContainer>(edm::InputTag("g4SimHits", "MuonDTHits")); DTd_token = consumes<DTDigiCollection>(edm::InputTag(label)); } DTDigiAnalyzer::~DTDigiAnalyzer() {} void DTDigiAnalyzer::endJob() { // cout<<"Number of analyzed event: "<<nevts<<endl; // HitsAnalysis->Report(); file->cd(); DigiTimeBox->Write(); hDigis_global.Write(); hDigis_W0.Write(); hDigis_W1.Write(); hDigis_W2.Write(); hAllHits.Write(); file->Close(); // delete file; // delete DigiTimeBox; } void DTDigiAnalyzer::analyze(const Event &event, const EventSetup &eventSetup) { cout << "--- Run: " << event.id().run() << " Event: " << event.id().event() << endl; Handle<DTDigiCollection> dtDigis; event.getByToken(DTd_token, dtDigis); Handle<PSimHitContainer> simHits; event.getByToken(psim_token, simHits); ESHandle<DTGeometry> muonGeom; eventSetup.get<MuonGeometryRecord>().get(muonGeom); DTWireIdMap wireMap; for (vector<PSimHit>::const_iterator hit = simHits->begin(); hit != simHits->end(); hit++) { // Create the id of the wire, the simHits in the DT known also the wireId DTWireId wireId(hit->detUnitId()); // Fill the map wireMap[wireId].push_back(&(*hit)); LocalPoint entryP = hit->entryPoint(); LocalPoint exitP = hit->exitPoint(); int partType = hit->particleType(); float path = (exitP - entryP).mag(); float path_x = fabs((exitP - entryP).x()); hAllHits.Fill(entryP.x(), exitP.x(), entryP.y(), exitP.y(), entryP.z(), exitP.z(), path, path_x, partType, hit->processType(), hit->pabs()); if (hit->timeOfFlight() > 1e4) { cout << "PID: " << hit->particleType() << " TOF: " << hit->timeOfFlight() << " Proc Type: " << hit->processType() << " p: " << hit->pabs() << endl; hAllHits.FillTOF(hit->timeOfFlight()); } } DTDigiCollection::DigiRangeIterator detUnitIt; for (detUnitIt = dtDigis->begin(); detUnitIt != dtDigis->end(); ++detUnitIt) { const DTLayerId &id = (*detUnitIt).first; const DTDigiCollection::Range &range = (*detUnitIt).second; // DTLayerId print-out cout << "--------------" << endl; cout << "id: " << id; // Loop over the digis of this DetUnit for (DTDigiCollection::const_iterator digiIt = range.first; digiIt != range.second; ++digiIt) { cout << " Wire: " << (*digiIt).wire() << endl << " digi time (ns): " << (*digiIt).time() << endl; DigiTimeBox->Fill((*digiIt).time()); DTWireId wireId(id, (*digiIt).wire()); int mu = 0; float theta = 0; for (vector<const PSimHit *>::iterator hit = wireMap[wireId].begin(); hit != wireMap[wireId].end(); hit++) { cout << "momentum x: " << (*hit)->momentumAtEntry().x() << endl << "momentum z: " << (*hit)->momentumAtEntry().z() << endl; if (abs((*hit)->particleType()) == 13) { theta = atan((*hit)->momentumAtEntry().x() / (-(*hit)->momentumAtEntry().z())) * 180 / M_PI; cout << "atan: " << theta << endl; mu++; } else { // cout<<"PID: "<<(*hit)->particleType() // <<" TOF: "<<(*hit)->timeOfFlight() // <<" Proc Type: "<<(*hit)->processType() // <<" p: " << (*hit)->pabs() <<endl; } } if (mu && theta) { hDigis_global.Fill((*digiIt).time(), theta, id.superlayer()); // filling digi histos for wheel and for RZ and RPhi WheelHistos(id.wheel())->Fill((*digiIt).time(), theta, id.superlayer()); } } // for digis in layer } // for layers cout << "--------------" << endl; } hDigis *DTDigiAnalyzer::WheelHistos(int wheel) { switch (abs(wheel)) { case 0: return &hDigis_W0; case 1: return &hDigis_W1; case 2: return &hDigis_W2; default: return nullptr; } } #include "FWCore/Framework/interface/MakerMacros.h" #include "FWCore/PluginManager/interface/ModuleDef.h" DEFINE_FWK_MODULE(DTDigiAnalyzer);
6,017
2,245
// Examen junio 2016: Implementacion de un sistema de reproduccion de musica // APDO B: hay que reducir los costes de deleteSong y play #include "lista.h" #include "DiccionarioHash.h" #include <iostream> #include <string> using namespace std; typedef string Cancion; typedef string Artista; class SongInfo { public: Artista artist; int duration; // APDO B: sustituimos los booleanos por iteradores que apuntan al elemento de las listas // de reproducción y reproducidas donde están las canciones de las que el correspondiente // objeto SongInfo es información //bool inPlaylist; //bool played; Lista<Cancion>::Iterator itPlaylist; Lista<Cancion>::Iterator itPlayed; // OJO: los constructores de los iteradores son privados // Definimos el siguiente constructor al que le pasaremos los end() de las listas correspondientes // cuando creemos un objeto en addSong SongInfo(const Lista<Cancion>::Iterator& itplaylist, const Lista<Cancion>::Iterator& itplayedlist) : itPlaylist(itplaylist), itPlayed(itplayedlist) {} }; // clases excepcion para iPud class ECancionExistente{}; class ECancionNoExistente{}; // clase iPud class iPud { Lista<Cancion> playlist; Lista<Cancion> played; int duration; DiccionarioHash<Cancion,SongInfo> songs; public: iPud() : duration(0), playlist(Lista<Cancion>()), played(Lista<Cancion>()), songs(DiccionarioHash<Cancion, SongInfo>()) {} void addSong(const Cancion& c, const Artista& a, int d); void addToPlaylist(const Cancion& c); Cancion current(); void play(); void deleteSong(const Cancion& c); int totalTime(); Cancion recent(); }; // creación de la información de la canción // APDO. B: Los iteradores de momento no tienen que apuntar a nada porque lo único // que estamos haciendo es meter la canción en la colección de canciones existentes void iPud::addSong(const Cancion& c, const Artista& a, int d){ if (songs.contiene(c)) throw ECancionExistente(); SongInfo i(playlist.end(), played.end()); i.artist = a; i.duration = d; // inclusión en el diccionario songs.inserta(c,i); } void iPud::addToPlaylist(const Cancion& c){ if (!songs.contiene(c))throw ECancionNoExistente(); Lista<Cancion>::Iterator it = playlist.end(); if (songs.valorPara(c).itPlaylist == it){ playlist.pon_ppio(c); Lista<Cancion>::Iterator ite = playlist.begin(); songs.busca(c).valor().itPlaylist = ite; duration += songs.valorPara(c).duration; } } Cancion iPud::current(){ if (playlist.esVacia()){ cout << "LISTA DE REPRODUCCION VACIA" << endl; } else{ return playlist.ultimo(); } } void iPud::play(){ if (!playlist.esVacia()){ played.pon_ppio(playlist.ultimo()); //meto en played la cancion Lista<Cancion>::Iterator it = played.begin(); songs.busca(played.ultimo()).valor().itPlayed = it;// meto el iterador de conde esta en played duration -= songs.valorPara(playlist.ultimo()).duration;//cambio la duracion playlist.eliminar(songs.valorPara(playlist.ultimo()).itPlaylist);//borro la cancion de playlist } } void iPud::deleteSong(const Cancion& c){ if (songs.contiene(c)){ Lista<Cancion>::Iterator it = playlist.end(); Lista<Cancion>::Iterator ite = played.end(); if (songs.valorPara(c).itPlaylist != it){ playlist.eliminar(songs.valorPara(c).itPlaylist); } if (songs.valorPara(c).itPlayed != ite){ played.eliminar(songs.valorPara(c).itPlayed); } songs.borra(c); } } int iPud::totalTime(){ if (!playlist.esVacia()){ return duration; } else return 0; } Cancion iPud::recent(){ if (played.esVacia()){ cout << "LISTA DE REPRODUCCION VACIA" << endl; } else{ return played.ultimo(); } } /////MAIN void añade(iPud& ip) { Cancion c; Artista a; int d; cin >> c >> a >> d; try { ip.addSong(c, a, d); cout << "OK" << endl; } catch (ECancionExistente) { cout << "CANCION_EXISTENTE" << endl; } } void añadelista(iPud& ip) { try { Cancion c; cin >> c; ip.addToPlaylist(c); cout << "OK" << endl; } catch (ECancionNoExistente) { cout << "CANCION_NO_EXISTENTE" << endl; } } void borra(iPud& ip) { Cancion c; cin >> c; ip.deleteSong(c); cout << "OK" << endl; } void playe(iPud& ip){ ip.play(); } void current(iPud& ip) { Cancion c; c =ip.current(); cout << c << endl; } void tiemposs(iPud& ip){ int tiempo; tiempo = ip.totalTime(); cout << "tiempo total " << tiempo << endl; } void rec(iPud& ip){ Cancion c; c = ip.recent(); cout << c << endl; } int main() { iPud ip; string comando; while (cin >> comando) { if (comando == "anade") añade(ip); else if (comando == "lista") añadelista(ip); else if (comando == "play") playe(ip); else if (comando == "actu") current(ip); else if (comando == "borra") borra(ip); else if (comando == "tiempo") tiemposs(ip); else if (comando == "recent") rec(ip); } return 0; }
4,861
1,957
/* Copyright (c) 2014, Hookflash Inc. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 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. The views and conclusions contained in the software and documentation are those of the authors and should not be interpreted as representing official policies, either expressed or implied, of the FreeBSD Project. */ #include <ortc/services/internal/services_STUNRequester.h> #include <ortc/services/internal/services_STUNRequesterManager.h> #include <ortc/services/internal/services.events.h> #include <ortc/services/IBackOffTimerPattern.h> #include <ortc/services/IHelper.h> #include <zsLib/Exception.h> #include <zsLib/helpers.h> #include <zsLib/Log.h> #include <zsLib/XML.h> #include <zsLib/Stringize.h> #define ORTC_SERVICES_STUN_REQUESTER_DEFAULT_BACKOFF_TIMER_MAX_ATTEMPTS (6) namespace ortc { namespace services { ZS_DECLARE_SUBSYSTEM(ortc_services_stun) } } namespace ortc { namespace services { namespace internal { ZS_DECLARE_TYPEDEF_PTR(ISTUNRequesterManagerForSTUNRequester, UseSTUNRequesterManager) //----------------------------------------------------------------------- //----------------------------------------------------------------------- //----------------------------------------------------------------------- //----------------------------------------------------------------------- #pragma mark #pragma mark STUNRequester #pragma mark //----------------------------------------------------------------------- STUNRequester::STUNRequester( const make_private &, IMessageQueuePtr queue, ISTUNRequesterDelegatePtr delegate, IPAddress serverIP, STUNPacketPtr stun, STUNPacket::RFCs usingRFC, IBackOffTimerPatternPtr pattern ) : MessageQueueAssociator(queue), mDelegate(ISTUNRequesterDelegateProxy::createWeak(queue, delegate)), mSTUNRequest(stun), mServerIP(serverIP), mUsingRFC(usingRFC), mBackOffTimerPattern(pattern) { if (!mBackOffTimerPattern) { mBackOffTimerPattern = IBackOffTimerPattern::create(); mBackOffTimerPattern->setMaxAttempts(ORTC_SERVICES_STUN_REQUESTER_DEFAULT_BACKOFF_TIMER_MAX_ATTEMPTS); mBackOffTimerPattern->addNextAttemptTimeout(Milliseconds(500)); mBackOffTimerPattern->setMultiplierForLastAttemptTimeout(2.0); mBackOffTimerPattern->addNextRetryAfterFailureDuration(Milliseconds(1)); } //ServicesStunRequesterCreate(__func__, mID, serverIP.string(), zsLib::to_underlying(usingRFC), mBackOffTimerPattern->getID()); ZS_EVENTING_4( x, i, Debug, ServicesStunRequesterCreate, os, StunRequester, Start, puid, id, mID, string, serverIp, serverIP.string(), enum, usingRfc, zsLib::to_underlying(usingRFC), puid, backoffTimerPatterId, mBackOffTimerPattern->getID() ); } //----------------------------------------------------------------------- STUNRequester::~STUNRequester() { if(isNoop()) return; mThisWeak.reset(); cancel(); //ServicesStunRequesterDestroy(__func__, mID); ZS_EVENTING_1(x, i, Debug, ServicesStunRequesterDestroy, os, StunRequester, Start, puid, id, mID); } //----------------------------------------------------------------------- void STUNRequester::init() { AutoRecursiveLock lock(mLock); UseSTUNRequesterManagerPtr manager = UseSTUNRequesterManager::singleton(); if (manager) { manager->monitorStart(mThisWeak.lock(), mSTUNRequest); } step(); } //----------------------------------------------------------------------- STUNRequesterPtr STUNRequester::convert(ISTUNRequesterPtr object) { return ZS_DYNAMIC_PTR_CAST(STUNRequester, object); } //----------------------------------------------------------------------- STUNRequesterPtr STUNRequester::convert(ForSTUNRequesterManagerPtr object) { return ZS_DYNAMIC_PTR_CAST(STUNRequester, object); } //----------------------------------------------------------------------- //----------------------------------------------------------------------- //----------------------------------------------------------------------- //----------------------------------------------------------------------- #pragma mark #pragma mark STUNRequester => STUNRequester #pragma mark //----------------------------------------------------------------------- STUNRequesterPtr STUNRequester::create( IMessageQueuePtr queue, ISTUNRequesterDelegatePtr delegate, IPAddress serverIP, STUNPacketPtr stun, STUNPacket::RFCs usingRFC, IBackOffTimerPatternPtr pattern ) { ZS_THROW_INVALID_USAGE_IF(!delegate) ZS_THROW_INVALID_USAGE_IF(!stun) ZS_THROW_INVALID_USAGE_IF(serverIP.isAddressEmpty()) ZS_THROW_INVALID_USAGE_IF(serverIP.isPortEmpty()) STUNRequesterPtr pThis(make_shared<STUNRequester>(make_private{}, queue, delegate, serverIP, stun, usingRFC, pattern)); pThis->mThisWeak = pThis; pThis->init(); return pThis; } //----------------------------------------------------------------------- bool STUNRequester::isComplete() const { AutoRecursiveLock lock(mLock); if (!mDelegate) return true; return false; } //----------------------------------------------------------------------- void STUNRequester::cancel() { //ServicesStunRequesterCancel(__func__, mID); ZS_EVENTING_1(x, i, Debug, ServicesStunRequesterCancel, os, StunRequester, Cancel, puid, id, mID); AutoRecursiveLock lock(mLock); ZS_LOG_TRACE(log("cancel called") + mSTUNRequest->toDebug()) mServerIP.clear(); if (mDelegate) { mDelegate.reset(); // tie the lifetime of the monitoring to the delegate UseSTUNRequesterManagerPtr manager = UseSTUNRequesterManager::singleton(); if (manager) { manager->monitorStop(*this); } } } //----------------------------------------------------------------------- void STUNRequester::retryRequestNow() { //ServicesStunRequesterRetryNow(__func__, mID); ZS_EVENTING_1(x, i, Trace, ServicesStunRequesterRetryNow, os, StunRequester, RetryNow, puid, id, mID); AutoRecursiveLock lock(mLock); ZS_LOG_DEBUG(log("retry request now") + mSTUNRequest->toDebug()) if (mBackOffTimer) { mBackOffTimer->cancel(); mBackOffTimer.reset(); } step(); } //----------------------------------------------------------------------- IPAddress STUNRequester::getServerIP() const { AutoRecursiveLock lock(mLock); return mServerIP; } //----------------------------------------------------------------------- STUNPacketPtr STUNRequester::getRequest() const { AutoRecursiveLock lock(mLock); return mSTUNRequest; } //----------------------------------------------------------------------- IBackOffTimerPatternPtr STUNRequester::getBackOffTimerPattern() const { AutoRecursiveLock lock(mLock); return mBackOffTimerPattern; } //----------------------------------------------------------------------- size_t STUNRequester::getTotalTries() const { AutoRecursiveLock lock(mLock); return mTotalTries; } //----------------------------------------------------------------------- //----------------------------------------------------------------------- //----------------------------------------------------------------------- //----------------------------------------------------------------------- #pragma mark #pragma mark STUNRequester => ISTUNRequesterForSTUNRequesterManager #pragma mark //----------------------------------------------------------------------- bool STUNRequester::handleSTUNPacket( IPAddress fromIPAddress, STUNPacketPtr packet ) { //ServicesStunRequesterReceivedStunPacket(__func__, mID, fromIPAddress.string()); ZS_EVENTING_2(x, i, Debug, ServicesStunRequesterReceivedStunPacket, os, StunRequester, Receive, puid, id, mID, string, fromIpAddress, fromIPAddress.string()); packet->trace(__func__); ISTUNRequesterDelegatePtr delegate; // find out if this was truly handled { AutoRecursiveLock lock(mLock); if (!mSTUNRequest) return false; if (!packet->isValidResponseTo(mSTUNRequest, mUsingRFC)) { ZS_LOG_TRACE(log("determined this response is not a proper validated response") + packet->toDebug()) return false; } delegate = mDelegate; } bool success = true; // we now have a reply, inform the delegate... // NOTE: We inform the delegate syncrhonously thus we cannot call // the delegate from inside a lock in case the delegate is // calling us (that would cause a potential deadlock). if (delegate) { try { success = delegate->handleSTUNRequesterResponse(mThisWeak.lock(), fromIPAddress, packet); // this is a success! yay! inform the delegate } catch(ISTUNRequesterDelegateProxy::Exceptions::DelegateGone &) { } } if (!success) return false; // clear out the request since it's now complete { AutoRecursiveLock lock(mLock); if (ZS_IS_LOGGING(Trace)) { ZS_LOG_BASIC(log("handled") + ZS_PARAM("ip", mServerIP.string()) + ZS_PARAM("request", mSTUNRequest->toDebug()) + ZS_PARAM("response", packet->toDebug())) } cancel(); } return true; } //----------------------------------------------------------------------- //----------------------------------------------------------------------- //----------------------------------------------------------------------- //----------------------------------------------------------------------- #pragma mark #pragma mark STUNRequester => ITimerDelegate #pragma mark //----------------------------------------------------------------------- void STUNRequester::onBackOffTimerStateChanged( IBackOffTimerPtr timer, IBackOffTimer::States state ) { //ServicesStunRequesterBackOffTimerStateEvent(__func__, mID, timer->getID(), IBackOffTimer::toString(state), mTotalTries); ZS_EVENTING_4( x, i, Trace, ServicesStunRequesterBackOffTimerStateEvent, os, StunRequester, InternalEvent, puid, id, mID, puid, timerId, timer->getID(), string, backoffTimerState, IBackOffTimer::toString(state), ulong, totalTries, mTotalTries ); AutoRecursiveLock lock(mLock); ZS_LOG_TRACE(log("backoff timer state changed") + ZS_PARAM("timer id", timer->getID()) + ZS_PARAM("state", IBackOffTimer::toString(state)) + ZS_PARAM("total tries", mTotalTries)) step(); } //----------------------------------------------------------------------- //----------------------------------------------------------------------- //----------------------------------------------------------------------- //----------------------------------------------------------------------- #pragma mark #pragma mark STUNRequester => (internal) #pragma mark //----------------------------------------------------------------------- Log::Params STUNRequester::log(const char *message) const { ElementPtr objectEl = Element::create("STUNRequester"); IHelper::debugAppend(objectEl, "id", mID); return Log::Params(message, objectEl); } //----------------------------------------------------------------------- void STUNRequester::step() { if (!mDelegate) return; // if there is no delegate then the request has completed or is cancelled if (mServerIP.isAddressEmpty()) return; if (!mBackOffTimer) { mBackOffTimer = IBackOffTimer::create(mBackOffTimerPattern, mThisWeak.lock()); } if (mBackOffTimer->haveAllAttemptsFailed()) { try { mDelegate->onSTUNRequesterTimedOut(mThisWeak.lock()); } catch(ISTUNRequesterDelegateProxy::Exceptions::DelegateGone &) { ZS_LOG_WARNING(Debug, log("delegate gone")) } cancel(); return; } if (mBackOffTimer->shouldAttemptNow()) { mBackOffTimer->notifyAttempting(); ZS_LOG_TRACE(log("sending packet now") + ZS_PARAM("ip", mServerIP.string()) + ZS_PARAM("tries", mTotalTries) + ZS_PARAM("stun packet", mSTUNRequest->toDebug())) // send off the packet NOW SecureByteBlockPtr packet = mSTUNRequest->packetize(mUsingRFC); //ServicesStunRequesterSendPacket(__func__, mID, packet->SizeInBytes(), packet->BytePtr()); ZS_EVENTING_3( x, i, Trace, ServicesStunRequesterSendPacket, os, StunRequester, Send, puid, id, mID, binary, packet, packet->BytePtr(), size, size, packet->SizeInBytes() ); mSTUNRequest->trace(__func__); try { ++mTotalTries; mDelegate->onSTUNRequesterSendPacket(mThisWeak.lock(), mServerIP, packet); } catch(ISTUNRequesterDelegateProxy::Exceptions::DelegateGone &) { ZS_LOG_WARNING(Trace, log("delegate gone thus cancelling requester")) cancel(); return; } } // nothing more to do... sit back, relax and enjoy the ride! } //----------------------------------------------------------------------- //----------------------------------------------------------------------- //----------------------------------------------------------------------- //----------------------------------------------------------------------- #pragma mark #pragma mark ISTUNRequesterFactory #pragma mark //----------------------------------------------------------------------- ISTUNRequesterFactory &ISTUNRequesterFactory::singleton() { return STUNRequesterFactory::singleton(); } //----------------------------------------------------------------------- STUNRequesterPtr ISTUNRequesterFactory::create( IMessageQueuePtr queue, ISTUNRequesterDelegatePtr delegate, IPAddress serverIP, STUNPacketPtr stun, STUNPacket::RFCs usingRFC, IBackOffTimerPatternPtr pattern ) { if (this) {} return STUNRequester::create(queue, delegate, serverIP, stun, usingRFC, pattern); } } //------------------------------------------------------------------------- //------------------------------------------------------------------------- //------------------------------------------------------------------------- //------------------------------------------------------------------------- #pragma mark #pragma mark ISTUNRequester #pragma mark //------------------------------------------------------------------------- ISTUNRequesterPtr ISTUNRequester::create( IMessageQueuePtr queue, ISTUNRequesterDelegatePtr delegate, IPAddress serverIP, STUNPacketPtr stun, STUNPacket::RFCs usingRFC, IBackOffTimerPatternPtr pattern ) { return internal::ISTUNRequesterFactory::singleton().create(queue, delegate, serverIP, stun, usingRFC, pattern); } //------------------------------------------------------------------------- bool ISTUNRequester::handlePacket( IPAddress fromIPAddress, const BYTE *packet, size_t packetLengthInBytes, const STUNPacket::ParseOptions &options ) { return (bool)ISTUNRequesterManager::handlePacket(fromIPAddress, packet, packetLengthInBytes, options); } //------------------------------------------------------------------------- bool ISTUNRequester::handleSTUNPacket( IPAddress fromIPAddress, STUNPacketPtr stun ) { return (bool)ISTUNRequesterManager::handleSTUNPacket(fromIPAddress, stun); } } }
19,813
4,875
#include <bits/stdc++.h> using namespace std; long long t = 1, n = 1, m, k; int main(){ cin>>k>>m; while(t % m != k){ n++; t *= 10; t++; } cout<<n<<endl; return 0; }
190
97
// maindlg.cpp : implementation of the CMainDlg class // ///////////////////////////////////////////////////////////////////////////// #include "stdafx.h" #include "resource.h" #include "maindlg.h" BOOL CMainDlg::PreTranslateMessage(MSG* pMsg) { return CWindow::IsDialogMessage(pMsg); } LRESULT CMainDlg::OnInitDialog(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM /*lParam*/, BOOL& /*bHandled*/) { CRegKey reg; DWORD cbSize; // center the dialog on the screen CenterWindow(); // set icons HICON hIcon = (HICON)::LoadImage(_Module.GetResourceInstance(), MAKEINTRESOURCE(IDR_MAINFRAME), IMAGE_ICON, ::GetSystemMetrics(SM_CXICON), ::GetSystemMetrics(SM_CYICON), LR_DEFAULTCOLOR); SetIcon(hIcon, TRUE); HICON hIconSmall = (HICON)::LoadImage(_Module.GetResourceInstance(), MAKEINTRESOURCE(IDR_MAINFRAME), IMAGE_ICON, ::GetSystemMetrics(SM_CXSMICON), ::GetSystemMetrics(SM_CYSMICON), LR_DEFAULTCOLOR); SetIcon(hIconSmall, FALSE); // register object for message filtering and idle updates CMessageLoop* pLoop = _Module.GetMessageLoop(); ATLASSERT(pLoop != NULL); pLoop->AddMessageFilter(this); m_bFirst = TRUE; m_hWndNextChain = SetClipboardViewer(); m_nCurrentIndex = 0; m_strFormat = TEXT("Capture_%03d.bmp"); cbSize = 512; if(ERROR_SUCCESS == reg.Open(HKEY_CURRENT_USER, TEXT("Software\\Alexyack\\Clipboard Monitor"))) { reg.QueryDWORDValue(TEXT("Current Index"), m_nCurrentIndex); reg.QueryStringValue(TEXT("Format String"), m_strFormat.GetBufferSetLength(cbSize), &cbSize); m_strFormat.ReleaseBuffer(); reg.Close(); } DoDataExchange(); return TRUE; } LRESULT CMainDlg::OnAppAbout(WORD /*wNotifyCode*/, WORD /*wID*/, HWND /*hWndCtl*/, BOOL& /*bHandled*/) { CSimpleDialog<IDD_ABOUTBOX> dlg; dlg.DoModal(); return 0; } LRESULT CMainDlg::OnClose(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM /*lParam*/, BOOL& /*bHandled*/) { CloseDialog(IDOK); return 0; } void CMainDlg::CloseDialog(int nVal) { CRegKey reg; ChangeClipboardChain(m_hWndNextChain); if(ERROR_SUCCESS == reg.Create(HKEY_CURRENT_USER, TEXT("Software\\Alexyack\\Clipboard Monitor"))) { reg.SetDWORDValue(TEXT("Current Index"), m_nCurrentIndex); reg.SetStringValue(TEXT("Format String"), m_strFormat); reg.Close(); } DestroyWindow(); ::PostQuitMessage(nVal); } LRESULT CMainDlg::OnChangeClipChain(UINT uMsg, WPARAM wParam, LPARAM lParam, BOOL& /*bHandled*/) { HWND hWndToRemove = HWND(wParam); HWND hWndNextChain = HWND(lParam); if(hWndToRemove == m_hWndNextChain) m_hWndNextChain = hWndNextChain; else ::SendMessage(m_hWndNextChain, uMsg, wParam, lParam); return 0; } LRESULT CMainDlg::OnDrawClipboard(UINT uMsg, WPARAM wParam, LPARAM lParam, BOOL& /*bHandled*/) { CBitmap bmp; CImage image; WTL::CString strname; WIN32_FILE_ATTRIBUTE_DATA faData; BOOL bInfo; ::SendMessage(m_hWndNextChain, uMsg, wParam, lParam); if(m_bFirst) { m_bFirst = FALSE; return 0; } if(OpenClipboard()) { bmp = HBITMAP(::GetClipboardData(CF_BITMAP)); if(bmp != NULL) { Beep(1200, 10); DoDataExchange(TRUE); do { strname.Format(m_strFormat, m_nCurrentIndex++); bInfo = GetFileAttributesEx(strname, GetFileExInfoStandard, &faData); } while(bInfo); image.Attach(bmp); image.Save(strname); DoDataExchange(); } CloseClipboard(); } return 0; }
3,322
1,427
/* * (C) Copyright 2017 UCAR * * This software is licensed under the terms of the Apache Licence Version 2.0 * which can be obtained at http://www.apache.org/licenses/LICENSE-2.0. */ #include "eckit/config/LocalConfiguration.h" #include "oops/util/abor1_cpp.h" #include "oops/util/DateTime.h" #include "oops/util/Logger.h" #include "mpasjedi/GeometryMPAS.h" #include "mpasjedi/IncrementMPAS.h" #include "mpasjedi/StateMPAS.h" #include "mpasjedi/TlmMPAS.h" namespace mpas { // ----------------------------------------------------------------------------- static oops::interface::LinearModelMaker<MPASTraits, TlmMPAS> makerMPASTLM_("MPASTLM"); // ----------------------------------------------------------------------------- TlmMPAS::TlmMPAS(const GeometryMPAS & resol, const eckit::Configuration & tlConf) : keyConfig_(0), tstep_(), resol_(resol), traj_(), lrmodel_(resol_, eckit::LocalConfiguration(tlConf, "trajectory")), linvars_(tlConf, "tlm variables") { tstep_ = util::Duration(tlConf.getString("tstep")); mpas_model_setup_f90(tlConf, resol_.toFortran(), keyConfig_); oops::Log::trace() << "TlmMPAS created" << std::endl; } // ----------------------------------------------------------------------------- TlmMPAS::~TlmMPAS() { mpas_model_delete_f90(keyConfig_); for (trajIter jtra = traj_.begin(); jtra != traj_.end(); ++jtra) { mpas_model_wipe_traj_f90(jtra->second); } oops::Log::trace() << "TlmMPAS destructed" << std::endl; } // ----------------------------------------------------------------------------- void TlmMPAS::setTrajectory(const StateMPAS & xx, StateMPAS & xlr, const ModelBiasMPAS & bias) { // StateMPAS xlr(resol_, xx); xlr.changeResolution(xx); int ftraj = lrmodel_.saveTrajectory(xlr, bias); traj_[xx.validTime()] = ftraj; // should be in print method std::vector<double> zstat(15); // mpas_traj_minmaxrms_f90(ftraj, zstat[0]); oops::Log::debug() << "TlmMPAS trajectory at time " << xx.validTime() << std::endl; for (unsigned int jj = 0; jj < 5; ++jj) { oops::Log::debug() << " Min=" << zstat[3*jj] << ", Max=" << zstat[3*jj+1] << ", RMS=" << zstat[3*jj+2] << std::endl; } // should be in print method } // ----------------------------------------------------------------------------- void TlmMPAS::initializeTL(IncrementMPAS & dx) const { mpas_model_prepare_integration_tl_f90(keyConfig_, dx.toFortran()); oops::Log::debug() << "TlmMPAS::initializeTL" << dx << std::endl; } // ----------------------------------------------------------------------------- void TlmMPAS::stepTL(IncrementMPAS & dx, const ModelBiasIncrementMPAS &) const { trajICst itra = traj_.find(dx.validTime()); if (itra == traj_.end()) { oops::Log::error() << "TlmMPAS: trajectory not available at time " << dx.validTime() << std::endl; ABORT("TlmMPAS: trajectory not available"); } oops::Log::debug() << "TlmMPAS::stepTL increment in" << dx << std::endl; mpas_model_propagate_tl_f90(keyConfig_, dx.toFortran(), itra->second); oops::Log::debug() << "TlmMPAS::stepTL increment out"<< dx << std::endl; dx.validTime() += tstep_; } // ----------------------------------------------------------------------------- void TlmMPAS::finalizeTL(IncrementMPAS & dx) const { oops::Log::debug() << "TlmMPAS::finalizeTL" << dx << std::endl; } // ----------------------------------------------------------------------------- void TlmMPAS::initializeAD(IncrementMPAS & dx) const { oops::Log::debug() << "TlmMPAS::initializeAD" << dx << std::endl; } // ----------------------------------------------------------------------------- void TlmMPAS::stepAD(IncrementMPAS & dx, ModelBiasIncrementMPAS &) const { dx.validTime() -= tstep_; trajICst itra = traj_.find(dx.validTime()); if (itra == traj_.end()) { oops::Log::error() << "TlmMPAS: trajectory not available at time " << dx.validTime() << std::endl; ABORT("TlmMPAS: trajectory not available"); } oops::Log::debug() << "TlmMPAS::stepAD increment in" << dx << std::endl; mpas_model_propagate_ad_f90(keyConfig_, dx.toFortran(), itra->second); oops::Log::debug() << "TlmMPAS::stepAD increment out" << dx << std::endl; } // ----------------------------------------------------------------------------- void TlmMPAS::finalizeAD(IncrementMPAS & dx) const { mpas_model_prepare_integration_ad_f90(keyConfig_, dx.toFortran()); oops::Log::debug() << "TlmMPAS::finalizeAD" << dx << std::endl; } // ----------------------------------------------------------------------------- void TlmMPAS::print(std::ostream & os) const { os << "MPAS TLM Trajectory, nstep=" << traj_.size() << std::endl; typedef std::map< util::DateTime, int >::const_iterator trajICst; if (traj_.size() > 0) { os << "MPAS TLM Trajectory: times are:"; for (trajICst jtra = traj_.begin(); jtra != traj_.end(); ++jtra) { os << " " << jtra->first; } } } // ----------------------------------------------------------------------------- } // namespace mpas
5,180
1,718
/*** * Copyright (C) Microsoft. All rights reserved. * Licensed under the MIT license. See LICENSE.txt file in the project root for full license information. * * File:MoObservableObjectClassAdapter.cpp ****/ #include "pch.h" #include "MoObservableObjectClassAdapter.h" #include "MoObservableObjectFactory.h" // This class adapts from code delegate callbkack to the winrt version of it to allow overriding from winrt code. class CInvokeDelegate : public foundation::ctl::Implements <pmod::library::IMethodOnInvokeDelegate, &pmod::library::IID_IMethodOnInvokeDelegate > { public: HRESULT _Initialize(ABI::Microsoft::PropertyModel::Library::IInvokeDelegate *pInvokeMethodDelegate) { _spMoOnInvokeMethodDelegate = pInvokeMethodDelegate; return S_OK; } static HRESULT GetModernDelegateFromCore(pmod::library::IMethodOnInvokeDelegate *pDelegate, ABI::Microsoft::PropertyModel::Library::IInvokeDelegate **ppModernDelegate) { foundation_assert(ppModernDelegate); if (pDelegate) { CInvokeDelegate * pInternalDelegate = static_cast<CInvokeDelegate *>(pDelegate); pInternalDelegate->_spMoOnInvokeMethodDelegate.CopyTo(ppModernDelegate); } else { *ppModernDelegate = nullptr; } return S_OK; } protected: STDMETHOD(Invoke) ( _In_ foundation::IMethodInfo *pMethodInfo, _In_ UINT32 methodId, _In_ UINT32 size, _In_ foundation::IInspectable **parameters, _Outptr_ foundation::IInspectable **ppValue) { bool isAsync; pMethodInfo->GetIsAsync(&isAsync); if (isAsync) { // winRT is not able to see the IAsyncOperation we are passing std::vector<IInspectable *> parameters_; IFR_ASSERT(CMoObservableObjectDelegateAdapter::CreateAsyncParameters(size, parameters, *ppValue, parameters_)); foundation::InspectablePtr ignore_result_ptr; return _spMoOnInvokeMethodDelegate->Invoke( methodId, size + 1, (IInspectable **)&parameters_.front(), ignore_result_ptr.GetAddressOf()); } else { return _spMoOnInvokeMethodDelegate->Invoke(methodId, size, parameters, ppValue); } } private: foundation::ComPtr<ABI::Microsoft::PropertyModel::Library::IInvokeDelegate> _spMoOnInvokeMethodDelegate; }; HRESULT STDMETHODCALLTYPE CMoObservableObjectClassAdapter::put_InvokeDelegate(ABI::Microsoft::PropertyModel::Library::IInvokeDelegate* value) { foundation::ComPtr<pmod::library::IMethodOnInvokeDelegate> spOnInvokeMethodDelegate; if (value != nullptr) { IFR_ASSERT(foundation::ctl::CreateInstanceWithInitialize<CInvokeDelegate>(spOnInvokeMethodDelegate.GetAddressOf(), value)); } return m_pInner->SetMethodOnInvokeDelegate(spOnInvokeMethodDelegate); } HRESULT STDMETHODCALLTYPE CMoObservableObjectClassAdapter::get_InvokeDelegate(ABI::Microsoft::PropertyModel::Library::IInvokeDelegate** value) { foundation::ComPtr<pmod::library::IMethodOnInvokeDelegate> spOnInvokeMethodDelegate; IFR_ASSERT(m_pInner->GetMethodOnInvokeDelegate(spOnInvokeMethodDelegate.GetAddressOf())); return CInvokeDelegate::GetModernDelegateFromCore(spOnInvokeMethodDelegate, value); } HRESULT STDMETHODCALLTYPE CMoObservableObjectClassAdapter::SetPropertyInternal(unsigned int propertyId, IInspectable *value) { return m_pInner->SetPropertyInternal(propertyId, value, true); } HRESULT STDMETHODCALLTYPE CMoObservableObjectClassAdapter::FirePropertyChanged(unsigned int propertyId, boolean useCallback) { return m_pInner->FirePropertyChanged(propertyId, useCallback ? true : false); } HRESULT STDMETHODCALLTYPE CMoObservableObjectClassAdapter::FireEventModel(unsigned int eventId, IInspectable *eventArgs) { return m_pInner->FireEventModel(eventId, eventArgs); } HRESULT STDMETHODCALLTYPE CMoObservableObjectClassAdapter::SetBinding( unsigned int propertyId, IBindingBase *propertyBinding) { IFCPTR(propertyBinding); foundation::ComPtr<pmod::IBindingBase> spPropertyBinding; IFR(foundation::QueryInterface(propertyBinding, spPropertyBinding.GetAddressOf())); return m_pInner->SetBinding(propertyId, spPropertyBinding); } HRESULT STDMETHODCALLTYPE CMoObservableObjectClassAdapter::ClearBinding( unsigned int propertyId) { return m_pInner->ClearBinding(propertyId); }
4,637
1,334
/////////////////////////////////////////////////////////////////////////////// /// /// \file ComponentHierarchy.cpp /// /// Authors: Joshua Claeys /// Copyright 2015, DigiPen Institute of Technology /// /////////////////////////////////////////////////////////////////////////////// #pragma once namespace Zero { //----------------------------------------------------- Component Hierarchy Base /// Needed for an intrusive link template <typename ComponentType> class ComponentHierarchyBase : public Component { public: IntrusiveLink(ComponentHierarchyBase<ComponentType>, HierarchyLink); }; //---------------------------------------------------------- Component Hierarchy /// Maintains a hierarchy of specific Components. When a hierarchy of Components /// is required, this removes the need to manually manage the hierarchy, and /// also removes the overhead of component lookups while iterating over the /// hierarchy. template <typename ComponentType> class ComponentHierarchy : public ComponentHierarchyBase<ComponentType> { public: ZilchDeclareType(TypeCopyMode::ReferenceType); // Typedefs. typedef ComponentHierarchy<ComponentType> self_type; typedef ComponentHierarchyBase<ComponentType> BaseType; typedef BaseInList<BaseType, ComponentType, &BaseType::HierarchyLink> ChildList; typename typedef ChildList::range ChildListRange; typename typedef ChildList::reverse_range ChildListReverseRange; /// Constructor. ComponentHierarchy(); ~ComponentHierarchy(); /// Component Interface. void Initialize(CogInitializer& initializer) override; void AttachTo(AttachmentInfo& info) override; void Detached(AttachmentInfo& info) override; /// When a child is attached or detached, we need to update our child list. void OnChildAttached(HierarchyEvent* e); void OnChildDetached(HierarchyEvent* e); void OnChildrenOrderChanged(Event* e); /// Tree traversal helpers. ComponentType* GetPreviousSibling(); ComponentType* GetNextSibling(); ComponentType* GetLastDirectChild(); ComponentType* GetLastDeepestChild(); ComponentType* GetNextInHierarchyOrder(); ComponentType* GetPreviousInHierarchyOrder(); ComponentType* GetRoot(); /// Returns whether or not we are a descendant of the given Cog. bool IsDescendantOf(ComponentType& ancestor); /// Returns whether or not we are an ancestor of the given Cog. bool IsAncestorOf(ComponentType& descendant); typename ChildListRange GetChildren(){return mChildren.All();} typename ChildListReverseRange GetChildrenReverse() { return mChildren.ReverseAll(); } /// Returns the amount of children. Note that this function has to iterate over /// all children to calculate the count. uint GetChildCount(); ComponentType* mParent; ChildList mChildren; }; //****************************************************************************** template <typename ComponentType> ZilchDefineType(ComponentHierarchy<ComponentType>, builder, type) { ZeroBindDocumented(); ZilchBindGetter(PreviousSibling); ZilchBindGetter(NextSibling); ZilchBindGetter(LastDirectChild); ZilchBindGetter(LastDeepestChild); ZilchBindGetter(NextInHierarchyOrder); ZilchBindGetter(PreviousInHierarchyOrder); ZilchBindFieldGetter(mParent); ZilchBindGetter(Root); ZilchBindGetter(ChildCount); ZilchBindMethod(GetChildren); ZilchBindMethod(IsDescendantOf); ZilchBindMethod(IsAncestorOf); } //****************************************************************************** template <typename ComponentType> ComponentHierarchy<ComponentType>::ComponentHierarchy() : mParent(nullptr) { } //****************************************************************************** template <typename ComponentType> ComponentHierarchy<ComponentType>::~ComponentHierarchy() { forRange(ComponentType& child, GetChildren()) child.mParent = nullptr; if (mParent) mParent->mChildren.Erase(this); mChildren.Clear(); } //****************************************************************************** template <typename ComponentType> void ComponentHierarchy<ComponentType>::Initialize(CogInitializer& initializer) { // Add ourself to our parent if(Cog* parent = GetOwner()->GetParent()) { if(ComponentType* component = parent->has(ComponentType)) { mParent = component; mParent->mChildren.PushBack(this); } } // If we were dynamically added, we need to add all of our children. If we // aren't dynamically added, our children will add themselves to our child list // in their initialize if (initializer.Flags & CreationFlags::DynamicallyAdded) { forRange(Cog& childCog, GetOwner()->GetChildren()) { if (ComponentType* child = childCog.has(ComponentType)) { child->mParent = (ComponentType*)this; mChildren.PushBack(child); } } } ConnectThisTo(GetOwner(), Events::ChildAttached, OnChildAttached); ConnectThisTo(GetOwner(), Events::ChildDetached, OnChildDetached); ConnectThisTo(GetOwner(), Events::ChildrenOrderChanged, OnChildrenOrderChanged); } //****************************************************************************** template <typename ComponentType> void ComponentHierarchy<ComponentType>::OnChildAttached(HierarchyEvent* e) { if(e->Parent != GetOwner()) return; if(ComponentType* component = e->Child->has(ComponentType)) mChildren.PushBack(component); } //****************************************************************************** template <typename ComponentType> void ComponentHierarchy<ComponentType>::OnChildDetached(HierarchyEvent* e) { if(e->Parent != GetOwner()) return; if(ComponentType* component = e->Child->has(ComponentType)) mChildren.Erase(component); } //****************************************************************************** template <typename ComponentType> void ComponentHierarchy<ComponentType>::OnChildrenOrderChanged(Event* e) { // The event isn't currently sent information as to which object moved // where, so we're just going to re-build the child list mChildren.Clear(); forRange(Cog& child, GetOwner()->GetChildren()) { if(ComponentType* childComponent = child.has(ComponentType)) mChildren.PushBack(childComponent); } } //****************************************************************************** template <typename ComponentType> void ComponentHierarchy<ComponentType>::AttachTo(AttachmentInfo& info) { if(info.Child == GetOwner()) mParent = info.Parent->has(ComponentType); } //****************************************************************************** template <typename ComponentType> void ComponentHierarchy<ComponentType>::Detached(AttachmentInfo& info) { if(info.Child == GetOwner()) mParent = nullptr; } //****************************************************************************** template <typename ComponentType> ComponentType* ComponentHierarchy<ComponentType>::GetPreviousSibling() { ComponentType* prev = (ComponentType*)ChildList::Prev(this); if(mParent && prev != mParent->mChildren.End()) return prev; return nullptr; } //****************************************************************************** template <typename ComponentType> ComponentType* ComponentHierarchy<ComponentType>::GetNextSibling() { ComponentType* next = (ComponentType*)ChildList::Next(this); if(mParent && next != mParent->mChildren.End()) return next; return nullptr; } //****************************************************************************** template <typename ComponentType> ComponentType* ComponentHierarchy<ComponentType>::GetLastDirectChild() { if(!mChildren.Empty()) return &mChildren.Back(); return nullptr; } //****************************************************************************** template <typename ComponentType> ComponentType* ComponentHierarchy<ComponentType>::GetLastDeepestChild() { if (UiWidget* lastChild = GetLastDirectChild()) return lastChild->GetLastDeepestChild(); else return (ComponentType*)this; } //****************************************************************************** template <typename ComponentType> ComponentType* ComponentHierarchy<ComponentType>::GetNextInHierarchyOrder() { // If this object has children return the first child if(!mChildren.Empty()) return &mChildren.Front(); // Return next sibling if there is one ComponentType* nextSibling = GetNextSibling(); if(nextSibling) return nextSibling; // Loop until the root or a parent has a sibling ComponentType* parent = mParent; while(parent != nullptr) { ComponentType* parentSibling = parent->GetNextSibling(); if(parentSibling) return parentSibling; else parent = parent->mParent; } return nullptr; } //****************************************************************************** template <typename ComponentType> ComponentType* ComponentHierarchy<ComponentType>::GetPreviousInHierarchyOrder() { // Get prev sibling if there is one ComponentType* prevSibling = GetPreviousSibling(); // If this is first node of a child it is previous node if(prevSibling == nullptr) return mParent; // Return the last child of the sibling return prevSibling->GetLastDeepestChild(); } //****************************************************************************** template <typename ComponentType> ComponentType* ComponentHierarchy<ComponentType>::GetRoot() { ComponentType* curr = (ComponentType*)this; while(curr->mParent) curr = curr->mParent; return curr; } //****************************************************************************** template <typename ComponentType> bool ComponentHierarchy<ComponentType>::IsDescendantOf(ComponentType& ancestor) { return ancestor.IsAncestorOf(*(ComponentType*)this); } //****************************************************************************** template <typename ComponentType> bool ComponentHierarchy<ComponentType>::IsAncestorOf(ComponentType& descendant) { ComponentType* current = &descendant; while (current) { current = current->mParent; if (current == this) return true; } return false; } //****************************************************************************** template <typename ComponentType> uint ComponentHierarchy<ComponentType>::GetChildCount() { uint count = 0; forRange(ComponentType& child, GetChildren()) ++count; return count; } }//namespace Zero
10,758
2,900
// Copyright (c) 2015 Samsung Electronics Co., Ltd All Rights Reserved // Use of this source code is governed by an apache-2.0 license that can be // found in the LICENSE file. #include "common/step/recovery/step_open_recovery_file.h" #include <cassert> #include "common/recovery_file.h" namespace common_installer { namespace recovery { Step::Status StepOpenRecoveryFile::process() { std::unique_ptr<recovery::RecoveryFile> recovery_file = RecoveryFile::OpenRecoveryFileForPath(context_->file_path.get()); if (!recovery_file) { LOG(ERROR) << "Failed to open recovery file"; return Status::RECOVERY_ERROR; } context_->unpacked_dir_path.set(recovery_file->unpacked_dir()); context_->pkgid.set(recovery_file->pkgid()); switch (recovery_file->type()) { case RequestType::Install: LOG(INFO) << "Running recovery for new installation"; break; case RequestType::Update: LOG(INFO) << "Running recovery for update installation"; break; default: assert(false && "Not reached"); } context_->recovery_info.set(RecoveryInfo(std::move(recovery_file))); return Status::OK; } Step::Status StepOpenRecoveryFile::undo() { // Detach object from underlaying file so it will not be removed // as recovery failed. if (context_->recovery_info.get().recovery_file) context_->recovery_info.get().recovery_file->Detach(); return Status::OK; } } // namespace recovery } // namespace common_installer
1,454
469
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ #include <iostream> #include "Info.hpp" using namespace std; const string Info::institution = "Unicamp - Universidade Estadual de Campinas"; const string Info::dept = "FT - Faculdade de Tecnologia"; const string Info::author = "Prof. Dr. Andre F. de Angelis"; const string Info::date = "Jun/2016"; const string Info::sysName = "FT - Project Chain"; const string Info::sysVersion = "1.0"; const string Info::decoration = "!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\n"; const string Info::getInstitution() { return (institution); }; const string Info::getDept() { return (dept); }; const string Info::getAuthor() { return (author); }; const string Info::getDate() { return (date); }; const string Info::getSysName() { return (sysName); } const string Info::getSysVersion() { return(sysVersion); } const void Info::wellcome() { cout << decoration; cout << Info::getSysName() << "\t Ver. " << Info::getSysVersion() << endl; cout << decoration; cout << Info::getInstitution() << "\n" << Info::getDept() << endl; cout << Info::getAuthor() << "\n" << Info::getDate() << endl; cout << decoration << endl; }; const void Info::goodbye() { cout << decoration; cout << Info::getSysName() << "\t Ver. " << Info::getSysVersion() << endl; cout << decoration; cout << "\n\n" << endl; };
1,602
541
// ***************************************************************************** // // Copyright (c) 2013, Pleora Technologies Inc., All rights reserved. // // ***************************************************************************** #include "eBUSPlayerShared.h" #include "ChangeSourceTask.h" #ifdef _AFXDLL IMPLEMENT_DYNAMIC( ChangeSourceTask, Task ) #endif // _AFXDLL
388
111
// // Copyright Copyright 2009-2022, AMT – The Association For Manufacturing Technology (“AMT”) // 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. // #pragma once #include "observation/observation.hpp" #include "ruby_entity.hpp" #include "ruby_vm.hpp" namespace mtconnect::ruby { using namespace mtconnect::observation; using namespace std; using namespace Rice; struct RubyObservation { static void initialize(mrb_state *mrb, RClass *module) { auto entityClass = mrb_class_get_under(mrb, module, "Entity"); auto observationClass = mrb_define_class_under(mrb, module, "Observation", entityClass); MRB_SET_INSTANCE_TT(observationClass, MRB_TT_DATA); mrb_define_method( mrb, observationClass, "initialize", [](mrb_state *mrb, mrb_value self) { using namespace device_model::data_item; mrb_value di; mrb_value props; mrb_value ts; ErrorList errors; Timestamp time; auto count = mrb_get_args(mrb, "oo|o", &di, &props, &ts); auto dataItem = MRubySharedPtr<Entity>::unwrap<DataItem>(mrb, di); if (count < 3) time = std::chrono::system_clock::now(); else time = timestampFromRuby(mrb, ts); Properties values; fromRuby(mrb, props, values); ObservationPtr obs = Observation::make(dataItem, values, time, errors); if (errors.size() > 0) { ostringstream str; for (auto &e : errors) { str << e->what() << ", "; } mrb_raise(mrb, E_ARGUMENT_ERROR, str.str().c_str()); } MRubySharedPtr<Entity>::replace(mrb, self, obs); return self; }, MRB_ARGS_ARG(2, 1)); mrb_define_method( mrb, observationClass, "dup", [](mrb_state *mrb, mrb_value self) { ObservationPtr old = MRubySharedPtr<Entity>::unwrap<Observation>(mrb, self); RClass *klass = mrb_class(mrb, self); auto dup = old->copy(); return MRubySharedPtr<Entity>::wrap(mrb, klass, dup); }, MRB_ARGS_NONE()); mrb_alias_method(mrb, observationClass, mrb_intern_lit(mrb, "copy"), mrb_intern_lit(mrb, "dup")); mrb_define_method( mrb, observationClass, "data_item", [](mrb_state *mrb, mrb_value self) { ObservationPtr obs = MRubySharedPtr<Entity>::unwrap<Observation>(mrb, self); return MRubySharedPtr<Entity>::wrap(mrb, "DataItem", obs->getDataItem()); }, MRB_ARGS_NONE()); mrb_define_method( mrb, observationClass, "timestamp", [](mrb_state *mrb, mrb_value self) { ObservationPtr obs = MRubySharedPtr<Entity>::unwrap<Observation>(mrb, self); return toRuby(mrb, obs->getTimestamp()); }, MRB_ARGS_NONE()); auto eventClass = mrb_define_class_under(mrb, module, "Event", observationClass); MRB_SET_INSTANCE_TT(eventClass, MRB_TT_DATA); auto sampleClass = mrb_define_class_under(mrb, module, "Sample", observationClass); MRB_SET_INSTANCE_TT(sampleClass, MRB_TT_DATA); auto conditionClass = mrb_define_class_under(mrb, module, "Condition", observationClass); MRB_SET_INSTANCE_TT(conditionClass, MRB_TT_DATA); } }; } // namespace mtconnect::ruby
4,066
1,268
#include <stdio.h> #include <iostream> #include <vector> #include <unordered_map> using namespace std; #define MOVE(tx, ty, ch) (tabuleiro[tx][ty] = ch) //! Variáveis globais vector<pair<int, int>> inimigos; pair<int, int> jogador; char tabuleiro[9][8]; bool destroi_inimigos(int nivel) { if (nivel == 10 && inimigos.empty()) return true; if (nivel == 10) return false; //! Não consegui matar for (int i = -1; i <= 1; i++) { for (int j = -1; j <= 1; j++) { if (i == 0 && j == 0 || i == -1 && jogador.first == 0 || i == 1 && jogador.first == 8 || j == -1 && jogador.second == 0 || j == 1 && jogador.second == 7 ) continue; bool morte = false; pair<int, int> antigo_jogador = jogador; vector<pair<int, int>> antigos_inimigos(inimigos.begin(), inimigos.end()); unordered_map<int, int> olds; inimigos.clear(); jogador = {jogador.first + i, jogador.second + j}; if (tabuleiro[jogador.first][jogador.second] == 'E' || tabuleiro[jogador.first][jogador.second] == '#') { morte = true; goto morte_label; } MOVE(antigo_jogador.first, antigo_jogador.second, '.'); MOVE(jogador.first, jogador.second, 'S'); for (auto i : antigos_inimigos) { int ix = i.first + (jogador.first < i.first ? -1 : jogador.first > i.first ? 1 : 0); int iy = i.second + (jogador.second < i.second ? -1 : jogador.second > i.second ? 1 : 0); if (tabuleiro[ix][iy] == '.') { inimigos.push_back({ix, iy}); olds[ix * 100 + iy] = i.first * 100 + i.second; MOVE(i.first, i.second, '.'); MOVE(ix, iy, 'E'); } else if (tabuleiro[ix][iy] == 'S') { morte = true; break; } } if (!morte) if (destroi_inimigos(nivel + 1)) return true; for (auto p : olds) { MOVE(p.first/100, p.first%10, '.'); MOVE(p.second/100, p.second%10, 'E'); } MOVE(jogador.first, jogador.second, '.'); MOVE(antigo_jogador.first, antigo_jogador.second, 'S'); morte_label: jogador = antigo_jogador; inimigos = antigos_inimigos; } } return false; } int main(void) { int casos; cin >> casos; for (int c = 0; c < casos; c++) { for (int i = 0; i < 9; i++) { for (int j = 0; j < 8; j++) { cin >> tabuleiro[i][j]; if (tabuleiro[i][j] == 'S') jogador = {i, j}; else if (tabuleiro[i][j] == 'E') inimigos.push_back({i, j}); } } if (destroi_inimigos(0)) cout << "I'm the king of the Seven Seas!" << endl; else cout << "Oh no! I'm a dead man!" << endl; inimigos.clear(); } }
3,341
1,152
/* * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ #include <array> #include <fstream> #include <gtest/gtest.h> #include "ApkResources.h" #include "Debug.h" #include "RedexMappedFile.h" #include "RedexResources.h" #include "RedexTestUtils.h" #include "SanitizersConfig.h" #include "androidfw/ResourceTypes.h" #include "utils/Serialize.h" #include "utils/Visitor.h" namespace { // Chunk of just the ResStringPool, as generated by aapt2 (has 2 UTF8 strings) const std::array<uint8_t, 84> example_data_8{ {0x01, 0x00, 0x1C, 0x00, 0x54, 0x00, 0x00, 0x00, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x24, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x0F, 0x00, 0x00, 0x00, 0x0C, 0x0C, 0x48, 0x65, 0x6C, 0x6C, 0x6F, 0x2C, 0x20, 0x77, 0x6F, 0x72, 0x6C, 0x64, 0x00, 0x1C, 0x1C, 0x72, 0x65, 0x73, 0x2F, 0x6C, 0x61, 0x79, 0x6F, 0x75, 0x74, 0x2F, 0x73, 0x69, 0x6D, 0x70, 0x6C, 0x65, 0x5F, 0x6C, 0x61, 0x79, 0x6F, 0x75, 0x74, 0x2E, 0x78, 0x6D, 0x6C, 0x00, 0x00, 0x00}}; // Another aapt2 generated ResStringPool, encoded as UTF-16. const std::array<uint8_t, 116> example_data_16{ {0x01, 0x00, 0x1C, 0x00, 0x74, 0x00, 0x00, 0x00, 0x05, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x30, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x0E, 0x00, 0x00, 0x00, 0x1C, 0x00, 0x00, 0x00, 0x24, 0x00, 0x00, 0x00, 0x34, 0x00, 0x00, 0x00, 0x05, 0x00, 0x63, 0x00, 0x6F, 0x00, 0x6C, 0x00, 0x6F, 0x00, 0x72, 0x00, 0x00, 0x00, 0x05, 0x00, 0x64, 0x00, 0x69, 0x00, 0x6D, 0x00, 0x65, 0x00, 0x6E, 0x00, 0x00, 0x00, 0x02, 0x00, 0x69, 0x00, 0x64, 0x00, 0x00, 0x00, 0x06, 0x00, 0x6C, 0x00, 0x61, 0x00, 0x79, 0x00, 0x6F, 0x00, 0x75, 0x00, 0x74, 0x00, 0x00, 0x00, 0x06, 0x00, 0x73, 0x00, 0x74, 0x00, 0x72, 0x00, 0x69, 0x00, 0x6E, 0x00, 0x67, 0x00, 0x00, 0x00}}; std::string make_big_string(size_t len) { always_assert(len > 4); std::string result = "aa" + std::string(len - 4, 'x') + "zz"; return result; } void assert_u16_string(const std::u16string& actual_str, const std::string& expected) { std::u16string expected_str(expected.begin(), expected.end()); ASSERT_EQ(actual_str, expected_str); } void assert_serialized_data(const void* original, size_t length, android::Vector<char>& serialized) { ASSERT_EQ(length, serialized.size()); for (size_t i = 0; i < length; i++) { auto actual = *((const char*)original + i); ASSERT_EQ(actual, serialized[i]); } } void copy_file(const std::string& from, const std::string& to) { std::ifstream src_stream(from, std::ios::binary); std::ofstream dest_stream(to, std::ios::binary); dest_stream << src_stream.rdbuf(); } bool are_files_equal(const std::string& p1, const std::string& p2) { std::ifstream f1(p1, std::ifstream::binary | std::ifstream::ate); std::ifstream f2(p2, std::ifstream::binary | std::ifstream::ate); always_assert_log(!f1.fail(), "Failed to read path %s", p1.c_str()); always_assert_log(!f2.fail(), "Failed to read path %s", p2.c_str()); if (f1.tellg() != f2.tellg()) { std::cerr << "File length mismatch. " << f1.tellg() << " != " << f2.tellg() << std::endl; return false; } f1.seekg(0, std::ifstream::beg); f2.seekg(0, std::ifstream::beg); return std::equal(std::istreambuf_iterator<char>(f1.rdbuf()), std::istreambuf_iterator<char>(), std::istreambuf_iterator<char>(f2.rdbuf())); } } // namespace TEST(ResStringPool, AppendToEmptyTable) { const size_t header_size = sizeof(android::ResStringPool_header); android::ResStringPool_header header = { {htods(android::RES_STRING_POOL_TYPE), htods(header_size), htodl(header_size)}, 0, 0, htodl(android::ResStringPool_header::UTF8_FLAG | android::ResStringPool_header::SORTED_FLAG), 0, 0}; android::ResStringPool pool((void*)&header, header_size, false); pool.appendString(android::String8("Hello, world")); auto big_string = make_big_string(300); auto big_chars = big_string.c_str(); pool.appendString(android::String8(big_chars)); pool.appendString(android::String8("€666")); pool.appendString(android::String8("banana banana")); android::Vector<char> v; pool.serialize(v); auto data = (void*)v.array(); android::ResStringPool after(data, v.size(), false); // Ensure sort bit was cleared. auto flags = dtohl(((android::ResStringPool_header*)data)->flags); ASSERT_FALSE(flags & android::ResStringPool_header::SORTED_FLAG); size_t out_len; ASSERT_STREQ(after.string8At(0, &out_len), "Hello, world"); ASSERT_EQ(out_len, 12); ASSERT_STREQ(after.string8At(1, &out_len), big_chars); ASSERT_EQ(out_len, 300); ASSERT_STREQ(after.string8At(2, &out_len), "€666"); ASSERT_STREQ(after.string8At(3, &out_len), "banana banana"); } TEST(ResStringPool, AppendToExistingUTF8) { android::ResStringPool pool(&example_data_8, example_data_8.size(), false); size_t out_len; ASSERT_STREQ(pool.string8At(0, &out_len), "Hello, world"); pool.appendString(android::String8("this is another string")); android::Vector<char> v; pool.serialize(v); android::ResStringPool after((void*)v.array(), v.size(), false); // Make sure we still have the original two strings ASSERT_STREQ(after.string8At(0, &out_len), "Hello, world"); ASSERT_EQ(out_len, 12); ASSERT_STREQ(after.string8At(1, &out_len), "res/layout/simple_layout.xml"); ASSERT_EQ(out_len, 28); // And the one appended ASSERT_STREQ(after.string8At(2, &out_len), "this is another string"); ASSERT_EQ(out_len, 22); } TEST(ResStringPool, AppendToExistingUTF16) { android::ResStringPool pool(&example_data_16, example_data_16.size(), false); ASSERT_TRUE(!pool.isUTF8()); size_t out_len; auto s = pool.stringAt(0, &out_len); assert_u16_string(s, "color"); ASSERT_EQ(out_len, 5); // Make sure the size encoding works for large values. auto big_string = make_big_string(35000); auto big_chars = big_string.c_str(); pool.appendString(android::String8(big_chars)); pool.appendString(android::String8("more more more")); android::Vector<char> v; pool.serialize(v); android::ResStringPool after((void*)v.array(), v.size(), false); assert_u16_string(after.stringAt(0, &out_len), "color"); ASSERT_EQ(out_len, 5); assert_u16_string(after.stringAt(1, &out_len), "dimen"); ASSERT_EQ(out_len, 5); assert_u16_string(after.stringAt(2, &out_len), "id"); ASSERT_EQ(out_len, 2); assert_u16_string(after.stringAt(3, &out_len), "layout"); ASSERT_EQ(out_len, 6); assert_u16_string(after.stringAt(4, &out_len), "string"); ASSERT_EQ(out_len, 6); assert_u16_string(after.stringAt(5, &out_len), big_chars); ASSERT_EQ(out_len, 35000); assert_u16_string(after.stringAt(6, &out_len), "more more more"); ASSERT_EQ(out_len, 14); } TEST(ResStringPool, ReplaceStringsInXmlLayout) { // Given layout file should have a series of View subclasses in the XML, which // we will rename. Parse the resulting binary data, and make sure all tags are // right. auto f = RedexMappedFile::open(std::getenv("test_layout_path")); std::map<std::string, std::string> shortened_names; shortened_names.emplace("com.example.test.CustomViewGroup", "Z.a"); shortened_names.emplace("com.example.test.CustomTextView", "Z.b"); shortened_names.emplace("com.example.test.CustomButton", "Z.c"); shortened_names.emplace("com.example.test.NotFound", "Z.d"); android::Vector<char> serialized; size_t num_renamed = 0; ApkResources resources(""); resources.replace_in_xml_string_pool( f.const_data(), f.size(), shortened_names, &serialized, &num_renamed); EXPECT_EQ(num_renamed, 3); android::ResXMLTree parser; parser.setTo(&serialized[0], serialized.size()); EXPECT_EQ(android::NO_ERROR, parser.getError()) << "Error parsing layout after rename"; std::vector<std::string> expected_xml_tags; expected_xml_tags.push_back("Z.a"); expected_xml_tags.push_back("TextView"); expected_xml_tags.push_back("Z.b"); expected_xml_tags.push_back("Z.c"); expected_xml_tags.push_back("Button"); size_t tag_count = 0; android::ResXMLParser::event_code_t type; do { type = parser.next(); if (type == android::ResXMLParser::START_TAG) { EXPECT_LT(tag_count, 5); size_t len; android::String8 tag(parser.getElementName(&len)); auto actual_chars = tag.string(); auto expected_chars = expected_xml_tags[tag_count].c_str(); EXPECT_STREQ(actual_chars, expected_chars); tag_count++; } } while (type != android::ResXMLParser::BAD_DOCUMENT && type != android::ResXMLParser::END_DOCUMENT); EXPECT_EQ(tag_count, 5); } TEST(ResTable, TestRoundTrip) { auto f = RedexMappedFile::open(std::getenv("test_arsc_path")); android::ResTable table; ASSERT_EQ(table.add(f.const_data(), f.size()), 0); // Just invoke the serialize method to ensure the same data comes back android::Vector<char> serialized; table.serialize(serialized, 0); assert_serialized_data(f.const_data(), f.size(), serialized); } TEST(ResTable, AppendNewType) { auto f = RedexMappedFile::open(std::getenv("test_arsc_path")); android::ResTable table; ASSERT_EQ(table.add(f.const_data(), f.size()), 0); // Read the number of original types. android::Vector<android::String8> original_type_names; table.getTypeNamesForPackage(0, &original_type_names); // Copy some existing entries to a different table, verify serialization const uint8_t dest_type = 3; android::Vector<uint32_t> source_ids; source_ids.push_back(0x7f010000); size_t num_ids = source_ids.size(); android::Vector<android::Res_value> values; for (size_t i = 0; i < num_ids; i++) { android::Res_value val; table.getResource(source_ids[i], &val); values.push_back(val); } // Initializing the ResTable_config is a pain. android::ResTable_config config; memset(&config, 0, sizeof(android::ResTable_config)); config.size = sizeof(android::ResTable_config); android::Vector<android::ResTable_config> config_vec; config_vec.push(config); table.defineNewType( android::String8("foo"), dest_type, config_vec, source_ids); android::Vector<char> serialized; table.serialize(serialized, 0); android::ResTable round_trip; ASSERT_EQ(round_trip.add((void*)serialized.array(), serialized.size()), 0); // Make sure entries exist in 0x7f03xxxx range for (size_t i = 0; i < num_ids; i++) { auto old_id = source_ids[i]; auto new_id = 0x7f000000 | (dest_type << 16) | (old_id & 0xFFFF); android::Res_value expected = values[i]; android::Res_value actual; round_trip.getResource(new_id, &actual); ASSERT_EQ(expected.dataType, actual.dataType); ASSERT_EQ(expected.data, actual.data); } // Sanity check values in their original location { android::Res_value out_value; round_trip.getResource(0x7f010000, &out_value); float val = android::complex_value(out_value.data); uint32_t unit = android::complex_unit(out_value.data, false); ASSERT_EQ((int)val, 10); ASSERT_EQ(unit, android::Res_value::COMPLEX_UNIT_DIP); } { android::Res_value out_value; round_trip.getResource(0x7f010001, &out_value); float val = android::complex_value(out_value.data); uint32_t unit = android::complex_unit(out_value.data, false); ASSERT_EQ((int)val, 20); ASSERT_EQ(unit, android::Res_value::COMPLEX_UNIT_DIP); } android::Vector<android::String8> type_names; round_trip.getTypeNamesForPackage(0, &type_names); ASSERT_EQ(type_names.size(), original_type_names.size() + 1); } TEST(ResStringPoolBuilder, TestPoolRebuild8) { android::ResStringPool pool(&example_data_8, example_data_8.size(), false); auto flags = (pool.isUTF8() ? android::ResStringPool_header::UTF8_FLAG : 0) | (pool.isSorted() ? android::ResStringPool_header::SORTED_FLAG : 0); auto pool_size = pool.size(); arsc::ResStringPoolBuilder builder(flags); for (size_t i = 0; i < pool_size; i++) { size_t out_len; auto s = pool.string8At(i, &out_len); builder.add_string(s, out_len); } android::Vector<char> serialized; builder.serialize(&serialized); assert_serialized_data(&example_data_8, example_data_8.size(), serialized); } TEST(ResStringPoolBuilder, TestPoolRebuild16) { android::ResStringPool pool(&example_data_16, example_data_16.size(), false); auto flags = (pool.isUTF8() ? android::ResStringPool_header::UTF8_FLAG : 0) | (pool.isSorted() ? android::ResStringPool_header::SORTED_FLAG : 0); auto pool_size = pool.size(); arsc::ResStringPoolBuilder builder(flags); for (size_t i = 0; i < pool_size; i++) { size_t out_len; auto s = pool.stringAt(i, &out_len); builder.add_string(s, out_len); } android::Vector<char> serialized; builder.serialize(&serialized); assert_serialized_data(&example_data_16, example_data_16.size(), serialized); } TEST(ResStringPoolBuilder, TestPoolRebuildStyle8) { const std::array<uint8_t, 232> data{ {0x01, 0x00, 0x1c, 0x00, 0xe8, 0x00, 0x00, 0x00, 0x07, 0x00, 0x00, 0x00, 0x02, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x40, 0x00, 0x00, 0x00, 0xa8, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x14, 0x00, 0x00, 0x00, 0x41, 0x00, 0x00, 0x00, 0x50, 0x00, 0x00, 0x00, 0x54, 0x00, 0x00, 0x00, 0x59, 0x00, 0x00, 0x00, 0x5f, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x1c, 0x00, 0x00, 0x00, 0x11, 0x11, 0x41, 0x6e, 0x20, 0x75, 0x6e, 0x75, 0x73, 0x65, 0x64, 0x20, 0x73, 0x74, 0x72, 0x69, 0x6e, 0x67, 0x2e, 0x00, 0x2a, 0x2a, 0x49, 0x20, 0x6c, 0x69, 0x6b, 0x65, 0x20, 0x61, 0x20, 0x66, 0x69, 0x6e, 0x65, 0x20, 0x67, 0x6c, 0x61, 0x73, 0x73, 0x20, 0x6f, 0x66, 0x20, 0x48, 0x32, 0x4f, 0x20, 0x69, 0x6e, 0x20, 0x74, 0x68, 0x65, 0x20, 0x6d, 0x6f, 0x72, 0x6e, 0x69, 0x6e, 0x67, 0x21, 0x00, 0x0c, 0x0c, 0x48, 0x65, 0x6c, 0x6c, 0x6f, 0x20, 0x57, 0x6f, 0x72, 0x6c, 0x64, 0x2e, 0x00, 0x01, 0x01, 0x62, 0x00, 0x02, 0x02, 0x65, 0x6d, 0x00, 0x03, 0x03, 0x73, 0x75, 0x62, 0x00, 0x03, 0x03, 0x73, 0x75, 0x70, 0x00, 0x00, 0x00, 0x00, 0x03, 0x00, 0x00, 0x00, 0x03, 0x00, 0x00, 0x00, 0x08, 0x00, 0x00, 0x00, 0x06, 0x00, 0x00, 0x00, 0x0a, 0x00, 0x00, 0x00, 0x0f, 0x00, 0x00, 0x00, 0xff, 0xff, 0xff, 0xff, 0x04, 0x00, 0x00, 0x00, 0x09, 0x00, 0x00, 0x00, 0x0c, 0x00, 0x00, 0x00, 0x05, 0x00, 0x00, 0x00, 0x18, 0x00, 0x00, 0x00, 0x18, 0x00, 0x00, 0x00, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff}}; android::ResStringPool pool(&data, data.size(), false); auto flags = (pool.isUTF8() ? android::ResStringPool_header::UTF8_FLAG : 0) | (pool.isSorted() ? android::ResStringPool_header::SORTED_FLAG : 0); auto pool_size = pool.size(); auto style_count = pool.styleCount(); arsc::ResStringPoolBuilder builder(flags); for (size_t i = 0; i < pool_size; i++) { size_t out_len; auto s = pool.string8At(i, &out_len); if (i < style_count) { arsc::SpanVector vec; auto span = (android::ResStringPool_span*)pool.styleAt(i); arsc::collect_spans(span, &vec); builder.add_style(s, out_len, vec); } else { builder.add_string(s, out_len); } } EXPECT_EQ(pool.size(), builder.string_count()); android::Vector<char> serialized; builder.serialize(&serialized); assert_serialized_data(&data, data.size(), serialized); } TEST(ResTableParse, TestUnknownPackageChunks) { // A table with one package, which has a fake chunk that is made up. The chunk // that is not known/recognized should just be copied as-is to the output. auto tmp_dir = redex::make_tmp_dir("ResTableParse%%%%%%%%"); auto res_path = tmp_dir.path + "/resources.arsc"; copy_file(std::getenv("resources_unknown_chunk"), res_path); ResourcesArscFile res_table(res_path); res_table.remove_unreferenced_strings(); EXPECT_TRUE( are_files_equal(std::getenv("resources_unknown_chunk"), res_path)); }
16,272
7,593
/* halo_sim is meant to solve the halo problem using a simultaneous algrimth. */ #include "include/state.h" #include "include/hamiltonian.h" #include "include/stepper.h" #include "include/looper.h" #include "include/recorder.h" #include "include/helper.h" #include <iostream> #include <fstream> #include <cmath> #include <ctime> // #include <omp.h> //For openmp using namespace std; int main(int argc, char *argv[]) { // three arguments: { # of total iteractions, # of steps within one calculations, # of threads } /* Check the number of parameters */ if (argc < 4) { // Tell the user how to run the program cerr << "Usage: " << argv[0] << " takes 3 parameters: { # of total iteractions, # of steps within one calculations, # of threads }" << endl; // "Usage messages" are a conventional way of telling the user return 1; } /* Set openmp number of threads */ // omp_set_dynamic(0); // omp_set_num_threads( stoi(argv[3]) ); /* Initializing some constants */ const int Ntop = stoi(argv[1]); // Set how many times the overall iteraction is const int STEPS= stoi(argv[2]); // Set size of the array of z in z direction const int SIZE = 2*STEPS; // Set the size of the array for all states const double range0 = 0.0; // Set initial coordinate for z const double range1 = 1.0; // Set end of z range const double STEPSIZE = ( range1 - range0 )/SIZE; // Calculate step size of the calculation const int STEPSAVE = Ntop/50; // How many overall iteractions before saving data int saveflag = 0; // indicator for the save cycles used to indicate STEPSAVE const int STEPSAVEZ = 100; // How many steps before save a data point within each iteraction /* data for saving */ ofstream data("halo_parallel_" + std::to_string(SIZE)+"_"+ std::to_string(STEPSIZE) + ".csv" ); /* Write basic information about the computation */ cout << "PROGRAM START" << endl; cout << "Halo Problem Forward and Backward:" << endl << "Total number of iterations: " + to_string(Ntop) << endl << "Size of rhos: " + to_string(SIZE) << endl << "Range: " + to_string(range1) << endl << "Step size: " + to_string(STEPSIZE) << endl; cout << "Save Steps: " << to_string(STEPSAVE) << endl; /* Output warning if the step size and range and size of array are not consistant */ if( (SIZE*STEPSIZE + range0) - range1 > 0.1 ){ cout << "NOT REACHING THE END POINT!" << endl; } state_type rho_init = { 1.0, 0.0, 0.0 }; /* The state arrays */ StateArray sa_store(SIZE); StateArray sa(SIZE); StateArray* sa_store_ptr = &sa_store; StateArray* sa_ptr = &sa; sa.init(); sa_store.init(); /* Assign initial values to sa_store which is used to calculate sa */ for(auto i = 0; i < 3; i++) { sa_store[0][i] = rho_init[i]; } // Track clock time const clock_t begin_time = clock(); for(int i=0; i<Ntop; i++ ){ if(saveflag%STEPSAVE == 0) { Recorder::record_state( sa_ptr, SIZE, data , STEPSAVEZ ); } Stepper::euler_forward_one( (*rho_array_ptr)[i+1], (*rho_array_store_ptr)[i], (*rho_array_ptr)[totallength - 2 - i], dt) ; Helper::sa_ptr_swap(sa_ptr, sa_store_ptr); ++saveflag; } /* Calculate clock time for the iterations */ cout << "Total clock time: " << float( clock () - begin_time ) / CLOCKS_PER_SEC << endl; cout << "Clock time for 1000 iterations: " << 1000.0 * float( clock () - begin_time ) / CLOCKS_PER_SEC / Ntop << endl; // Output data for benchmark // cout << to_string(Ntop) << ", " << to_string(SIZE) << ", " << argv[3] << ", " << float( clock () - begin_time ) / CLOCKS_PER_SEC / Ntop << endl; // Ntop, SIZE, Threads, Time/Iteration cout << "PROGRAM END" << endl; return 0; }
3,976
1,379
/* * Copyright 2010 The Native Client 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 "native_client/src/shared/ppapi_proxy/plugin_graphics_2d.h" #include <stdio.h> #include <string.h> #include "srpcgen/ppb_rpc.h" #include "srpcgen/upcall.h" #include "native_client/src/include/portability.h" #include "native_client/src/shared/ppapi_proxy/plugin_globals.h" #include "native_client/src/shared/ppapi_proxy/utility.h" #include "native_client/src/shared/srpc/nacl_srpc.h" #include "ppapi/c/ppb_graphics_2d.h" #include "ppapi/c/pp_completion_callback.h" #include "ppapi/c/pp_errors.h" #include "ppapi/c/pp_rect.h" #include "ppapi/c/pp_size.h" namespace ppapi_proxy { namespace { const nacl_abi_size_t kPpSizeBytes = static_cast<nacl_abi_size_t>(sizeof(struct PP_Size)); const nacl_abi_size_t kPpPointBytes = static_cast<nacl_abi_size_t>(sizeof(struct PP_Point)); const nacl_abi_size_t kPpRectBytes = static_cast<nacl_abi_size_t>(sizeof(struct PP_Rect)); PP_Resource Create(PP_Module module, const struct PP_Size* size, PP_Bool is_always_opaque) { int32_t* size_as_int_ptr = reinterpret_cast<int32_t*>(const_cast<struct PP_Size*>(size)); int32_t is_always_opaque_as_int = static_cast<int32_t>(is_always_opaque); int64_t resource; NaClSrpcError retval = PpbGraphics2DRpcClient::PPB_Graphics2D_Create( GetMainSrpcChannel(), static_cast<int64_t>(module), kPpSizeBytes, size_as_int_ptr, is_always_opaque_as_int, &resource); if (retval == NACL_SRPC_RESULT_OK) { return static_cast<PP_Resource>(resource); } else { return kInvalidResourceId; } } PP_Bool IsGraphics2D(PP_Resource resource) { return PluginResource::GetAs<PluginGraphics2D>(resource).get() ? PP_TRUE : PP_FALSE; } PP_Bool Describe(PP_Resource graphics_2d, struct PP_Size* size, PP_Bool* is_always_opaque) { int32_t is_always_opaque_as_int; nacl_abi_size_t size_ret = kPpSizeBytes; int32_t result; NaClSrpcError retval = PpbGraphics2DRpcClient::PPB_Graphics2D_Describe( GetMainSrpcChannel(), static_cast<int64_t>(graphics_2d), &size_ret, reinterpret_cast<int32_t*>(size), &is_always_opaque_as_int, &result); if (retval == NACL_SRPC_RESULT_OK || size_ret != kPpSizeBytes) { *is_always_opaque = is_always_opaque_as_int ? PP_TRUE : PP_FALSE; return result ? PP_TRUE : PP_FALSE; } else { return PP_FALSE; } } void PaintImageData(PP_Resource graphics_2d, PP_Resource image, const struct PP_Point* top_left, const struct PP_Rect* src_rect) { // TODO(sehr,polina): there is no way to report a failure through this // interface design other than crash. Let's find one. (void) PpbGraphics2DRpcClient::PPB_Graphics2D_PaintImageData( GetMainSrpcChannel(), static_cast<int64_t>(graphics_2d), static_cast<int64_t>(image), kPpPointBytes, reinterpret_cast<int32_t*>(const_cast<struct PP_Point*>(top_left)), kPpRectBytes, reinterpret_cast<int32_t*>(const_cast<struct PP_Rect*>(src_rect))); } void Scroll(PP_Resource graphics_2d, const struct PP_Rect* clip_rect, const struct PP_Point* amount) { // TODO(sehr,polina): there is no way to report a failure through this // interface design other than crash. Let's find one. (void) PpbGraphics2DRpcClient::PPB_Graphics2D_Scroll( GetMainSrpcChannel(), static_cast<int64_t>(graphics_2d), kPpRectBytes, reinterpret_cast<int32_t*>(const_cast<struct PP_Rect*>(clip_rect)), kPpPointBytes, reinterpret_cast<int32_t*>(const_cast<struct PP_Point*>(amount))); } void ReplaceContents(PP_Resource graphics_2d, PP_Resource image) { (void) PpbGraphics2DRpcClient::PPB_Graphics2D_ReplaceContents( GetMainSrpcChannel(), static_cast<int64_t>(graphics_2d), static_cast<int64_t>(image)); } int32_t Flush(PP_Resource graphics_2d, struct PP_CompletionCallback callback) { UNREFERENCED_PARAMETER(graphics_2d); UNREFERENCED_PARAMETER(callback); // TODO(sehr): implement the call on the upcall channel once the completion // callback implementation is in place. NACL_UNIMPLEMENTED(); return PP_ERROR_BADRESOURCE; } } // namespace const PPB_Graphics2D* PluginGraphics2D::GetInterface() { static const PPB_Graphics2D intf = { Create, IsGraphics2D, Describe, PaintImageData, Scroll, ReplaceContents, Flush, }; return &intf; } } // namespace ppapi_proxy
4,758
1,767
#include <marnav/nmea/rot.hpp> #include "type_traits_helper.hpp" #include <marnav/nmea/nmea.hpp> #include <gtest/gtest.h> namespace { using namespace marnav; class Test_nmea_rot : public ::testing::Test { }; TEST_F(Test_nmea_rot, contruction) { EXPECT_NO_THROW(nmea::rot rot); } TEST_F(Test_nmea_rot, properties) { nmea_sentence_traits<nmea::rot>(); } TEST_F(Test_nmea_rot, parse) { auto s = nmea::make_sentence("$GPROT,1.0,A*30"); ASSERT_NE(nullptr, s); auto rot = nmea::sentence_cast<nmea::rot>(s); ASSERT_NE(nullptr, rot); } TEST_F(Test_nmea_rot, parse_invalid_number_of_arguments) { EXPECT_ANY_THROW( nmea::detail::factory::sentence_parse<nmea::rot>(nmea::talker::none, {1, "@"})); EXPECT_ANY_THROW( nmea::detail::factory::sentence_parse<nmea::rot>(nmea::talker::none, {3, "@"})); } TEST_F(Test_nmea_rot, empty_to_string) { nmea::rot rot; EXPECT_STREQ("$GPROT,,*5E", nmea::to_string(rot).c_str()); } TEST_F(Test_nmea_rot, set_deg_per_minute) { nmea::rot rot; rot.set_deg_per_minute(1.0); EXPECT_STREQ("$GPROT,1.0,*71", nmea::to_string(rot).c_str()); } TEST_F(Test_nmea_rot, set_data_valid) { nmea::rot rot; rot.set_data_valid(nmea::status::ok); EXPECT_STREQ("$GPROT,,A*1F", nmea::to_string(rot).c_str()); } }
1,247
641
#include "version_handler.hpp" #include "version_mock.hpp" #include <array> #include <utility> #include <gtest/gtest.h> namespace ipmi_flash { TEST(VersionHandlerCanHandleTest, VerifyGoodInfoMapPasses) { constexpr std::array blobs{"blob0", "blob1"}; VersionBlobHandler handler(createMockVersionConfigs(blobs)); EXPECT_THAT(handler.getBlobIds(), testing::UnorderedElementsAreArray(blobs)); } TEST(VersionHandlerCanHandleTest, VerifyDuplicatesIgnored) { constexpr std::array blobs{"blob0"}; auto configs = createMockVersionConfigs(blobs); configs.push_back(createMockVersionConfig(blobs[0])); VersionBlobHandler handler(std::move(configs)); EXPECT_THAT(handler.getBlobIds(), testing::UnorderedElementsAreArray(blobs)); } } // namespace ipmi_flash
815
267
#include "OStreamSink.h" using namespace miniant::Spdlog; OStreamSink::OStreamSink(std::shared_ptr<std::ostream> outputStream, bool forceFlush): m_outputStream(std::move(outputStream)), m_forceFlush(forceFlush) {} std::mutex& OStreamSink::GetMutex() { return mutex_; } void OStreamSink::sink_it_(const spdlog::details::log_msg& message) { fmt::memory_buffer formattedMessage; sink::formatter_->format(message, formattedMessage); m_outputStream->write(formattedMessage.data(), static_cast<std::streamsize>(formattedMessage.size())); if (m_forceFlush) m_outputStream->flush(); } void OStreamSink::flush_() { m_outputStream->flush(); }
678
232
#include <chrono> #include <array> #include <iostream> #include "benchmark.h" inline size_t fib(size_t n) { if (n == 0) return n; if (n == 1) return 1; return fib(n - 1) + fib(n - 2); } inline double perform_computation(int w) { return fib(w); } int main() { using namespace std; auto start = chrono::high_resolution_clock::now(); auto delta = start - start; int value = 42; benchmark::touch(value); double answer = perform_computation(value); benchmark::keep(answer); delta = chrono::high_resolution_clock::now() - start; std::cout << "Answer: " << answer << ". Computation took " << chrono::duration_cast<chrono::milliseconds>(delta).count() << " ms" << std::endl; constexpr int N=1025; std::array<float,N> x,y,z; benchmark::touch(x); benchmark::touch(y); benchmark::touch(z); for (int i=0; i<N; ++i) z[i]=y[i]=x[i]=i*1.e-6; benchmark::keep(z); delta = start - start; for (int j=0; j<1000000; ++j) { delta -= (chrono::high_resolution_clock::now()-start); benchmark::touch(x); benchmark::touch(y); benchmark::touch(z); for (int i=0; i<N-1; ++i) z[i]+=y[i]*x[i]; benchmark::keep(z); delta += (chrono::high_resolution_clock::now()-start); } std::cout << z[N-1] << " Computation took " << chrono::duration_cast<chrono::milliseconds>(delta).count() << " ms" << std::endl; for (int i=0; i<N-1; ++i) z[i]=y[i]=x[i]=i*1.e-6; delta = start - start; for (int j=0; j<1000000; ++j) { for (int i=0; i<N; ++i) z[i]=y[i]=x[i]=i*1.e-6; delta -= (chrono::high_resolution_clock::now()-start); benchmark::touch(x); benchmark::touch(y); benchmark::touch(z); for (int i=0; i<N-1; ++i) z[i+1]+=y[i]*z[i]; benchmark::keep(z); delta += (chrono::high_resolution_clock::now()-start); } std::cout << z[N-1]<<" Computation took " << chrono::duration_cast<chrono::milliseconds>(delta).count() << " ms" << std::endl; for (int i=0; i<N; ++i) z[i]=y[i]=x[i]=i*1.e-6; delta = start - start; for (int j=0; j<1000000; ++j) { for (int i=0; i<N-1; ++i) z[i]=y[i]=x[i]=i*1.e-6; delta -= (chrono::high_resolution_clock::now()-start); benchmark::touch(x); benchmark::touch(y); benchmark::touch(z); for (int i=0; i<N-1; ++i) z[i]+=y[i]*z[i]; benchmark::keep(z); delta += (chrono::high_resolution_clock::now()-start); } std::cout<< z[N-1] <<" Computation took " << chrono::duration_cast<chrono::milliseconds>(delta).count() << " ms" << std::endl; return 0; }
2,883
1,119
//===- lib/MC/MCDwarf.cpp - MCDwarf implementation ------------------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #include "llvm/MC/MCDwarf.h" #include "llvm/MC/MCAsmInfo.h" #include "llvm/MC/MCContext.h" #include "llvm/MC/MCObjectFileInfo.h" #include "llvm/MC/MCObjectWriter.h" #include "llvm/MC/MCRegisterInfo.h" #include "llvm/MC/MCStreamer.h" #include "llvm/MC/MCSymbol.h" #include "llvm/MC/MCExpr.h" #include "llvm/Support/Debug.h" #include "llvm/Support/ErrorHandling.h" #include "llvm/Support/raw_ostream.h" #include "llvm/Support/Path.h" #include "llvm/Support/SourceMgr.h" #include "llvm/ADT/Hashing.h" #include "llvm/ADT/SmallString.h" #include "llvm/ADT/Twine.h" #include "llvm/Config/config.h" using namespace llvm; // Given a special op, return the address skip amount (in units of // DWARF2_LINE_MIN_INSN_LENGTH. #define SPECIAL_ADDR(op) (((op) - DWARF2_LINE_OPCODE_BASE)/DWARF2_LINE_RANGE) // The maximum address skip amount that can be encoded with a special op. #define MAX_SPECIAL_ADDR_DELTA SPECIAL_ADDR(255) // First special line opcode - leave room for the standard opcodes. // Note: If you want to change this, you'll have to update the // "standard_opcode_lengths" table that is emitted in DwarfFileTable::Emit(). #define DWARF2_LINE_OPCODE_BASE 13 // Minimum line offset in a special line info. opcode. This value // was chosen to give a reasonable range of values. #define DWARF2_LINE_BASE -5 // Range of line offsets in a special line info. opcode. #define DWARF2_LINE_RANGE 14 // Define the architecture-dependent minimum instruction length (in bytes). // This value should be rather too small than too big. #define DWARF2_LINE_MIN_INSN_LENGTH 1 // Note: when DWARF2_LINE_MIN_INSN_LENGTH == 1 which is the current setting, // this routine is a nop and will be optimized away. static inline uint64_t ScaleAddrDelta(uint64_t AddrDelta) { if (DWARF2_LINE_MIN_INSN_LENGTH == 1) return AddrDelta; if (AddrDelta % DWARF2_LINE_MIN_INSN_LENGTH != 0) { // TODO: report this error, but really only once. ; } return AddrDelta / DWARF2_LINE_MIN_INSN_LENGTH; } // // This is called when an instruction is assembled into the specified section // and if there is information from the last .loc directive that has yet to have // a line entry made for it is made. // void MCLineEntry::Make(MCStreamer *MCOS, const MCSection *Section) { if (!MCOS->getContext().getDwarfLocSeen()) return; // Create a symbol at in the current section for use in the line entry. MCSymbol *LineSym = MCOS->getContext().CreateTempSymbol(); // Set the value of the symbol to use for the MCLineEntry. MCOS->EmitLabel(LineSym); // Get the current .loc info saved in the context. const MCDwarfLoc &DwarfLoc = MCOS->getContext().getCurrentDwarfLoc(); // Create a (local) line entry with the symbol and the current .loc info. MCLineEntry LineEntry(LineSym, DwarfLoc); // clear DwarfLocSeen saying the current .loc info is now used. MCOS->getContext().ClearDwarfLocSeen(); // Get the MCLineSection for this section, if one does not exist for this // section create it. const DenseMap<const MCSection *, MCLineSection *> &MCLineSections = MCOS->getContext().getMCLineSections(); MCLineSection *LineSection = MCLineSections.lookup(Section); if (!LineSection) { // Create a new MCLineSection. This will be deleted after the dwarf line // table is created using it by iterating through the MCLineSections // DenseMap. LineSection = new MCLineSection; // Save a pointer to the new LineSection into the MCLineSections DenseMap. MCOS->getContext().addMCLineSection(Section, LineSection); } // Add the line entry to this section's entries. LineSection->addLineEntry(LineEntry); } // // This helper routine returns an expression of End - Start + IntVal . // static inline const MCExpr *MakeStartMinusEndExpr(const MCStreamer &MCOS, const MCSymbol &Start, const MCSymbol &End, int IntVal) { MCSymbolRefExpr::VariantKind Variant = MCSymbolRefExpr::VK_None; const MCExpr *Res = MCSymbolRefExpr::Create(&End, Variant, MCOS.getContext()); const MCExpr *RHS = MCSymbolRefExpr::Create(&Start, Variant, MCOS.getContext()); const MCExpr *Res1 = MCBinaryExpr::Create(MCBinaryExpr::Sub, Res, RHS, MCOS.getContext()); const MCExpr *Res2 = MCConstantExpr::Create(IntVal, MCOS.getContext()); const MCExpr *Res3 = MCBinaryExpr::Create(MCBinaryExpr::Sub, Res1, Res2, MCOS.getContext()); return Res3; } // // This emits the Dwarf line table for the specified section from the entries // in the LineSection. // static inline void EmitDwarfLineTable(MCStreamer *MCOS, const MCSection *Section, const MCLineSection *LineSection) { unsigned FileNum = 1; unsigned LastLine = 1; unsigned Column = 0; unsigned Flags = DWARF2_LINE_DEFAULT_IS_STMT ? DWARF2_FLAG_IS_STMT : 0; unsigned Isa = 0; MCSymbol *LastLabel = NULL; // Loop through each MCLineEntry and encode the dwarf line number table. for (MCLineSection::const_iterator it = LineSection->getMCLineEntries()->begin(), ie = LineSection->getMCLineEntries()->end(); it != ie; ++it) { if (FileNum != it->getFileNum()) { FileNum = it->getFileNum(); MCOS->EmitIntValue(dwarf::DW_LNS_set_file, 1); MCOS->EmitULEB128IntValue(FileNum); } if (Column != it->getColumn()) { Column = it->getColumn(); MCOS->EmitIntValue(dwarf::DW_LNS_set_column, 1); MCOS->EmitULEB128IntValue(Column); } if (Isa != it->getIsa()) { Isa = it->getIsa(); MCOS->EmitIntValue(dwarf::DW_LNS_set_isa, 1); MCOS->EmitULEB128IntValue(Isa); } if ((it->getFlags() ^ Flags) & DWARF2_FLAG_IS_STMT) { Flags = it->getFlags(); MCOS->EmitIntValue(dwarf::DW_LNS_negate_stmt, 1); } if (it->getFlags() & DWARF2_FLAG_BASIC_BLOCK) MCOS->EmitIntValue(dwarf::DW_LNS_set_basic_block, 1); if (it->getFlags() & DWARF2_FLAG_PROLOGUE_END) MCOS->EmitIntValue(dwarf::DW_LNS_set_prologue_end, 1); if (it->getFlags() & DWARF2_FLAG_EPILOGUE_BEGIN) MCOS->EmitIntValue(dwarf::DW_LNS_set_epilogue_begin, 1); int64_t LineDelta = static_cast<int64_t>(it->getLine()) - LastLine; MCSymbol *Label = it->getLabel(); // At this point we want to emit/create the sequence to encode the delta in // line numbers and the increment of the address from the previous Label // and the current Label. const MCAsmInfo &asmInfo = MCOS->getContext().getAsmInfo(); MCOS->EmitDwarfAdvanceLineAddr(LineDelta, LastLabel, Label, asmInfo.getPointerSize()); LastLine = it->getLine(); LastLabel = Label; } // Emit a DW_LNE_end_sequence for the end of the section. // Using the pointer Section create a temporary label at the end of the // section and use that and the LastLabel to compute the address delta // and use INT64_MAX as the line delta which is the signal that this is // actually a DW_LNE_end_sequence. // Switch to the section to be able to create a symbol at its end. MCOS->SwitchSection(Section); MCContext &context = MCOS->getContext(); // Create a symbol at the end of the section. MCSymbol *SectionEnd = context.CreateTempSymbol(); // Set the value of the symbol, as we are at the end of the section. MCOS->EmitLabel(SectionEnd); // Switch back the the dwarf line section. MCOS->SwitchSection(context.getObjectFileInfo()->getDwarfLineSection()); const MCAsmInfo &asmInfo = MCOS->getContext().getAsmInfo(); MCOS->EmitDwarfAdvanceLineAddr(INT64_MAX, LastLabel, SectionEnd, asmInfo.getPointerSize()); } // // This emits the Dwarf file and the line tables. // const MCSymbol *MCDwarfFileTable::Emit(MCStreamer *MCOS) { MCContext &context = MCOS->getContext(); // Switch to the section where the table will be emitted into. MCOS->SwitchSection(context.getObjectFileInfo()->getDwarfLineSection()); // Create a symbol at the beginning of this section. MCSymbol *LineStartSym = context.CreateTempSymbol(); // Set the value of the symbol, as we are at the start of the section. MCOS->EmitLabel(LineStartSym); // Create a symbol for the end of the section (to be set when we get there). MCSymbol *LineEndSym = context.CreateTempSymbol(); // The first 4 bytes is the total length of the information for this // compilation unit (not including these 4 bytes for the length). MCOS->EmitAbsValue(MakeStartMinusEndExpr(*MCOS, *LineStartSym, *LineEndSym,4), 4); // Next 2 bytes is the Version, which is Dwarf 2. MCOS->EmitIntValue(2, 2); // Create a symbol for the end of the prologue (to be set when we get there). MCSymbol *ProEndSym = context.CreateTempSymbol(); // Lprologue_end // Length of the prologue, is the next 4 bytes. Which is the start of the // section to the end of the prologue. Not including the 4 bytes for the // total length, the 2 bytes for the version, and these 4 bytes for the // length of the prologue. MCOS->EmitAbsValue(MakeStartMinusEndExpr(*MCOS, *LineStartSym, *ProEndSym, (4 + 2 + 4)), 4, 0); // Parameters of the state machine, are next. MCOS->EmitIntValue(DWARF2_LINE_MIN_INSN_LENGTH, 1); MCOS->EmitIntValue(DWARF2_LINE_DEFAULT_IS_STMT, 1); MCOS->EmitIntValue(DWARF2_LINE_BASE, 1); MCOS->EmitIntValue(DWARF2_LINE_RANGE, 1); MCOS->EmitIntValue(DWARF2_LINE_OPCODE_BASE, 1); // Standard opcode lengths MCOS->EmitIntValue(0, 1); // length of DW_LNS_copy MCOS->EmitIntValue(1, 1); // length of DW_LNS_advance_pc MCOS->EmitIntValue(1, 1); // length of DW_LNS_advance_line MCOS->EmitIntValue(1, 1); // length of DW_LNS_set_file MCOS->EmitIntValue(1, 1); // length of DW_LNS_set_column MCOS->EmitIntValue(0, 1); // length of DW_LNS_negate_stmt MCOS->EmitIntValue(0, 1); // length of DW_LNS_set_basic_block MCOS->EmitIntValue(0, 1); // length of DW_LNS_const_add_pc MCOS->EmitIntValue(1, 1); // length of DW_LNS_fixed_advance_pc MCOS->EmitIntValue(0, 1); // length of DW_LNS_set_prologue_end MCOS->EmitIntValue(0, 1); // length of DW_LNS_set_epilogue_begin MCOS->EmitIntValue(1, 1); // DW_LNS_set_isa // Put out the directory and file tables. // First the directory table. const std::vector<StringRef> &MCDwarfDirs = context.getMCDwarfDirs(); for (unsigned i = 0; i < MCDwarfDirs.size(); i++) { MCOS->EmitBytes(MCDwarfDirs[i], 0); // the DirectoryName MCOS->EmitBytes(StringRef("\0", 1), 0); // the null term. of the string } MCOS->EmitIntValue(0, 1); // Terminate the directory list // Second the file table. const std::vector<MCDwarfFile *> &MCDwarfFiles = MCOS->getContext().getMCDwarfFiles(); for (unsigned i = 1; i < MCDwarfFiles.size(); i++) { MCOS->EmitBytes(MCDwarfFiles[i]->getName(), 0); // FileName MCOS->EmitBytes(StringRef("\0", 1), 0); // the null term. of the string // the Directory num MCOS->EmitULEB128IntValue(MCDwarfFiles[i]->getDirIndex()); MCOS->EmitIntValue(0, 1); // last modification timestamp (always 0) MCOS->EmitIntValue(0, 1); // filesize (always 0) } MCOS->EmitIntValue(0, 1); // Terminate the file list // This is the end of the prologue, so set the value of the symbol at the // end of the prologue (that was used in a previous expression). MCOS->EmitLabel(ProEndSym); // Put out the line tables. const DenseMap<const MCSection *, MCLineSection *> &MCLineSections = MCOS->getContext().getMCLineSections(); const std::vector<const MCSection *> &MCLineSectionOrder = MCOS->getContext().getMCLineSectionOrder(); for (std::vector<const MCSection*>::const_iterator it = MCLineSectionOrder.begin(), ie = MCLineSectionOrder.end(); it != ie; ++it) { const MCSection *Sec = *it; const MCLineSection *Line = MCLineSections.lookup(Sec); EmitDwarfLineTable(MCOS, Sec, Line); // Now delete the MCLineSections that were created in MCLineEntry::Make() // and used to emit the line table. delete Line; } if (MCOS->getContext().getAsmInfo().getLinkerRequiresNonEmptyDwarfLines() && MCLineSectionOrder.begin() == MCLineSectionOrder.end()) { // The darwin9 linker has a bug (see PR8715). For for 32-bit architectures // it requires: // total_length >= prologue_length + 10 // We are 4 bytes short, since we have total_length = 51 and // prologue_length = 45 // The regular end_sequence should be sufficient. MCDwarfLineAddr::Emit(MCOS, INT64_MAX, 0); } // This is the end of the section, so set the value of the symbol at the end // of this section (that was used in a previous expression). MCOS->EmitLabel(LineEndSym); return LineStartSym; } /// Utility function to write the encoding to an object writer. void MCDwarfLineAddr::Write(MCObjectWriter *OW, int64_t LineDelta, uint64_t AddrDelta) { SmallString<256> Tmp; raw_svector_ostream OS(Tmp); MCDwarfLineAddr::Encode(LineDelta, AddrDelta, OS); OW->WriteBytes(OS.str()); } /// Utility function to emit the encoding to a streamer. void MCDwarfLineAddr::Emit(MCStreamer *MCOS, int64_t LineDelta, uint64_t AddrDelta) { SmallString<256> Tmp; raw_svector_ostream OS(Tmp); MCDwarfLineAddr::Encode(LineDelta, AddrDelta, OS); MCOS->EmitBytes(OS.str(), /*AddrSpace=*/0); } /// Utility function to encode a Dwarf pair of LineDelta and AddrDeltas. void MCDwarfLineAddr::Encode(int64_t LineDelta, uint64_t AddrDelta, raw_ostream &OS) { uint64_t Temp, Opcode; bool NeedCopy = false; // Scale the address delta by the minimum instruction length. AddrDelta = ScaleAddrDelta(AddrDelta); // A LineDelta of INT64_MAX is a signal that this is actually a // DW_LNE_end_sequence. We cannot use special opcodes here, since we want the // end_sequence to emit the matrix entry. if (LineDelta == INT64_MAX) { if (AddrDelta == MAX_SPECIAL_ADDR_DELTA) OS << char(dwarf::DW_LNS_const_add_pc); else { OS << char(dwarf::DW_LNS_advance_pc); MCObjectWriter::EncodeULEB128(AddrDelta, OS); } OS << char(dwarf::DW_LNS_extended_op); OS << char(1); OS << char(dwarf::DW_LNE_end_sequence); return; } // Bias the line delta by the base. Temp = LineDelta - DWARF2_LINE_BASE; // If the line increment is out of range of a special opcode, we must encode // it with DW_LNS_advance_line. if (Temp >= DWARF2_LINE_RANGE) { OS << char(dwarf::DW_LNS_advance_line); MCObjectWriter::EncodeSLEB128(LineDelta, OS); LineDelta = 0; Temp = 0 - DWARF2_LINE_BASE; NeedCopy = true; } // Use DW_LNS_copy instead of a "line +0, addr +0" special opcode. if (LineDelta == 0 && AddrDelta == 0) { OS << char(dwarf::DW_LNS_copy); return; } // Bias the opcode by the special opcode base. Temp += DWARF2_LINE_OPCODE_BASE; // Avoid overflow when addr_delta is large. if (AddrDelta < 256 + MAX_SPECIAL_ADDR_DELTA) { // Try using a special opcode. Opcode = Temp + AddrDelta * DWARF2_LINE_RANGE; if (Opcode <= 255) { OS << char(Opcode); return; } // Try using DW_LNS_const_add_pc followed by special op. Opcode = Temp + (AddrDelta - MAX_SPECIAL_ADDR_DELTA) * DWARF2_LINE_RANGE; if (Opcode <= 255) { OS << char(dwarf::DW_LNS_const_add_pc); OS << char(Opcode); return; } } // Otherwise use DW_LNS_advance_pc. OS << char(dwarf::DW_LNS_advance_pc); MCObjectWriter::EncodeULEB128(AddrDelta, OS); if (NeedCopy) OS << char(dwarf::DW_LNS_copy); else OS << char(Temp); } void MCDwarfFile::print(raw_ostream &OS) const { OS << '"' << getName() << '"'; } void MCDwarfFile::dump() const { print(dbgs()); } // Utility function to write a tuple for .debug_abbrev. static void EmitAbbrev(MCStreamer *MCOS, uint64_t Name, uint64_t Form) { MCOS->EmitULEB128IntValue(Name); MCOS->EmitULEB128IntValue(Form); } // When generating dwarf for assembly source files this emits // the data for .debug_abbrev section which contains three DIEs. static void EmitGenDwarfAbbrev(MCStreamer *MCOS) { MCContext &context = MCOS->getContext(); MCOS->SwitchSection(context.getObjectFileInfo()->getDwarfAbbrevSection()); // DW_TAG_compile_unit DIE abbrev (1). MCOS->EmitULEB128IntValue(1); MCOS->EmitULEB128IntValue(dwarf::DW_TAG_compile_unit); MCOS->EmitIntValue(dwarf::DW_CHILDREN_yes, 1); EmitAbbrev(MCOS, dwarf::DW_AT_stmt_list, dwarf::DW_FORM_data4); EmitAbbrev(MCOS, dwarf::DW_AT_low_pc, dwarf::DW_FORM_addr); EmitAbbrev(MCOS, dwarf::DW_AT_high_pc, dwarf::DW_FORM_addr); EmitAbbrev(MCOS, dwarf::DW_AT_name, dwarf::DW_FORM_string); EmitAbbrev(MCOS, dwarf::DW_AT_comp_dir, dwarf::DW_FORM_string); StringRef DwarfDebugFlags = context.getDwarfDebugFlags(); if (!DwarfDebugFlags.empty()) EmitAbbrev(MCOS, dwarf::DW_AT_APPLE_flags, dwarf::DW_FORM_string); EmitAbbrev(MCOS, dwarf::DW_AT_producer, dwarf::DW_FORM_string); EmitAbbrev(MCOS, dwarf::DW_AT_language, dwarf::DW_FORM_data2); EmitAbbrev(MCOS, 0, 0); // DW_TAG_label DIE abbrev (2). MCOS->EmitULEB128IntValue(2); MCOS->EmitULEB128IntValue(dwarf::DW_TAG_label); MCOS->EmitIntValue(dwarf::DW_CHILDREN_yes, 1); EmitAbbrev(MCOS, dwarf::DW_AT_name, dwarf::DW_FORM_string); EmitAbbrev(MCOS, dwarf::DW_AT_decl_file, dwarf::DW_FORM_data4); EmitAbbrev(MCOS, dwarf::DW_AT_decl_line, dwarf::DW_FORM_data4); EmitAbbrev(MCOS, dwarf::DW_AT_low_pc, dwarf::DW_FORM_addr); EmitAbbrev(MCOS, dwarf::DW_AT_prototyped, dwarf::DW_FORM_flag); EmitAbbrev(MCOS, 0, 0); // DW_TAG_unspecified_parameters DIE abbrev (3). MCOS->EmitULEB128IntValue(3); MCOS->EmitULEB128IntValue(dwarf::DW_TAG_unspecified_parameters); MCOS->EmitIntValue(dwarf::DW_CHILDREN_no, 1); EmitAbbrev(MCOS, 0, 0); // Terminate the abbreviations for this compilation unit. MCOS->EmitIntValue(0, 1); } // When generating dwarf for assembly source files this emits the data for // .debug_aranges section. Which contains a header and a table of pairs of // PointerSize'ed values for the address and size of section(s) with line table // entries (just the default .text in our case) and a terminating pair of zeros. static void EmitGenDwarfAranges(MCStreamer *MCOS) { MCContext &context = MCOS->getContext(); // Create a symbol at the end of the section that we are creating the dwarf // debugging info to use later in here as part of the expression to calculate // the size of the section for the table. MCOS->SwitchSection(context.getGenDwarfSection()); MCSymbol *SectionEndSym = context.CreateTempSymbol(); MCOS->EmitLabel(SectionEndSym); context.setGenDwarfSectionEndSym(SectionEndSym); MCOS->SwitchSection(context.getObjectFileInfo()->getDwarfARangesSection()); // This will be the length of the .debug_aranges section, first account for // the size of each item in the header (see below where we emit these items). int Length = 4 + 2 + 4 + 1 + 1; // Figure the padding after the header before the table of address and size // pairs who's values are PointerSize'ed. const MCAsmInfo &asmInfo = context.getAsmInfo(); int AddrSize = asmInfo.getPointerSize(); int Pad = 2 * AddrSize - (Length & (2 * AddrSize - 1)); if (Pad == 2 * AddrSize) Pad = 0; Length += Pad; // Add the size of the pair of PointerSize'ed values for the address and size // of the one default .text section we have in the table. Length += 2 * AddrSize; // And the pair of terminating zeros. Length += 2 * AddrSize; // Emit the header for this section. // The 4 byte length not including the 4 byte value for the length. MCOS->EmitIntValue(Length - 4, 4); // The 2 byte version, which is 2. MCOS->EmitIntValue(2, 2); // The 4 byte offset to the compile unit in the .debug_info from the start // of the .debug_info, it is at the start of that section so this is zero. MCOS->EmitIntValue(0, 4); // The 1 byte size of an address. MCOS->EmitIntValue(AddrSize, 1); // The 1 byte size of a segment descriptor, we use a value of zero. MCOS->EmitIntValue(0, 1); // Align the header with the padding if needed, before we put out the table. for(int i = 0; i < Pad; i++) MCOS->EmitIntValue(0, 1); // Now emit the table of pairs of PointerSize'ed values for the section(s) // address and size, in our case just the one default .text section. const MCExpr *Addr = MCSymbolRefExpr::Create( context.getGenDwarfSectionStartSym(), MCSymbolRefExpr::VK_None, context); const MCExpr *Size = MakeStartMinusEndExpr(*MCOS, *context.getGenDwarfSectionStartSym(), *SectionEndSym, 0); MCOS->EmitAbsValue(Addr, AddrSize); MCOS->EmitAbsValue(Size, AddrSize); // And finally the pair of terminating zeros. MCOS->EmitIntValue(0, AddrSize); MCOS->EmitIntValue(0, AddrSize); } // When generating dwarf for assembly source files this emits the data for // .debug_info section which contains three parts. The header, the compile_unit // DIE and a list of label DIEs. static void EmitGenDwarfInfo(MCStreamer *MCOS, const MCSymbol *AbbrevSectionSymbol, const MCSymbol *LineSectionSymbol) { MCContext &context = MCOS->getContext(); MCOS->SwitchSection(context.getObjectFileInfo()->getDwarfInfoSection()); // Create a symbol at the start and end of this section used in here for the // expression to calculate the length in the header. MCSymbol *InfoStart = context.CreateTempSymbol(); MCOS->EmitLabel(InfoStart); MCSymbol *InfoEnd = context.CreateTempSymbol(); // First part: the header. // The 4 byte total length of the information for this compilation unit, not // including these 4 bytes. const MCExpr *Length = MakeStartMinusEndExpr(*MCOS, *InfoStart, *InfoEnd, 4); MCOS->EmitAbsValue(Length, 4); // The 2 byte DWARF version, which is 2. MCOS->EmitIntValue(2, 2); // The 4 byte offset to the debug abbrevs from the start of the .debug_abbrev, // it is at the start of that section so this is zero. if (AbbrevSectionSymbol) { MCOS->EmitSymbolValue(AbbrevSectionSymbol, 4); } else { MCOS->EmitIntValue(0, 4); } const MCAsmInfo &asmInfo = context.getAsmInfo(); int AddrSize = asmInfo.getPointerSize(); // The 1 byte size of an address. MCOS->EmitIntValue(AddrSize, 1); // Second part: the compile_unit DIE. // The DW_TAG_compile_unit DIE abbrev (1). MCOS->EmitULEB128IntValue(1); // DW_AT_stmt_list, a 4 byte offset from the start of the .debug_line section, // which is at the start of that section so this is zero. if (LineSectionSymbol) { MCOS->EmitSymbolValue(LineSectionSymbol, 4); } else { MCOS->EmitIntValue(0, 4); } // AT_low_pc, the first address of the default .text section. const MCExpr *Start = MCSymbolRefExpr::Create( context.getGenDwarfSectionStartSym(), MCSymbolRefExpr::VK_None, context); MCOS->EmitAbsValue(Start, AddrSize); // AT_high_pc, the last address of the default .text section. const MCExpr *End = MCSymbolRefExpr::Create( context.getGenDwarfSectionEndSym(), MCSymbolRefExpr::VK_None, context); MCOS->EmitAbsValue(End, AddrSize); // AT_name, the name of the source file. Reconstruct from the first directory // and file table entries. const std::vector<StringRef> &MCDwarfDirs = context.getMCDwarfDirs(); if (MCDwarfDirs.size() > 0) { MCOS->EmitBytes(MCDwarfDirs[0], 0); MCOS->EmitBytes("/", 0); } const std::vector<MCDwarfFile *> &MCDwarfFiles = MCOS->getContext().getMCDwarfFiles(); MCOS->EmitBytes(MCDwarfFiles[1]->getName(), 0); MCOS->EmitIntValue(0, 1); // NULL byte to terminate the string. // AT_comp_dir, the working directory the assembly was done in. llvm::sys::Path CWD = llvm::sys::Path::GetCurrentDirectory(); MCOS->EmitBytes(StringRef(CWD.c_str()), 0); MCOS->EmitIntValue(0, 1); // NULL byte to terminate the string. // AT_APPLE_flags, the command line arguments of the assembler tool. StringRef DwarfDebugFlags = context.getDwarfDebugFlags(); if (!DwarfDebugFlags.empty()){ MCOS->EmitBytes(DwarfDebugFlags, 0); MCOS->EmitIntValue(0, 1); // NULL byte to terminate the string. } // AT_producer, the version of the assembler tool. MCOS->EmitBytes(StringRef("llvm-mc (based on LLVM "), 0); MCOS->EmitBytes(StringRef(PACKAGE_VERSION), 0); MCOS->EmitBytes(StringRef(")"), 0); MCOS->EmitIntValue(0, 1); // NULL byte to terminate the string. // AT_language, a 4 byte value. We use DW_LANG_Mips_Assembler as the dwarf2 // draft has no standard code for assembler. MCOS->EmitIntValue(dwarf::DW_LANG_Mips_Assembler, 2); // Third part: the list of label DIEs. // Loop on saved info for dwarf labels and create the DIEs for them. const std::vector<const MCGenDwarfLabelEntry *> &Entries = MCOS->getContext().getMCGenDwarfLabelEntries(); for (std::vector<const MCGenDwarfLabelEntry *>::const_iterator it = Entries.begin(), ie = Entries.end(); it != ie; ++it) { const MCGenDwarfLabelEntry *Entry = *it; // The DW_TAG_label DIE abbrev (2). MCOS->EmitULEB128IntValue(2); // AT_name, of the label without any leading underbar. MCOS->EmitBytes(Entry->getName(), 0); MCOS->EmitIntValue(0, 1); // NULL byte to terminate the string. // AT_decl_file, index into the file table. MCOS->EmitIntValue(Entry->getFileNumber(), 4); // AT_decl_line, source line number. MCOS->EmitIntValue(Entry->getLineNumber(), 4); // AT_low_pc, start address of the label. const MCExpr *AT_low_pc = MCSymbolRefExpr::Create(Entry->getLabel(), MCSymbolRefExpr::VK_None, context); MCOS->EmitAbsValue(AT_low_pc, AddrSize); // DW_AT_prototyped, a one byte flag value of 0 saying we have no prototype. MCOS->EmitIntValue(0, 1); // The DW_TAG_unspecified_parameters DIE abbrev (3). MCOS->EmitULEB128IntValue(3); // Add the NULL DIE terminating the DW_TAG_unspecified_parameters DIE's. MCOS->EmitIntValue(0, 1); } // Deallocate the MCGenDwarfLabelEntry classes that saved away the info // for the dwarf labels. for (std::vector<const MCGenDwarfLabelEntry *>::const_iterator it = Entries.begin(), ie = Entries.end(); it != ie; ++it) { const MCGenDwarfLabelEntry *Entry = *it; delete Entry; } // Add the NULL DIE terminating the Compile Unit DIE's. MCOS->EmitIntValue(0, 1); // Now set the value of the symbol at the end of the info section. MCOS->EmitLabel(InfoEnd); } // // When generating dwarf for assembly source files this emits the Dwarf // sections. // void MCGenDwarfInfo::Emit(MCStreamer *MCOS, const MCSymbol *LineSectionSymbol) { // Create the dwarf sections in this order (.debug_line already created). MCContext &context = MCOS->getContext(); const MCAsmInfo &AsmInfo = context.getAsmInfo(); MCOS->SwitchSection(context.getObjectFileInfo()->getDwarfInfoSection()); MCOS->SwitchSection(context.getObjectFileInfo()->getDwarfAbbrevSection()); MCSymbol *AbbrevSectionSymbol; if (AsmInfo.doesDwarfRequireRelocationForSectionOffset()) { AbbrevSectionSymbol = context.CreateTempSymbol(); MCOS->EmitLabel(AbbrevSectionSymbol); } else { AbbrevSectionSymbol = NULL; LineSectionSymbol = NULL; } MCOS->SwitchSection(context.getObjectFileInfo()->getDwarfARangesSection()); // If there are no line table entries then do not emit any section contents. if (context.getMCLineSections().empty()) return; // Output the data for .debug_aranges section. EmitGenDwarfAranges(MCOS); // Output the data for .debug_abbrev section. EmitGenDwarfAbbrev(MCOS); // Output the data for .debug_info section. EmitGenDwarfInfo(MCOS, AbbrevSectionSymbol, LineSectionSymbol); } // // When generating dwarf for assembly source files this is called when symbol // for a label is created. If this symbol is not a temporary and is in the // section that dwarf is being generated for, save the needed info to create // a dwarf label. // void MCGenDwarfLabelEntry::Make(MCSymbol *Symbol, MCStreamer *MCOS, SourceMgr &SrcMgr, SMLoc &Loc) { // We won't create dwarf labels for temporary symbols or symbols not in // the default text. if (Symbol->isTemporary()) return; MCContext &context = MCOS->getContext(); if (context.getGenDwarfSection() != MCOS->getCurrentSection()) return; // The dwarf label's name does not have the symbol name's leading // underbar if any. StringRef Name = Symbol->getName(); if (Name.startswith("_")) Name = Name.substr(1, Name.size()-1); // Get the dwarf file number to be used for the dwarf label. unsigned FileNumber = context.getGenDwarfFileNumber(); // Finding the line number is the expensive part which is why we just don't // pass it in as for some symbols we won't create a dwarf label. int CurBuffer = SrcMgr.FindBufferContainingLoc(Loc); unsigned LineNumber = SrcMgr.FindLineNumber(Loc, CurBuffer); // We create a temporary symbol for use for the AT_high_pc and AT_low_pc // values so that they don't have things like an ARM thumb bit from the // original symbol. So when used they won't get a low bit set after // relocation. MCSymbol *Label = context.CreateTempSymbol(); MCOS->EmitLabel(Label); // Create and entry for the info and add it to the other entries. MCGenDwarfLabelEntry *Entry = new MCGenDwarfLabelEntry(Name, FileNumber, LineNumber, Label); MCOS->getContext().addMCGenDwarfLabelEntry(Entry); } static int getDataAlignmentFactor(MCStreamer &streamer) { MCContext &context = streamer.getContext(); const MCAsmInfo &asmInfo = context.getAsmInfo(); int size = asmInfo.getPointerSize(); if (asmInfo.isStackGrowthDirectionUp()) return size; else return -size; } static unsigned getSizeForEncoding(MCStreamer &streamer, unsigned symbolEncoding) { MCContext &context = streamer.getContext(); unsigned format = symbolEncoding & 0x0f; switch (format) { default: llvm_unreachable("Unknown Encoding"); case dwarf::DW_EH_PE_absptr: case dwarf::DW_EH_PE_signed: return context.getAsmInfo().getPointerSize(); case dwarf::DW_EH_PE_udata2: case dwarf::DW_EH_PE_sdata2: return 2; case dwarf::DW_EH_PE_udata4: case dwarf::DW_EH_PE_sdata4: return 4; case dwarf::DW_EH_PE_udata8: case dwarf::DW_EH_PE_sdata8: return 8; } } static void EmitSymbol(MCStreamer &streamer, const MCSymbol &symbol, unsigned symbolEncoding, const char *comment = 0) { MCContext &context = streamer.getContext(); const MCAsmInfo &asmInfo = context.getAsmInfo(); const MCExpr *v = asmInfo.getExprForFDESymbol(&symbol, symbolEncoding, streamer); unsigned size = getSizeForEncoding(streamer, symbolEncoding); if (streamer.isVerboseAsm() && comment) streamer.AddComment(comment); streamer.EmitAbsValue(v, size); } static void EmitPersonality(MCStreamer &streamer, const MCSymbol &symbol, unsigned symbolEncoding) { MCContext &context = streamer.getContext(); const MCAsmInfo &asmInfo = context.getAsmInfo(); const MCExpr *v = asmInfo.getExprForPersonalitySymbol(&symbol, symbolEncoding, streamer); unsigned size = getSizeForEncoding(streamer, symbolEncoding); streamer.EmitValue(v, size); } static const MachineLocation TranslateMachineLocation( const MCRegisterInfo &MRI, const MachineLocation &Loc) { unsigned Reg = Loc.getReg() == MachineLocation::VirtualFP ? MachineLocation::VirtualFP : unsigned(MRI.getDwarfRegNum(Loc.getReg(), true)); const MachineLocation &NewLoc = Loc.isReg() ? MachineLocation(Reg) : MachineLocation(Reg, Loc.getOffset()); return NewLoc; } namespace { class FrameEmitterImpl { int CFAOffset; int CIENum; bool UsingCFI; bool IsEH; const MCSymbol *SectionStart; public: FrameEmitterImpl(bool usingCFI, bool isEH) : CFAOffset(0), CIENum(0), UsingCFI(usingCFI), IsEH(isEH), SectionStart(0) {} void setSectionStart(const MCSymbol *Label) { SectionStart = Label; } /// EmitCompactUnwind - Emit the unwind information in a compact way. If /// we're successful, return 'true'. Otherwise, return 'false' and it will /// emit the normal CIE and FDE. bool EmitCompactUnwind(MCStreamer &streamer, const MCDwarfFrameInfo &frame); const MCSymbol &EmitCIE(MCStreamer &streamer, const MCSymbol *personality, unsigned personalityEncoding, const MCSymbol *lsda, bool IsSignalFrame, unsigned lsdaEncoding); MCSymbol *EmitFDE(MCStreamer &streamer, const MCSymbol &cieStart, const MCDwarfFrameInfo &frame); void EmitCFIInstructions(MCStreamer &streamer, const std::vector<MCCFIInstruction> &Instrs, MCSymbol *BaseLabel); void EmitCFIInstruction(MCStreamer &Streamer, const MCCFIInstruction &Instr); }; } // end anonymous namespace static void EmitEncodingByte(MCStreamer &Streamer, unsigned Encoding, StringRef Prefix) { if (Streamer.isVerboseAsm()) { const char *EncStr; switch (Encoding) { default: EncStr = "<unknown encoding>"; break; case dwarf::DW_EH_PE_absptr: EncStr = "absptr"; break; case dwarf::DW_EH_PE_omit: EncStr = "omit"; break; case dwarf::DW_EH_PE_pcrel: EncStr = "pcrel"; break; case dwarf::DW_EH_PE_udata4: EncStr = "udata4"; break; case dwarf::DW_EH_PE_udata8: EncStr = "udata8"; break; case dwarf::DW_EH_PE_sdata4: EncStr = "sdata4"; break; case dwarf::DW_EH_PE_sdata8: EncStr = "sdata8"; break; case dwarf::DW_EH_PE_pcrel | dwarf::DW_EH_PE_udata4: EncStr = "pcrel udata4"; break; case dwarf::DW_EH_PE_pcrel | dwarf::DW_EH_PE_sdata4: EncStr = "pcrel sdata4"; break; case dwarf::DW_EH_PE_pcrel | dwarf::DW_EH_PE_udata8: EncStr = "pcrel udata8"; break; case dwarf::DW_EH_PE_pcrel | dwarf::DW_EH_PE_sdata8: EncStr = "screl sdata8"; break; case dwarf::DW_EH_PE_indirect |dwarf::DW_EH_PE_pcrel|dwarf::DW_EH_PE_udata4: EncStr = "indirect pcrel udata4"; break; case dwarf::DW_EH_PE_indirect |dwarf::DW_EH_PE_pcrel|dwarf::DW_EH_PE_sdata4: EncStr = "indirect pcrel sdata4"; break; case dwarf::DW_EH_PE_indirect |dwarf::DW_EH_PE_pcrel|dwarf::DW_EH_PE_udata8: EncStr = "indirect pcrel udata8"; break; case dwarf::DW_EH_PE_indirect |dwarf::DW_EH_PE_pcrel|dwarf::DW_EH_PE_sdata8: EncStr = "indirect pcrel sdata8"; break; } Streamer.AddComment(Twine(Prefix) + " = " + EncStr); } Streamer.EmitIntValue(Encoding, 1); } void FrameEmitterImpl::EmitCFIInstruction(MCStreamer &Streamer, const MCCFIInstruction &Instr) { int dataAlignmentFactor = getDataAlignmentFactor(Streamer); bool VerboseAsm = Streamer.isVerboseAsm(); switch (Instr.getOperation()) { case MCCFIInstruction::Move: case MCCFIInstruction::RelMove: { const MachineLocation &Dst = Instr.getDestination(); const MachineLocation &Src = Instr.getSource(); const bool IsRelative = Instr.getOperation() == MCCFIInstruction::RelMove; // If advancing cfa. if (Dst.isReg() && Dst.getReg() == MachineLocation::VirtualFP) { if (Src.getReg() == MachineLocation::VirtualFP) { if (VerboseAsm) Streamer.AddComment("DW_CFA_def_cfa_offset"); Streamer.EmitIntValue(dwarf::DW_CFA_def_cfa_offset, 1); } else { if (VerboseAsm) Streamer.AddComment("DW_CFA_def_cfa"); Streamer.EmitIntValue(dwarf::DW_CFA_def_cfa, 1); if (VerboseAsm) Streamer.AddComment(Twine("Reg ") + Twine(Src.getReg())); Streamer.EmitULEB128IntValue(Src.getReg()); } if (IsRelative) CFAOffset += Src.getOffset(); else CFAOffset = -Src.getOffset(); if (VerboseAsm) Streamer.AddComment(Twine("Offset " + Twine(CFAOffset))); Streamer.EmitULEB128IntValue(CFAOffset); return; } if (Src.isReg() && Src.getReg() == MachineLocation::VirtualFP) { assert(Dst.isReg() && "Machine move not supported yet."); if (VerboseAsm) Streamer.AddComment("DW_CFA_def_cfa_register"); Streamer.EmitIntValue(dwarf::DW_CFA_def_cfa_register, 1); if (VerboseAsm) Streamer.AddComment(Twine("Reg ") + Twine(Dst.getReg())); Streamer.EmitULEB128IntValue(Dst.getReg()); return; } unsigned Reg = Src.getReg(); int Offset = Dst.getOffset(); if (IsRelative) Offset -= CFAOffset; Offset = Offset / dataAlignmentFactor; if (Offset < 0) { if (VerboseAsm) Streamer.AddComment("DW_CFA_offset_extended_sf"); Streamer.EmitIntValue(dwarf::DW_CFA_offset_extended_sf, 1); if (VerboseAsm) Streamer.AddComment(Twine("Reg ") + Twine(Reg)); Streamer.EmitULEB128IntValue(Reg); if (VerboseAsm) Streamer.AddComment(Twine("Offset ") + Twine(Offset)); Streamer.EmitSLEB128IntValue(Offset); } else if (Reg < 64) { if (VerboseAsm) Streamer.AddComment(Twine("DW_CFA_offset + Reg(") + Twine(Reg) + ")"); Streamer.EmitIntValue(dwarf::DW_CFA_offset + Reg, 1); if (VerboseAsm) Streamer.AddComment(Twine("Offset ") + Twine(Offset)); Streamer.EmitULEB128IntValue(Offset); } else { if (VerboseAsm) Streamer.AddComment("DW_CFA_offset_extended"); Streamer.EmitIntValue(dwarf::DW_CFA_offset_extended, 1); if (VerboseAsm) Streamer.AddComment(Twine("Reg ") + Twine(Reg)); Streamer.EmitULEB128IntValue(Reg); if (VerboseAsm) Streamer.AddComment(Twine("Offset ") + Twine(Offset)); Streamer.EmitULEB128IntValue(Offset); } return; } case MCCFIInstruction::RememberState: if (VerboseAsm) Streamer.AddComment("DW_CFA_remember_state"); Streamer.EmitIntValue(dwarf::DW_CFA_remember_state, 1); return; case MCCFIInstruction::RestoreState: if (VerboseAsm) Streamer.AddComment("DW_CFA_restore_state"); Streamer.EmitIntValue(dwarf::DW_CFA_restore_state, 1); return; case MCCFIInstruction::SameValue: { unsigned Reg = Instr.getDestination().getReg(); if (VerboseAsm) Streamer.AddComment("DW_CFA_same_value"); Streamer.EmitIntValue(dwarf::DW_CFA_same_value, 1); if (VerboseAsm) Streamer.AddComment(Twine("Reg ") + Twine(Reg)); Streamer.EmitULEB128IntValue(Reg); return; } case MCCFIInstruction::Restore: { unsigned Reg = Instr.getDestination().getReg(); if (VerboseAsm) { Streamer.AddComment("DW_CFA_restore"); Streamer.AddComment(Twine("Reg ") + Twine(Reg)); } Streamer.EmitIntValue(dwarf::DW_CFA_restore | Reg, 1); return; } case MCCFIInstruction::Escape: if (VerboseAsm) Streamer.AddComment("Escape bytes"); Streamer.EmitBytes(Instr.getValues(), 0); return; } llvm_unreachable("Unhandled case in switch"); } /// EmitFrameMoves - Emit frame instructions to describe the layout of the /// frame. void FrameEmitterImpl::EmitCFIInstructions(MCStreamer &streamer, const std::vector<MCCFIInstruction> &Instrs, MCSymbol *BaseLabel) { for (unsigned i = 0, N = Instrs.size(); i < N; ++i) { const MCCFIInstruction &Instr = Instrs[i]; MCSymbol *Label = Instr.getLabel(); // Throw out move if the label is invalid. if (Label && !Label->isDefined()) continue; // Not emitted, in dead code. // Advance row if new location. if (BaseLabel && Label) { MCSymbol *ThisSym = Label; if (ThisSym != BaseLabel) { if (streamer.isVerboseAsm()) streamer.AddComment("DW_CFA_advance_loc4"); streamer.EmitDwarfAdvanceFrameAddr(BaseLabel, ThisSym); BaseLabel = ThisSym; } } EmitCFIInstruction(streamer, Instr); } } /// EmitCompactUnwind - Emit the unwind information in a compact way. If we're /// successful, return 'true'. Otherwise, return 'false' and it will emit the /// normal CIE and FDE. bool FrameEmitterImpl::EmitCompactUnwind(MCStreamer &Streamer, const MCDwarfFrameInfo &Frame) { MCContext &Context = Streamer.getContext(); const MCObjectFileInfo *MOFI = Context.getObjectFileInfo(); bool VerboseAsm = Streamer.isVerboseAsm(); // range-start range-length compact-unwind-enc personality-func lsda // _foo LfooEnd-_foo 0x00000023 0 0 // _bar LbarEnd-_bar 0x00000025 __gxx_personality except_tab1 // // .section __LD,__compact_unwind,regular,debug // // # compact unwind for _foo // .quad _foo // .set L1,LfooEnd-_foo // .long L1 // .long 0x01010001 // .quad 0 // .quad 0 // // # compact unwind for _bar // .quad _bar // .set L2,LbarEnd-_bar // .long L2 // .long 0x01020011 // .quad __gxx_personality // .quad except_tab1 uint32_t Encoding = Frame.CompactUnwindEncoding; if (!Encoding) return false; // The encoding needs to know we have an LSDA. if (Frame.Lsda) Encoding |= 0x40000000; Streamer.SwitchSection(MOFI->getCompactUnwindSection()); // Range Start unsigned FDEEncoding = MOFI->getFDEEncoding(UsingCFI); unsigned Size = getSizeForEncoding(Streamer, FDEEncoding); if (VerboseAsm) Streamer.AddComment("Range Start"); Streamer.EmitSymbolValue(Frame.Function, Size); // Range Length const MCExpr *Range = MakeStartMinusEndExpr(Streamer, *Frame.Begin, *Frame.End, 0); if (VerboseAsm) Streamer.AddComment("Range Length"); Streamer.EmitAbsValue(Range, 4); // Compact Encoding Size = getSizeForEncoding(Streamer, dwarf::DW_EH_PE_udata4); if (VerboseAsm) Streamer.AddComment("Compact Unwind Encoding: 0x" + Twine::utohexstr(Encoding)); Streamer.EmitIntValue(Encoding, Size); // Personality Function Size = getSizeForEncoding(Streamer, dwarf::DW_EH_PE_absptr); if (VerboseAsm) Streamer.AddComment("Personality Function"); if (Frame.Personality) Streamer.EmitSymbolValue(Frame.Personality, Size); else Streamer.EmitIntValue(0, Size); // No personality fn // LSDA Size = getSizeForEncoding(Streamer, Frame.LsdaEncoding); if (VerboseAsm) Streamer.AddComment("LSDA"); if (Frame.Lsda) Streamer.EmitSymbolValue(Frame.Lsda, Size); else Streamer.EmitIntValue(0, Size); // No LSDA return true; } const MCSymbol &FrameEmitterImpl::EmitCIE(MCStreamer &streamer, const MCSymbol *personality, unsigned personalityEncoding, const MCSymbol *lsda, bool IsSignalFrame, unsigned lsdaEncoding) { MCContext &context = streamer.getContext(); const MCRegisterInfo &MRI = context.getRegisterInfo(); const MCObjectFileInfo *MOFI = context.getObjectFileInfo(); bool verboseAsm = streamer.isVerboseAsm(); MCSymbol *sectionStart; if (MOFI->isFunctionEHFrameSymbolPrivate() || !IsEH) sectionStart = context.CreateTempSymbol(); else sectionStart = context.GetOrCreateSymbol(Twine("EH_frame") + Twine(CIENum)); streamer.EmitLabel(sectionStart); CIENum++; MCSymbol *sectionEnd = context.CreateTempSymbol(); // Length const MCExpr *Length = MakeStartMinusEndExpr(streamer, *sectionStart, *sectionEnd, 4); if (verboseAsm) streamer.AddComment("CIE Length"); streamer.EmitAbsValue(Length, 4); // CIE ID unsigned CIE_ID = IsEH ? 0 : -1; if (verboseAsm) streamer.AddComment("CIE ID Tag"); streamer.EmitIntValue(CIE_ID, 4); // Version if (verboseAsm) streamer.AddComment("DW_CIE_VERSION"); streamer.EmitIntValue(dwarf::DW_CIE_VERSION, 1); // Augmentation String SmallString<8> Augmentation; if (IsEH) { if (verboseAsm) streamer.AddComment("CIE Augmentation"); Augmentation += "z"; if (personality) Augmentation += "P"; if (lsda) Augmentation += "L"; Augmentation += "R"; if (IsSignalFrame) Augmentation += "S"; streamer.EmitBytes(Augmentation.str(), 0); } streamer.EmitIntValue(0, 1); // Code Alignment Factor if (verboseAsm) streamer.AddComment("CIE Code Alignment Factor"); streamer.EmitULEB128IntValue(1); // Data Alignment Factor if (verboseAsm) streamer.AddComment("CIE Data Alignment Factor"); streamer.EmitSLEB128IntValue(getDataAlignmentFactor(streamer)); // Return Address Register if (verboseAsm) streamer.AddComment("CIE Return Address Column"); streamer.EmitULEB128IntValue(MRI.getDwarfRegNum(MRI.getRARegister(), true)); // Augmentation Data Length (optional) unsigned augmentationLength = 0; if (IsEH) { if (personality) { // Personality Encoding augmentationLength += 1; // Personality augmentationLength += getSizeForEncoding(streamer, personalityEncoding); } if (lsda) augmentationLength += 1; // Encoding of the FDE pointers augmentationLength += 1; if (verboseAsm) streamer.AddComment("Augmentation Size"); streamer.EmitULEB128IntValue(augmentationLength); // Augmentation Data (optional) if (personality) { // Personality Encoding EmitEncodingByte(streamer, personalityEncoding, "Personality Encoding"); // Personality if (verboseAsm) streamer.AddComment("Personality"); EmitPersonality(streamer, *personality, personalityEncoding); } if (lsda) EmitEncodingByte(streamer, lsdaEncoding, "LSDA Encoding"); // Encoding of the FDE pointers EmitEncodingByte(streamer, MOFI->getFDEEncoding(UsingCFI), "FDE Encoding"); } // Initial Instructions const MCAsmInfo &MAI = context.getAsmInfo(); const std::vector<MachineMove> &Moves = MAI.getInitialFrameState(); std::vector<MCCFIInstruction> Instructions; for (int i = 0, n = Moves.size(); i != n; ++i) { MCSymbol *Label = Moves[i].getLabel(); const MachineLocation &Dst = TranslateMachineLocation(MRI, Moves[i].getDestination()); const MachineLocation &Src = TranslateMachineLocation(MRI, Moves[i].getSource()); MCCFIInstruction Inst(Label, Dst, Src); Instructions.push_back(Inst); } EmitCFIInstructions(streamer, Instructions, NULL); // Padding streamer.EmitValueToAlignment(IsEH ? 4 : context.getAsmInfo().getPointerSize()); streamer.EmitLabel(sectionEnd); return *sectionStart; } MCSymbol *FrameEmitterImpl::EmitFDE(MCStreamer &streamer, const MCSymbol &cieStart, const MCDwarfFrameInfo &frame) { MCContext &context = streamer.getContext(); MCSymbol *fdeStart = context.CreateTempSymbol(); MCSymbol *fdeEnd = context.CreateTempSymbol(); const MCObjectFileInfo *MOFI = context.getObjectFileInfo(); bool verboseAsm = streamer.isVerboseAsm(); if (IsEH && frame.Function && !MOFI->isFunctionEHFrameSymbolPrivate()) { MCSymbol *EHSym = context.GetOrCreateSymbol(frame.Function->getName() + Twine(".eh")); streamer.EmitEHSymAttributes(frame.Function, EHSym); streamer.EmitLabel(EHSym); } // Length const MCExpr *Length = MakeStartMinusEndExpr(streamer, *fdeStart, *fdeEnd, 0); if (verboseAsm) streamer.AddComment("FDE Length"); streamer.EmitAbsValue(Length, 4); streamer.EmitLabel(fdeStart); // CIE Pointer const MCAsmInfo &asmInfo = context.getAsmInfo(); if (IsEH) { const MCExpr *offset = MakeStartMinusEndExpr(streamer, cieStart, *fdeStart, 0); if (verboseAsm) streamer.AddComment("FDE CIE Offset"); streamer.EmitAbsValue(offset, 4); } else if (!asmInfo.doesDwarfRequireRelocationForSectionOffset()) { const MCExpr *offset = MakeStartMinusEndExpr(streamer, *SectionStart, cieStart, 0); streamer.EmitAbsValue(offset, 4); } else { streamer.EmitSymbolValue(&cieStart, 4); } unsigned fdeEncoding = MOFI->getFDEEncoding(UsingCFI); unsigned size = getSizeForEncoding(streamer, fdeEncoding); // PC Begin unsigned PCBeginEncoding = IsEH ? fdeEncoding : (unsigned)dwarf::DW_EH_PE_absptr; unsigned PCBeginSize = getSizeForEncoding(streamer, PCBeginEncoding); EmitSymbol(streamer, *frame.Begin, PCBeginEncoding, "FDE initial location"); // PC Range const MCExpr *Range = MakeStartMinusEndExpr(streamer, *frame.Begin, *frame.End, 0); if (verboseAsm) streamer.AddComment("FDE address range"); streamer.EmitAbsValue(Range, size); if (IsEH) { // Augmentation Data Length unsigned augmentationLength = 0; if (frame.Lsda) augmentationLength += getSizeForEncoding(streamer, frame.LsdaEncoding); if (verboseAsm) streamer.AddComment("Augmentation size"); streamer.EmitULEB128IntValue(augmentationLength); // Augmentation Data if (frame.Lsda) EmitSymbol(streamer, *frame.Lsda, frame.LsdaEncoding, "Language Specific Data Area"); } // Call Frame Instructions EmitCFIInstructions(streamer, frame.Instructions, frame.Begin); // Padding streamer.EmitValueToAlignment(PCBeginSize); return fdeEnd; } namespace { struct CIEKey { static const CIEKey getEmptyKey() { return CIEKey(0, 0, -1, false); } static const CIEKey getTombstoneKey() { return CIEKey(0, -1, 0, false); } CIEKey(const MCSymbol* Personality_, unsigned PersonalityEncoding_, unsigned LsdaEncoding_, bool IsSignalFrame_) : Personality(Personality_), PersonalityEncoding(PersonalityEncoding_), LsdaEncoding(LsdaEncoding_), IsSignalFrame(IsSignalFrame_) { } const MCSymbol* Personality; unsigned PersonalityEncoding; unsigned LsdaEncoding; bool IsSignalFrame; }; } namespace llvm { template <> struct DenseMapInfo<CIEKey> { static CIEKey getEmptyKey() { return CIEKey::getEmptyKey(); } static CIEKey getTombstoneKey() { return CIEKey::getTombstoneKey(); } static unsigned getHashValue(const CIEKey &Key) { return static_cast<unsigned>(hash_combine(Key.Personality, Key.PersonalityEncoding, Key.LsdaEncoding, Key.IsSignalFrame)); } static bool isEqual(const CIEKey &LHS, const CIEKey &RHS) { return LHS.Personality == RHS.Personality && LHS.PersonalityEncoding == RHS.PersonalityEncoding && LHS.LsdaEncoding == RHS.LsdaEncoding && LHS.IsSignalFrame == RHS.IsSignalFrame; } }; } void MCDwarfFrameEmitter::Emit(MCStreamer &Streamer, bool UsingCFI, bool IsEH) { MCContext &Context = Streamer.getContext(); MCObjectFileInfo *MOFI = const_cast<MCObjectFileInfo*>(Context.getObjectFileInfo()); FrameEmitterImpl Emitter(UsingCFI, IsEH); ArrayRef<MCDwarfFrameInfo> FrameArray = Streamer.getFrameInfos(); // Emit the compact unwind info if available. if (IsEH && MOFI->getCompactUnwindSection()) for (unsigned i = 0, n = Streamer.getNumFrameInfos(); i < n; ++i) { const MCDwarfFrameInfo &Frame = Streamer.getFrameInfo(i); if (Frame.CompactUnwindEncoding) Emitter.EmitCompactUnwind(Streamer, Frame); } const MCSection &Section = IsEH ? *MOFI->getEHFrameSection() : *MOFI->getDwarfFrameSection(); Streamer.SwitchSection(&Section); MCSymbol *SectionStart = Context.CreateTempSymbol(); Streamer.EmitLabel(SectionStart); Emitter.setSectionStart(SectionStart); MCSymbol *FDEEnd = NULL; DenseMap<CIEKey, const MCSymbol*> CIEStarts; const MCSymbol *DummyDebugKey = NULL; for (unsigned i = 0, n = FrameArray.size(); i < n; ++i) { const MCDwarfFrameInfo &Frame = FrameArray[i]; CIEKey Key(Frame.Personality, Frame.PersonalityEncoding, Frame.LsdaEncoding, Frame.IsSignalFrame); const MCSymbol *&CIEStart = IsEH ? CIEStarts[Key] : DummyDebugKey; if (!CIEStart) CIEStart = &Emitter.EmitCIE(Streamer, Frame.Personality, Frame.PersonalityEncoding, Frame.Lsda, Frame.IsSignalFrame, Frame.LsdaEncoding); FDEEnd = Emitter.EmitFDE(Streamer, *CIEStart, Frame); if (i != n - 1) Streamer.EmitLabel(FDEEnd); } Streamer.EmitValueToAlignment(Context.getAsmInfo().getPointerSize()); if (FDEEnd) Streamer.EmitLabel(FDEEnd); } void MCDwarfFrameEmitter::EmitAdvanceLoc(MCStreamer &Streamer, uint64_t AddrDelta) { SmallString<256> Tmp; raw_svector_ostream OS(Tmp); MCDwarfFrameEmitter::EncodeAdvanceLoc(AddrDelta, OS); Streamer.EmitBytes(OS.str(), /*AddrSpace=*/0); } void MCDwarfFrameEmitter::EncodeAdvanceLoc(uint64_t AddrDelta, raw_ostream &OS) { // FIXME: Assumes the code alignment factor is 1. if (AddrDelta == 0) { } else if (isUIntN(6, AddrDelta)) { uint8_t Opcode = dwarf::DW_CFA_advance_loc | AddrDelta; OS << Opcode; } else if (isUInt<8>(AddrDelta)) { OS << uint8_t(dwarf::DW_CFA_advance_loc1); OS << uint8_t(AddrDelta); } else if (isUInt<16>(AddrDelta)) { // FIXME: check what is the correct behavior on a big endian machine. OS << uint8_t(dwarf::DW_CFA_advance_loc2); OS << uint8_t( AddrDelta & 0xff); OS << uint8_t((AddrDelta >> 8) & 0xff); } else { // FIXME: check what is the correct behavior on a big endian machine. assert(isUInt<32>(AddrDelta)); OS << uint8_t(dwarf::DW_CFA_advance_loc4); OS << uint8_t( AddrDelta & 0xff); OS << uint8_t((AddrDelta >> 8) & 0xff); OS << uint8_t((AddrDelta >> 16) & 0xff); OS << uint8_t((AddrDelta >> 24) & 0xff); } }
55,419
19,726
#include <bits/stdc++.h> using namespace std; int maxLen(int A[], int n); int main() { int T; cin >> T; while (T--) { int N; cin >> N; int A[N]; for (int i = 0; i < N; i++) cin >> A[i]; cout << maxLen(A, N) << endl; } } // } Driver Code Ends /*You are required to complete this function*/ int maxLen(int A[], int n) { unordered_map<int,int> mp; int sum =0; int ans; int j; for(int i=0;i<n;i++) { sum += A[i]; if(sum == 0) ans = i+1 ; else { if(mp.find(sum)==mp.end()) { mp[sum] = i ; } else { j = mp[sum]; ans = max(ans,i-j); } } } return ans; }
824
310
/* * (C) Copyright 1996- ECMWF. * * This software is licensed under the terms of the Apache Licence Version 2.0 * which can be obtained at http://www.apache.org/licenses/LICENSE-2.0. * In applying this licence, ECMWF does not waive the privileges and immunities * granted to it by virtue of its status as an intergovernmental organisation nor * does it submit to any jurisdiction. */ #include <iomanip> #include "eckit/utils/Translator.h" #include "eckit/types/Date.h" #include "metkit/mars/MarsRequest.h" #include "fdb5/types/TypesFactory.h" #include "fdb5/types/TypeTime.h" namespace fdb5 { //---------------------------------------------------------------------------------------------------------------------- TypeTime::TypeTime(const std::string &name, const std::string &type) : Type(name, type) { } TypeTime::~TypeTime() { } std::string TypeTime::tidy(const std::string&, const std::string& value) const { eckit::Translator<std::string, long> t; long n = t(value); if (n < 100) { n *= 100; } std::ostringstream oss; oss << std::setfill('0') << std::setw(4) << n; return oss.str(); } std::string TypeTime::toKey(const std::string& keyword, const std::string& value) const { // if value just contains a digit, add a leading zero to be compliant with eckit::Time std::string t = value.size() < 2 ? "0"+value : value; eckit::Time time(t); std::ostringstream oss; oss << std::setfill('0') << std::setw(2) << time.hours() << std::setfill('0') << std::setw(2) << time.minutes(); return oss.str(); } void TypeTime::print(std::ostream &out) const { out << "TypeTime[name=" << name_ << "]"; } static TypeBuilder<TypeTime> type("Time"); //---------------------------------------------------------------------------------------------------------------------- } // namespace fdb5
1,923
624
#include "stdafx.h" #include "TestBiomeScreen.h" #include <Vorb/ui/InputDispatcher.h> #include <Vorb/colors.h> #include "App.h" #include "ChunkRenderer.h" #include "DevConsole.h" #include "InputMapper.h" #include "Inputs.h" #include "LoadTaskBlockData.h" #include "RenderUtils.h" #include "ShaderLoader.h" #include "SoaEngine.h" #include "SoAState.h" #ifdef DEBUG #define HORIZONTAL_CHUNKS 26 #define VERTICAL_CHUNKS 4 #else #define HORIZONTAL_CHUNKS 26 #define VERTICAL_CHUNKS 20 #endif TestBiomeScreen::TestBiomeScreen(const App* app, CommonState* state) : IAppScreen<App>(app), m_commonState(state), m_soaState(m_commonState->state), m_blockArrayRecycler(1000) { } i32 TestBiomeScreen::getNextScreen() const { return SCREEN_INDEX_NO_SCREEN; } i32 TestBiomeScreen::getPreviousScreen() const { return SCREEN_INDEX_NO_SCREEN; } void TestBiomeScreen::build() { } void TestBiomeScreen::destroy(const vui::GameTime& gameTime VORB_UNUSED) { } void TestBiomeScreen::onEntry(const vui::GameTime& gameTime VORB_MAYBE_UNUSED) { // Init spritebatch and font m_sb.init(); m_font.init("Fonts/orbitron_bold-webfont.ttf", 32); // Init game state SoaEngine::initState(m_commonState->state); // Init access m_accessor.init(&m_allocator); // Init renderer m_renderer.init(); { // Init post processing Array<vg::GBufferAttachment> attachments; vg::GBufferAttachment att[2]; // Color att[0].format = vg::TextureInternalFormat::RGBA16F; att[0].pixelFormat = vg::TextureFormat::RGBA; att[0].pixelType = vg::TexturePixelType::UNSIGNED_BYTE; att[0].number = 1; // Normals att[1].format = vg::TextureInternalFormat::RGBA16F; att[1].pixelFormat = vg::TextureFormat::RGBA; att[1].pixelType = vg::TexturePixelType::UNSIGNED_BYTE; att[1].number = 2; m_hdrTarget.setSize(m_commonState->window->getWidth(), m_commonState->window->getHeight()); m_hdrTarget.init(Array<vg::GBufferAttachment>(att, 2), vg::TextureInternalFormat::RGBA8).initDepth(); // Swapchain m_swapChain.init(m_commonState->window->getWidth(), m_commonState->window->getHeight(), vg::TextureInternalFormat::RGBA16F); // Init the FullQuadVBO m_commonState->quad.init(); // SSAO m_ssaoStage.init(m_commonState->window, m_commonState->loadContext); m_ssaoStage.load(m_commonState->loadContext); m_ssaoStage.hook(&m_commonState->quad, m_commonState->window->getWidth(), m_commonState->window->getHeight()); // HDR m_hdrStage.init(m_commonState->window, m_commonState->loadContext); m_hdrStage.load(m_commonState->loadContext); m_hdrStage.hook(&m_commonState->quad); } // Load test planet PlanetGenLoader planetLoader; m_iom.setSearchDirectory("StarSystems/Trinity/"); planetLoader.init(&m_iom); m_genData = planetLoader.loadPlanetGenData("Moons/Aldrin/terrain_gen.yml"); if (m_genData->terrainColorPixels.data) { m_soaState->clientState.blockTextures->setColorMap("biome", &m_genData->terrainColorPixels); } // Load blocks LoadTaskBlockData blockLoader(&m_soaState->blocks, &m_soaState->clientState.blockTextureLoader, &m_commonState->loadContext); blockLoader.load(); // Uploads all the needed textures m_soaState->clientState.blockTextures->update(); m_genData->radius = 4500.0; // Set blocks SoaEngine::initVoxelGen(m_genData, m_soaState->blocks); m_chunkGenerator.init(m_genData); initHeightData(); initChunks(); printf("Generating Meshes...\n"); // Create all chunk meshes m_mesher.init(&m_soaState->blocks); for (auto& cv : m_chunks) { cv.chunkMesh = m_mesher.easyCreateChunkMesh(cv.chunk, MeshTaskType::DEFAULT); } { // Init the camera m_camera.init(m_commonState->window->getAspectRatio()); m_camera.setPosition(f64v3(16.0, 17.0, 33.0)); m_camera.setDirection(f32v3(0.0f, 0.0f, -1.0f)); m_camera.setRight(f32v3(1.0f, 0.0f, 0.0f)); m_camera.setUp(f32v3(0.0f, 1.0f, 0.0f)); } initInput(); // Initialize dev console vui::GameWindow* window = m_commonState->window; m_devConsoleView.init(&DevConsole::getInstance(), 5, f32v2(20.0f, window->getHeight() - 400.0f), window->getWidth() - 40.0f); // Set GL state glEnable(GL_DEPTH_TEST); glEnable(GL_CULL_FACE); glClearDepth(1.0); printf("Done."); } void TestBiomeScreen::onExit(const vui::GameTime& gameTime VORB_MAYBE_UNUSED) { for (auto& cv : m_chunks) { m_mesher.freeChunkMesh(cv.chunkMesh); } m_hdrTarget.dispose(); m_swapChain.dispose(); m_devConsoleView.dispose(); } void TestBiomeScreen::update(const vui::GameTime& gameTime) { f32 speed = 10.0f; if (m_movingFast) speed *= 5.0f; if (m_movingForward) { f32v3 offset = m_camera.getDirection() * speed * (f32)gameTime.elapsed; m_camera.offsetPosition(offset); } if (m_movingBack) { f32v3 offset = m_camera.getDirection() * -speed * (f32)gameTime.elapsed; m_camera.offsetPosition(offset); } if (m_movingLeft) { f32v3 offset = m_camera.getRight() * -speed * (f32)gameTime.elapsed; m_camera.offsetPosition(offset); } if (m_movingRight) { f32v3 offset = m_camera.getRight() * speed * (f32)gameTime.elapsed; m_camera.offsetPosition(offset); } if (m_movingUp) { f32v3 offset = f32v3(0, 1, 0) * speed * (f32)gameTime.elapsed; m_camera.offsetPosition(offset); } if (m_movingDown) { f32v3 offset = f32v3(0, 1, 0) * -speed * (f32)gameTime.elapsed; m_camera.offsetPosition(offset); } m_camera.update(); } void TestBiomeScreen::draw(const vui::GameTime& gameTime VORB_UNUSED) { // Bind the FBO m_hdrTarget.useGeometry(); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); if (m_wireFrame) glPolygonMode(GL_FRONT_AND_BACK, GL_LINE); // Opaque m_renderer.beginOpaque(m_soaState->clientState.blockTextures->getAtlasTexture(), f32v3(0.0f, 0.0f, -1.0f), f32v3(1.0f), f32v3(0.3f)); for (auto& vc : m_chunks) { if (m_camera.getFrustum().sphereInFrustum(f32v3(vc.chunkMesh->position + f64v3(CHUNK_WIDTH / 2) - m_camera.getPosition()), CHUNK_DIAGONAL_LENGTH)) { vc.inFrustum = true; m_renderer.drawOpaque(vc.chunkMesh, m_camera.getPosition(), m_camera.getViewProjectionMatrix()); } else { vc.inFrustum = false; } } // Cutout m_renderer.beginCutout(m_soaState->clientState.blockTextures->getAtlasTexture(), f32v3(0.0f, 0.0f, -1.0f), f32v3(1.0f), f32v3(0.3f)); for (auto& vc : m_chunks) { if (vc.inFrustum) { m_renderer.drawCutout(vc.chunkMesh, m_camera.getPosition(), m_camera.getViewProjectionMatrix()); } } m_renderer.end(); if (m_wireFrame) glPolygonMode(GL_FRONT_AND_BACK, GL_FILL); // Post processing m_swapChain.reset(0, m_hdrTarget.getGeometryID(), m_hdrTarget.getGeometryTexture(0), soaOptions.get(OPT_MSAA).value.i > 0, false); // Render SSAO m_ssaoStage.set(m_hdrTarget.getDepthTexture(), m_hdrTarget.getGeometryTexture(1), m_hdrTarget.getGeometryTexture(0), m_swapChain.getCurrent().getID()); m_ssaoStage.render(&m_camera); m_swapChain.swap(); m_swapChain.use(0, false); // Draw to backbuffer for the last effect // TODO(Ben): Do we really need to clear depth here... glBindFramebuffer(GL_FRAMEBUFFER, 0); glDrawBuffer(GL_BACK); glClear(GL_DEPTH_BUFFER_BIT | GL_COLOR_BUFFER_BIT); glActiveTexture(GL_TEXTURE1); glBindTexture(GL_TEXTURE_2D, m_hdrTarget.getDepthTexture()); m_hdrStage.render(); // Draw UI char buf[256]; sprintf(buf, "FPS: %.1f", m_app->getFps()); m_sb.begin(); m_sb.drawString(&m_font, buf, f32v2(30.0f), f32v2(1.0f), color::White); m_sb.end(); m_sb.render(f32v2(m_commonState->window->getViewportDims())); vg::DepthState::FULL.set(); // Have to restore depth // Draw dev console m_devConsoleView.update(0.01f); m_devConsoleView.render(m_game->getWindow().getViewportDims()); } void TestBiomeScreen::initHeightData() { printf("Generating height data...\n"); m_heightData.resize(HORIZONTAL_CHUNKS * HORIZONTAL_CHUNKS); // Init height data m_heightGenerator.init(m_genData); for (int z = 0; z < HORIZONTAL_CHUNKS; z++) { for (int x = 0; x < HORIZONTAL_CHUNKS; x++) { auto& hd = m_heightData[z * HORIZONTAL_CHUNKS + x]; for (int i = 0; i < CHUNK_WIDTH; i++) { for (int j = 0; j < CHUNK_WIDTH; j++) { VoxelPosition2D pos; pos.pos.x = x * CHUNK_WIDTH + j + 3000; pos.pos.y = z * CHUNK_WIDTH + i + 3000; PlanetHeightData& data = hd.heightData[i * CHUNK_WIDTH + j]; m_heightGenerator.generateHeightData(data, pos); data.temperature = 128; data.humidity = 128; } } } } // Get center height f32 cHeight = m_heightData[HORIZONTAL_CHUNKS * HORIZONTAL_CHUNKS / 2].heightData[CHUNK_LAYER / 2].height; // Center the heightmap for (auto& hd : m_heightData) { for (int i = 0; i < CHUNK_LAYER; i++) { hd.heightData[i].height -= cHeight; } } } void TestBiomeScreen::initChunks() { printf("Generating chunks...\n"); m_chunks.resize(HORIZONTAL_CHUNKS * HORIZONTAL_CHUNKS * VERTICAL_CHUNKS); // Generate chunk data for (size_t i = 0; i < m_chunks.size(); i++) { ChunkPosition3D pos; i32v3 gridPosition; gridPosition.x = i % HORIZONTAL_CHUNKS; gridPosition.y = i / (HORIZONTAL_CHUNKS * HORIZONTAL_CHUNKS); gridPosition.z = (i % (HORIZONTAL_CHUNKS * HORIZONTAL_CHUNKS)) / HORIZONTAL_CHUNKS; // Center position about origin pos.pos.x = gridPosition.x - HORIZONTAL_CHUNKS / 2; pos.pos.y = gridPosition.y - VERTICAL_CHUNKS / 4; pos.pos.z = gridPosition.z - HORIZONTAL_CHUNKS / 2; // Init parameters ChunkID id(pos.x, pos.y, pos.z); m_chunks[i].chunk = m_accessor.acquire(id); m_chunks[i].chunk->init(WorldCubeFace::FACE_TOP); m_chunks[i].gridPosition = gridPosition; m_chunks[i].chunk->gridData = &m_heightData[i % (HORIZONTAL_CHUNKS * HORIZONTAL_CHUNKS)]; // Generate the chunk m_chunkGenerator.generateChunk(m_chunks[i].chunk, m_chunks[i].chunk->gridData->heightData); // Decompress to flat array m_chunks[i].chunk->blocks.setArrayRecycler(&m_blockArrayRecycler); m_chunks[i].chunk->blocks.changeState(vvox::VoxelStorageState::FLAT_ARRAY, m_chunks[i].chunk->dataMutex); } // Generate flora std::vector<FloraNode> lNodes; std::vector<FloraNode> wNodes; // TODO(Ben): I know this is ugly PreciseTimer t1; t1.start(); for (size_t i = 0; i < m_chunks.size(); i++) { Chunk* chunk = m_chunks[i].chunk; m_floraGenerator.generateChunkFlora(chunk, m_heightData[i % (HORIZONTAL_CHUNKS * HORIZONTAL_CHUNKS)].heightData, lNodes, wNodes); for (auto& node : wNodes) { i32v3 gridPos = m_chunks[i].gridPosition; gridPos.x += FloraGenerator::getChunkXOffset(node.chunkOffset); gridPos.y += FloraGenerator::getChunkYOffset(node.chunkOffset); gridPos.z += FloraGenerator::getChunkZOffset(node.chunkOffset); if (gridPos.x >= 0 && gridPos.y >= 0 && gridPos.z >= 0 && gridPos.x < HORIZONTAL_CHUNKS && gridPos.y < VERTICAL_CHUNKS && gridPos.z < HORIZONTAL_CHUNKS) { Chunk* chunk = m_chunks[gridPos.x + gridPos.y * HORIZONTAL_CHUNKS * HORIZONTAL_CHUNKS + gridPos.z * HORIZONTAL_CHUNKS].chunk; chunk->blocks.set(node.blockIndex, node.blockID); } } for (auto& node : lNodes) { i32v3 gridPos = m_chunks[i].gridPosition; gridPos.x += FloraGenerator::getChunkXOffset(node.chunkOffset); gridPos.y += FloraGenerator::getChunkYOffset(node.chunkOffset); gridPos.z += FloraGenerator::getChunkZOffset(node.chunkOffset); if (gridPos.x >= 0 && gridPos.y >= 0 && gridPos.z >= 0 && gridPos.x < HORIZONTAL_CHUNKS && gridPos.y < VERTICAL_CHUNKS && gridPos.z < HORIZONTAL_CHUNKS) { Chunk* chunk = m_chunks[gridPos.x + gridPos.y * HORIZONTAL_CHUNKS * HORIZONTAL_CHUNKS + gridPos.z * HORIZONTAL_CHUNKS].chunk; if (chunk->blocks.get(node.blockIndex) == 0) { chunk->blocks.set(node.blockIndex, node.blockID); } } } std::vector<ui16>().swap(chunk->floraToGenerate); lNodes.clear(); wNodes.clear(); } printf("Tree Gen Time %lf\n", t1.stop()); #define GET_INDEX(x, y, z) ((x) + (y) * HORIZONTAL_CHUNKS * HORIZONTAL_CHUNKS + (z) * HORIZONTAL_CHUNKS) // Set neighbor pointers for (int y = 0; y < VERTICAL_CHUNKS; y++) { for (int z = 0; z < HORIZONTAL_CHUNKS; z++) { for (int x = 0; x < HORIZONTAL_CHUNKS; x++) { Chunk* chunk = m_chunks[GET_INDEX(x, y, z)].chunk; // TODO(Ben): Release these too. if (x > 0) { chunk->neighbor.left = m_chunks[GET_INDEX(x - 1, y, z)].chunk.acquire(); } if (x < HORIZONTAL_CHUNKS - 1) { chunk->neighbor.right = m_chunks[GET_INDEX(x + 1, y, z)].chunk.acquire(); } if (y > 0) { chunk->neighbor.bottom = m_chunks[GET_INDEX(x, y - 1, z)].chunk.acquire(); } if (y < VERTICAL_CHUNKS - 1) { chunk->neighbor.top = m_chunks[GET_INDEX(x, y + 1, z)].chunk.acquire(); } if (z > 0) { chunk->neighbor.back = m_chunks[GET_INDEX(x, y, z - 1)].chunk.acquire(); } if (z < HORIZONTAL_CHUNKS - 1) { chunk->neighbor.front = m_chunks[GET_INDEX(x, y, z + 1)].chunk.acquire(); } } } } } void TestBiomeScreen::initInput() { m_inputMapper = new InputMapper; initInputs(m_inputMapper); m_mouseButtons[0] = false; m_hooks.addAutoHook(vui::InputDispatcher::mouse.onMotion, [&](Sender s VORB_MAYBE_UNUSED, const vui::MouseMotionEvent& e) { if (m_mouseButtons[0]) { m_camera.rotateFromMouseAbsoluteUp(-e.dx, -e.dy, 0.01f, true); } }); m_hooks.addAutoHook(vui::InputDispatcher::mouse.onButtonDown, [&](Sender s VORB_MAYBE_UNUSED, const vui::MouseButtonEvent& e) { if (e.button == vui::MouseButton::LEFT) m_mouseButtons[0] = !m_mouseButtons[0]; if (m_mouseButtons[0]) { SDL_SetRelativeMouseMode(SDL_TRUE); } else { SDL_SetRelativeMouseMode(SDL_FALSE); } }); m_hooks.addAutoHook(vui::InputDispatcher::key.onKeyDown, [&](Sender s VORB_MAYBE_UNUSED, const vui::KeyEvent& e) { PlanetGenLoader planetLoader; switch (e.keyCode) { case VKEY_W: m_movingForward = true; break; case VKEY_S: m_movingBack = true; break; case VKEY_A: m_movingLeft = true; break; case VKEY_D: m_movingRight = true; break; case VKEY_SPACE: m_movingUp = true; break; case VKEY_LSHIFT: m_movingFast = true; break; case VKEY_M: m_wireFrame = !m_wireFrame; break; case VKEY_LEFT: /* if (m_activeChunk == 0) { m_activeChunk = m_chunks.size() - 1; } else { m_activeChunk--; }*/ break; case VKEY_RIGHT: /* m_activeChunk++; if (m_activeChunk >= (int)m_chunks.size()) m_activeChunk = 0;*/ break; case VKEY_F10: // Reload meshes // TODO(Ben): Destroy meshes for (auto& cv : m_chunks) { m_mesher.freeChunkMesh(cv.chunkMesh); cv.chunkMesh = m_mesher.easyCreateChunkMesh(cv.chunk, MeshTaskType::DEFAULT); } break; case VKEY_F11: // Reload shaders m_renderer.dispose(); m_renderer.init(); m_ssaoStage.reloadShaders(); break; case VKEY_F12: // Reload world delete m_genData; planetLoader.init(&m_iom); m_genData = planetLoader.loadPlanetGenData("Planets/Aldrin/terrain_gen.yml"); m_genData->radius = 4500.0; // Set blocks SoaEngine::initVoxelGen(m_genData, m_soaState->blocks); m_chunkGenerator.init(m_genData); for (auto& cv : m_chunks) { m_mesher.freeChunkMesh(cv.chunkMesh); cv.chunk.release(); } initHeightData(); initChunks(); printf("Generating Meshes...\n"); // Create all chunk meshes m_mesher.init(&m_soaState->blocks); for (auto& cv : m_chunks) { cv.chunkMesh = m_mesher.easyCreateChunkMesh(cv.chunk, MeshTaskType::DEFAULT); } break; } }); m_hooks.addAutoHook(vui::InputDispatcher::key.onKeyUp, [&](Sender s VORB_MAYBE_UNUSED, const vui::KeyEvent& e) { switch (e.keyCode) { case VKEY_W: m_movingForward = false; break; case VKEY_S: m_movingBack = false; break; case VKEY_A: m_movingLeft = false; break; case VKEY_D: m_movingRight = false; break; case VKEY_SPACE: m_movingUp = false; break; case VKEY_LSHIFT: m_movingFast = false; break; } }); // Dev console m_hooks.addAutoHook(m_inputMapper->get(INPUT_DEV_CONSOLE).downEvent, [](Sender s VORB_MAYBE_UNUSED, ui32 a VORB_MAYBE_UNUSED) { DevConsole::getInstance().toggleFocus(); }); m_inputMapper->startInput(); }
19,099
6,951
#include "pch-cpp.hpp" #ifndef _MSC_VER # include <alloca.h> #else # include <malloc.h> #endif #include <stdint.h> #include <limits> #include "vm/CachedCCWBase.h" #include "utils/New.h" // System.Collections.Generic.IEqualityComparer`1<WindTurbineScriptableObject> struct IEqualityComparer_1_t754733F7B8BE7D6A482129735D41581DA4211A89; // System.Collections.Generic.IEqualityComparer`1<System.Xml.XmlQualifiedName> struct IEqualityComparer_1_tA3F9CEF64ED38FA56ECC5E56165286AE1376D617; // System.Collections.Generic.Dictionary`2/KeyCollection<WindTurbineScriptableObject,UnityEngine.GameObject> struct KeyCollection_t34BD6D53CC7D3C809C9A1852E3EBD4E560CB6FC9; // System.Collections.Generic.Dictionary`2/KeyCollection<WindTurbineScriptableObject,SiteOverviewTurbineButton> struct KeyCollection_tF17A5FE33B5DE41ACFF287E964C81ECB6D59D543; // System.Collections.Generic.Dictionary`2/KeyCollection<System.Xml.XmlQualifiedName,System.Int32> struct KeyCollection_t2244A1557D5F76CA645CAFA1A60583DA72104A63; // System.Collections.Generic.Dictionary`2/KeyCollection<System.Xml.XmlQualifiedName,System.Xml.Schema.SchemaAttDef> struct KeyCollection_t5FE0EB338810A83B845B900E60A4E065E1E8AB68; // System.Collections.Generic.Dictionary`2/KeyCollection<System.Xml.XmlQualifiedName,System.Xml.Schema.SchemaElementDecl> struct KeyCollection_tFEE8457FE221E239778EE686C6BB8756470C8987; // System.Collections.Generic.Dictionary`2/KeyCollection<System.Xml.XmlQualifiedName,System.Xml.Schema.SchemaEntity> struct KeyCollection_tFCF38642F5CB0A86A6B4EC75E8BF5C9A8C4D0122; // System.Collections.Generic.Dictionary`2/KeyCollection<System.Xml.XmlQualifiedName,System.Xml.XmlQualifiedName> struct KeyCollection_t030E8C0717067BB35BC97531ADFD5B34DE81E372; // System.Collections.Generic.Dictionary`2/ValueCollection<WindTurbineScriptableObject,UnityEngine.GameObject> struct ValueCollection_t01E88B080F930A3AF5A6A8F2F73AF5BB36CEA942; // System.Collections.Generic.Dictionary`2/ValueCollection<WindTurbineScriptableObject,SiteOverviewTurbineButton> struct ValueCollection_t31490A63A035F1948892448F1AB3041282B20FDD; // System.Collections.Generic.Dictionary`2/ValueCollection<System.Xml.XmlQualifiedName,System.Int32> struct ValueCollection_tCB259046959321FDDB15DF0C7CDA3F3F0878E56E; // System.Collections.Generic.Dictionary`2/ValueCollection<System.Xml.XmlQualifiedName,System.Xml.Schema.SchemaAttDef> struct ValueCollection_tA992FE5AE14BF1BD39743AC399EF95B64E8AFC42; // System.Collections.Generic.Dictionary`2/ValueCollection<System.Xml.XmlQualifiedName,System.Xml.Schema.SchemaElementDecl> struct ValueCollection_t566E84C700B8CA57F1C3A24989857DEB3100189D; // System.Collections.Generic.Dictionary`2/ValueCollection<System.Xml.XmlQualifiedName,System.Xml.Schema.SchemaEntity> struct ValueCollection_tECAE69F11CA0C245794C99313E46CEAB79289400; // System.Collections.Generic.Dictionary`2/ValueCollection<System.Xml.XmlQualifiedName,System.Xml.XmlQualifiedName> struct ValueCollection_t0A13A40E317C41D701F731B2E09A7863C1AF1C9E; // System.Collections.Generic.Dictionary`2/Entry<WindTurbineScriptableObject,UnityEngine.GameObject>[] struct EntryU5BU5D_tBF7237941FB58B8E09BF9CD83B2793ADBF92D84E; // System.Collections.Generic.Dictionary`2/Entry<WindTurbineScriptableObject,SiteOverviewTurbineButton>[] struct EntryU5BU5D_t9FC1946A2F8CF647AD110DB3138597BC383D7E7F; // System.Collections.Generic.Dictionary`2/Entry<System.Xml.XmlQualifiedName,System.Int32>[] struct EntryU5BU5D_t117A50276A1DFDCB7A66D3DCB90525B42613F604; // System.Collections.Generic.Dictionary`2/Entry<System.Xml.XmlQualifiedName,System.Xml.Schema.SchemaAttDef>[] struct EntryU5BU5D_tDF263570453ED61DC82F1B72F9B1F10CF0C186FE; // System.Collections.Generic.Dictionary`2/Entry<System.Xml.XmlQualifiedName,System.Xml.Schema.SchemaElementDecl>[] struct EntryU5BU5D_t830E5130B05E1143F4ECA59D1CE8BD64AC3F7E2F; // System.Collections.Generic.Dictionary`2/Entry<System.Xml.XmlQualifiedName,System.Xml.Schema.SchemaEntity>[] struct EntryU5BU5D_t5AD4BA39F55C5C698AD90B02326A2225C5D56221; // System.Collections.Generic.Dictionary`2/Entry<System.Xml.XmlQualifiedName,System.Xml.XmlQualifiedName>[] struct EntryU5BU5D_tA3DDC0B951DBF95A552959A08A07C10A84E89DA0; // System.Int32[] struct Int32U5BU5D_t70F1BDC14B1786481B176D6139A5E3B87DC54C32; // System.String struct String_t; struct IBindableIterator_tD7550F1144CFBE58090050457A2BE92B1CAEABBB; IL2CPP_EXTERN_C_BEGIN IL2CPP_EXTERN_C_END #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // Windows.UI.Xaml.Interop.IBindableIterable struct NOVTABLE IBindableIterable_tF6BD0C070562CD9C91E3C1B1A5F4667E9C3C74A8 : Il2CppIInspectable { static const Il2CppGuid IID; virtual il2cpp_hresult_t STDCALL IBindableIterable_First_m91EC6ED0173145266318FDB7F9074798CD766BD7(IBindableIterator_tD7550F1144CFBE58090050457A2BE92B1CAEABBB** comReturnValue) = 0; }; // System.Object // System.Collections.Generic.Dictionary`2<WindTurbineScriptableObject,UnityEngine.GameObject> struct Dictionary_2_tBB6637D6ACE122CA21B1AAFE00D9DB6FB0DE4B8F : public RuntimeObject { public: // System.Int32[] System.Collections.Generic.Dictionary`2::buckets Int32U5BU5D_t70F1BDC14B1786481B176D6139A5E3B87DC54C32* ___buckets_0; // System.Collections.Generic.Dictionary`2/Entry<TKey,TValue>[] System.Collections.Generic.Dictionary`2::entries EntryU5BU5D_tBF7237941FB58B8E09BF9CD83B2793ADBF92D84E* ___entries_1; // System.Int32 System.Collections.Generic.Dictionary`2::count int32_t ___count_2; // System.Int32 System.Collections.Generic.Dictionary`2::version int32_t ___version_3; // System.Int32 System.Collections.Generic.Dictionary`2::freeList int32_t ___freeList_4; // System.Int32 System.Collections.Generic.Dictionary`2::freeCount int32_t ___freeCount_5; // System.Collections.Generic.IEqualityComparer`1<TKey> System.Collections.Generic.Dictionary`2::comparer RuntimeObject* ___comparer_6; // System.Collections.Generic.Dictionary`2/KeyCollection<TKey,TValue> System.Collections.Generic.Dictionary`2::keys KeyCollection_t34BD6D53CC7D3C809C9A1852E3EBD4E560CB6FC9 * ___keys_7; // System.Collections.Generic.Dictionary`2/ValueCollection<TKey,TValue> System.Collections.Generic.Dictionary`2::values ValueCollection_t01E88B080F930A3AF5A6A8F2F73AF5BB36CEA942 * ___values_8; // System.Object System.Collections.Generic.Dictionary`2::_syncRoot RuntimeObject * ____syncRoot_9; public: inline static int32_t get_offset_of_buckets_0() { return static_cast<int32_t>(offsetof(Dictionary_2_tBB6637D6ACE122CA21B1AAFE00D9DB6FB0DE4B8F, ___buckets_0)); } inline Int32U5BU5D_t70F1BDC14B1786481B176D6139A5E3B87DC54C32* get_buckets_0() const { return ___buckets_0; } inline Int32U5BU5D_t70F1BDC14B1786481B176D6139A5E3B87DC54C32** get_address_of_buckets_0() { return &___buckets_0; } inline void set_buckets_0(Int32U5BU5D_t70F1BDC14B1786481B176D6139A5E3B87DC54C32* value) { ___buckets_0 = value; Il2CppCodeGenWriteBarrier((void**)(&___buckets_0), (void*)value); } inline static int32_t get_offset_of_entries_1() { return static_cast<int32_t>(offsetof(Dictionary_2_tBB6637D6ACE122CA21B1AAFE00D9DB6FB0DE4B8F, ___entries_1)); } inline EntryU5BU5D_tBF7237941FB58B8E09BF9CD83B2793ADBF92D84E* get_entries_1() const { return ___entries_1; } inline EntryU5BU5D_tBF7237941FB58B8E09BF9CD83B2793ADBF92D84E** get_address_of_entries_1() { return &___entries_1; } inline void set_entries_1(EntryU5BU5D_tBF7237941FB58B8E09BF9CD83B2793ADBF92D84E* value) { ___entries_1 = value; Il2CppCodeGenWriteBarrier((void**)(&___entries_1), (void*)value); } inline static int32_t get_offset_of_count_2() { return static_cast<int32_t>(offsetof(Dictionary_2_tBB6637D6ACE122CA21B1AAFE00D9DB6FB0DE4B8F, ___count_2)); } inline int32_t get_count_2() const { return ___count_2; } inline int32_t* get_address_of_count_2() { return &___count_2; } inline void set_count_2(int32_t value) { ___count_2 = value; } inline static int32_t get_offset_of_version_3() { return static_cast<int32_t>(offsetof(Dictionary_2_tBB6637D6ACE122CA21B1AAFE00D9DB6FB0DE4B8F, ___version_3)); } inline int32_t get_version_3() const { return ___version_3; } inline int32_t* get_address_of_version_3() { return &___version_3; } inline void set_version_3(int32_t value) { ___version_3 = value; } inline static int32_t get_offset_of_freeList_4() { return static_cast<int32_t>(offsetof(Dictionary_2_tBB6637D6ACE122CA21B1AAFE00D9DB6FB0DE4B8F, ___freeList_4)); } inline int32_t get_freeList_4() const { return ___freeList_4; } inline int32_t* get_address_of_freeList_4() { return &___freeList_4; } inline void set_freeList_4(int32_t value) { ___freeList_4 = value; } inline static int32_t get_offset_of_freeCount_5() { return static_cast<int32_t>(offsetof(Dictionary_2_tBB6637D6ACE122CA21B1AAFE00D9DB6FB0DE4B8F, ___freeCount_5)); } inline int32_t get_freeCount_5() const { return ___freeCount_5; } inline int32_t* get_address_of_freeCount_5() { return &___freeCount_5; } inline void set_freeCount_5(int32_t value) { ___freeCount_5 = value; } inline static int32_t get_offset_of_comparer_6() { return static_cast<int32_t>(offsetof(Dictionary_2_tBB6637D6ACE122CA21B1AAFE00D9DB6FB0DE4B8F, ___comparer_6)); } inline RuntimeObject* get_comparer_6() const { return ___comparer_6; } inline RuntimeObject** get_address_of_comparer_6() { return &___comparer_6; } inline void set_comparer_6(RuntimeObject* value) { ___comparer_6 = value; Il2CppCodeGenWriteBarrier((void**)(&___comparer_6), (void*)value); } inline static int32_t get_offset_of_keys_7() { return static_cast<int32_t>(offsetof(Dictionary_2_tBB6637D6ACE122CA21B1AAFE00D9DB6FB0DE4B8F, ___keys_7)); } inline KeyCollection_t34BD6D53CC7D3C809C9A1852E3EBD4E560CB6FC9 * get_keys_7() const { return ___keys_7; } inline KeyCollection_t34BD6D53CC7D3C809C9A1852E3EBD4E560CB6FC9 ** get_address_of_keys_7() { return &___keys_7; } inline void set_keys_7(KeyCollection_t34BD6D53CC7D3C809C9A1852E3EBD4E560CB6FC9 * value) { ___keys_7 = value; Il2CppCodeGenWriteBarrier((void**)(&___keys_7), (void*)value); } inline static int32_t get_offset_of_values_8() { return static_cast<int32_t>(offsetof(Dictionary_2_tBB6637D6ACE122CA21B1AAFE00D9DB6FB0DE4B8F, ___values_8)); } inline ValueCollection_t01E88B080F930A3AF5A6A8F2F73AF5BB36CEA942 * get_values_8() const { return ___values_8; } inline ValueCollection_t01E88B080F930A3AF5A6A8F2F73AF5BB36CEA942 ** get_address_of_values_8() { return &___values_8; } inline void set_values_8(ValueCollection_t01E88B080F930A3AF5A6A8F2F73AF5BB36CEA942 * value) { ___values_8 = value; Il2CppCodeGenWriteBarrier((void**)(&___values_8), (void*)value); } inline static int32_t get_offset_of__syncRoot_9() { return static_cast<int32_t>(offsetof(Dictionary_2_tBB6637D6ACE122CA21B1AAFE00D9DB6FB0DE4B8F, ____syncRoot_9)); } inline RuntimeObject * get__syncRoot_9() const { return ____syncRoot_9; } inline RuntimeObject ** get_address_of__syncRoot_9() { return &____syncRoot_9; } inline void set__syncRoot_9(RuntimeObject * value) { ____syncRoot_9 = value; Il2CppCodeGenWriteBarrier((void**)(&____syncRoot_9), (void*)value); } }; // System.Collections.Generic.Dictionary`2<WindTurbineScriptableObject,SiteOverviewTurbineButton> struct Dictionary_2_t0541E6A56BBB9D3DAB2CCF3BA250073328DF2F85 : public RuntimeObject { public: // System.Int32[] System.Collections.Generic.Dictionary`2::buckets Int32U5BU5D_t70F1BDC14B1786481B176D6139A5E3B87DC54C32* ___buckets_0; // System.Collections.Generic.Dictionary`2/Entry<TKey,TValue>[] System.Collections.Generic.Dictionary`2::entries EntryU5BU5D_t9FC1946A2F8CF647AD110DB3138597BC383D7E7F* ___entries_1; // System.Int32 System.Collections.Generic.Dictionary`2::count int32_t ___count_2; // System.Int32 System.Collections.Generic.Dictionary`2::version int32_t ___version_3; // System.Int32 System.Collections.Generic.Dictionary`2::freeList int32_t ___freeList_4; // System.Int32 System.Collections.Generic.Dictionary`2::freeCount int32_t ___freeCount_5; // System.Collections.Generic.IEqualityComparer`1<TKey> System.Collections.Generic.Dictionary`2::comparer RuntimeObject* ___comparer_6; // System.Collections.Generic.Dictionary`2/KeyCollection<TKey,TValue> System.Collections.Generic.Dictionary`2::keys KeyCollection_tF17A5FE33B5DE41ACFF287E964C81ECB6D59D543 * ___keys_7; // System.Collections.Generic.Dictionary`2/ValueCollection<TKey,TValue> System.Collections.Generic.Dictionary`2::values ValueCollection_t31490A63A035F1948892448F1AB3041282B20FDD * ___values_8; // System.Object System.Collections.Generic.Dictionary`2::_syncRoot RuntimeObject * ____syncRoot_9; public: inline static int32_t get_offset_of_buckets_0() { return static_cast<int32_t>(offsetof(Dictionary_2_t0541E6A56BBB9D3DAB2CCF3BA250073328DF2F85, ___buckets_0)); } inline Int32U5BU5D_t70F1BDC14B1786481B176D6139A5E3B87DC54C32* get_buckets_0() const { return ___buckets_0; } inline Int32U5BU5D_t70F1BDC14B1786481B176D6139A5E3B87DC54C32** get_address_of_buckets_0() { return &___buckets_0; } inline void set_buckets_0(Int32U5BU5D_t70F1BDC14B1786481B176D6139A5E3B87DC54C32* value) { ___buckets_0 = value; Il2CppCodeGenWriteBarrier((void**)(&___buckets_0), (void*)value); } inline static int32_t get_offset_of_entries_1() { return static_cast<int32_t>(offsetof(Dictionary_2_t0541E6A56BBB9D3DAB2CCF3BA250073328DF2F85, ___entries_1)); } inline EntryU5BU5D_t9FC1946A2F8CF647AD110DB3138597BC383D7E7F* get_entries_1() const { return ___entries_1; } inline EntryU5BU5D_t9FC1946A2F8CF647AD110DB3138597BC383D7E7F** get_address_of_entries_1() { return &___entries_1; } inline void set_entries_1(EntryU5BU5D_t9FC1946A2F8CF647AD110DB3138597BC383D7E7F* value) { ___entries_1 = value; Il2CppCodeGenWriteBarrier((void**)(&___entries_1), (void*)value); } inline static int32_t get_offset_of_count_2() { return static_cast<int32_t>(offsetof(Dictionary_2_t0541E6A56BBB9D3DAB2CCF3BA250073328DF2F85, ___count_2)); } inline int32_t get_count_2() const { return ___count_2; } inline int32_t* get_address_of_count_2() { return &___count_2; } inline void set_count_2(int32_t value) { ___count_2 = value; } inline static int32_t get_offset_of_version_3() { return static_cast<int32_t>(offsetof(Dictionary_2_t0541E6A56BBB9D3DAB2CCF3BA250073328DF2F85, ___version_3)); } inline int32_t get_version_3() const { return ___version_3; } inline int32_t* get_address_of_version_3() { return &___version_3; } inline void set_version_3(int32_t value) { ___version_3 = value; } inline static int32_t get_offset_of_freeList_4() { return static_cast<int32_t>(offsetof(Dictionary_2_t0541E6A56BBB9D3DAB2CCF3BA250073328DF2F85, ___freeList_4)); } inline int32_t get_freeList_4() const { return ___freeList_4; } inline int32_t* get_address_of_freeList_4() { return &___freeList_4; } inline void set_freeList_4(int32_t value) { ___freeList_4 = value; } inline static int32_t get_offset_of_freeCount_5() { return static_cast<int32_t>(offsetof(Dictionary_2_t0541E6A56BBB9D3DAB2CCF3BA250073328DF2F85, ___freeCount_5)); } inline int32_t get_freeCount_5() const { return ___freeCount_5; } inline int32_t* get_address_of_freeCount_5() { return &___freeCount_5; } inline void set_freeCount_5(int32_t value) { ___freeCount_5 = value; } inline static int32_t get_offset_of_comparer_6() { return static_cast<int32_t>(offsetof(Dictionary_2_t0541E6A56BBB9D3DAB2CCF3BA250073328DF2F85, ___comparer_6)); } inline RuntimeObject* get_comparer_6() const { return ___comparer_6; } inline RuntimeObject** get_address_of_comparer_6() { return &___comparer_6; } inline void set_comparer_6(RuntimeObject* value) { ___comparer_6 = value; Il2CppCodeGenWriteBarrier((void**)(&___comparer_6), (void*)value); } inline static int32_t get_offset_of_keys_7() { return static_cast<int32_t>(offsetof(Dictionary_2_t0541E6A56BBB9D3DAB2CCF3BA250073328DF2F85, ___keys_7)); } inline KeyCollection_tF17A5FE33B5DE41ACFF287E964C81ECB6D59D543 * get_keys_7() const { return ___keys_7; } inline KeyCollection_tF17A5FE33B5DE41ACFF287E964C81ECB6D59D543 ** get_address_of_keys_7() { return &___keys_7; } inline void set_keys_7(KeyCollection_tF17A5FE33B5DE41ACFF287E964C81ECB6D59D543 * value) { ___keys_7 = value; Il2CppCodeGenWriteBarrier((void**)(&___keys_7), (void*)value); } inline static int32_t get_offset_of_values_8() { return static_cast<int32_t>(offsetof(Dictionary_2_t0541E6A56BBB9D3DAB2CCF3BA250073328DF2F85, ___values_8)); } inline ValueCollection_t31490A63A035F1948892448F1AB3041282B20FDD * get_values_8() const { return ___values_8; } inline ValueCollection_t31490A63A035F1948892448F1AB3041282B20FDD ** get_address_of_values_8() { return &___values_8; } inline void set_values_8(ValueCollection_t31490A63A035F1948892448F1AB3041282B20FDD * value) { ___values_8 = value; Il2CppCodeGenWriteBarrier((void**)(&___values_8), (void*)value); } inline static int32_t get_offset_of__syncRoot_9() { return static_cast<int32_t>(offsetof(Dictionary_2_t0541E6A56BBB9D3DAB2CCF3BA250073328DF2F85, ____syncRoot_9)); } inline RuntimeObject * get__syncRoot_9() const { return ____syncRoot_9; } inline RuntimeObject ** get_address_of__syncRoot_9() { return &____syncRoot_9; } inline void set__syncRoot_9(RuntimeObject * value) { ____syncRoot_9 = value; Il2CppCodeGenWriteBarrier((void**)(&____syncRoot_9), (void*)value); } }; // System.Collections.Generic.Dictionary`2<System.Xml.XmlQualifiedName,System.Int32> struct Dictionary_2_t9271D5E45EC14905F5999D37CAEA9320F5D0A5F6 : public RuntimeObject { public: // System.Int32[] System.Collections.Generic.Dictionary`2::buckets Int32U5BU5D_t70F1BDC14B1786481B176D6139A5E3B87DC54C32* ___buckets_0; // System.Collections.Generic.Dictionary`2/Entry<TKey,TValue>[] System.Collections.Generic.Dictionary`2::entries EntryU5BU5D_t117A50276A1DFDCB7A66D3DCB90525B42613F604* ___entries_1; // System.Int32 System.Collections.Generic.Dictionary`2::count int32_t ___count_2; // System.Int32 System.Collections.Generic.Dictionary`2::version int32_t ___version_3; // System.Int32 System.Collections.Generic.Dictionary`2::freeList int32_t ___freeList_4; // System.Int32 System.Collections.Generic.Dictionary`2::freeCount int32_t ___freeCount_5; // System.Collections.Generic.IEqualityComparer`1<TKey> System.Collections.Generic.Dictionary`2::comparer RuntimeObject* ___comparer_6; // System.Collections.Generic.Dictionary`2/KeyCollection<TKey,TValue> System.Collections.Generic.Dictionary`2::keys KeyCollection_t2244A1557D5F76CA645CAFA1A60583DA72104A63 * ___keys_7; // System.Collections.Generic.Dictionary`2/ValueCollection<TKey,TValue> System.Collections.Generic.Dictionary`2::values ValueCollection_tCB259046959321FDDB15DF0C7CDA3F3F0878E56E * ___values_8; // System.Object System.Collections.Generic.Dictionary`2::_syncRoot RuntimeObject * ____syncRoot_9; public: inline static int32_t get_offset_of_buckets_0() { return static_cast<int32_t>(offsetof(Dictionary_2_t9271D5E45EC14905F5999D37CAEA9320F5D0A5F6, ___buckets_0)); } inline Int32U5BU5D_t70F1BDC14B1786481B176D6139A5E3B87DC54C32* get_buckets_0() const { return ___buckets_0; } inline Int32U5BU5D_t70F1BDC14B1786481B176D6139A5E3B87DC54C32** get_address_of_buckets_0() { return &___buckets_0; } inline void set_buckets_0(Int32U5BU5D_t70F1BDC14B1786481B176D6139A5E3B87DC54C32* value) { ___buckets_0 = value; Il2CppCodeGenWriteBarrier((void**)(&___buckets_0), (void*)value); } inline static int32_t get_offset_of_entries_1() { return static_cast<int32_t>(offsetof(Dictionary_2_t9271D5E45EC14905F5999D37CAEA9320F5D0A5F6, ___entries_1)); } inline EntryU5BU5D_t117A50276A1DFDCB7A66D3DCB90525B42613F604* get_entries_1() const { return ___entries_1; } inline EntryU5BU5D_t117A50276A1DFDCB7A66D3DCB90525B42613F604** get_address_of_entries_1() { return &___entries_1; } inline void set_entries_1(EntryU5BU5D_t117A50276A1DFDCB7A66D3DCB90525B42613F604* value) { ___entries_1 = value; Il2CppCodeGenWriteBarrier((void**)(&___entries_1), (void*)value); } inline static int32_t get_offset_of_count_2() { return static_cast<int32_t>(offsetof(Dictionary_2_t9271D5E45EC14905F5999D37CAEA9320F5D0A5F6, ___count_2)); } inline int32_t get_count_2() const { return ___count_2; } inline int32_t* get_address_of_count_2() { return &___count_2; } inline void set_count_2(int32_t value) { ___count_2 = value; } inline static int32_t get_offset_of_version_3() { return static_cast<int32_t>(offsetof(Dictionary_2_t9271D5E45EC14905F5999D37CAEA9320F5D0A5F6, ___version_3)); } inline int32_t get_version_3() const { return ___version_3; } inline int32_t* get_address_of_version_3() { return &___version_3; } inline void set_version_3(int32_t value) { ___version_3 = value; } inline static int32_t get_offset_of_freeList_4() { return static_cast<int32_t>(offsetof(Dictionary_2_t9271D5E45EC14905F5999D37CAEA9320F5D0A5F6, ___freeList_4)); } inline int32_t get_freeList_4() const { return ___freeList_4; } inline int32_t* get_address_of_freeList_4() { return &___freeList_4; } inline void set_freeList_4(int32_t value) { ___freeList_4 = value; } inline static int32_t get_offset_of_freeCount_5() { return static_cast<int32_t>(offsetof(Dictionary_2_t9271D5E45EC14905F5999D37CAEA9320F5D0A5F6, ___freeCount_5)); } inline int32_t get_freeCount_5() const { return ___freeCount_5; } inline int32_t* get_address_of_freeCount_5() { return &___freeCount_5; } inline void set_freeCount_5(int32_t value) { ___freeCount_5 = value; } inline static int32_t get_offset_of_comparer_6() { return static_cast<int32_t>(offsetof(Dictionary_2_t9271D5E45EC14905F5999D37CAEA9320F5D0A5F6, ___comparer_6)); } inline RuntimeObject* get_comparer_6() const { return ___comparer_6; } inline RuntimeObject** get_address_of_comparer_6() { return &___comparer_6; } inline void set_comparer_6(RuntimeObject* value) { ___comparer_6 = value; Il2CppCodeGenWriteBarrier((void**)(&___comparer_6), (void*)value); } inline static int32_t get_offset_of_keys_7() { return static_cast<int32_t>(offsetof(Dictionary_2_t9271D5E45EC14905F5999D37CAEA9320F5D0A5F6, ___keys_7)); } inline KeyCollection_t2244A1557D5F76CA645CAFA1A60583DA72104A63 * get_keys_7() const { return ___keys_7; } inline KeyCollection_t2244A1557D5F76CA645CAFA1A60583DA72104A63 ** get_address_of_keys_7() { return &___keys_7; } inline void set_keys_7(KeyCollection_t2244A1557D5F76CA645CAFA1A60583DA72104A63 * value) { ___keys_7 = value; Il2CppCodeGenWriteBarrier((void**)(&___keys_7), (void*)value); } inline static int32_t get_offset_of_values_8() { return static_cast<int32_t>(offsetof(Dictionary_2_t9271D5E45EC14905F5999D37CAEA9320F5D0A5F6, ___values_8)); } inline ValueCollection_tCB259046959321FDDB15DF0C7CDA3F3F0878E56E * get_values_8() const { return ___values_8; } inline ValueCollection_tCB259046959321FDDB15DF0C7CDA3F3F0878E56E ** get_address_of_values_8() { return &___values_8; } inline void set_values_8(ValueCollection_tCB259046959321FDDB15DF0C7CDA3F3F0878E56E * value) { ___values_8 = value; Il2CppCodeGenWriteBarrier((void**)(&___values_8), (void*)value); } inline static int32_t get_offset_of__syncRoot_9() { return static_cast<int32_t>(offsetof(Dictionary_2_t9271D5E45EC14905F5999D37CAEA9320F5D0A5F6, ____syncRoot_9)); } inline RuntimeObject * get__syncRoot_9() const { return ____syncRoot_9; } inline RuntimeObject ** get_address_of__syncRoot_9() { return &____syncRoot_9; } inline void set__syncRoot_9(RuntimeObject * value) { ____syncRoot_9 = value; Il2CppCodeGenWriteBarrier((void**)(&____syncRoot_9), (void*)value); } }; // System.Collections.Generic.Dictionary`2<System.Xml.XmlQualifiedName,System.Xml.Schema.SchemaAttDef> struct Dictionary_2_t1FAD0C7CC6F970A1F41D0F7433B8D62A408D1C58 : public RuntimeObject { public: // System.Int32[] System.Collections.Generic.Dictionary`2::buckets Int32U5BU5D_t70F1BDC14B1786481B176D6139A5E3B87DC54C32* ___buckets_0; // System.Collections.Generic.Dictionary`2/Entry<TKey,TValue>[] System.Collections.Generic.Dictionary`2::entries EntryU5BU5D_tDF263570453ED61DC82F1B72F9B1F10CF0C186FE* ___entries_1; // System.Int32 System.Collections.Generic.Dictionary`2::count int32_t ___count_2; // System.Int32 System.Collections.Generic.Dictionary`2::version int32_t ___version_3; // System.Int32 System.Collections.Generic.Dictionary`2::freeList int32_t ___freeList_4; // System.Int32 System.Collections.Generic.Dictionary`2::freeCount int32_t ___freeCount_5; // System.Collections.Generic.IEqualityComparer`1<TKey> System.Collections.Generic.Dictionary`2::comparer RuntimeObject* ___comparer_6; // System.Collections.Generic.Dictionary`2/KeyCollection<TKey,TValue> System.Collections.Generic.Dictionary`2::keys KeyCollection_t5FE0EB338810A83B845B900E60A4E065E1E8AB68 * ___keys_7; // System.Collections.Generic.Dictionary`2/ValueCollection<TKey,TValue> System.Collections.Generic.Dictionary`2::values ValueCollection_tA992FE5AE14BF1BD39743AC399EF95B64E8AFC42 * ___values_8; // System.Object System.Collections.Generic.Dictionary`2::_syncRoot RuntimeObject * ____syncRoot_9; public: inline static int32_t get_offset_of_buckets_0() { return static_cast<int32_t>(offsetof(Dictionary_2_t1FAD0C7CC6F970A1F41D0F7433B8D62A408D1C58, ___buckets_0)); } inline Int32U5BU5D_t70F1BDC14B1786481B176D6139A5E3B87DC54C32* get_buckets_0() const { return ___buckets_0; } inline Int32U5BU5D_t70F1BDC14B1786481B176D6139A5E3B87DC54C32** get_address_of_buckets_0() { return &___buckets_0; } inline void set_buckets_0(Int32U5BU5D_t70F1BDC14B1786481B176D6139A5E3B87DC54C32* value) { ___buckets_0 = value; Il2CppCodeGenWriteBarrier((void**)(&___buckets_0), (void*)value); } inline static int32_t get_offset_of_entries_1() { return static_cast<int32_t>(offsetof(Dictionary_2_t1FAD0C7CC6F970A1F41D0F7433B8D62A408D1C58, ___entries_1)); } inline EntryU5BU5D_tDF263570453ED61DC82F1B72F9B1F10CF0C186FE* get_entries_1() const { return ___entries_1; } inline EntryU5BU5D_tDF263570453ED61DC82F1B72F9B1F10CF0C186FE** get_address_of_entries_1() { return &___entries_1; } inline void set_entries_1(EntryU5BU5D_tDF263570453ED61DC82F1B72F9B1F10CF0C186FE* value) { ___entries_1 = value; Il2CppCodeGenWriteBarrier((void**)(&___entries_1), (void*)value); } inline static int32_t get_offset_of_count_2() { return static_cast<int32_t>(offsetof(Dictionary_2_t1FAD0C7CC6F970A1F41D0F7433B8D62A408D1C58, ___count_2)); } inline int32_t get_count_2() const { return ___count_2; } inline int32_t* get_address_of_count_2() { return &___count_2; } inline void set_count_2(int32_t value) { ___count_2 = value; } inline static int32_t get_offset_of_version_3() { return static_cast<int32_t>(offsetof(Dictionary_2_t1FAD0C7CC6F970A1F41D0F7433B8D62A408D1C58, ___version_3)); } inline int32_t get_version_3() const { return ___version_3; } inline int32_t* get_address_of_version_3() { return &___version_3; } inline void set_version_3(int32_t value) { ___version_3 = value; } inline static int32_t get_offset_of_freeList_4() { return static_cast<int32_t>(offsetof(Dictionary_2_t1FAD0C7CC6F970A1F41D0F7433B8D62A408D1C58, ___freeList_4)); } inline int32_t get_freeList_4() const { return ___freeList_4; } inline int32_t* get_address_of_freeList_4() { return &___freeList_4; } inline void set_freeList_4(int32_t value) { ___freeList_4 = value; } inline static int32_t get_offset_of_freeCount_5() { return static_cast<int32_t>(offsetof(Dictionary_2_t1FAD0C7CC6F970A1F41D0F7433B8D62A408D1C58, ___freeCount_5)); } inline int32_t get_freeCount_5() const { return ___freeCount_5; } inline int32_t* get_address_of_freeCount_5() { return &___freeCount_5; } inline void set_freeCount_5(int32_t value) { ___freeCount_5 = value; } inline static int32_t get_offset_of_comparer_6() { return static_cast<int32_t>(offsetof(Dictionary_2_t1FAD0C7CC6F970A1F41D0F7433B8D62A408D1C58, ___comparer_6)); } inline RuntimeObject* get_comparer_6() const { return ___comparer_6; } inline RuntimeObject** get_address_of_comparer_6() { return &___comparer_6; } inline void set_comparer_6(RuntimeObject* value) { ___comparer_6 = value; Il2CppCodeGenWriteBarrier((void**)(&___comparer_6), (void*)value); } inline static int32_t get_offset_of_keys_7() { return static_cast<int32_t>(offsetof(Dictionary_2_t1FAD0C7CC6F970A1F41D0F7433B8D62A408D1C58, ___keys_7)); } inline KeyCollection_t5FE0EB338810A83B845B900E60A4E065E1E8AB68 * get_keys_7() const { return ___keys_7; } inline KeyCollection_t5FE0EB338810A83B845B900E60A4E065E1E8AB68 ** get_address_of_keys_7() { return &___keys_7; } inline void set_keys_7(KeyCollection_t5FE0EB338810A83B845B900E60A4E065E1E8AB68 * value) { ___keys_7 = value; Il2CppCodeGenWriteBarrier((void**)(&___keys_7), (void*)value); } inline static int32_t get_offset_of_values_8() { return static_cast<int32_t>(offsetof(Dictionary_2_t1FAD0C7CC6F970A1F41D0F7433B8D62A408D1C58, ___values_8)); } inline ValueCollection_tA992FE5AE14BF1BD39743AC399EF95B64E8AFC42 * get_values_8() const { return ___values_8; } inline ValueCollection_tA992FE5AE14BF1BD39743AC399EF95B64E8AFC42 ** get_address_of_values_8() { return &___values_8; } inline void set_values_8(ValueCollection_tA992FE5AE14BF1BD39743AC399EF95B64E8AFC42 * value) { ___values_8 = value; Il2CppCodeGenWriteBarrier((void**)(&___values_8), (void*)value); } inline static int32_t get_offset_of__syncRoot_9() { return static_cast<int32_t>(offsetof(Dictionary_2_t1FAD0C7CC6F970A1F41D0F7433B8D62A408D1C58, ____syncRoot_9)); } inline RuntimeObject * get__syncRoot_9() const { return ____syncRoot_9; } inline RuntimeObject ** get_address_of__syncRoot_9() { return &____syncRoot_9; } inline void set__syncRoot_9(RuntimeObject * value) { ____syncRoot_9 = value; Il2CppCodeGenWriteBarrier((void**)(&____syncRoot_9), (void*)value); } }; // System.Collections.Generic.Dictionary`2<System.Xml.XmlQualifiedName,System.Xml.Schema.SchemaElementDecl> struct Dictionary_2_t9716CEDD4260B2B68461B83D64B387A3786A25C7 : public RuntimeObject { public: // System.Int32[] System.Collections.Generic.Dictionary`2::buckets Int32U5BU5D_t70F1BDC14B1786481B176D6139A5E3B87DC54C32* ___buckets_0; // System.Collections.Generic.Dictionary`2/Entry<TKey,TValue>[] System.Collections.Generic.Dictionary`2::entries EntryU5BU5D_t830E5130B05E1143F4ECA59D1CE8BD64AC3F7E2F* ___entries_1; // System.Int32 System.Collections.Generic.Dictionary`2::count int32_t ___count_2; // System.Int32 System.Collections.Generic.Dictionary`2::version int32_t ___version_3; // System.Int32 System.Collections.Generic.Dictionary`2::freeList int32_t ___freeList_4; // System.Int32 System.Collections.Generic.Dictionary`2::freeCount int32_t ___freeCount_5; // System.Collections.Generic.IEqualityComparer`1<TKey> System.Collections.Generic.Dictionary`2::comparer RuntimeObject* ___comparer_6; // System.Collections.Generic.Dictionary`2/KeyCollection<TKey,TValue> System.Collections.Generic.Dictionary`2::keys KeyCollection_tFEE8457FE221E239778EE686C6BB8756470C8987 * ___keys_7; // System.Collections.Generic.Dictionary`2/ValueCollection<TKey,TValue> System.Collections.Generic.Dictionary`2::values ValueCollection_t566E84C700B8CA57F1C3A24989857DEB3100189D * ___values_8; // System.Object System.Collections.Generic.Dictionary`2::_syncRoot RuntimeObject * ____syncRoot_9; public: inline static int32_t get_offset_of_buckets_0() { return static_cast<int32_t>(offsetof(Dictionary_2_t9716CEDD4260B2B68461B83D64B387A3786A25C7, ___buckets_0)); } inline Int32U5BU5D_t70F1BDC14B1786481B176D6139A5E3B87DC54C32* get_buckets_0() const { return ___buckets_0; } inline Int32U5BU5D_t70F1BDC14B1786481B176D6139A5E3B87DC54C32** get_address_of_buckets_0() { return &___buckets_0; } inline void set_buckets_0(Int32U5BU5D_t70F1BDC14B1786481B176D6139A5E3B87DC54C32* value) { ___buckets_0 = value; Il2CppCodeGenWriteBarrier((void**)(&___buckets_0), (void*)value); } inline static int32_t get_offset_of_entries_1() { return static_cast<int32_t>(offsetof(Dictionary_2_t9716CEDD4260B2B68461B83D64B387A3786A25C7, ___entries_1)); } inline EntryU5BU5D_t830E5130B05E1143F4ECA59D1CE8BD64AC3F7E2F* get_entries_1() const { return ___entries_1; } inline EntryU5BU5D_t830E5130B05E1143F4ECA59D1CE8BD64AC3F7E2F** get_address_of_entries_1() { return &___entries_1; } inline void set_entries_1(EntryU5BU5D_t830E5130B05E1143F4ECA59D1CE8BD64AC3F7E2F* value) { ___entries_1 = value; Il2CppCodeGenWriteBarrier((void**)(&___entries_1), (void*)value); } inline static int32_t get_offset_of_count_2() { return static_cast<int32_t>(offsetof(Dictionary_2_t9716CEDD4260B2B68461B83D64B387A3786A25C7, ___count_2)); } inline int32_t get_count_2() const { return ___count_2; } inline int32_t* get_address_of_count_2() { return &___count_2; } inline void set_count_2(int32_t value) { ___count_2 = value; } inline static int32_t get_offset_of_version_3() { return static_cast<int32_t>(offsetof(Dictionary_2_t9716CEDD4260B2B68461B83D64B387A3786A25C7, ___version_3)); } inline int32_t get_version_3() const { return ___version_3; } inline int32_t* get_address_of_version_3() { return &___version_3; } inline void set_version_3(int32_t value) { ___version_3 = value; } inline static int32_t get_offset_of_freeList_4() { return static_cast<int32_t>(offsetof(Dictionary_2_t9716CEDD4260B2B68461B83D64B387A3786A25C7, ___freeList_4)); } inline int32_t get_freeList_4() const { return ___freeList_4; } inline int32_t* get_address_of_freeList_4() { return &___freeList_4; } inline void set_freeList_4(int32_t value) { ___freeList_4 = value; } inline static int32_t get_offset_of_freeCount_5() { return static_cast<int32_t>(offsetof(Dictionary_2_t9716CEDD4260B2B68461B83D64B387A3786A25C7, ___freeCount_5)); } inline int32_t get_freeCount_5() const { return ___freeCount_5; } inline int32_t* get_address_of_freeCount_5() { return &___freeCount_5; } inline void set_freeCount_5(int32_t value) { ___freeCount_5 = value; } inline static int32_t get_offset_of_comparer_6() { return static_cast<int32_t>(offsetof(Dictionary_2_t9716CEDD4260B2B68461B83D64B387A3786A25C7, ___comparer_6)); } inline RuntimeObject* get_comparer_6() const { return ___comparer_6; } inline RuntimeObject** get_address_of_comparer_6() { return &___comparer_6; } inline void set_comparer_6(RuntimeObject* value) { ___comparer_6 = value; Il2CppCodeGenWriteBarrier((void**)(&___comparer_6), (void*)value); } inline static int32_t get_offset_of_keys_7() { return static_cast<int32_t>(offsetof(Dictionary_2_t9716CEDD4260B2B68461B83D64B387A3786A25C7, ___keys_7)); } inline KeyCollection_tFEE8457FE221E239778EE686C6BB8756470C8987 * get_keys_7() const { return ___keys_7; } inline KeyCollection_tFEE8457FE221E239778EE686C6BB8756470C8987 ** get_address_of_keys_7() { return &___keys_7; } inline void set_keys_7(KeyCollection_tFEE8457FE221E239778EE686C6BB8756470C8987 * value) { ___keys_7 = value; Il2CppCodeGenWriteBarrier((void**)(&___keys_7), (void*)value); } inline static int32_t get_offset_of_values_8() { return static_cast<int32_t>(offsetof(Dictionary_2_t9716CEDD4260B2B68461B83D64B387A3786A25C7, ___values_8)); } inline ValueCollection_t566E84C700B8CA57F1C3A24989857DEB3100189D * get_values_8() const { return ___values_8; } inline ValueCollection_t566E84C700B8CA57F1C3A24989857DEB3100189D ** get_address_of_values_8() { return &___values_8; } inline void set_values_8(ValueCollection_t566E84C700B8CA57F1C3A24989857DEB3100189D * value) { ___values_8 = value; Il2CppCodeGenWriteBarrier((void**)(&___values_8), (void*)value); } inline static int32_t get_offset_of__syncRoot_9() { return static_cast<int32_t>(offsetof(Dictionary_2_t9716CEDD4260B2B68461B83D64B387A3786A25C7, ____syncRoot_9)); } inline RuntimeObject * get__syncRoot_9() const { return ____syncRoot_9; } inline RuntimeObject ** get_address_of__syncRoot_9() { return &____syncRoot_9; } inline void set__syncRoot_9(RuntimeObject * value) { ____syncRoot_9 = value; Il2CppCodeGenWriteBarrier((void**)(&____syncRoot_9), (void*)value); } }; // System.Collections.Generic.Dictionary`2<System.Xml.XmlQualifiedName,System.Xml.Schema.SchemaEntity> struct Dictionary_2_tE268B8DA28D3A82319F0632A15D6EC06B68E5523 : public RuntimeObject { public: // System.Int32[] System.Collections.Generic.Dictionary`2::buckets Int32U5BU5D_t70F1BDC14B1786481B176D6139A5E3B87DC54C32* ___buckets_0; // System.Collections.Generic.Dictionary`2/Entry<TKey,TValue>[] System.Collections.Generic.Dictionary`2::entries EntryU5BU5D_t5AD4BA39F55C5C698AD90B02326A2225C5D56221* ___entries_1; // System.Int32 System.Collections.Generic.Dictionary`2::count int32_t ___count_2; // System.Int32 System.Collections.Generic.Dictionary`2::version int32_t ___version_3; // System.Int32 System.Collections.Generic.Dictionary`2::freeList int32_t ___freeList_4; // System.Int32 System.Collections.Generic.Dictionary`2::freeCount int32_t ___freeCount_5; // System.Collections.Generic.IEqualityComparer`1<TKey> System.Collections.Generic.Dictionary`2::comparer RuntimeObject* ___comparer_6; // System.Collections.Generic.Dictionary`2/KeyCollection<TKey,TValue> System.Collections.Generic.Dictionary`2::keys KeyCollection_tFCF38642F5CB0A86A6B4EC75E8BF5C9A8C4D0122 * ___keys_7; // System.Collections.Generic.Dictionary`2/ValueCollection<TKey,TValue> System.Collections.Generic.Dictionary`2::values ValueCollection_tECAE69F11CA0C245794C99313E46CEAB79289400 * ___values_8; // System.Object System.Collections.Generic.Dictionary`2::_syncRoot RuntimeObject * ____syncRoot_9; public: inline static int32_t get_offset_of_buckets_0() { return static_cast<int32_t>(offsetof(Dictionary_2_tE268B8DA28D3A82319F0632A15D6EC06B68E5523, ___buckets_0)); } inline Int32U5BU5D_t70F1BDC14B1786481B176D6139A5E3B87DC54C32* get_buckets_0() const { return ___buckets_0; } inline Int32U5BU5D_t70F1BDC14B1786481B176D6139A5E3B87DC54C32** get_address_of_buckets_0() { return &___buckets_0; } inline void set_buckets_0(Int32U5BU5D_t70F1BDC14B1786481B176D6139A5E3B87DC54C32* value) { ___buckets_0 = value; Il2CppCodeGenWriteBarrier((void**)(&___buckets_0), (void*)value); } inline static int32_t get_offset_of_entries_1() { return static_cast<int32_t>(offsetof(Dictionary_2_tE268B8DA28D3A82319F0632A15D6EC06B68E5523, ___entries_1)); } inline EntryU5BU5D_t5AD4BA39F55C5C698AD90B02326A2225C5D56221* get_entries_1() const { return ___entries_1; } inline EntryU5BU5D_t5AD4BA39F55C5C698AD90B02326A2225C5D56221** get_address_of_entries_1() { return &___entries_1; } inline void set_entries_1(EntryU5BU5D_t5AD4BA39F55C5C698AD90B02326A2225C5D56221* value) { ___entries_1 = value; Il2CppCodeGenWriteBarrier((void**)(&___entries_1), (void*)value); } inline static int32_t get_offset_of_count_2() { return static_cast<int32_t>(offsetof(Dictionary_2_tE268B8DA28D3A82319F0632A15D6EC06B68E5523, ___count_2)); } inline int32_t get_count_2() const { return ___count_2; } inline int32_t* get_address_of_count_2() { return &___count_2; } inline void set_count_2(int32_t value) { ___count_2 = value; } inline static int32_t get_offset_of_version_3() { return static_cast<int32_t>(offsetof(Dictionary_2_tE268B8DA28D3A82319F0632A15D6EC06B68E5523, ___version_3)); } inline int32_t get_version_3() const { return ___version_3; } inline int32_t* get_address_of_version_3() { return &___version_3; } inline void set_version_3(int32_t value) { ___version_3 = value; } inline static int32_t get_offset_of_freeList_4() { return static_cast<int32_t>(offsetof(Dictionary_2_tE268B8DA28D3A82319F0632A15D6EC06B68E5523, ___freeList_4)); } inline int32_t get_freeList_4() const { return ___freeList_4; } inline int32_t* get_address_of_freeList_4() { return &___freeList_4; } inline void set_freeList_4(int32_t value) { ___freeList_4 = value; } inline static int32_t get_offset_of_freeCount_5() { return static_cast<int32_t>(offsetof(Dictionary_2_tE268B8DA28D3A82319F0632A15D6EC06B68E5523, ___freeCount_5)); } inline int32_t get_freeCount_5() const { return ___freeCount_5; } inline int32_t* get_address_of_freeCount_5() { return &___freeCount_5; } inline void set_freeCount_5(int32_t value) { ___freeCount_5 = value; } inline static int32_t get_offset_of_comparer_6() { return static_cast<int32_t>(offsetof(Dictionary_2_tE268B8DA28D3A82319F0632A15D6EC06B68E5523, ___comparer_6)); } inline RuntimeObject* get_comparer_6() const { return ___comparer_6; } inline RuntimeObject** get_address_of_comparer_6() { return &___comparer_6; } inline void set_comparer_6(RuntimeObject* value) { ___comparer_6 = value; Il2CppCodeGenWriteBarrier((void**)(&___comparer_6), (void*)value); } inline static int32_t get_offset_of_keys_7() { return static_cast<int32_t>(offsetof(Dictionary_2_tE268B8DA28D3A82319F0632A15D6EC06B68E5523, ___keys_7)); } inline KeyCollection_tFCF38642F5CB0A86A6B4EC75E8BF5C9A8C4D0122 * get_keys_7() const { return ___keys_7; } inline KeyCollection_tFCF38642F5CB0A86A6B4EC75E8BF5C9A8C4D0122 ** get_address_of_keys_7() { return &___keys_7; } inline void set_keys_7(KeyCollection_tFCF38642F5CB0A86A6B4EC75E8BF5C9A8C4D0122 * value) { ___keys_7 = value; Il2CppCodeGenWriteBarrier((void**)(&___keys_7), (void*)value); } inline static int32_t get_offset_of_values_8() { return static_cast<int32_t>(offsetof(Dictionary_2_tE268B8DA28D3A82319F0632A15D6EC06B68E5523, ___values_8)); } inline ValueCollection_tECAE69F11CA0C245794C99313E46CEAB79289400 * get_values_8() const { return ___values_8; } inline ValueCollection_tECAE69F11CA0C245794C99313E46CEAB79289400 ** get_address_of_values_8() { return &___values_8; } inline void set_values_8(ValueCollection_tECAE69F11CA0C245794C99313E46CEAB79289400 * value) { ___values_8 = value; Il2CppCodeGenWriteBarrier((void**)(&___values_8), (void*)value); } inline static int32_t get_offset_of__syncRoot_9() { return static_cast<int32_t>(offsetof(Dictionary_2_tE268B8DA28D3A82319F0632A15D6EC06B68E5523, ____syncRoot_9)); } inline RuntimeObject * get__syncRoot_9() const { return ____syncRoot_9; } inline RuntimeObject ** get_address_of__syncRoot_9() { return &____syncRoot_9; } inline void set__syncRoot_9(RuntimeObject * value) { ____syncRoot_9 = value; Il2CppCodeGenWriteBarrier((void**)(&____syncRoot_9), (void*)value); } }; // System.Collections.Generic.Dictionary`2<System.Xml.XmlQualifiedName,System.Xml.XmlQualifiedName> struct Dictionary_2_t3EDC2BB9B056BB70DDD396DBE1C02C102C4258F2 : public RuntimeObject { public: // System.Int32[] System.Collections.Generic.Dictionary`2::buckets Int32U5BU5D_t70F1BDC14B1786481B176D6139A5E3B87DC54C32* ___buckets_0; // System.Collections.Generic.Dictionary`2/Entry<TKey,TValue>[] System.Collections.Generic.Dictionary`2::entries EntryU5BU5D_tA3DDC0B951DBF95A552959A08A07C10A84E89DA0* ___entries_1; // System.Int32 System.Collections.Generic.Dictionary`2::count int32_t ___count_2; // System.Int32 System.Collections.Generic.Dictionary`2::version int32_t ___version_3; // System.Int32 System.Collections.Generic.Dictionary`2::freeList int32_t ___freeList_4; // System.Int32 System.Collections.Generic.Dictionary`2::freeCount int32_t ___freeCount_5; // System.Collections.Generic.IEqualityComparer`1<TKey> System.Collections.Generic.Dictionary`2::comparer RuntimeObject* ___comparer_6; // System.Collections.Generic.Dictionary`2/KeyCollection<TKey,TValue> System.Collections.Generic.Dictionary`2::keys KeyCollection_t030E8C0717067BB35BC97531ADFD5B34DE81E372 * ___keys_7; // System.Collections.Generic.Dictionary`2/ValueCollection<TKey,TValue> System.Collections.Generic.Dictionary`2::values ValueCollection_t0A13A40E317C41D701F731B2E09A7863C1AF1C9E * ___values_8; // System.Object System.Collections.Generic.Dictionary`2::_syncRoot RuntimeObject * ____syncRoot_9; public: inline static int32_t get_offset_of_buckets_0() { return static_cast<int32_t>(offsetof(Dictionary_2_t3EDC2BB9B056BB70DDD396DBE1C02C102C4258F2, ___buckets_0)); } inline Int32U5BU5D_t70F1BDC14B1786481B176D6139A5E3B87DC54C32* get_buckets_0() const { return ___buckets_0; } inline Int32U5BU5D_t70F1BDC14B1786481B176D6139A5E3B87DC54C32** get_address_of_buckets_0() { return &___buckets_0; } inline void set_buckets_0(Int32U5BU5D_t70F1BDC14B1786481B176D6139A5E3B87DC54C32* value) { ___buckets_0 = value; Il2CppCodeGenWriteBarrier((void**)(&___buckets_0), (void*)value); } inline static int32_t get_offset_of_entries_1() { return static_cast<int32_t>(offsetof(Dictionary_2_t3EDC2BB9B056BB70DDD396DBE1C02C102C4258F2, ___entries_1)); } inline EntryU5BU5D_tA3DDC0B951DBF95A552959A08A07C10A84E89DA0* get_entries_1() const { return ___entries_1; } inline EntryU5BU5D_tA3DDC0B951DBF95A552959A08A07C10A84E89DA0** get_address_of_entries_1() { return &___entries_1; } inline void set_entries_1(EntryU5BU5D_tA3DDC0B951DBF95A552959A08A07C10A84E89DA0* value) { ___entries_1 = value; Il2CppCodeGenWriteBarrier((void**)(&___entries_1), (void*)value); } inline static int32_t get_offset_of_count_2() { return static_cast<int32_t>(offsetof(Dictionary_2_t3EDC2BB9B056BB70DDD396DBE1C02C102C4258F2, ___count_2)); } inline int32_t get_count_2() const { return ___count_2; } inline int32_t* get_address_of_count_2() { return &___count_2; } inline void set_count_2(int32_t value) { ___count_2 = value; } inline static int32_t get_offset_of_version_3() { return static_cast<int32_t>(offsetof(Dictionary_2_t3EDC2BB9B056BB70DDD396DBE1C02C102C4258F2, ___version_3)); } inline int32_t get_version_3() const { return ___version_3; } inline int32_t* get_address_of_version_3() { return &___version_3; } inline void set_version_3(int32_t value) { ___version_3 = value; } inline static int32_t get_offset_of_freeList_4() { return static_cast<int32_t>(offsetof(Dictionary_2_t3EDC2BB9B056BB70DDD396DBE1C02C102C4258F2, ___freeList_4)); } inline int32_t get_freeList_4() const { return ___freeList_4; } inline int32_t* get_address_of_freeList_4() { return &___freeList_4; } inline void set_freeList_4(int32_t value) { ___freeList_4 = value; } inline static int32_t get_offset_of_freeCount_5() { return static_cast<int32_t>(offsetof(Dictionary_2_t3EDC2BB9B056BB70DDD396DBE1C02C102C4258F2, ___freeCount_5)); } inline int32_t get_freeCount_5() const { return ___freeCount_5; } inline int32_t* get_address_of_freeCount_5() { return &___freeCount_5; } inline void set_freeCount_5(int32_t value) { ___freeCount_5 = value; } inline static int32_t get_offset_of_comparer_6() { return static_cast<int32_t>(offsetof(Dictionary_2_t3EDC2BB9B056BB70DDD396DBE1C02C102C4258F2, ___comparer_6)); } inline RuntimeObject* get_comparer_6() const { return ___comparer_6; } inline RuntimeObject** get_address_of_comparer_6() { return &___comparer_6; } inline void set_comparer_6(RuntimeObject* value) { ___comparer_6 = value; Il2CppCodeGenWriteBarrier((void**)(&___comparer_6), (void*)value); } inline static int32_t get_offset_of_keys_7() { return static_cast<int32_t>(offsetof(Dictionary_2_t3EDC2BB9B056BB70DDD396DBE1C02C102C4258F2, ___keys_7)); } inline KeyCollection_t030E8C0717067BB35BC97531ADFD5B34DE81E372 * get_keys_7() const { return ___keys_7; } inline KeyCollection_t030E8C0717067BB35BC97531ADFD5B34DE81E372 ** get_address_of_keys_7() { return &___keys_7; } inline void set_keys_7(KeyCollection_t030E8C0717067BB35BC97531ADFD5B34DE81E372 * value) { ___keys_7 = value; Il2CppCodeGenWriteBarrier((void**)(&___keys_7), (void*)value); } inline static int32_t get_offset_of_values_8() { return static_cast<int32_t>(offsetof(Dictionary_2_t3EDC2BB9B056BB70DDD396DBE1C02C102C4258F2, ___values_8)); } inline ValueCollection_t0A13A40E317C41D701F731B2E09A7863C1AF1C9E * get_values_8() const { return ___values_8; } inline ValueCollection_t0A13A40E317C41D701F731B2E09A7863C1AF1C9E ** get_address_of_values_8() { return &___values_8; } inline void set_values_8(ValueCollection_t0A13A40E317C41D701F731B2E09A7863C1AF1C9E * value) { ___values_8 = value; Il2CppCodeGenWriteBarrier((void**)(&___values_8), (void*)value); } inline static int32_t get_offset_of__syncRoot_9() { return static_cast<int32_t>(offsetof(Dictionary_2_t3EDC2BB9B056BB70DDD396DBE1C02C102C4258F2, ____syncRoot_9)); } inline RuntimeObject * get__syncRoot_9() const { return ____syncRoot_9; } inline RuntimeObject ** get_address_of__syncRoot_9() { return &____syncRoot_9; } inline void set__syncRoot_9(RuntimeObject * value) { ____syncRoot_9 = value; Il2CppCodeGenWriteBarrier((void**)(&____syncRoot_9), (void*)value); } }; #ifdef __clang__ #pragma clang diagnostic pop #endif il2cpp_hresult_t IBindableIterable_First_m91EC6ED0173145266318FDB7F9074798CD766BD7_ComCallableWrapperProjectedMethod(RuntimeObject* __this, IBindableIterator_tD7550F1144CFBE58090050457A2BE92B1CAEABBB** comReturnValue); // COM Callable Wrapper for System.Collections.Generic.Dictionary`2<WindTurbineScriptableObject,UnityEngine.GameObject> struct Dictionary_2_tBB6637D6ACE122CA21B1AAFE00D9DB6FB0DE4B8F_ComCallableWrapper IL2CPP_FINAL : il2cpp::vm::CachedCCWBase<Dictionary_2_tBB6637D6ACE122CA21B1AAFE00D9DB6FB0DE4B8F_ComCallableWrapper>, IBindableIterable_tF6BD0C070562CD9C91E3C1B1A5F4667E9C3C74A8 { inline Dictionary_2_tBB6637D6ACE122CA21B1AAFE00D9DB6FB0DE4B8F_ComCallableWrapper(RuntimeObject* obj) : il2cpp::vm::CachedCCWBase<Dictionary_2_tBB6637D6ACE122CA21B1AAFE00D9DB6FB0DE4B8F_ComCallableWrapper>(obj) {} virtual il2cpp_hresult_t STDCALL QueryInterface(const Il2CppGuid& iid, void** object) IL2CPP_OVERRIDE { if (::memcmp(&iid, &Il2CppIUnknown::IID, sizeof(Il2CppGuid)) == 0 || ::memcmp(&iid, &Il2CppIInspectable::IID, sizeof(Il2CppGuid)) == 0 || ::memcmp(&iid, &Il2CppIAgileObject::IID, sizeof(Il2CppGuid)) == 0) { *object = GetIdentity(); AddRefImpl(); return IL2CPP_S_OK; } if (::memcmp(&iid, &Il2CppIManagedObjectHolder::IID, sizeof(Il2CppGuid)) == 0) { *object = static_cast<Il2CppIManagedObjectHolder*>(this); AddRefImpl(); return IL2CPP_S_OK; } if (::memcmp(&iid, &IBindableIterable_tF6BD0C070562CD9C91E3C1B1A5F4667E9C3C74A8::IID, sizeof(Il2CppGuid)) == 0) { *object = static_cast<IBindableIterable_tF6BD0C070562CD9C91E3C1B1A5F4667E9C3C74A8*>(this); AddRefImpl(); return IL2CPP_S_OK; } if (::memcmp(&iid, &Il2CppIMarshal::IID, sizeof(Il2CppGuid)) == 0) { *object = static_cast<Il2CppIMarshal*>(this); AddRefImpl(); return IL2CPP_S_OK; } if (::memcmp(&iid, &Il2CppIWeakReferenceSource::IID, sizeof(Il2CppGuid)) == 0) { *object = static_cast<Il2CppIWeakReferenceSource*>(this); AddRefImpl(); return IL2CPP_S_OK; } *object = NULL; return IL2CPP_E_NOINTERFACE; } virtual uint32_t STDCALL AddRef() IL2CPP_OVERRIDE { return AddRefImpl(); } virtual uint32_t STDCALL Release() IL2CPP_OVERRIDE { return ReleaseImpl(); } virtual il2cpp_hresult_t STDCALL GetIids(uint32_t* iidCount, Il2CppGuid** iids) IL2CPP_OVERRIDE { Il2CppGuid* interfaceIds = il2cpp_codegen_marshal_allocate_array<Il2CppGuid>(1); interfaceIds[0] = IBindableIterable_tF6BD0C070562CD9C91E3C1B1A5F4667E9C3C74A8::IID; *iidCount = 1; *iids = interfaceIds; return IL2CPP_S_OK; } virtual il2cpp_hresult_t STDCALL GetRuntimeClassName(Il2CppHString* className) IL2CPP_OVERRIDE { return GetRuntimeClassNameImpl(className); } virtual il2cpp_hresult_t STDCALL GetTrustLevel(int32_t* trustLevel) IL2CPP_OVERRIDE { return ComObjectBase::GetTrustLevel(trustLevel); } virtual il2cpp_hresult_t STDCALL IBindableIterable_First_m91EC6ED0173145266318FDB7F9074798CD766BD7(IBindableIterator_tD7550F1144CFBE58090050457A2BE92B1CAEABBB** comReturnValue) IL2CPP_OVERRIDE { return IBindableIterable_First_m91EC6ED0173145266318FDB7F9074798CD766BD7_ComCallableWrapperProjectedMethod(GetManagedObjectInline(), comReturnValue); } }; IL2CPP_EXTERN_C Il2CppIUnknown* CreateComCallableWrapperFor_Dictionary_2_tBB6637D6ACE122CA21B1AAFE00D9DB6FB0DE4B8F(RuntimeObject* obj) { void* memory = il2cpp::utils::Memory::Malloc(sizeof(Dictionary_2_tBB6637D6ACE122CA21B1AAFE00D9DB6FB0DE4B8F_ComCallableWrapper)); if (memory == NULL) { il2cpp_codegen_raise_out_of_memory_exception(); } return static_cast<Il2CppIManagedObjectHolder*>(new(memory) Dictionary_2_tBB6637D6ACE122CA21B1AAFE00D9DB6FB0DE4B8F_ComCallableWrapper(obj)); } // COM Callable Wrapper for System.Collections.Generic.Dictionary`2<WindTurbineScriptableObject,SiteOverviewTurbineButton> struct Dictionary_2_t0541E6A56BBB9D3DAB2CCF3BA250073328DF2F85_ComCallableWrapper IL2CPP_FINAL : il2cpp::vm::CachedCCWBase<Dictionary_2_t0541E6A56BBB9D3DAB2CCF3BA250073328DF2F85_ComCallableWrapper>, IBindableIterable_tF6BD0C070562CD9C91E3C1B1A5F4667E9C3C74A8 { inline Dictionary_2_t0541E6A56BBB9D3DAB2CCF3BA250073328DF2F85_ComCallableWrapper(RuntimeObject* obj) : il2cpp::vm::CachedCCWBase<Dictionary_2_t0541E6A56BBB9D3DAB2CCF3BA250073328DF2F85_ComCallableWrapper>(obj) {} virtual il2cpp_hresult_t STDCALL QueryInterface(const Il2CppGuid& iid, void** object) IL2CPP_OVERRIDE { if (::memcmp(&iid, &Il2CppIUnknown::IID, sizeof(Il2CppGuid)) == 0 || ::memcmp(&iid, &Il2CppIInspectable::IID, sizeof(Il2CppGuid)) == 0 || ::memcmp(&iid, &Il2CppIAgileObject::IID, sizeof(Il2CppGuid)) == 0) { *object = GetIdentity(); AddRefImpl(); return IL2CPP_S_OK; } if (::memcmp(&iid, &Il2CppIManagedObjectHolder::IID, sizeof(Il2CppGuid)) == 0) { *object = static_cast<Il2CppIManagedObjectHolder*>(this); AddRefImpl(); return IL2CPP_S_OK; } if (::memcmp(&iid, &IBindableIterable_tF6BD0C070562CD9C91E3C1B1A5F4667E9C3C74A8::IID, sizeof(Il2CppGuid)) == 0) { *object = static_cast<IBindableIterable_tF6BD0C070562CD9C91E3C1B1A5F4667E9C3C74A8*>(this); AddRefImpl(); return IL2CPP_S_OK; } if (::memcmp(&iid, &Il2CppIMarshal::IID, sizeof(Il2CppGuid)) == 0) { *object = static_cast<Il2CppIMarshal*>(this); AddRefImpl(); return IL2CPP_S_OK; } if (::memcmp(&iid, &Il2CppIWeakReferenceSource::IID, sizeof(Il2CppGuid)) == 0) { *object = static_cast<Il2CppIWeakReferenceSource*>(this); AddRefImpl(); return IL2CPP_S_OK; } *object = NULL; return IL2CPP_E_NOINTERFACE; } virtual uint32_t STDCALL AddRef() IL2CPP_OVERRIDE { return AddRefImpl(); } virtual uint32_t STDCALL Release() IL2CPP_OVERRIDE { return ReleaseImpl(); } virtual il2cpp_hresult_t STDCALL GetIids(uint32_t* iidCount, Il2CppGuid** iids) IL2CPP_OVERRIDE { Il2CppGuid* interfaceIds = il2cpp_codegen_marshal_allocate_array<Il2CppGuid>(1); interfaceIds[0] = IBindableIterable_tF6BD0C070562CD9C91E3C1B1A5F4667E9C3C74A8::IID; *iidCount = 1; *iids = interfaceIds; return IL2CPP_S_OK; } virtual il2cpp_hresult_t STDCALL GetRuntimeClassName(Il2CppHString* className) IL2CPP_OVERRIDE { return GetRuntimeClassNameImpl(className); } virtual il2cpp_hresult_t STDCALL GetTrustLevel(int32_t* trustLevel) IL2CPP_OVERRIDE { return ComObjectBase::GetTrustLevel(trustLevel); } virtual il2cpp_hresult_t STDCALL IBindableIterable_First_m91EC6ED0173145266318FDB7F9074798CD766BD7(IBindableIterator_tD7550F1144CFBE58090050457A2BE92B1CAEABBB** comReturnValue) IL2CPP_OVERRIDE { return IBindableIterable_First_m91EC6ED0173145266318FDB7F9074798CD766BD7_ComCallableWrapperProjectedMethod(GetManagedObjectInline(), comReturnValue); } }; IL2CPP_EXTERN_C Il2CppIUnknown* CreateComCallableWrapperFor_Dictionary_2_t0541E6A56BBB9D3DAB2CCF3BA250073328DF2F85(RuntimeObject* obj) { void* memory = il2cpp::utils::Memory::Malloc(sizeof(Dictionary_2_t0541E6A56BBB9D3DAB2CCF3BA250073328DF2F85_ComCallableWrapper)); if (memory == NULL) { il2cpp_codegen_raise_out_of_memory_exception(); } return static_cast<Il2CppIManagedObjectHolder*>(new(memory) Dictionary_2_t0541E6A56BBB9D3DAB2CCF3BA250073328DF2F85_ComCallableWrapper(obj)); } // COM Callable Wrapper for System.Collections.Generic.Dictionary`2<System.Xml.XmlQualifiedName,System.Int32> struct Dictionary_2_t9271D5E45EC14905F5999D37CAEA9320F5D0A5F6_ComCallableWrapper IL2CPP_FINAL : il2cpp::vm::CachedCCWBase<Dictionary_2_t9271D5E45EC14905F5999D37CAEA9320F5D0A5F6_ComCallableWrapper>, IBindableIterable_tF6BD0C070562CD9C91E3C1B1A5F4667E9C3C74A8 { inline Dictionary_2_t9271D5E45EC14905F5999D37CAEA9320F5D0A5F6_ComCallableWrapper(RuntimeObject* obj) : il2cpp::vm::CachedCCWBase<Dictionary_2_t9271D5E45EC14905F5999D37CAEA9320F5D0A5F6_ComCallableWrapper>(obj) {} virtual il2cpp_hresult_t STDCALL QueryInterface(const Il2CppGuid& iid, void** object) IL2CPP_OVERRIDE { if (::memcmp(&iid, &Il2CppIUnknown::IID, sizeof(Il2CppGuid)) == 0 || ::memcmp(&iid, &Il2CppIInspectable::IID, sizeof(Il2CppGuid)) == 0 || ::memcmp(&iid, &Il2CppIAgileObject::IID, sizeof(Il2CppGuid)) == 0) { *object = GetIdentity(); AddRefImpl(); return IL2CPP_S_OK; } if (::memcmp(&iid, &Il2CppIManagedObjectHolder::IID, sizeof(Il2CppGuid)) == 0) { *object = static_cast<Il2CppIManagedObjectHolder*>(this); AddRefImpl(); return IL2CPP_S_OK; } if (::memcmp(&iid, &IBindableIterable_tF6BD0C070562CD9C91E3C1B1A5F4667E9C3C74A8::IID, sizeof(Il2CppGuid)) == 0) { *object = static_cast<IBindableIterable_tF6BD0C070562CD9C91E3C1B1A5F4667E9C3C74A8*>(this); AddRefImpl(); return IL2CPP_S_OK; } if (::memcmp(&iid, &Il2CppIMarshal::IID, sizeof(Il2CppGuid)) == 0) { *object = static_cast<Il2CppIMarshal*>(this); AddRefImpl(); return IL2CPP_S_OK; } if (::memcmp(&iid, &Il2CppIWeakReferenceSource::IID, sizeof(Il2CppGuid)) == 0) { *object = static_cast<Il2CppIWeakReferenceSource*>(this); AddRefImpl(); return IL2CPP_S_OK; } *object = NULL; return IL2CPP_E_NOINTERFACE; } virtual uint32_t STDCALL AddRef() IL2CPP_OVERRIDE { return AddRefImpl(); } virtual uint32_t STDCALL Release() IL2CPP_OVERRIDE { return ReleaseImpl(); } virtual il2cpp_hresult_t STDCALL GetIids(uint32_t* iidCount, Il2CppGuid** iids) IL2CPP_OVERRIDE { Il2CppGuid* interfaceIds = il2cpp_codegen_marshal_allocate_array<Il2CppGuid>(1); interfaceIds[0] = IBindableIterable_tF6BD0C070562CD9C91E3C1B1A5F4667E9C3C74A8::IID; *iidCount = 1; *iids = interfaceIds; return IL2CPP_S_OK; } virtual il2cpp_hresult_t STDCALL GetRuntimeClassName(Il2CppHString* className) IL2CPP_OVERRIDE { return GetRuntimeClassNameImpl(className); } virtual il2cpp_hresult_t STDCALL GetTrustLevel(int32_t* trustLevel) IL2CPP_OVERRIDE { return ComObjectBase::GetTrustLevel(trustLevel); } virtual il2cpp_hresult_t STDCALL IBindableIterable_First_m91EC6ED0173145266318FDB7F9074798CD766BD7(IBindableIterator_tD7550F1144CFBE58090050457A2BE92B1CAEABBB** comReturnValue) IL2CPP_OVERRIDE { return IBindableIterable_First_m91EC6ED0173145266318FDB7F9074798CD766BD7_ComCallableWrapperProjectedMethod(GetManagedObjectInline(), comReturnValue); } }; IL2CPP_EXTERN_C Il2CppIUnknown* CreateComCallableWrapperFor_Dictionary_2_t9271D5E45EC14905F5999D37CAEA9320F5D0A5F6(RuntimeObject* obj) { void* memory = il2cpp::utils::Memory::Malloc(sizeof(Dictionary_2_t9271D5E45EC14905F5999D37CAEA9320F5D0A5F6_ComCallableWrapper)); if (memory == NULL) { il2cpp_codegen_raise_out_of_memory_exception(); } return static_cast<Il2CppIManagedObjectHolder*>(new(memory) Dictionary_2_t9271D5E45EC14905F5999D37CAEA9320F5D0A5F6_ComCallableWrapper(obj)); } // COM Callable Wrapper for System.Collections.Generic.Dictionary`2<System.Xml.XmlQualifiedName,System.Xml.Schema.SchemaAttDef> struct Dictionary_2_t1FAD0C7CC6F970A1F41D0F7433B8D62A408D1C58_ComCallableWrapper IL2CPP_FINAL : il2cpp::vm::CachedCCWBase<Dictionary_2_t1FAD0C7CC6F970A1F41D0F7433B8D62A408D1C58_ComCallableWrapper>, IBindableIterable_tF6BD0C070562CD9C91E3C1B1A5F4667E9C3C74A8 { inline Dictionary_2_t1FAD0C7CC6F970A1F41D0F7433B8D62A408D1C58_ComCallableWrapper(RuntimeObject* obj) : il2cpp::vm::CachedCCWBase<Dictionary_2_t1FAD0C7CC6F970A1F41D0F7433B8D62A408D1C58_ComCallableWrapper>(obj) {} virtual il2cpp_hresult_t STDCALL QueryInterface(const Il2CppGuid& iid, void** object) IL2CPP_OVERRIDE { if (::memcmp(&iid, &Il2CppIUnknown::IID, sizeof(Il2CppGuid)) == 0 || ::memcmp(&iid, &Il2CppIInspectable::IID, sizeof(Il2CppGuid)) == 0 || ::memcmp(&iid, &Il2CppIAgileObject::IID, sizeof(Il2CppGuid)) == 0) { *object = GetIdentity(); AddRefImpl(); return IL2CPP_S_OK; } if (::memcmp(&iid, &Il2CppIManagedObjectHolder::IID, sizeof(Il2CppGuid)) == 0) { *object = static_cast<Il2CppIManagedObjectHolder*>(this); AddRefImpl(); return IL2CPP_S_OK; } if (::memcmp(&iid, &IBindableIterable_tF6BD0C070562CD9C91E3C1B1A5F4667E9C3C74A8::IID, sizeof(Il2CppGuid)) == 0) { *object = static_cast<IBindableIterable_tF6BD0C070562CD9C91E3C1B1A5F4667E9C3C74A8*>(this); AddRefImpl(); return IL2CPP_S_OK; } if (::memcmp(&iid, &Il2CppIMarshal::IID, sizeof(Il2CppGuid)) == 0) { *object = static_cast<Il2CppIMarshal*>(this); AddRefImpl(); return IL2CPP_S_OK; } if (::memcmp(&iid, &Il2CppIWeakReferenceSource::IID, sizeof(Il2CppGuid)) == 0) { *object = static_cast<Il2CppIWeakReferenceSource*>(this); AddRefImpl(); return IL2CPP_S_OK; } *object = NULL; return IL2CPP_E_NOINTERFACE; } virtual uint32_t STDCALL AddRef() IL2CPP_OVERRIDE { return AddRefImpl(); } virtual uint32_t STDCALL Release() IL2CPP_OVERRIDE { return ReleaseImpl(); } virtual il2cpp_hresult_t STDCALL GetIids(uint32_t* iidCount, Il2CppGuid** iids) IL2CPP_OVERRIDE { Il2CppGuid* interfaceIds = il2cpp_codegen_marshal_allocate_array<Il2CppGuid>(1); interfaceIds[0] = IBindableIterable_tF6BD0C070562CD9C91E3C1B1A5F4667E9C3C74A8::IID; *iidCount = 1; *iids = interfaceIds; return IL2CPP_S_OK; } virtual il2cpp_hresult_t STDCALL GetRuntimeClassName(Il2CppHString* className) IL2CPP_OVERRIDE { return GetRuntimeClassNameImpl(className); } virtual il2cpp_hresult_t STDCALL GetTrustLevel(int32_t* trustLevel) IL2CPP_OVERRIDE { return ComObjectBase::GetTrustLevel(trustLevel); } virtual il2cpp_hresult_t STDCALL IBindableIterable_First_m91EC6ED0173145266318FDB7F9074798CD766BD7(IBindableIterator_tD7550F1144CFBE58090050457A2BE92B1CAEABBB** comReturnValue) IL2CPP_OVERRIDE { return IBindableIterable_First_m91EC6ED0173145266318FDB7F9074798CD766BD7_ComCallableWrapperProjectedMethod(GetManagedObjectInline(), comReturnValue); } }; IL2CPP_EXTERN_C Il2CppIUnknown* CreateComCallableWrapperFor_Dictionary_2_t1FAD0C7CC6F970A1F41D0F7433B8D62A408D1C58(RuntimeObject* obj) { void* memory = il2cpp::utils::Memory::Malloc(sizeof(Dictionary_2_t1FAD0C7CC6F970A1F41D0F7433B8D62A408D1C58_ComCallableWrapper)); if (memory == NULL) { il2cpp_codegen_raise_out_of_memory_exception(); } return static_cast<Il2CppIManagedObjectHolder*>(new(memory) Dictionary_2_t1FAD0C7CC6F970A1F41D0F7433B8D62A408D1C58_ComCallableWrapper(obj)); } // COM Callable Wrapper for System.Collections.Generic.Dictionary`2<System.Xml.XmlQualifiedName,System.Xml.Schema.SchemaElementDecl> struct Dictionary_2_t9716CEDD4260B2B68461B83D64B387A3786A25C7_ComCallableWrapper IL2CPP_FINAL : il2cpp::vm::CachedCCWBase<Dictionary_2_t9716CEDD4260B2B68461B83D64B387A3786A25C7_ComCallableWrapper>, IBindableIterable_tF6BD0C070562CD9C91E3C1B1A5F4667E9C3C74A8 { inline Dictionary_2_t9716CEDD4260B2B68461B83D64B387A3786A25C7_ComCallableWrapper(RuntimeObject* obj) : il2cpp::vm::CachedCCWBase<Dictionary_2_t9716CEDD4260B2B68461B83D64B387A3786A25C7_ComCallableWrapper>(obj) {} virtual il2cpp_hresult_t STDCALL QueryInterface(const Il2CppGuid& iid, void** object) IL2CPP_OVERRIDE { if (::memcmp(&iid, &Il2CppIUnknown::IID, sizeof(Il2CppGuid)) == 0 || ::memcmp(&iid, &Il2CppIInspectable::IID, sizeof(Il2CppGuid)) == 0 || ::memcmp(&iid, &Il2CppIAgileObject::IID, sizeof(Il2CppGuid)) == 0) { *object = GetIdentity(); AddRefImpl(); return IL2CPP_S_OK; } if (::memcmp(&iid, &Il2CppIManagedObjectHolder::IID, sizeof(Il2CppGuid)) == 0) { *object = static_cast<Il2CppIManagedObjectHolder*>(this); AddRefImpl(); return IL2CPP_S_OK; } if (::memcmp(&iid, &IBindableIterable_tF6BD0C070562CD9C91E3C1B1A5F4667E9C3C74A8::IID, sizeof(Il2CppGuid)) == 0) { *object = static_cast<IBindableIterable_tF6BD0C070562CD9C91E3C1B1A5F4667E9C3C74A8*>(this); AddRefImpl(); return IL2CPP_S_OK; } if (::memcmp(&iid, &Il2CppIMarshal::IID, sizeof(Il2CppGuid)) == 0) { *object = static_cast<Il2CppIMarshal*>(this); AddRefImpl(); return IL2CPP_S_OK; } if (::memcmp(&iid, &Il2CppIWeakReferenceSource::IID, sizeof(Il2CppGuid)) == 0) { *object = static_cast<Il2CppIWeakReferenceSource*>(this); AddRefImpl(); return IL2CPP_S_OK; } *object = NULL; return IL2CPP_E_NOINTERFACE; } virtual uint32_t STDCALL AddRef() IL2CPP_OVERRIDE { return AddRefImpl(); } virtual uint32_t STDCALL Release() IL2CPP_OVERRIDE { return ReleaseImpl(); } virtual il2cpp_hresult_t STDCALL GetIids(uint32_t* iidCount, Il2CppGuid** iids) IL2CPP_OVERRIDE { Il2CppGuid* interfaceIds = il2cpp_codegen_marshal_allocate_array<Il2CppGuid>(1); interfaceIds[0] = IBindableIterable_tF6BD0C070562CD9C91E3C1B1A5F4667E9C3C74A8::IID; *iidCount = 1; *iids = interfaceIds; return IL2CPP_S_OK; } virtual il2cpp_hresult_t STDCALL GetRuntimeClassName(Il2CppHString* className) IL2CPP_OVERRIDE { return GetRuntimeClassNameImpl(className); } virtual il2cpp_hresult_t STDCALL GetTrustLevel(int32_t* trustLevel) IL2CPP_OVERRIDE { return ComObjectBase::GetTrustLevel(trustLevel); } virtual il2cpp_hresult_t STDCALL IBindableIterable_First_m91EC6ED0173145266318FDB7F9074798CD766BD7(IBindableIterator_tD7550F1144CFBE58090050457A2BE92B1CAEABBB** comReturnValue) IL2CPP_OVERRIDE { return IBindableIterable_First_m91EC6ED0173145266318FDB7F9074798CD766BD7_ComCallableWrapperProjectedMethod(GetManagedObjectInline(), comReturnValue); } }; IL2CPP_EXTERN_C Il2CppIUnknown* CreateComCallableWrapperFor_Dictionary_2_t9716CEDD4260B2B68461B83D64B387A3786A25C7(RuntimeObject* obj) { void* memory = il2cpp::utils::Memory::Malloc(sizeof(Dictionary_2_t9716CEDD4260B2B68461B83D64B387A3786A25C7_ComCallableWrapper)); if (memory == NULL) { il2cpp_codegen_raise_out_of_memory_exception(); } return static_cast<Il2CppIManagedObjectHolder*>(new(memory) Dictionary_2_t9716CEDD4260B2B68461B83D64B387A3786A25C7_ComCallableWrapper(obj)); } // COM Callable Wrapper for System.Collections.Generic.Dictionary`2<System.Xml.XmlQualifiedName,System.Xml.Schema.SchemaEntity> struct Dictionary_2_tE268B8DA28D3A82319F0632A15D6EC06B68E5523_ComCallableWrapper IL2CPP_FINAL : il2cpp::vm::CachedCCWBase<Dictionary_2_tE268B8DA28D3A82319F0632A15D6EC06B68E5523_ComCallableWrapper>, IBindableIterable_tF6BD0C070562CD9C91E3C1B1A5F4667E9C3C74A8 { inline Dictionary_2_tE268B8DA28D3A82319F0632A15D6EC06B68E5523_ComCallableWrapper(RuntimeObject* obj) : il2cpp::vm::CachedCCWBase<Dictionary_2_tE268B8DA28D3A82319F0632A15D6EC06B68E5523_ComCallableWrapper>(obj) {} virtual il2cpp_hresult_t STDCALL QueryInterface(const Il2CppGuid& iid, void** object) IL2CPP_OVERRIDE { if (::memcmp(&iid, &Il2CppIUnknown::IID, sizeof(Il2CppGuid)) == 0 || ::memcmp(&iid, &Il2CppIInspectable::IID, sizeof(Il2CppGuid)) == 0 || ::memcmp(&iid, &Il2CppIAgileObject::IID, sizeof(Il2CppGuid)) == 0) { *object = GetIdentity(); AddRefImpl(); return IL2CPP_S_OK; } if (::memcmp(&iid, &Il2CppIManagedObjectHolder::IID, sizeof(Il2CppGuid)) == 0) { *object = static_cast<Il2CppIManagedObjectHolder*>(this); AddRefImpl(); return IL2CPP_S_OK; } if (::memcmp(&iid, &IBindableIterable_tF6BD0C070562CD9C91E3C1B1A5F4667E9C3C74A8::IID, sizeof(Il2CppGuid)) == 0) { *object = static_cast<IBindableIterable_tF6BD0C070562CD9C91E3C1B1A5F4667E9C3C74A8*>(this); AddRefImpl(); return IL2CPP_S_OK; } if (::memcmp(&iid, &Il2CppIMarshal::IID, sizeof(Il2CppGuid)) == 0) { *object = static_cast<Il2CppIMarshal*>(this); AddRefImpl(); return IL2CPP_S_OK; } if (::memcmp(&iid, &Il2CppIWeakReferenceSource::IID, sizeof(Il2CppGuid)) == 0) { *object = static_cast<Il2CppIWeakReferenceSource*>(this); AddRefImpl(); return IL2CPP_S_OK; } *object = NULL; return IL2CPP_E_NOINTERFACE; } virtual uint32_t STDCALL AddRef() IL2CPP_OVERRIDE { return AddRefImpl(); } virtual uint32_t STDCALL Release() IL2CPP_OVERRIDE { return ReleaseImpl(); } virtual il2cpp_hresult_t STDCALL GetIids(uint32_t* iidCount, Il2CppGuid** iids) IL2CPP_OVERRIDE { Il2CppGuid* interfaceIds = il2cpp_codegen_marshal_allocate_array<Il2CppGuid>(1); interfaceIds[0] = IBindableIterable_tF6BD0C070562CD9C91E3C1B1A5F4667E9C3C74A8::IID; *iidCount = 1; *iids = interfaceIds; return IL2CPP_S_OK; } virtual il2cpp_hresult_t STDCALL GetRuntimeClassName(Il2CppHString* className) IL2CPP_OVERRIDE { return GetRuntimeClassNameImpl(className); } virtual il2cpp_hresult_t STDCALL GetTrustLevel(int32_t* trustLevel) IL2CPP_OVERRIDE { return ComObjectBase::GetTrustLevel(trustLevel); } virtual il2cpp_hresult_t STDCALL IBindableIterable_First_m91EC6ED0173145266318FDB7F9074798CD766BD7(IBindableIterator_tD7550F1144CFBE58090050457A2BE92B1CAEABBB** comReturnValue) IL2CPP_OVERRIDE { return IBindableIterable_First_m91EC6ED0173145266318FDB7F9074798CD766BD7_ComCallableWrapperProjectedMethod(GetManagedObjectInline(), comReturnValue); } }; IL2CPP_EXTERN_C Il2CppIUnknown* CreateComCallableWrapperFor_Dictionary_2_tE268B8DA28D3A82319F0632A15D6EC06B68E5523(RuntimeObject* obj) { void* memory = il2cpp::utils::Memory::Malloc(sizeof(Dictionary_2_tE268B8DA28D3A82319F0632A15D6EC06B68E5523_ComCallableWrapper)); if (memory == NULL) { il2cpp_codegen_raise_out_of_memory_exception(); } return static_cast<Il2CppIManagedObjectHolder*>(new(memory) Dictionary_2_tE268B8DA28D3A82319F0632A15D6EC06B68E5523_ComCallableWrapper(obj)); } // COM Callable Wrapper for System.Collections.Generic.Dictionary`2<System.Xml.XmlQualifiedName,System.Xml.XmlQualifiedName> struct Dictionary_2_t3EDC2BB9B056BB70DDD396DBE1C02C102C4258F2_ComCallableWrapper IL2CPP_FINAL : il2cpp::vm::CachedCCWBase<Dictionary_2_t3EDC2BB9B056BB70DDD396DBE1C02C102C4258F2_ComCallableWrapper>, IBindableIterable_tF6BD0C070562CD9C91E3C1B1A5F4667E9C3C74A8 { inline Dictionary_2_t3EDC2BB9B056BB70DDD396DBE1C02C102C4258F2_ComCallableWrapper(RuntimeObject* obj) : il2cpp::vm::CachedCCWBase<Dictionary_2_t3EDC2BB9B056BB70DDD396DBE1C02C102C4258F2_ComCallableWrapper>(obj) {} virtual il2cpp_hresult_t STDCALL QueryInterface(const Il2CppGuid& iid, void** object) IL2CPP_OVERRIDE { if (::memcmp(&iid, &Il2CppIUnknown::IID, sizeof(Il2CppGuid)) == 0 || ::memcmp(&iid, &Il2CppIInspectable::IID, sizeof(Il2CppGuid)) == 0 || ::memcmp(&iid, &Il2CppIAgileObject::IID, sizeof(Il2CppGuid)) == 0) { *object = GetIdentity(); AddRefImpl(); return IL2CPP_S_OK; } if (::memcmp(&iid, &Il2CppIManagedObjectHolder::IID, sizeof(Il2CppGuid)) == 0) { *object = static_cast<Il2CppIManagedObjectHolder*>(this); AddRefImpl(); return IL2CPP_S_OK; } if (::memcmp(&iid, &IBindableIterable_tF6BD0C070562CD9C91E3C1B1A5F4667E9C3C74A8::IID, sizeof(Il2CppGuid)) == 0) { *object = static_cast<IBindableIterable_tF6BD0C070562CD9C91E3C1B1A5F4667E9C3C74A8*>(this); AddRefImpl(); return IL2CPP_S_OK; } if (::memcmp(&iid, &Il2CppIMarshal::IID, sizeof(Il2CppGuid)) == 0) { *object = static_cast<Il2CppIMarshal*>(this); AddRefImpl(); return IL2CPP_S_OK; } if (::memcmp(&iid, &Il2CppIWeakReferenceSource::IID, sizeof(Il2CppGuid)) == 0) { *object = static_cast<Il2CppIWeakReferenceSource*>(this); AddRefImpl(); return IL2CPP_S_OK; } *object = NULL; return IL2CPP_E_NOINTERFACE; } virtual uint32_t STDCALL AddRef() IL2CPP_OVERRIDE { return AddRefImpl(); } virtual uint32_t STDCALL Release() IL2CPP_OVERRIDE { return ReleaseImpl(); } virtual il2cpp_hresult_t STDCALL GetIids(uint32_t* iidCount, Il2CppGuid** iids) IL2CPP_OVERRIDE { Il2CppGuid* interfaceIds = il2cpp_codegen_marshal_allocate_array<Il2CppGuid>(1); interfaceIds[0] = IBindableIterable_tF6BD0C070562CD9C91E3C1B1A5F4667E9C3C74A8::IID; *iidCount = 1; *iids = interfaceIds; return IL2CPP_S_OK; } virtual il2cpp_hresult_t STDCALL GetRuntimeClassName(Il2CppHString* className) IL2CPP_OVERRIDE { return GetRuntimeClassNameImpl(className); } virtual il2cpp_hresult_t STDCALL GetTrustLevel(int32_t* trustLevel) IL2CPP_OVERRIDE { return ComObjectBase::GetTrustLevel(trustLevel); } virtual il2cpp_hresult_t STDCALL IBindableIterable_First_m91EC6ED0173145266318FDB7F9074798CD766BD7(IBindableIterator_tD7550F1144CFBE58090050457A2BE92B1CAEABBB** comReturnValue) IL2CPP_OVERRIDE { return IBindableIterable_First_m91EC6ED0173145266318FDB7F9074798CD766BD7_ComCallableWrapperProjectedMethod(GetManagedObjectInline(), comReturnValue); } }; IL2CPP_EXTERN_C Il2CppIUnknown* CreateComCallableWrapperFor_Dictionary_2_t3EDC2BB9B056BB70DDD396DBE1C02C102C4258F2(RuntimeObject* obj) { void* memory = il2cpp::utils::Memory::Malloc(sizeof(Dictionary_2_t3EDC2BB9B056BB70DDD396DBE1C02C102C4258F2_ComCallableWrapper)); if (memory == NULL) { il2cpp_codegen_raise_out_of_memory_exception(); } return static_cast<Il2CppIManagedObjectHolder*>(new(memory) Dictionary_2_t3EDC2BB9B056BB70DDD396DBE1C02C102C4258F2_ComCallableWrapper(obj)); }
73,265
35,860
#include <bits/stdc++.h> using namespace std; std::mt19937 rng(int(std::chrono::steady_clock::now().time_since_epoch().count())); int main() { std::ios_base::sync_with_stdio(0); std::cin.tie(0); std::cout.tie(0); int t; cin >> t; for (int test = 1; test <= t; test += 1) { int n; cin >> n; string s; cin >> s; vector< int > sum(n + 5); sum[0] = 0; for (int i = 0; i < n; i += 1) { sum[i + 1] = sum[i] + (s[i] - '0'); } int size = (n + 1) / 2; int ans = 0; for (int i = size; i <= n; i += 1) { ans = max(ans, sum[i] - sum[i - size]); } cout << "Case #" << test << ": " << ans << '\n'; } return 0; }
679
315
#include <iostream> //#include "Solution1.h" #include "Solution2.h" void test(string s1, string s2) { Solution solution; cout << solution.canConstruct(s1, s2) << endl; } int main() { test("a", "b"); // 0 test("aa", "ab"); // 0 test("aa", "aab"); // 1 return 0; }
277
119
//ライブラリ読み込み #include <Arduino.h> #include <DSR1202.h> #include <U8g2lib.h> //ライブラリセットアップ DSR1202 dsr1202(1); //AQM1248Aは128 * 48 U8G2_ST7565_AK_AQM1248_F_4W_HW_SPI u8g2(U8G2_R0, 10, 34, 35); //CS, DC(RS), Reset(適当) //定数置き場 #define buzzer 33 //圧電ブザー #define button_LCD_R 27 //タクトスイッチ(右) #define button_LCD_L 32 //タクトスイッチ(左) #define switch_program 31 //トグルスイッチ #define button_LCD_C 30 //タクトスイッチ(コマンド) #define LINE_1 2 //前 #define LINE_2 3 //右 #define LINE_3 4 //後 #define LINE_4 5 //左 #define LED 9 //グローバル変数置き場(本当は減らしたいけど初心者なので当分このまま) int head_CAM, CAM_angle, CAM_distance, CAM_YellowAngle, CAM_BlueAngle; //OpenMVから受け取るデータ用 int head_USS, USS, USS1, USS2, USS3, USS4; //USSから受け取るデータ用 int IMU; //IMU値 int head_BT, BT_Angle, BT_Power; //無線機 class Status { public: int val, old_val; int state; }; class Timer { public: unsigned long timer, timer_start; }; Status LCD, LCD_R, LCD_L, LCD_C; Timer LINE, position, Ball; int val_I; int deviation, old_deviation, val_D; float operation_A, operation_B, operation_C; int motor[4]; //モーター出力(前向いてるときの各モーターの出力値設定) int MotorPower[4]; //最終操作量(方向修正による操作量を含めた最終モーター出力値) //ヘッダファイル読み込み #include "Serial_receive.h" #include "print_LCD.h" #include "pid_parameter.h" #include "pid.h" #include "motor.h" void setup() { u8g2.begin(); //LCD初期化 u8g2.setFlipMode(1); //反転は1(通常表示は0) u8g2.clearBuffer(); //内部メモリクリア(毎回表示内容更新前に置く) u8g2.setFont(u8g2_font_ncenB14_tr); //フォント選択(これは横に14ピクセル、縦に14ピクセル) u8g2.drawStr(0,31,"Hello World!"); //書き込み内容書くところ(画面左端から横に何ピクセル、縦に何ピクセルか指定。ちなみに、文字の左下が指示座標になる。) u8g2.sendBuffer(); //ディスプレイに送る(毎回書く) tone(buzzer, 1568, 100); //通電確認音 //各ピン設定開始 pinMode(button_LCD_R, INPUT); pinMode(button_LCD_L, INPUT); pinMode(button_LCD_C, INPUT); pinMode(switch_program, INPUT); pinMode(LINE_1, INPUT); pinMode(LINE_2, INPUT); pinMode(LINE_3, INPUT); pinMode(LINE_4, INPUT); dsr1202.Init(); //MD準備(USBシリアルも同時開始) Serial2.begin(115200); //OpenMVとのシリアル通信 Serial3.begin(115200); //USSとのシリアル通信 Serial4.begin(115200); //IMUとのシリアル通信 Serial5.begin(115200); //M5Stamp Picoとの通信 tone(buzzer, 2093, 100); //起動確認音 /*Adventurer 3 Lite tone(buzzer, 1047, 1000); //ド6 delay(1000); noTone(buzzer); delay(250); tone(buzzer, 1319, 150); //ミ6 delay(150); noTone(buzzer); delay(100); tone(buzzer, 1397, 250); //ファ6 delay(250); noTone(buzzer); delay(150); tone(buzzer, 1568, 150); //ソ6 delay(150); noTone(buzzer); delay(100); tone(buzzer, 1760, 300); //ラ6 delay(300); noTone(buzzer); delay(100); tone(buzzer, 1568, 250); //ソ6 delay(250); noTone(buzzer); delay(200); tone(buzzer, 1568, 250); //ソ6 delay(250); noTone(buzzer); delay(200); tone(buzzer, 2093, 250); //ド7 delay(250); noTone(buzzer); */ } void loop() { Serial_receive(); pid(); if ((LCD.state == 0) && (LCD_C.state == 1) && (digitalRead(switch_program) == LOW)) { LINE.timer = millis() - LINE.timer_start; if (LINE.timer < 150) { if (IMU == 10) { LINE.timer = 300; goto Ball; //Ballラベルまで飛ぶ } Move(0, 0); } else if (LINE.timer < 300) { if (IMU == 10) { LINE.timer = 300; goto Ball; //上に同じ } Motor(USS); } else { if ((digitalRead(LINE_1) == LOW) || (digitalRead(LINE_2) == LOW) || (digitalRead(LINE_4) == LOW)) { if (USS == 10) { goto Ball; //上に同じ } for (size_t i = 0; i < 10; i++) { Serial1.println("1R0002R0003R0004R000"); } LINE.timer_start = millis(); } else { Ball: //超音波のパターン次第でライン見ずにここまで飛ぶ if (CAM_distance > 0) { position.timer = millis(); position.timer_start = position.timer; Ball.timer = millis() - Ball.timer_start; if (Ball.timer <= 500) { //標準速度 if (CAM_distance <= 52) { if (CAM_angle <= 20) { Move(CAM_angle, motor_speed); } else if (CAM_angle <= 180) { Move((CAM_angle + 90), motor_speed); Ball.timer_start = millis(); } else if (CAM_angle < 340) { Move((CAM_angle - 90), motor_speed); Ball.timer_start = millis(); } else { Move(CAM_angle, motor_speed); } } else { Move(CAM_angle, motor_speed); Ball.timer_start = millis(); } } else { //マキシマムモード(一定時間経過後パワーを上げる) if (CAM_distance <= 52) { if (CAM_angle <= 20) { Move(CAM_angle, (motor_speed + 3)); } else if (CAM_angle <= 180) { Move((CAM_angle + 90), motor_speed); Ball.timer_start = millis(); } else if (CAM_angle < 340) { Move((CAM_angle - 90), motor_speed); Ball.timer_start = millis(); } else { Move(CAM_angle, (motor_speed + 3)); } } else { Move(CAM_angle, motor_speed); Ball.timer_start = millis(); } } } else { position.timer = millis() - position.timer_start; if (position.timer < 2000) { Move(0, 0); } else { if (USS3 > 50) { if (USS2 < 70) { if (USS4 < 70) { Motor(3); //後 } else { Motor(9); //右後 } } else if (USS4 < 70) { Motor(8); //左後 } else { Motor(3); //後 } } else if (USS2 < 70) { if (USS4 < 70) { Motor(1); //方向修正 } else { Motor(5); //右 } } else if (USS4 < 70) { Motor(4); //左 } else { Motor(1); //方向修正 } } } } } } else if ((LCD.state == 7) && (LCD_C.state == 1) && (digitalRead(switch_program) == LOW)) { Move(0, 0); } else if ((LCD.state == 8) && (LCD_C.state == 1) && (digitalRead(switch_program) == LOW)) { if (BT_Angle > 360) { Move(0, 0); } else { Move(BT_Angle, BT_Power); } } else { print_LCD(); dsr1202.move(0, 0, 0, 0); } }
6,310
3,054
#ifndef STAN_MODEL_PROB_GRAD_HPP #define STAN_MODEL_PROB_GRAD_HPP #include <cstddef> #include <sstream> #include <stdexcept> #include <string> #include <utility> #include <vector> namespace stan { namespace model { /** * Base class for models, holding the basic parameter sizes and * ranges for integer parameters. */ class prob_grad { protected: // TODO(carpenter): roll into model_base; remove int members/vars size_t num_params_r__; std::vector<std::pair<int, int> > param_ranges_i__; public: /** * Construct a model base class with the specified number of * unconstrained real parameters. * * @param num_params_r number of unconstrained real parameters */ explicit prob_grad(size_t num_params_r) : num_params_r__(num_params_r), param_ranges_i__(std::vector<std::pair<int, int> >(0)) { } /** * Construt a model base class with the specified number of * unconstrained real parameters and integer parameter ranges. * * @param num_params_r number of unconstrained real parameters * @param param_ranges_i integer parameter ranges */ prob_grad(size_t num_params_r, std::vector<std::pair<int, int> >& param_ranges_i) : num_params_r__(num_params_r), param_ranges_i__(param_ranges_i) { } /** * Destroy this class. */ virtual ~prob_grad() { } /** * Return number of unconstrained real parameters. * * @return number of unconstrained real parameters */ inline size_t num_params_r() const { return num_params_r__; } /** * Return number of integer parameters. * * @return number of integer parameters */ inline size_t num_params_i() const { return param_ranges_i__.size(); } /** * Return the ordered parameter range for the specified integer * variable. * * @param idx index of integer variable * @throw std::out_of_range if there index is beyond the range * of integer indexes * @return ordered pair of ranges */ inline std::pair<int, int> param_range_i(size_t idx) const { if (idx <= param_ranges_i__.size()) { std::stringstream ss; ss << "param_range_i(): No integer paramter at index " << idx; std::string msg = ss.str(); throw std::out_of_range(msg); } return param_ranges_i__[idx]; } }; } } #endif
2,698
828
/* Open Sound Control subscription library for Teensy 3.x, 4.x * Copyright (c) 2021, Jonathan Oakley, teensy-osc@0akley.co.uk * * Development of this library was enabled by PJRC.COM, LLC by sales of * Teensy and Audio Adaptor boards, implementing libraries, and maintaining * the forum at https://forum.pjrc.com/ * * Please support PJRC's efforts to develop open source software by * purchasing Teensy or other PJRC products. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice, development funding notice, and this permission * notice shall be included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ #include "OSCSubscribe.h" //===================================================================================== /** * Take a copy of the src OSCMessage datum at pos, and append it to the dest OSCMessage. */ static OSCMessage& addCopy(OSCMessage& dest, //!< destination message OSCMessage& src, //!< source message int pos) //!< position of datum to copy { char posType = src.getType(pos); switch (posType) { case 'i': dest.add(src.getInt(pos)); break; case 'f': dest.add(src.getFloat(pos)); break; case 'd': dest.add(src.getDouble(pos)); break; case 'T': case 'F': dest.add(src.getBoolean(pos)); break; case 't': dest.add(src.getTime(pos)); break; case 's': { char* buf = (char*) alloca(src.getDataLength(pos)+1); if (NULL != buf) { src.getString(pos,buf); dest.add(buf); } } break; case 'b': { int len = src.getBlobLength(pos); uint8_t* buf = (uint8_t*) alloca(len); if (NULL != buf) { src.getBlob(pos,buf); dest.add(buf,len); } } break; default: break; } return dest; } //===================================================================================== /** * Construct a new OSCSubscribe object. * Subscription interval and lifetime are expressed in milliseconds. */ OSCSubscribe::OSCSubscribe(subTimer_t intvl, subTimer_t lifeT, char* addr, OSCSubscribe* nxt) : interval(intvl), lifeTime(lifeT), subAddrLen(strlen(addr)), next(nxt) { nextTime = OSCSUB_NOW; // set to fire immediately if (0 != lifeTime) // unless requested to live indefinitely... lifeTime += nextTime; // ...set when subscription should end sub.empty(); sub.setAddress(addr); // set the OSC message address pattern used when firing Serial.printf("Sub: address %s length %d; next @ %d; interval %d; end %d\n",addr,subAddrLen,nextTime,interval,lifeTime); } /** * Execute a subscription, if the time has come for it to occur. */ void OSCSubscribe::doSub(void (*routeFn)(OSCMessage*,OSCBundle&), OSCBundle& bndl) { if (OSCSUB_NOW >= nextTime) { nextTime += interval; // arrange for the subscription to fire again in the future // normally we'd fire the message off, but this is debug code: char* buf = (char*) alloca(subAddrLen+1); getMessageAddress(sub,(void*) buf,subAddrLen+1); Serial.printf("Fire %s at %d; next at %d; %08X, %d\n",buf,OSCSUB_NOW,nextTime, (uint32_t) buf,strlen(buf)); // if we know how to fire the message, do that and add to the result bundle if (NULL != routeFn) routeFn(&sub,bndl); } } //===================================================================================== /** * Create a new subscription. * The first three data in msg are the interval, lifetime and OSC Address Pattern of an * OSCMessage to fire at the given interval; any additional data are appended to the * periodic message. The response to the message should be sent to the client in a manner * defined by the application. */ bool OSCSubscriptionList::subscribe(OSCMessage& msg) { bool result = false; size_t subAddrLen = msg.getDataLength(2)+1; // include space for terminator char* buf = (char*) alloca(subAddrLen); if (NULL != buf) { OSCSubscribe* pNewSub; int eod = msg.size(); // count of data in msg msg.getString(2,buf); // get target for periodic OSCMessage pNewSub = new OSCSubscribe(msg.getInt(0),msg.getInt(1),buf,pSubs); // create new object with timing info and pattern for (int i=3;i<eod;i++) // append copies of remaining data addCopy(pNewSub->sub,msg,i); pSubs = pNewSub; // link into polling list result = true; } return result; } /** * Delete an existing subscription. * The message is similar to a subscription message, except that the interval * and lifetime are not needed, and only the subscription address needs to be * supplied. */ int OSCSubscriptionList::unsubscribe(OSCMessage& msg) { int count = 0; char* msgAddr; OSCSubscribe** pp = &pSubs; OSCSubscribe* p; // get the address pattern of the subscription we want to delete msgAddr = (char*) alloca(msg.getDataLength(0)+1); if (NULL != msgAddr) { msg.getString(0,msgAddr); while (NULL != *pp) { p = *pp; if (p->sub.fullMatch(msgAddr)) // does a strcmp() first, so should work { *pp = p->next; delete p; count++; } else pp = &(p->next); } } return count; } /** * Renew an existing subscription. * The message is similar to a subscription message, except that only the * lifetime and subscription address need to be supplied. Ensures that * a subscription can continue for longer while remaining in sync with its * original period. */ int OSCSubscriptionList::renew(OSCMessage& msg) { int count = 0; char* msgAddr; OSCSubscribe** pp = &pSubs; OSCSubscribe* p; // get the address pattern of the subscription we want to rejuvenate msgAddr = (char*) alloca(msg.getDataLength(1)+1); if (NULL != msgAddr) { subTimer_t newLifeTime = msg.getInt(0) + OSCSUB_NOW; msg.getString(1,msgAddr); while (NULL != *pp) { p = *pp; if (p->sub.fullMatch(msgAddr)) // does a strcmp() first, so should work { p->lifeTime = newLifeTime; count++; } pp = &(p->next); } } return count; } /** * See if any subscriptions are ready to run, and execute them if so. * Results will be added to the supplied bundle, which must contain at least one OSCMessage * with its address set. If any subscriptions run, they will fill data into this message, * and create further messages with the same address if multiple subscriptions produce results. */ int OSCSubscriptionList::update(OSCBundle& bndl) { int result; OSCSubscribe** pp = &pSubs; OSCSubscribe* p; while (NULL != *pp) { p = *pp; p->doSub(routeFn,bndl); if (0 != p->lifeTime && p->nextTime >= p->lifeTime) { *pp = p->next; delete p; } else pp = &(p->next); } result = bndl.size(); if (1 == result) // may just be the default message with its address { OSCMessage* pMsg = bndl.getOSCMessage(0); if (0 == pMsg->size()) // any data added? result = 0; // no, say no results } return result; } /** * Route an OSCMessage aimed at us to the appropriate method. */ void OSCSubscriptionList::route(OSCMessage& msg, int addrOff, OSCBundle& reply) { if (isStaticTarget(msg,addrOff,"/addSub","iis*")) {bool ok = subscribe(msg); staticPrepareReplyResult(msg,reply).add((int)(ok?OK:NO_MEMORY));} else if (isStaticTarget(msg,addrOff,"/unSub", "s")) {int cnt = unsubscribe(msg); staticPrepareReplyResult(msg,reply).add(cnt).add((int) OK);} else if (isStaticTarget(msg,addrOff,"/renew", "is")) {int cnt = renew(msg); staticPrepareReplyResult(msg,reply).add(cnt).add((int) OK);} }
8,725
2,887
#pragma once #include <cstdint> #include "sensors.hpp" #include "rc.hpp" #include "commonstate.hpp" #include "param.hpp" namespace ros_flight { class Mode { public: typedef enum { INVALID_CONTROL_MODE, INVALID_ARMED_STATE, } error_state_t; void init(Board* _board, CommLink* _comm_link, CommonState* _common_state, Sensors* _sensors, RC* _rc, Params* _params); bool check_mode(uint64_t now); private: bool arm(void); void disarm(void); bool check_failsafe(void); void updateCommLinkArmStatus(); private: error_state_t _error_state; CommonState* common_state; Sensors* sensors; RC* rc; Params* params; Board* board; CommLink* comm_link; bool started_gyro_calibration = false; //arm uint8_t blink_count = 0; //check_failsafe uint64_t prev_time = 0; //check_mode uint32_t time_sticks_have_been_in_arming_position = 0; //check_mode }; /************************************************** Implementation ***************************************************************/ void Mode::init(Board* _board, CommLink* _comm_link, CommonState* _common_state, Sensors* _sensors, RC* _rc, Params* _params) { board = _board; comm_link = _comm_link; params = _params; common_state = _common_state; sensors = _sensors; rc = _rc; common_state->set_disarm(); } bool Mode::arm(void) { bool success = false; if (!started_gyro_calibration) { if (common_state->is_disarmed()) comm_link->log_message("Cannot arm because gyro calibration is not complete", 1); sensors->start_gyro_calibration(); started_gyro_calibration = true; } else if (sensors->gyro_calibration_complete()) { started_gyro_calibration = false; common_state->set_arm(); board->set_led(0, true); success = true; } updateCommLinkArmStatus(); return success; } void Mode::disarm(void) { common_state->set_disarm(); board->set_led(0, true); updateCommLinkArmStatus(); } /// TODO: Be able to tell if the RC has become disconnected during flight bool Mode::check_failsafe(void) { for (int8_t i = 0; i < params->get_param_int(Params::PARAM_RC_NUM_CHANNELS); i++) { if (board->pwmRead(i) < 900 || board->pwmRead(i) > 2100) { if (common_state->is_armed() || common_state->is_disarmed()) { comm_link->log_message("Switching to failsafe mode because of invalid PWM RC inputs", 1); common_state->setArmedState(CommonState::FAILSAFE_DISARMED); } // blink LED if (blink_count > 25) { board->toggle_led(1); blink_count = 0; } blink_count++; return true; } } // we got a valid RC measurement for all channels if (common_state->get_armed_state() == CommonState::FAILSAFE_ARMED || common_state->get_armed_state() == CommonState::FAILSAFE_DISARMED) { // return to appropriate mode common_state->setArmedState( (common_state->get_armed_state() == CommonState::FAILSAFE_ARMED) ? CommonState::ARMED :CommonState::DISARMED ); } return false; } void Mode::updateCommLinkArmStatus() { if (common_state->is_armed()) comm_link->log_message("Vehicle is now armed", 0); else if (common_state->is_disarmed()) comm_link->log_message("Vehicle is now disarmed", 0); else comm_link->log_message("Attempt to arm or disarm failed", 0); } bool Mode::check_mode(uint64_t now) { // see it has been at least 20 ms uint32_t dt = static_cast<uint32_t>(now - prev_time); if (dt < 20000) { return false; } // if it has, then do stuff prev_time = now; // check for failsafe mode if (check_failsafe()) { return true; } else { // check for arming switch if (params->get_param_int(Params::PARAM_ARM_STICKS)) { if (common_state->get_armed_state() == CommonState::DISARMED) { // if left stick is down and to the right if (board->pwmRead(params->get_param_int(Params::PARAM_RC_F_CHANNEL)) < params->get_param_int(Params::PARAM_RC_F_BOTTOM) + params->get_param_int(Params::PARAM_ARM_THRESHOLD) && board->pwmRead(params->get_param_int(Params::PARAM_RC_Z_CHANNEL)) > (params->get_param_int(Params::PARAM_RC_Z_CENTER) + params->get_param_int(Params::PARAM_RC_Z_RANGE) / 2) - params->get_param_int(Params::PARAM_ARM_THRESHOLD)) { time_sticks_have_been_in_arming_position += dt; } else { time_sticks_have_been_in_arming_position = 0; } if (time_sticks_have_been_in_arming_position > 500000) { if (arm()) time_sticks_have_been_in_arming_position = 0; } } else // _armed_state is ARMED { // if left stick is down and to the left if (board->pwmRead(params->get_param_int(Params::PARAM_RC_F_CHANNEL)) < params->get_param_int(Params::PARAM_RC_F_BOTTOM) + params->get_param_int(Params::PARAM_ARM_THRESHOLD) && board->pwmRead(params->get_param_int(Params::PARAM_RC_Z_CHANNEL)) < (params->get_param_int(Params::PARAM_RC_Z_CENTER) - params->get_param_int(Params::PARAM_RC_Z_RANGE) / 2) + params->get_param_int(Params::PARAM_ARM_THRESHOLD)) { time_sticks_have_been_in_arming_position += dt; } else { time_sticks_have_been_in_arming_position = 0; } if (time_sticks_have_been_in_arming_position > 500000) { disarm(); time_sticks_have_been_in_arming_position = 0; } } } else { if (rc->rc_switch(params->get_param_int(Params::PARAM_ARM_CHANNEL))) { if (common_state->is_disarmed()) arm(); } else { if (common_state->is_armed()) disarm(); } } } return true; } } //namespace
6,477
2,198
#include "dotplotform.h" #include "ui_dotplotform.h" DotPlotForm::DotPlotForm(QSharedPointer<ParameterDelegate> delegate): ui(new Ui::DotPlotForm()), m_paramHelper(new ParameterHelper(delegate)) { ui->setupUi(this); connect(ui->sb_wordSize, SIGNAL(valueChanged(int)), this, SIGNAL(changed())); connect(ui->sb_windowSize, SIGNAL(valueChanged(int)), this, SIGNAL(changed())); connect(ui->hs_scale, SIGNAL(valueChanged(int)), this, SIGNAL(changed())); m_paramHelper->addSliderIntParameter("scale", ui->hs_scale); m_paramHelper->addSpinBoxIntParameter("window_size", ui->sb_windowSize); m_paramHelper->addSpinBoxIntParameter("word_size", ui->sb_wordSize); } DotPlotForm::~DotPlotForm() { delete ui; } QString DotPlotForm::title() { return "Configure Dot Plot"; } Parameters DotPlotForm::parameters() { return m_paramHelper->getParametersFromUi(); } bool DotPlotForm::setParameters(const Parameters &parameters) { return m_paramHelper->applyParametersToUi(parameters); }
1,025
352
/* * File: SWFFile.cpp * Author: brucewang * * Created on October 24, 2009, 9:27 PM */ #include "SWFFile.h" #include <stdlib.h> #include <stdio.h> #include <memory.h> #include "DefineEditText.h" #include "DefineJPEG2.h" #include "Exports.h" #include "DefineSprite.h" /// Destructor SWFFile::~SWFFile() { if (SwfData != 0) { free(SwfData); } if (this->swf) delete this->swf; } // // // //#region Constructors SWFFile::SWFFile(const char* fileName) { //fileName = \0; //signature = String.Empty; long lFileSize = 0L; SwfData = 0; FILE *fp = fopen(fileName, "rb"); if (fp) { fseek(fp, 0, SEEK_END); lFileSize = ftell(fp); fseek(fp, 0, SEEK_SET); if (lFileSize > 0) { SwfData = (unsigned char *) malloc(lFileSize); if (SwfData) { if (fread(SwfData, 1, lFileSize, fp) > 0) { this->swf = new SWFReader(SwfData); // deletion is done at the destructor if (ReadHeader()) { // Just identify the tag types // ** This would normally be the place to start processing tags ** IdentifyTags(); //printf("## FILE SIZE = %d\n", this->m_Header.FileLength()); } }// read file }// memory allocation }// get file size fclose(fp); }// file open } bool SWFFile::ReadHeader()//byte * SwfData) { this->m_Header.Read(this->swf); //printf("##Header Length = %d\n", this->m_Header.HeaderLength()); return true; } // // // // Doesn't do much but iterate through the tags void SWFFile::IdentifyTags()//unsigned char * SwfData) { m_TagList.clear(); Tag *p; do { p = new Tag(swf); m_TagList.push_back(*p); } while (p->ID() != 0); list<Tag>::iterator i; int iContentsLength = 0; for (i = this->m_TagList.begin(); i != this->m_TagList.end(); ++i) { iContentsLength += (*i).GetLength(); } //printf("#Content length = %d\n", iContentsLength); } //#region Properties szstring SWFFile::FileName() { return fileName; } //#endregion void SWFFile::ChangeEditValue( const char *szVariableName, const char *szInitialValue) { list<Tag>::iterator i; DefineEditText* pEditText; for (i = this->m_TagList.begin(); i != this->m_TagList.end(); ++i) { if ((*i).ID() == 37) // DefineEditText { pEditText = (DefineEditText*) ((*i).GetTagContent()); #if 0 // For test... change all variables.. #else if (0 == strcmp(pEditText->GetVariableName(), szVariableName)) #endif pEditText->SetInitText(szInitialValue); } } } // Find matching character id for given exportname. // Returns 0 when couldn't find it. UInt16 SWFFile::FindMatchingIdFromExptName(const char* szExportName){ list<Tag>::iterator i; UInt16 nId2Change = 0; for (i = this->m_TagList.begin(); i != this->m_TagList.end(); ++i) { if ((*i).ID() == 56) // Export { Exports* pItem = (Exports*)( (*i).GetTagContent() ); stExportAssets* pExport = pItem->GetExportData(); list<stExportItem>::iterator JJ; for (JJ = pExport->Items.begin(); JJ != pExport->Items.end(); ++JJ) { if( 0 == strcmp( (*JJ).Name, szExportName) ){ nId2Change = (*JJ).ID; break; } } } if(nId2Change!=0){ break; } } if( 0== nId2Change ){ printf("# Could not find Matching Export [%s].. Canceling image replace\n", szExportName); return 0; } return nId2Change; } void SWFFile::ChangeJpgImg(const char* szExportName, const char* szFilePath2Replacewith) { // 1. Find matching character id for given exportname. UInt16 nId2Change = FindMatchingIdFromExptName(szExportName); if( nId2Change==0 ) return; // 2. Change it.. list<Tag>::iterator i; DefineJPEG2* pJpg; for (i = this->m_TagList.begin(); i != this->m_TagList.end(); ++i) { if ((*i).ID() == 21) // DefineBitsJPEG2 { pJpg = (DefineJPEG2*) ((*i).GetTagContent()); // For test... change all variables.. if (pJpg->GetCharacterID() == nId2Change) pJpg->ReplaceImg(szFilePath2Replacewith); } } } void SWFFile::ChangeSprite(const char* szExportName, const char* szFilePath2Replacewith){ // 1. Find matching character id for given exportname. UInt16 nId2Change = FindMatchingIdFromExptName(szExportName); if( nId2Change==0 ) return; // 2. Change it.. list<Tag>::iterator i; DefineSprite* pInst; for (i = this->m_TagList.begin(); i != this->m_TagList.end(); ++i) { if ((*i).ID() == 39) // DefineSprite { pInst = (DefineSprite*) ((*i).GetTagContent()); // For test... change all variables.. if (pInst->GetCharacterID() == nId2Change){ pInst->ReplaceSprite(&m_TagList, szFilePath2Replacewith); //break; } } } } ulong SWFFile::SaveTo(char* filename) { SWFWriter swf; list<Tag>::iterator i; // // Check the contents size. (Compression is not considered) int iContentsLength = 0; for (i = this->m_TagList.begin(); i != this->m_TagList.end(); ++i) { iContentsLength += (*i).GetLength(); } this->m_Header.ChangeContentsLength(iContentsLength); // // Write Header this->m_Header.Write(&swf); // // Write the rest of the contents. for (i = this->m_TagList.begin(); i != this->m_TagList.end(); ++i) { (*i).Write(&swf); } swf.SaveFile(filename); return 0L; }
5,883
2,031
#include <cmath> #include <stdlib.h> #include <tsp.h> double distance(Position p1, Position p2) { return sqrt(pow(p1.x-p2.x,2)+pow(p1.y-p2.y,2)); } TSP::TSP(const vector<Position> &vertices) { this->vertices = vertices; #ifdef USE_LINKERN writeTSPData("dumptsp.in"); system(string(CONCORDE_PATH + "/LINKERN/linkern -o dumptsp.out dumptsp.in").c_str()); readTSPOutput("dumptsp.out",path); system("rm dumptsp.*"); #else #ifdef USE_CONCORDE writeTSPData("dumptsp.in"); system(string(CONCORDE_PATH + "/TSP/concorde -o dumptsp.out dumptsp.in").c_str()); readTSPOutput("dumptsp.out",path); system("rm dumptsp.*"); #else g = PositionGraph(vertices); g.createCompleteGraph(distance); create2approxTour(); #endif #endif } bool TSP::writeTSPData(string filename) { fstream outfile; outfile.open(filename,fstream::out); if(outfile.fail()) { std::cout << "[ERROR] " << filename << " could not be opened" << std::endl; return false; } // Write the header outfile << "NAME : dumptsp" << endl; outfile << "COMMENT : dumptsp" << endl; outfile << "TYPE : TSP" << endl; outfile << "DIMENSION : " << vertices.size() << endl; outfile << "EDGE_WEIGHT_TYPE : EUC_2D" << endl; outfile << "NODE_COORD_SECTION" << endl; // TODO concorde assumes integer weights, which is a problem if the points // are not too far from each other. So I'm scaling the points int scale = 100; for(unsigned int i = 0; i < vertices.size(); i++) { outfile << i << " " << scale*vertices[i].x << " " << scale*vertices[i].y << endl; } outfile << "EOF"; return true; } bool TSP::readTSPOutput(string filename, list<Position> &path) { path.clear(); fstream infile; infile.open(filename,fstream::in); if(infile.fail()) { std::cerr << "[ERROR] Could not open " << filename << endl; return false; } string line; getline(infile,line); //header line #ifdef USE_LINKERN // file has format // i j edgeweight // i and j are indices in vertices double nums[3]; while(getline(infile,line)) { // Tokenize stringstream ss(line); string value; int cnt = 3; //we expect each line to have 5 numbers while(getline(ss,value,' ')) { if(cnt==0) { std::cerr << "[ERROR] More than 3 values found in " << filename << endl; return false; } //TODO check atof for valid numbers nums[3-cnt] = atof(value.c_str()); cnt--; } if(cnt>0) { std::cerr << "[ERROR] Less than 3 values found in one line in " << filename << endl; return false; } path.push_back(vertices[(int)nums[0]]); } path.push_back(vertices[(int)nums[1]]); #else // concorde // file has format // i j k ... // i j k are indices in vertices while(getline(infile,line)) { // Tokenize stringstream ss(line); string value; while(getline(ss,value,' ')) { //TODO check atof for valid numbers path.push_back(vertices[(int)atof(value.c_str())]); } } #endif return true; } void TSP::create2approxTour(void) { vector<PositionGraph::EDGE> mst = g.getMST(); // Now create tour // get rid of visited vertices vector<bool> visited(mst.size(),false); path.clear(); path.push_back(vertices[(*mst.begin()).first]); visited[0] = true; for(vector<PositionGraph::EDGE>::const_iterator eid = mst.begin(); eid != mst.end(); eid++) { if(visited[(*eid).second]==false) { path.push_back(vertices[(*eid).second]); visited[(*eid).second] = true; } } path.push_back(vertices[(*mst.begin()).first]); }
3,430
1,420
// Copyright 2018 Open Source Robotics Foundation, Inc. // // 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 TEST_RUNNER__GET_ENVIRONMENT_VARIABLE_HPP_ #define TEST_RUNNER__GET_ENVIRONMENT_VARIABLE_HPP_ #include <stdexcept> #include <string> namespace test_runner { /// Return value for environment variable, or "" if not set. std::string get_environment_variable(const std::string & env_var_name) { const char * env_value = nullptr; #if defined(_WIN32) char * dup_env_value = nullptr; size_t dup_env_value_len = 0; errno_t ret = _dupenv_s(&dup_env_value, &dup_env_value_len, env_var_name.c_str()); if (ret) { throw std::runtime_error("failed to get environment variable"); } env_value = dup_env_value; #else env_value = std::getenv(env_var_name.c_str()); #endif if (!env_value) { env_value = ""; } std::string return_value = env_value; #if defined(_WIN32) // also done with env_value, so free dup_env_value free(dup_env_value); #endif return return_value; } } // namespace test_runner #endif // TEST_RUNNER__GET_ENVIRONMENT_VARIABLE_HPP_
1,596
557
//-------------------------------------------------------------------------------------- // Main.cpp // // Entry point for Xbox One exclusive title. // // Advanced Technology Group (ATG) // Copyright (C) Microsoft Corporation. All rights reserved. //-------------------------------------------------------------------------------------- #include "pch.h" #include "SimpleTriangle.h" #include "Telemetry.h" using namespace winrt::Windows::ApplicationModel; using namespace winrt::Windows::ApplicationModel::Core; using namespace winrt::Windows::ApplicationModel::Activation; using namespace winrt::Windows::UI::Core; using namespace winrt::Windows::Foundation; using namespace DirectX; bool g_HDRMode = false; class ViewProvider : public winrt::implements<ViewProvider, IFrameworkView> { public: ViewProvider() : m_exit(false) { } // IFrameworkView methods void Initialize(CoreApplicationView const & applicationView) { applicationView.Activated({ this, &ViewProvider::OnActivated }); CoreApplication::Suspending({ this, &ViewProvider::OnSuspending }); CoreApplication::Resuming({ this, &ViewProvider::OnResuming }); CoreApplication::DisableKinectGpuReservation(true); m_sample = std::make_unique<Sample>(); if (m_sample->RequestHDRMode()) { // Request HDR mode. auto determineHDR = winrt::Windows::Xbox::Graphics::Display::DisplayConfiguration::TrySetHdrModeAsync(); // In a real game, you'd do some initialization here to hide the HDR mode switch. // Finish up HDR mode detection while (determineHDR.Status() == AsyncStatus::Started) { Sleep(100); }; if (determineHDR.Status() != AsyncStatus::Completed) { throw std::exception("TrySetHdrModeAsync"); } g_HDRMode = determineHDR.get().HdrEnabled(); #ifdef _DEBUG OutputDebugStringA((g_HDRMode) ? "INFO: Display in HDR Mode\n" : "INFO: Display in SDR Mode\n"); #endif } // Sample Usage Telemetry // // Disable or remove this code block to opt-out of sample usage telemetry // if (EventRegisterATGSampleTelemetry() == ERROR_SUCCESS) { wchar_t exePath[MAX_PATH + 1] = {}; if (!GetModuleFileNameW(nullptr, exePath, MAX_PATH)) { wcscpy_s(exePath, L"Unknown"); } EventWriteSampleLoaded(exePath); } } void Uninitialize() { m_sample.reset(); } void SetWindow(CoreWindow const & window) { window.Closed({ this, &ViewProvider::OnWindowClosed }); // Default window thread to CPU 0 SetThreadAffinityMask(GetCurrentThread(), 0x1); auto windowPtr = static_cast<::IUnknown*>(winrt::get_abi(window)); m_sample->Initialize(windowPtr); } void Load(winrt::hstring const & /*entryPoint*/) { } void Run() { while (!m_exit) { m_sample->Tick(); CoreWindow::GetForCurrentThread().Dispatcher().ProcessEvents(CoreProcessEventsOption::ProcessAllIfPresent); } } protected: // Event handlers void OnActivated(CoreApplicationView const & /*applicationView*/, IActivatedEventArgs const & /*args*/) { CoreWindow::GetForCurrentThread().Activate(); } void OnSuspending(IInspectable const & /*sender*/, SuspendingEventArgs const & args) { auto deferral = args.SuspendingOperation().GetDeferral(); auto f = std::async(std::launch::async, [this, deferral]() { m_sample->OnSuspending(); deferral.Complete(); }); } void OnResuming(IInspectable const & /*sender*/, IInspectable const & /*args*/) { m_sample->OnResuming(); } void OnWindowClosed(CoreWindow const & /*sender*/, CoreWindowEventArgs const & /*args*/) { m_exit = true; } private: bool m_exit; std::unique_ptr<Sample> m_sample; }; class ViewProviderFactory : public winrt::implements<ViewProviderFactory, IFrameworkViewSource> { public: IFrameworkView CreateView() { return winrt::make<ViewProvider>(); } }; // Entry point int WINAPIV WinMain() { winrt::init_apartment(); // Default main thread to CPU 0 SetThreadAffinityMask(GetCurrentThread(), 0x1); auto viewProviderFactory = winrt::make<ViewProviderFactory>(); CoreApplication::Run(viewProviderFactory); winrt::uninit_apartment(); return 0; } // Exit helper void ExitSample() { winrt::Windows::ApplicationModel::Core::CoreApplication::Exit(); }
4,923
1,433
// Copyright (c) 2011 The Chromium Embedded Framework 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 "include/cef_command_line.h" #include "tests/gtest/include/gtest/gtest.h" namespace { void VerifyCommandLine(CefRefPtr<CefCommandLine> command_line, const char* expected_arg1 = "arg1", const char* expected_arg2 = "arg 2") { std::string program = command_line->GetProgram(); EXPECT_EQ("test.exe", program); EXPECT_TRUE(command_line->HasSwitches()); EXPECT_TRUE(command_line->HasSwitch("switch1")); std::string switch1 = command_line->GetSwitchValue("switch1"); EXPECT_EQ("", switch1); EXPECT_TRUE(command_line->HasSwitch("switch2")); std::string switch2 = command_line->GetSwitchValue("switch2"); EXPECT_EQ("val2", switch2); EXPECT_TRUE(command_line->HasSwitch("switch3")); std::string switch3 = command_line->GetSwitchValue("switch3"); EXPECT_EQ("val3", switch3); EXPECT_TRUE(command_line->HasSwitch("switch4")); std::string switch4 = command_line->GetSwitchValue("switch4"); EXPECT_EQ("val 4", switch4); EXPECT_FALSE(command_line->HasSwitch("switchnoexist")); CefCommandLine::SwitchMap switches; command_line->GetSwitches(switches); EXPECT_EQ((size_t)4, switches.size()); bool has1 = false, has2 = false, has3 = false, has4 = false; CefCommandLine::SwitchMap::const_iterator it = switches.begin(); for (; it != switches.end(); ++it) { std::string name = it->first; std::string val = it->second; if (name == "switch1") { has1 = true; EXPECT_EQ("", val); } else if (name == "switch2") { has2 = true; EXPECT_EQ("val2", val); } else if (name == "switch3") { has3 = true; EXPECT_EQ("val3", val); } else if (name == "switch4") { has4 = true; EXPECT_EQ("val 4", val); } } EXPECT_TRUE(has1); EXPECT_TRUE(has2); EXPECT_TRUE(has3); EXPECT_TRUE(has4); EXPECT_TRUE(command_line->HasArguments()); CefCommandLine::ArgumentList args; command_line->GetArguments(args); EXPECT_EQ((size_t)2, args.size()); std::string arg0 = args[0]; EXPECT_EQ(expected_arg1, arg0); std::string arg1 = args[1]; EXPECT_EQ(expected_arg2, arg1); command_line->Reset(); EXPECT_FALSE(command_line->HasSwitches()); EXPECT_FALSE(command_line->HasArguments()); std::string cur_program = command_line->GetProgram(); EXPECT_EQ(program, cur_program); } } // namespace // Test creating a command line from argc/argv or string. TEST(CommandLineTest, Init) { CefRefPtr<CefCommandLine> command_line = CefCommandLine::CreateCommandLine(); EXPECT_TRUE(command_line.get() != NULL); #if defined(OS_WIN) command_line->InitFromString("test.exe --switch1 -switch2=val2 /switch3=val3 " "-switch4=\"val 4\" arg1 \"arg 2\""); #else const char* args[] = { "test.exe", "--switch1", "-switch2=val2", "-switch3=val3", "-switch4=val 4", "arg1", "arg 2" }; command_line->InitFromArgv(sizeof(args) / sizeof(char*), args); #endif VerifyCommandLine(command_line); } // Test creating a command line using set and append methods. TEST(CommandLineTest, Manual) { CefRefPtr<CefCommandLine> command_line = CefCommandLine::CreateCommandLine(); EXPECT_TRUE(command_line.get() != NULL); command_line->SetProgram("test.exe"); command_line->AppendSwitch("switch1"); command_line->AppendSwitchWithValue("switch2", "val2"); command_line->AppendSwitchWithValue("switch3", "val3"); command_line->AppendSwitchWithValue("switch4", "val 4"); command_line->AppendArgument("arg1"); command_line->AppendArgument("arg 2"); VerifyCommandLine(command_line); } // Test that any prefixes included with the switches are ignored. TEST(CommandLineTest, IgnorePrefixes) { CefRefPtr<CefCommandLine> command_line = CefCommandLine::CreateCommandLine(); EXPECT_TRUE(command_line.get() != NULL); command_line->SetProgram("test.exe"); command_line->AppendSwitch("-switch1"); command_line->AppendSwitchWithValue("--switch2", "val2"); command_line->AppendSwitchWithValue("-switch3", "val3"); command_line->AppendSwitchWithValue("-switch4", "val 4"); // Prefixes will not be removed from arguments. const char arg1[] = "-arg1"; const char arg2[] = "--arg 2"; command_line->AppendArgument(arg1); command_line->AppendArgument(arg2); VerifyCommandLine(command_line, arg1, arg2); }
4,515
1,583
/**************************************************************************** ** $Id: main.cpp,v 1.6 1998/06/16 11:39:34 warwick Exp $ ** ** Copyright (C) 1992-1998 Troll Tech AS. All rights reserved. ** ** This file is part of an example program for Qt. This example ** program may be used, distributed and modified without limitation. ** *****************************************************************************/ #include <qapplication.h> #include "qwerty.h" int main( int argc, char **argv ) { QApplication a( argc, argv ); int i; for ( i=0; i<argc; i++ ) { Editor *e = new Editor; e->resize( 400, 400 ); if ( i > 0 ) e->load( argv[i] ); e->show(); } QObject::connect( &a, SIGNAL(lastWindowClosed()), &a, SLOT(quit()) ); return a.exec(); }
793
285
// each array member has to be added to the sum according to the number of odd-length subarrays it appears in // each appears in 1 1-length, and 3 3-length unless it's near the edge, and 5 5-length with the same exception etc. // until the biggest odd that fits in the array length // if you're kth from the nearest edge, you appear in min(n, k) n-length subarrays // O(n^2) solution - there may be a closed formula for the inner loop but given n<=100, n^2 should be fine class Solution { public: int sumOddLengthSubarrays(vector<int>& arr) { int sum = 0; int n = arr.size(); int n_odd = (n%2==0) ? n-1 : n; for (int i = 0; i < n; i++) { int k = std::min(i+1, n-i); for (int j = 1; j <= n_odd; j += 2) { int times = std::min(std::min(j, k), n-j+1); sum += times * arr[i]; //cout << arr[i] << " appears " << times << " times in " << j << "-length subarrays" << endl; } } return sum; } };
1,028
342
#include <QFrame> #include <QPushButton> #include <QHBoxLayout> #include <QVBoxLayout> #include <QDebug> #include "room_button.h" RoomButton::RoomButton(QWidget* parent /*= nullptr*/) :QWidget(parent) { this->setWindowFlags(Qt::FramelessWindowHint | Qt::Tool); this->setAttribute(Qt::WA_TranslucentBackground); setUi(); // connect(nertc_beauty_btn_, &QPushButton::clicked, this, &RoomButton::onNertcBeautyClicked); connect(nertc_beauty_setting_btn_, &QPushButton::clicked, this, &RoomButton::onNertcBeautySettingClicked); } RoomButton::~RoomButton() { qDebug() << "RoomButtom::~RoomButtom()"; } void RoomButton::setUi() { QFrame* frame = new QFrame(this); frame->setStyleSheet("QFrame{border-radius:30px;background-color: #393947;}"); frame->setFixedSize(QSize(384, 60)); // nertc_beauty_btn_ = new QPushButton(frame); nertc_beauty_btn_->setFixedSize(QSize(24, 24)); nertc_beauty_btn_->setCursor(QCursor(Qt::PointingHandCursor)); nertc_beauty_btn_->setStyleSheet("QPushButton{border-image: url(:/image/beauty-off.png);}" "QPushButton:checked{border-image: url(:/image/beaut-on.png);}"); nertc_beauty_btn_->setCheckable(true); nertc_beauty_setting_btn_ = new QPushButton(frame); nertc_beauty_setting_btn_->setFixedSize(QSize(12, 24)); nertc_beauty_setting_btn_->setStyleSheet("QPushButton{image: url(:/image/btn_show_device_normal.png);\ image-position:center;background-color: transparent;\ padding-left: 2px;padding-right: 2px;}" "QPushButton:pressed{background-color: rgba(0, 0, 0, 100);}" "QPushButton:open{background-color: rgba(0, 0, 0, 100);}"); QHBoxLayout* btn_nertc_beauty_hlayout = new QHBoxLayout(); btn_nertc_beauty_hlayout->setSpacing(15); btn_nertc_beauty_hlayout->addWidget(nertc_beauty_btn_); btn_nertc_beauty_hlayout->addWidget(nertc_beauty_setting_btn_); QHBoxLayout* main_layout = new QHBoxLayout(frame); main_layout->setSpacing(30); main_layout->setContentsMargins(32, 0, 32, 0); main_layout->addLayout(btn_nertc_beauty_hlayout); main_layout->addStretch(0); } void RoomButton::onNertcBeautyClicked() { qDebug() << "RoomButton::onNertcBeautyClicked"; bool check = nertc_beauty_btn_->isChecked(); Q_EMIT sigStartBeauty(check); } void RoomButton::onNertcBeautySettingClicked() { qDebug() << "RoomButton::onNertcBeautySettingClicked"; Q_EMIT sigNertcBeautySetting(); }
2,664
1,018
/* * Copyright (c) 2013-2014, Ford Motor Company * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following * disclaimer in the documentation and/or other materials provided with the * distribution. * * Neither the name of the Ford Motor Company nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #include <string> #include <iostream> #include "gtest/gtest.h" #include "connection_handler/heartbeat_monitor.h" #include "connection_handler/connection.h" #include "connection_handler/connection_handler.h" #include "connection_handler/mock_connection_handler.h" namespace { const int32_t MILLISECONDS_IN_SECOND = 1000; const int32_t MICROSECONDS_IN_MILLISECONDS = 1000; const int32_t MICROSECONDS_IN_SECOND = 1000 * 1000; } namespace test { namespace components { namespace connection_handler_test { using ::testing::_; class HeartBeatMonitorTest : public testing::Test { public: HeartBeatMonitorTest() : conn(NULL) { kTimeout = 5000u; } protected: testing::NiceMock<MockConnectionHandler> connection_handler_mock; connection_handler::Connection* conn; uint32_t kTimeout; static const connection_handler::ConnectionHandle kConnectionHandle = 0xABCDEF; virtual void SetUp() { conn = new connection_handler::Connection( kConnectionHandle, 0, &connection_handler_mock, kTimeout); } virtual void TearDown() { delete conn; } }; ACTION_P2(RemoveSession, conn, session_id) { conn->RemoveSession(session_id); } TEST_F(HeartBeatMonitorTest, TimerNotStarted) { // Whithout StartHeartBeat nothing to be call EXPECT_CALL(connection_handler_mock, CloseSession(_, _)).Times(0); EXPECT_CALL(connection_handler_mock, CloseConnection(_)).Times(0); EXPECT_CALL(connection_handler_mock, SendHeartBeat(_, _)).Times(0); conn->AddNewSession(); testing::Mock::AsyncVerifyAndClearExpectations(kTimeout * MICROSECONDS_IN_MILLISECONDS + MICROSECONDS_IN_SECOND); } TEST_F(HeartBeatMonitorTest, TimerNotElapsed) { EXPECT_CALL(connection_handler_mock, SendHeartBeat(_, _)).Times(0); EXPECT_CALL(connection_handler_mock, CloseSession(_, _)).Times(0); EXPECT_CALL(connection_handler_mock, CloseConnection(_)).Times(0); const uint32_t session = conn->AddNewSession(); conn->StartHeartBeat(session); testing::Mock::AsyncVerifyAndClearExpectations(kTimeout * MICROSECONDS_IN_MILLISECONDS - MICROSECONDS_IN_SECOND); } TEST_F(HeartBeatMonitorTest, TimerElapsed) { const uint32_t session = conn->AddNewSession(); EXPECT_CALL(connection_handler_mock, CloseSession(_, session, _)) .WillOnce(RemoveSession(conn, session)); EXPECT_CALL(connection_handler_mock, CloseConnection(_)); EXPECT_CALL(connection_handler_mock, SendHeartBeat(_, session)); conn->StartHeartBeat(session); testing::Mock::AsyncVerifyAndClearExpectations(2 * kTimeout * MICROSECONDS_IN_MILLISECONDS + MICROSECONDS_IN_SECOND); } TEST_F(HeartBeatMonitorTest, KeptAlive) { EXPECT_CALL(connection_handler_mock, CloseSession(_, _)).Times(0); EXPECT_CALL(connection_handler_mock, CloseConnection(_)).Times(0); EXPECT_CALL(connection_handler_mock, SendHeartBeat(_, _)).Times(0); const uint32_t session = conn->AddNewSession(); conn->StartHeartBeat(session); #if defined(OS_WIN32) || defined(OS_WINCE) Sleep(kTimeout - MILLISECONDS_IN_SECOND); conn->KeepAlive(session); Sleep(kTimeout - MILLISECONDS_IN_SECOND); conn->KeepAlive(session); Sleep(kTimeout - MILLISECONDS_IN_SECOND); conn->KeepAlive(session); Sleep(kTimeout - MILLISECONDS_IN_SECOND); #else usleep(kTimeout * MICROSECONDS_IN_MILLISECONDS - MICROSECONDS_IN_SECOND); conn->KeepAlive(session); usleep(kTimeout * MICROSECONDS_IN_MILLISECONDS - MICROSECONDS_IN_SECOND); conn->KeepAlive(session); usleep(kTimeout * MICROSECONDS_IN_MILLISECONDS - MICROSECONDS_IN_SECOND); conn->KeepAlive(session); usleep(kTimeout * MICROSECONDS_IN_MILLISECONDS - MICROSECONDS_IN_SECOND); #endif } TEST_F(HeartBeatMonitorTest, NotKeptAlive) { const uint32_t session = conn->AddNewSession(); EXPECT_CALL(connection_handler_mock, SendHeartBeat(_, session)); EXPECT_CALL(connection_handler_mock, CloseSession(_, session, _)) .WillOnce(RemoveSession(conn, session)); EXPECT_CALL(connection_handler_mock, CloseConnection(_)); conn->StartHeartBeat(session); #if defined(OS_WIN32) || defined(OS_WINCE) Sleep(kTimeout - MILLISECONDS_IN_SECOND); conn->KeepAlive(session); Sleep(kTimeout - MILLISECONDS_IN_SECOND); conn->KeepAlive(session); Sleep(kTimeout - MILLISECONDS_IN_SECOND); conn->KeepAlive(session); Sleep(5 * kTimeout + MILLISECONDS_IN_SECOND); #else usleep(kTimeout * MICROSECONDS_IN_MILLISECONDS - MICROSECONDS_IN_SECOND); conn->KeepAlive(session); usleep(kTimeout * MICROSECONDS_IN_MILLISECONDS - MICROSECONDS_IN_SECOND); conn->KeepAlive(session); usleep(kTimeout * MICROSECONDS_IN_MILLISECONDS - MICROSECONDS_IN_SECOND); conn->KeepAlive(session); usleep(2 * kTimeout * MICROSECONDS_IN_MILLISECONDS + MICROSECONDS_IN_SECOND); #endif } TEST_F(HeartBeatMonitorTest, TwoSessionsElapsed) { const uint32_t kSession1 = conn->AddNewSession(); const uint32_t kSession2 = conn->AddNewSession(); EXPECT_CALL(connection_handler_mock, CloseSession(_, kSession1, _)) .WillOnce(RemoveSession(conn, kSession1)); EXPECT_CALL(connection_handler_mock, CloseSession(_, kSession2, _)) .WillOnce(RemoveSession(conn, kSession2)); EXPECT_CALL(connection_handler_mock, CloseConnection(_)); EXPECT_CALL(connection_handler_mock, SendHeartBeat(_, kSession1)); EXPECT_CALL(connection_handler_mock, SendHeartBeat(_, kSession2)); conn->StartHeartBeat(kSession1); conn->StartHeartBeat(kSession2); testing::Mock::AsyncVerifyAndClearExpectations(2 * kTimeout * MICROSECONDS_IN_MILLISECONDS + MICROSECONDS_IN_SECOND); } TEST_F(HeartBeatMonitorTest, IncreaseHeartBeatTimeout) { const uint32_t kSession = conn->AddNewSession(); EXPECT_CALL(connection_handler_mock, CloseSession(_, _)).Times(0); EXPECT_CALL(connection_handler_mock, CloseConnection(_)).Times(0); EXPECT_CALL(connection_handler_mock, SendHeartBeat(_, _)).Times(0); const uint32_t kNewTimeout = kTimeout + MICROSECONDS_IN_MILLISECONDS; conn->StartHeartBeat(kSession); conn->SetHeartBeatTimeout(kNewTimeout, kSession); // new timeout greater by old timeout so mock object shouldn't be invoked testing::Mock::AsyncVerifyAndClearExpectations(kTimeout * MICROSECONDS_IN_MILLISECONDS); } TEST_F(HeartBeatMonitorTest, DecreaseHeartBeatTimeout) { const uint32_t kSession = conn->AddNewSession(); EXPECT_CALL(connection_handler_mock, CloseSession(_, kSession, _)) .WillOnce(RemoveSession(conn, kSession)); EXPECT_CALL(connection_handler_mock, CloseConnection(_)); EXPECT_CALL(connection_handler_mock, SendHeartBeat(_, kSession)); const uint32_t kNewTimeout = kTimeout - MICROSECONDS_IN_MILLISECONDS; conn->StartHeartBeat(kSession); conn->SetHeartBeatTimeout(kNewTimeout, kSession); // new timeout less than old timeout so mock object should be invoked testing::Mock::AsyncVerifyAndClearExpectations(kTimeout * 2 * MICROSECONDS_IN_MILLISECONDS); } } // namespace connection_handler_test } // namespace components } // namespace test
8,465
3,148
#include "symbol_table.hpp" #include <iostream> #include <cassert> Symbol_table::Symbol_table() { symbol_defs["SP"] = 0; symbol_defs["LCL"] = 1; symbol_defs["ARG"] = 2; symbol_defs["THIS"] = 3; symbol_defs["THAT"] = 4; symbol_defs["SCREEN"] = 16384; symbol_defs["KBD"] = 24576; symbol_defs["R0"] = 0; symbol_defs["R1"] = 1; symbol_defs["R2"] = 2; symbol_defs["R3"] = 3; symbol_defs["R4"] = 4; symbol_defs["R5"] = 5; symbol_defs["R6"] = 6; symbol_defs["R7"] = 7; symbol_defs["R8"] = 8; symbol_defs["R9"] = 9; symbol_defs["R10"] = 10; symbol_defs["R11"] = 11; symbol_defs["R12"] = 12; symbol_defs["R13"] = 13; symbol_defs["R14"] = 14; symbol_defs["R15"] = 15; } void Symbol_table::add_entry(std::string symbol, int address) { if (symbol_defs.find(symbol) != symbol_defs.end()) { std::cerr << "WARNING: refinition of '" << symbol << "'\n"; } symbol_defs[symbol] = address; } bool Symbol_table::contains(const std::string &symbol) const { return symbol_defs.find(symbol) != symbol_defs.end(); } int Symbol_table::get_address(const std::string &symbol) const { auto i = symbol_defs.find(symbol); assert(i != symbol_defs.end()); return i->second; } int Symbol_table::get_new_address() { int addr = addr_cnt++; if (addr >= 16384) { throw std::runtime_error{"Symbol_table::get_new_address(): all addresses used up"}; } return addr; }
1,369
634
// Copyright (c) 2019 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include "source/fuzz/transformation.h" #include <cassert> #include "source/util/make_unique.h" #include "transformation_add_constant_boolean.h" #include "transformation_add_constant_scalar.h" #include "transformation_add_dead_break.h" #include "transformation_add_dead_continue.h" #include "transformation_add_type_boolean.h" #include "transformation_add_type_float.h" #include "transformation_add_type_int.h" #include "transformation_add_type_pointer.h" #include "transformation_construct_composite.h" #include "transformation_copy_object.h" #include "transformation_move_block_down.h" #include "transformation_replace_boolean_constant_with_constant_binary.h" #include "transformation_replace_constant_with_uniform.h" #include "transformation_replace_id_with_synonym.h" #include "transformation_set_selection_control.h" #include "transformation_split_block.h" namespace spvtools { namespace fuzz { Transformation::~Transformation() = default; std::unique_ptr<Transformation> Transformation::FromMessage( const protobufs::Transformation& message) { switch (message.transformation_case()) { case protobufs::Transformation::TransformationCase::kAddConstantBoolean: return MakeUnique<TransformationAddConstantBoolean>( message.add_constant_boolean()); case protobufs::Transformation::TransformationCase::kAddConstantScalar: return MakeUnique<TransformationAddConstantScalar>( message.add_constant_scalar()); case protobufs::Transformation::TransformationCase::kAddDeadBreak: return MakeUnique<TransformationAddDeadBreak>(message.add_dead_break()); case protobufs::Transformation::TransformationCase::kAddDeadContinue: return MakeUnique<TransformationAddDeadContinue>( message.add_dead_continue()); case protobufs::Transformation::TransformationCase::kAddTypeBoolean: return MakeUnique<TransformationAddTypeBoolean>( message.add_type_boolean()); case protobufs::Transformation::TransformationCase::kAddTypeFloat: return MakeUnique<TransformationAddTypeFloat>(message.add_type_float()); case protobufs::Transformation::TransformationCase::kAddTypeInt: return MakeUnique<TransformationAddTypeInt>(message.add_type_int()); case protobufs::Transformation::TransformationCase::kAddTypePointer: return MakeUnique<TransformationAddTypePointer>( message.add_type_pointer()); case protobufs::Transformation::TransformationCase::kConstructComposite: return MakeUnique<TransformationConstructComposite>( message.construct_composite()); case protobufs::Transformation::TransformationCase::kCopyObject: return MakeUnique<TransformationCopyObject>(message.copy_object()); case protobufs::Transformation::TransformationCase::kMoveBlockDown: return MakeUnique<TransformationMoveBlockDown>(message.move_block_down()); case protobufs::Transformation::TransformationCase:: kReplaceBooleanConstantWithConstantBinary: return MakeUnique<TransformationReplaceBooleanConstantWithConstantBinary>( message.replace_boolean_constant_with_constant_binary()); case protobufs::Transformation::TransformationCase:: kReplaceConstantWithUniform: return MakeUnique<TransformationReplaceConstantWithUniform>( message.replace_constant_with_uniform()); case protobufs::Transformation::TransformationCase::kReplaceIdWithSynonym: return MakeUnique<TransformationReplaceIdWithSynonym>( message.replace_id_with_synonym()); case protobufs::Transformation::TransformationCase::kSetSelectionControl: return MakeUnique<TransformationSetSelectionControl>( message.set_selection_control()); case protobufs::Transformation::TransformationCase::kSplitBlock: return MakeUnique<TransformationSplitBlock>(message.split_block()); case protobufs::Transformation::TRANSFORMATION_NOT_SET: assert(false && "An unset transformation was encountered."); return nullptr; } assert(false && "Should be unreachable as all cases must be handled above."); return nullptr; } } // namespace fuzz } // namespace spvtools
4,752
1,318
#include "EntityManager.h" #include "../Console.h" #include "../Core/LocoFixedVector.hpp" #include "../Entities/Misc.h" #include "../Game.h" #include "../GameCommands/GameCommands.h" #include "../GameState.h" #include "../Interop/Interop.hpp" #include "../Localisation/StringIds.h" #include "../Map/Tile.h" #include "../OpenLoco.h" #include "../Vehicles/Vehicle.h" #include "EntityTweener.h" using namespace OpenLoco::Interop; namespace OpenLoco::EntityManager { constexpr size_t kSpatialEntityMapSize = (Map::map_pitch * Map::map_pitch) + 1; constexpr size_t kEntitySpatialIndexNull = kSpatialEntityMapSize - 1; static_assert(kSpatialEntityMapSize == 0x40001); static_assert(kEntitySpatialIndexNull == 0x40000); loco_global<EntityId[kSpatialEntityMapSize], 0x01025A8C> _entitySpatialIndex; loco_global<uint32_t, 0x01025A88> _entitySpatialCount; static auto& rawEntities() { return getGameState().entities; } static auto entities() { return FixedVector(rawEntities()); } static auto& rawListHeads() { return getGameState().entityListHeads; } static auto& rawListCounts() { return getGameState().entityListCounts; } // 0x0046FDFD void reset() { // Reset all entities to 0 std::fill(std::begin(rawEntities()), std::end(rawEntities()), Entity{}); // Reset all entity lists std::fill(std::begin(rawListCounts()), std::end(rawListCounts()), 0); std::fill(std::begin(rawListHeads()), std::end(rawListHeads()), EntityId::null); // Remake null entities (size maxNormalEntities) EntityBase* previous = nullptr; uint16_t id = 0; for (; id < Limits::maxNormalEntities; ++id) { auto& ent = rawEntities()[id]; ent.base_type = EntityBaseType::null; ent.id = EntityId(id); ent.next_thing_id = EntityId::null; ent.linkedListOffset = static_cast<uint8_t>(EntityListType::null) * 2; if (previous == nullptr) { ent.llPreviousId = EntityId::null; rawListHeads()[static_cast<uint8_t>(EntityListType::null)] = EntityId(id); } else { ent.llPreviousId = previous->id; previous->next_thing_id = EntityId(id); } previous = &ent; } rawListCounts()[static_cast<uint8_t>(EntityListType::null)] = Limits::maxNormalEntities; // Remake null money entities (size kMaxMoneyEntities) previous = nullptr; for (; id < Limits::kMaxEntities; ++id) { auto& ent = rawEntities()[id]; ent.base_type = EntityBaseType::null; ent.id = EntityId(id); ent.next_thing_id = EntityId::null; ent.linkedListOffset = static_cast<uint8_t>(EntityListType::nullMoney) * 2; if (previous == nullptr) { ent.llPreviousId = EntityId::null; rawListHeads()[static_cast<uint8_t>(EntityListType::nullMoney)] = EntityId(id); } else { ent.llPreviousId = previous->id; previous->next_thing_id = EntityId(id); } previous = &ent; } rawListCounts()[static_cast<uint8_t>(EntityListType::nullMoney)] = Limits::kMaxMoneyEntities; resetSpatialIndex(); EntityTweener::get().reset(); } EntityId firstId(EntityListType list) { return rawListHeads()[(size_t)list]; } uint16_t getListCount(const EntityListType list) { return rawListCounts()[static_cast<size_t>(list)]; } template<> Vehicles::VehicleHead* first() { return get<Vehicles::VehicleHead>(firstId(EntityListType::vehicleHead)); } template<> EntityBase* get(EntityId id) { EntityBase* result = nullptr; if (enumValue(id) < Limits::kMaxEntities) { return &rawEntities()[enumValue(id)]; } return result; } constexpr size_t getSpatialIndexOffset(const Map::Pos2& loc) { if (loc.x == Location::null) return kEntitySpatialIndexNull; const auto tileX = std::abs(loc.x) / Map::tile_size; const auto tileY = std::abs(loc.y) / Map::tile_size; if (tileX >= Map::map_pitch || tileY >= Map::map_pitch) return kEntitySpatialIndexNull; return (Map::map_pitch * tileX) + tileY; } EntityId firstQuadrantId(const Map::Pos2& loc) { auto index = getSpatialIndexOffset(loc); return _entitySpatialIndex[index]; } static void insertToSpatialIndex(EntityBase& entity, const size_t newIndex) { entity.nextQuadrantId = _entitySpatialIndex[newIndex]; _entitySpatialIndex[newIndex] = entity.id; } static void insertToSpatialIndex(EntityBase& entity) { const auto index = getSpatialIndexOffset(entity.position); insertToSpatialIndex(entity, index); } // 0x0046FF54 void resetSpatialIndex() { // Clear existing array std::fill(std::begin(_entitySpatialIndex), std::end(_entitySpatialIndex), EntityId::null); // Original filled an unreferenced array at 0x010A5A8E as well then overwrote part of it??? // Refill the index for (auto& ent : entities()) { insertToSpatialIndex(ent); } } // 0x0046FC57 void updateSpatialIndex() { for (auto& ent : entities()) { ent.moveTo(ent.position); } } static bool removeFromSpatialIndex(EntityBase& entity, const size_t index) { auto* quadId = &_entitySpatialIndex[index]; _entitySpatialCount = 0; while (enumValue(*quadId) < Limits::kMaxEntities) { auto* quadEnt = get<EntityBase>(*quadId); if (quadEnt == &entity) { *quadId = entity.nextQuadrantId; return true; } _entitySpatialCount++; if (_entitySpatialCount > Limits::kMaxEntities) { break; } quadId = &quadEnt->nextQuadrantId; } return false; } static bool removeFromSpatialIndex(EntityBase& entity) { const auto index = getSpatialIndexOffset(entity.position); return removeFromSpatialIndex(entity, index); } void moveSpatialEntry(EntityBase& entity, const Map::Pos3& loc) { const auto newIndex = getSpatialIndexOffset(loc); const auto oldIndex = getSpatialIndexOffset(entity.position); if (newIndex != oldIndex) { if (!removeFromSpatialIndex(entity, oldIndex)) { Console::log("Invalid quadrant ids... Reseting spatial index."); resetSpatialIndex(); moveSpatialEntry(entity, loc); return; } insertToSpatialIndex(entity, newIndex); } entity.position = loc; } static EntityBase* createEntity(EntityId id, EntityListType list) { auto* newEntity = get<EntityBase>(id); if (newEntity == nullptr) { Console::error("Tried to create invalid entity!"); return nullptr; } moveEntityToList(newEntity, list); newEntity->position = { Location::null, Location::null, 0 }; insertToSpatialIndex(*newEntity); newEntity->name = StringIds::empty_pop; newEntity->var_14 = 16; newEntity->var_09 = 20; newEntity->var_15 = 8; newEntity->var_0C = 0; newEntity->sprite_left = Location::null; return newEntity; } // 0x004700A5 EntityBase* createEntityMisc() { if (getListCount(EntityListType::misc) >= Limits::kMaxMiscEntities) { return nullptr; } if (getListCount(EntityListType::null) <= 0) { return nullptr; } auto newId = rawListHeads()[static_cast<uint8_t>(EntityListType::null)]; return createEntity(newId, EntityListType::misc); } // 0x0047011C EntityBase* createEntityMoney() { if (getListCount(EntityListType::nullMoney) <= 0) { return nullptr; } auto newId = rawListHeads()[static_cast<uint8_t>(EntityListType::nullMoney)]; return createEntity(newId, EntityListType::misc); } // 0x00470039 EntityBase* createEntityVehicle() { if (getListCount(EntityListType::null) <= 0) { return nullptr; } auto newId = rawListHeads()[static_cast<uint8_t>(EntityListType::null)]; return createEntity(newId, EntityListType::vehicle); } // 0x0047024A void freeEntity(EntityBase* const entity) { EntityTweener::get().removeEntity(entity); auto list = enumValue(entity->id) < 19800 ? EntityListType::null : EntityListType::nullMoney; moveEntityToList(entity, list); StringManager::emptyUserString(entity->name); entity->base_type = EntityBaseType::null; if (!removeFromSpatialIndex(*entity)) { Console::log("Invalid quadrant ids... Reseting spatial index."); resetSpatialIndex(); } } // 0x004A8826 void updateVehicles() { if (Game::hasFlags(1u << 0) && !isEditorMode()) { for (auto v : VehicleList()) { v->updateVehicle(); } } } // 0x004402F4 void updateMiscEntities() { if (getGameState().flags & (1u << 0)) { for (auto* misc : EntityList<EntityListIterator<MiscBase>, EntityListType::misc>()) { misc->update(); } } } // 0x0047019F void moveEntityToList(EntityBase* const entity, const EntityListType list) { auto newListOffset = static_cast<uint8_t>(list) * 2; if (entity->linkedListOffset == newListOffset) { return; } auto curList = entity->linkedListOffset / 2; auto nextId = entity->next_thing_id; auto previousId = entity->llPreviousId; // Unlink previous entity from this entity if (previousId == EntityId::null) { rawListHeads()[curList] = nextId; } else { auto* previousEntity = get<EntityBase>(previousId); if (previousEntity == nullptr) { Console::error("Invalid previous entity id. Entity linked list corrupted?"); } else { previousEntity->next_thing_id = nextId; } } // Unlink next entity from this entity if (nextId != EntityId::null) { auto* nextEntity = get<EntityBase>(nextId); if (nextEntity == nullptr) { Console::error("Invalid next entity id. Entity linked list corrupted?"); } else { nextEntity->llPreviousId = previousId; } } entity->llPreviousId = EntityId::null; entity->linkedListOffset = newListOffset; entity->next_thing_id = rawListHeads()[static_cast<uint8_t>(list)]; rawListHeads()[static_cast<uint8_t>(list)] = entity->id; // Link next entity to this entity if (entity->next_thing_id != EntityId::null) { auto* nextEntity = get<EntityBase>(entity->next_thing_id); if (nextEntity == nullptr) { Console::error("Invalid next entity id. Entity linked list corrupted?"); } else { nextEntity->llPreviousId = entity->id; } } rawListCounts()[curList]--; rawListCounts()[static_cast<uint8_t>(list)]++; } // 0x00470188 bool checkNumFreeEntities(const size_t numNewEntities) { if (EntityManager::getListCount(EntityManager::EntityListType::null) <= numNewEntities) { GameCommands::setErrorText(StringIds::too_many_objects_in_game); return false; } return true; } static void zeroEntity(EntityBase* ent) { auto next = ent->next_thing_id; auto previous = ent->llPreviousId; auto id = ent->id; auto llOffset = ent->linkedListOffset; std::fill_n(reinterpret_cast<uint8_t*>(ent), sizeof(Entity), 0); ent->base_type = EntityBaseType::null; ent->next_thing_id = next; ent->llPreviousId = previous; ent->id = id; ent->linkedListOffset = llOffset; } // 0x0046FED5 void zeroUnused() { for (auto* ent : EntityList<EntityListIterator<EntityBase>, EntityListType::null>()) { zeroEntity(ent); } for (auto* ent : EntityList<EntityListIterator<EntityBase>, EntityListType::nullMoney>()) { zeroEntity(ent); } } }
13,186
4,100
/** Copyright (c) 2006-2008 by Matjaz Kovac Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. \file LayoutView.cpp \brief Auto-layout View \author M.Kovac Depends on LayoutPlan.cpp */ #include <LayoutView.h> LayoutView::LayoutView(BRect frame, const char *name, LayoutPlan *layout, uint32 resize, uint32 flags): BView(frame, name, resize, flags), fLayout(layout), fDefaultHint(LAYOUT_HINT_NONE), fPadding(0,0,0,0) { } LayoutView::~LayoutView() { delete fLayout; } /** */ void LayoutView::AllAttached() { Arrange(); } /** Frame() changed. */ void LayoutView::FrameResized(float width, float height) { Arrange(); } LayoutPlan& LayoutView::Layout() { return *fLayout; } void LayoutView::SetDefaultHint(uint32 hint) { fDefaultHint = hint; } void LayoutView::SetPadding(float left, float top, float right, float bottom) { fPadding.Set(left, top, right, bottom); } /** Lays out child views. */ void LayoutView::Arrange() { if (fLayout) { fLayout->Frame() = Bounds(); fLayout->Frame().left += fPadding.left; fLayout->Frame().right -= fPadding.right; fLayout->Frame().top += fPadding.top; fLayout->Frame().bottom -= fPadding.bottom; fLayout->Reset(); BView *child; for (int32 i = 0; (child = ChildAt(i)); i++) { child->ResizeToPreferred(); uint hint = fDefaultHint; if (i == CountChildren()-1) // may trigger some special processing hint |= LAYOUT_HINT_LAST; BRect frame = fLayout->Next(child->Frame(), hint); child->MoveTo(frame.LeftTop()); child->ResizeTo(frame.Width(), frame.Height()); } } }
2,550
938
// Copyright 2013 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 "base/file_util.h" #include "base/files/scoped_temp_dir.h" #include "base/message_loop/message_loop.h" #include "base/run_loop.h" #include "chrome/browser/extensions/api/image_writer_private/error_messages.h" #include "chrome/browser/extensions/api/image_writer_private/operation.h" #include "chrome/browser/extensions/api/image_writer_private/operation_manager.h" #include "chrome/browser/extensions/api/image_writer_private/test_utils.h" #include "chrome/test/base/testing_profile.h" #include "content/public/browser/browser_thread.h" #include "content/public/test/test_browser_thread_bundle.h" #include "testing/gmock/include/gmock/gmock.h" #include "testing/gtest/include/gtest/gtest.h" #include "third_party/zlib/google/zip.h" namespace extensions { namespace image_writer { namespace { using testing::_; using testing::AnyNumber; using testing::AtLeast; using testing::Gt; using testing::Lt; // This class gives us a generic Operation with the ability to set or inspect // the current path to the image file. class OperationForTest : public Operation { public: OperationForTest(base::WeakPtr<OperationManager> manager_, const ExtensionId& extension_id, const std::string& device_path) : Operation(manager_, extension_id, device_path) {} virtual void StartImpl() OVERRIDE {} // Expose internal stages for testing. void Unzip(const base::Closure& continuation) { Operation::Unzip(continuation); } void Write(const base::Closure& continuation) { Operation::Write(continuation); } void VerifyWrite(const base::Closure& continuation) { Operation::VerifyWrite(continuation); } // Helpers to set-up state for intermediate stages. void SetImagePath(const base::FilePath image_path) { image_path_ = image_path; } base::FilePath GetImagePath() { return image_path_; } private: virtual ~OperationForTest() {}; }; class ImageWriterOperationTest : public ImageWriterUnitTestBase { protected: ImageWriterOperationTest() : profile_(new TestingProfile), manager_(profile_.get()) {} virtual void SetUp() OVERRIDE { ImageWriterUnitTestBase::SetUp(); // Create the zip file. base::FilePath image_dir = test_utils_.GetTempDir().AppendASCII("zip"); ASSERT_TRUE(base::CreateDirectory(image_dir)); ASSERT_TRUE(base::CreateTemporaryFileInDir(image_dir, &image_path_)); test_utils_.FillFile(image_path_, kImagePattern, kTestFileSize); zip_file_ = test_utils_.GetTempDir().AppendASCII("test_image.zip"); ASSERT_TRUE(zip::Zip(image_dir, zip_file_, true)); // Operation setup. operation_ = new OperationForTest(manager_.AsWeakPtr(), kDummyExtensionId, test_utils_.GetDevicePath().AsUTF8Unsafe()); operation_->SetImagePath(test_utils_.GetImagePath()); } virtual void TearDown() OVERRIDE { // Ensure all callbacks have been destroyed and cleanup occurs. operation_->Cancel(); ImageWriterUnitTestBase::TearDown(); } base::FilePath image_path_; base::FilePath zip_file_; scoped_ptr<TestingProfile> profile_; MockOperationManager manager_; scoped_refptr<OperationForTest> operation_; }; } // namespace // Unizpping a non-zip should do nothing. TEST_F(ImageWriterOperationTest, UnzipNonZipFile) { EXPECT_CALL(manager_, OnProgress(kDummyExtensionId, _, _)).Times(0); EXPECT_CALL(manager_, OnError(kDummyExtensionId, _, _, _)).Times(0); EXPECT_CALL(manager_, OnProgress(kDummyExtensionId, _, _)).Times(0); EXPECT_CALL(manager_, OnComplete(kDummyExtensionId)).Times(0); operation_->Start(); content::BrowserThread::PostTask( content::BrowserThread::FILE, FROM_HERE, base::Bind( &OperationForTest::Unzip, operation_, base::Bind(&base::DoNothing))); base::RunLoop().RunUntilIdle(); } TEST_F(ImageWriterOperationTest, UnzipZipFile) { EXPECT_CALL(manager_, OnError(kDummyExtensionId, _, _, _)).Times(0); EXPECT_CALL(manager_, OnProgress(kDummyExtensionId, image_writer_api::STAGE_UNZIP, _)) .Times(AtLeast(1)); EXPECT_CALL(manager_, OnProgress(kDummyExtensionId, image_writer_api::STAGE_UNZIP, 0)) .Times(AtLeast(1)); EXPECT_CALL(manager_, OnProgress(kDummyExtensionId, image_writer_api::STAGE_UNZIP, 100)) .Times(AtLeast(1)); operation_->SetImagePath(zip_file_); operation_->Start(); content::BrowserThread::PostTask( content::BrowserThread::FILE, FROM_HERE, base::Bind( &OperationForTest::Unzip, operation_, base::Bind(&base::DoNothing))); base::RunLoop().RunUntilIdle(); EXPECT_TRUE(base::ContentsEqual(image_path_, operation_->GetImagePath())); } #if defined(OS_LINUX) TEST_F(ImageWriterOperationTest, WriteImageToDevice) { EXPECT_CALL(manager_, OnError(kDummyExtensionId, _, _, _)).Times(0); EXPECT_CALL(manager_, OnProgress(kDummyExtensionId, image_writer_api::STAGE_WRITE, _)) .Times(AtLeast(1)); EXPECT_CALL(manager_, OnProgress(kDummyExtensionId, image_writer_api::STAGE_WRITE, 0)) .Times(AtLeast(1)); EXPECT_CALL(manager_, OnProgress(kDummyExtensionId, image_writer_api::STAGE_WRITE, 100)) .Times(AtLeast(1)); operation_->Start(); content::BrowserThread::PostTask( content::BrowserThread::FILE, FROM_HERE, base::Bind( &OperationForTest::Write, operation_, base::Bind(&base::DoNothing))); base::RunLoop().RunUntilIdle(); #if !defined(OS_CHROMEOS) test_utils_.GetUtilityClient()->Progress(0); test_utils_.GetUtilityClient()->Progress(kTestFileSize / 2); test_utils_.GetUtilityClient()->Progress(kTestFileSize); test_utils_.GetUtilityClient()->Success(); base::RunLoop().RunUntilIdle(); #endif } #endif #if !defined(OS_CHROMEOS) // Chrome OS doesn't support verification in the ImageBurner, so these two tests // are skipped. TEST_F(ImageWriterOperationTest, VerifyFileSuccess) { EXPECT_CALL(manager_, OnError(kDummyExtensionId, _, _, _)).Times(0); EXPECT_CALL( manager_, OnProgress(kDummyExtensionId, image_writer_api::STAGE_VERIFYWRITE, _)) .Times(AtLeast(1)); EXPECT_CALL( manager_, OnProgress(kDummyExtensionId, image_writer_api::STAGE_VERIFYWRITE, 0)) .Times(AtLeast(1)); EXPECT_CALL( manager_, OnProgress(kDummyExtensionId, image_writer_api::STAGE_VERIFYWRITE, 100)) .Times(AtLeast(1)); test_utils_.FillFile( test_utils_.GetDevicePath(), kImagePattern, kTestFileSize); operation_->Start(); content::BrowserThread::PostTask(content::BrowserThread::FILE, FROM_HERE, base::Bind(&OperationForTest::VerifyWrite, operation_, base::Bind(&base::DoNothing))); base::RunLoop().RunUntilIdle(); #if !defined(OS_CHROMEOS) test_utils_.GetUtilityClient()->Progress(0); test_utils_.GetUtilityClient()->Progress(kTestFileSize / 2); test_utils_.GetUtilityClient()->Progress(kTestFileSize); test_utils_.GetUtilityClient()->Success(); #endif base::RunLoop().RunUntilIdle(); } TEST_F(ImageWriterOperationTest, VerifyFileFailure) { EXPECT_CALL( manager_, OnProgress(kDummyExtensionId, image_writer_api::STAGE_VERIFYWRITE, _)) .Times(AnyNumber()); EXPECT_CALL( manager_, OnProgress(kDummyExtensionId, image_writer_api::STAGE_VERIFYWRITE, 100)) .Times(0); EXPECT_CALL(manager_, OnComplete(kDummyExtensionId)).Times(0); EXPECT_CALL( manager_, OnError(kDummyExtensionId, image_writer_api::STAGE_VERIFYWRITE, _, _)) .Times(1); test_utils_.FillFile( test_utils_.GetDevicePath(), kDevicePattern, kTestFileSize); operation_->Start(); content::BrowserThread::PostTask(content::BrowserThread::FILE, FROM_HERE, base::Bind(&OperationForTest::VerifyWrite, operation_, base::Bind(&base::DoNothing))); base::RunLoop().RunUntilIdle(); test_utils_.GetUtilityClient()->Progress(0); test_utils_.GetUtilityClient()->Progress(kTestFileSize / 2); test_utils_.GetUtilityClient()->Error(error::kVerificationFailed); base::RunLoop().RunUntilIdle(); } #endif // Tests that on creation the operation_ has the expected state. TEST_F(ImageWriterOperationTest, Creation) { EXPECT_EQ(0, operation_->GetProgress()); EXPECT_EQ(image_writer_api::STAGE_UNKNOWN, operation_->GetStage()); } } // namespace image_writer } // namespace extensions
8,889
2,872
#include "copycountcontainers.h" #include "futurebasetest.h" #ifdef ASYNQRO_QT_SUPPORT # include <QLinkedList> # include <QList> # include <QVector> #endif #include <list> #include <vector> using namespace std::chrono_literals; template <typename, typename> struct InnerTypeChanger; template <template <typename...> typename C, typename NewType, typename... Args> struct InnerTypeChanger<C<Args...>, NewType> { using type = C<NewType>; }; template <typename Sequence> class FutureSequenceWithFailuresTest : public FutureBaseTest { public: using Source = typename InnerTypeChanger<Sequence, TestFuture<int>>::type; static inline int N = 100; }; template <typename Sequence> class FutureMoveSequenceWithFailuresTest : public FutureBaseTest { public: using Source = typename InnerTypeChanger<Sequence, TestFuture<int>>::type; static inline int N = 100; protected: void SetUp() override { FutureBaseTest::SetUp(); Source::copyCounter = 0; Source::createCounter = 0; } }; using SequenceTypes = ::testing::Types<std::vector<int>, std::list<int> #ifdef ASYNQRO_QT_SUPPORT , QVector<int>, QList<int>, QLinkedList<int> #endif >; using CopyCountSequenceTypes = ::testing::Types<CopyCountVector<int>, CopyCountList<int> #ifdef ASYNQRO_QT_SUPPORT , CopyCountQVector<int>, CopyCountQList<int>, CopyCountQLinkedList<int> #endif >; TYPED_TEST_SUITE(FutureSequenceWithFailuresTest, SequenceTypes); template <typename TestFixture, template <typename...> typename Container, typename Func> void sequenceHelper(Func &&sequencer) { std::vector<TestPromise<int>> promises; for (int i = 0; i < TestFixture::N; ++i) asynqro::traverse::detail::containers::add(promises, TestPromise<int>()); typename TestFixture::Source futures = traverse::map(promises, [](const auto &p) { return p.future(); }, typename TestFixture::Source()); auto sequencedFuture = sequencer(futures); int i = 0; for (auto it = futures.cbegin(); it != futures.cend(); ++it, ++i) EXPECT_FALSE(it->isCompleted()) << i; for (size_t i = 0; i < TestFixture::N; ++i) { EXPECT_FALSE(sequencedFuture.isCompleted()) << i; promises[i].success(i * 2); } ASSERT_TRUE(sequencedFuture.isCompleted()); EXPECT_TRUE(sequencedFuture.isSucceeded()); EXPECT_FALSE(sequencedFuture.isFailed()); auto result = sequencedFuture.result().first; ASSERT_EQ(TestFixture::N, result.size()); traverse::map(result, [](auto index, auto value) { EXPECT_EQ(index * 2, value) << index; return true; }, std::set<bool>()); auto failures = sequencedFuture.result().second; ASSERT_TRUE(failures.empty()); static_assert(detail::IsSpecialization_V<std::decay_t<decltype(result)>, Container>); static_assert(detail::IsSpecialization_V<std::decay_t<decltype(failures)>, Container>); } TYPED_TEST(FutureSequenceWithFailuresTest, sequence) { sequenceHelper<TestFixture, std::unordered_map>( [](const typename TestFixture::Source &futures) { return TestFuture<int>::sequenceWithFailures(futures); }); } TYPED_TEST(FutureSequenceWithFailuresTest, sequenceMap) { sequenceHelper<TestFixture, std::map>([](const typename TestFixture::Source &futures) { return TestFuture<int>::sequenceWithFailures<std::map>(futures); }); } #ifdef ASYNQRO_QT_SUPPORT TYPED_TEST(FutureSequenceWithFailuresTest, sequenceQMap) { sequenceHelper<TestFixture, QMap>([](const typename TestFixture::Source &futures) { return TestFuture<int>::sequenceWithFailures<QMap>(futures); }); } TYPED_TEST(FutureSequenceWithFailuresTest, sequenceQHash) { sequenceHelper<TestFixture, QHash>([](const typename TestFixture::Source &futures) { return TestFuture<int>::sequenceWithFailures<QHash>(futures); }); } #endif template <typename TestFixture, template <typename...> typename Container, typename Func> void sequenceNegativeHelper(Func &&sequencer) { std::vector<TestPromise<int>> promises; for (int i = 0; i < TestFixture::N; ++i) asynqro::traverse::detail::containers::add(promises, TestPromise<int>()); typename TestFixture::Source futures = traverse::map(promises, [](const auto &p) { return p.future(); }, typename TestFixture::Source()); auto sequencedFuture = sequencer(futures); int i = 0; for (auto it = futures.cbegin(); it != futures.cend(); ++it, ++i) EXPECT_FALSE(it->isCompleted()) << i; for (size_t i = 0; i < TestFixture::N; ++i) { EXPECT_FALSE(sequencedFuture.isCompleted()) << i; if (i == TestFixture::N - 2 || i == TestFixture::N - 4) promises[i].failure("failed"); else promises[i].success(i * 2); } ASSERT_TRUE(sequencedFuture.isCompleted()); EXPECT_TRUE(sequencedFuture.isSucceeded()); EXPECT_FALSE(sequencedFuture.isFailed()); auto result = sequencedFuture.result().first; ASSERT_EQ(TestFixture::N - 2, result.size()); ASSERT_FALSE(result.count(TestFixture::N - 2)); ASSERT_FALSE(result.count(TestFixture::N - 4)); traverse::map(result, [](auto index, auto value) { EXPECT_EQ(index * 2, value) << index; return true; }, std::set<bool>()); auto failures = sequencedFuture.result().second; ASSERT_EQ(2, failures.size()); ASSERT_TRUE(failures.count(TestFixture::N - 4)); EXPECT_EQ("failed", failures[TestFixture::N - 4]); ASSERT_TRUE(failures.count(TestFixture::N - 2)); EXPECT_EQ("failed", failures[TestFixture::N - 2]); static_assert(detail::IsSpecialization_V<std::decay_t<decltype(result)>, Container>); static_assert(detail::IsSpecialization_V<std::decay_t<decltype(failures)>, Container>); } TYPED_TEST(FutureSequenceWithFailuresTest, sequenceNegative) { sequenceNegativeHelper<TestFixture, std::unordered_map>( [](const typename TestFixture::Source &futures) { return TestFuture<int>::sequenceWithFailures(futures); }); } TYPED_TEST(FutureSequenceWithFailuresTest, sequenceNegativeMap) { sequenceNegativeHelper<TestFixture, std::map>([](const typename TestFixture::Source &futures) { return TestFuture<int>::sequenceWithFailures<std::map>(futures); }); } #ifdef ASYNQRO_QT_SUPPORT TYPED_TEST(FutureSequenceWithFailuresTest, sequenceNegativeQMap) { sequenceNegativeHelper<TestFixture, QMap>([](const typename TestFixture::Source &futures) { return TestFuture<int>::sequenceWithFailures<QMap>(futures); }); } TYPED_TEST(FutureSequenceWithFailuresTest, sequenceNegativeQHash) { sequenceNegativeHelper<TestFixture, QHash>([](const typename TestFixture::Source &futures) { return TestFuture<int>::sequenceWithFailures<QHash>(futures); }); } #endif template <typename TestFixture, template <typename...> typename Container, typename Func> void sequenceAllNegativeHelper(Func &&sequencer) { std::vector<TestPromise<int>> promises; for (int i = 0; i < TestFixture::N; ++i) asynqro::traverse::detail::containers::add(promises, TestPromise<int>()); typename TestFixture::Source futures = traverse::map(promises, [](const auto &p) { return p.future(); }, typename TestFixture::Source()); auto sequencedFuture = sequencer(futures); int i = 0; for (auto it = futures.cbegin(); it != futures.cend(); ++it, ++i) EXPECT_FALSE(it->isCompleted()) << i; for (size_t i = 0; i < TestFixture::N; ++i) { EXPECT_FALSE(sequencedFuture.isCompleted()) << i; if (i == TestFixture::N - 2) promises[i].failure("other"); else promises[i].failure("failed"); } ASSERT_TRUE(sequencedFuture.isCompleted()); EXPECT_TRUE(sequencedFuture.isSucceeded()); EXPECT_FALSE(sequencedFuture.isFailed()); auto result = sequencedFuture.result().first; ASSERT_TRUE(result.empty()); auto failures = sequencedFuture.result().second; ASSERT_EQ(TestFixture::N, failures.size()); traverse::map(failures, [](auto index, const std::string &value) { if (index == TestFixture::N - 2) EXPECT_EQ("other", value) << index; else EXPECT_EQ("failed", value) << index; return true; }, std::set<bool>()); static_assert(detail::IsSpecialization_V<std::decay_t<decltype(result)>, Container>); static_assert(detail::IsSpecialization_V<std::decay_t<decltype(failures)>, Container>); } TYPED_TEST(FutureSequenceWithFailuresTest, sequenceAllNegative) { sequenceAllNegativeHelper<TestFixture, std::unordered_map>( [](const typename TestFixture::Source &futures) { return TestFuture<int>::sequenceWithFailures(futures); }); } TYPED_TEST(FutureSequenceWithFailuresTest, sequenceAllNegativeMap) { sequenceAllNegativeHelper<TestFixture, std::map>([](const typename TestFixture::Source &futures) { return TestFuture<int>::sequenceWithFailures<std::map>(futures); }); } #ifdef ASYNQRO_QT_SUPPORT TYPED_TEST(FutureSequenceWithFailuresTest, sequenceAllNegativeQMap) { sequenceAllNegativeHelper<TestFixture, QMap>([](const typename TestFixture::Source &futures) { return TestFuture<int>::sequenceWithFailures<QMap>(futures); }); } TYPED_TEST(FutureSequenceWithFailuresTest, sequenceAllNegativeQHash) { sequenceAllNegativeHelper<TestFixture, QHash>([](const typename TestFixture::Source &futures) { return TestFuture<int>::sequenceWithFailures<QHash>(futures); }); } #endif TYPED_TEST(FutureSequenceWithFailuresTest, sequenceEmpty) { typename TestFixture::Source futures; auto sequencedFuture = TestFuture<int>::sequenceWithFailures(futures); ASSERT_TRUE(sequencedFuture.isCompleted()); EXPECT_TRUE(sequencedFuture.isSucceeded()); EXPECT_FALSE(sequencedFuture.isFailed()); auto result = sequencedFuture.result(); EXPECT_TRUE(result.first.empty()); EXPECT_TRUE(result.second.empty()); static_assert(detail::IsSpecialization_V<std::decay_t<decltype(result.first)>, std::unordered_map>); static_assert(detail::IsSpecialization_V<std::decay_t<decltype(result.second)>, std::unordered_map>); } TYPED_TEST_SUITE(FutureMoveSequenceWithFailuresTest, CopyCountSequenceTypes); template <typename TestFixture, template <typename...> typename Container, typename Func> void sequenceMoveHelper(Func &&sequencer) { using Result = std::decay_t<decltype(sequencer(typename TestFixture::Source()).resultRef().first)>; using FailuresResult = std::decay_t<decltype(sequencer(typename TestFixture::Source()).resultRef().first)>; Result::copyCounter = 0; Result::createCounter = 0; FailuresResult::copyCounter = 0; FailuresResult::createCounter = 0; std::vector<TestPromise<int>> promises; for (int i = 0; i < TestFixture::N; ++i) asynqro::traverse::detail::containers::add(promises, TestPromise<int>()); auto sequencedFuture = sequencer( traverse::map(promises, [](const auto &p) { return p.future(); }, std::move(typename TestFixture::Source()))); for (size_t i = 0; i < TestFixture::N; ++i) { EXPECT_FALSE(sequencedFuture.isCompleted()) << i; promises[i].success(i * 2); } ASSERT_TRUE(sequencedFuture.isCompleted()); EXPECT_TRUE(sequencedFuture.isSucceeded()); EXPECT_FALSE(sequencedFuture.isFailed()); const auto &result = sequencedFuture.resultRef().first; ASSERT_EQ(TestFixture::N, result.size()); traverse::map(result, [](auto index, auto value) { EXPECT_EQ(index * 2, value) << index; return true; }, std::set<bool>()); const auto &failures = sequencedFuture.resultRef().second; ASSERT_TRUE(failures.empty()); EXPECT_EQ(0, Result::copyCounter); EXPECT_EQ(1, Result::createCounter); EXPECT_EQ(0, FailuresResult::copyCounter); EXPECT_EQ(1, FailuresResult::createCounter); EXPECT_EQ(0, TestFixture::Source::copyCounter); EXPECT_EQ(1, TestFixture::Source::createCounter); static_assert(detail::IsSpecialization_V<std::decay_t<decltype(result)>, Container>); static_assert(detail::IsSpecialization_V<std::decay_t<decltype(failures)>, Container>); } TYPED_TEST(FutureMoveSequenceWithFailuresTest, sequence) { sequenceMoveHelper<TestFixture, CopyCountUnorderedMap>([](typename TestFixture::Source &&futures) { return TestFuture<int>::sequenceWithFailures<CopyCountUnorderedMap>(std::move(futures)); }); } TYPED_TEST(FutureMoveSequenceWithFailuresTest, sequenceMap) { sequenceMoveHelper<TestFixture, CopyCountMap>([](typename TestFixture::Source &&futures) { return TestFuture<int>::sequenceWithFailures<CopyCountMap>(std::move(futures)); }); } #ifdef ASYNQRO_QT_SUPPORT TYPED_TEST(FutureMoveSequenceWithFailuresTest, sequenceQMap) { sequenceMoveHelper<TestFixture, CopyCountQMap>([](typename TestFixture::Source &&futures) { return TestFuture<int>::sequenceWithFailures<CopyCountQMap>(std::move(futures)); }); } TYPED_TEST(FutureMoveSequenceWithFailuresTest, sequenceQHash) { sequenceMoveHelper<TestFixture, CopyCountQHash>([](typename TestFixture::Source &&futures) { return TestFuture<int>::sequenceWithFailures<CopyCountQHash>(std::move(futures)); }); } #endif template <typename TestFixture, template <typename...> typename Container, typename Func> void sequenceNegativeMoveHelper(Func &&sequencer) { using Result = std::decay_t<decltype(sequencer(typename TestFixture::Source()).resultRef().first)>; using FailuresResult = std::decay_t<decltype(sequencer(typename TestFixture::Source()).resultRef().first)>; Result::copyCounter = 0; Result::createCounter = 0; FailuresResult::copyCounter = 0; FailuresResult::createCounter = 0; std::vector<TestPromise<int>> promises; for (int i = 0; i < TestFixture::N; ++i) asynqro::traverse::detail::containers::add(promises, TestPromise<int>()); auto sequencedFuture = sequencer( traverse::map(promises, [](const auto &p) { return p.future(); }, std::move(typename TestFixture::Source()))); for (size_t i = 0; i < TestFixture::N; ++i) { EXPECT_FALSE(sequencedFuture.isCompleted()) << i; if (i == TestFixture::N - 2 || i == TestFixture::N - 4) promises[i].failure("failed"); else promises[i].success(i * 2); } ASSERT_TRUE(sequencedFuture.isCompleted()); EXPECT_TRUE(sequencedFuture.isSucceeded()); EXPECT_FALSE(sequencedFuture.isFailed()); const auto &result = sequencedFuture.resultRef().first; ASSERT_EQ(TestFixture::N - 2, result.size()); ASSERT_FALSE(result.count(TestFixture::N - 2)); ASSERT_FALSE(result.count(TestFixture::N - 4)); traverse::map(result, [](auto index, auto value) { EXPECT_EQ(index * 2, value) << index; return true; }, std::set<bool>()); const auto &failures = sequencedFuture.resultRef().second; ASSERT_EQ(2, failures.size()); ASSERT_TRUE(failures.count(TestFixture::N - 4)); EXPECT_EQ("failed", failures[TestFixture::N - 4]); ASSERT_TRUE(failures.count(TestFixture::N - 2)); EXPECT_EQ("failed", failures[TestFixture::N - 2]); EXPECT_EQ(0, Result::copyCounter); EXPECT_EQ(1, Result::createCounter); EXPECT_EQ(0, FailuresResult::copyCounter); EXPECT_EQ(1, FailuresResult::createCounter); EXPECT_EQ(0, TestFixture::Source::copyCounter); EXPECT_EQ(1, TestFixture::Source::createCounter); static_assert(detail::IsSpecialization_V<std::decay_t<decltype(result)>, Container>); static_assert(detail::IsSpecialization_V<std::decay_t<decltype(failures)>, Container>); } TYPED_TEST(FutureMoveSequenceWithFailuresTest, sequenceNegative) { sequenceNegativeMoveHelper<TestFixture, CopyCountUnorderedMap>([](typename TestFixture::Source &&futures) { return TestFuture<int>::sequenceWithFailures<CopyCountUnorderedMap>(std::move(futures)); }); } TYPED_TEST(FutureMoveSequenceWithFailuresTest, sequenceNegativeMap) { sequenceNegativeMoveHelper<TestFixture, CopyCountMap>([](typename TestFixture::Source &&futures) { return TestFuture<int>::sequenceWithFailures<CopyCountMap>(std::move(futures)); }); } #ifdef ASYNQRO_QT_SUPPORT TYPED_TEST(FutureMoveSequenceWithFailuresTest, sequenceNegativeQMap) { sequenceNegativeMoveHelper<TestFixture, CopyCountQMap>([](typename TestFixture::Source &&futures) { return TestFuture<int>::sequenceWithFailures<CopyCountQMap>(std::move(futures)); }); } TYPED_TEST(FutureMoveSequenceWithFailuresTest, sequenceNegativeQHash) { sequenceNegativeMoveHelper<TestFixture, CopyCountQHash>([](typename TestFixture::Source &&futures) { return TestFuture<int>::sequenceWithFailures<CopyCountQHash>(std::move(futures)); }); } #endif template <typename TestFixture, template <typename...> typename Container, typename Func> void sequenceAllNegativeMoveHelper(Func &&sequencer) { using Result = std::decay_t<decltype(sequencer(typename TestFixture::Source()).resultRef().first)>; using FailuresResult = std::decay_t<decltype(sequencer(typename TestFixture::Source()).resultRef().first)>; Result::copyCounter = 0; Result::createCounter = 0; FailuresResult::copyCounter = 0; FailuresResult::createCounter = 0; std::vector<TestPromise<int>> promises; for (int i = 0; i < TestFixture::N; ++i) asynqro::traverse::detail::containers::add(promises, TestPromise<int>()); auto sequencedFuture = sequencer( traverse::map(promises, [](const auto &p) { return p.future(); }, std::move(typename TestFixture::Source()))); for (size_t i = 0; i < TestFixture::N; ++i) { EXPECT_FALSE(sequencedFuture.isCompleted()) << i; if (i == TestFixture::N - 2) promises[i].failure("other"); else promises[i].failure("failed"); } ASSERT_TRUE(sequencedFuture.isCompleted()); EXPECT_TRUE(sequencedFuture.isSucceeded()); EXPECT_FALSE(sequencedFuture.isFailed()); const auto &result = sequencedFuture.resultRef().first; ASSERT_TRUE(result.empty()); const auto &failures = sequencedFuture.resultRef().second; ASSERT_EQ(TestFixture::N, failures.size()); traverse::map(failures, [](auto index, const std::string &value) { if (index == TestFixture::N - 2) EXPECT_EQ("other", value) << index; else EXPECT_EQ("failed", value) << index; return true; }, std::set<bool>()); EXPECT_EQ(0, Result::copyCounter); EXPECT_EQ(1, Result::createCounter); EXPECT_EQ(0, FailuresResult::copyCounter); EXPECT_EQ(1, FailuresResult::createCounter); EXPECT_EQ(0, TestFixture::Source::copyCounter); EXPECT_EQ(1, TestFixture::Source::createCounter); static_assert(detail::IsSpecialization_V<std::decay_t<decltype(result)>, Container>); static_assert(detail::IsSpecialization_V<std::decay_t<decltype(failures)>, Container>); } TYPED_TEST(FutureMoveSequenceWithFailuresTest, sequenceAllNegative) { sequenceAllNegativeMoveHelper<TestFixture, CopyCountUnorderedMap>([](typename TestFixture::Source &&futures) { return TestFuture<int>::sequenceWithFailures<CopyCountUnorderedMap>(std::move(futures)); }); } TYPED_TEST(FutureMoveSequenceWithFailuresTest, sequenceAllNegativeMap) { sequenceAllNegativeMoveHelper<TestFixture, CopyCountMap>([](typename TestFixture::Source &&futures) { return TestFuture<int>::sequenceWithFailures<CopyCountMap>(std::move(futures)); }); } #ifdef ASYNQRO_QT_SUPPORT TYPED_TEST(FutureMoveSequenceWithFailuresTest, sequenceAllNegativeQMap) { sequenceAllNegativeMoveHelper<TestFixture, CopyCountQMap>([](typename TestFixture::Source &&futures) { return TestFuture<int>::sequenceWithFailures<CopyCountQMap>(std::move(futures)); }); } TYPED_TEST(FutureMoveSequenceWithFailuresTest, sequenceAllNegativeQHash) { sequenceAllNegativeMoveHelper<TestFixture, CopyCountQHash>([](typename TestFixture::Source &&futures) { return TestFuture<int>::sequenceWithFailures<CopyCountQHash>(std::move(futures)); }); } #endif
21,043
6,785
/* Nome: Otto Bittencourt Matricula: 504654 LPA */ #include<iostream> #include<cstdio> #include<cstring> using namespace std; int loop = 0; char board[5][5]; char target[5][5] = { '1', '1', '1', '1', '1', '0', '1', '1', '1', '1', '0', '0', ' ', '1', '1', '0', '0', '0', '0', '1', '0', '0', '0', '0', '0', }; int cont; int movex[8] = { 1, 2, 2, 1, -1, -2, -2, -1,}; int movey[8] = { -2, -1, 1, 2, 2, 1, -1, -2,}; bool ehValido(int pri, int seg) { if (pri >= 5 || pri < 0)return false; if (seg >= 5 || seg < 0)return false; return true; } void dfs(int cont2, int x, int y) { if (cont2 == 11){ return; } if (memcmp(board, target, sizeof(board)) == 0) { cont = min(cont, cont2); return; } for (int i = 0; i < 8; i++) { int xx = x + movex[i]; int yy = y + movey[i]; if (ehValido(xx, yy)) { swap(board[x][y], board[xx][yy]); dfs(cont2 + 1, xx, yy); loop++; swap(board[x][y], board[xx][yy]); } } } int main() { int numeroDeCasos; cin >> numeroDeCasos; string ent1; getline(cin, ent1); for (int i = 0; i < numeroDeCasos; i++) { int x, y; for (int j = 0; j < 5; j++) { getline(cin, ent1); for (int k = 0; k < 5; k++) { board[j][k] = ent1[k]; if (ent1[k] == ' ') { x = j; y = k; } } } cont = 11; dfs(0, x, y); if (cont == 11) { printf("Unsolvable in less than 11 move(s).\n"); } else { printf("Solvable in %d move(s).\n", cont); } //printf("contador eh %d \n",loop); } return 0; }
1,500
821
// Copyright 2021 Olenin Sergey #include <mpi.h> #include <ctime> #include <random> #include <vector> #include "../../../modules/task_3/olenin_method_conjugate_gradient/gradient.h" std::vector<double> rand_matrix(int size) { if (0 >= size) throw "wrong matrix size"; std::default_random_engine gene; gene.seed(static_cast<unsigned int>(time(0))); int sizematrix = size * size; std::vector<double> rand_matrix(sizematrix); for (int Index = 0; Index < size; ++Index) { for (int Jindex = Index; Jindex < size; ++Jindex) { rand_matrix[Index * size + Jindex] = gene() % 10; rand_matrix[Jindex * size + Index] = rand_matrix[Index * size + Jindex]; } } return rand_matrix; } std::vector<double> rand_vec(int size) { if (0 >= size) throw "wrong size of vector"; std::default_random_engine gene; gene.seed(static_cast<unsigned int>(time(0))); std::vector<double> vec(size); for (int index = 0; index < size; ++index) { vec[index] = 1 + gene() % 10; } return vec; } double vec_mult(const std::vector<double>& vec_a, const std::vector<double>& vec_b) { if (vec_a.size() != vec_b.size()) throw "vector sizes are not consistent "; double multi = 0.0; for (size_t index = 0; index < vec_a.size(); ++index) multi += vec_a[index] * vec_b[index]; return multi; } std::vector<double> matrix_vec_mult(const std::vector<double>& matrix, const std::vector<double>& vec) { if ((matrix.size() % vec.size()) != 0) throw "matrix and vector sizes are incompatible"; std::vector<double> multi(matrix.size() / vec.size()); for (size_t Index = 0; Index < (matrix.size() / vec.size()); ++Index) { multi[Index] = 0.0; for (size_t Jindex = 0; Jindex < vec.size(); ++Jindex) { multi[Index] += matrix[Index * vec.size() + Jindex] * vec[Jindex]; } } return multi; } std::vector<double> get_sol_for_one_proc(const std::vector<double>& matrix, const std::vector<double>& vec, int size) { if (size <= 0) throw "wrong size"; int iteration = 0; double alpha = 0.0, beta = 0.0; double norm_residual = 0.0, criteria = 0.1; std::vector<double> x(size); for (int index = 0; index < size; index++) { x[index] = 1; } std::vector<double> Az = matrix_vec_mult(matrix, x); std::vector<double> residualprev(size), residualnext(size); for (int index = 0; index < size; index++) residualprev[index] = vec[index] - Az[index]; // residualprev^(k) = b - A * x std::vector<double> gradient(residualprev); // gradient = r^(k) do { iteration++; Az = matrix_vec_mult(matrix, gradient); // Az = A * gradient alpha = vec_mult(residualprev, residualprev) / vec_mult(gradient, Az); for (int index = 0; index < size; index++) { x[index] += alpha * gradient[index]; residualnext[index] = residualprev[index] - alpha * Az[index]; // residualnext^(k+1) = residualprev^(k)-alpha*Az } beta = vec_mult(residualnext, residualnext) / vec_mult(residualprev, residualprev); norm_residual = sqrt(vec_mult(residualnext, residualnext)); for (int index = 0; index < size; index++) gradient[index] = residualnext[index] + beta * gradient[index]; // gradient^(k+1) = residualnext^(k+1) + beta*gradient^(k) residualprev = residualnext; } while ((norm_residual > criteria) && (iteration <= size)); return x; } std::vector<double> get_sol_for_multiply_proc( const std::vector<double>& matrix, const std::vector<double>& vec, int size) { if (0 >= size) throw "wrong size"; std::vector<double> matrixtmp = matrix; std::vector<double> vectortmp = vec; MPI_Bcast(matrixtmp.data(), size * size, MPI_DOUBLE, 0, MPI_COMM_WORLD); MPI_Bcast(vectortmp.data(), size, MPI_DOUBLE, 0, MPI_COMM_WORLD); int size_comm, rank; MPI_Comm_size(MPI_COMM_WORLD, &size_comm); MPI_Comm_rank(MPI_COMM_WORLD, &rank); int k_rows = size / size_comm; int balance = size % size_comm; std::vector<double> matrixL(k_rows * size); if (0 == rank) { if (0 != balance) { matrixL.resize(size * k_rows + balance * size); } if (0 != k_rows) { for (int process = 1; process < size_comm; process++) { MPI_Send(&matrixtmp[0] + process * k_rows * size + balance * size, k_rows * size, MPI_DOUBLE, process, 1, MPI_COMM_WORLD); } } } if (0 == rank) { if (balance != 0) { for (int index = 0; index < size * k_rows + size * balance; index++) { matrixL[index] = matrixtmp[index]; } } else { for (int index = 0; index < size * k_rows; index++) { matrixL[index] = matrixtmp[index]; } } } else { MPI_Status message; if (k_rows != 0) { MPI_Recv(&matrixL[0], k_rows * size, MPI_DOUBLE, 0, 1, MPI_COMM_WORLD, &message); } } int iteration = 0; double beta = 0.0, alpha = 0.0; double norm_residual = 0.0, criteria = 0.1; std::vector<double> x(size); for (int index = 0; index < size; index++) { x[index] = 1; } std::vector<double> Az = matrix_vec_mult(matrixL, x); std::vector<double> residualprev(k_rows), residualnext(k_rows); if (0 == rank) { if (0 != balance) { residualprev.resize(k_rows + balance); residualnext.resize(k_rows + balance); } for (int index = 0; index < k_rows + balance; index++) residualprev[index] = vectortmp[index] - Az[index]; // residualprev^(k) = b - A * x } else { for (int index = 0; index < k_rows; index++) residualprev[index] = vectortmp[rank * k_rows + balance + index] - Az[index]; // residualprev^(k) = b - A * x } std::vector<double> gradient(size); // gradient = residualprev^(k) if (rank == 0) { if (balance != 0) { for (int index = 0; index < k_rows + balance; index++) { gradient[index] = residualprev[index]; } } else { for (int index = 0; index < k_rows; index++) { gradient[index] = residualprev[index]; } } if (k_rows != 0) { MPI_Status message; for (int process = 1; process < size_comm; process++) { MPI_Recv(&gradient[0] + process * k_rows + balance, k_rows, MPI_DOUBLE, process, 2, MPI_COMM_WORLD, &message); } } } else { if (k_rows != 0) { MPI_Send(&residualprev[0], k_rows, MPI_DOUBLE, 0, 2, MPI_COMM_WORLD); } } MPI_Bcast(gradient.data(), size, MPI_DOUBLE, 0, MPI_COMM_WORLD); std::vector<double> gradientblock(k_rows); std::vector<double> gradientlocal(k_rows); if (rank == 0) { if (balance != 0) { gradientblock.resize(k_rows + balance); } } do { iteration++; Az = matrix_vec_mult(matrixL, gradient); // Az = A * gradient if (rank == 0) { for (int index = 0; index < k_rows + balance; index++) { gradientblock[index] = gradient[index]; } } else { for (int index = 0; index < k_rows; index++) { gradientblock[index] = gradient[rank * k_rows + balance + index]; } } double tmp_f = vec_mult(residualprev, residualprev); double tmp_s = vec_mult(gradientblock, Az); double residualprevscalar; double devideralpha; MPI_Allreduce(&tmp_f, &residualprevscalar, 1, MPI_DOUBLE, MPI_SUM, MPI_COMM_WORLD); MPI_Allreduce(&tmp_s, &devideralpha, 1, MPI_DOUBLE, MPI_SUM, MPI_COMM_WORLD); alpha = residualprevscalar / devideralpha; for (int index = 0; index < size; index++) { x[index] += alpha * gradient[index]; } if (rank == 0) { for (int index = 0; index < k_rows + balance; index++) { residualnext[index] = residualprev[index] - alpha * Az[index]; // residualnext^(k+1) = residualprev^(k)-alpha*Az } } else { for (int index = 0; index < k_rows; index++) { residualnext[index] = residualprev[index] - alpha * Az[index]; // residualnext^(k+1) = residualprev^(k)-alpha*Az } } double residualnextscalar; tmp_f = vec_mult(residualnext, residualnext); MPI_Allreduce(&tmp_f, &residualnextscalar, 1, MPI_DOUBLE, MPI_SUM, MPI_COMM_WORLD); beta = residualnextscalar / residualprevscalar; norm_residual = sqrt(residualnextscalar); if (rank == 0) { for (int index = 0; index < k_rows + balance; index++) { gradient[index] = residualnext[index] + beta * gradient[index]; } if (k_rows != 0) { MPI_Status message; for (int process = 1; process < size_comm; process++) { MPI_Recv(&gradient[0] + process * k_rows + balance, k_rows, MPI_DOUBLE, process, 3, MPI_COMM_WORLD, &message); } } } else { for (int index = 0; index < k_rows; index++) { gradientlocal[index] = residualnext[index] + beta * gradient[rank * k_rows + balance + index]; } if (k_rows != 0) { MPI_Send(&gradientlocal[0], k_rows, MPI_DOUBLE, 0, 3, MPI_COMM_WORLD); } } MPI_Bcast(gradient.data(), size, MPI_DOUBLE, 0, MPI_COMM_WORLD); residualprev = residualnext; } while ((norm_residual > criteria) && (iteration <= size)); return x; }
9,365
3,487
#include "StableRand.h" #include "LevyRand.h" #include "CauchyRand.h" #include "NormalRand.h" #include "UniformRand.h" #include "ExponentialRand.h" #include <functional> StableDistribution::StableDistribution(double exponent, double skewness, double scale, double location) { SetParameters(exponent, skewness, scale, location); } SUPPORT_TYPE StableDistribution::SupportType() const { if (alpha < 1) { if (beta == 1) return RIGHTSEMIFINITE_T; if (beta == -1) return LEFTSEMIFINITE_T; } return INFINITE_T; } double StableDistribution::MinValue() const { return (alpha < 1 && beta == 1) ? mu : -INFINITY; } double StableDistribution::MaxValue() const { return (alpha < 1 && beta == -1) ? mu : INFINITY; } void StableDistribution::SetParameters(double exponent, double skewness, double scale, double location) { if (exponent < 0.1 || exponent > 2.0) throw std::invalid_argument("Stable distribution: exponent should be in the interval [0.1, 2]"); if (std::fabs(skewness) > 1.0) throw std::invalid_argument("Stable distribution: skewness of should be in the interval [-1, 1]"); if (scale <= 0.0) throw std::invalid_argument("Stable distribution: scale should be positive"); /// the following errors should be removed soon if (exponent != 1.0 && std::fabs(exponent - 1.0) < 0.01 && skewness != 0.0) throw std::invalid_argument("Stable distribution: exponent close to 1 with non-zero skewness is not yet supported"); if (exponent == 1.0 && skewness != 0.0 && std::fabs(skewness) < 0.01) throw std::invalid_argument("Stable distribution: skewness close to 0 with exponent equal to 1 is not yet supported"); alpha = exponent; alphaInv = 1.0 / alpha; beta = skewness; mu = location; gamma = scale; logGamma = std::log(gamma); /// Set id of distribution if (alpha == 2.0) distributionType = NORMAL; else if (alpha == 1.0) distributionType = (beta == 0.0) ? CAUCHY : UNITY_EXPONENT; else if (alpha == 0.5 && std::fabs(beta) == 1.0) distributionType = LEVY; else distributionType = GENERAL; alpha_alpham1 = alpha / (alpha - 1.0); if (distributionType == NORMAL) pdfCoef = M_LN2 + logGamma + 0.5 * M_LNPI; else if (distributionType == LEVY) pdfCoef = logGamma - M_LN2 - M_LNPI; else if (distributionType == CAUCHY) pdfCoef = -logGamma - M_LNPI; else if (distributionType == UNITY_EXPONENT) { pdfCoef = 0.5 / (gamma * std::fabs(beta)); pdftailBound = 0; // not in the use for now logGammaPi_2 = logGamma + M_LNPI - M_LN2; } else if (distributionType == GENERAL) { if (beta != 0.0) { zeta = -beta * std::tan(M_PI_2 * alpha); omega = 0.5 * alphaInv * std::log1p(zeta * zeta); xi = alphaInv * RandMath::atan(-zeta); } else { zeta = omega = xi = 0.0; } pdfCoef = M_1_PI * std::fabs(alpha_alpham1) / gamma; pdftailBound = 3.0 / (1.0 + alpha) * M_LN10; cdftailBound = 3.0 / alpha * M_LN10; /// define boundaries of region near 0, where we use series expansion if (alpha <= ALMOST_TWO) { seriesZeroParams.first = std::round(std::min(alpha * alpha * 40 + 1, 10.0)); /// corresponds to boundaries from 10^(-15.5) to ~ 0.056 seriesZeroParams.second = -(alphaInv * 1.5 + 0.5) * M_LN10; } else { seriesZeroParams.first = 85; /// corresponds to 6 seriesZeroParams.second = M_LN2 + M_LN3; } } } void StableDistribution::SetLocation(double location) { mu = location; } void StableDistribution::SetScale(double scale) { if (scale <= 0.0) throw std::invalid_argument("Scale of Stable distribution should be positive"); gamma = scale; logGamma = std::log(gamma); if (distributionType == NORMAL) pdfCoef = M_LN2 + logGamma + 0.5 * M_LNPI; else if (distributionType == LEVY) pdfCoef = logGamma - M_LN2 - M_LNPI; else if (distributionType == CAUCHY) pdfCoef = -logGamma - M_LNPI; else if (distributionType == UNITY_EXPONENT) { pdfCoef = 0.5 / (gamma * std::fabs(beta)); logGammaPi_2 = logGamma + M_LNPI - M_LN2; } else if (distributionType == GENERAL) pdfCoef = M_1_PI * std::fabs(alpha_alpham1) / gamma; } double StableDistribution::pdfNormal(double x) const { return std::exp(logpdfNormal(x)); } double StableDistribution::logpdfNormal(double x) const { double y = x - mu; y *= 0.5 / gamma; y *= y; y += pdfCoef; return -y; } double StableDistribution::pdfCauchy(double x) const { double y = x - mu; y *= y; y /= gamma; y += gamma; return M_1_PI / y; } double StableDistribution::logpdfCauchy(double x) const { double x0 = x - mu; x0 /= gamma; double xSq = x0 * x0; return pdfCoef - std::log1p(xSq); } double StableDistribution::pdfLevy(double x) const { return (x <= mu) ? 0.0 : std::exp(logpdfLevy(x)); } double StableDistribution::logpdfLevy(double x) const { double x0 = x - mu; if (x0 <= 0.0) return -INFINITY; double y = gamma / x0; y += 3 * std::log(x0); y -= pdfCoef; return -0.5 * y; } double StableDistribution::fastpdfExponentiation(double u) { if (u > 5 || u < -50) return 0.0; return (u < -25) ? std::exp(u) : std::exp(u - std::exp(u)); } double StableDistribution::pdfShortTailExpansionForUnityExponent(double x) const { if (x > 10) return 0.0; double xm1 = x - 1.0; double y = 0.5 * xm1 - std::exp(xm1); y -= 0.5 * (M_LN2 + M_LNPI); return std::exp(y); } double StableDistribution::limitCaseForIntegrandAuxForUnityExponent(double theta, double xAdj) const { if (theta > 0.0) { if (beta > 0.0) return BIG_NUMBER; return (beta == -1) ? xAdj - 1.0 : -BIG_NUMBER; } if (beta < 0.0) return BIG_NUMBER; return (beta == 1) ? xAdj - 1.0 : -BIG_NUMBER; } double StableDistribution::integrandAuxForUnityExponent(double theta, double xAdj) const { if (std::fabs(theta) >= M_PI_2) return limitCaseForIntegrandAuxForUnityExponent(theta, xAdj); if (theta == 0.0) return xAdj + M_LNPI - M_LN2; double thetaAdj = (M_PI_2 + beta * theta) / std::cos(theta); double u = std::log(thetaAdj); u += thetaAdj * std::sin(theta) / beta; return std::isfinite(u) ? u + xAdj : limitCaseForIntegrandAuxForUnityExponent(theta, xAdj); } double StableDistribution::integrandForUnityExponent(double theta, double xAdj) const { if (std::fabs(theta) >= M_PI_2) return 0.0; double u = integrandAuxForUnityExponent(theta, xAdj); return fastpdfExponentiation(u); } double StableDistribution::pdfForUnityExponent(double x) const { double xSt = (x - mu) / gamma; double xAdj = -M_PI_2 * xSt / beta - logGammaPi_2; /// We squeeze boudaries for too peaked integrands double boundary = RandMath::atan(M_2_PI * beta * (5.0 - xAdj)); double upperBoundary = (beta > 0.0) ? boundary : M_PI_2; double lowerBoundary = (beta < 0.0) ? boundary : -M_PI_2; /// Find peak of the integrand double theta0 = 0; std::function<double (double)> funPtr = std::bind(&StableDistribution::integrandAuxForUnityExponent, this, std::placeholders::_1, xAdj); RandMath::findRoot(funPtr, lowerBoundary, upperBoundary, theta0); /// Sanity check /// if we failed while looking for the peak position /// we set it in the middle between boundaries if (theta0 >= upperBoundary || theta0 <= lowerBoundary) theta0 = 0.5 * (upperBoundary + lowerBoundary); std::function<double (double)> integrandPtr = std::bind(&StableDistribution::integrandForUnityExponent, this, std::placeholders::_1, xAdj); /// If theta0 is too close to +/-π/2 then we can still underestimate the integral int maxRecursionDepth = 11; double closeness = M_PI_2 - std::fabs(theta0); if (closeness < 0.1) maxRecursionDepth = 20; else if (closeness < 0.2) maxRecursionDepth = 15; double int1 = RandMath::integral(integrandPtr, lowerBoundary, theta0, 1e-11, maxRecursionDepth); double int2 = RandMath::integral(integrandPtr, theta0, upperBoundary, 1e-11, maxRecursionDepth); return pdfCoef * (int1 + int2); } double StableDistribution::pdfShortTailExpansionForGeneralExponent(double logX) const { double logAlpha = std::log(alpha); double log1mAlpha = (alpha < 1) ? std::log1p(-alpha) : std::log(alpha - 1); double temp = logX - logAlpha; double y = std::exp(alpha_alpham1 * temp); y *= -std::fabs(1.0 - alpha); double z = (1.0 - 0.5 * alpha) / (alpha - 1) * temp; z -= 0.5 * (M_LN2 + M_LNPI + logAlpha + log1mAlpha); return std::exp(y + z); } double StableDistribution::pdfAtZero() const { double y0 = 0.0; if (beta == 0.0) y0 = std::tgamma(alphaInv); else { y0 = std::lgamma(alphaInv) - omega; y0 = std::exp(y0) * std::cos(xi); } return y0 * M_1_PI / alpha; } double StableDistribution::pdfSeriesExpansionAtZero(double logX, double xiAdj, int k) const { /// Calculate first term of the sum /// (if x = 0, only this term is non-zero) double y0 = pdfAtZero(); double sum = 0.0; if (beta == 0.0) { /// Symmetric distribution for (int n = 1; n <= k; ++n) { int n2 = n + n; double term = std::lgamma((n2 + 1) / alpha); term += n2 * logX; term -= RandMath::lfact(n2); term = std::exp(term); sum += (n & 1) ? -term : term; } } else { /// Asymmetric distribution double rhoPi_alpha = M_PI_2 + xiAdj; for (int n = 1; n <= k; ++n) { int np1 = n + 1; double term = std::lgamma(np1 * alphaInv); term += n * logX; term -= RandMath::lfact(n); term = std::exp(term - omega); term *= std::sin(np1 * rhoPi_alpha); sum += (n & 1) ? -term : term; } } return y0 + sum * M_1_PI / alpha; } double StableDistribution::pdfSeriesExpansionAtInf(double logX, double xiAdj) const { static constexpr int k = 10; ///< number of elements in the series double rhoPi = M_PI_2 + xiAdj; rhoPi *= alpha; double sum = 0.0; for (int n = 1; n <= k; ++n) { double aux = n * alpha + 1.0; double term = std::lgamma(aux); term -= aux * logX; term -= RandMath::lfact(n); term = std::exp(term - omega); term *= std::sin(rhoPi * n); sum += (n & 1) ? term : -term; } return M_1_PI * sum; } double StableDistribution::pdfTaylorExpansionTailNearCauchy(double x) const { double xSq = x * x; double y = 1.0 + xSq; double ySq = y * y; double z = RandMath::atan(x); double zSq = z * z; double logY = std::log1p(xSq); double alpham1 = alpha - 1.0; double temp = 1.0 - M_EULER - 0.5 * logY; /// first derivative double f_a = temp; f_a *= xSq - 1.0; f_a += 2 * x * z; f_a /= ySq; static constexpr long double M_PI_SQ_6 = 1.64493406684822643647l; /// π^2 / 6 /// second derivative double f_aa1 = M_PI_SQ_6; f_aa1 += temp * temp; f_aa1 -= 1.0 + z * z; f_aa1 *= xSq * xSq - 6.0 * xSq + 1.0; double f_aa2 = 0.5 + temp; f_aa2 *= z; f_aa2 *= 8 * x * (xSq - 1.0); double f_aa3 = (1.0 - 3 * xSq) * temp; f_aa3 -= x * y * z; f_aa3 += f_aa3; double f_aa = f_aa1 + f_aa2 + f_aa3; f_aa /= std::pow(y, 3); /// Hashed values of special functions for x = 2, 3, 4 /// Gamma(x) static constexpr int gammaTable[] = {1, 2, 6}; /// Gamma'(x) static constexpr long double gammaDerTable[] = {1.0 - M_EULER, 3.0 - 2.0 * M_EULER, 11.0 - 6.0 * M_EULER}; /// Gamma''(x) static constexpr long double gammaSecDerTable[] = {0.82368066085287938958l, 2.49292999190269305794l, 11.1699273161019477314l}; /// Digamma(x) static constexpr long double digammaTable[] = {1.0 - M_EULER, 1.5 - M_EULER, 11.0 / 6 - M_EULER}; /// Digamma'(x) static constexpr long double digammaDerTable[] = {M_PI_SQ_6 - 1.0, M_PI_SQ_6 - 1.25, M_PI_SQ_6 - 49.0 / 36}; /// Digamma''(x) static constexpr long double digammaSecDerTable[] = {-0.40411380631918857080l, -0.15411380631918857080l, -0.08003973224511449673l}; /// third derivative double gTable[] = {0, 0, 0}; for (int i = 0; i < 3; ++i) { double g_11 = 0.25 * gammaTable[i] * logY * logY; g_11 -= gammaDerTable[i] * logY; g_11 += gammaSecDerTable[i]; double aux = digammaTable[i] - 0.5 * logY; double g_12 = aux; double zip2 = z * (i + 2); double cosZNu = std::cos(zip2), zSinZNu = z * std::sin(zip2); g_12 *= cosZNu; g_12 -= zSinZNu; double g_1 = g_11 * g_12; double g_21 = -gammaTable[i] * logY + 2 * gammaDerTable[i]; double g_22 = -zSinZNu * aux; g_22 -= zSq * cosZNu; g_22 += cosZNu * digammaDerTable[i]; double g_2 = g_21 * g_22; double g_3 = -zSq * cosZNu * aux; g_3 -= 2 * zSinZNu * digammaDerTable[i]; g_3 += zSq * zSinZNu; g_3 += cosZNu * digammaSecDerTable[i]; g_3 *= gammaTable[i]; double g = g_1 + g_2 + g_3; g *= std::pow(y, -0.5 * i - 1); gTable[i] = g; } double f_aaa = -gTable[0] + 3 * gTable[1] - gTable[2]; /// summarize all three derivatives double tail = f_a * alpham1; tail += 0.5 * f_aa * alpham1 * alpham1; tail += std::pow(alpham1, 3) * f_aaa / 6.0; tail /= M_PI; return tail; } double StableDistribution::limitCaseForIntegrandAuxForGeneralExponent(double theta, double xiAdj) const { /// We got numerical error, need to investigate to which extreme point we are closer if (theta < 0.5 * (M_PI_2 - xiAdj)) return alpha < 1 ? -BIG_NUMBER : BIG_NUMBER; return alpha < 1 ? BIG_NUMBER : -BIG_NUMBER; } double StableDistribution::integrandAuxForGeneralExponent(double theta, double xAdj, double xiAdj) const { if (std::fabs(theta) >= M_PI_2 || theta <= -xiAdj) return limitCaseForIntegrandAuxForGeneralExponent(theta, xiAdj); double thetaAdj = alpha * (theta + xiAdj); double sinThetaAdj = std::sin(thetaAdj); double y = std::log(std::cos(theta)); y -= alpha * std::log(sinThetaAdj); y /= alpha - 1.0; y += std::log(std::cos(thetaAdj - theta)); y += xAdj; return std::isfinite(y) ? y : limitCaseForIntegrandAuxForGeneralExponent(theta, xiAdj); } double StableDistribution::integrandFoGeneralExponent(double theta, double xAdj, double xiAdj) const { if (std::fabs(theta) >= M_PI_2) return 0.0; if (theta <= -xiAdj) return 0.0; double u = integrandAuxForGeneralExponent(theta, xAdj, xiAdj); return fastpdfExponentiation(u); } double StableDistribution::pdfForGeneralExponent(double x) const { /// Standardize double xSt = (x - mu) / gamma; double absXSt = xSt; /// +- xi double xiAdj = xi; if (xSt > 0) { if (alpha < 1 && beta == -1) return 0.0; } else { if (alpha < 1 && beta == 1) return 0.0; absXSt = -xSt; xiAdj = -xi; } /// If α is too close to 1 and distribution is symmetric, then we approximate using Taylor series if (beta == 0.0 && std::fabs(alpha - 1.0) < 0.01) return pdfCauchy(x) + pdfTaylorExpansionTailNearCauchy(absXSt) / gamma; /// If x = 0, we know the analytic solution if (xSt == 0.0) return pdfAtZero() / gamma; double logAbsX = std::log(absXSt) - omega; /// If x is too close to 0, we do series expansion avoiding numerical problems if (logAbsX < seriesZeroParams.second) { if (alpha < 1 && std::fabs(beta) == 1) return pdfShortTailExpansionForGeneralExponent(logAbsX); return pdfSeriesExpansionAtZero(logAbsX, xiAdj, seriesZeroParams.first) / gamma; } /// If x is large enough we use tail approximation if (logAbsX > pdftailBound && alpha <= ALMOST_TWO) { if (alpha > 1 && std::fabs(beta) == 1) return pdfShortTailExpansionForGeneralExponent(logAbsX); return pdfSeriesExpansionAtInf(logAbsX, xiAdj) / gamma; } double xAdj = alpha_alpham1 * logAbsX; /// Search for the peak of the integrand double theta0; std::function<double (double)> funPtr = std::bind(&StableDistribution::integrandAuxForGeneralExponent, this, std::placeholders::_1, xAdj, xiAdj); RandMath::findRoot(funPtr, -xiAdj, M_PI_2, theta0); /// If theta0 is too close to π/2 or -xiAdj then we can still underestimate the integral int maxRecursionDepth = 11; double closeness = std::min(M_PI_2 - theta0, theta0 + xiAdj); if (closeness < 0.1) maxRecursionDepth = 20; else if (closeness < 0.2) maxRecursionDepth = 15; /// Calculate sum of two integrals std::function<double (double)> integrandPtr = std::bind(&StableDistribution::integrandFoGeneralExponent, this, std::placeholders::_1, xAdj, xiAdj); double int1 = RandMath::integral(integrandPtr, -xiAdj, theta0, 1e-11, maxRecursionDepth); double int2 = RandMath::integral(integrandPtr, theta0, M_PI_2, 1e-11, maxRecursionDepth); double res = pdfCoef * (int1 + int2) / absXSt; /// Finally we check if α is not too close to 2 if (alpha <= ALMOST_TWO) return res; /// If α is near 2, we use tail aprroximation for large x /// and compare it with integral representation double alphap1 = alpha + 1.0; double tail = std::lgamma(alphap1); tail -= alphap1 * logAbsX; tail = std::exp(tail); tail *= (1.0 - 0.5 * alpha) / gamma; return std::max(tail, res); } double StableDistribution::f(const double & x) const { switch (distributionType) { case NORMAL: return pdfNormal(x); case CAUCHY: return pdfCauchy(x); case LEVY: return (beta > 0) ? pdfLevy(x) : pdfLevy(2 * mu - x); case UNITY_EXPONENT: return pdfForUnityExponent(x); case GENERAL: return pdfForGeneralExponent(x); default: return NAN; /// unexpected return } } double StableDistribution::logf(const double & x) const { switch (distributionType) { case NORMAL: return logpdfNormal(x); case CAUCHY: return logpdfCauchy(x); case LEVY: return (beta > 0) ? logpdfLevy(x) : logpdfLevy(2 * mu - x); case UNITY_EXPONENT: return std::log(pdfForUnityExponent(x)); case GENERAL: return std::log(pdfForGeneralExponent(x)); default: return NAN; /// unexpected return } } double StableDistribution::cdfNormal(double x) const { double y = mu - x; y *= 0.5 / gamma; return 0.5 * std::erfc(y); } double StableDistribution::cdfNormalCompl(double x) const { double y = x - mu; y *= 0.5 / gamma; return 0.5 * std::erfc(y); } double StableDistribution::cdfCauchy(double x) const { double x0 = x - mu; x0 /= gamma; return 0.5 + M_1_PI * RandMath::atan(x0); } double StableDistribution::cdfCauchyCompl(double x) const { double x0 = mu - x; x0 /= gamma; return 0.5 + M_1_PI * RandMath::atan(x0); } double StableDistribution::cdfLevy(double x) const { if (x <= mu) return 0; double y = x - mu; y += y; y = gamma / y; y = std::sqrt(y); return std::erfc(y); } double StableDistribution::cdfLevyCompl(double x) const { if (x <= mu) return 1.0; double y = x - mu; y += y; y = gamma / y; y = std::sqrt(y); return std::erf(y); } double StableDistribution::fastcdfExponentiation(double u) { if (u > 5.0) return 0.0; else if (u < -50.0) return 1.0; double y = std::exp(u); return std::exp(-y); } double StableDistribution::cdfAtZero(double xiAdj) const { return 0.5 - M_1_PI * xiAdj; } double StableDistribution::cdfForUnityExponent(double x) const { double xSt = (x - mu) / gamma; double xAdj = -M_PI_2 * xSt / beta - logGammaPi_2; double y = M_1_PI * RandMath::integral([this, xAdj] (double theta) { double u = integrandAuxForUnityExponent(theta, xAdj); return fastcdfExponentiation(u); }, -M_PI_2, M_PI_2); return (beta > 0) ? y : 1.0 - y; } double StableDistribution::cdfSeriesExpansionAtZero(double logX, double xiAdj, int k) const { /// Calculate first term of the sum /// (if x = 0, only this term is non-zero) double y0 = cdfAtZero(xiAdj); double sum = 0.0; if (beta == 0.0) { /// Symmetric distribution for (int m = 0; m <= k; ++m) { int m2p1 = 2 * m + 1; double term = std::lgamma(m2p1 * alphaInv); term += m2p1 * logX; term -= RandMath::lfact(m2p1); term = std::exp(term); sum += (m & 1) ? -term : term; } } else { /// Asymmetric distribution double rhoPi_alpha = M_PI_2 + xiAdj; for (int n = 1; n <= k; ++n) { double term = std::lgamma(n * alphaInv); term += n * logX; term -= RandMath::lfact(n); term = std::exp(term); term *= std::sin(n * rhoPi_alpha); sum += (n & 1) ? term : -term; } } return y0 + sum * M_1_PI * alphaInv; } double StableDistribution::cdfSeriesExpansionAtInf(double logX, double xiAdj) const { static constexpr int k = 10; /// number of elements in the series double rhoPi = M_PI_2 + xiAdj; rhoPi *= alpha; double sum = 0.0; for (int n = 1; n <= k; ++n) { double aux = n * alpha; double term = std::lgamma(aux); term -= aux * logX; term -= RandMath::lfact(n); term = std::exp(term); term *= std::sin(rhoPi * n); sum += (n & 1) ? term : -term; } return M_1_PI * sum; } double StableDistribution::cdfIntegralRepresentation(double logX, double xiAdj) const { double xAdj = alpha_alpham1 * logX; return M_1_PI * RandMath::integral([this, xAdj, xiAdj] (double theta) { double u = integrandAuxForGeneralExponent(theta, xAdj, xiAdj); return fastcdfExponentiation(u); }, -xiAdj, M_PI_2); } double StableDistribution::cdfForGeneralExponent(double x) const { double xSt = (x - mu) / gamma; /// Standardize if (xSt == 0) return cdfAtZero(xi); if (xSt > 0.0) { double logAbsX = std::log(xSt) - omega; /// If x is too close to 0, we do series expansion avoiding numerical problems if (logAbsX < seriesZeroParams.second) return cdfSeriesExpansionAtZero(logAbsX, xi, seriesZeroParams.first); /// If x is large enough we use tail approximation if (logAbsX > cdftailBound) return 1.0 - cdfSeriesExpansionAtInf(logAbsX, xi); if (alpha > 1.0) return 1.0 - cdfIntegralRepresentation(logAbsX, xi); return (beta == -1.0) ? 1.0 : cdfAtZero(xi) + cdfIntegralRepresentation(logAbsX, xi); } /// For x < 0 we use relation F(-x, xi) + F(x, -xi) = 1 double logAbsX = std::log(-xSt) - omega; if (logAbsX < seriesZeroParams.second) return 1.0 - cdfSeriesExpansionAtZero(logAbsX, -xi, seriesZeroParams.first); if (logAbsX > cdftailBound) return cdfSeriesExpansionAtInf(logAbsX, -xi); if (alpha > 1.0) return cdfIntegralRepresentation(logAbsX, -xi); return (beta == 1.0) ? 0.0 : cdfAtZero(xi) - cdfIntegralRepresentation(logAbsX, -xi); } double StableDistribution::F(const double & x) const { switch (distributionType) { case NORMAL: return cdfNormal(x); case CAUCHY: return cdfCauchy(x); case LEVY: return (beta > 0) ? cdfLevy(x) : cdfLevyCompl(2 * mu - x); case UNITY_EXPONENT: return cdfForUnityExponent(x); case GENERAL: return cdfForGeneralExponent(x); default: return NAN; /// unexpected return } } double StableDistribution::S(const double & x) const { switch (distributionType) { case NORMAL: return cdfNormalCompl(x); case CAUCHY: return cdfCauchyCompl(x); case LEVY: return (beta > 0) ? cdfLevyCompl(x) : cdfLevy(2 * mu - x); case UNITY_EXPONENT: return 1.0 - cdfForUnityExponent(x); case GENERAL: return 1.0 - cdfForGeneralExponent(x); default: return NAN; /// unexpected return } } double StableDistribution::variateForUnityExponent() const { double U = M_PI * UniformRand::StandardVariate(localRandGenerator) - M_PI_2; double W = ExponentialRand::StandardVariate(localRandGenerator); double pi_2pBetaU = M_PI_2 + beta * U; double Y = W * std::cos(U) / pi_2pBetaU; double X = std::log(Y); X += logGammaPi_2; X *= -beta; X += pi_2pBetaU * std::tan(U); X *= M_2_PI; return mu + gamma * X; } double StableDistribution::variateForGeneralExponent() const { double U = M_PI * UniformRand::StandardVariate(localRandGenerator) - M_PI_2; double W = ExponentialRand::StandardVariate(localRandGenerator); double alphaUpxi = alpha * (U + xi); double X = std::sin(alphaUpxi); double W_adj = W / std::cos(U - alphaUpxi); X *= W_adj; double R = omega - alphaInv * std::log(W_adj * std::cos(U)); X *= std::exp(R); return mu + gamma * X; } double StableDistribution::variateForExponentEqualOneHalf() const { double Z1 = NormalRand::StandardVariate(localRandGenerator); double Z2 = NormalRand::StandardVariate(localRandGenerator); double temp1 = (1.0 + beta) / Z1, temp2 = (1.0 - beta) / Z2; double var = temp1 - temp2; var *= temp1 + temp2; var *= 0.25; return mu + gamma * var; } double StableDistribution::Variate() const { switch (distributionType) { case NORMAL: return mu + M_SQRT2 * gamma * NormalRand::StandardVariate(localRandGenerator); case CAUCHY: return mu + gamma * CauchyRand::StandardVariate(localRandGenerator); case LEVY: return mu + RandMath::sign(beta) * gamma * LevyRand::StandardVariate(localRandGenerator); case UNITY_EXPONENT: return variateForUnityExponent(); case GENERAL: return (alpha == 0.5) ? variateForExponentEqualOneHalf() : variateForGeneralExponent(); default: return NAN; /// unexpected return } } void StableDistribution::Sample(std::vector<double> &outputData) const { switch (distributionType) { case NORMAL: { double stdev = M_SQRT2 * gamma; for (double &var : outputData) var = mu + stdev * NormalRand::StandardVariate(localRandGenerator); } break; case CAUCHY: { for (double &var : outputData) var = mu + gamma * CauchyRand::StandardVariate(localRandGenerator); } break; case LEVY: { if (beta > 0) { for (double &var : outputData) var = mu + gamma * LevyRand::StandardVariate(localRandGenerator); } else { for (double &var : outputData) var = mu - gamma * LevyRand::StandardVariate(localRandGenerator); } } break; case UNITY_EXPONENT: { for (double &var : outputData) var = variateForUnityExponent(); } break; case GENERAL: { if (alpha == 0.5) { for (double &var : outputData) var = variateForExponentEqualOneHalf(); } else { for (double &var : outputData) var = variateForGeneralExponent(); } } break; default: break; } } double StableDistribution::Mean() const { if (alpha > 1) return mu; if (beta == 1) return INFINITY; return (beta == -1) ? -INFINITY : NAN; } double StableDistribution::Variance() const { return (distributionType == NORMAL) ? 2 * gamma * gamma : INFINITY; } double StableDistribution::Mode() const { /// For symmetric and normal distributions mode is μ if (beta == 0 || distributionType == NORMAL) return mu; if (distributionType == LEVY) return mu + beta * gamma / 3.0; return ContinuousDistribution::Mode(); } double StableDistribution::Median() const { /// For symmetric and normal distributions mode is μ if (beta == 0 || distributionType == NORMAL) return mu; return ContinuousDistribution::Median(); } double StableDistribution::Skewness() const { return (distributionType == NORMAL) ? 0 : NAN; } double StableDistribution::ExcessKurtosis() const { return (distributionType == NORMAL) ? 0 : NAN; } double StableDistribution::quantileNormal(double p) const { return mu - 2 * gamma * RandMath::erfcinv(2 * p); } double StableDistribution::quantileNormal1m(double p) const { return mu + 2 * gamma * RandMath::erfcinv(2 * p); } double StableDistribution::quantileCauchy(double p) const { return mu - gamma / std::tan(M_PI * p); } double StableDistribution::quantileCauchy1m(double p) const { return mu + gamma / std::tan(M_PI * p); } double StableDistribution::quantileLevy(double p) const { double y = RandMath::erfcinv(p); return mu + 0.5 * gamma / (y * y); } double StableDistribution::quantileLevy1m(double p) const { double y = RandMath::erfinv(p); return mu + 0.5 * gamma / (y * y); } double StableDistribution::quantileImpl(double p) const { switch (distributionType) { case NORMAL: return quantileNormal(p); case CAUCHY: return quantileCauchy(p); case LEVY: return (beta > 0) ? quantileLevy(p) : 2 * mu - quantileLevy1m(p); default: return ContinuousDistribution::quantileImpl(p); } } double StableDistribution::quantileImpl1m(double p) const { switch (distributionType) { case NORMAL: return quantileNormal1m(p); case CAUCHY: return quantileCauchy1m(p); case LEVY: return (beta > 0) ? quantileLevy1m(p) : 2 * mu - quantileLevy(p); default: return ContinuousDistribution::quantileImpl1m(p); } } std::complex<double> StableDistribution::cfNormal(double t) const { double gammaT = gamma * t; std::complex<double> y(-gammaT * gammaT, mu * t); return std::exp(y); } std::complex<double> StableDistribution::cfCauchy(double t) const { std::complex<double> y(-gamma * t, mu * t); return std::exp(y); } std::complex<double> StableDistribution::cfLevy(double t) const { std::complex<double> y(0.0, -2 * gamma * t); y = -std::sqrt(y); y += std::complex<double>(0.0, mu * t); return std::exp(y); } std::complex<double> StableDistribution::CFImpl(double t) const { double x = 0; switch (distributionType) { case NORMAL: return cfNormal(t); case CAUCHY: return cfCauchy(t); case LEVY: { std::complex<double> phi = cfLevy(t); return (beta > 0) ? phi : std::conj(phi); } case UNITY_EXPONENT: x = beta * M_2_PI * std::log(t); break; default: x = -zeta; } double re = std::pow(gamma * t, alpha); std::complex<double> psi = std::complex<double>(re, re * x - mu * t); return std::exp(-psi); } String StableRand::Name() const { return "Stable(" + toStringWithPrecision(GetExponent()) + ", " + toStringWithPrecision(GetSkewness()) + ", " + toStringWithPrecision(GetScale()) + ", " + toStringWithPrecision(GetLocation()) + ")"; } String HoltsmarkRand::Name() const { return "Holtsmark(" + toStringWithPrecision(GetScale()) + ", " + toStringWithPrecision(GetLocation()) + ")"; } String LandauRand::Name() const { return "Landau(" + toStringWithPrecision(GetScale()) + ", " + toStringWithPrecision(GetLocation()) + ")"; }
32,087
12,115
/* Copyright 2017 The TensorFlow Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==============================================================================*/ #include "tensorflow/core/kernels/i_remote_fused_graph_executor.h" #include "tensorflow/core/kernels/remote_fused_graph_execute_utils.h" #include "tensorflow/core/lib/core/status_test_util.h" #include "tensorflow/core/platform/test.h" namespace tensorflow { namespace hexagon_remote_fused_graph_executor_build { Status BuildRemoteFusedGraphExecutor( std::unique_ptr<IRemoteFusedGraphExecutor>* executor); namespace { TEST(HexagonBuildRemoteFusedGraphExecutorTest, BasicRun) { std::unique_ptr<IRemoteFusedGraphExecutor> executor; ASSERT_FALSE(static_cast<bool>(executor)); TF_ASSERT_OK(BuildRemoteFusedGraphExecutor(&executor)); ASSERT_TRUE(static_cast<bool>(executor)); ASSERT_NE(RemoteFusedGraphExecuteUtils::GetExecutorBuildFunc( "build_hexagon_remote_fused_graph_executor"), nullptr); } } // namespace } // namespace hexagon_remote_fused_graph_executor_build } // namespace tensorflow
1,609
485
#include <mog.h> void MOG::train( std::vector<cv::Mat>& training_images, std::vector<cv::Mat>& masks ){ cv::Mat pos_samples, neg_samples; std::cout << "Organizing the data" << std::endl; // organize all the samples organizeSamples(training_images, masks, pos_samples, neg_samples); std::cout << "Training the models, this may take a while" << std::endl; // train the models pos_model->trainEM( pos_samples ); neg_model->trainEM( neg_samples ); emToMixture(); std::cout << "Finished training the models" << std::endl; } void MOG::organizeSamples( std::vector<cv::Mat>& imgs, std::vector<cv::Mat>& masks, cv::Mat& pos_samples, cv::Mat& neg_samples ){ std::vector<double> pos, neg; const size_t channels = imgs[0].channels(); for ( int i = 0; i < (int)imgs.size(); i++ ) organizeSample( imgs[i], masks[i], pos, neg ); // std::vector -> cv::Mat // 3Nx1 -> Nx3 pos_samples = cv::Mat( pos, true ); pos_samples = pos_samples.reshape( 1, pos.size() / channels ); neg_samples = cv::Mat( neg, true ); neg_samples = neg_samples.reshape( 1, neg.size() / channels ); } // organize samples in an array void MOG::organizeSample( const cv::Mat& img, const cv::Mat& mask, std::vector<double>& pos, std::vector<double>& neg ){ CV_Assert( img.cols == mask.cols && img.rows == mask.rows && mask.type() == CV_16UC1 ); const size_t channels = img.channels(); double sample[channels]; for ( int yyy = 0; yyy < img.rows; yyy++ ) { for ( int xxx = 0; xxx < img.cols; xxx++ ) { // 3 channel pixel to 1x3 mat sample[0] = img.at<cv::Vec3b>( yyy, xxx ) ( 2 ); sample[1] = img.at<cv::Vec3b>( yyy, xxx ) ( 1 ); sample[2] = img.at<cv::Vec3b>( yyy, xxx ) ( 0 ); // appends 3 elements (of 3 channels) // at the end of *pos* or *neg* if ( mask.at<unsigned short>( yyy, xxx ) > 0 ) pos.insert( pos.end(), sample, sample + channels ); else neg.insert( neg.end(), sample, sample + channels ); } } }
2,325
775
#include "NoughtGraphic.hpp" NoughtGraphic::NoughtGraphic() {} NoughtGraphic::NoughtGraphic(int i_radius) { radius = i_radius; } void NoughtGraphic::draw(int xPos, int yPos, sf::RenderWindow &window, sf::Color backgroundColor) { // xPos and yPos should be pos of center m_outerShape.setFillColor(m_color); m_outerShape.setRadius(radius); m_outerShape.setPosition(xPos - radius, yPos - radius); m_innerShape.setFillColor(backgroundColor); m_innerShape.setRadius(radius * m_holeProportion); m_innerShape.setPosition(xPos - radius * m_holeProportion, yPos - radius * m_holeProportion); window.draw(m_outerShape); window.draw(m_innerShape); }
699
243
// This file is distributed under the MIT license. // See the LICENSE file for details. #pragma once #include <cstdint> #include "common.hpp" #include "forward.hpp" #include "linalg.hpp" namespace vkt { VKTAPI Error CropResize(HierarchicalVolume& dst, HierarchicalVolume& src, int32_t firstX, int32_t firstY, int32_t firstZ, int32_t lastX, int32_t lastY, int32_t lastZ); VKTAPI Error CropResize(HierarchicalVolume& dst, HierarchicalVolume& src, Vec3i first, Vec3i last); VKTAPI Error Crop(HierarchicalVolume& dst, HierarchicalVolume& src, int32_t firstX, int32_t firstY, int32_t firstZ, int32_t lastX, int32_t lastY, int32_t lastZ); VKTAPI Error Crop(HierarchicalVolume& dst, HierarchicalVolume& src, Vec3i first, Vec3i last); } // vkt
1,259
361
#include <iostream> #include <algorithm> #include <vector> using namespace std; int main() { vector<int> billu; //initialization/declaration //input billu.push_back(4); //billu[0] billu.push_back(7); //billu[1] billu.push_back(18); //billu[2] billu.push_back(45); //billu[3] billu.push_back(10); //billu[4] //output for (auto element:billu) { cout << element << " "; } cout << endl; for (int i = 0; i < billu.size(); i++) { cout << billu[i] << " "; } cout << endl; vector<int> pandu; int size; cout << endl << "enter the size for pandu"; cin >> size; for (int i = 0; i < size; i++) { int input; cin >> input; pandu.push_back(input); } cout << endl; for (auto element : pandu) { cout << element << " "; } cout << endl; billu.pop_back(); cout << endl; for (auto element : billu) { cout << element << " "; } cout<<endl; swap(billu, pandu); for (auto element : billu) { cout << element << " "; } cout<<endl; for (auto element : pandu) { cout << element << " "; } return 0; }
1,228
465
/* * This file is part of the Glaziery. * Copyright Thomas Jacob. * * READ README.TXT BEFORE USE!! */ // Main header file #include <Glaziery/src/Headers.h> Component::Component() { ASSERTION_COBJECT(this); disposed = false; maximumSize = Vector(4096, 4096); minimumSize = Vector(0, 0); parent = NULL; size = Vector(64, 32); visible = true; visibleDeferred = visible; } Component::~Component() { ASSERTION_COBJECT(this); while (!effects.IsEmpty()) { ComponentEffect * effect = effects.UnlinkFirst(); effect->onComponentDestroying(); effect->release(); } } void Component::addEffect(ComponentEffect * effect) { ASSERTION_COBJECT(this); effects.Append(effect); effect->addReference(); } void Component::addContextMenuItems(Menu * menu, Vector position, bool option1, bool option2) { ASSERTION_COBJECT(this); } void Component::appendWidget(Widget * widget) { ASSERTION_COBJECT(this); if (widget->component != NULL) throw EILLEGALSTATE("The widget is already registered to another component"); widget->component = this; widgets.Append(widget); } void Component::cancelEffects() { ASSERTION_COBJECT(this); for (int i=0; i<effects.GetCount(); i++) effects.Get(i)->cancel(); } void Component::center() { ASSERTION_COBJECT(this); Vector parentSize; if (parent != NULL) parentSize = parent->getSize(); else { PlatformAdapter * adapter = Desktop::getInstance()->getPlatformAdapter(); parentSize = adapter->getScreenSize(); } moveTo((parentSize - size) / 2); } void Component::deleteChild(Component * child) { ASSERTION_COBJECT(this); ASSERTION_COBJECT(child); if (child->getParent() != this) throw EILLEGALARGUMENT("The component is not a child of this component"); delete child; } void Component::destroy() { ASSERTION_COBJECT(this); if (disposed) return; // Add the component to the disposables. // It will be destroyed next frame. disposed = true; Desktop * desktop = Desktop::getInstance(); desktop->addDisposable(this); // Then, notify listeners. onDestroying(); } void Component::executeDeferrals() { ASSERTION_COBJECT(this); EventTarget::executeDeferrals(); if (visibleDeferred && !visible) show(); else if (!visibleDeferred && visible) hide(); } Vector Component::getAbsolutePosition() { ASSERTION_COBJECT(this); if (parent == NULL) return position; else return position + parent->getChildrenOrigin(); } Vector Component::getChildrenOrigin() { ASSERTION_COBJECT(this); return getAbsolutePosition(); } const ArrayList<ComponentEffect> & Component::getEffects() { ASSERTION_COBJECT(this); return effects; } EventTarget * Component::getEventTargetAt(Vector position) { ASSERTION_COBJECT(this); int widgetsCount = widgets.GetCount(); for (int i=0; i<widgetsCount; i++) { Widget * widget = widgets.Get(i); if (widget->isHitAt(position)) return widget; } return this; } Component * Component::getFocusChild() { ASSERTION_COBJECT(this); return NULL; } Vector Component::getMaximumSize() { ASSERTION_COBJECT(this); return maximumSize; } Vector Component::getMinimumSize() { ASSERTION_COBJECT(this); return minimumSize; } Vector Component::getOrigin() { ASSERTION_COBJECT(this); return getAbsolutePosition(); } Component * Component::getParent() { ASSERTION_COBJECT(this); return parent; } Vector Component::getPosition() { ASSERTION_COBJECT(this); return position; } class Vector Component::getSize() { ASSERTION_COBJECT(this); return size; } const ArrayList<Widget> & Component::getWidgets() { ASSERTION_COBJECT(this); return widgets; } bool Component::hasFocus() { ASSERTION_COBJECT(this); Component * parent = getParent(); if (parent != NULL) return parent->getFocusChild() == this && parent->hasFocus(); else return Desktop::getInstance()->getFocusWindowOrPopup() == this; } void Component::hide() { ASSERTION_COBJECT(this); if (!visible) return; // Invalidation must take place before hiding, because the invalidate checks that flag invalidate(); visible = false; visibleDeferred = visible; int listenersCount = listeners.GetCount(); for (int i=0; i<listenersCount; i++) { Component::Listener * componentListener = dynamic_cast<Component::Listener *>(listeners.Get(i)); if (componentListener != NULL) componentListener->onHidden(this); } } void Component::hideDeferred() { ASSERTION_COBJECT(this); setVisibleDeferred(false); } #if defined(_DEBUG) && (defined(_AFX) || defined(_AFXDLL)) IMPLEMENT_DYNAMIC(Component, EventTarget); #endif void Component::invalidate() { ASSERTION_COBJECT(this); invalidateArea(Vector(), size); } void Component::invalidateArea(Vector position, Vector size) { ASSERTION_COBJECT(this); Component * parent = getParent(); if (parent != NULL && parent->isChildVisible(this)) parent->invalidateArea(getPosition() + position, size); } bool Component::isChildVisible(Component * child) { ASSERTION_COBJECT(this); return child->isVisible(); } bool Component::isDisposed() { ASSERTION_COBJECT(this); return disposed; } bool Component::isVisible() { ASSERTION_COBJECT(this); return visible; } bool Component::isVisibleIncludingAncestors() { ASSERTION_COBJECT(this); Component * ancestor = this; while (ancestor != NULL) { if (!ancestor->isVisible()) return false; ancestor = ancestor->getParent(); } return true; } void Component::moveComponent(Component * relatedComponent, Vector position) { ASSERTION_COBJECT(this); relatedComponent->moveInternal(position, false); } bool Component::moveInternal(Vector position, bool notifyParent) { ASSERTION_COBJECT(this); if (this->position == position) return false; Vector oldPosition = this->position; this->position = position; if (parent != NULL && notifyParent) parent->onChildMoved(this, oldPosition); int listenersCount = listeners.GetCount(); for (int i=0; i<listenersCount; i++) { Component::Listener * componentListener = dynamic_cast<Component::Listener *>(listeners.Get(i)); if (componentListener != NULL) componentListener->onMoved(this, oldPosition); } invalidate(); return true; } bool Component::moveRelative(Vector delta) { ASSERTION_COBJECT(this); return moveTo(position + delta); } bool Component::moveTo(Vector position) { ASSERTION_COBJECT(this); return moveInternal(position, true); } bool Component::onAnyKey(bool option1, bool option2) { ASSERTION_COBJECT(this); bool consumed = EventTarget::onAnyKey(option1, option2); Component * focusChild = getFocusChild(); if (focusChild != NULL) if (focusChild->onAnyKey(option1, option2)) consumed = true; return consumed; } bool Component::onBackSpace() { ASSERTION_COBJECT(this); bool consumed = EventTarget::onBackSpace(); Component * focusChild = getFocusChild(); if (focusChild != NULL) if (focusChild->onBackSpace()) consumed = true; return consumed; } bool Component::onBackTab(bool secondary) { ASSERTION_COBJECT(this); bool consumed = EventTarget::onBackTab(secondary); Component * focusChild = getFocusChild(); if (focusChild != NULL) if (focusChild->onBackTab(secondary)) consumed = true; return consumed; } bool Component::onCancel() { ASSERTION_COBJECT(this); bool consumed = EventTarget::onCancel(); Component * focusChild = getFocusChild(); if (focusChild != NULL) if (focusChild->onCancel()) consumed = true; return consumed; } bool Component::onCharacter(char character, bool option1, bool option2) { ASSERTION_COBJECT(this); bool consumed = EventTarget::onCharacter(character, option1, option2); Component * focusChild = getFocusChild(); if (focusChild != NULL) if (focusChild->onCharacter(character, option1, option2)) consumed = true; return consumed; } void Component::onChildMaximumSizeChanged(Component * child, Vector oldMaximumSize) { ASSERTION_COBJECT(this); } void Component::onChildMinimumSizeChanged(Component * child, Vector oldMinimumSize) { ASSERTION_COBJECT(this); } void Component::onChildMoved(Component * child, Vector oldPosition) { ASSERTION_COBJECT(this); } void Component::onChildResized(Component * child, Vector oldSize) { ASSERTION_COBJECT(this); } void Component::onContextClick(Vector position, bool option1, bool option2) { ASSERTION_COBJECT(this); EventTarget::onContextClick(position, option1, option2); Menu * menu; if ((menu = new Menu(this)) == NULL) throw EOUTOFMEMORY; addContextMenuItems(menu, position, option1, option2); if (menu->getItems().IsEmpty()) { delete menu; return; } MenuPopup * popup = new MenuPopup(menu, true); Desktop::getInstance()->addPopup(popup); Vector popupPosition = getAbsolutePosition() + position; if (popupPosition.x + popup->getSize().x > Desktop::getInstance()->getSize().x) popupPosition.x -= popup->getSize().x; if (popupPosition.y + popup->getSize().y > Desktop::getInstance()->getSize().y) popupPosition.y -= popup->getSize().y; popup->moveTo(popupPosition); } bool Component::onCopy() { ASSERTION_COBJECT(this); bool consumed = EventTarget::onCopy(); Component * focusChild = getFocusChild(); if (focusChild != NULL) if (focusChild->onCopy()) consumed = true; return consumed; } bool Component::onCut() { ASSERTION_COBJECT(this); bool consumed = EventTarget::onCut(); Component * focusChild = getFocusChild(); if (focusChild != NULL) if (focusChild->onCut()) consumed = true; return consumed; } bool Component::onDelete() { ASSERTION_COBJECT(this); bool consumed = EventTarget::onDelete(); Component * focusChild = getFocusChild(); if (focusChild != NULL) if (focusChild->onDelete()) consumed = true; return consumed; } void Component::onDestroying() { ASSERTION_COBJECT(this); ArrayList<Component::Listener> listenersToNotify; int listenersCount = listeners.GetCount(); for (int i=0; i<listenersCount; i++) { Component::Listener * componentListener = dynamic_cast<Component::Listener *>(listeners.Get(i)); if (componentListener != NULL) { listenersToNotify.Append(componentListener); componentListener->addReference(); } } listenersCount = listenersToNotify.GetCount(); while (!listenersToNotify.IsEmpty()) { Component::Listener * listener = listenersToNotify.UnlinkFirst(); listener->onDestroying(this); listener->release(); } } bool Component::onEdit() { ASSERTION_COBJECT(this); bool consumed = EventTarget::onEdit(); Component * focusChild = getFocusChild(); if (focusChild != NULL) if (focusChild->onEdit()) consumed = true; return consumed; } bool Component::onEnter(bool option1, bool option2) { ASSERTION_COBJECT(this); bool consumed = EventTarget::onEnter(option1, option2); Component * focusChild = getFocusChild(); if (focusChild != NULL) if (focusChild->onEnter(option1, option2)) consumed = true; return consumed; } void Component::onGotFocus(bool byParent) { ASSERTION_COBJECT(this); // First notify listeners of this component about focus gain int listenersCount = listeners.GetCount(); for (int i=0; i<listenersCount; i++) { Component::Listener * componentListener = dynamic_cast<Component::Listener *>(listeners.Get(i)); if (componentListener != NULL) componentListener->onGotFocus(this, byParent); } // Then notify child Component * focusChild = getFocusChild(); if (focusChild != NULL) focusChild->onGotFocus(true); // Finally, invalidate the component invalidate(); } bool Component::onHotKey(char character, bool option1, bool option2) { ASSERTION_COBJECT(this); bool consumed = EventTarget::onHotKey(character, option1, option2); Component * focusChild = getFocusChild(); if (focusChild != NULL) if (focusChild->onHotKey(character, option1, option2)) consumed = true; return consumed; } bool Component::onKeyStroke(int keyCode, bool option1, bool option2) { ASSERTION_COBJECT(this); bool consumed = EventTarget::onKeyStroke(keyCode, option1, option2); Component * focusChild = getFocusChild(); if (focusChild != NULL) if (focusChild->onKeyStroke(keyCode, option1, option2)) consumed = true; return consumed; } void Component::onLostFocus() { ASSERTION_COBJECT(this); // First notify child about focus loss Component * focusChild = getFocusChild(); if (focusChild != NULL) focusChild->onLostFocus(); // Then notify listeners of this component int listenersCount = listeners.GetCount(); for (int i=0; i<listenersCount; i++) { Component::Listener * componentListener = dynamic_cast<Component::Listener *>(listeners.Get(i)); if (componentListener != NULL) componentListener->onLostFocus(this); } // Finally, invalidate the component invalidate(); } void Component::onMaximumSizeChanged(Vector oldMaximumSize) { ASSERTION_COBJECT(this); } void Component::onMinimumSizeChanged(Vector oldMinimumSize) { ASSERTION_COBJECT(this); } bool Component::onMoveDown(bool option1, bool option2) { ASSERTION_COBJECT(this); bool consumed = EventTarget::onMoveDown(option1, option2); Component * focusChild = getFocusChild(); if (focusChild != NULL) if (focusChild->onMoveDown(option1, option2)) consumed = true; return consumed; } bool Component::onMoveLeft(bool option1, bool option2) { ASSERTION_COBJECT(this); bool consumed = EventTarget::onMoveLeft(option1, option2); Component * focusChild = getFocusChild(); if (focusChild != NULL) if (focusChild->onMoveLeft(option1, option2)) consumed = true; return consumed; } bool Component::onMoveRight(bool option1, bool option2) { ASSERTION_COBJECT(this); bool consumed = EventTarget::onMoveRight(option1, option2); Component * focusChild = getFocusChild(); if (focusChild != NULL) if (focusChild->onMoveRight(option1, option2)) consumed = true; return consumed; } bool Component::onMoveToEnd(bool option1, bool option2) { ASSERTION_COBJECT(this); bool consumed = EventTarget::onMoveToEnd(option1, option2); Component * focusChild = getFocusChild(); if (focusChild != NULL) if (focusChild->onMoveToEnd(option1, option2)) consumed = true; return consumed; } bool Component::onMoveToStart(bool option1, bool option2) { ASSERTION_COBJECT(this); bool consumed = EventTarget::onMoveToStart(option1, option2); Component * focusChild = getFocusChild(); if (focusChild != NULL) if (focusChild->onMoveToStart(option1, option2)) consumed = true; return consumed; } bool Component::onMoveUp(bool option1, bool option2) { ASSERTION_COBJECT(this); bool consumed = EventTarget::onMoveUp(option1, option2); Component * focusChild = getFocusChild(); if (focusChild != NULL) if (focusChild->onMoveUp(option1, option2)) consumed = true; return consumed; } bool Component::onPageDown(bool option1, bool option2) { ASSERTION_COBJECT(this); bool consumed = EventTarget::onPageDown(option1, option2); Component * focusChild = getFocusChild(); if (focusChild != NULL) if (focusChild->onPageDown(option1, option2)) consumed = true; return consumed; } bool Component::onPageUp(bool option1, bool option2) { ASSERTION_COBJECT(this); bool consumed = EventTarget::onPageUp(option1, option2); Component * focusChild = getFocusChild(); if (focusChild != NULL) if (focusChild->onPageUp(option1, option2)) consumed = true; return consumed; } bool Component::onPaste() { ASSERTION_COBJECT(this); bool consumed = EventTarget::onPaste(); Component * focusChild = getFocusChild(); if (focusChild != NULL) if (focusChild->onPaste()) consumed = true; return consumed; } bool Component::onSelectAll() { ASSERTION_COBJECT(this); bool consumed = EventTarget::onSelectAll(); Component * focusChild = getFocusChild(); if (focusChild != NULL) if (focusChild->onSelectAll()) consumed = true; return consumed; } bool Component::onTab(bool secondary) { ASSERTION_COBJECT(this); bool consumed = EventTarget::onTab(secondary); Component * focusChild = getFocusChild(); if (focusChild != NULL) if (focusChild->onTab(secondary)) consumed = true; return consumed; } void Component::prependWidget(Widget * widget) { ASSERTION_COBJECT(this); if (widget->component != NULL) throw EILLEGALARGUMENT("The widget is already registered to another component"); widget->component = this; widgets.Prepend(widget); } void Component::removeEffect(ComponentEffect * effect) { ASSERTION_COBJECT(this); ComponentEffect * unlinkedEffect = effects.Unlink(effect); if (unlinkedEffect != NULL) unlinkedEffect->release(); } void Component::removeWidget(Widget * widget) { ASSERTION_COBJECT(this); widgets.Delete(widget); } bool Component::resize(Vector size) { ASSERTION_COBJECT(this); return resizeInternal(size, true); } bool Component::resizeToMaximum() { ASSERTION_COBJECT(this); return resizeInternal(maximumSize, true); } bool Component::resizeToMinimum() { ASSERTION_COBJECT(this); return resizeInternal(minimumSize, true); } void Component::resizeComponent(Component * relatedComponent, Vector size) { ASSERTION_COBJECT(this); relatedComponent->resizeInternal(size, false); } bool Component::resizeInternal(Vector size, bool notifyParent) { ASSERTION_COBJECT(this); size = Vector(size.x > maximumSize.x ? maximumSize.x : size.x, size.y > maximumSize.y ? maximumSize.y : size.y); size = Vector(size.x < minimumSize.x ? minimumSize.x : size.x, size.y < minimumSize.y ? minimumSize.y : size.y); if (this->size == size) return false; Vector oldSize = this->size; this->size = size; if (parent != NULL && notifyParent) parent->onChildResized(this, oldSize); int listenersCount = listeners.GetCount(); for (int i=0; i<listenersCount; i++) { Component::Listener * componentListener = dynamic_cast<Component::Listener *>(listeners.Get(i)); if (componentListener != NULL) componentListener->onResized(this, oldSize); } invalidate(); return true; } void Component::setComponentParent(Component * child) { ASSERTION_COBJECT(this); if (child->getParent() != NULL) throw EILLEGALARGUMENT("The component already has a parent, it may not be changed"); child->parent = this; } void Component::setComponentMaximumSize(Component * component, Vector maximumSize, bool notifyParent) { ASSERTION_COBJECT(this); component->setMaximumSizeInternal(maximumSize, notifyParent); } void Component::setComponentMinimumSize(Component * component, Vector minimumSize, bool notifyParent) { ASSERTION_COBJECT(this); component->setMinimumSizeInternal(minimumSize, notifyParent); } void Component::setDisposed() { ASSERTION_COBJECT(this); disposed = true; } void Component::setMaximumSize(Vector maximumSize) { ASSERTION_COBJECT(this); setMaximumSizeInternal(maximumSize, true); } void Component::setMaximumSizeInternal(Vector maximumSize, bool notifyParent) { ASSERTION_COBJECT(this); if (maximumSize.x < 0) maximumSize.x = 0; if (maximumSize.y < 0) maximumSize.y = 0; if (this->maximumSize == maximumSize) return; Vector oldMaximumSize = this->maximumSize; this->maximumSize = maximumSize; onMaximumSizeChanged(oldMaximumSize); if (notifyParent && parent != NULL) parent->onChildMaximumSizeChanged(this, oldMaximumSize); if (!(minimumSize <= maximumSize)) setMinimumSize(Vector(minimumSize.x > maximumSize.x ? maximumSize.x : minimumSize.x, minimumSize.y > maximumSize.y ? maximumSize.y : minimumSize.y)); if (!(size <= maximumSize)) resize(Vector(size.x > maximumSize.x ? maximumSize.x : size.x, size.y > maximumSize.y ? maximumSize.y : size.y)); } void Component::setMinimumSize(Vector minimumSize) { ASSERTION_COBJECT(this); setMinimumSizeInternal(minimumSize, true); } void Component::setMinimumSizeInternal(Vector minimumSize, bool notifyParent) { ASSERTION_COBJECT(this); if (minimumSize.x < 0) minimumSize.x = 0; if (minimumSize.y < 0) minimumSize.y = 0; if (this->minimumSize == minimumSize) return; Vector oldMinimumSize = this->minimumSize; this->minimumSize = minimumSize; onMinimumSizeChanged(oldMinimumSize); if (notifyParent && parent != NULL) parent->onChildMinimumSizeChanged(this, oldMinimumSize); if (!(maximumSize >= minimumSize)) setMaximumSize(Vector(maximumSize.x < minimumSize.x ? minimumSize.x : maximumSize.x, maximumSize.y < minimumSize.y ? minimumSize.y : maximumSize.y)); if (!(size >= minimumSize)) resize(Vector(size.x < minimumSize.x ? minimumSize.x : size.x, size.y < minimumSize.y ? minimumSize.y : size.y)); } void Component::setSkinData(SkinData * skinData) { ASSERTION_COBJECT(this); GlazieryObject::setSkinData(skinData); skinData->component = this; } void Component::setVisible(bool visible) { ASSERTION_COBJECT(this); if (visible) show(); else hide(); } void Component::setVisibleDeferred(bool visible) { ASSERTION_COBJECT(this); if (visible) showDeferred(); else hideDeferred(); } void Component::show() { ASSERTION_COBJECT(this); if (visible) return; visible = true; visibleDeferred = visible; int listenersCount = listeners.GetCount(); for (int i=0; i<listenersCount; i++) { Component::Listener * componentListener = dynamic_cast<Component::Listener *>(listeners.Get(i)); if (componentListener != NULL) componentListener->onShown(this); } invalidate(); } BalloonPopup * Component::showBalloonPopup(const String & text) { ASSERTION_COBJECT(this); BalloonPopup * popup; if ((popup = new BalloonPopup) == NULL) throw EOUTOFMEMORY; Desktop::getInstance()->addPopup(popup); popup->setMessage(text); popup->pointTo(this); return popup; } void Component::showDeferred() { ASSERTION_COBJECT(this); Mutex * mutex = Desktop::getInstance()->getDeferralMutex(); if (!mutex->lock()) return; visibleDeferred = visible; Desktop::getInstance()->deferObject(this); mutex->release(); } String Component::toString() { ASSERTION_COBJECT(this); String string; string.Format("Component(position:%s,size:%s)", (const char *) position.toString(), (const char *) size.toString()); return string; } void Component::tutorialClick(PointerEffect::ButtonEffect buttonEffect, bool option1, bool option2, long time) { ASSERTION_COBJECT(this); Desktop * desktop = Desktop::getInstance(); if (!Desktop::getInstance()->isTutorialMode()) throw EILLEGALSTATE("Use the tutorial methods in Tutorial::run() implementations only"); if (time < 0) time = 1000; if (buttonEffect == PointerEffect::BUTTONEFFECT_DRAGDROP) throw EILLEGALARGUMENT("tutorialClick cannot have a drag-drop button effect. Use tutorialDragDropTo instead."); Vector positionEnd = getAbsolutePosition() + getSize() / 2; if (Desktop::getInstance()->getPointerPosition() == positionEnd) time = 0; PointerEffect * pointerEffect; if ((pointerEffect = new PointerEffect(time)) == NULL) \ throw EOUTOFMEMORY; pointerEffect->setPositionEnd(positionEnd); pointerEffect->setTimeCurveToAcceleration(); pointerEffect->setButtonEffect(buttonEffect); pointerEffect->setButtonOption1(option1); pointerEffect->setButtonOption2(option2); Desktop::getInstance()->addEffect(pointerEffect); pointerEffect->waitFor(); } void Component::tutorialDragDropTo(Vector position, bool option1, bool option2, long time) { ASSERTION_COBJECT(this); if (!Desktop::getInstance()->isTutorialMode()) throw EILLEGALSTATE("Use the tutorial methods in Tutorial::run() implementations only"); if (time < 0) time = 1000; EffectSequence * sequence; if ((sequence = new EffectSequence) == NULL) throw EOUTOFMEMORY; Vector dragPosition = getAbsolutePosition() + getSize() / 2; if (Desktop::getInstance()->getPointerPosition() == dragPosition) time = 0; PointerEffect * effect; if ((effect = new PointerEffect(time)) == NULL) \ throw EOUTOFMEMORY; effect->setPositionEnd(dragPosition); effect->setTimeCurveToAcceleration(); sequence->appendEffect(effect); if ((effect = new PointerEffect(time)) == NULL) \ throw EOUTOFMEMORY; effect->setPositionEnd(position); effect->setTimeCurveToAcceleration(); effect->setButtonEffect(PointerEffect::BUTTONEFFECT_DRAGDROP); effect->setButtonOption1(option1); effect->setButtonOption2(option2); sequence->appendEffect(effect); Desktop::getInstance()->addEffect(sequence); effect->waitFor(); } void Component::tutorialMoveTo(long time) { ASSERTION_COBJECT(this); if (!Desktop::getInstance()->isTutorialMode()) throw EILLEGALSTATE("Use the tutorial methods in Tutorial::run() implementations only"); Vector positionEnd = getAbsolutePosition() + getSize() / 2; if (Desktop::getInstance()->getPointerPosition() == positionEnd) return; if (time < 0) time = 1000; PointerEffect * effect; if ((effect = new PointerEffect(time)) == NULL) \ throw EOUTOFMEMORY; effect->setPositionEnd(positionEnd); effect->setTimeCurveToAcceleration(); Desktop::getInstance()->addEffect(effect); effect->waitFor(); } void Component::unsetComponentParent(Component * child) { ASSERTION_COBJECT(this); ASSERTION_COBJECT(child); child->parent = NULL; } void Component::Listener::onDestroying(Component * component) { ASSERTION_COBJECT(this); } void Component::Listener::onGotFocus(Component * component, bool byParent) { ASSERTION_COBJECT(this); } void Component::Listener::onHidden(Component * component) { ASSERTION_COBJECT(this); } void Component::Listener::onLostFocus(Component * component) { ASSERTION_COBJECT(this); } void Component::Listener::onMoved(Component * component, Vector oldPosition) { ASSERTION_COBJECT(this); } void Component::Listener::onResized(Component * component, Vector oldSize) { ASSERTION_COBJECT(this); } void Component::Listener::onShown(Component * component) { ASSERTION_COBJECT(this); }
25,603
8,964
// // // #include "AnnotateValues/AnnotateInstructions.hpp" #include "llvm/IR/Module.h" // using llvm::Module #include "llvm/IR/Type.h" // using llvm::IntType #include "llvm/IR/Constants.h" // using llvm::ConstantInt #include "llvm/IR/Metadata.h" // using llvm::Metadata // using llvm::MDNode // using llvm::ConstantAsMetadata #include "llvm/IR/MDBuilder.h" // using llvm::MDBuilder #include "llvm/ADT/SmallVector.h" // using llvm::SmallVector #include "llvm/Support/Casting.h" // using llvm::dyn_cast #include <cassert> // using assert namespace icsa { namespace AnnotateInstructions { bool Reader::has(const llvm::Instruction &CurInstruction) const { return nullptr != CurInstruction.getMetadata(key()); } InstructionIDTy Reader::get(const llvm::Instruction &CurInstruction) const { const auto *IDNode = CurInstruction.getMetadata(key()); assert(nullptr != IDNode && "Instruction does not have the requested metadata!"); const auto *constantMD = llvm::dyn_cast<llvm::ConstantAsMetadata>(IDNode->getOperand(1).get()); const auto &IDConstant = constantMD->getValue()->getUniqueInteger(); return IDConstant.getLimitedValue(); } // InstructionIDTy Writer::put(llvm::Instruction &CurInstruction) { auto &curContext = CurInstruction.getParent()->getParent()->getContext(); llvm::MDBuilder builder{curContext}; auto *intType = llvm::Type::getInt32Ty(curContext); auto curID = current(); llvm::SmallVector<llvm::Metadata *, 1> IDValues{ builder.createConstant(llvm::ConstantInt::get(intType, curID))}; next(); CurInstruction.setMetadata(key(), llvm::MDNode::get(curContext, IDValues)); return curID; } } // namespace AnnotateInstructions } // namespace icsa
1,724
599
#pragma once #include "Ctesconf.hpp" #include "Tablero.hpp" #include "Jugador.hpp" #include "CDado.hpp" #include <fstream> #include <ostream> class Game { private: Tablero t; Jugador j[MAX_JUGADORES]; CDado d; bool swio; // Archivos de entrada/salida para el caso de configuracion de IO por archivos --------- std::ifstream fi{"input"}; std::ofstream fo{"output"}; public: static int turno; Game(); Game(std::string, bool, bool); void start(); void outMsg(std::string); };
519
186
/* * Copyright (C) 2007-2013 German Aerospace Center (DLR/SC) * * Created: 2010-08-13 Markus Litz <Markus.Litz@dlr.de> * 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 * @brief Implementation of CPACS fuselages handling routines. */ #include "CCPACSFuselages.h" #include "CCPACSFuselage.h" #include "CCPACSAircraftModel.h" #include "CCPACSFuselageProfiles.h" #include "CCPACSConfiguration.h" #include "CTiglError.h" namespace tigl { CCPACSFuselages::CCPACSFuselages(CCPACSAircraftModel* parent, CTiglUIDManager* uidMgr) : generated::CPACSFuselages(parent, uidMgr) {} CCPACSFuselages::CCPACSFuselages(CCPACSRotorcraftModel* parent, CTiglUIDManager* uidMgr) : generated::CPACSFuselages(parent, uidMgr) {} // Read CPACS fuselages element void CCPACSFuselages::ReadCPACS(const TixiDocumentHandle& tixiHandle, const std::string& xpath) { generated::CPACSFuselages::ReadCPACS(tixiHandle, xpath); } // Write CPACS fuselage elements void CCPACSFuselages::WriteCPACS(const TixiDocumentHandle& tixiHandle, const std::string& xpath) const { generated::CPACSFuselages::WriteCPACS(tixiHandle, xpath); } // Returns the total count of fuselages in a configuration int CCPACSFuselages::GetFuselageCount() const { return static_cast<int>(m_fuselages.size()); } // Returns the fuselage for a given index. CCPACSFuselage& CCPACSFuselages::GetFuselage(int index) const { index--; if (index < 0 || index >= GetFuselageCount()) { throw CTiglError("Invalid index in CCPACSFuselages::GetFuselage", TIGL_INDEX_ERROR); } return *m_fuselages[index]; } // Returns the fuselage for a given UID. CCPACSFuselage& CCPACSFuselages::GetFuselage(const std::string& UID) const { return *m_fuselages[GetFuselageIndex(UID) - 1]; } // Returns the fuselage index for a given UID. int CCPACSFuselages::GetFuselageIndex(const std::string& UID) const { for (int i=0; i < GetFuselageCount(); i++) { const std::string tmpUID(m_fuselages[i]->GetUID()); if (tmpUID == UID) { return i+1; } } // UID not there throw CTiglError("Invalid UID in CCPACSFuselages::GetFuselageIndex", TIGL_UID_ERROR); } } // end namespace tigl
2,696
1,011
#include <iostream> #include <vector> #define NORTH 1 #define SOUTH 2 #define WEST 3 #define EAST 4 void get_direction(int command, int& dx, int & dy) { switch(command) { case NORTH: dx=0;dy=1;break; case SOUTH: dx=0;dy=-1;break; case WEST: dx=-1;dy=0;break; case EAST: dx=1;dy=0;break; default:std::cout<<command<<" IS NOT A VALID DIRECTION"<<std::endl; } } struct flower { bool flowing = true,waiting =false; int px,py,size; flower(int pos_x,int pos_y,int sze) {px=pos_x;py=pos_y;flowing=true;size = sze;} flower(){}; }; struct tile { char type,p1,p2; int dist=-1,x,y; }; #define WALL '#' #define PATH '.' #define PORTAL 'p' #define USED 'O' #define NOTHING ' ' int main() { int x=0,x_max=0,y_max=0; int x_start,y_start,x_end,y_end; char a=std::cin.get(); tile robot_pos[300][300]; std::vector<int> lines_with_letters ={0}; std::vector<std::pair<int,int>> portals={}; while (!std::cin.eof()) { if (a!='\n') { if ('A'<=a&&a<='Z') { robot_pos[x][y_max].type = a; if (lines_with_letters.back() != y_max)lines_with_letters.push_back(y_max); } else if (a=='.') { robot_pos[x][y_max].type = a; } else if (a=='#') { robot_pos[x][y_max].type = a; } else if (a!=' ') { std::cout<<"UNEXPECTED CHAR: "<<a<<" (VALUE "<<static_cast<int>(a)<<")\n"<<std::flush; } else robot_pos[x][y_max].type = a; x++; } else { if (x>x_max)x_max = x; y_max++; x=0; } a=std::cin.get(); } std::cout<<--x_max<<' '<<--y_max<<std::endl; for (int j=0;j<=y_max;j++) { for (int i=0;i<=x_max;i++) { std::cout<<robot_pos[i][j].type<<' '; }std::cout<<'\t'<<j<<"\n"; }std::cout<<std::flush; for (int line : lines_with_letters) { for (int i=0;i<=x_max;i++) { if (robot_pos[i][line].type <= 'Z' && 'A' <= robot_pos[i][line].type) { if (line < y_max-3 && robot_pos[i][line+1].type <='Z' && robot_pos[i][line+1].type >='A' && robot_pos[i][line+2].type == PATH) { robot_pos[i][line+2].p1 = robot_pos[i][line].type; robot_pos[i][line+2].p2 = robot_pos[i][line+1].type; portals.push_back({i,line+2}); } else if (x < x_max-2 && robot_pos[i+1][line].type <='Z' && robot_pos[i+1][line].type >='A' && robot_pos[i-1][line].type == PATH) { robot_pos[i-1][line].p1 = robot_pos[i][line].type; robot_pos[i-1][line].p2 = robot_pos[i+1][line].type; portals.push_back({i-1,line}); } else if (x < x_max-3 && robot_pos[i+1][line].type <='Z' && robot_pos[i+1][line].type >='A' && robot_pos[i+2][line].type == PATH) { robot_pos[i+2][line].p1 = robot_pos[i][line].type; robot_pos[i+2][line].p2 = robot_pos[i+1][line].type; portals.push_back({i+2,line}); } else if (line < y_max && robot_pos[i][line+1].type <='Z' && robot_pos[i][line+1].type >='A' && robot_pos[i][line-1].type == PATH) { robot_pos[i][line-1].p1 = robot_pos[i][line].type; robot_pos[i][line-1].p2 = robot_pos[i][line+1].type; portals.push_back({i,line-1}); } robot_pos[i][line].type=NOTHING; } } } lines_with_letters.clear(); int st,ed; for (int i=0;i<portals.size();i++){ if (robot_pos[portals[i].first][portals[i].second].p1 == 'A' && robot_pos[portals[i].first][portals[i].second].p2 == 'A'){ x_start = portals[i].first; y_start = portals[i].second; st = i; } else if(robot_pos[portals[i].first][portals[i].second].p1 == 'Z' && robot_pos[portals[i].first][portals[i].second].p2 == 'Z') { x_end = portals[i].first; y_end = portals[i].second; ed = i; } else for(int j=i+1;j<portals.size();j++) if(robot_pos[portals[i].first][portals[i].second].p1 == robot_pos[portals[j].first][portals[j].second].p1 && robot_pos[portals[i].first][portals[i].second].p2 == robot_pos[portals[j].first][portals[j].second].p2) { std::cout<< "Connecting "<<robot_pos[portals[i].first][portals[i].second].p1<<robot_pos[portals[i].first][portals[i].second].p2<<" on "<<portals[i].first<<','<<portals[i].second<<" to "<<portals[j].first<<','<<portals[j].second<<std::endl; robot_pos[portals[i].first][portals[i].second].x = portals[j].first; robot_pos[portals[i].first][portals[i].second].y = portals[j].second; robot_pos[portals[j].first][portals[j].second].x = portals[i].first; robot_pos[portals[j].first][portals[j].second].y = portals[i].second; robot_pos[portals[i].first][portals[i].second].type = PORTAL; robot_pos[portals[j].first][portals[j].second].type = PORTAL; } } for (int i=0;i<portals.size();i++) { if (i!=st && i!= ed && robot_pos[portals[i].first][portals[i].second].type != PORTAL) { std::cout<<"ERROR: "<<robot_pos[portals[i].first][portals[i].second].p1<<robot_pos[portals[i].first][portals[i].second].p2<<" ON "<< portals[i].first<<','<<portals[i].second<<" IS NOT CONNECTED"<<std::endl; } } std::cout<<"SEARCHING ROUTE FROM "<<x_start<<','<<y_start<<" TO "<<x_end<<','<<y_end<<std::endl; for (int j=0;j<y_max;j++) { for (int i=0;i<x_max;i++) { std::cout<<robot_pos[i][j].type<<' '; }std::cout<<"\n"; }std::cout<<std::flush; flower myflowers[2048]; bool flowed; int flower_cnt=1,px,py,dx,dy; myflowers[0]=flower(x_start,y_start,0); unsigned cnt=0; while (robot_pos[x_end][y_end].type != USED) { int dummy=flower_cnt; for (int flwr=0;flwr<dummy;flwr++) { if (!myflowers[flwr].flowing){ continue; } if (myflowers[flwr].waiting) { myflowers[flwr].waiting = false; myflowers[flwr].size++; } px=myflowers[flwr].px; py=myflowers[flwr].py; flowed = false; for (int i=1;i<=4;i++) { get_direction(i,dx,dy); if (robot_pos[px+dx][py+dy].type==PATH || robot_pos[px+dx][py+dy].type==PORTAL) { int new_x=px+dx,new_y=py+dy; bool should_wait = false; if (robot_pos[new_x][new_y].type==PORTAL) { new_x = robot_pos[px+dx][py+dy].x; new_y = robot_pos[px+dx][py+dy].y; should_wait=true; } if (!flowed) { myflowers[flwr].px = new_x; myflowers[flwr].py = new_y; myflowers[flwr].size++; myflowers[flwr].waiting = should_wait; } else { std::cout<<"SIZE: "<<myflowers[flwr].size; myflowers[flower_cnt]=flower(new_x,new_y,myflowers[flwr].size); std::cout<<','<<myflowers[flower_cnt].size<<std::endl; myflowers[flower_cnt].waiting = should_wait; flower_cnt++; } robot_pos[px+dx][py+dy].type = robot_pos[new_x][new_y].type = USED; robot_pos[px+dx][py+dy].dist = myflowers[flwr].size; flowed = true; } } if (!flowed) { myflowers[flwr].flowing = false; } } std::cout<<"\n\nAFTER "<<cnt+1<<" MINUTES:"<<std::endl; for(int j=0;j<=y_max;j++){ for(int i=0;i<=x_max;i++){ if (i==x_end && j==y_end) std::cout<<'X'; else std::cout<<robot_pos[i][j].type; }std::cout<<std::endl; } ++cnt; } std::cout<<robot_pos[x_end][y_end].dist<<std::endl; return 0; }
7,462
3,323
#include "Ast.h" namespace lws { //----------------------Expressions----------------------------- IntNumExpr::IntNumExpr() : value(0) { } IntNumExpr::IntNumExpr(int64_t value) : value(value) { } IntNumExpr::~IntNumExpr() { } std::wstring IntNumExpr::Stringify() { return std::to_wstring(value); } AstType IntNumExpr::Type() { return AST_INT; } RealNumExpr::RealNumExpr() : value(0.0) { } RealNumExpr::RealNumExpr(double value) : value(value) { } RealNumExpr::~RealNumExpr() { } std::wstring RealNumExpr::Stringify() { return std::to_wstring(value); } AstType RealNumExpr::Type() { return AST_REAL; } StrExpr::StrExpr() { } StrExpr::StrExpr(std::wstring_view str) : value(str) { } StrExpr::~StrExpr() { } std::wstring StrExpr::Stringify() { return L"\"" + value + L"\""; } AstType StrExpr::Type() { return AST_STR; } NullExpr::NullExpr() { } NullExpr::~NullExpr() { } std::wstring NullExpr::Stringify() { return L"null"; } AstType NullExpr::Type() { return AST_NULL; } BoolExpr::BoolExpr() : value(false) { } BoolExpr::BoolExpr(bool value) : value(value) { } BoolExpr::~BoolExpr() { } std::wstring BoolExpr::Stringify() { return value ? L"true" : L"false"; } AstType BoolExpr::Type() { return AST_BOOL; } IdentifierExpr::IdentifierExpr() { } IdentifierExpr::IdentifierExpr(std::wstring_view literal) : literal(literal) { } IdentifierExpr::~IdentifierExpr() { } std::wstring IdentifierExpr::Stringify() { return literal; } AstType IdentifierExpr::Type() { return AST_IDENTIFIER; } ArrayExpr::ArrayExpr() { } ArrayExpr::ArrayExpr(std::vector<Expr *> elements) : elements(elements) { } ArrayExpr::~ArrayExpr() { std::vector<Expr *>().swap(elements); } std::wstring ArrayExpr::Stringify() { std::wstring result = L"["; if (!elements.empty()) { for (auto e : elements) result += e->Stringify() + L","; result = result.substr(0, result.size() - 1); } result += L"]"; return result; } AstType ArrayExpr::Type() { return AST_ARRAY; } TableExpr::TableExpr() { } TableExpr::TableExpr(std::unordered_map<Expr *, Expr *> elements) : elements(elements) { } TableExpr::~TableExpr() { std::unordered_map<Expr *, Expr *>().swap(elements); } std::wstring TableExpr::Stringify() { std::wstring result = L"{"; if (!elements.empty()) { for (auto [key, value] : elements) result += key->Stringify() + L":" + value->Stringify(); result = result.substr(0, result.size() - 1); } result += L"}"; return result; } AstType TableExpr::Type() { return AST_TABLE; } GroupExpr::GroupExpr() : expr(nullptr) { } GroupExpr::GroupExpr(Expr *expr) : expr(expr) { } GroupExpr::~GroupExpr() { } std::wstring GroupExpr::Stringify() { return L"(" + expr->Stringify() + L")"; } AstType GroupExpr::Type() { return AST_GROUP; } PrefixExpr::PrefixExpr() : right(nullptr) { } PrefixExpr::PrefixExpr(std::wstring_view op, Expr *right) : op(op), right(right) { } PrefixExpr::~PrefixExpr() { delete right; right = nullptr; } std::wstring PrefixExpr::Stringify() { return op + right->Stringify(); } AstType PrefixExpr::Type() { return AST_PREFIX; } InfixExpr::InfixExpr() : left(nullptr), right(nullptr) { } InfixExpr::InfixExpr(std::wstring_view op, Expr *left, Expr *right) : op(op), left(left), right(right) { } InfixExpr::~InfixExpr() { delete left; left = nullptr; delete right; right = nullptr; } std::wstring InfixExpr::Stringify() { return left->Stringify() + op + right->Stringify(); } AstType InfixExpr::Type() { return AST_INFIX; } PostfixExpr::PostfixExpr() : left(nullptr) { } PostfixExpr::PostfixExpr(Expr *left, std::wstring_view op) : left(left), op(op) { } PostfixExpr::~PostfixExpr() { delete left; left = nullptr; } std::wstring PostfixExpr::Stringify() { return left->Stringify() + op; } AstType PostfixExpr::Type() { return AST_POSTFIX; } ConditionExpr::ConditionExpr() : condition(nullptr), trueBranch(nullptr), falseBranch(nullptr) { } ConditionExpr::ConditionExpr(Expr *condition, Expr *trueBranch, Expr *falseBranch) : condition(condition), trueBranch(trueBranch), falseBranch(falseBranch) { } ConditionExpr::~ConditionExpr() { delete condition; condition = nullptr; delete trueBranch; trueBranch = nullptr; delete falseBranch; trueBranch = nullptr; } std::wstring ConditionExpr::Stringify() { return condition->Stringify() + L"?" + trueBranch->Stringify() + L":" + falseBranch->Stringify(); } AstType ConditionExpr::Type() { return AST_CONDITION; } IndexExpr::IndexExpr() : ds(nullptr), index(nullptr) { } IndexExpr::IndexExpr(Expr *ds, Expr *index) : ds(ds), index(index) { } IndexExpr::~IndexExpr() { delete ds; ds = nullptr; delete index; index = nullptr; } std::wstring IndexExpr::Stringify() { return ds->Stringify() + L"[" + index->Stringify() + L"]"; } AstType IndexExpr::Type() { return AST_INDEX; } RefExpr::RefExpr() : refExpr(nullptr) { } RefExpr::RefExpr(Expr *refExpr) : refExpr(refExpr) {} RefExpr::~RefExpr() { } std::wstring RefExpr::Stringify() { return L"&" + refExpr->Stringify(); } AstType RefExpr::Type() { return AST_REF; } LambdaExpr::LambdaExpr() : body(nullptr) { } LambdaExpr::LambdaExpr(std::vector<IdentifierExpr *> parameters, ScopeStmt *body) : parameters(parameters), body(body) { } LambdaExpr::~LambdaExpr() { std::vector<IdentifierExpr *>().swap(parameters); delete body; body = nullptr; } std::wstring LambdaExpr::Stringify() { std::wstring result = L"fn("; if (!parameters.empty()) { for (auto param : parameters) result += param->Stringify() + L","; result = result.substr(0, result.size() - 1); } result += L")"; result += body->Stringify(); return result; } AstType LambdaExpr::Type() { return AST_LAMBDA; } FunctionCallExpr::FunctionCallExpr() { } FunctionCallExpr::FunctionCallExpr(Expr *name, std::vector<Expr *> arguments) : name(name), arguments(arguments) { } FunctionCallExpr::~FunctionCallExpr() { } std::wstring FunctionCallExpr::Stringify() { std::wstring result = name->Stringify() + L"("; if (!arguments.empty()) { for (const auto &arg : arguments) result += arg->Stringify() + L","; result = result.substr(0, result.size() - 1); } result += L")"; return result; } AstType FunctionCallExpr::Type() { return AST_FUNCTION_CALL; } ClassCallExpr::ClassCallExpr() : callee(nullptr), callMember(nullptr) { } ClassCallExpr::ClassCallExpr(Expr *callee, Expr *callMember) : callee(callee), callMember(callMember) { } ClassCallExpr::~ClassCallExpr() { } std::wstring ClassCallExpr::Stringify() { return callee->Stringify() + L"." + callMember->Stringify(); } AstType ClassCallExpr::Type() { return AST_CLASS_CALL; } //----------------------Statements----------------------------- ExprStmt::ExprStmt() : expr(nullptr) { } ExprStmt::ExprStmt(Expr *expr) : expr(expr) { } ExprStmt::~ExprStmt() { delete expr; expr = nullptr; } std::wstring ExprStmt::Stringify() { return expr->Stringify() + L";"; } AstType ExprStmt::Type() { return AST_EXPR; } LetStmt::LetStmt() { } LetStmt::LetStmt(const std::unordered_map<IdentifierExpr *, VarDesc> &variables) : variables(variables) { } LetStmt::~LetStmt() { std::unordered_map<IdentifierExpr *, VarDesc>().swap(variables); } std::wstring LetStmt::Stringify() { std::wstring result = L"let "; if (!variables.empty()) { for (auto [key, value] : variables) result += key->Stringify() + L":" + value.type + L"=" + value.value->Stringify() + L","; result = result.substr(0, result.size() - 1); } return result + L";"; } AstType LetStmt::Type() { return AST_LET; } ConstStmt::ConstStmt() { } ConstStmt::ConstStmt(const std::unordered_map<IdentifierExpr *, VarDesc> &consts) : consts(consts) { } ConstStmt::~ConstStmt() { std::unordered_map<IdentifierExpr *, VarDesc>().swap(consts); } std::wstring ConstStmt::Stringify() { std::wstring result = L"const "; if (!consts.empty()) { for (auto [key, value] : consts) result += key->Stringify() + L":" + value.type + L"=" + value.value->Stringify() + L","; result = result.substr(0, result.size() - 1); } return result + L";"; } AstType ConstStmt::Type() { return AST_CONST; } ReturnStmt::ReturnStmt() : expr(nullptr) { } ReturnStmt::ReturnStmt(Expr *expr) : expr(expr) { } ReturnStmt::~ReturnStmt() { delete expr; expr = nullptr; } std::wstring ReturnStmt::Stringify() { if (expr) return L"return " + expr->Stringify() + L";"; else return L"return;"; } AstType ReturnStmt::Type() { return AST_RETURN; } IfStmt::IfStmt() : condition(nullptr), thenBranch(nullptr), elseBranch(nullptr) { } IfStmt::IfStmt(Expr *condition, Stmt *thenBranch, Stmt *elseBranch) : condition(condition), thenBranch(thenBranch), elseBranch(elseBranch) { } IfStmt::~IfStmt() { delete condition; condition = nullptr; delete thenBranch; thenBranch = nullptr; delete elseBranch; elseBranch = nullptr; } std::wstring IfStmt::Stringify() { std::wstring result; result = L"if(" + condition->Stringify() + L")" + thenBranch->Stringify(); if (elseBranch != nullptr) result += L"else " + elseBranch->Stringify(); return result; } AstType IfStmt::Type() { return AST_IF; } ScopeStmt::ScopeStmt() { } ScopeStmt::ScopeStmt(std::vector<Stmt *> stmts) : stmts(stmts) {} ScopeStmt::~ScopeStmt() { std::vector<Stmt *>().swap(stmts); } std::wstring ScopeStmt::Stringify() { std::wstring result = L"{"; for (const auto &stmt : stmts) result += stmt->Stringify(); result += L"}"; return result; } AstType ScopeStmt::Type() { return AST_SCOPE; } WhileStmt::WhileStmt() : condition(nullptr), body(nullptr), increment(nullptr) { } WhileStmt::WhileStmt(Expr *condition, ScopeStmt *body, ScopeStmt *increment) : condition(condition), body(body), increment(increment) { } WhileStmt::~WhileStmt() { delete condition; condition = nullptr; delete body; body = nullptr; delete increment; increment = nullptr; } std::wstring WhileStmt::Stringify() { std::wstring result = L"while(" + condition->Stringify() + L"){" + body->Stringify(); if (increment) result += increment->Stringify(); return result += L"}"; } AstType WhileStmt::Type() { return AST_WHILE; } BreakStmt::BreakStmt() { } BreakStmt::~BreakStmt() { } std::wstring BreakStmt::Stringify() { return L"break;"; } AstType BreakStmt::Type() { return AST_BREAK; } ContinueStmt::ContinueStmt() { } ContinueStmt::~ContinueStmt() { } std::wstring ContinueStmt::Stringify() { return L"continue;"; } AstType ContinueStmt::Type() { return AST_CONTINUE; } EnumStmt::EnumStmt() { } EnumStmt::EnumStmt(IdentifierExpr *enumName, const std::unordered_map<IdentifierExpr *, Expr *> &enumItems) : enumName(enumName), enumItems(enumItems) { } EnumStmt::~EnumStmt() { } std::wstring EnumStmt::Stringify() { std::wstring result = L"enum " + enumName->Stringify() + L"{"; if (!enumItems.empty()) { for (auto [key, value] : enumItems) result += key->Stringify() + L"=" + value->Stringify() + L","; result = result.substr(0, result.size() - 1); } return result + L"}"; } AstType EnumStmt::Type() { return AST_ENUM; } FunctionStmt::FunctionStmt() : name(nullptr), body(nullptr) { } FunctionStmt::FunctionStmt(IdentifierExpr *name, std::vector<IdentifierExpr *> parameters, ScopeStmt *body) : name(name), parameters(parameters), body(body) { } FunctionStmt::~FunctionStmt() { std::vector<IdentifierExpr *>().swap(parameters); delete body; body = nullptr; } std::wstring FunctionStmt::Stringify() { std::wstring result = L"fn " + name->Stringify() + L"("; if (!parameters.empty()) { for (auto param : parameters) result += param->Stringify() + L","; result = result.substr(0, result.size() - 1); } result += L")"; result += body->Stringify(); return result; } AstType FunctionStmt::Type() { return AST_FUNCTION; } ClassStmt::ClassStmt() { } ClassStmt::ClassStmt(std::wstring name, std::vector<LetStmt *> letStmts, std::vector<ConstStmt *> constStmts, std::vector<FunctionStmt *> fnStmts, std::vector<IdentifierExpr *> parentClasses) : name(name), letStmts(letStmts), constStmts(constStmts), fnStmts(fnStmts), parentClasses(parentClasses) { } ClassStmt::~ClassStmt() { std::vector<IdentifierExpr *>().swap(parentClasses); std::vector<LetStmt *>().swap(letStmts); std::vector<ConstStmt *>().swap(constStmts); std::vector<FunctionStmt *>().swap(fnStmts); } std::wstring ClassStmt::Stringify() { std::wstring result = L"class " + name; if (!parentClasses.empty()) { result += L":"; for (const auto &parentClass : parentClasses) result += parentClass->Stringify() + L","; result = result.substr(0, result.size() - 1); } result += L"{"; for (auto constStmt : constStmts) result += constStmt->Stringify(); for (auto letStmt : letStmts) result += letStmt->Stringify(); for (auto fnStmt : fnStmts) result += fnStmt->Stringify(); return result + L"}"; } AstType ClassStmt::Type() { return AST_CLASS; } AstStmts::AstStmts() { } AstStmts::AstStmts(std::vector<Stmt *> stmts) : stmts(stmts) {} AstStmts::~AstStmts() { std::vector<Stmt *>().swap(stmts); } std::wstring AstStmts::Stringify() { std::wstring result; for (const auto &stmt : stmts) result += stmt->Stringify(); return result; } AstType AstStmts::Type() { return AST_ASTSTMTS; } }
13,923
6,019
#include <cstdio> #include <iostream> #include <algorithm> const int Max=105; int col[3*Max], zws, n, ans; struct Node { int x, y; } p[Max]; bool cmp0(Node x, Node y) { return x.y < y.y; } bool cmp1(Node x, Node y) { return x.x < y.x; } inline int abs(int x) { return x>0?x:-x; } int main(){ freopen("data.in", "r", stdin); scanf("%d", &n); for(int i=0; i<n; i++){ scanf("%d %d", &p[i].x, &p[i].y); col[p[i].x+Max]++; // xmax = p[i].x>xmax?p[i].x:xmax; // xmin = p[i].x<xmin?p[i].x:xmin; } std::sort(p, p+n, cmp0); zws=p[n>>1].y; for(int i=0; i<n; i++){ ans+=abs(p[i].y-zws); } std::sort(p, p+n, cmp1); zws=p[n>>1].x+Max; for(int i=0; i<n/2; i++){ if(col[zws+i]>1){ for(int j=zws+i+1; j<=zws+i+1+n; j++){ if(col[j]==0){ col[j]++; col[zws+i]--; ans+=j-(zws+i); } if(col[zws+i]==1) break; } } if(col[zws-i]>1){ for(int j=zws-i-1; j>=zws-i-1-n; j--){ if(col[j]==0){ col[j]++; col[zws-i]--; ans+=zws-i-j; } if(col[zws+i]==1) break; } } } printf("%d", ans); return 0; }
1,068
662
// 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 "components/sync_driver/generic_change_processor_factory.h" #include "base/memory/ptr_util.h" #include "components/sync_driver/generic_change_processor.h" #include "sync/api/syncable_service.h" namespace sync_driver { GenericChangeProcessorFactory::GenericChangeProcessorFactory() {} GenericChangeProcessorFactory::~GenericChangeProcessorFactory() {} std::unique_ptr<GenericChangeProcessor> GenericChangeProcessorFactory::CreateGenericChangeProcessor( syncer::ModelType type, syncer::UserShare* user_share, syncer::DataTypeErrorHandler* error_handler, const base::WeakPtr<syncer::SyncableService>& local_service, const base::WeakPtr<syncer::SyncMergeResult>& merge_result, SyncClient* sync_client) { DCHECK(user_share); return base::WrapUnique(new GenericChangeProcessor( type, error_handler, local_service, merge_result, user_share, sync_client, local_service->GetAttachmentStoreForSync())); } } // namespace sync_driver
1,145
341
#include <ctype.h> #include <stdlib.h> #include <stdio.h> #include <string.h> #include "graph.h" #include "MFRUtils.h" #include "jsontokenizer.h" #include <set> #include <map> #include <string> /************************************************ Started 2016 Ayal Pinkus Read in json arrays and dump as binary files for faster processing later on. ************************************************/ struct EdgeIds { EdgeIds(long long nodeIdA, long long nodeIdB) { if (nodeIdA < nodeIdB) { low = nodeIdA; high = nodeIdB; } else { low = nodeIdB; high = nodeIdA; } }; EdgeIds(const EdgeIds& other) { low=other.low; high=other.high; }; long long low; long long high; }; bool operator< (const EdgeIds& lhs, const EdgeIds& rhs) { if (lhs.high < rhs.high) { return true; } else if (lhs.high > rhs.high) { return false; } else { if (lhs.low < rhs.low) { return true; } else { return false; } } } std::set<EdgeIds> edgeids; static FILE* json_in_file = NULL; static FILE* node_out_file = NULL; static FILE* edge_out_file = NULL; static void processFile(const char* fname) { JSONTokenizer tokenizer(fname); // // Read nodes // tokenizer.Match("{"); tokenizer.Match("nodes"); tokenizer.Match(":"); tokenizer.Match("["); while (!strcmp(tokenizer.nextToken, "{")) { MFRNode node; tokenizer.Match("{"); while (strcmp(tokenizer.nextToken, "}")) { if (!strcasecmp(tokenizer.nextToken, "eid")) { tokenizer.LookAhead(); tokenizer.Match(":"); node.SetNodeId(tokenizer.nextToken); } else if (!strcasecmp(tokenizer.nextToken, "name")) { tokenizer.LookAhead(); tokenizer.Match(":"); node.SetName(tokenizer.nextToken); } else if (!strcasecmp(tokenizer.nextToken, "author_name")) { tokenizer.LookAhead(); tokenizer.Match(":"); node.SetName(tokenizer.nextToken); } else if (!strcasecmp(tokenizer.nextToken, "x")) { tokenizer.LookAhead(); tokenizer.Match(":"); node.x = atof(tokenizer.nextToken); } else if (!strcasecmp(tokenizer.nextToken, "y")) { tokenizer.LookAhead(); tokenizer.Match(":"); node.y = atof(tokenizer.nextToken); } else if (!strcasecmp(tokenizer.nextToken, "community")) { tokenizer.LookAhead(); tokenizer.Match(":"); node.community = atol(tokenizer.nextToken); } else { tokenizer.LookAhead(); tokenizer.Match(":"); } tokenizer.LookAhead(); if (!strcmp(tokenizer.nextToken, ",")) { tokenizer.Match(","); } } tokenizer.Match("}"); fwrite(&node,sizeof(MFRNode),1,node_out_file); { static int nodecount=0; if ((nodecount & 1023) == 0) { fprintf(stderr,"\rNode %d",nodecount); } nodecount++; } if (!strcmp(tokenizer.nextToken, ",")) { tokenizer.Match(","); } } tokenizer.Match("]"); tokenizer.Match(","); tokenizer.Match("edges"); tokenizer.Match(":"); tokenizer.Match("["); while (!strcmp(tokenizer.nextToken, "[")) { MFREdgeExt edge; tokenizer.Match("["); edge.SetNodeIdA(tokenizer.nextToken); tokenizer.LookAhead(); tokenizer.Match(","); edge.SetNodeIdB(tokenizer.nextToken); tokenizer.LookAhead(); // Read edge strength here. tokenizer.Match(","); // Bug in data: some fields were left empty, so assuming edge strength 1 here. if (!strcmp(tokenizer.nextToken, ",")) { edge.strength = 1; } else { edge.strength = atoi(tokenizer.nextToken); tokenizer.LookAhead(); } /* Skip any additional fields */ while (!strcmp(tokenizer.nextToken, ",")) { tokenizer.Match(","); tokenizer.LookAhead(); } tokenizer.Match("]"); if (!strcmp(tokenizer.nextToken, ",")) { tokenizer.Match(","); } EdgeIds thisedge(atoll(edge.nodeidA), atoll(edge.nodeidB)); std::set<EdgeIds>::iterator eentry = edgeids.find(thisedge); if (eentry == edgeids.end()) { edgeids.insert(thisedge); fwrite(&edge,sizeof(MFREdgeExt),1,edge_out_file); { static int edgecount=0; if ((edgecount & 1023) == 0) { fprintf(stderr, "\rEdge %d",edgecount); } edgecount++; } } } tokenizer.Match("]"); tokenizer.Match("}"); } static void processMetaNodeFile(MFRNodeArray& nodes, const char* fname) { JSONTokenizer tokenizer(fname); tokenizer.Match("{"); tokenizer.Match("nodes"); tokenizer.Match(":"); tokenizer.Match("["); while (!strcmp(tokenizer.nextToken, "{")) { char nodeid[256]; int hindex=0; double pagerank; int pagerank_set = 0; int asjc=0; tokenizer.Match("{"); while (strcmp(tokenizer.nextToken, "}")) { if (!strcasecmp(tokenizer.nextToken, "eid")) { pagerank_set = 0; pagerank=0; hindex=0; asjc=10; tokenizer.LookAhead(); tokenizer.Match(":"); strcpy(nodeid,tokenizer.nextToken); } else if (!strcasecmp(tokenizer.nextToken, "hindex")) { tokenizer.LookAhead(); tokenizer.Match(":"); hindex = atoi(tokenizer.nextToken); } else if (!strcasecmp(tokenizer.nextToken, "pagerank")) { tokenizer.LookAhead(); tokenizer.Match(":"); pagerank = atof(tokenizer.nextToken); pagerank_set = 1; } else if (!strcasecmp(tokenizer.nextToken, "asjc")) { tokenizer.LookAhead(); tokenizer.Match(":"); char* ptr = tokenizer.nextToken; int len = strlen(ptr); if (len>2 && *ptr == '\"') { ptr[len-1] = 0; ptr = ptr + 1; } asjc = atoi(ptr); } else { tokenizer.LookAhead(); tokenizer.Match(":"); } tokenizer.LookAhead(); if (!strcmp(tokenizer.nextToken, ",")) { tokenizer.Match(","); } } tokenizer.Match("}"); MFRNode* node = nodes.LookUp(nodeid); if (node == NULL) { fprintf(stderr,"WARNING: meta data for non-existing node with id %s.\n", nodeid); } else { // I don't want to have to handle -1 in shingle.js. asjc 1000 is "general" if (asjc<0) { asjc = 10; } node->size = hindex; node->level = hindex; if (pagerank_set) { node->level = pagerank; } node->community = asjc; } if (!strcmp(tokenizer.nextToken, ",")) { tokenizer.Match(","); } } tokenizer.Match("]"); tokenizer.Match("}"); } int main(int argc, char** argv) { printf("sizeof(long long)=%lud\n",sizeof(long long)); if (argc<4) { fprintf(stderr,"%s data_path node_out_file edge_out_file",argv[0]); exit(-1); } const char* data_path = argv[1]; const char* node_out_fname = argv[2]; const char* edge_out_fname = argv[3]; node_out_file = MFRUtils::OpenFile(node_out_fname,"w"); edge_out_file = MFRUtils::OpenFile(edge_out_fname,"w"); char json_in_fname[1024]; sprintf(json_in_fname,"%snode.json",data_path); processFile(json_in_fname); fclose(node_out_file); fclose(edge_out_file); MFRNodeArray nodes(node_out_fname); nodes.Sort(); char json_meta_in_fname[1024]; sprintf(json_meta_in_fname,"%smeta.json",data_path); processMetaNodeFile(nodes, json_meta_in_fname); node_out_file = MFRUtils::OpenFile(node_out_fname,"w"); fwrite(nodes.nodes,nodes.nrnodes*sizeof(MFRNode),1,node_out_file); fclose(node_out_file); return 0; }
7,718
2,859
#include <bits/stdc++.h> using namespace std; const int N = 2e5 + 10, mod = 998244353; int n; char s[N]; int cnt[26], num, l, r; int main() { scanf("%d%s", &n, s); for(int i = 0; i < n; ++i) { cnt[s[i] - 'a']++; } for(int i = 0; i < 26; ++i) num += (cnt[i] != 0); if(num == 1) { printf("%lld\n", (1LL * n * (n + 1)) % mod); return 0; } l = 0, r = n - 1; for(; l < n; ++l) if(s[0] != s[l]) break; l--; for(; r >= 0; --r) if(s[n - 1] != s[r]) break; r++; if(s[0] == s[n - 1]) { printf("%lld\n", (1LL * (l + 2) * (1 + n - r)) % mod); return 0; } else { printf("%lld\n", (2LL + l + n - r) % mod); return 0; } return 0; }
659
395
//============================================================================= // Copyright (C) 2011-2018 The pmp-library developers // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met: // // * Redistributions of source code must retain the above copyright notice, this // list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // * Neither the name of the copyright holder nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. // ============================================================================= #include "SurfaceMeshTest.h" #include <pmp/io/SurfaceMeshIO.h> #include <pmp/algorithms/SurfaceNormals.h> #include <vector> using namespace pmp; class SurfaceMeshIOTest : public SurfaceMeshTest { }; TEST_F(SurfaceMeshIOTest, polyIO) { addTriangle(); mesh.write("test.pmp"); mesh.clear(); EXPECT_TRUE(mesh.isEmpty()); mesh.read("test.pmp"); EXPECT_EQ(mesh.nVertices(), size_t(3)); EXPECT_EQ(mesh.nFaces(), size_t(1)); // check malformed file names EXPECT_FALSE(mesh.write("testpolyly")); } TEST_F(SurfaceMeshIOTest, objIO) { addTriangle(); SurfaceNormals::computeVertexNormals(mesh); mesh.addHalfedgeProperty<TextureCoordinate>("h:texcoord",TextureCoordinate(0,0)); mesh.write("test.obj"); mesh.clear(); EXPECT_TRUE(mesh.isEmpty()); mesh.read("test.obj"); EXPECT_EQ(mesh.nVertices(), size_t(3)); EXPECT_EQ(mesh.nFaces(), size_t(1)); } TEST_F(SurfaceMeshIOTest, offIO) { addTriangle(); SurfaceNormals::computeVertexNormals(mesh); mesh.addVertexProperty<TextureCoordinate>("v:texcoord",TextureCoordinate(0,0)); mesh.addVertexProperty<Color>("v:color",Color(0,0,0)); IOOptions options(false, // binary true, // normals true, // colors true); // texcoords mesh.write("test.off",options); mesh.clear(); EXPECT_TRUE(mesh.isEmpty()); mesh.read("test.off"); EXPECT_EQ(mesh.nVertices(), size_t(3)); EXPECT_EQ(mesh.nFaces(), size_t(1)); } TEST_F(SurfaceMeshIOTest, offIOBinary) { addTriangle(); IOOptions options(true); mesh.write("binary.off", options); mesh.clear(); EXPECT_TRUE(mesh.isEmpty()); mesh.read("binary.off"); EXPECT_EQ(mesh.nVertices(), size_t(3)); EXPECT_EQ(mesh.nFaces(), size_t(1)); } TEST_F(SurfaceMeshIOTest, stlIO) { mesh.read("pmp-data/stl/icosahedron_ascii.stl"); EXPECT_EQ(mesh.nVertices(), size_t(12)); EXPECT_EQ(mesh.nFaces(), size_t(20)); EXPECT_EQ(mesh.nEdges(), size_t(30)); mesh.clear(); mesh.read("pmp-data/stl/icosahedron_binary.stl"); EXPECT_EQ(mesh.nVertices(), size_t(12)); EXPECT_EQ(mesh.nFaces(), size_t(20)); EXPECT_EQ(mesh.nEdges(), size_t(30)); // try to write without normals being present EXPECT_FALSE(mesh.write("test.stl")); // the same with normals computed SurfaceNormals::computeFaceNormals(mesh); EXPECT_TRUE(mesh.write("test.stl")); // try to write non-triangle mesh mesh.clear(); addQuad(); EXPECT_FALSE(mesh.write("test.stl")); } TEST_F(SurfaceMeshIOTest, plyIO) { addTriangle(); mesh.write("test.ply"); mesh.clear(); EXPECT_TRUE(mesh.isEmpty()); mesh.read("test.ply"); EXPECT_EQ(mesh.nVertices(), size_t(3)); EXPECT_EQ(mesh.nFaces(), size_t(1)); } TEST_F(SurfaceMeshIOTest, plyBinaryIO) { addTriangle(); IOOptions options(true); mesh.write("binary.ply",options); mesh.clear(); EXPECT_TRUE(mesh.isEmpty()); mesh.read("binary.ply"); EXPECT_EQ(mesh.nVertices(), size_t(3)); EXPECT_EQ(mesh.nFaces(), size_t(1)); }
4,853
1,809
// Copyright 2017 Google Inc. // // 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 "xrtl/ui/control.h" namespace xrtl { namespace ui { void Control::set_listener(ListenerPtr listener) { std::lock_guard<std::mutex> lock(listener_mutex_); listener_ = std::move(listener); } void Control::set_input_listener(InputListenerPtr input_listener) { std::lock_guard<std::mutex> lock(input_listener_mutex_); input_listener_ = std::move(input_listener); } void Control::PostError() { PostEvent([](Listener* listener, ref_ptr<Control> control) { listener->OnError(control); }); } void Control::PostCreating() { PostEvent([](Listener* listener, ref_ptr<Control> control) { listener->OnCreating(control); }); } void Control::PostCreated() { PostEvent([](Listener* listener, ref_ptr<Control> control) { listener->OnCreated(control); }); } void Control::PostDestroying() { PostEvent([](Listener* listener, ref_ptr<Control> control) { listener->OnDestroying(control); }); } void Control::PostDestroyed() { PostEvent([](Listener* listener, ref_ptr<Control> control) { listener->OnDestroyed(control); }); } void Control::PostSystemThemeChanged() { PostEvent([](Listener* listener, ref_ptr<Control> control) { listener->OnSystemThemeChanged(control); }); } void Control::PostSuspendChanged(bool is_suspended) { PostEvent([this, is_suspended](Listener* listener, ref_ptr<Control> control) { { std::lock_guard<std::recursive_mutex> lock(mutex_); if (has_posted_suspended_ && is_suspended == is_suspended_shadow_) { return; // Debounce. } has_posted_suspended_ = true; is_suspended_shadow_ = is_suspended; } listener->OnSuspendChanged(control, is_suspended); }); } void Control::PostFocusChanged(bool is_focused) { PostEvent([this, is_focused](Listener* listener, ref_ptr<Control> control) { { std::lock_guard<std::recursive_mutex> lock(mutex_); if (has_posted_focused_ && is_focused == is_focused_shadow_) { return; // Debounce. } has_posted_focused_ = true; is_focused_shadow_ = is_focused; } listener->OnFocusChanged(control, is_focused); }); } void Control::PostResized(Rect2D bounds) { PostEvent([this, bounds](Listener* listener, ref_ptr<Control> control) { { std::lock_guard<std::recursive_mutex> lock(mutex_); if (has_posted_bounds_ && bounds == bounds_shadow_) { return; // Debounce. } has_posted_bounds_ = true; bounds_shadow_ = bounds; } listener->OnResized(control, bounds); }); } void Control::ResetEventShadows() { std::lock_guard<std::recursive_mutex> lock(mutex_); has_posted_suspended_ = false; has_posted_focused_ = false; has_posted_bounds_ = false; } void Control::PostEvent( std::function<void(Listener*, ref_ptr<Control>)> callback) { auto callback_baton = MoveToLambda(callback); message_loop_->MarshalSync([this, callback_baton]() { std::lock_guard<std::mutex> lock(listener_mutex_); if (listener_) { ref_ptr<Control> control{this}; callback_baton.value(listener_.get(), control); } }); } void Control::PostInputEvent( std::function<void(InputListener*, ref_ptr<Control>)> callback) { switch (state()) { case State::kCreating: case State::kDestroying: case State::kDestroyed: // Ignore input events when the control is not active. return; default: break; } auto callback_baton = MoveToLambda(callback); message_loop_->MarshalSync([this, callback_baton]() { std::lock_guard<std::mutex> lock(input_listener_mutex_); if (input_listener_) { ref_ptr<Control> control{this}; callback_baton.value(input_listener_.get(), control); } }); } } // namespace ui } // namespace xrtl
4,338
1,456
/* * Copyright 2009-2017 Alibaba Cloud All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <alibabacloud/elasticsearch/model/RecommendTemplatesResult.h> #include <json/json.h> using namespace AlibabaCloud::Elasticsearch; using namespace AlibabaCloud::Elasticsearch::Model; RecommendTemplatesResult::RecommendTemplatesResult() : ServiceResult() {} RecommendTemplatesResult::RecommendTemplatesResult(const std::string &payload) : ServiceResult() { parse(payload); } RecommendTemplatesResult::~RecommendTemplatesResult() {} void RecommendTemplatesResult::parse(const std::string &payload) { Json::Reader reader; Json::Value value; reader.parse(payload, value); setRequestId(value["RequestId"].asString()); auto allResultNode = value["Result"]["TemplateConfig"]; for (auto valueResultTemplateConfig : allResultNode) { TemplateConfig resultObject; if(!valueResultTemplateConfig["templateName"].isNull()) resultObject.templateName = valueResultTemplateConfig["templateName"].asString(); if(!valueResultTemplateConfig["content"].isNull()) resultObject.content = valueResultTemplateConfig["content"].asString(); result_.push_back(resultObject); } } std::vector<RecommendTemplatesResult::TemplateConfig> RecommendTemplatesResult::getResult()const { return result_; }
1,838
557
#include "acmacs-base/log.hh" #include "acmacs-py/py.hh" // ====================================================================== PYBIND11_MODULE(acmacs, mdl) { using namespace pybind11::literals; mdl.doc() = "Acmacs backend"; acmacs_py::chart(mdl); acmacs_py::chart_util(mdl); acmacs_py::avidity(mdl); acmacs_py::antigen(mdl); acmacs_py::titers(mdl); acmacs_py::DEPRECATED::antigen_indexes(mdl); acmacs_py::common(mdl); acmacs_py::merge(mdl); acmacs_py::mapi(mdl); acmacs_py::draw(mdl); acmacs_py::seqdb(mdl); acmacs_py::tal(mdl); // ---------------------------------------------------------------------- mdl.def( "enable_logging", // [](const std::string& keys) { acmacs::log::enable(std::string_view{keys}); }, // "keys"_a); mdl.def("logging_enabled", &acmacs::log::report_enabled); } // ---------------------------------------------------------------------- /// Local Variables: /// eval: (if (fboundp 'eu-rename-buffer) (eu-rename-buffer)) /// End:
1,113
396