blob_id
stringlengths
40
40
directory_id
stringlengths
40
40
path
stringlengths
3
264
content_id
stringlengths
40
40
detected_licenses
listlengths
0
85
license_type
stringclasses
2 values
repo_name
stringlengths
5
140
snapshot_id
stringlengths
40
40
revision_id
stringlengths
40
40
branch_name
stringclasses
905 values
visit_date
timestamp[us]date
2015-08-09 11:21:18
2023-09-06 10:45:07
revision_date
timestamp[us]date
1997-09-14 05:04:47
2023-09-17 19:19:19
committer_date
timestamp[us]date
1997-09-14 05:04:47
2023-09-06 06:22:19
github_id
int64
3.89k
681M
star_events_count
int64
0
209k
fork_events_count
int64
0
110k
gha_license_id
stringclasses
22 values
gha_event_created_at
timestamp[us]date
2012-06-07 00:51:45
2023-09-14 21:58:39
gha_created_at
timestamp[us]date
2008-03-27 23:40:48
2023-08-21 23:17:38
gha_language
stringclasses
141 values
src_encoding
stringclasses
34 values
language
stringclasses
1 value
is_vendor
bool
1 class
is_generated
bool
2 classes
length_bytes
int64
3
10.4M
extension
stringclasses
115 values
content
stringlengths
3
10.4M
authors
listlengths
1
1
author_id
stringlengths
0
158
e1aab18ff48a5c32bb31d3eea59efc31c516f5ad
f12e3f64c7caa0fe330b6171058a3f712e48d139
/FIT2049 - Week 4/Texture.cpp
6b74fd2f379c532d3ad5b22d4787557d4a2ff202
[]
no_license
pirow99/Ass2b
3bbc0e7c355df6eb0d512b57f7eebc4c14ba5830
e0b9ac72b0380d3780f01a85164f3963eb7a0c72
refs/heads/master
2020-03-19T02:58:43.928212
2018-06-03T05:36:02
2018-06-03T05:36:02
135,681,942
0
0
null
null
null
null
UTF-8
C++
false
false
1,346
cpp
/* FIT2049 - Example Code * Texture.cpp * Created by Elliott Wilson & Mike Yeates - 2016 - Monash University * Implementation of Texture.h */ #include "Texture.h" #include "DirectXTK/WICTextureLoader.h" #include <sstream> using namespace DirectX; Texture::Texture() { m_referenceCount = 0; m_filename = ""; m_texture = NULL; m_textureView = NULL; } Texture::~Texture() { if (m_texture) { m_texture->Release(); m_texture = NULL; } if (m_textureView) { m_textureView->Release(); m_textureView = NULL; } } bool Texture::Load(Direct3D* direct3D, const char* filename) { //This method uses the CreateWICTextureFromFile function. This function comes from the DirectXToolKit library wchar_t* wideFilename = ConvertString(filename); HRESULT result = CreateWICTextureFromFile(direct3D->GetDevice(), wideFilename, &m_texture, &m_textureView); if (FAILED(result)) { return false; } m_filename = filename; return true; } wchar_t* Texture::ConvertString(const char * str) { // Convert C string (which we like using) into a wchar_t* (which the texture loader likes) // https://msdn.microsoft.com/en-us/library/ms235631.aspx size_t newsize = strlen(str) + 1; wchar_t* wcstring = new wchar_t[newsize]; size_t convertedChars = 0; mbstowcs_s(&convertedChars, wcstring, newsize, str, _TRUNCATE); return wcstring; }
[ "39756333+pirow99@users.noreply.github.com" ]
39756333+pirow99@users.noreply.github.com
e927e628225cac889fd711d5b2242db4fd3131c6
0c4a749e5636df8a1bdde384a0df63b47b7f4f07
/Class 3/project7.cpp
3704aad9902b908af6c6ecd223969df5e4213462
[ "MIT" ]
permissive
Sadik326-ctrl/computer_programming
28dad2d26c8758b2dddd3198f2a35e115d37ca29
cbae264ffa04fc487008fa6a0a32e0a1a316e01e
refs/heads/master
2023-06-27T21:54:33.532239
2021-07-25T16:47:48
2021-07-25T16:47:48
364,974,600
0
0
null
null
null
null
UTF-8
C++
false
false
333
cpp
#include <iostream> using namespace std; int main(){ char Letter1,Letter2,Letter3,Letter4,Letter5; Letter1='S'; Letter2='A'; Letter3='D'; Letter4='I'; Letter5='K'; cout<<Letter1<<Letter2<<Letter3<<Letter4<<Letter5<<endl; string name; name="Ahmed Sadik Khan"; cout<<name<<endl; return 0; }
[ "ahmedsadikkhan@gmail.com" ]
ahmedsadikkhan@gmail.com
9bfb1bfb392276096beccc7e73cbfb93320dc0b1
88a759d540bbd1c59a4d6558b357c78dfd875d88
/acceleratedcpp/chapt6/analysis.cc
6638e449c32943a82d121249a847c930480a3546
[]
no_license
ivantan/cppdevelopment
20d7df1de7145378af9919989f1a1455cd64884b
aa7ac87c98afbda167ea55dfef1687d6a4455bcd
refs/heads/master
2016-08-03T05:42:06.446905
2015-08-24T13:41:17
2015-08-24T13:41:17
28,193,100
0
0
null
null
null
null
UTF-8
C++
false
false
2,170
cc
#include <algorithm> #include <iostream> #include <iterator> #include <numeric> #include <stdexcept> #include <vector> #include "Student_info.h" #include "grade.h" #include "median.h" using std::accumulate; using std::back_inserter; using std::domain_error; using std::endl; using std::ostream; using std::remove_copy; using std::string; using std::transform; using std::vector; double grade_aux(const Student_info& s) { try { return grade(s); } catch (domain_error) { return grade(s.midterm, s.final, 0); } } double median_analysis(const vector<Student_info>& students) { vector<double> grades; transform(students.begin(), students.end(), back_inserter(grades), grade_aux); return median(grades); } void write_analysis(ostream& out, const string& name, double analysis(const vector<Student_info>&), const vector<Student_info>& did, const vector<Student_info>& didnt) { out << name << ": median(did) = " << analysis(did) << ", median(didnt) = " << analysis(didnt) << endl; } double average(const vector<double>& v) { return accumulate(v.begin(), v.end(), 0.0) / v.size(); } double average_grade(const Student_info& s) { return grade(s.midterm, s.final, average(s.homework)); } double average_analysis(const vector<Student_info>& students) { vector<double> grades; transform(students.begin(), students.end(), back_inserter(grades), average_grade); return median(grades); } // median of the nonzero elements of `s.homework', or `0' if no such elements exist double optimistic_median(const Student_info& s) { vector<double> nonzero; remove_copy(s.homework.begin(), s.homework.end(), back_inserter(nonzero), 0); if (nonzero.empty()) return grade(s.midterm, s.final, 0); else return grade(s.midterm, s.final, median(nonzero)); } double optimistic_median_analysis(const vector<Student_info>& students) { vector<double> grades; transform(students.begin(), students.end(), back_inserter(grades), optimistic_median); return median(grades); }
[ "ivan.wjt@gmail.com" ]
ivan.wjt@gmail.com
b0ab0d7410f0146d68bb1fc65ade60e5e90e462b
390f4d0ddc43fd53ef924469345c7445c7af2a33
/src/Net.h
efa761ed5855e4244b01cffc2eb5600189ee0a18
[]
no_license
larrythecow/sdl-net
8255e2d5bbffd302412131a107bc2f0960bb3b8d
5fa8839f889c9ec782ee6cb811545992f3e79880
refs/heads/master
2020-12-24T13:35:34.576444
2012-09-09T01:24:39
2012-09-09T01:24:39
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,190
h
#ifndef _NET_H_ #define _NET_H_ #include <iostream> #include <stdlib.h> #include <SDL/SDL.h> #include <SDL/SDL_net.h> #include "Ip.h" #define DIMBUFFER 1024 #define DIMCLIENT 16 #define TIMEOUT 1000; class Net { private: bool running; bool type; // 0=client; 1=server TCPsocket socket; TCPsocket socketPeer; SDLNet_SocketSet socketSetClient; Ip ipPeer; char buffer[DIMBUFFER]; int clientCount; public: Net(); ~Net(); bool init(); int clientExecute(); int serverExecute(); void cleanup(); void logic(); TCPsocket tcpOpen(); TCPsocket tcpOpen(IPaddress *); int tcpSend(); int tcpSend(TCPsocket socket, const void *); int tcpSend(TCPsocket socket, const void *, int len); IPaddress * tcpGetPeerAddress(); IPaddress * tcpGetPeerAddress(TCPsocket socket); TCPsocket tcpAccept(); TCPsocket tcpAccept(TCPsocket); SDLNet_SocketSet allocSocketSet(); SDLNet_SocketSet allocSocketSet(int maxSockets); int addSocket(); int addSocket(SDLNet_SocketSet, TCPsocket); int checkSockets(Uint32 timeout); int checkSockets(SDLNet_SocketSet set, Uint32 timeout); }; #endif
[ "sid@projekt-turm.de" ]
sid@projekt-turm.de
ddc95ecc12af37d94e5b55d6b5aceb94edb3ff00
30bdd8ab897e056f0fb2f9937dcf2f608c1fd06a
/CodesNew/234.cpp
da029a6b5e9e5558f3db5ace01865adfa3d6243d
[]
no_license
thegamer1907/Code_Analysis
0a2bb97a9fb5faf01d983c223d9715eb419b7519
48079e399321b585efc8a2c6a84c25e2e7a22a61
refs/heads/master
2020-05-27T01:20:55.921937
2019-11-20T11:15:11
2019-11-20T11:15:11
188,403,594
2
1
null
null
null
null
UTF-8
C++
false
false
1,328
cpp
#include <stdio.h> #include <iostream> #include <vector> using namespace std; int max(long long a, long long b) { if (a > b) return a; else return b; } int min(long long a,long long b) { if (a > b) return b; else return a; } void swap(int*pa, int*pb) { int t = *pa; *pa = *pb; *pb = t; } int get(int a) { if (a >= 'a'&&a <= 'f') return 10 + a - 'a'; else return a - '0'; } #define scanf_s scanf /*int main(void) { double a,b,c,d; scanf_s("%lf%lf%lf%lf",&a,&b,&c,&d); if (a < b) { double t = a; a = b; b = t; } if (c < d) { double t = c; c = d; d = t; } if (a*a + b*b < c*c + d*d) { printf("NO"); return 0; } if (a >= c&&b >= d) { printf("YES"); return 0; } if (a*a + b*b > (c + d)*(c + d)) { printf("YES"); return 0; } printf("NO"); return 0; }*/ int main() { int n; int t; cin >> n >> t; vector <int> a(n+1); a[0] = 0; for (int i = 1; i <= n; i++) cin>>a[i]; int d = 0; int j = 0; int max_ = 0; for (int i = 1;j<=n && i <= n; i++) { while (j<n && d + a[j+1] <= t) { d += a[j+1]; j++; } max_ = max(j - i + 1, max_); d -= a[i]; } cout << max_; return 0; }
[ "harshitagar1907@gmail.com" ]
harshitagar1907@gmail.com
b353c7d6e2946d954efe5888bb7090ddd4c2fd86
2124d0b0d00c3038924f5d2ad3fe14b35a1b8644
/source/GamosCore/GamosData/Data/include/GmDataFinalXS.hh
c3408c09c9a168bbc313c8c60740a6b6e7c46c31
[]
no_license
arceciemat/GAMOS
2f3059e8b0992e217aaf98b8591ef725ad654763
7db8bd6d1846733387b6cc946945f0821567662b
refs/heads/master
2023-07-08T13:31:01.021905
2023-06-26T10:57:43
2023-06-26T10:57:43
21,818,258
1
0
null
null
null
null
UTF-8
C++
false
false
358
hh
#ifndef GmDataFinalXS_hh #define GmDataFinalXS_hh #include "GamosCore/GamosData/Management/include/GmVDataString.hh" class GmDataFinalXS : public GmVDataString { public: GmDataFinalXS(); ~GmDataFinalXS(); virtual G4String GetStringValueFromStep( const G4Step* aStep ); virtual G4String GetStringValueFromTrack( const G4Track* aTrack ); }; #endif
[ "pedro.arce@ciemat.es" ]
pedro.arce@ciemat.es
eba998527783fda1377772a88287ddaefc69eed1
96ab4dd1b01a51164031c2cdf2dc9e7b773a4293
/csbot/engine.cpp
ec1648b528cb1fc6fb28c76b57b81a78267a7f0d
[]
no_license
N7P0L3ON/hlsdk10-bots
25e821d519f8229ac5ab6ab614df7698ce843f90
d12620edecb1d2012663f32957a01d2c7b16c52a
refs/heads/master
2023-05-02T05:57:31.064376
2018-08-25T10:01:57
2018-08-25T10:01:57
null
0
0
null
null
null
null
UTF-8
C++
false
false
32,159
cpp
/********************************** TheBot Eric Bieschke's CS Bot http://gamershomepage.com/thebot/ *********************************** Adapted from: HPB_bot botman's High Ping Bastard bot http://planethalflife.com/botman/ *********************************** $Source: /usr/local/cvsroot/csbot/src/dlls/engine.cpp,v $ $Revision: 1.5 $ $Date: 2001/04/30 08:06:11 $ $State: Exp $ *********************************** $Log: engine.cpp,v $ Revision 1.5 2001/04/30 08:06:11 eric willFire() deals with crouching versus standing Revision 1.4 2001/04/30 07:17:17 eric Movement priorities determined by bot index Revision 1.3 2001/04/29 01:45:36 eric Tweaked CVS info headers Revision 1.2 2001/04/29 01:36:00 eric Added Header and Log CVS options **********************************/ #include "extdll.h" #include "util.h" #include "bot.h" #include "bot_client.h" #include "engine.h" extern enginefuncs_t g_engfuncs; extern bot_t bots[MAX_BOTS]; int debug_engine = 0; void (*botMsgFunction)(void *, int) = NULL; void (*botMsgEndFunction)(void *, int) = NULL; int botMsgIndex; // messages created in RegUserMsg which will be "caught" int message_ShowMenu = 0; int message_WeaponList = 0; int message_CurWeapon = 0; int message_AmmoX = 0; int message_AmmoPickup = 0; int message_Damage = 0; int message_Money = 0; // for Counter-Strike int message_DeathMsg = 0; int message_TextMsg = 0; int message_ScreenFade = 0; static FILE *fp; int pfnPrecacheModel(char* s) { if (debug_engine) { fp=fopen("bot.txt","a"); fprintf(fp,"pfnPrecacheModel: %s\n",s); fclose(fp); } return (*g_engfuncs.pfnPrecacheModel)(s); } int pfnPrecacheSound(char* s) { if (debug_engine) { fp=fopen("bot.txt","a"); fprintf(fp,"pfnPrecacheSound: %s\n",s); fclose(fp); } return (*g_engfuncs.pfnPrecacheSound)(s); } void pfnSetModel(edict_t *e, const char *m) { if (debug_engine) { fp=fopen("bot.txt","a"); fprintf(fp,"pfnSetModel: edict=%x %s\n",e,m); fclose(fp); } (*g_engfuncs.pfnSetModel)(e, m); } int pfnModelIndex(const char *m) { // if (debug_engine) { fp=fopen("bot.txt","a"); fprintf(fp,"pfnModelIndex: %s\n",m); fclose(fp); } return (*g_engfuncs.pfnModelIndex)(m); } int pfnModelFrames(int modelIndex) { if (debug_engine) { fp=fopen("bot.txt","a"); fprintf(fp,"pfnModelFrames:\n"); fclose(fp); } return (*g_engfuncs.pfnModelFrames)(modelIndex); } void pfnSetSize(edict_t *e, const float *rgflMin, const float *rgflMax) { if (debug_engine) { fp=fopen("bot.txt","a"); fprintf(fp,"pfnSetSize: %x\n",e); fclose(fp); } (*g_engfuncs.pfnSetSize)(e, rgflMin, rgflMax); } void pfnChangeLevel(char* s1, char* s2) { if (debug_engine) { fp=fopen("bot.txt","a"); fprintf(fp,"pfnChangeLevel:\n"); fclose(fp); } // kick any bot off of the server after time/frag limit... for (int index = 0; index < MAX_BOTS; index++) { if (bots[index].is_used) // is this slot used? { char cmd[40]; sprintf(cmd, "kick \"%s\"\n", bots[index].name); bots[index].respawn_state = RESPAWN_NEED_TO_RESPAWN; SERVER_COMMAND(cmd); // kick the bot using (kick "name") } } (*g_engfuncs.pfnChangeLevel)(s1, s2); } void pfnGetSpawnParms(edict_t *ent) { if (debug_engine) { fp=fopen("bot.txt","a"); fprintf(fp,"pfnGetSpawnParms:\n"); fclose(fp); } (*g_engfuncs.pfnGetSpawnParms)(ent); } void pfnSaveSpawnParms(edict_t *ent) { if (debug_engine) { fp=fopen("bot.txt","a"); fprintf(fp,"pfnSaveSpawnParms:\n"); fclose(fp); } (*g_engfuncs.pfnSaveSpawnParms)(ent); } float pfnVecToYaw(const float *rgflVector) { // if (debug_engine) { fp=fopen("bot.txt","a"); fprintf(fp,"pfnVecToYaw:\n"); fclose(fp); } return (*g_engfuncs.pfnVecToYaw)(rgflVector); } void pfnVecToAngles(const float *rgflVectorIn, float *rgflVectorOut) { // if (debug_engine) { fp=fopen("bot.txt","a"); fprintf(fp,"pfnVecToAngles:\n"); fclose(fp); } (*g_engfuncs.pfnVecToAngles)(rgflVectorIn, rgflVectorOut); } void pfnMoveToOrigin(edict_t *ent, const float *pflGoal, float dist, int iMoveType) { if (debug_engine) { fp=fopen("bot.txt","a"); fprintf(fp,"pfnMoveToOrigin:\n"); fclose(fp); } (*g_engfuncs.pfnMoveToOrigin)(ent, pflGoal, dist, iMoveType); } void pfnChangeYaw(edict_t* ent) { // if (debug_engine) { fp=fopen("bot.txt","a"); fprintf(fp,"pfnChangeYaw:\n"); fclose(fp); } (*g_engfuncs.pfnChangeYaw)(ent); } void pfnChangePitch(edict_t* ent) { // if (debug_engine) { fp=fopen("bot.txt","a"); fprintf(fp,"pfnChangePitch:\n"); fclose(fp); } (*g_engfuncs.pfnChangePitch)(ent); } /* edict_t* pfnFindEntityByString(edict_t *pEdictStartSearchAfter, const char *pszField, const char *pszValue) { // if (debug_engine) { fp=fopen("bot.txt","a"); fprintf(fp,"pfnFindEntityByString: %s\n",pszValue); fclose(fp); } return (*g_engfuncs.pfnFindEntityByString)(pEdictStartSearchAfter, pszField, pszValue); }*/ edict_t* pfnFindEntityByString(edict_t *pEdictStartSearchAfter, const char *pszField, const char *pszValue) { if (strcmp (pszValue, "func_bomb_target") == 0) round_begin (); // if (debug_engine) { fp=fopen("bot.txt","a"); fprintf(fp,"pfnFindEntityByString: %s\n",pszValue); fclose(fp); } return (*g_engfuncs.pfnFindEntityByString)(pEdictStartSearchAfter, pszField, pszValue); } int pfnGetEntityIllum(edict_t* pEnt) { if (debug_engine) { fp=fopen("bot.txt","a"); fprintf(fp,"pfnGetEntityIllum:\n"); fclose(fp); } return (*g_engfuncs.pfnGetEntityIllum)(pEnt); } edict_t* pfnFindEntityInSphere(edict_t *pEdictStartSearchAfter, const float *org, float rad) { if (debug_engine) { fp=fopen("bot.txt","a"); fprintf(fp,"pfnFindEntityInSphere:\n"); fclose(fp); } return (*g_engfuncs.pfnFindEntityInSphere)(pEdictStartSearchAfter, org, rad); } edict_t* pfnFindClientInPVS(edict_t *pEdict) { if (debug_engine) { fp=fopen("bot.txt","a"); fprintf(fp,"pfnFindClientInPVS:\n"); fclose(fp); } return (*g_engfuncs.pfnFindClientInPVS)(pEdict); } edict_t* pfnEntitiesInPVS(edict_t *pplayer) { if (debug_engine) { fp=fopen("bot.txt","a"); fprintf(fp,"pfnEntitiesInPVS:\n"); fclose(fp); } return (*g_engfuncs.pfnEntitiesInPVS)(pplayer); } void pfnMakeVectors(const float *rgflVector) { // if (debug_engine) { fp=fopen("bot.txt","a"); fprintf(fp,"pfnMakeVectors:\n"); fclose(fp); } (*g_engfuncs.pfnMakeVectors)(rgflVector); } void pfnAngleVectors(const float *rgflVector, float *forward, float *right, float *up) { // if (debug_engine) { fp=fopen("bot.txt","a"); fprintf(fp,"pfnAngleVectors:\n"); fclose(fp); } (*g_engfuncs.pfnAngleVectors)(rgflVector, forward, right, up); } edict_t* pfnCreateEntity(void) { edict_t *pent = (*g_engfuncs.pfnCreateEntity)(); if (debug_engine) { fp=fopen("bot.txt","a"); fprintf(fp,"pfnCreateEntity: %x\n",pent); fclose(fp); } return pent; } void pfnRemoveEntity(edict_t* e) { // if (debug_engine) { fp=fopen("bot.txt","a"); fprintf(fp,"pfnRemoveEntity: %x\n",e); fclose(fp); } if (debug_engine) { fp=fopen("bot.txt","a"); fprintf(fp,"pfnRemoveEntity: %x\n",e); if (e->v.model != 0) fprintf(fp," model=%s\n", STRING(e->v.model)); fclose(fp); } (*g_engfuncs.pfnRemoveEntity)(e); } edict_t* pfnCreateNamedEntity(int className) { edict_t *pent = (*g_engfuncs.pfnCreateNamedEntity)(className); if (debug_engine) { fp=fopen("bot.txt","a"); fprintf(fp,"pfnCreateNamedEntity: edict=%x name=%s\n",pent,STRING(className)); fclose(fp); } return pent; } void pfnMakeStatic(edict_t *ent) { if (debug_engine) { fp=fopen("bot.txt","a"); fprintf(fp,"pfnMakeStatic:\n"); fclose(fp); } (*g_engfuncs.pfnMakeStatic)(ent); } int pfnEntIsOnFloor(edict_t *e) { if (debug_engine) { fp=fopen("bot.txt","a"); fprintf(fp,"pfnEntIsOnFloor:\n"); fclose(fp); } return (*g_engfuncs.pfnEntIsOnFloor)(e); } int pfnDropToFloor(edict_t* e) { if (debug_engine) { fp=fopen("bot.txt","a"); fprintf(fp,"pfnDropToFloor:\n"); fclose(fp); } return (*g_engfuncs.pfnDropToFloor)(e); } int pfnWalkMove(edict_t *ent, float yaw, float dist, int iMode) { if (debug_engine) { fp=fopen("bot.txt","a"); fprintf(fp,"pfnWalkMove:\n"); fclose(fp); } return (*g_engfuncs.pfnWalkMove)(ent, yaw, dist, iMode); } void pfnSetOrigin(edict_t *e, const float *rgflOrigin) { if (debug_engine) { fp=fopen("bot.txt","a"); fprintf(fp,"pfnSetOrigin:\n"); fclose(fp); } (*g_engfuncs.pfnSetOrigin)(e, rgflOrigin); } void pfnEmitSound(edict_t *entity, int channel, const char *sample, /*int*/float volume, float attenuation, int fFlags, int pitch) { if (debug_engine) { fp=fopen("bot.txt","a"); fprintf(fp,"pfnEmitSound:\n"); fclose(fp); } (*g_engfuncs.pfnEmitSound)(entity, channel, sample, volume, attenuation, fFlags, pitch); } void pfnEmitAmbientSound(edict_t *entity, float *pos, const char *samp, float vol, float attenuation, int fFlags, int pitch) { if (debug_engine) { fp=fopen("bot.txt","a"); fprintf(fp,"pfnEmitAmbientSound:\n"); fclose(fp); } (*g_engfuncs.pfnEmitAmbientSound)(entity, pos, samp, vol, attenuation, fFlags, pitch); } void pfnTraceLine(const float *v1, const float *v2, int fNoMonsters, edict_t *pentToSkip, TraceResult *ptr) { // if (debug_engine) { fp=fopen("bot.txt","a"); fprintf(fp,"pfnTraceLine:\n"); fclose(fp); } (*g_engfuncs.pfnTraceLine)(v1, v2, fNoMonsters, pentToSkip, ptr); } void pfnTraceToss(edict_t* pent, edict_t* pentToIgnore, TraceResult *ptr) { // if (debug_engine) { fp=fopen("bot.txt","a"); fprintf(fp,"pfnTraceToss:\n"); fclose(fp); } (*g_engfuncs.pfnTraceToss)(pent, pentToIgnore, ptr); } int pfnTraceMonsterHull(edict_t *pEdict, const float *v1, const float *v2, int fNoMonsters, edict_t *pentToSkip, TraceResult *ptr) { // if (debug_engine) { fp=fopen("bot.txt","a"); fprintf(fp,"pfnTraceMonsterHull:\n"); fclose(fp); } return (*g_engfuncs.pfnTraceMonsterHull)(pEdict, v1, v2, fNoMonsters, pentToSkip, ptr); } void pfnTraceHull(const float *v1, const float *v2, int fNoMonsters, int hullNumber, edict_t *pentToSkip, TraceResult *ptr) { // if (debug_engine) { fp=fopen("bot.txt","a"); fprintf(fp,"pfnTraceHull:\n"); fclose(fp); } (*g_engfuncs.pfnTraceHull)(v1, v2, fNoMonsters, hullNumber, pentToSkip, ptr); } void pfnTraceModel(const float *v1, const float *v2, int hullNumber, edict_t *pent, TraceResult *ptr) { // if (debug_engine) { fp=fopen("bot.txt","a"); fprintf(fp,"pfnTraceModel:\n"); fclose(fp); } (*g_engfuncs.pfnTraceModel)(v1, v2, hullNumber, pent, ptr); } const char *pfnTraceTexture(edict_t *pTextureEntity, const float *v1, const float *v2 ) { // if (debug_engine) { fp=fopen("bot.txt","a"); fprintf(fp,"pfnTraceTexture:\n"); fclose(fp); } return (*g_engfuncs.pfnTraceTexture)(pTextureEntity, v1, v2); } void pfnTraceSphere(const float *v1, const float *v2, int fNoMonsters, float radius, edict_t *pentToSkip, TraceResult *ptr) { // if (debug_engine) { fp=fopen("bot.txt","a"); fprintf(fp,"pfnTraceSphere:\n"); fclose(fp); } (*g_engfuncs.pfnTraceSphere)(v1, v2, fNoMonsters, radius, pentToSkip, ptr); } void pfnGetAimVector(edict_t* ent, float speed, float *rgflReturn) { // if (debug_engine) { fp=fopen("bot.txt","a"); fprintf(fp,"pfnGetAimVector:\n"); fclose(fp); } (*g_engfuncs.pfnGetAimVector)(ent, speed, rgflReturn); } void pfnServerCommand(char* str) { if (debug_engine) { fp=fopen("bot.txt","a"); fprintf(fp,"pfnServerCommand: %s\n",str); fclose(fp); } (*g_engfuncs.pfnServerCommand)(str); } void pfnServerExecute(void) { if (debug_engine) { fp=fopen("bot.txt","a"); fprintf(fp,"pfnServerExecute:\n"); fclose(fp); } (*g_engfuncs.pfnServerExecute)(); } void pfnClientCommand(edict_t* pEdict, char* szFmt, ...) { if (debug_engine) { fp=fopen("bot.txt","a"); fprintf(fp,"pfnClientCommand=%s\n",szFmt); fclose(fp); } return; } void pfnParticleEffect(const float *org, const float *dir, float color, float count) { // if (debug_engine) { fp=fopen("bot.txt","a"); fprintf(fp,"pfnParticleEffect:\n"); fclose(fp); } (*g_engfuncs.pfnParticleEffect)(org, dir, color, count); } void pfnLightStyle(int style, char* val) { // if (debug_engine) { fp=fopen("bot.txt","a"); fprintf(fp,"pfnLightStyle:\n"); fclose(fp); } (*g_engfuncs.pfnLightStyle)(style, val); } int pfnDecalIndex(const char *name) { // if (debug_engine) { fp=fopen("bot.txt","a"); fprintf(fp,"pfnDecalIndex:\n"); fclose(fp); } return (*g_engfuncs.pfnDecalIndex)(name); } int pfnPointContents(const float *rgflVector) { // if (debug_engine) { fp=fopen("bot.txt","a"); fprintf(fp,"pfnPointContents:\n"); fclose(fp); } return (*g_engfuncs.pfnPointContents)(rgflVector); } void pfnMessageBegin(int msg_dest, int msg_type, const float *pOrigin, edict_t *ed) { if (gpGlobals->deathmatch) { int index = -1; if (debug_engine) { fp=fopen("bot.txt","a"); fprintf(fp,"pfnMessageBegin: edict=%x dest=%d type=%d\n",ed,msg_dest,msg_type); fclose(fp); } if (ed) { index = UTIL_GetBotIndex(ed); // is this message for a bot? if (index != -1) { botMsgFunction = NULL; // no msg function until known otherwise botMsgEndFunction = NULL; // no msg end function until known otherwise botMsgIndex = index; // index of bot receiving message if (msg_type == message_ShowMenu) botMsgFunction = BotClient_CS_ShowMenu; else if (msg_type == message_WeaponList) botMsgFunction = BotClient_CS_WeaponList; else if (msg_type == message_CurWeapon) botMsgFunction = BotClient_CS_CurrentWeapon; else if (msg_type == message_AmmoX) botMsgFunction = BotClient_CS_AmmoX; else if (msg_type == message_AmmoPickup) botMsgFunction = BotClient_CS_AmmoPickup; else if (msg_type == message_Damage) botMsgFunction = BotClient_CS_Damage; else if (msg_type == message_Money) botMsgFunction = BotClient_CS_Money; else if (msg_type == message_ScreenFade) botMsgFunction = BotClient_CS_ScreenFade; else if (msg_type == message_TextMsg) botMsgFunction = BotClient_CS_TextMsg; } } else if (msg_dest == MSG_ALL) { botMsgFunction = NULL; // no msg function until known otherwise botMsgIndex = -1; // index of bot receiving message (none) if (msg_type == message_DeathMsg) botMsgFunction = BotClient_CS_DeathMsg; else if (msg_type == message_TextMsg) botMsgFunction = BotClient_CS_TextMsg; } } (*g_engfuncs.pfnMessageBegin)(msg_dest, msg_type, pOrigin, ed); } void pfnMessageEnd(void) { if (gpGlobals->deathmatch) { if (debug_engine) { fp=fopen("bot.txt","a"); fprintf(fp,"pfnMessageEnd:\n"); fclose(fp); } if (botMsgEndFunction) (*botMsgEndFunction)(NULL, botMsgIndex); // NULL indicated msg end // clear out the bot message function pointers... botMsgFunction = NULL; botMsgEndFunction = NULL; } (*g_engfuncs.pfnMessageEnd)(); } void pfnWriteByte(int iValue) { if (gpGlobals->deathmatch) { if (debug_engine) { fp=fopen("bot.txt","a"); fprintf(fp,"pfnWriteByte: %d\n",iValue); fclose(fp); } // if this message is for a bot, call the client message function... if (botMsgFunction) (*botMsgFunction)((void *)&iValue, botMsgIndex); } (*g_engfuncs.pfnWriteByte)(iValue); } void pfnWriteChar(int iValue) { if (gpGlobals->deathmatch) { if (debug_engine) { fp=fopen("bot.txt","a"); fprintf(fp,"pfnWriteChar: %d\n",iValue); fclose(fp); } // if this message is for a bot, call the client message function... if (botMsgFunction) (*botMsgFunction)((void *)&iValue, botMsgIndex); } (*g_engfuncs.pfnWriteChar)(iValue); } void pfnWriteShort(int iValue) { if (gpGlobals->deathmatch) { if (debug_engine) { fp=fopen("bot.txt","a"); fprintf(fp,"pfnWriteShort: %d\n",iValue); fclose(fp); } // if this message is for a bot, call the client message function... if (botMsgFunction) (*botMsgFunction)((void *)&iValue, botMsgIndex); } (*g_engfuncs.pfnWriteShort)(iValue); } void pfnWriteLong(int iValue) { if (gpGlobals->deathmatch) { if (debug_engine) { fp=fopen("bot.txt","a"); fprintf(fp,"pfnWriteLong: %d\n",iValue); fclose(fp); } // if this message is for a bot, call the client message function... if (botMsgFunction) (*botMsgFunction)((void *)&iValue, botMsgIndex); } (*g_engfuncs.pfnWriteLong)(iValue); } void pfnWriteAngle(float flValue) { if (gpGlobals->deathmatch) { if (debug_engine) { fp=fopen("bot.txt","a"); fprintf(fp,"pfnWriteAngle: %f\n",flValue); fclose(fp); } // if this message is for a bot, call the client message function... if (botMsgFunction) (*botMsgFunction)((void *)&flValue, botMsgIndex); } (*g_engfuncs.pfnWriteAngle)(flValue); } void pfnWriteCoord(float flValue) { if (gpGlobals->deathmatch) { if (debug_engine) { fp=fopen("bot.txt","a"); fprintf(fp,"pfnWriteCoord: %f\n",flValue); fclose(fp); } // if this message is for a bot, call the client message function... if (botMsgFunction) (*botMsgFunction)((void *)&flValue, botMsgIndex); } (*g_engfuncs.pfnWriteCoord)(flValue); } void pfnWriteString(const char *sz) { if (gpGlobals->deathmatch) { if (debug_engine) { fp=fopen("bot.txt","a"); fprintf(fp,"pfnWriteString: %s\n",sz); fclose(fp); } // if this message is for a bot, call the client message function... if (botMsgFunction) (*botMsgFunction)((void *)sz, botMsgIndex); } (*g_engfuncs.pfnWriteString)(sz); } void pfnWriteEntity(int iValue) { if (gpGlobals->deathmatch) { if (debug_engine) { fp=fopen("bot.txt","a"); fprintf(fp,"pfnWriteEntity: %d\n",iValue); fclose(fp); } // if this message is for a bot, call the client message function... if (botMsgFunction) (*botMsgFunction)((void *)&iValue, botMsgIndex); } (*g_engfuncs.pfnWriteEntity)(iValue); } void pfnCVarRegister(cvar_t *pCvar) { if (debug_engine) { fp=fopen("bot.txt","a"); fprintf(fp,"pfnCVarRegister:\n"); fclose(fp); } (*g_engfuncs.pfnCVarRegister)(pCvar); } float pfnCVarGetFloat(const char *szVarName) { // if (debug_engine) { fp=fopen("bot.txt","a"); fprintf(fp,"pfnCVarGetFloat: %s\n",szVarName); fclose(fp); } return (*g_engfuncs.pfnCVarGetFloat)(szVarName); } const char* pfnCVarGetString(const char *szVarName) { // if (debug_engine) { fp=fopen("bot.txt","a"); fprintf(fp,"pfnCVarGetString:\n"); fclose(fp); } return (*g_engfuncs.pfnCVarGetString)(szVarName); } void pfnCVarSetFloat(const char *szVarName, float flValue) { // if (debug_engine) { fp=fopen("bot.txt","a"); fprintf(fp,"pfnCVarSetFloat:\n"); fclose(fp); } (*g_engfuncs.pfnCVarSetFloat)(szVarName, flValue); } void pfnCVarSetString(const char *szVarName, const char *szValue) { // if (debug_engine) { fp=fopen("bot.txt","a"); fprintf(fp,"pfnCVarSetString:\n"); fclose(fp); } (*g_engfuncs.pfnCVarSetString)(szVarName, szValue); } void* pfnPvAllocEntPrivateData(edict_t *pEdict, long cb) { if (debug_engine) { fp=fopen("bot.txt","a"); fprintf(fp,"pfnPvAllocEntPrivateData:\n"); fclose(fp); } return (*g_engfuncs.pfnPvAllocEntPrivateData)(pEdict, cb); } void* pfnPvEntPrivateData(edict_t *pEdict) { if (debug_engine) { fp=fopen("bot.txt","a"); fprintf(fp,"pfnPvEntPrivateData:\n"); fclose(fp); } return (*g_engfuncs.pfnPvEntPrivateData)(pEdict); } void pfnFreeEntPrivateData(edict_t *pEdict) { if (debug_engine) { fp=fopen("bot.txt","a"); fprintf(fp,"pfnFreeEntPrivateData:\n"); fclose(fp); } (*g_engfuncs.pfnFreeEntPrivateData)(pEdict); } const char* pfnSzFromIndex(int iString) { if (debug_engine) { fp=fopen("bot.txt","a"); fprintf(fp,"pfnSzFromIndex:\n"); fclose(fp); } return (*g_engfuncs.pfnSzFromIndex)(iString); } int pfnAllocString(const char *szValue) { if (debug_engine) { fp=fopen("bot.txt","a"); fprintf(fp,"pfnAllocString:\n"); fclose(fp); } return (*g_engfuncs.pfnAllocString)(szValue); } edict_t* pfnPEntityOfEntOffset(int iEntOffset) { // if (debug_engine) { fp=fopen("bot.txt","a"); fprintf(fp,"pfnPEntityOfEntOffset:\n"); fclose(fp); } return (*g_engfuncs.pfnPEntityOfEntOffset)(iEntOffset); } int pfnEntOffsetOfPEntity(const edict_t *pEdict) { // if (debug_engine) { fp=fopen("bot.txt","a"); fprintf(fp,"pfnEntOffsetOfPEntity: %x\n",pEdict); fclose(fp); } return (*g_engfuncs.pfnEntOffsetOfPEntity)(pEdict); } int pfnIndexOfEdict(const edict_t *pEdict) { // if (debug_engine) { fp=fopen("bot.txt","a"); fprintf(fp,"pfnIndexOfEdict: %x\n",pEdict); fclose(fp); } return (*g_engfuncs.pfnIndexOfEdict)(pEdict); } edict_t* pfnPEntityOfEntIndex(int iEntIndex) { // if (debug_engine) { fp=fopen("bot.txt","a"); fprintf(fp,"pfnPEntityOfEntIndex:\n"); fclose(fp); } return (*g_engfuncs.pfnPEntityOfEntIndex)(iEntIndex); } edict_t* pfnFindEntityByVars(entvars_t* pvars) { // if (debug_engine) { fp=fopen("bot.txt","a"); fprintf(fp,"pfnFindEntityByVars:\n"); fclose(fp); } return (*g_engfuncs.pfnFindEntityByVars)(pvars); } void* pfnGetModelPtr(edict_t* pEdict) { // if (debug_engine) { fp=fopen("bot.txt","a"); fprintf(fp,"pfnGetModelPtr: %x\n",pEdict); fclose(fp); } return (*g_engfuncs.pfnGetModelPtr)(pEdict); } int pfnRegUserMsg(const char *pszName, int iSize) { int msg; msg = (*g_engfuncs.pfnRegUserMsg)(pszName, iSize); if (gpGlobals->deathmatch) { #ifdef _DEBUG fp=fopen("bot.txt","a"); fprintf(fp,"pfnRegUserMsg: pszName=%s msg=%d\n",pszName,msg); fclose(fp); #endif if (strcmp(pszName, "ShowMenu") == 0) message_ShowMenu = msg; else if (strcmp(pszName, "WeaponList") == 0) message_WeaponList = msg; else if (strcmp(pszName, "CurWeapon") == 0) message_CurWeapon = msg; else if (strcmp(pszName, "AmmoX") == 0) message_AmmoX = msg; else if (strcmp(pszName, "AmmoPickup") == 0) message_AmmoPickup = msg; else if (strcmp(pszName, "Damage") == 0) message_Damage = msg; else if (strcmp(pszName, "Money") == 0) message_Money = msg; else if (strcmp(pszName, "DeathMsg") == 0) message_DeathMsg = msg; else if (strcmp(pszName, "ScreenFade") == 0) message_ScreenFade = msg; else if (strcmp(pszName, "TextMsg") == 0) message_TextMsg = msg; } return msg; } void pfnAnimationAutomove(const edict_t* pEdict, float flTime) { // if (debug_engine) { fp=fopen("bot.txt","a"); fprintf(fp,"pfnAnimationAutomove:\n"); fclose(fp); } (*g_engfuncs.pfnAnimationAutomove)(pEdict, flTime); } void pfnGetBonePosition(const edict_t* pEdict, int iBone, float *rgflOrigin, float *rgflAngles ) { // if (debug_engine) { fp=fopen("bot.txt","a"); fprintf(fp,"pfnGetBonePosition:\n"); fclose(fp); } (*g_engfuncs.pfnGetBonePosition)(pEdict, iBone, rgflOrigin, rgflAngles); } unsigned long pfnFunctionFromName( const char *pName ) { if (debug_engine) { fp=fopen("bot.txt","a"); fprintf(fp,"pfnFunctionFromName:\n"); fclose(fp); } return (*g_engfuncs.pfnFunctionFromName)(pName); } const char *pfnNameForFunction( unsigned long function ) { if (debug_engine) { fp=fopen("bot.txt","a"); fprintf(fp,"pfnNameForFunction:\n"); fclose(fp); } return (*g_engfuncs.pfnNameForFunction)(function); } void pfnClientPrintf( edict_t* pEdict, PRINT_TYPE ptype, const char *szMsg ) { if (debug_engine) { fp=fopen("bot.txt","a"); fprintf(fp,"pfnClientPrintf:\n"); fclose(fp); } (*g_engfuncs.pfnClientPrintf)(pEdict, ptype, szMsg); } void pfnServerPrint( const char *szMsg ) { if (debug_engine) { fp=fopen("bot.txt","a"); fprintf(fp,"pfnServerPrint: %s\n",szMsg); fclose(fp); } (*g_engfuncs.pfnServerPrint)(szMsg); } void pfnGetAttachment(const edict_t *pEdict, int iAttachment, float *rgflOrigin, float *rgflAngles ) { // if (debug_engine) { fp=fopen("bot.txt","a"); fprintf(fp,"pfnGetAttachment:\n"); fclose(fp); } (*g_engfuncs.pfnGetAttachment)(pEdict, iAttachment, rgflOrigin, rgflAngles); } void pfnCRC32_Init(CRC32_t *pulCRC) { if (debug_engine) { fp=fopen("bot.txt","a"); fprintf(fp,"pfnCRC32_Init:\n"); fclose(fp); } (*g_engfuncs.pfnCRC32_Init)(pulCRC); } void pfnCRC32_ProcessBuffer(CRC32_t *pulCRC, void *p, int len) { if (debug_engine) { fp=fopen("bot.txt","a"); fprintf(fp,"pfnCRC32_ProcessBuffer:\n"); fclose(fp); } (*g_engfuncs.pfnCRC32_ProcessBuffer)(pulCRC, p, len); } void pfnCRC32_ProcessByte(CRC32_t *pulCRC, unsigned char ch) { if (debug_engine) { fp=fopen("bot.txt","a"); fprintf(fp,"pfnCRC32_ProcessByte:\n"); fclose(fp); } (*g_engfuncs.pfnCRC32_ProcessByte)(pulCRC, ch); } CRC32_t pfnCRC32_Final(CRC32_t pulCRC) { if (debug_engine) { fp=fopen("bot.txt","a"); fprintf(fp,"pfnCRC32_Final:\n"); fclose(fp); } return (*g_engfuncs.pfnCRC32_Final)(pulCRC); } long pfnRandomLong(long lLow, long lHigh) { // if (debug_engine) { fp=fopen("bot.txt","a"); fprintf(fp,"pfnRandomLong: lLow=%d lHigh=%d\n",lLow,lHigh); fclose(fp); } return (*g_engfuncs.pfnRandomLong)(lLow, lHigh); } float pfnRandomFloat(float flLow, float flHigh) { // if (debug_engine) { fp=fopen("bot.txt","a"); fprintf(fp,"pfnRandomFloat:\n"); fclose(fp); } return (*g_engfuncs.pfnRandomFloat)(flLow, flHigh); } void pfnSetView(const edict_t *pClient, const edict_t *pViewent ) { if (debug_engine) { fp=fopen("bot.txt","a"); fprintf(fp,"pfnSetView:\n"); fclose(fp); } (*g_engfuncs.pfnSetView)(pClient, pViewent); } float pfnTime( void ) { if (debug_engine) { fp=fopen("bot.txt","a"); fprintf(fp,"pfnTime:\n"); fclose(fp); } return (*g_engfuncs.pfnTime)(); } void pfnCrosshairAngle(const edict_t *pClient, float pitch, float yaw) { if (debug_engine) { fp=fopen("bot.txt","a"); fprintf(fp,"pfnCrosshairAngle:\n"); fclose(fp); } (*g_engfuncs.pfnCrosshairAngle)(pClient, pitch, yaw); } byte *pfnLoadFileForMe(char *filename, int *pLength) { if (debug_engine) { fp=fopen("bot.txt","a"); fprintf(fp,"pfnLoadFileForMe: filename=%s\n",filename); fclose(fp); } return (*g_engfuncs.pfnLoadFileForMe)(filename, pLength); } void pfnFreeFile(void *buffer) { if (debug_engine) { fp=fopen("bot.txt","a"); fprintf(fp,"pfnFreeFile:\n"); fclose(fp); } (*g_engfuncs.pfnFreeFile)(buffer); } void pfnEndSection(const char *pszSectionName) { if (debug_engine) { fp=fopen("bot.txt","a"); fprintf(fp,"pfnEndSection:\n"); fclose(fp); } (*g_engfuncs.pfnEndSection)(pszSectionName); } int pfnCompareFileTime(char *filename1, char *filename2, int *iCompare) { if (debug_engine) { fp=fopen("bot.txt","a"); fprintf(fp,"pfnCompareFileTime:\n"); fclose(fp); } return (*g_engfuncs.pfnCompareFileTime)(filename1, filename2, iCompare); } void pfnGetGameDir(char *szGetGameDir) { if (debug_engine) { fp=fopen("bot.txt","a"); fprintf(fp,"pfnGetGameDir:\n"); fclose(fp); } (*g_engfuncs.pfnGetGameDir)(szGetGameDir); } void pfnCvar_RegisterVariable(cvar_t *variable) { if (debug_engine) { fp=fopen("bot.txt","a"); fprintf(fp,"pfnCvar_RegisterVariable:\n"); fclose(fp); } (*g_engfuncs.pfnCvar_RegisterVariable)(variable); } void pfnFadeClientVolume(const edict_t *pEdict, int fadePercent, int fadeOutSeconds, int holdTime, int fadeInSeconds) { if (debug_engine) { fp=fopen("bot.txt","a"); fprintf(fp,"pfnFadeClientVolume:\n"); fclose(fp); } (*g_engfuncs.pfnFadeClientVolume)(pEdict, fadePercent, fadeOutSeconds, holdTime, fadeInSeconds); } /* void pfnSetClientMaxspeed(const edict_t *pEdict, float fNewMaxspeed) { if (debug_engine) { fp=fopen("bot.txt","a"); fprintf(fp,"pfnSetClientMaxspeed: edict=%x %f\n",pEdict,fNewMaxspeed); fclose(fp); } (*g_engfuncs.pfnSetClientMaxspeed)(pEdict, fNewMaxspeed); } */ void pfnSetClientMaxspeed(const edict_t *pEdict, float fNewMaxspeed) { int index = UTIL_GetBotIndex((edict_t *)pEdict); if (index != -1) bots[index].max_speed = fNewMaxspeed; (*g_engfuncs.pfnSetClientMaxspeed)(pEdict, fNewMaxspeed); } edict_t * pfnCreateFakeClient(const char *netname) { if (debug_engine) { fp=fopen("bot.txt","a"); fprintf(fp,"pfnCreateFakeClient:\n"); fclose(fp); } return (*g_engfuncs.pfnCreateFakeClient)(netname); } void pfnRunPlayerMove(edict_t *fakeclient, const float *viewangles, float forwardmove, float sidemove, float upmove, unsigned short buttons, byte impulse, byte msec ) { if (debug_engine) { fp=fopen("bot.txt","a"); fprintf(fp,"pfnRunPlayerMove:\n"); fclose(fp); } (*g_engfuncs.pfnRunPlayerMove)(fakeclient, viewangles, forwardmove, sidemove, upmove, buttons, impulse, msec); } int pfnNumberOfEntities(void) { if (debug_engine) { fp=fopen("bot.txt","a"); fprintf(fp,"pfnNumberOfEntities:\n"); fclose(fp); } return (*g_engfuncs.pfnNumberOfEntities)(); } char* pfnGetInfoKeyBuffer(edict_t *e) { if (debug_engine) { fp=fopen("bot.txt","a"); fprintf(fp,"pfnGetInfoKeyBuffer:\n"); fclose(fp); } return (*g_engfuncs.pfnGetInfoKeyBuffer)(e); } char* pfnInfoKeyValue(char *infobuffer, char *key) { if (debug_engine) { fp=fopen("bot.txt","a"); fprintf(fp,"pfnInfoKeyValue: %s %s\n",infobuffer,key); fclose(fp); } return (*g_engfuncs.pfnInfoKeyValue)(infobuffer, key); } void pfnSetKeyValue(char *infobuffer, char *key, char *value) { if (debug_engine) { fp=fopen("bot.txt","a"); fprintf(fp,"pfnSetKeyValue: %s %s\n",key,value); fclose(fp); } (*g_engfuncs.pfnSetKeyValue)(infobuffer, key, value); } void pfnSetClientKeyValue(int clientIndex, char *infobuffer, char *key, char *value) { if (debug_engine) { fp=fopen("bot.txt","a"); fprintf(fp,"pfnSetClientKeyValue: %s %s\n",key,value); fclose(fp); } (*g_engfuncs.pfnSetClientKeyValue)(clientIndex, infobuffer, key, value); } int pfnIsMapValid(char *filename) { if (debug_engine) { fp=fopen("bot.txt","a"); fprintf(fp,"pfnIsMapValid:\n"); fclose(fp); } return (*g_engfuncs.pfnIsMapValid)(filename); } void pfnStaticDecal( const float *origin, int decalIndex, int entityIndex, int modelIndex ) { if (debug_engine) { fp=fopen("bot.txt","a"); fprintf(fp,"pfnStaticDecal:\n"); fclose(fp); } (*g_engfuncs.pfnStaticDecal)(origin, decalIndex, entityIndex, modelIndex); } int pfnPrecacheGeneric(char* s) { if (debug_engine) { fp=fopen("bot.txt","a"); fprintf(fp,"pfnPrecacheGeneric: %s\n",s); fclose(fp); } return (*g_engfuncs.pfnPrecacheGeneric)(s); } int pfnGetPlayerUserId(edict_t *e ) { if (gpGlobals->deathmatch) { if (debug_engine) { fp=fopen("bot.txt","a"); fprintf(fp,"pfnGetPlayerUserId: %x\n",e); fclose(fp); } } return (*g_engfuncs.pfnGetPlayerUserId)(e); } void pfnBuildSoundMsg(edict_t *entity, int channel, const char *sample, /*int*/float volume, float attenuation, int fFlags, int pitch, int msg_dest, int msg_type, const float *pOrigin, edict_t *ed) { if (debug_engine) { fp=fopen("bot.txt","a"); fprintf(fp,"pfnBuildSoundMsg:\n"); fclose(fp); } (*g_engfuncs.pfnBuildSoundMsg)(entity, channel, sample, volume, attenuation, fFlags, pitch, msg_dest, msg_type, pOrigin, ed); } int pfnIsDedicatedServer(void) { if (debug_engine) { fp=fopen("bot.txt","a"); fprintf(fp,"pfnIsDedicatedServer:\n"); fclose(fp); } return (*g_engfuncs.pfnIsDedicatedServer)(); }
[ "weimingzhi@baidu.com" ]
weimingzhi@baidu.com
677927375a94a0aa16f8f69d62a2bf9450569227
f2ee22679f4015815f567c38089d396971e4c51a
/CAAVisualization.edu/CAAVisManagerImpl.m/src/CAAEVis3DGeoVisuForCGRObject.cpp
9c6307092070a34ea9485142c398fefe3687697b
[]
no_license
poborskii/CAADoc_SelectAgent
72f0a162fa7a502d6763df15d65d76554e9268fe
51e0235ef461b5ac1fd710828c29be4bb538c43c
refs/heads/master
2022-12-06T01:19:28.965598
2020-08-31T02:48:11
2020-08-31T02:48:11
291,596,517
0
0
null
null
null
null
UTF-8
C++
false
false
2,642
cpp
// COPYRIGHT DASSAULT SYSTEMES 2000 // Local Framework #include "CAAEVis3DGeoVisuForCGRObject.h" #include "CAAIVisModelCGRObject.h" // Visualization framework #include "CATRep.h" // Standard Library #include <iostream.h> //------------------------------------------------------------------------------------------- // Creates the TIE Object #include "TIE_CATI3DGeoVisu.h" TIE_CATI3DGeoVisu(CAAEVis3DGeoVisuForCGRObject); // To declare that the class is a data extension of CAAVisModelCGRObject // CATImplementClass(CAAEVis3DGeoVisuForCGRObject,DataExtension,CATBaseUnknown,CAAVisModelCGRObject); // // To declare that CAAEVis3DGeoVisuForCGRObject implements CATI3DGeoVisu, insert // the following line in the interface dictionary: // // CAAVisModelCGRObject CATI3DGeoVisu libCAAVisManagerImpl // //-------------------------------------------------------------------------------------------- CAAEVis3DGeoVisuForCGRObject::CAAEVis3DGeoVisuForCGRObject() { cout << "CAAEVis3DGeoVisuForCGRObject::CAAEVis3DGeoVisuForCGRObject" << endl; } //-------------------------------------------------------------------------------------------- CAAEVis3DGeoVisuForCGRObject::~CAAEVis3DGeoVisuForCGRObject() { cout << "CAAEVis3DGeoVisuForCGRObject::~CAAEVis3DGeoVisuForCGRObject" << endl; UnreferenceRep(); } //-------------------------------------------------------------------------------------------- CATRep * CAAEVis3DGeoVisuForCGRObject::BuildRep() { CATRep * pRepToReturn = NULL ; CAAIVisModelCGRObject *pIVisModelCGRObject =NULL; HRESULT rc = QueryInterface(IID_CAAIVisModelCGRObject,(void **)&pIVisModelCGRObject); if ( SUCCEEDED(rc) ) { CATRep *pRep = NULL ; rc = pIVisModelCGRObject->GetCGRRep(&pRep); if ( SUCCEEDED(rc) ) { pRepToReturn= pRep ; } pIVisModelCGRObject->Release(); pIVisModelCGRObject = NULL ; } return pRepToReturn ; } //------------------------------------------------------------------------------- CATRep * CAAEVis3DGeoVisuForCGRObject::GetRep() { if ( NULL != _rep) return _rep; else { _rep = BuildRep(); if ( NULL != _rep) { // check if default identificator has to be put if ( _rep->GetIdentificator() && ( _rep->GetIdentificator()->GetIntId() == 0 ) ) { CATModelIdentificator ident(this); _rep->SetNewId(ident); } } return _rep; } } //------------------------------------------------------------------------------------ void CAAEVis3DGeoVisuForCGRObject::UnreferenceRep () { _rep = NULL; }
[ "poborsk_liu@613.com" ]
poborsk_liu@613.com
a35cc584bf682f6d79cc4b24314fd9acda65e17d
892d94d439d22613e913c6893799cc4427550f90
/include/DiggerOffline/Action.h
f401365c806b44da0af358e5eda0a1dd5c0b7dd0
[]
no_license
VovaMiller/digger-offline-2d
cc3452e06ef73070b75ed1ccc709e646e644367b
cb6d01ef5c5884a156a4ac94b4827519638411b6
refs/heads/master
2021-09-14T19:25:58.035846
2018-05-17T21:15:36
2018-05-17T21:15:36
121,681,872
0
0
null
2018-05-17T20:46:07
2018-02-15T20:56:43
null
UTF-8
C++
false
false
1,273
h
#pragma once #include <string> #include <vector> class Action { public: virtual ~Action() {} virtual void Act() = 0; }; class ActionMacro : public Action { public: virtual ~ActionMacro(); virtual void Act(); void AddAction(Action* action); private: std::vector<Action*> actions_; }; class Action_OpenMapMenu : public Action { public: virtual void Act(); }; class Action_Exit : public Action { public: virtual void Act(); }; class Action_LoadMap : public Action { public: Action_LoadMap(const std::string& map_path); std::string map_path_; virtual void Act(); }; class Action_Back : public Action { public: virtual void Act(); }; class Action_Save : public Action { public: virtual void Act(); }; class Action_Continue : public Action { public: virtual void Act(); }; class Action_Halt : public Action { public: virtual void Act(); }; class Action_PlaySound : public Action { public: Action_PlaySound(const std::string& sound_path, bool interrupt); std::string sound_path_; bool interrupt_; virtual void Act(); }; class Action_StopSound : public Action { public: Action_StopSound(const std::string& sound_path); std::string sound_path_; virtual void Act(); }; class Action_NewMap : public Action { public: virtual void Act(); };
[ "Miller.VV@phystech.edu" ]
Miller.VV@phystech.edu
4dd2aef926f67ec4c1b7fad95ecaa1ad32902670
81ca44fbdc15a9e593998a6ea0611918fb08e132
/101-the_block_problem/main.cpp
57a6e8836cf3c8998f6a2df21f1d4edccdbe0a46
[]
no_license
hugues-vincent/uva
613be2ac1314611b0b951a21192e9cf1cbb38fe7
39498a9e9302aed60da924990b5408363002a171
refs/heads/master
2020-04-06T16:54:18.611529
2018-11-29T19:31:55
2018-11-29T19:31:55
157,638,707
0
0
null
null
null
null
UTF-8
C++
false
false
277
cpp
#include <iostream> using namespace std; int main() { int n, a, b; char word1[4], word2[4]; string foo; bool quit = false; scanf("%d", &n); while(!quit){ scanf("%s", word1); if(word1) cout << word1; } return 0; }
[ "hugues.vincent.ropert@tetha.pw" ]
hugues.vincent.ropert@tetha.pw
ad0c5bf8c38eb132b7f73a2946f08ebdb4172d01
857eb9ffc1385b5a2eac2ff95f9dcd68d50c170b
/include/subsystem_controllers/chassis_controller.hpp
e3ceea36ff417745d5991bbeb5c9c582390de6bd
[]
no_license
77788J/77788J-TP-Mark-III
8823ce3fb7a0f497e94b6c7f27e68da48b53c7e1
6792e670d0917a5225743cc2093d5753c0a69f95
refs/heads/master
2022-01-10T09:14:49.795439
2019-05-15T18:14:31
2019-05-15T18:14:31
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,196
hpp
#ifndef CHASSIS_CONTROLLER_H_ #define CHASSIS_CONTROLLER_H_ #include "subsystem_interfaces/chassis_interface.hpp" namespace chassis_controller { enum MovementMode { none, dist_pid, rot_pid }; extern MovementMode mode; typedef struct PidConstants { float kp; // proportional constant float ki; // integral constant float kd; // derivative constant float max_accel; // maximum acceleration (vel difference per 10ms) int max_voltage; // max voltage to apply int min_voltage; // minimum voltage to supply } PidConstants; // constants extern PidConstants dist_pid_constants; extern PidConstants orientation_pid_constants; // move distance with custom PID controller void move_dist_pid(units::Distance dist, PidConstants constants=dist_pid_constants, bool wait=true, bool* flag=nullptr); // move dist (PID) (with timeout) void move_dist_pid(units::Distance dist, units::Time timeout, bool* flag=nullptr); // rotate with custom PID controller void rotate_pid(units::Angle orientation, PidConstants constants=orientation_pid_constants, bool wait=true, bool* flag=nullptr); // update controller void update(); } #endif
[ "zachchampion79@gmail.com" ]
zachchampion79@gmail.com
01429d77837fb4cdd178bcdd98b142ba3baab88e
dfab96efeea9646fe54bd54ea91bc75e8086e892
/InputStream.h
3745f086a96120eddbc9f6ceb10126dbbc8a3ea3
[]
no_license
lisaula/Compi_exam
8be7202e0d1861873a1cf12b9a94d46109ec51bc
50ee480a22b4294415ae8f9c8feb2dfbd2dc2779
refs/heads/master
2020-12-30T11:51:18.926076
2017-05-17T03:16:34
2017-05-17T03:16:34
91,528,679
0
0
null
null
null
null
UTF-8
C++
false
false
308
h
#ifndef INPUTSTREAM_H #define INPUTSTREAM_H #include <string.h> class InputStream { public: unsigned int contador, length; char* code; InputStream(char* code); char getNextSymbol(); virtual ~InputStream(); protected: private: }; #endif // INPUTSTREAM_H
[ "luisca_elfather@hotmail.com" ]
luisca_elfather@hotmail.com
44960a9d2737ccc50e42f2d4548cd50b21e62c27
30150c7f6ed7a10ac50eee3f40101bc3165ebf9e
/src/installer/sysinfo.h
33af8aec9ff63dc6ce75984b5e4d1230882b6529
[]
no_license
toontown-restoration-project/toontown
c2ad0d552cb9d5d3232ae6941e28f00c11ca3aa8
9bef6d9f823b2c12a176b33518eaa51ddbe3fd2f
refs/heads/master
2022-12-23T19:46:16.697036
2020-10-02T20:17:09
2020-10-02T20:17:09
300,672,330
0
0
null
null
null
null
UTF-8
C++
false
false
7,490
h
// Filename: sysinfo.h // Created by: jimbob (09Jan97) // $Id$ // //////////////////////////////////////////////////////////////////// #ifndef SYSINFO_H #define SYSINFO_H // //////////////////////////////////////////////////////////////////// // Includes //////////////////////////////////////////////////////////////////// #undef WIN32_LEAN_AND_MEAN #include <windows.h> #include <stdlib.h> #include <stdio.h> #include <ddraw.h> #include <psapi.h> #include <string> #include <sstream> // stringstream easier to use than strstream, no memleaks or 'ends' reqd using namespace std; HRESULT DxDiag_Init(void); HRESULT PrintDxDiagDisplayInfo(void); //////////////////////////////////////////////////////////////////// // Class : SysInfo // Description : //////////////////////////////////////////////////////////////////// class SysInfo { public: #include "sysinfodefs.h" public: ostringstream _gfx_report_str; SysInfo(void); SysInfo::~SysInfo(void); bool write_log_file(const char *logfilename); static bool get_available_space(const char *dirname, unsigned __int64 &free_bytes); // inline OSType get_os_type(void) const { return os_type; } static OSType get_os_type(void); static float get_os_servicepack_version(void); string get_os_namestr(void); // inline CPUType get_cpu_type(void) const { return cpu_type; } // inline int get_cpu_level(void) const { return cpu_level; } inline bool get_mouse_enabled(void) const { return _mouse_enabled; } void check_language_info(void); bool has_custom_mousecursor_ability(void) const { return _bHas_custom_mousecursor_ability; } inline float get_ram_megs_total(void) const { return _ram_megs_total; } inline GAPIType get_suggested_gfx_api(void) const { return _gfx_api_suggested; } string get_gfx_api_name(GAPIType gapi) const; inline bool get_3d_hw(void) const { return _has_3d_hw; } inline bool get_sound_enabled(void) const { return _sound_enabled; } inline int get_max_baud(void) const { return _comm_baud; } #if defined(USE_DX9) void Test_DX9(bool bWhatever); #endif void Test_DX8(bool bIsDX81); #if defined(USE_DX7) void Test_DX7(bool bPrintUserErrors); #endif void Test_OpenGL(void); bool ValidateCardTypeandDriver(void); bool IsBadVidMemCheckCard(DDDEVICEIDENTIFIER2 *pDevInfo); DWORD GetVidMemSizeFromRegistry(void); void CheckForBadMouseCursorDriver(void); GAPIType GetPreferredGAPI(void) const; void PrintProcessMemInfo(HANDLE hProcess); // static so we dont have to do the 'run TT' path to get this info static void print_os_info(void); static bool IsNTAdmin(void); // const char *GetGraphicsCardCanonicalName(void); void SetVideoCardConfigInfo(UINT AdapterNum, DDDEVICEIDENTIFIER2 *pDeviceID,SYSTEMTIME *pDriverDate_SysTime); void PrintNo3DHWMsg(void); void SetGeneric3DError(char *LogError); protected: void check_os(void); void check_cpu(void); void check_mouse(void); void check_ram(void); void check_3d_hw(void); void check_snd(void); void check_net_connection(void); int get_commport_baud(const char *cportname); void get_country_info(HINSTANCE hKernel); public: string _CPUNameStr,_CPUMakerStr,_CPUTypeStr; DWORD _NumCPUs, _CPUMhz; OSType _os_type; float _OSServicePackVer; // e.g. 3.5 if service pack 3, minor ver 5 is installed bool _mouse_enabled; int _mouse_buttons; bool _bHas_custom_mousecursor_ability; float _ram_megs_total; float _ram_megs_available; bool _has_3d_hw; bool _forbidOpenGL; // dbg flag GAPIType _dx_level_installed; GAPIType _gfx_api_suggested; // what we tell configrc.exe #if defined(USE_DX7) GfxCheckStatus _DX7_status; #endif GfxCheckStatus _DX8_status,_OpenGL_status; #if defined(USE_DX9) GfxCheckStatus _DX9_status; #endif DDDEVICEIDENTIFIER2 _VideoDeviceID; SYSTEMTIME _VideoDriverDate; bool _bValidVideoDeviceID; // GfxCardType _graphics_card_type; string _DXVerStr; bool _sound_enabled; CommType _comm_type; int _comm_baud; time_t _startup_time; HINSTANCE _hPsAPI; bool _bNetworkIsLAN; string _KeybdLayoutStr; string _LangIDStr; string _LocaleIDStr; string _CountryNameStr; string _IEVersionStr; double _IEVersionNum; // float so you can represent IE 5.5, etc string _IPAddrStr; string _MACAddrStr; string _VideoCardNameStr; DWORD _VideoCardVendorID; string _VideoCardVendorIDStr; DWORD _VideoCardDeviceID; string _VideoCardDeviceIDStr; DWORD _VideoCardSubsysID; string _VideoCardSubsysIDStr; DWORD _VideoCardRevisionID; string _VideoCardRevisionIDStr; string _VideoCardDriverDateStr; string _VideoCardDriverVerStr; DWORD _VideoCardDriverDateMon; DWORD _VideoCardDriverDateDay; DWORD _VideoCardDriverDateYear; bool _bDoneVidMemCheck; DWORD _VideoRamTotalBytes; DWORD _numMonitors; string _OGLVendorNameStr; string _OGLRendererNameStr; string _OGLVerStr; /* this stuff must come from configrc via the registry string _ScreenModeStr; */ // 1 string contains fields for all devices. may want to break this out further l8r string _MidiOutAllDevicesStr; string _DSoundDevicesStr; // catch-all string for all other unanticipated data to store on stat server string _ExtraStr; // MS misspelt 'performance' in psapi.h. duh. typedef BOOL (WINAPI *GETPERFINFO)(PPERFORMACE_INFORMATION pPerformanceInformation,DWORD cb); typedef BOOL (WINAPI *GETPROCESSMEMORYINFO)(HANDLE Process,PPROCESS_MEMORY_COUNTERS ppsmemCounters,DWORD cb); typedef void (WINAPI *GNSI)(LPSYSTEM_INFO si); GETPERFINFO _pGetPerfInfo; GETPROCESSMEMORYINFO _pGetProcessMemoryInfo; GNSI _pGetSystemInfo; static GNSI getSystemInfoProc(); }; #define SET_USER_ERROR(LOGSTR,USERSTR) { \ errorLog << LOGSTR << std::endl; \ _gfx_report_str << USERSTR << std::endl; } #define ONE_MB_BYTES (1<<20) #define SAFE_RELEASE(P) { if((P)!=NULL) { (P)->Release(); (P) = NULL; } } #define SAFE_FREELIB(hLIB) { if((hLIB)!=NULL) { FreeLibrary(hLIB); (hLIB) = NULL; } } #define SAFE_DELETE(P) { if((P)!=NULL) { delete (P); (P) = NULL; } } #define SAFE_DELETE_ARRAY(P) { if((P)!=NULL) { delete [] (P); (P) = NULL; } } #define SAFE_REGCLOSEKEY(HKEY) { if((HKEY)!=NULL) { RegCloseKey(HKEY); (HKEY) = NULL; } } #define SET_BOTH_ERROR(LOGSTR) SET_USER_ERROR(LOGSTR,LOGSTR) extern void SearchforDriverInfo(const char *driver_filename,ULARGE_INTEGER *pli,SYSTEMTIME *pDriverDate); extern void MyGetModuleVersion(HMODULE hMod, ULARGE_INTEGER *pli); extern void MyGetFileVersion(char *FileName, ULARGE_INTEGER *pli); extern HWND CreateOpenGLWindow(char *title, int pixfmtnum, PIXELFORMATDESCRIPTOR *pPFD, int x, int y, int width, int height, BYTE type, DWORD flags,HDC *hDC); extern void ShowErrorBox(const char *msg); // these flags are for debugging only. might be better to use dbg-only regkeys so dont have to rebuild (but then have to include dbg code) //#define FORBID_OPENGL //#define FORBID_DX8 //#define FORBID_DX7 //#define FORCE_OPENGL //#define FORCE_DX7 // skip DX8 //#define PREFER_DX7 //#define PREFER_DX8 //#define PREFER_OPENGL #define PRINTDRIVER_VERSTR(LARGEINT_VER) HIWORD(LARGEINT_VER.HighPart) << "." << LOWORD(LARGEINT_VER.HighPart) << "." << HIWORD(LARGEINT_VER.LowPart) << "." << LOWORD(LARGEINT_VER.LowPart) #define LARGEINT_EQUAL(LI1,LI2) ((LI1.HighPart==LI2.HighPart)&&(LI1.LowPart==LI2.LowPart)) #endif
[ "brianlach72@gmail.com" ]
brianlach72@gmail.com
6d83a29764a72a3351bb135a7811da422873f55d
5499e8b91353ef910d2514c8a57a80565ba6f05b
/src/connectivity/wlan/drivers/third_party/broadcom/brcmfmac/test/sim_test.cc
1530fbde4a93f0ec8952efb9250a5557b2818a18
[ "BSD-3-Clause", "ISC" ]
permissive
winksaville/fuchsia
410f451b8dfc671f6372cb3de6ff0165a2ef30ec
a0ec86f1d51ae8d2538ff3404dad46eb302f9b4f
refs/heads/master
2022-11-01T11:57:38.343655
2019-11-01T17:06:19
2019-11-01T17:06:19
223,695,500
3
2
BSD-3-Clause
2022-10-13T13:47:02
2019-11-24T05:08:59
C++
UTF-8
C++
false
false
2,144
cc
// Copyright 2019 The Fuchsia 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 "sim_test.h" #include <gtest/gtest.h> #include "src/connectivity/wlan/drivers/testing/lib/sim-device/device.h" #include "src/connectivity/wlan/drivers/testing/lib/sim-env/sim-env.h" #include "src/connectivity/wlan/drivers/third_party/broadcom/brcmfmac/sim_device.h" namespace wlan::brcmfmac { intptr_t SimTest::instance_num_ = 0; SimTest::SimTest() { env_ = std::make_shared<simulation::Environment>(); env_->AddStation(this); dev_mgr_ = std::make_shared<simulation::FakeDevMgr>(); parent_dev_ = reinterpret_cast<zx_device_t*>(instance_num_++); } zx_status_t SimTest::Init() { return brcmfmac::SimDevice::Create(parent_dev_, dev_mgr_, env_, &device_); } zx_status_t SimTest::CreateInterface(wlan_info_mac_role_t role, const wlanif_impl_ifc_protocol& sme_protocol, std::unique_ptr<SimInterface>* ifc_out) { zx_status_t status; std::unique_ptr<SimInterface> sim_ifc = std::make_unique<SimInterface>(); if ((status = sim_ifc->Init()) != ZX_OK) { return status; } wlanphy_impl_create_iface_req_t req = {.role = role, .sme_channel = sim_ifc->ch_mlme_}; if ((status = device_->WlanphyImplCreateIface(&req, &sim_ifc->iface_id_)) != ZX_OK) { return status; } // This should have created a WLANIF_IMPL device auto device_info = dev_mgr_->FindFirstByProtocolId(ZX_PROTOCOL_WLANIF_IMPL); if (device_info == std::nullopt) { return ZX_ERR_INTERNAL; } sim_ifc->if_impl_args_ = device_info->dev_args; auto if_impl_ops = static_cast<wlanif_impl_protocol_ops_t*>(sim_ifc->if_impl_args_.proto_ops); zx_handle_t sme_ch; status = if_impl_ops->start(device_info->dev_args.ctx, &sme_protocol, &sme_ch); // Verify that the channel passed back from start() is the same one we gave to create_iface() if (sme_ch != sim_ifc->ch_mlme_) { return ZX_ERR_INTERNAL; } *ifc_out = std::move(sim_ifc); return ZX_OK; } } // namespace wlan::brcmfmac
[ "commit-bot@chromium.org" ]
commit-bot@chromium.org
fd13c84fd43a3097424d69ac87d5509ecb07a4b3
eedd904304046caceb3e982dec1d829c529da653
/clanlib/ClanLib-2.2.8/Sources/API/Crypto/private_key.h
fa5e55a7cdd7a1b53e702ea4a2f9cb5c84658abe
[]
no_license
PaulFSherwood/cplusplus
b550a9a573e9bca5b828b10849663e40fd614ff0
999c4d18d2dd4d0dd855e1547d2d2ad5eddc6938
refs/heads/master
2023-06-07T09:00:20.421362
2023-05-21T03:36:50
2023-05-21T03:36:50
12,607,904
4
0
null
null
null
null
UTF-8
C++
false
false
1,875
h
/* ** ClanLib SDK ** Copyright (c) 1997-2011 The ClanLib Team ** ** This software is provided 'as-is', without any express or implied ** warranty. In no event will the authors be held liable for any damages ** arising from the use of this software. ** ** Permission is granted to anyone to use this software for any purpose, ** including commercial applications, and to alter it and redistribute it ** freely, subject to the following restrictions: ** ** 1. The origin of this software must not be misrepresented; you must not ** claim that you wrote the original software. If you use this software ** in a product, an acknowledgment in the product documentation would be ** appreciated but is not required. ** 2. Altered source versions must be plainly marked as such, and must not be ** misrepresented as being the original software. ** 3. This notice may not be removed or altered from any source distribution. ** ** Note: Some of the libraries ClanLib may link to may have additional ** requirements or restrictions. ** ** File Author(s): ** ** Magnus Norddahl */ #pragma once /// \addtogroup clanCrypto_System clanCrypto System /// \{ #include <prio.h> #include <keyt.h> /// \brief Private Key /// /// \xmlonly !group=Crypto/System! !header=crypto.h! \endxmlonly class CL_PrivateKey { /// \name Construction /// \{ public: CL_PrivateKey(); /// \brief Constructs a PrivateKey /// /// \param key = SECKEYPrivate Key CL_PrivateKey(SECKEYPrivateKey *key); /// \brief Constructs a PrivateKey /// /// \param copy = Private Key CL_PrivateKey(const CL_PrivateKey &copy); ~CL_PrivateKey(); /// \} /// \name Attributes /// \{ public: SECKEYPrivateKey *key; /// \} /// \name Operations /// \{ public: CL_PrivateKey &operator =(const CL_PrivateKey &copy); /// \} /// \name Implementation /// \{ private: /// \} }; /// \}
[ "paulfsherwood@gmail.com" ]
paulfsherwood@gmail.com
7942f258eb801d0d8b757482a9d9ecc46cb49336
dca28153d0fbfef939ce3a8a51135e95499dfa0c
/readMatrix.cpp
e09a32a78b2d6f625c543b44ea8baff0735e2a7c
[]
no_license
htimsnahtan/matrix-calculator
aaf4d3f3691aef43187ada074320e4bc9e25e8d8
5a81d10d992b66add7706fc06edbd73f81df7267
refs/heads/main
2020-03-22T14:44:58.109575
2018-07-20T20:50:00
2018-07-20T20:50:00
140,202,590
0
0
null
null
null
null
UTF-8
C++
false
false
621
cpp
#include "readMatrix.hpp" #include <iostream> /* Give 2 inputs of a pointer to a square 2d array and the size of the matrix, prompts user to input integers into each point on the matrix. Does not return. */ void readMatrix(int **arrayPtrIn, int matrixSizeIn) { std::cout << "Enter " << matrixSizeIn*matrixSizeIn << " numbers separated by the Enter key (counting left to right from top, left point in matrix" << std::endl; for (int i = 0; i < matrixSizeIn; ++i) for (int j = 0; j < matrixSizeIn; ++j) { std::cin >> arrayPtrIn[i][j]; } }
[ "htimsnahtan@gmail.com" ]
htimsnahtan@gmail.com
9dc77114c43945fb979a6c635f71771a3ab74378
52dab43236a9b0cd0f406aaf6c15f145f1376c98
/cpp/include/PMTResponse.h
9d24680ccc20b3058521049668709cae26040034
[]
no_license
Abdoelabassi/MDT
1f94162cece50384059703e8618365250994d46b
27fae8e9cf2d04cca48a117fa4216d474a6cab61
refs/heads/master
2023-07-27T12:34:36.563250
2021-06-18T17:49:16
2021-06-18T17:49:16
null
0
0
null
null
null
null
UTF-8
C++
false
false
611
h
#pragma once #include <iostream> #include <string> #include <cmath> #include "MTRandom.h" // Manage: // // - generation of SPE // - timing resolution // // for R12199_02 3'' PMT for mPMT // // The implementations are based on: // - WCSimPMTObject.cc // - WCSimWCDigitizer.cc class PMTResponse { public: PMTResponse(const int); virtual ~PMTResponse(); double GetRawSPE(); float HitTimeSmearing(float); private: MTRandom *fRand; static const float fqpe0[501]; float fTResConstant; float fTResMinimum; float fSclFacTTS; };
[ "rakutsu@icrr.u-tokyo.ac.jp" ]
rakutsu@icrr.u-tokyo.ac.jp
598afd77d3fc59490869b9c462f3ff3bc4e8b966
0ce33ddb5a912652be7947485bac4435a7fff344
/8-segment-led/SegmentLED.ino
e4b12000b5d5deff7b9ee9cbdb3fec8e8e78cb2f
[ "MIT" ]
permissive
michaelachrisco/Arduino-projects
b2cf4206e9bb486dd11035b36808544e504a5320
c3fedfe9aee232a23b5813ffc9761d4aab417f0a
refs/heads/master
2021-07-12T15:20:34.539133
2021-07-03T23:11:13
2021-07-03T23:11:13
224,782,643
0
0
MIT
2019-12-10T04:40:42
2019-11-29T05:27:43
C++
UTF-8
C++
false
false
1,757
ino
// https://www.datasheetarchive.com/pdf/download.php?id=143240d741a05b795bfc23691077a7c4a43b10&type=P&term=Display%25205082%25207731 const int pinDP = 8; const int pinA = 9; const int pinB = 10; const int pinC = 11; const int pinD = 12; const int pinG = 13; const int pinE = 2; const int pinF = 3; //TODO: Add in all combos int one[3] = {pinB,pinC,pinDP}; int two[6] = {pinA,pinB,pinG,pinE,pinD,pinDP}; int three[6] = {pinA,pinB,pinG,pinC,pinD,pinDP}; int four[5] = {pinF,pinG,pinB,pinC,pinDP}; int five[6] = {pinA,pinF,pinG,pinC,pinD,pinDP}; int six[6] = {pinA,pinF,pinG,pinC,pinD,pinE}; int seven[6] = {pinA,pinB,pinC,pinDP}; int eight[8] = {pinA,pinB,pinG,pinC,pinD,pinE,pinF,pinDP}; int nine[6] = {pinA,pinB,pinC,pinF,pinDP}; int* allnums[] = {one, two, three, four, five, six, seven, eight, nine}; int counter; void applyDigits(int arr[], int sizeOfArray){ resetDigits(); for ( int k = 0 ; k < sizeOfArray ; ++k ){ digitalWrite(arr[k], LOW); } } void resetDigits(){ digitalWrite(pinDP, HIGH); digitalWrite(pinA, HIGH); digitalWrite(pinB, HIGH); digitalWrite(pinC, HIGH); digitalWrite(pinD, HIGH); digitalWrite(pinE, HIGH); digitalWrite(pinF, HIGH); digitalWrite(pinG, HIGH); } void allON(){ digitalWrite(pinDP, LOW); digitalWrite(pinA, LOW); digitalWrite(pinB, LOW); digitalWrite(pinC, LOW); digitalWrite(pinD, LOW); digitalWrite(pinE, LOW); digitalWrite(pinF, LOW); digitalWrite(pinG, LOW); } void setup(){ // one = {0,1,2,3,4,5}; pinMode(pinD, OUTPUT); } void loop(){ // resetDigits(); //while(true){ // digitalWrite(pinG, LOW); //delay(1000); //digitalWrite(pinG, HIGH); //} // applyDigits(one, 2); // delay(10000); // resetDigits(); delay(1000); allON(); delay(1000); }
[ "michaelachrisco@gmail.com" ]
michaelachrisco@gmail.com
78f927941b1965b36356c3a549fa4f20f87ffabb
eee2f48594874f5138a0da8fa1a5a4db3c6817dc
/RTC_DS1307.h
395695409eb55641b6979fda47970cc2031fd13e
[]
no_license
CNCBASHER/AnyRtc
79a8c39788066fe4db3a777702c6e77b098deb51
3d807561d8d44a3c6dd49f928aac19f37ea17385
refs/heads/master
2021-01-17T22:02:43.178887
2012-06-24T02:45:29
2012-06-24T02:45:29
null
0
0
null
null
null
null
UTF-8
C++
false
false
602
h
// Code by JeeLabs http://news.jeelabs.org/code/ // Released to the public domain! Enjoy! #ifndef __RTC_DS1307_H__ #define __RTC_DS1307_H__ #include <AnyRtc.h> #include <Wire.h> // RTC based on the DS1307 chip connected via I2C and the Wire library class RTC_DS1307: public IRTC { public: uint8_t begin(void); void adjust(const DateTime& dt); uint8_t isrunning(void); DateTime nowDateTime(void) const; void adjust(uint32_t tv) { adjust(DateTime(tv)); } uint32_t now(void) const { return nowDateTime().unixtime(); } }; #endif // __RTC_DS1307_H__ // vim:ci:sw=4 sts=4 ft=cpp
[ "maniacbug@ymail.com" ]
maniacbug@ymail.com
dbdba54fb1b975368a1b7cd2e2dc58a92199ee80
37dfdfbae6886a23cf6a3626a05f57869a89b3f5
/Source/FairyGUIEnginePlugin/fairygui/GGraph.h
6beec50ad741e62745d6be3a2ecede54427e1dbb
[ "MIT" ]
permissive
fhaoquan/FairyGUI-vision
8dbf79982d2c9b07e0f8fe73ada1f5c91dee2ef8
63c2f5a4bfc7e3db954ef55a689be26b9a0f3518
refs/heads/master
2020-03-30T22:33:17.013554
2018-05-24T15:07:44
2018-05-24T15:07:44
null
0
0
null
null
null
null
UTF-8
C++
false
false
912
h
#ifndef __GGRAPH_H__ #define __GGRAPH_H__ #include "FGUIMacros.h" #include "GObject.h" #include "core/Shape.h" #include "gears/GearColor.h" NS_FGUI_BEGIN class FGUI_IMPEXP GGraph : public GObject, public IColorGear { public: CREATE_FUNC(GGraph); void drawRect(float aWidth, float aHeight, int lineSize, const VColorRef& lineColor, const VColorRef& fillColor); void drawEllipse(float aWidth, float aHeight, const VColorRef& fillColor); bool isEmpty() const { return _shape->isEmpty(); } const VColorRef& getColor() const override; void setColor(const VColorRef& value) override; protected: GGraph(); virtual ~GGraph(); protected: virtual void handleInit() override; virtual void setup_BeforeAdd(TXMLElement* xml) override; private: Shape *_shape; private: CC_DISALLOW_COPY_AND_ASSIGN(GGraph); }; NS_FGUI_END #endif
[ "gzytom@139.com" ]
gzytom@139.com
195eee30caf0dd73e89bfe4f3afaf013d52dff6d
6fd3d7340eaaab551a22f5918d3c5fd3d27040c0
/SERVERS/WorldServer/DB_UpdatePlayerFlag.h
d20dc696a5ac6102cb3f26cac9f6c2db248f7670
[]
no_license
Aden2018/WinServer
beda5bb9058a08d1961f2852b48ca5217ca80e86
f3c068cd8afed691e32fc6516060187014ba3a71
refs/heads/master
2023-03-18T20:10:55.698791
2018-03-02T03:50:21
2018-03-02T03:50:21
null
0
0
null
null
null
null
UTF-8
C++
false
false
334
h
#ifndef _DB_UPDATEPLAYERFLAG_H_ #define _DB_UPDATEPLAYERFLAG_H_ #include "CommLib/ThreadPool.h" class DB_UpdatePlayerFlag : public ThreadBase { public: DB_UpdatePlayerFlag(void); //method from ThreadBase virtual int Execute(int ctxId,void* param); U32 mPlayerId; U32 mPlayerFlag; }; #endif /*_DBUPDATEACCOUNTTIME_*/
[ "754266963@qq.com" ]
754266963@qq.com
40d5afedf21f32751b2db0f4be74ce871f8452d7
dac35c7e3d56879016a98a2d0d72100b175e4517
/OpenWorld/Source/OpenWorld/OpenWorldCharacter.cpp
e6694664a04363cb0beec6322de2106813332ec6
[]
no_license
TheK-B1000/OpenWorld
b00df3ff1b8a79c21e9cdc6392fbf35360b9e74d
01b497ea4cb463f6f31b7860665e8fd3d4a65ac9
refs/heads/master
2020-12-04T22:29:50.064107
2020-01-06T15:14:36
2020-01-06T15:14:36
231,922,669
0
0
null
null
null
null
UTF-8
C++
false
false
5,296
cpp
// Copyright 1998-2019 Epic Games, Inc. All Rights Reserved. #include "OpenWorldCharacter.h" #include "HeadMountedDisplayFunctionLibrary.h" #include "Camera/CameraComponent.h" #include "Components/CapsuleComponent.h" #include "Components/InputComponent.h" #include "GameFramework/CharacterMovementComponent.h" #include "GameFramework/Controller.h" #include "GameFramework/SpringArmComponent.h" ////////////////////////////////////////////////////////////////////////// // AOpenWorldCharacter AOpenWorldCharacter::AOpenWorldCharacter() { // Set size for collision capsule GetCapsuleComponent()->InitCapsuleSize(42.f, 96.0f); // set our turn rates for input BaseTurnRate = 45.f; BaseLookUpRate = 45.f; // Don't rotate when the controller rotates. Let that just affect the camera. bUseControllerRotationPitch = false; bUseControllerRotationYaw = false; bUseControllerRotationRoll = false; // Configure character movement GetCharacterMovement()->bOrientRotationToMovement = true; // Character moves in the direction of input... GetCharacterMovement()->RotationRate = FRotator(0.0f, 540.0f, 0.0f); // ...at this rotation rate GetCharacterMovement()->JumpZVelocity = 600.f; GetCharacterMovement()->AirControl = 0.2f; // Create a camera boom (pulls in towards the player if there is a collision) CameraBoom = CreateDefaultSubobject<USpringArmComponent>(TEXT("CameraBoom")); CameraBoom->SetupAttachment(RootComponent); CameraBoom->TargetArmLength = 300.0f; // The camera follows at this distance behind the character CameraBoom->bUsePawnControlRotation = true; // Rotate the arm based on the controller // Create a follow camera FollowCamera = CreateDefaultSubobject<UCameraComponent>(TEXT("FollowCamera")); FollowCamera->SetupAttachment(CameraBoom, USpringArmComponent::SocketName); // Attach the camera to the end of the boom and let the boom adjust to match the controller orientation FollowCamera->bUsePawnControlRotation = false; // Camera does not rotate relative to arm // Note: The skeletal mesh and anim blueprint references on the Mesh component (inherited from Character) // are set in the derived blueprint asset named MyCharacter (to avoid direct content references in C++) } ////////////////////////////////////////////////////////////////////////// // Input void AOpenWorldCharacter::SetupPlayerInputComponent(class UInputComponent* PlayerInputComponent) { // Set up gameplay key bindings check(PlayerInputComponent); PlayerInputComponent->BindAction("Jump", IE_Pressed, this, &ACharacter::Jump); PlayerInputComponent->BindAction("Jump", IE_Released, this, &ACharacter::StopJumping); PlayerInputComponent->BindAxis("MoveForward", this, &AOpenWorldCharacter::MoveForward); PlayerInputComponent->BindAxis("MoveRight", this, &AOpenWorldCharacter::MoveRight); // We have 2 versions of the rotation bindings to handle different kinds of devices differently // "turn" handles devices that provide an absolute delta, such as a mouse. // "turnrate" is for devices that we choose to treat as a rate of change, such as an analog joystick PlayerInputComponent->BindAxis("Turn", this, &APawn::AddControllerYawInput); PlayerInputComponent->BindAxis("TurnRate", this, &AOpenWorldCharacter::TurnAtRate); PlayerInputComponent->BindAxis("LookUp", this, &APawn::AddControllerPitchInput); PlayerInputComponent->BindAxis("LookUpRate", this, &AOpenWorldCharacter::LookUpAtRate); // handle touch devices PlayerInputComponent->BindTouch(IE_Pressed, this, &AOpenWorldCharacter::TouchStarted); PlayerInputComponent->BindTouch(IE_Released, this, &AOpenWorldCharacter::TouchStopped); // VR headset functionality PlayerInputComponent->BindAction("ResetVR", IE_Pressed, this, &AOpenWorldCharacter::OnResetVR); } void AOpenWorldCharacter::OnResetVR() { UHeadMountedDisplayFunctionLibrary::ResetOrientationAndPosition(); } void AOpenWorldCharacter::TouchStarted(ETouchIndex::Type FingerIndex, FVector Location) { Jump(); } void AOpenWorldCharacter::TouchStopped(ETouchIndex::Type FingerIndex, FVector Location) { StopJumping(); } void AOpenWorldCharacter::TurnAtRate(float Rate) { // calculate delta for this frame from the rate information AddControllerYawInput(Rate * BaseTurnRate * GetWorld()->GetDeltaSeconds()); } void AOpenWorldCharacter::LookUpAtRate(float Rate) { // calculate delta for this frame from the rate information AddControllerPitchInput(Rate * BaseLookUpRate * GetWorld()->GetDeltaSeconds()); } void AOpenWorldCharacter::MoveForward(float Value) { if ((Controller != NULL) && (Value != 0.0f)) { // find out which way is forward const FRotator Rotation = Controller->GetControlRotation(); const FRotator YawRotation(0, Rotation.Yaw, 0); // get forward vector const FVector Direction = FRotationMatrix(YawRotation).GetUnitAxis(EAxis::X); AddMovementInput(Direction, Value); } } void AOpenWorldCharacter::MoveRight(float Value) { if ( (Controller != NULL) && (Value != 0.0f) ) { // find out which way is right const FRotator Rotation = Controller->GetControlRotation(); const FRotator YawRotation(0, Rotation.Yaw, 0); // get right vector const FVector Direction = FRotationMatrix(YawRotation).GetUnitAxis(EAxis::Y); // add movement in that direction AddMovementInput(Direction, Value); } }
[ "k-b0514@hotmail.com" ]
k-b0514@hotmail.com
efad31c9898834a98eb1b26ff247c60c4f288427
38c10c01007624cd2056884f25e0d6ab85442194
/chrome/browser/ui/views/crypto_module_password_dialog_view_unittest.cc
74279192c4f35b8823f2d89cdb7e00b43858ba09
[ "BSD-3-Clause" ]
permissive
zenoalbisser/chromium
6ecf37b6c030c84f1b26282bc4ef95769c62a9b2
e71f21b9b4b9b839f5093301974a45545dad2691
refs/heads/master
2022-12-25T14:23:18.568575
2016-07-14T21:49:52
2016-07-23T08:02:51
63,980,627
0
2
BSD-3-Clause
2022-12-12T12:43:41
2016-07-22T20:14:04
null
UTF-8
C++
false
false
1,674
cc
// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/ui/views/crypto_module_password_dialog_view.h" #include <string> #include "base/bind.h" #include "base/strings/utf_string_conversions.h" #include "chrome/browser/ui/crypto_module_password_dialog.h" #include "testing/gtest/include/gtest/gtest.h" #include "ui/views/controls/textfield/textfield.h" namespace chrome { class CryptoModulePasswordDialogViewTest : public testing::Test { public: CryptoModulePasswordDialogViewTest() {} ~CryptoModulePasswordDialogViewTest() override {} void Capture(const std::string& text) { text_ = text; } void CreateCryptoDialog(const CryptoModulePasswordCallback& callback) { dialog_.reset(new CryptoModulePasswordDialogView("slot", kCryptoModulePasswordKeygen, "server", callback)); } std::string text_; scoped_ptr<CryptoModulePasswordDialogView> dialog_; }; TEST_F(CryptoModulePasswordDialogViewTest, TestAccept) { CryptoModulePasswordCallback cb( base::Bind(&CryptoModulePasswordDialogViewTest::Capture, base::Unretained(this))); CreateCryptoDialog(cb); EXPECT_EQ(dialog_->password_entry_, dialog_->GetInitiallyFocusedView()); EXPECT_TRUE(dialog_->GetModalType() != ui::MODAL_TYPE_NONE); const std::string kPassword = "diAl0g"; dialog_->password_entry_->SetText(base::ASCIIToUTF16(kPassword)); EXPECT_TRUE(dialog_->Accept()); EXPECT_EQ(kPassword, text_); const base::string16 empty; EXPECT_EQ(empty, dialog_->password_entry_->text()); } } // namespace chrome
[ "zeno.albisser@hemispherian.com" ]
zeno.albisser@hemispherian.com
a41438aa7e5b0e5801496fae01a8cc2331fb75f1
10ecd7454a082e341eb60817341efa91d0c7fd0b
/SDK/BP_FishingFish_Islehopper_03_Colour_01_Stone_functions.cpp
f516d392de37b816420c938523919f39fdfdbc70
[]
no_license
Blackstate/Sot-SDK
1dba56354524572894f09ed27d653ae5f367d95b
cd73724ce9b46e3eb5b075c468427aa5040daf45
refs/heads/main
2023-04-10T07:26:10.255489
2021-04-23T01:39:08
2021-04-23T01:39:08
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,024
cpp
// Name: SoT, Version: 2.1.0.1 #include "../SDK.h" /*!!DEFINE!!*/ /*!!HELPER_DEF!!*/ /*!!HELPER_INC!!*/ #ifdef _MSC_VER #pragma pack(push, 0x01) #endif namespace CG { //--------------------------------------------------------------------------- // Functions //--------------------------------------------------------------------------- // Function BP_FishingFish_Islehopper_03_Colour_01_Stone.BP_FishingFish_Islehopper_03_Colour_01_Stone_C.UserConstructionScript // (Event, Public, BlueprintCallable, BlueprintEvent) void ABP_FishingFish_Islehopper_03_Colour_01_Stone_C::UserConstructionScript() { static auto fn = UObject::FindObject<UFunction>("Function BP_FishingFish_Islehopper_03_Colour_01_Stone.BP_FishingFish_Islehopper_03_Colour_01_Stone_C.UserConstructionScript"); ABP_FishingFish_Islehopper_03_Colour_01_Stone_C_UserConstructionScript_Params params; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } } #ifdef _MSC_VER #pragma pack(pop) #endif
[ "ploszjanos9844@gmail.com" ]
ploszjanos9844@gmail.com
4169a75d98dc28687822cdff60c13ee0af72b8a4
c2b161ce52e127f7036882f0ffa523f520dc1c87
/tutorials/playground/convert_test.cpp
ce04c825417272999a0dc8470e61fef5638afc48
[]
no_license
dmosher42/cosmos-core
9991e7268044fa3b139716a48e3bf3c707ea3422
625d1de84eded5ff69b2870a9cbf57c1a6476f89
refs/heads/master
2023-03-21T17:26:05.288081
2021-01-28T00:12:33
2021-01-28T00:12:33
null
0
0
null
null
null
null
UTF-8
C++
false
false
15,472
cpp
/******************************************************************** * Copyright (C) 2015 by Interstel Technologies, Inc. * and Hawaii Space Flight Laboratory. * * This file is part of the COSMOS/core that is the central * module for COSMOS. For more information on COSMOS go to * <http://cosmos-project.com> * * The COSMOS/core software is licenced under the * GNU Lesser General Public License (LGPL) version 3 licence. * * You should have received a copy of the * GNU Lesser General Public License * If not, go to <http://www.gnu.org/licenses/> * * COSMOS/core is free software: you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public License * as published by the Free Software Foundation, either version 3 of * the License, or (at your option) any later version. * * COSMOS/core is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * Refer to the "licences" folder for further information on the * condititons and terms to use this software. ********************************************************************/ #include "mathlib.h" #include "convertlib.h" #include <stdio.h> #include <string.h> //maximum length+1 (for the null terminator) of any function name in the library #define MAX_NAME 15 /*My own little set of file reading functions*/ int openFileLine(FILE **fp, const char filename[], int startLine);//opens a file from 'convert_test_data' for reading and moves the pointer to startLine void skipLines(FILE *fp, int lines);//skips 'lines' many lines, stops at EOF if necessary int main(int argc, char *argv[]) { /*remember to adjust the number of loops in line 18 to match the number of names here*/ char names[][MAX_NAME] = {"rearth","kep2eci","eci2kep"}; //the name of every function being tested, must be IN ORDER! int i, jumpto = -1, skip = -1; //normally we don't jump to or skip anything, so those are initialized out of range. double error, adjerror,avgerror, minerror, maxerror, terror, tminerror, tmaxerror; error = adjerror = avgerror = minerror = maxerror = terror = tminerror = tmaxerror = 0.; i=0; while (argc>1&&i<3) { //If arguments were entered: loop through the names array,... if (strcmp(argv[1], names[i]) == 0) { //and determine if we're to supposed to jump to a specific function,... jumpto = i; printf("\nFunctionality Test:\t%s\n\n", names[i]); break; } else if ((*argv[1] == '-')&&(strcmp(&argv[1][1], names[i]) == 0)) {//or skip a specific function. skip = i; jumpto = 0; printf("\nFunctionality Tests:\tconvertlib (without %s)\n\n", names[i]); break; } i++; } /*Tests can test a single function, or a small group of functions, but must provide error values individually for every function within the test. Each test is contained within a switch case, so they don't interfere with eachother, and can be excluded or run alone.*/ switch (jumpto) { case -1: //Default first line if no arguments were entered printf("\nFunctionality Tests:\tconvertlib\n\n"); case 0: if (skip!=0){ //if skip is the same as this case value, skip this function printf("Function: rearth()\n"); FILE *LATvRdata; if (openFileLine(&LATvRdata, "LATvR.txt", 0)!=0) { i=0; int z = 30; //display one test out of every ___ int numTests; //the number of tests (written at top of file) fscanf(LATvRdata, "%d", &numTests); skipLines(LATvRdata, 2); double lat, rad, maxErrorL, minErrorL, maxErrorR, minErrorR; error = adjerror = avgerror = 0.0; printf("Latitude: \tRadius(function):\tRadius(correct):\t Delta:\n"); printf("(deg)\t(rad) \t(m)\t\t\t(m)\t\t\t (m)\n");//this is very nicely formatted, please don't break it. while (i<numTests&&!feof(LATvRdata)) { fscanf(LATvRdata, "%lf%lf", &lat, &rad); error = rearth(lat) - rad; if (i==0) { minerror = maxerror = error; maxErrorL = minErrorL = lat; maxErrorR = minErrorR = rad; } else if (fabs(error)>fabs(maxerror)) { maxerror = error; maxErrorL = lat; maxErrorR = rad; } else if (fabs(error)<fabs(minerror)) { minerror = error; minErrorL = lat; minErrorR = rad; } avgerror += fabs(error); adjerror = avgerror/rad; if (i%z==0||i==0) { printf("%0.0f \t%0.15f\t%0.9f (-) %0.9f (=) %11.5g\n", DEGOF(lat), lat, rearth(lat), rad, error); } i++; } fclose(LATvRdata); printf("%d tests total. One out of every %d shown.\n",i,z); printf("\n"); adjerror = adjerror/i; avgerror = avgerror/i; printf("Max Error:%0.0f \t%0.15f\t%0.9f (-) %0.9f (=) %11.5g\n", DEGOF(maxErrorL), maxErrorL, rearth(maxErrorL), maxErrorR, maxerror); printf("Min Error:%0.0f \t%0.15f\t%0.9f (-) %0.9f (=) %11.5g\n", DEGOF(minErrorL), minErrorL, rearth(minErrorL), minErrorR, minerror); printf("Average Error:%11.5g\tAdjusted Error:%11.5g\n", avgerror, adjerror); printf("\n"); terror += adjerror; printf("rearth() Error: %11.5g\tTerror:%11.5g\n",adjerror, terror); printf("\n"); } if (jumpto!=-1) break; //this function was jumped to, no other functions need to be tested. } case 1: //this is the first of a group of functions tested together, drop through cases to the actuall test. if (skip!=1) { printf("Function: kep2eci()\n"); if (jumpto!=-1) break; } case 2: if (skip!=2) { printf("Function: eci2kep()\n"); FILE *KeplerData; FILE *ECIData; if ((openFileLine(&KeplerData, "kepler_data.txt", 0)!=0)&&(openFileLine(&ECIData, "eci_data.txt", 2)!=0)) { int numTests; fscanf(KeplerData, "%d", &numTests); skipLines(KeplerData, 2); kepstruc kepcorrect, keptest, Kmaxerror, Kminerror; cartpos eciinput, Emaxerror, Eminerror; int z = 100; //display one test out of every ___ i=0; printf("ECI vector input |#|Kepler element output\n"); while (i<numTests&&(!feof(KeplerData)||!feof(ECIData))) { fscanf(KeplerData, "%lf%lf%lf%lf%lf%lf%lf%lf%lf%lf%lf%lf%lf%lf", &kepcorrect.beta, &kepcorrect.period, &kepcorrect.alat, &kepcorrect.ap, &kepcorrect.ea, &kepcorrect.e, &kepcorrect.h.col[0], &kepcorrect.fa, &kepcorrect.i, &kepcorrect.ma, &kepcorrect.mm, &kepcorrect.raan, &kepcorrect.a, &kepcorrect.ta); kepcorrect.fa -= RADOF(90.); fscanf(ECIData, "%lf%lf%lf%lf%lf%lf%lf%lf%lf", &eciinput.s.col[0], &eciinput.s.col[1], &eciinput.s.col[2], &eciinput.v.col[0], &eciinput.v.col[1], &eciinput.v.col[2], &eciinput.a.col[0], &eciinput.a.col[1], &eciinput.a.col[2]); eciinput.utc = 55927; eci2kep(&eciinput, &keptest); error = fabs(keptest.beta - kepcorrect.beta)+fabs(keptest.period - kepcorrect.period)+fabs(keptest.alat - kepcorrect.alat)+fabs(keptest.ap - kepcorrect.ap)+fabs(keptest.ea - kepcorrect.ea)+fabs(keptest.e - kepcorrect.e)/*+fabs(keptest.h.col[0] - kepcorrect.h.col[0])*/+fabs(keptest.fa - kepcorrect.fa)+fabs(keptest.i - kepcorrect.i)+fabs(keptest.ma - kepcorrect.ma)+fabs(keptest.mm - kepcorrect.mm)+fabs(keptest.raan - kepcorrect.raan)+fabs(keptest.a - kepcorrect.a)+fabs(keptest.ta - kepcorrect.ta); if (i==0) { minerror = maxerror = error; Kmaxerror = Kminerror = kepcorrect; Emaxerror = Eminerror = eciinput; } else if (fabs(error)>fabs(maxerror)) { maxerror = error; Kmaxerror = kepcorrect; Emaxerror = eciinput; } else if (fabs(error)<fabs(minerror)) { minerror = error; Kminerror = kepcorrect; Eminerror = eciinput; } avgerror += fabs(error); if (i%z==0||i==0) { printf("%d______________________________________________________________________________________________________________\n",i); printf("pos x:%11.5g|#| Beta Angle |Period |alat |arg per |E anom |e |flight ang\n",eciinput.s.col[0]); printf(" y:%11.5g|#|function:%11.5g|%11.5g|%11.5g|%11.5g|%11.5g|%11.5g|%11.5g\n",eciinput.s.col[1],keptest.beta,keptest.period,keptest.alat,keptest.ap,keptest.ea,keptest.e,keptest.fa); printf(" z:%11.5g|#| correct:%11.5g|%11.5g|%11.5g|%11.5g|%11.5g|%11.5g|%11.5g\n",eciinput.s.col[2],kepcorrect.beta,kepcorrect.period,kepcorrect.alat,kepcorrect.ap,kepcorrect.ea,kepcorrect.e,kepcorrect.fa); printf("vel x:%11.5g|#| delta:%11.5g|%11.5g|%11.5g|%11.5g|%11.5g|%11.5g|%11.5g\n",eciinput.v.col[0],(keptest.beta-kepcorrect.beta),(keptest.period-kepcorrect.period),(keptest.alat-kepcorrect.alat),(keptest.ap-kepcorrect.ap),(keptest.ea-kepcorrect.ea),(keptest.e-kepcorrect.e),(keptest.fa-kepcorrect.fa)); printf(" y:%11.5g|#| i |mean anom |mean motion|raan |a |true anomaly \n",eciinput.v.col[1]); printf(" z:%11.5g|#|function:%11.5g|%11.5g|%11.5g|%11.5g|%11.5g|%11.5g \n",eciinput.v.col[2],keptest.i,keptest.ma,keptest.mm,keptest.raan,keptest.a,keptest.ta); printf("acc x:%11.5g|#| correct:%11.5g|%11.5g|%11.5g|%11.5g|%11.5g|%11.5g \n",eciinput.a.col[0],kepcorrect.i,kepcorrect.ma,kepcorrect.mm,kepcorrect.raan,kepcorrect.a,kepcorrect.ta); printf(" y:%11.5g|#| delta:%11.5g|%11.5g|%11.5g|%11.5g|%11.5g|%11.5g \n",eciinput.a.col[1],(keptest.i-kepcorrect.i),(keptest.ma-kepcorrect.ma),(keptest.mm-kepcorrect.mm),(keptest.raan-kepcorrect.raan),(keptest.a-kepcorrect.a),(keptest.ta-kepcorrect.ta)); printf(" z:%11.5g|#|\n",eciinput.a.col[2]); } i++; } printf("________________________________________________________________________________________________________________\n"); fclose(KeplerData); fclose(ECIData); printf("\n%d tests total, one out of every %d shown.\n",i,z); avgerror = avgerror/i; printf("\nMaximum Error:__________________________________________________________________________________________\n"); eci2kep(&Emaxerror, &keptest); printf("pos x:%11.5g|#| Beta Angle |Period |alat |arg per |E anom |e |flight ang\n",Emaxerror.s.col[0]); printf(" y:%11.5g|#|function:%11.5g|%11.5g|%11.5g|%11.5g|%11.5g|%11.5g|%11.5g\n",Emaxerror.s.col[1],keptest.beta,keptest.period,keptest.alat,keptest.ap,keptest.ea,keptest.e,keptest.fa); printf(" z:%11.5g|#| correct:%11.5g|%11.5g|%11.5g|%11.5g|%11.5g|%11.5g|%11.5g\n",Emaxerror.s.col[2],Kmaxerror.beta,Kmaxerror.period,Kmaxerror.alat,Kmaxerror.ap,Kmaxerror.ea,Kmaxerror.e,Kmaxerror.fa); printf("vel x:%11.5g|#| delta:%11.5g|%11.5g|%11.5g|%11.5g|%11.5g|%11.5g|%11.5g\n",Emaxerror.v.col[0],(keptest.beta-Kmaxerror.beta),(keptest.period-Kmaxerror.period),(keptest.alat-Kmaxerror.alat),(keptest.ap-Kmaxerror.ap),(keptest.ea-Kmaxerror.ea),(keptest.e-Kmaxerror.e),(keptest.fa-Kmaxerror.fa)); printf(" y:%11.5g|#| i |mean anom |mean motion|raan |a |true anomaly \n",Emaxerror.v.col[1]); printf(" z:%11.5g|#|function:%11.5g|%11.5g|%11.5g|%11.5g|%11.5g|%11.5g \n",Emaxerror.v.col[2],keptest.i,keptest.ma,keptest.mm,keptest.raan,keptest.a,keptest.ta); printf("acc x:%11.5g|#| correct:%11.5g|%11.5g|%11.5g|%11.5g|%11.5g|%11.5g \n",Emaxerror.a.col[0],Kmaxerror.i,Kmaxerror.ma,Kmaxerror.mm,Kmaxerror.raan,Kmaxerror.a,Kmaxerror.ta); printf(" y:%11.5g|#| delta:%11.5g|%11.5g|%11.5g|%11.5g|%11.5g|%11.5g \n",Emaxerror.a.col[1],(keptest.i-Kmaxerror.i),(keptest.ma-Kmaxerror.ma),(keptest.mm-Kmaxerror.mm),(keptest.raan-Kmaxerror.raan),(keptest.a-Kmaxerror.a),(keptest.ta-Kmaxerror.ta)); printf(" z:%11.5g|#|\n",Emaxerror.a.col[2]); printf("\nMinimum Error:__________________________________________________________________________________________\n"); eci2kep(&Eminerror, &keptest); printf("pos x:%11.5g|#| Beta Angle |Period |alat |arg per |E anom |e |flight ang\n",Eminerror.s.col[0]); printf(" y:%11.5g|#|function:%11.5g|%11.5g|%11.5g|%11.5g|%11.5g|%11.5g|%11.5g\n",Eminerror.s.col[1],keptest.beta,keptest.period,keptest.alat,keptest.ap,keptest.ea,keptest.e,keptest.fa); printf(" z:%11.5g|#| correct:%11.5g|%11.5g|%11.5g|%11.5g|%11.5g|%11.5g|%11.5g\n",Eminerror.s.col[2],Kminerror.beta,Kminerror.period,Kminerror.alat,Kminerror.ap,Kminerror.ea,Kminerror.e,Kminerror.fa); printf("vel x:%11.5g|#| delta:%11.5g|%11.5g|%11.5g|%11.5g|%11.5g|%11.5g|%11.5g\n",Eminerror.v.col[0],(keptest.beta-Kminerror.beta),(keptest.period-Kminerror.period),(keptest.alat-Kminerror.alat),(keptest.ap-Kminerror.ap),(keptest.ea-Kminerror.ea),(keptest.e-Kminerror.e),(keptest.fa-Kminerror.fa)); printf(" y:%11.5g|#| i |mean anom |mean motion|raan |a |true anomaly \n",Eminerror.v.col[1]); printf(" z:%11.5g|#|function:%11.5g|%11.5g|%11.5g|%11.5g|%11.5g|%11.5g \n",Eminerror.v.col[2],keptest.i,keptest.ma,keptest.mm,keptest.raan,keptest.a,keptest.ta); printf("acc x:%11.5g|#| correct:%11.5g|%11.5g|%11.5g|%11.5g|%11.5g|%11.5g \n",Eminerror.a.col[0],Kminerror.i,Kminerror.ma,Kminerror.mm,Kminerror.raan,Kminerror.a,Kminerror.ta); printf(" y:%11.5g|#| delta:%11.5g|%11.5g|%11.5g|%11.5g|%11.5g|%11.5g \n",Eminerror.a.col[1],(keptest.i-Kminerror.i),(keptest.ma-Kminerror.ma),(keptest.mm-Kminerror.mm),(keptest.raan-Kminerror.raan),(keptest.a-Kminerror.a),(keptest.ta-Kminerror.ta)); printf(" z:%11.5g|#|\n",Eminerror.a.col[2]); } if (jumpto!=-1) break; } default: printf("\nconvertlib total error"); if (skip!=-1) printf(" (without %s)",names[skip]); //indicate whether any function was skipped. printf(":\t%11.5g\n",terror); //final error stats for entire library. } } int openFileLine(FILE **fp, const char filename[], int startLine) { char filePath[40] = {"convert_test_data/"};//the folder containing the test files *fp = fopen(strcat(filePath, filename), "r"); //open the file if (fp == NULL) { //print error message if necessary. printf("\n\tError opening necessary data file!!!\n"); printf("Please check that the text file '%s' exists and\n", filename); printf("is in the directory titled 'convert_test_data'.\n\n"); return(0); //return 0 for failure.... } skipLines(*fp, startLine); //move the pointer to startLine return(1); //return 1 for sucess!!!! } void skipLines(FILE *fp, int lines) { char c; for (lines; lines>0; lines--) { //skip 'lines' many lines c=0; do { //scan through file untill the end of a line is reached c = fgetc(fp); if (c==EOF) return; //We've gone too far!!! } while(c!='\n'); } }
[ "pilger@hsfl.hawaii.edu" ]
pilger@hsfl.hawaii.edu
cba1292722f345ddde3d202149cb2a2ebb0e0716
6fa5433c3a3c5fbc74b7242a2d0160b212bcd847
/多进程/copyProgress/main.cpp
a63311c90d51010b532c124edcf78f7a98545b7b
[]
no_license
arafatms/Linux-Resource-manager
8c5165e1a1f27ab13c1477fe58f1ec021dd463d3
9f4a5b0482c207b402c51d4333fb1ffecd1ca158
refs/heads/master
2021-06-06T21:01:15.379886
2018-08-25T12:07:41
2018-08-25T12:07:41
146,092,096
1
0
null
null
null
null
UTF-8
C++
false
false
2,190
cpp
#include "mainwindow.h" #include <QApplication> #include "sem_shm.h" int main(int argc, char *argv[]) { using namespace std; QApplication a(argc, argv); MainWindow w; w.show(); struct sembuf sops; int ret, status; semun arg; int shmid = shmget(MY_KEY, sizeof(BUFF_T), IPC_CREAT | 0666); //0666表示:创建者和其他用户创建的进程都可以进行读和写操作, 4为只读 if(-1 == shmid){ cout << "shmget () error !" << endl; return 0; } //失败返回-1, 成功返回指向共享内存第一个字节的指针。 BUFF_T* sMem = (BUFF_T *)shmat(shmid, NULL, SHM_R | SHM_W); // NULL表示让系统自动分配内存地址 if((void *)-1 == sMem){ cout << "shmid () error !" << endl; return 0; } cout << "main :共享内存连接地址: " << (int*)sMem << endl ; semid = semget(888, 2, IPC_CREAT|0600); // 创建信号灯,自动,2个,不存在则创建。成功返回信号灯集ID,失败返回-1 if (semid == -1) { cout << "create sem failed!" << endl; return -1; } //对信号灯 赋初值1 (1表示占用) arg.val = 8; ret = semctl(semid, 0, SETVAL, arg); if (ret == -1) cout << "semctl failed!" << endl; arg.val = 0; ret = semctl(semid, 1, SETVAL, arg); if (ret == -1) cout << "semctl failed!" << endl; pid_t pw, pr; pr = fork(); //创建进程 if(!pr){ //读进程 char *a[]={NULL}; execv("//home/ezio/os-keshe/1/build-Read-Desktop_Qt_5_10_1_GCC_64bit-Debug/Read", a); } else{ pw = fork(); if(!pw){ //写进程 char *a[]={NULL}; execv("//home/ezio/os-keshe/1/build-Write-Desktop_Qt_5_10_1_GCC_64bit-Debug/Write", a); } else{ //主进程 //删除信号灯,删除共享内存 } } return a.exec(); }
[ "arafatms@outlook.com" ]
arafatms@outlook.com
724e67fc4575acf98d2e9dc38a75c5cccda53f0a
823d02e7c97162bb6a129fa902bc5d53a6cf5de7
/Utils/CodeLib.1/Cabs/CabView/OS.H
b6fe8d2c7747f62e7751fd1140767639df620dc8
[ "MIT" ]
permissive
starpeace-project/starpeace-original
c14d855253d20352b33c9663ce02d833a6f1eb39
74e773b88eedf3d089a6cf01b70b01a6ade4cd03
refs/heads/master
2023-09-01T10:47:45.382288
2021-09-20T17:24:49
2021-09-20T17:24:49
104,656,682
4
1
null
2021-09-20T17:24:51
2017-09-24T15:54:58
Pascal
UTF-8
C++
false
false
574
h
//******************************************************************************************* // // Filename : Os.h // // CFileTime // // Copyright (c) 1994 - 1996 Microsoft Corporation. All rights reserved // //******************************************************************************************* #ifndef _OS_H_ #define _OS_H_ class CFileTime { public: CFileTime() {} ~CFileTime() {} static void DateTimeToString(WORD wDate, WORD wTime, LPSTR pszText); private: static void FileTimeToDateTimeString(LPFILETIME lpft, LPSTR pszText); } ; #endif // _OS_H_
[ "ron.appleton@gmail.com" ]
ron.appleton@gmail.com
57fc92602408f926d3685148e6401a4444d6ca0e
603742c3a80dc337875e2d92c8b488cc9983349c
/Aplicacion/Nodo3.h
328c2bdafef1b97ffb33585ed21390aa8b0c8ebc
[ "MIT" ]
permissive
oigresagetro/EDYAA_TP1
c747963ccfc40697c57ba51fae5dbc8f06f59d2c
0f0b18ba1e705cec44c474c0debc0abc20106b14
refs/heads/master
2021-07-09T00:00:53.473933
2017-10-06T02:53:43
2017-10-06T02:53:43
104,901,752
0
0
null
null
null
null
UTF-8
C++
false
false
268
h
#ifndef _Nodo3 #define _Nodo3 #include <iostream> using namespace std; struct Nodo3{ public: char c; Nodo3 * hijoMasI; Nodo3 * hermanoD; // o padre; Nodo3 * ptrPadre; Nodo3 * hermanoI; Nodo3(char); ~Nodo3(); //bool operator==(const Nodo2&); }; #endif
[ "31581117+oigresagetro@users.noreply.github.com" ]
31581117+oigresagetro@users.noreply.github.com
2f149104a77ddcebb1bdb4701914a74358fadc24
b11b2b488d94ae20f58cfe40bae0987c32b5945e
/butaneVerification/1e-06/UPrime2Mean
0af575ac3984a6805ac9372b18da15f19c9740ee
[]
no_license
jamesjguthrie/mayerTestCase
93dbd9230e16a0f061cec97c7ddf6cb5303e1c95
9279ad56b62efa1507ff8b1bcd96e3ce2daceb56
refs/heads/master
2021-03-30T18:20:33.641846
2019-06-25T12:55:07
2019-06-25T12:55:07
26,530,210
0
0
null
null
null
null
UTF-8
C++
false
false
1,072
/*--------------------------------*- C++ -*----------------------------------*\ | ========= | | | \\ / F ield | OpenFOAM: The Open Source CFD Toolbox | | \\ / O peration | Version: 2.4.0 | | \\ / A nd | Web: www.OpenFOAM.org | | \\/ M anipulation | | \*---------------------------------------------------------------------------*/ FoamFile { version 2.0; format ascii; class volSymmTensorField; location "1e-06"; object UPrime2Mean; } // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // dimensions [0 2 -2 0 0 0 0]; internalField uniform (0 0 0 0 0 0); boundaryField { upperWall { type calculated; value uniform (0 0 0 0 0 0); } } // ************************************************************************* //
[ "james@heyjimmy.net" ]
james@heyjimmy.net
6327d464fdbd31b4a552fc7c3c20a3307343333c
c2b6bd54bef3c30e53c846e9cf57f1e44f8410df
/Temp/il2cppOutput/il2cppOutput/mscorlib_System_Collections_ObjectModel_ReadOnlyCo1676177880.h
4084538807cb6d333daf9ddfa6f2bc0e7508854b
[]
no_license
PriyeshWani/CrashReproduce-5.4p1
549a1f75c848bf9513b2f966f2f500ee6c75ba42
03dd84f7f990317fb9026cbcc3873bc110b1051e
refs/heads/master
2021-01-11T12:04:21.140491
2017-01-24T14:01:29
2017-01-24T14:01:29
79,388,416
0
0
null
null
null
null
UTF-8
C++
false
false
1,177
h
#pragma once #include "il2cpp-config.h" #ifndef _MSC_VER # include <alloca.h> #else # include <malloc.h> #endif #include <stdint.h> #include "mscorlib_System_Object2689449295.h" // System.Collections.Generic.IList`1<UnityEngine.UI.Selectable> struct IList_1_t2031332789; #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // System.Collections.ObjectModel.ReadOnlyCollection`1<UnityEngine.UI.Selectable> struct ReadOnlyCollection_1_t1676177880 : public Il2CppObject { public: // System.Collections.Generic.IList`1<T> System.Collections.ObjectModel.ReadOnlyCollection`1::list Il2CppObject* ___list_0; public: inline static int32_t get_offset_of_list_0() { return static_cast<int32_t>(offsetof(ReadOnlyCollection_1_t1676177880, ___list_0)); } inline Il2CppObject* get_list_0() const { return ___list_0; } inline Il2CppObject** get_address_of_list_0() { return &___list_0; } inline void set_list_0(Il2CppObject* value) { ___list_0 = value; Il2CppCodeGenWriteBarrier(&___list_0, value); } }; #ifdef __clang__ #pragma clang diagnostic pop #endif
[ "priyeshwani@gmail.com" ]
priyeshwani@gmail.com
c9db5511b866f14f8b7725eceb15d9265d5f6218
f53cf175a3fff8250f813c37922d737fb1648b36
/IDE/include/tv/win32/key.h
784facc06ec3f068fed7d85e843f5b9e678a3f4e
[ "MIT" ]
permissive
paule32/forth2asm
fbbe8e83a091dff62c021e73a2a6b69737645861
b1208581cd94017f8207b4b3bff28f0bce81ff7e
refs/heads/master
2020-09-20T15:08:48.218929
2019-12-27T16:29:15
2019-12-27T16:29:15
224,518,576
0
1
MIT
2019-12-09T00:18:34
2019-11-27T21:18:40
C++
UTF-8
C++
false
false
2,001
h
/* Win32 screen routines header. Copyright (c) 2002 by Salvador E. Tropea (SET) Covered by the GPL license. */ // This headers needs windows header #if defined(TVOS_Win32) && !defined(WIN32KEY_HEADER_INCLUDED) #define WIN32KEY_HEADER_INCLUDED struct TEvent; const unsigned eventKeyboardQSize=16; // A class to encapsulate the globals, all is static! class TGKeyWin32 : public TGKey { public: TGKeyWin32() {}; // Function replacements //static void Suspend(); //static void Resume(); static int KbHit(); //static void Clear(); //static ushort GKey(); static unsigned GetShiftState(); static void FillTEvent(TEvent &e); //static void SetKbdMapping(int version); // Setup the pointers to point our members static void Init(); static void DeInit(); protected: // For this driver // Extract the shift state from the event (also used by the mouse class) static void ProcessControlKeyState(INPUT_RECORD *ir); // Translate Win32 shift state values to TV equivalents static ushort transShiftState(DWORD state); // Translate Win32 key events to TV equivalents static int transKeyEvent(KeyDownEvent &dst, KEY_EVENT_RECORD& src); // Add a key to the queue static void putConsoleKeyboardEvent(KeyDownEvent &key); // Remove a key event from the queue static int getConsoleKeyboardEvent(KeyDownEvent &key); // Process a Win32 key event and put it in the queue static void HandleKeyEvent(); // Last value recieved for the shift modifiers static ushort LastControlKeyState; // Table used to Translate keyboard events static const char KeyTo[256]; // Table for ASCII printable values static const char testChars[]; // Queue static KeyDownEvent *evKeyboardIn; static KeyDownEvent *evKeyboardOut; static KeyDownEvent evKeyboardQueue[eventKeyboardQSize]; static unsigned evKeyboardLength; static CRITICAL_SECTION lockKeyboard; friend class THWMouseWin32; friend class TScreenWin32; }; #endif // WIN32KEY_HEADER_INCLUDED
[ "admin@dbase.center" ]
admin@dbase.center
d2b1482e37b794a57e30898177f0a745146e3029
c26dc7928b1facac2c0912f6532076d35c19e835
/devel/include/ros_arduino_msgs/Analog.h
b74669547528ba3c083bac79d4d00106d139c939
[]
no_license
mattedminster/inmoov_ros
33c29a2ea711f61f15ad5e2c53dd9db65ef6437f
e063a90b61418c3612b8df7876a633bc0dc2c428
refs/heads/master
2021-01-23T02:39:36.090746
2017-08-09T02:56:42
2017-08-09T02:56:42
85,995,826
0
0
null
2017-03-23T20:45:32
2017-03-23T20:45:32
null
UTF-8
C++
false
false
5,960
h
// Generated by gencpp from file ros_arduino_msgs/Analog.msg // DO NOT EDIT! #ifndef ROS_ARDUINO_MSGS_MESSAGE_ANALOG_H #define ROS_ARDUINO_MSGS_MESSAGE_ANALOG_H #include <string> #include <vector> #include <map> #include <ros/types.h> #include <ros/serialization.h> #include <ros/builtin_message_traits.h> #include <ros/message_operations.h> #include <std_msgs/Header.h> namespace ros_arduino_msgs { template <class ContainerAllocator> struct Analog_ { typedef Analog_<ContainerAllocator> Type; Analog_() : header() , value(0) { } Analog_(const ContainerAllocator& _alloc) : header(_alloc) , value(0) { (void)_alloc; } typedef ::std_msgs::Header_<ContainerAllocator> _header_type; _header_type header; typedef uint16_t _value_type; _value_type value; typedef boost::shared_ptr< ::ros_arduino_msgs::Analog_<ContainerAllocator> > Ptr; typedef boost::shared_ptr< ::ros_arduino_msgs::Analog_<ContainerAllocator> const> ConstPtr; }; // struct Analog_ typedef ::ros_arduino_msgs::Analog_<std::allocator<void> > Analog; typedef boost::shared_ptr< ::ros_arduino_msgs::Analog > AnalogPtr; typedef boost::shared_ptr< ::ros_arduino_msgs::Analog const> AnalogConstPtr; // constants requiring out of line definition template<typename ContainerAllocator> std::ostream& operator<<(std::ostream& s, const ::ros_arduino_msgs::Analog_<ContainerAllocator> & v) { ros::message_operations::Printer< ::ros_arduino_msgs::Analog_<ContainerAllocator> >::stream(s, "", v); return s; } } // namespace ros_arduino_msgs namespace ros { namespace message_traits { // BOOLTRAITS {'IsFixedSize': False, 'IsMessage': True, 'HasHeader': True} // {'std_msgs': ['/opt/ros/kinetic/share/std_msgs/cmake/../msg'], 'ros_arduino_msgs': ['/home/robot/inmoov_ros/src/ros_arduino_bridge/ros_arduino_msgs/msg']} // !!!!!!!!!!! ['__class__', '__delattr__', '__dict__', '__doc__', '__eq__', '__format__', '__getattribute__', '__hash__', '__init__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', '_parsed_fields', 'constants', 'fields', 'full_name', 'has_header', 'header_present', 'names', 'package', 'parsed_fields', 'short_name', 'text', 'types'] template <class ContainerAllocator> struct IsFixedSize< ::ros_arduino_msgs::Analog_<ContainerAllocator> > : FalseType { }; template <class ContainerAllocator> struct IsFixedSize< ::ros_arduino_msgs::Analog_<ContainerAllocator> const> : FalseType { }; template <class ContainerAllocator> struct IsMessage< ::ros_arduino_msgs::Analog_<ContainerAllocator> > : TrueType { }; template <class ContainerAllocator> struct IsMessage< ::ros_arduino_msgs::Analog_<ContainerAllocator> const> : TrueType { }; template <class ContainerAllocator> struct HasHeader< ::ros_arduino_msgs::Analog_<ContainerAllocator> > : TrueType { }; template <class ContainerAllocator> struct HasHeader< ::ros_arduino_msgs::Analog_<ContainerAllocator> const> : TrueType { }; template<class ContainerAllocator> struct MD5Sum< ::ros_arduino_msgs::Analog_<ContainerAllocator> > { static const char* value() { return "5760aa9c40c2caa52a04d293094e679d"; } static const char* value(const ::ros_arduino_msgs::Analog_<ContainerAllocator>&) { return value(); } static const uint64_t static_value1 = 0x5760aa9c40c2caa5ULL; static const uint64_t static_value2 = 0x2a04d293094e679dULL; }; template<class ContainerAllocator> struct DataType< ::ros_arduino_msgs::Analog_<ContainerAllocator> > { static const char* value() { return "ros_arduino_msgs/Analog"; } static const char* value(const ::ros_arduino_msgs::Analog_<ContainerAllocator>&) { return value(); } }; template<class ContainerAllocator> struct Definition< ::ros_arduino_msgs::Analog_<ContainerAllocator> > { static const char* value() { return "# Reading from a single analog IO pin.\n\ Header header\n\ uint16 value\n\ \n\ ================================================================================\n\ MSG: std_msgs/Header\n\ # Standard metadata for higher-level stamped data types.\n\ # This is generally used to communicate timestamped data \n\ # in a particular coordinate frame.\n\ # \n\ # sequence ID: consecutively increasing ID \n\ uint32 seq\n\ #Two-integer timestamp that is expressed as:\n\ # * stamp.sec: seconds (stamp_secs) since epoch (in Python the variable is called 'secs')\n\ # * stamp.nsec: nanoseconds since stamp_secs (in Python the variable is called 'nsecs')\n\ # time-handling sugar is provided by the client library\n\ time stamp\n\ #Frame this data is associated with\n\ # 0: no frame\n\ # 1: global frame\n\ string frame_id\n\ "; } static const char* value(const ::ros_arduino_msgs::Analog_<ContainerAllocator>&) { return value(); } }; } // namespace message_traits } // namespace ros namespace ros { namespace serialization { template<class ContainerAllocator> struct Serializer< ::ros_arduino_msgs::Analog_<ContainerAllocator> > { template<typename Stream, typename T> inline static void allInOne(Stream& stream, T m) { stream.next(m.header); stream.next(m.value); } ROS_DECLARE_ALLINONE_SERIALIZER }; // struct Analog_ } // namespace serialization } // namespace ros namespace ros { namespace message_operations { template<class ContainerAllocator> struct Printer< ::ros_arduino_msgs::Analog_<ContainerAllocator> > { template<typename Stream> static void stream(Stream& s, const std::string& indent, const ::ros_arduino_msgs::Analog_<ContainerAllocator>& v) { s << indent << "header: "; s << std::endl; Printer< ::std_msgs::Header_<ContainerAllocator> >::stream(s, indent + " ", v.header); s << indent << "value: "; Printer<uint16_t>::stream(s, indent + " ", v.value); } }; } // namespace message_operations } // namespace ros #endif // ROS_ARDUINO_MSGS_MESSAGE_ANALOG_H
[ "mattedminster@gmail.com" ]
mattedminster@gmail.com
298575b1069692f56cc6281240fe4ceeb0a090dd
ba916d93dfb8074241b0ea1f39997cb028509240
/cpp/sorting.cpp
a8664377c0dbaa46b0d0a6aacab753a39917391b
[]
no_license
satojkovic/algorithms
ecc1589898c61d2eef562093d3d2a9a2d127faa8
f666b215bc9bbdab2d2257c83ff1ee2c31c6ff8e
refs/heads/master
2023-09-06T08:17:08.712555
2023-08-31T14:19:01
2023-08-31T14:19:01
169,414,662
2
3
null
null
null
null
UTF-8
C++
false
false
628
cpp
#include <bits/stdc++.h> typedef long long ll; using namespace std; void print(const vector<int> &data) { for (int i = 0; i < data.size(); ++i) { cout << data[i]; if (i == data.size() - 1) cout << endl; else cout << ","; } } void partition(vector<int> &data, int l, int r) { int m = l; for (int i = l + 1; i <= r; ++i) { if (data[i] < data[l]) swap(data[i], data[++m]); } swap(data[l], data[m]); } int main() { vector<int> data{55, 41, 59, 26, 53, 58, 97, 93}; partition(data, 0, data.size() - 1); print(data); }
[ "satojkovic@gmail.com" ]
satojkovic@gmail.com
c7e4f7f2b84bad1bf29e4c9bc878ecf73944d3e5
0203c18e12531e00ef5154776cb32b731e6688d0
/PBINFO/284-interclsare3.cpp
b27d8ebe7b6b90d1cfa8a46b3161822dc6b56ec7
[]
no_license
KiraBeleaua/Solved-Problems
a656566e4592f206365a11cff670139baa27c80a
99a2343883faa9e0d61d8a92b8e82f9a0d89c2c2
refs/heads/main
2023-06-20T23:10:18.496603
2021-07-15T22:50:56
2021-07-15T22:50:56
359,094,167
0
0
null
null
null
null
UTF-8
C++
false
false
4,598
cpp
#include <iostream> #include <vector> #include <math.h> #include <algorithm> #include <iomanip> #include <array> #include <fstream> using namespace std; void printVector(vector<int64_t> v) { for (auto& el : v) { cout << el << " "; } cout << "\n"; } int maximAdi(vector<int64_t> v) { int64_t maxim = v[0], indice = 0; for (int i = 0; i < v.size() - 1; i++) { if (v[i] < v[i + 1] && maxim < v[i + 1]) { maxim = v[i + 1]; indice = i + 1; } else if (v[i] > v[i + 1] && maxim < v[i]) { maxim = v[i]; indice = i; } } return maxim; } int maxim(vector<int64_t> v) { int64_t m = v[0]; for (auto el : v) { m = max(el, m); } return m; } vector<int64_t> generateRandomVector(int64_t n, int64_t left, int64_t right) { srand(time(NULL)); int64_t space = right - left; vector <int64_t> v; for (int i = 0; i < n; i++) { int64_t el = rand() % space + left; v.push_back(el); } return v; } int64_t maxVector(vector<int64_t> a) { int64_t m = a[0]; for (int i = 1; i < a.size(); i++) { m = max(a[i], m); } return m; } int64_t maximIndiceVector(vector<int64_t> a) { int64_t m = a[0]; int indice = 0; for (int i = 1; i < a.size(); i++) { if (a[i] > m) { m = a[i]; indice = i; } } return indice; } int gcd(int a, int b) { return b ? gcd(b, a % b) : a; } int strlen(char v[]) { int size = 0; for (int i = 0; true; i++) { if (v[i] == '\0') { size = i; break; } } return size; } void strcpy(char v[], char w[]) { for (int i = 0; true; i++) { if (w[i] == '\0') { break; } v[i] = w[i]; } return; } int strcmp(char v[], char w[]) { int result = 0; for (int i = 0; true; i++) { if (v[i] > w[i]) { result++; break; } else if (w[i] > v[i]) { result--; break; } if (v[i] == '\0' || w[i] == '\0') { break; } } return result; } //refa ,de gasit tot w in v; return partea de unde incepe; int strstr(char v[], char w[]) { int indice = 0; for (int i = 0; strlen(v); i++) { for (int j = 0; true; j++) { if (w[j] == '\0') { break; } if (w[j] == v[i]) { indice = i; } } } return indice; } int strchr(char v[], char x) { int indice = 0; for (int i = 0; strlen(v); i++) { if (v[i] == x) { indice = i; break; } } return indice; } void strlower(char v[]) { for (int i = 0; strlen(v); i++) { if (v[i] == '\0') { break; } if (v[i] <= 'Z' && v[i] >= 'A') { v[i] += 'a' - 'A'; } } return; } void strupper(char v[]) { for (int i = 0; i < strlen(v); i++) { if (v[i] >= 'z' && v[i] <= 'a') { v[i] -= 'a' - 'A'; } } return; } int findstr(char v[], char w[]) { int64_t indice = -1, k = 0, lenv = 0, lenw = 0; lenv = strlen(v); lenw = strlen(w); for (int i = 0; i < lenv; i++) { k = 0; for (int j = 0; j < lenw; j++) { if (v[i + j] != w[j]) break; k++; } if (k == lenw) { indice = i; break; } } return indice; } int main() { ifstream fin("interclasare3.in"); ofstream fout("interclasare3.out"); int64_t n, m, i = 0, j = 0; vector <int64_t> v, w, e; fin >> n; fin >> m; v.resize(n); w.resize(m); for (auto& el : v) { fin >> el; } for (auto& el : w) { fin >> el; } j = w.size() - 1; while (i < v.size() && j >= 0) { if (v[i] >= w[j]) { if (w[j] % 2 == 0) { e.push_back(w[j]); } j--; } else if (v[i] < w[j]) { if (v[i] % 2 == 0) { e.push_back(v[i]); } i++; } } for (; i < v.size(); i++) { if (v[i] % 2 == 0) { e.push_back(v[i]); } } for (; j >= 0 ; j--) { if (w[j] % 2 == 0) { e.push_back(w[j]); } } for (int i = 0; i < e.size(); i++) { fout << e[i] << " "; if (i % 20 == 19 && i != 0) { fout << "\n"; } } }
[ "necula.adrian2009@gmail.com" ]
necula.adrian2009@gmail.com
4fcea0611b188c7f3a5e285323bb94afd8f50b3d
4c3068dd69156650a7e8042771fab4408794d653
/2.28/A1086 Tree Traversals Again.cpp
4b4009e21848e140583d10425fe5237cae63366e
[]
no_license
GXMhahahaha/PAT
396d4cae43fa4c51ad7aecc35e9c3482a06902e1
891061921a1b45e3e3ee49731b2206a54f1eb1fb
refs/heads/master
2023-07-08T19:06:37.482228
2021-08-05T03:21:47
2021-08-05T03:21:47
392,892,525
0
0
null
null
null
null
UTF-8
C++
false
false
1,275
cpp
//A1086 Tree Traversals Again #include <iostream> #include <stdio.h> #include <stack> #include <string.h> using namespace std; const int maxn = 50; int N; int pre[maxn]; int in[maxn]; stack<int> s; struct Node{ int key; Node* left; Node* right; }; Node* Build(int preL,int preR,int inL,int inR){ if(preL>preR || inL>inR){ return NULL; } Node* root = (Node*)malloc(sizeof(Node)*1); int Key = pre[preL]; root->key = Key; int pos = -1; for(int i=inL;i<=inR;i++){ if(in[i] == Key){ pos = i; break; } } int numL = pos - inL; int numR = inR - pos; root->left = Build(preL+1,preL+numL,inL,pos-1); root->right = Build(preR-numR+1,preR,pos+1,inR); return root; } int cal = 0; void PostOrder(Node* root){ if(root == NULL) return; PostOrder(root->left); PostOrder(root->right); printf("%d",root->key); cal++; if(cal<N){ printf(" "); } } int main(){ cin>>N; int num=0; int i=0,j=0; while(1){ char inst[5]; scanf("%s",inst); if(strcmp(inst,"Push")==0){ int key; scanf("%d",&key); s.push(key); pre[i++] = key; num++; } else{ int key = s.top(); in[j++] = key; s.pop(); } if(num==N && s.empty()){ break; } } Node* root = Build(0,i-1,0,j-1); PostOrder(root); printf("\n"); return 0; }
[ "1844720947@qq.com" ]
1844720947@qq.com
db9ac4af91f2cf8669b9470099df81d264c7f0cb
2588ad590b4df910fa5477ee84101b56dba69144
/MyTree/MyTree/TreeOperation.cpp
8124f26032e718494a2647cf3d40d93cc7c2a4e6
[]
no_license
Mr-Jason-Sam/Algorithms
e6829cf55addb7a01c425f8f8c732dce1082901c
6f015cc63407cda1aae310aefd3b705fcc00a361
refs/heads/master
2021-01-19T10:53:22.400040
2019-05-23T17:06:42
2019-05-23T17:06:42
87,910,106
0
1
null
null
null
null
UTF-8
C++
false
false
168
cpp
// // TreeOperation.cpp // MyTree // // Created by Jason_Sam on 2017/4/6. // Copyright © 2017年 Jason_Sam. All rights reserved. // #include "TreeOperation.hpp"
[ "Mr.Jason_Sam@iCloud.com" ]
Mr.Jason_Sam@iCloud.com
ed6c0ccee6dd44e5b7e6318621076a29b5731f7b
e3d7d6ddd33d0e0886199af66a281b83b4903d91
/C++02096.cpp
ec1978bfc5a5182bd69b6ca2066bc33b5de16bdb
[]
no_license
flydog98/CppBaekjoon
6c1805222c6669b0793d23cf64902677628c0ddb
6b218c371d39a2ccf1f2922b6fc4275c91c2bafb
refs/heads/master
2020-09-05T13:13:48.343902
2020-08-26T14:25:18
2020-08-26T14:25:18
220,116,434
0
0
null
null
null
null
UHC
C++
false
false
1,332
cpp
// 2096번 내려가기 #include <iostream> #include <algorithm> #include <vector> using namespace std; int main(void) { int amount = 0; vector<vector<int>> map; int higha = 0, highb = 0, highc = 0; int lowa = 0, lowb = 0, lowc = 0; int new_higha = 0, new_highb = 0, new_highc = 0; int new_lowa = 0, new_lowb = 0, new_lowc = 0; ios_base::sync_with_stdio(false); cin.tie(NULL); cout.tie(NULL); cin >> amount; for (int i = 0; i < 3; i++) { vector<int> temp; map.push_back(temp); } for (int i = 0; i < amount; i++) { for (int j = 0; j < 3; j++) { int temp; cin >> temp; map[j].push_back(temp); } } higha = map[0][0]; highb = map[1][0]; highc = map[2][0]; lowa = map[0][0]; lowb = map[1][0]; lowc = map[2][0]; for (int i = 1; i < amount; i++) { new_higha = map[0][i] + max(higha, highb); new_highb = map[1][i] + max(highc, max(higha, highb)); new_highc = map[2][i] + max(highc, highb); higha = new_higha; highb = new_highb; highc = new_highc; new_lowa = map[0][i] + min(lowa, lowb); new_lowb = map[1][i] + min(lowc, min(lowa, lowb)); new_lowc = map[2][i] + min(lowc, lowb); lowa = new_lowa; lowb = new_lowb; lowc = new_lowc; } int ans1 = max(max(higha, highb), highc); int ans2 = min(min(lowa, lowb), lowc); cout << ans1 << ' ' << ans2 << '\n'; return 0; }
[ "pyjpyj0825@gmail.com" ]
pyjpyj0825@gmail.com
93900d034516b9093ad1129fc63919ce288df7f6
e9a8f00bce09954668fb3f84382bc29397c78965
/src/rpcprotocol.cpp
5ede4ac80aa5320d4926d2f51d7a209dc87fe983
[ "MIT" ]
permissive
SkullCash/SkullCash
4b7dec25759d9012abfae0f678bcaed982a2d49f
7d8d87b4a6a24e9768d667b45e31d51e5cea1cd1
refs/heads/master
2020-03-23T04:51:38.559112
2018-07-16T08:30:12
2018-07-16T08:30:12
141,109,595
0
0
null
null
null
null
UTF-8
C++
false
false
9,661
cpp
// Copyright (c) 2010 Satoshi Nakamoto // Copyright (c) 2009-2013 The Bitcoin developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "rpcprotocol.h" #include "util.h" #include <stdint.h> #include <boost/algorithm/string.hpp> #include <boost/asio.hpp> #include <boost/asio/ssl.hpp> #include <boost/bind.hpp> #include <boost/filesystem.hpp> #include <boost/foreach.hpp> #include <boost/iostreams/concepts.hpp> #include <boost/iostreams/stream.hpp> #include <boost/lexical_cast.hpp> #include <boost/shared_ptr.hpp> #include "json/json_spirit_writer_template.h" #include <fstream> using namespace std; using namespace boost; using namespace boost::asio; using namespace json_spirit; // // HTTP protocol // // This ain't Apache. We're just using HTTP header for the length field // and to be compatible with other JSON-RPC implementations. // string HTTPPost(const string& strMsg, const map<string,string>& mapRequestHeaders) { ostringstream s; s << "POST / HTTP/1.1\r\n" << "User-Agent: skullcash-json-rpc/" << FormatFullVersion() << "\r\n" << "Host: 127.0.0.1\r\n" << "Content-Type: application/json\r\n" << "Content-Length: " << strMsg.size() << "\r\n" << "Connection: close\r\n" << "Accept: application/json\r\n"; BOOST_FOREACH(const PAIRTYPE(string, string)& item, mapRequestHeaders) s << item.first << ": " << item.second << "\r\n"; s << "\r\n" << strMsg; return s.str(); } static string rfc1123Time() { return DateTimeStrFormat("%a, %d %b %Y %H:%M:%S +0000", GetTime()); } string HTTPReply(int nStatus, const string& strMsg, bool keepalive) { if (nStatus == HTTP_UNAUTHORIZED) return strprintf("HTTP/1.0 401 Authorization Required\r\n" "Date: %s\r\n" "Server: skullcash-json-rpc/%s\r\n" "WWW-Authenticate: Basic realm=\"jsonrpc\"\r\n" "Content-Type: text/html\r\n" "Content-Length: 296\r\n" "\r\n" "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\"\r\n" "\"http://www.w3.org/TR/1999/REC-html401-19991224/loose.dtd\">\r\n" "<HTML>\r\n" "<HEAD>\r\n" "<TITLE>Error</TITLE>\r\n" "<META HTTP-EQUIV='Content-Type' CONTENT='text/html; charset=ISO-8859-1'>\r\n" "</HEAD>\r\n" "<BODY><H1>401 Unauthorized.</H1></BODY>\r\n" "</HTML>\r\n", rfc1123Time(), FormatFullVersion()); const char *cStatus; if (nStatus == HTTP_OK) cStatus = "OK"; else if (nStatus == HTTP_BAD_REQUEST) cStatus = "Bad Request"; else if (nStatus == HTTP_FORBIDDEN) cStatus = "Forbidden"; else if (nStatus == HTTP_NOT_FOUND) cStatus = "Not Found"; else if (nStatus == HTTP_INTERNAL_SERVER_ERROR) cStatus = "Internal Server Error"; else cStatus = ""; return strprintf( "HTTP/1.1 %d %s\r\n" "Date: %s\r\n" "Connection: %s\r\n" "Content-Length: %u\r\n" "Content-Type: application/json\r\n" "Server: skullcash-json-rpc/%s\r\n" "\r\n" "%s", nStatus, cStatus, rfc1123Time(), keepalive ? "keep-alive" : "close", strMsg.size(), FormatFullVersion(), strMsg); } bool ReadHTTPRequestLine(std::basic_istream<char>& stream, int &proto, string& http_method, string& http_uri) { string str; getline(stream, str); // HTTP request line is space-delimited vector<string> vWords; boost::split(vWords, str, boost::is_any_of(" ")); if (vWords.size() < 2) return false; // HTTP methods permitted: GET, POST http_method = vWords[0]; if (http_method != "GET" && http_method != "POST") return false; // HTTP URI must be an absolute path, relative to current host http_uri = vWords[1]; if (http_uri.size() == 0 || http_uri[0] != '/') return false; // parse proto, if present string strProto = ""; if (vWords.size() > 2) strProto = vWords[2]; proto = 0; const char *ver = strstr(strProto.c_str(), "HTTP/1."); if (ver != NULL) proto = atoi(ver+7); return true; } int ReadHTTPStatus(std::basic_istream<char>& stream, int &proto) { string str; getline(stream, str); vector<string> vWords; boost::split(vWords, str, boost::is_any_of(" ")); if (vWords.size() < 2) return HTTP_INTERNAL_SERVER_ERROR; proto = 0; const char *ver = strstr(str.c_str(), "HTTP/1."); if (ver != NULL) proto = atoi(ver+7); return atoi(vWords[1].c_str()); } int ReadHTTPHeaders(std::basic_istream<char>& stream, map<string, string>& mapHeadersRet) { int nLen = 0; while (true) { string str; std::getline(stream, str); if (str.empty() || str == "\r") break; string::size_type nColon = str.find(":"); if (nColon != string::npos) { string strHeader = str.substr(0, nColon); boost::trim(strHeader); boost::to_lower(strHeader); string strValue = str.substr(nColon+1); boost::trim(strValue); mapHeadersRet[strHeader] = strValue; if (strHeader == "content-length") nLen = atoi(strValue.c_str()); } } return nLen; } int ReadHTTPMessage(std::basic_istream<char>& stream, map<string, string>& mapHeadersRet, string& strMessageRet, int nProto) { mapHeadersRet.clear(); strMessageRet = ""; // Read header int nLen = ReadHTTPHeaders(stream, mapHeadersRet); if (nLen < 0 || nLen > (int)MAX_SIZE) return HTTP_INTERNAL_SERVER_ERROR; // Read message if (nLen > 0) { vector<char> vch(nLen); stream.read(&vch[0], nLen); strMessageRet = string(vch.begin(), vch.end()); } string sConHdr = mapHeadersRet["connection"]; if ((sConHdr != "close") && (sConHdr != "keep-alive")) { if (nProto >= 1) mapHeadersRet["connection"] = "keep-alive"; else mapHeadersRet["connection"] = "close"; } return HTTP_OK; } // // JSON-RPC protocol. SkullCash speaks version 1.0 for maximum compatibility, // but uses JSON-RPC 1.1/2.0 standards for parts of the 1.0 standard that were // unspecified (HTTP errors and contents of 'error'). // // 1.0 spec: http://json-rpc.org/wiki/specification // 1.2 spec: http://groups.google.com/group/json-rpc/web/json-rpc-over-http // http://www.codeproject.com/KB/recipes/JSON_Spirit.aspx // string JSONRPCRequest(const string& strMethod, const Array& params, const Value& id) { Object request; request.push_back(Pair("method", strMethod)); request.push_back(Pair("params", params)); request.push_back(Pair("id", id)); return write_string(Value(request), false) + "\n"; } Object JSONRPCReplyObj(const Value& result, const Value& error, const Value& id) { Object reply; if (error.type() != null_type) reply.push_back(Pair("result", Value::null)); else reply.push_back(Pair("result", result)); reply.push_back(Pair("error", error)); reply.push_back(Pair("id", id)); return reply; } string JSONRPCReply(const Value& result, const Value& error, const Value& id) { Object reply = JSONRPCReplyObj(result, error, id); return write_string(Value(reply), false) + "\n"; } Object JSONRPCError(int code, const string& message) { Object error; error.push_back(Pair("code", code)); error.push_back(Pair("message", message)); return error; } /** Username used when cookie authentication is in use (arbitrary, only for * recognizability in debugging/logging purposes) */ static const std::string COOKIEAUTH_USER = "__cookie__"; /** Default name for auth cookie file */ static const std::string COOKIEAUTH_FILE = "cookie"; boost::filesystem::path GetAuthCookieFile() { boost::filesystem::path path(GetArg("-rpccookiefile", COOKIEAUTH_FILE)); if (!path.is_complete()) path = GetDataDir() / path; return path; } bool GenerateAuthCookie(std::string *cookie_out) { unsigned char rand_pwd[32]; RAND_bytes(rand_pwd, 32); std::string cookie = COOKIEAUTH_USER + ":" + EncodeBase64(&rand_pwd[0],32); /* these are set to 077 in init.cpp unless overridden with -sysperms. */ std::ofstream file; boost::filesystem::path filepath = GetAuthCookieFile(); file.open(filepath.string().c_str()); if (!file.is_open()) { LogPrintf("Unable to open cookie authentication file %s for writing\n", filepath.string()); return false; } file << cookie; file.close(); LogPrintf("Generated RPC authentication cookie %s\n", filepath.string()); if (cookie_out) *cookie_out = cookie; return true; } bool GetAuthCookie(std::string *cookie_out) { std::ifstream file; std::string cookie; boost::filesystem::path filepath = GetAuthCookieFile(); file.open(filepath.string().c_str()); if (!file.is_open()) return false; std::getline(file, cookie); file.close(); if (cookie_out) *cookie_out = cookie; return true; } void DeleteAuthCookie() { try { boost::filesystem::remove(GetAuthCookieFile()); } catch (const boost::filesystem::filesystem_error& e) { LogPrintf("%s: Unable to remove random auth cookie file: %s\n", __func__, e.what()); } }
[ "skullcash@users.noreply.github.com" ]
skullcash@users.noreply.github.com
3eb519c289b12e3daccc44701418266ce6e47721
948f4e13af6b3014582909cc6d762606f2a43365
/testcases/juliet_test_suite/testcases/CWE122_Heap_Based_Buffer_Overflow/s11/CWE122_Heap_Based_Buffer_Overflow__placement_new_64b.cpp
67462a2cc5472ce5a9bbb7a199b4da8bea4c6cb3
[]
no_license
junxzm1990/ASAN--
0056a341b8537142e10373c8417f27d7825ad89b
ca96e46422407a55bed4aa551a6ad28ec1eeef4e
refs/heads/master
2022-08-02T15:38:56.286555
2022-06-16T22:19:54
2022-06-16T22:19:54
408,238,453
74
13
null
2022-06-16T22:19:55
2021-09-19T21:14:59
null
UTF-8
C++
false
false
3,879
cpp
/* TEMPLATE GENERATED TESTCASE FILE Filename: CWE122_Heap_Based_Buffer_Overflow__placement_new_64b.cpp Label Definition File: CWE122_Heap_Based_Buffer_Overflow__placement_new.label.xml Template File: sources-sinks-64b.tmpl.cpp */ /* * @description * CWE: 122 Heap Based Buffer Overflow * BadSource: Initialize data to a small buffer * GoodSource: Initialize data to a buffer large enough to hold a TwoIntsClass * Sinks: * GoodSink: Allocate a new class using placement new and a buffer that is large enough to hold the class * BadSink : Allocate a new class using placement new and a buffer that is too small * Flow Variant: 64 Data flow: void pointer to data passed from one function to another in different source files * * */ #include "std_testcase.h" namespace CWE122_Heap_Based_Buffer_Overflow__placement_new_64 { #ifndef OMITBAD void badSink(void * dataVoidPtr) { /* cast void pointer to a pointer of the appropriate type */ char * * dataPtr = (char * *)dataVoidPtr; /* dereference dataPtr into data */ char * data = (*dataPtr); { /* The Visual C++ compiler generates a warning if you initialize the class with (). * This will cause the compile to default-initialize the object. * See http://msdn.microsoft.com/en-us/library/wewb47ee%28v=VS.100%29.aspx */ /* POTENTIAL FLAW: data may not be large enough to hold a TwoIntsClass */ TwoIntsClass * classTwo = new(data) TwoIntsClass; /* Initialize and make use of the class */ classTwo->intOne = 5; classTwo->intTwo = 10; /* POTENTIAL FLAW: If sizeof(data) < sizeof(TwoIntsClass) then this line will be a buffer overflow */ printIntLine(classTwo->intOne); /* skip printing classTwo->intTwo since that could be a buffer overread */ free(data); } } #endif /* OMITBAD */ #ifndef OMITGOOD /* goodG2B uses the GoodSource with the BadSink */ void goodG2BSink(void * dataVoidPtr) { /* cast void pointer to a pointer of the appropriate type */ char * * dataPtr = (char * *)dataVoidPtr; /* dereference dataPtr into data */ char * data = (*dataPtr); { /* The Visual C++ compiler generates a warning if you initialize the class with (). * This will cause the compile to default-initialize the object. * See http://msdn.microsoft.com/en-us/library/wewb47ee%28v=VS.100%29.aspx */ /* POTENTIAL FLAW: data may not be large enough to hold a TwoIntsClass */ TwoIntsClass * classTwo = new(data) TwoIntsClass; /* Initialize and make use of the class */ classTwo->intOne = 5; classTwo->intTwo = 10; /* POTENTIAL FLAW: If sizeof(data) < sizeof(TwoIntsClass) then this line will be a buffer overflow */ printIntLine(classTwo->intOne); /* skip printing classTwo->intTwo since that could be a buffer overread */ free(data); } } /* goodB2G uses the BadSource with the GoodSink */ void goodB2GSink(void * dataVoidPtr) { /* cast void pointer to a pointer of the appropriate type */ char * * dataPtr = (char * *)dataVoidPtr; /* dereference dataPtr into data */ char * data = (*dataPtr); { /* The Visual C++ compiler generates a warning if you initialize the class with (). * This will cause the compile to default-initialize the object. * See http://msdn.microsoft.com/en-us/library/wewb47ee%28v=VS.100%29.aspx */ /* FIX: data will at least be the sizeof(OneIntClass) */ OneIntClass * classOne = new(data) OneIntClass; /* Initialize and make use of the class */ classOne->intOne = 5; printIntLine(classOne->intOne); free(data); } } #endif /* OMITGOOD */ } /* close namespace */
[ "yzhang0701@gmail.com" ]
yzhang0701@gmail.com
83f2bbd32912516c93250f2cef037232df122a28
c78023bb0d524f172e54ded23fa595861346531d
/MaterialLib/MPL/Properties/RelativePermeability/RelPermUdell.cpp
5e70d82b34a6ac16ed180c37f4b7a67db505cd57
[ "BSD-2-Clause", "BSD-3-Clause" ]
permissive
TH2M-NGH-group-zju/ogs
2f0d7fe050d9d65c27bd37b08cd32bb247ba292f
074c5129680e87516477708b081afe79facabe87
refs/heads/master
2023-02-06T16:56:28.454514
2020-12-24T13:13:01
2020-12-24T13:13:01
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,391
cpp
/** * \file * \author Norbert Grunwald * \date 01.12.2020 * * \copyright * Copyright (c) 2012-2020, OpenGeoSys Community (http://www.opengeosys.org) * Distributed under a Modified BSD License. * See accompanying file LICENSE.txt or * http://www.opengeosys.org/project/license * */ #include "RelPermUdell.h" #include <algorithm> #include <cmath> #include "MaterialLib/MPL/Medium.h" namespace MaterialPropertyLib { RelPermUdell::RelPermUdell(std::string name, const double residual_liquid_saturation, const double residual_gas_saturation, const double min_relative_permeability_liquid, const double min_relative_permeability_gas) : residual_liquid_saturation_(residual_liquid_saturation), residual_gas_saturation_(residual_gas_saturation), min_relative_permeability_liquid_(min_relative_permeability_liquid), min_relative_permeability_gas_(min_relative_permeability_gas) { name_ = std::move(name); } PropertyDataType RelPermUdell::value( VariableArray const& variable_array, ParameterLib::SpatialPosition const& /*pos*/, double const /*t*/, double const /*dt*/) const { const double s_L = std::get<double>( variable_array[static_cast<int>(Variable::liquid_saturation)]); if (std::isnan(s_L)) { OGS_FATAL("Liquid saturation not set in RelPermUdell::value()."); } auto const s_L_res = residual_liquid_saturation_; auto const s_L_max = 1. - residual_gas_saturation_; auto const k_rel_min_LR = min_relative_permeability_liquid_; auto const k_rel_min_GR = min_relative_permeability_gas_; auto const s = (s_L - s_L_res) / (s_L_max - s_L_res); if (s >= 1.0) { // fully saturated medium return Eigen::Vector2d{1.0, k_rel_min_GR}; } if (s <= 0.0) { // dry medium return Eigen::Vector2d{k_rel_min_LR, 1.0}; } auto const k_rel_LR = s * s * s; auto const k_rel_GR = (1. - s) * (1. - s) * (1. - s); return Eigen::Vector2d{std::max(k_rel_LR, k_rel_min_LR), std::max(k_rel_GR, k_rel_min_GR)}; } PropertyDataType RelPermUdell::dValue( VariableArray const& variable_array, Variable const primary_variable, ParameterLib::SpatialPosition const& /*pos*/, double const /*t*/, double const /*dt*/) const { (void)primary_variable; assert((primary_variable == Variable::liquid_saturation) && "RelPermUdell::dValue is implemented for " " derivatives with respect to liquid saturation only."); const double s_L = std::get<double>( variable_array[static_cast<int>(Variable::liquid_saturation)]); auto const s_L_res = residual_liquid_saturation_; auto const s_L_max = 1. - residual_gas_saturation_; auto const s = (s_L - s_L_res) / (s_L_max - s_L_res); if ((s < 0.) || (s > 1.)) { return Eigen::Vector2d{0., 0.}; } auto const d_se_d_sL = 1. / (s_L_max - s_L_res); auto const dk_rel_LRdse = 3. * s * s; auto const dk_rel_LRdsL = dk_rel_LRdse * d_se_d_sL; auto const dk_rel_GRdse = -3. * (1. - s) * (1. - s); auto const dk_rel_GRdsL = dk_rel_GRdse * d_se_d_sL; return Eigen::Vector2d{dk_rel_LRdsL, dk_rel_GRdsL}; } } // namespace MaterialPropertyLib
[ "Norbert.Grunwald@ufz.de" ]
Norbert.Grunwald@ufz.de
0b11dd97b4df8bf9d007ee52ab73916cee60bde4
0b60493522498390d25a8d6f701be80d8cae8538
/ProjektProbaSFML/ProjektProbaSFML/Standby.cpp
6de2abaef525c4d1f6d8098577b4614e2bff4cc6
[]
no_license
alekkul271/Programowanie2
1fa26aa942428b167372d7b385585afa8c773f89
174734743b97c8a2b9a46c8a588b8095b23d3066
refs/heads/master
2022-06-28T10:44:58.625051
2020-05-11T18:31:27
2020-05-11T18:31:27
262,615,273
0
0
null
null
null
null
UTF-8
C++
false
false
924
cpp
#include "Standby.h" Standby::Standby(sf::Texture* texture, sf::Vector2u imageCount, float switch_time) { this->imageCount = imageCount; this->switch_time = switch_time; total_time = 0.0f; currentImage.x = 0; uvRect.width = texture->getSize().x / static_cast<float>(imageCount.x); uvRect.height = texture->getSize().y / static_cast<float>(imageCount.y); } Standby::~Standby() { } void Standby::Update(int row, float deltaTime, bool faceRight) { currentImage.y = row; total_time += deltaTime; if (total_time >= switch_time) { total_time -= switch_time; currentImage.x++; if (currentImage.x >= imageCount.x) { currentImage.x = 0; } } uvRect.top = currentImage.y * uvRect.height; if (faceRight) { uvRect.left = currentImage.x * uvRect.width; uvRect.width = abs(uvRect.width); } else { uvRect.left = (currentImage.x + 1) * abs(uvRect.width); uvRect.width = -abs(uvRect.width); } }
[ "alekkul271@polsl.pl" ]
alekkul271@polsl.pl
5d2eda42570892f426fb8e1be0d9095a6fb197c3
bcd122dc1ec9131f148178950a1a9b6e0b61c808
/src/libinterpol/include/interpol/euclidean/bezier.hpp
8b1056d8138ff12436dc06e0ad4be5e6199e327c
[ "MIT" ]
permissive
QubingHuo-source/interpolation-methods
88d73cef91ad4ad4b2a8455a79d0bffc9817b535
094cbabbd0c25743d088a623f5913149c6b8a2ab
refs/heads/master
2023-04-30T19:55:29.781785
2020-02-21T13:14:30
2020-02-21T13:16:14
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,989
hpp
/** * This file is part of https://github.com/adrelino/interpolation-methods * * Copyright (c) 2018 Adrian Haarbach <mail@adrian-haarbach.de> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ #ifndef INTERPOL_BEZIER_HPP #define INTERPOL_BEZIER_HPP #include <spline.h> //tk::spline #include <interpol/utils/vector_a.hpp> namespace interpol { namespace bezier { template<unsigned int Dim> class Spline{ public: Spline() = default; Spline(vector_a<Eigen::Matrix<double,Dim,1>>& pts, std::vector<double>& t_vec, bool firstDerivBoundary=false, Eigen::Matrix<double,Dim,1> leftBoundary=Eigen::Matrix<double,Dim,1>::Zero(), Eigen::Matrix<double,Dim,1> rightBoundary=Eigen::Matrix<double,Dim,1>::Zero()){ n = pts.size(); assertCustom(n >= 2); assertCustom(n == t_vec.size()); std::vector<double> x_vecs[Dim]; for(size_t i=0; i<n; i++){ /* double tGlobal = i*1.0/(n-1); t_vec.push_back(tGlobal);*/ const Eigen::Matrix<double,Dim,1>& pos = pts[i]; for(unsigned int j=0; j<Dim; j++){ x_vecs[j].push_back(pos(j)); } } for(unsigned int j=0; j<Dim; j++){ if(firstDerivBoundary){ splines[j].set_boundary(tk::spline::bd_type::first_deriv,leftBoundary(j),tk::spline::bd_type::first_deriv,rightBoundary(j)); }else{ splines[j].set_boundary(tk::spline::bd_type::second_deriv,leftBoundary(j),tk::spline::bd_type::second_deriv,rightBoundary(j)); } splines[j].set_points(t_vec,x_vecs[j]); /* if(j==0){ splines[j].m_a={-4,-4,-4}; splines[j].m_b={6,6,6}; splines[j].m_c={0,0,0}; splines[j].m_y={-1,1,3}; }else if(j==1){ splines[j].m_a={0,0,0}; splines[j].m_b={-6,-6,-6}; splines[j].m_c={6,6,6}; splines[j].m_y={-1,-1,-1}; }*/ } } Eigen::Matrix<double,Dim,1> eval(double tGlobal) const{ Eigen::Matrix<double,Dim,1> p; for(unsigned int j=0; j<Dim; j++){ p(j)=splines[j](tGlobal); } return p; } vector_a<Eigen::Matrix<double,Dim,1>> getBasisPoints(){ vector_a<Eigen::Matrix<double,Dim,1>> pts; for(unsigned int i=0; i<n-1; i++) { for (int k = 0; k <= 3; k++) { Eigen::Matrix<double, Dim, 1> p; for (unsigned int j = 0; j < Dim; j++) { p(j) = splines[j].control_polygon(i, k); } pts.push_back(p); } } return pts; } private: // interpolated positions tk::spline splines[Dim]; size_t n; }; typedef Spline<3> Spline3d; typedef Spline<4> Spline4d; } // ns bezier } // ns interpol #endif // INTERPOL_BEZIER_HPP
[ "mail@adrian-haarbach.de" ]
mail@adrian-haarbach.de
361b162440c7959958e32218bb3412fec7209a56
35c90b9d070d6593a136a5e848c5b37142ff1748
/tools/bonsaiRenderer/splotch/renderloop.cpp
863d97e9485ef1dc177de2de0298963d1e6066a2
[ "Apache-2.0", "LicenseRef-scancode-warranty-disclaimer" ]
permissive
ericchill/Bonsai
b2979badcce5d0b26f76d9dff3d44d265f0e1e9c
8904dd3ebf395ccaaf0eacef38933002b49fc3ba
refs/heads/master
2022-01-24T04:45:09.787812
2020-10-10T09:09:33
2020-10-10T09:09:33
71,961,070
0
0
null
2016-10-26T03:05:49
2016-10-26T03:05:49
null
UTF-8
C++
false
false
15,992
cpp
#include <stdio.h> #include "GLSLProgram.h" #ifdef WIN32 #define NOMINMAX #endif #include <GL/glew.h> #ifdef WIN32 #include <GL/wglew.h> #else #include <GL/glxew.h> #endif #if defined(__APPLE__) || defined(MACOSX) #include <GLUT/glut.h> #else #include <GL/freeglut.h> #endif #include <algorithm> #include "renderloop.h" #include "renderer.h" #include "vector_math.h" #include <cstdarg> #include "colorMap" #include "Splotch.h" #include <sys/time.h> static inline double rtc(void) { struct timeval Tvalue; double etime; struct timezone dummy; gettimeofday(&Tvalue,&dummy); etime = (double) Tvalue.tv_sec + 1.e-6*((double) Tvalue.tv_usec); return etime; } unsigned long long fpsCount; double timeBegin; const char passThruVS[] = { " void main() \n " " { \n " " gl_Position = gl_Vertex; \n " " gl_TexCoord[0] = gl_MultiTexCoord0; \n " " gl_FrontColor = gl_Color; \n " " } \n " }; const char texture2DPS[] = { " uniform sampler2D tex; \n " " void main() \n " " { \n " " vec4 c = texture2D(tex, gl_TexCoord[0].xy); \n " " gl_FragColor = c; \n " " } \n " }; void beginDeviceCoords(void) { glMatrixMode(GL_PROJECTION); glPushMatrix(); glLoadIdentity(); glOrtho(0, glutGet(GLUT_WINDOW_WIDTH), 0, glutGet(GLUT_WINDOW_HEIGHT), -1, 1); glMatrixMode(GL_MODELVIEW); glPushMatrix(); glLoadIdentity(); } void glutStrokePrint(float x, float y, const char *s, void *font) { glPushMatrix(); glTranslatef(x, y, 0.0f); int len = (int) strlen(s); for (int i = 0; i < len; i++) { glutStrokeCharacter(font, s[i]); } glPopMatrix(); } void glPrintf(float x, float y, const char* format, ...) { //void *font = GLUT_STROKE_ROMAN; void *font = GLUT_STROKE_MONO_ROMAN; char buffer[256]; va_list args; va_start (args, format); vsnprintf (buffer, 255, format, args); glutStrokePrint(x, y, buffer, font); va_end(args); } class Demo { public: Demo(RendererData &idata) : m_idata(idata), m_ox(0), m_oy(0), m_buttonState(0), m_inertia(0.1f), m_paused(false), m_displayFps(true), m_displaySliders(true), m_texture(0), m_displayTexProg(0) // m_fov(40.0f)k // m_params(m_renderer.getParams()) { m_windowDims = make_int2(720, 480); m_cameraTrans = make_float3(0, -2, -10); m_cameraTransLag = m_cameraTrans; m_cameraRot = make_float3(0, 0, 0); m_cameraRotLag = m_cameraRot; //float color[4] = { 0.8f, 0.7f, 0.95f, 0.5f}; // float4 color = make_float4(1.0f, 1.0f, 1.0f, 1.0f); // m_renderer.setBaseColor(color); // m_renderer.setSpriteSizeScale(1.0f); m_displayTexProg = new GLSLProgram(passThruVS, texture2DPS); m_renderer.setColorMap(reinterpret_cast<float3*>(colorMap),256,256, 1.0f/255.0f); m_renderer.setWidth (m_windowDims.x); m_renderer.setHeight(m_windowDims.y); m_spriteSize = 0.1f; } ~Demo() { delete m_displayTexProg; } void cycleDisplayMode() {} void toggleSliders() { m_displaySliders = !m_displaySliders; } void toggleFps() { m_displayFps = !m_displayFps; } void drawQuad(const float s = 1.0f, const float z = 0.0f) { glBegin(GL_QUADS); glTexCoord2f(0.0, 0.0); glVertex3f(-s, -s, z); glTexCoord2f(1.0, 0.0); glVertex3f(s, -s, z); glTexCoord2f(1.0, 1.0); glVertex3f(s, s, z); glTexCoord2f(0.0, 1.0); glVertex3f(-s, s, z); glEnd(); } void displayTexture(const GLuint tex) { m_displayTexProg->enable(); m_displayTexProg->bindTexture("tex", tex, GL_TEXTURE_2D, 0); drawQuad(); m_displayTexProg->disable(); } GLuint createTexture(GLenum target, int w, int h, GLint internalformat, GLenum format, void *data) { GLuint texid; glGenTextures(1, &texid); glBindTexture(target, texid); glTexParameteri(target, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glTexParameteri(target, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexParameteri(target, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); glTexParameteri(target, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); glTexImage2D(target, 0, internalformat, w, h, 0, format, GL_FLOAT, data); return texid; } void drawStats() { const float fps = fpsCount/(rtc() - timeBegin); if (fpsCount > 10*fps) { fpsCount = 0; timeBegin = rtc(); } beginDeviceCoords(); glScalef(0.25f, 0.25f, 1.0f); glEnable(GL_LINE_SMOOTH); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); glEnable(GL_BLEND); glDisable(GL_DEPTH_TEST); glColor4f(0.0f, 1.0f, 0.0f, 1.0f); float x = 100.0f; float y = glutGet(GLUT_WINDOW_HEIGHT)*4.0f - 200.0f; const float lineSpacing = 140.0f; if (m_displayFps) { glPrintf(x, y, "FPS: %.2f", fps); y -= lineSpacing; } glDisable(GL_BLEND); endWinCoords(); char str[256]; sprintf(str, "N-Body Renderer: %0.1f fps", fps); glutSetWindowTitle(str); } void display() { getBodyData(); fpsCount++; // view transform { glMatrixMode(GL_MODELVIEW); glLoadIdentity(); m_cameraTransLag += (m_cameraTrans - m_cameraTransLag) * m_inertia; m_cameraRotLag += (m_cameraRot - m_cameraRotLag) * m_inertia; glTranslatef(m_cameraTransLag.x, m_cameraTransLag.y, m_cameraTransLag.z); glRotatef(m_cameraRotLag.x, 1.0, 0.0, 0.0); glRotatef(m_cameraRotLag.y, 0.0, 1.0, 0.0); } #if 0 if (m_displaySliders) { m_params->Render(0, 0); } #endif #if 1 glGetDoublev( GL_MODELVIEW_MATRIX, (GLdouble*)m_modelView); glGetDoublev(GL_PROJECTION_MATRIX, (GLdouble*)m_projection); m_renderer. setModelViewMatrix(m_modelView); m_renderer.setProjectionMatrix(m_projection); m_renderer.genImage(); fprintf(stderr, " --- frame done --- \n"); const int width = m_renderer.getWidth(); const int height = m_renderer.getHeight(); const float4 *img = &m_renderer.getImage()[0]; m_texture = createTexture(GL_TEXTURE_2D, width, height, GL_RGBA, GL_RGBA, (void*)img); #else const int width = 128; const int height = 128; std::vector<float> data(4*width*height); { using ShortVec3 = MathArray<float,3>; std::vector<ShortVec3> tex(256*256); int idx = 0; for (int i = 0; i < 256; i++) for (int j = 0; j < 256; j++) { tex[idx][0] = colorMap[i][j][0]/255.0f; tex[idx][1] = colorMap[i][j][1]/255.0f; tex[idx][2] = colorMap[i][j][2]/255.0f; idx++; } Texture2D<ShortVec3> texMap(&tex[0],256,256); for (int j = 0; j < height; j++) for (int i = 0; i < width; i++) { auto f = texMap(1.0f*i/width, j*1.0f/height); // f = texMap(1.0f, j*1.0f/height); data[0 + 4*(i + width*j)] = f[0]; data[1 + 4*(i + width*j)] = f[1]; data[2 + 4*(i + width*j)] = f[2]; data[3 + 4*(i + width*j)] = 1.0f; } } m_texture = createTexture(GL_TEXTURE_2D, width, height, GL_RGBA, GL_RGBA, &data[0]); #endif displayTexture(m_texture); drawStats(); } void mouse(int button, int state, int x, int y) { int mods; if (state == GLUT_DOWN) { m_buttonState |= 1<<button; } else if (state == GLUT_UP) { m_buttonState = 0; } mods = glutGetModifiers(); if (mods & GLUT_ACTIVE_SHIFT) { m_buttonState = 2; } else if (mods & GLUT_ACTIVE_CTRL) { m_buttonState = 3; } m_ox = x; m_oy = y; } void motion(int x, int y) { float dx = (float)(x - m_ox); float dy = (float)(y - m_oy); #if 0 if (m_displaySliders) { if (m_params->Motion(x, y)) return; } #endif if (m_buttonState == 3) { // left+middle = zoom m_cameraTrans.z += (dy / 100.0f) * 0.5f * fabs(m_cameraTrans.z); } else if (m_buttonState & 2) { // middle = translate m_cameraTrans.x += dx / 10.0f; m_cameraTrans.y -= dy / 10.0f; } else if (m_buttonState & 1) { // left = rotate m_cameraRot.x += dy / 5.0f; m_cameraRot.y += dx / 5.0f; } m_ox = x; m_oy = y; } void reshape(int w, int h) { m_windowDims = make_int2(w, h); fitCamera(); glMatrixMode(GL_MODELVIEW); glViewport(0, 0, m_windowDims.x, m_windowDims.y); m_renderer.setWidth (w); m_renderer.setHeight(h); } void fitCamera() { float3 boxMin = make_float3(m_idata.rmin()); float3 boxMax = make_float3(m_idata.rmax()); const float pi = 3.1415926f; float3 center = 0.5f * (boxMin + boxMax); float radius = std::max(length(boxMax), length(boxMin)); const float fovRads = (m_windowDims.x / (float)m_windowDims.y) * pi / 3.0f ; // 60 degrees float distanceToCenter = radius / sinf(0.5f * fovRads); m_cameraTrans = center + make_float3(0, 0, - distanceToCenter); m_cameraTransLag = m_cameraTrans; glMatrixMode(GL_PROJECTION); glLoadIdentity(); gluPerspective(60.0, (float) m_windowDims.x / (float) m_windowDims.y, 0.0001 * distanceToCenter, 4 * (radius + distanceToCenter)); } private: void getBodyData() { int n = m_idata.n(); const float velMax = m_idata.attributeMax(RendererData::VEL); const float velMin = m_idata.attributeMin(RendererData::VEL); const float rhoMax = m_idata.attributeMax(RendererData::RHO); const float rhoMin = m_idata.attributeMin(RendererData::RHO); const bool hasRHO = rhoMax > 0.0f; const float scaleVEL = 1.0/(velMax - velMin); const float scaleRHO = hasRHO ? 1.0/(rhoMax - rhoMin) : 0.0; m_renderer.resize(n); #pragma omp parallel for for (int i = 0; i < n; i++) { auto vtx = m_renderer.vertex_at(i); vtx.pos = Splotch::pos3d_t(m_idata.posx(i), m_idata.posy(i), m_idata.posz(i), m_spriteSize); // vtx.pos.h = m_idata.attribute(RendererData::H,i)*2; // vtx.pos.h *= m_spriteScale; vtx.color = make_float4(1.0f); float vel = m_idata.attribute(RendererData::VEL,i); float rho = m_idata.attribute(RendererData::RHO,i); vel = (vel - velMin) * scaleVEL; vel = std::pow(vel, 1.0f); rho = hasRHO ? (rho - rhoMin) * scaleRHO : 0.5f; assert(vel >= 0.0f && vel <= 1.0f); assert(rho >= 0.0f && rho <= 1.0f); vtx.attr = Splotch::attr_t(rho, vel, m_spriteIntensity, m_idata.type(i)); } } RendererData &m_idata; Splotch m_renderer; // view params int m_ox; // = 0 int m_oy; // = 0; int m_buttonState; int2 m_windowDims; float3 m_cameraTrans; float3 m_cameraRot; float3 m_cameraTransLag; float3 m_cameraRotLag; const float m_inertia; bool m_paused; bool m_displayBoxes; bool m_displayFps; bool m_displaySliders; ParamListGL *m_params; float m_spriteSize; float m_spriteIntensity; unsigned int m_texture; GLSLProgram *m_displayTexProg; double m_modelView [4][4]; double m_projection[4][4]; }; Demo *theDemo = NULL; void onexit() { if (theDemo) delete theDemo; } void display() { glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); theDemo->display(); glutSwapBuffers(); } void reshape(int w, int h) { theDemo->reshape(w, h); glutPostRedisplay(); } void mouse(int button, int state, int x, int y) { theDemo->mouse(button, state, x, y); glutPostRedisplay(); } void motion(int x, int y) { theDemo->motion(x, y); glutPostRedisplay(); } // commented out to remove unused parameter warnings in Linux void key(unsigned char key, int /*x*/, int /*y*/) { switch (key) { case ' ': // theDemo->togglePause(); break; case 27: // escape case 'q': case 'Q': // cudaDeviceReset(); exit(0); break; /*case '`': bShowSliders = !bShowSliders; break;*/ case 'p': case 'P': theDemo->cycleDisplayMode(); break; case 'b': case 'B': // theDemo->toggleBoxes(); break; case 'd': case 'D': //displayEnabled = !displayEnabled; break; case 'f': case 'F': theDemo->fitCamera(); break; case ',': case '<': // theDemo->incrementOctreeDisplayLevel(-1); break; case '.': case '>': // theDemo->incrementOctreeDisplayLevel(+1); break; case 'h': case 'H': theDemo->toggleSliders(); // m_enableStats = !m_displaySliders; break; case '0': theDemo->toggleFps(); break; } glutPostRedisplay(); } void special(int key, int x, int y) { //paramlist->Special(key, x, y); glutPostRedisplay(); } void idle(void) { glutPostRedisplay(); } void initGL(int argc, char** argv) { // First initialize OpenGL context, so we can properly set the GL for CUDA. // This is necessary in order to achieve optimal performance with OpenGL/CUDA interop. glutInit(&argc, argv); //glutInitWindowSize(720, 480); glutInitWindowSize(1024, 768); glutInitDisplayMode(GLUT_RGB | GLUT_DEPTH | GLUT_DOUBLE); glutCreateWindow("Bonsai Tree-code Gravitational N-body Simulation"); //if (bFullscreen) // glutFullScreen(); GLenum err = glewInit(); if (GLEW_OK != err) { fprintf(stderr, "GLEW Error: %s\n", glewGetErrorString(err)); // cudaDeviceReset(); exit(-1); } else if (!glewIsSupported("GL_VERSION_2_0 " "GL_VERSION_1_5 " "GL_ARB_multitexture " "GL_ARB_vertex_buffer_object")) { fprintf(stderr, "Required OpenGL extensions missing."); exit(-1); } else { #if defined(WIN32) wglSwapIntervalEXT(0); #elif defined(LINUX) glxSwapIntervalSGI(0); #endif } glutDisplayFunc(display); glutReshapeFunc(reshape); glutMouseFunc(mouse); glutMotionFunc(motion); glutKeyboardFunc(key); glutSpecialFunc(special); glutIdleFunc(idle); glEnable(GL_DEPTH_TEST); glClearColor(0.0, 0.0, 0.0, 1.0); checkGLErrors("initGL"); atexit(onexit); } void initAppRenderer( int argc, char** argv, RendererData &idata) { initGL(argc, argv); theDemo = new Demo(idata); fpsCount = 0; timeBegin = rtc(); glutMainLoop(); }
[ "egaburov@dds.nl" ]
egaburov@dds.nl
d9b6bd6e6c55323933ce5c8d07c2f39a466791bc
0f62b851257647d01658fdef5714586dc3c56a27
/PKU_20120224_1789.cpp
69c55ef547862050247339d39bc415bd148454eb
[]
no_license
cheeseonhead/PKUProblems
5de3a5d6e8f23d87873ce382d56b25a593460a11
65b0a3a20b551166d9e23644b90e06ca847cc541
refs/heads/master
2021-01-15T23:40:09.666781
2015-03-26T00:16:40
2015-03-26T00:16:40
32,898,397
0
0
null
null
null
null
UTF-8
C++
false
false
1,006
cpp
/* Judge: PKU PROG: 1789 */ #include <cstdio> #include <cstring> #include <algorithm> #define MAXN 2147483647 using namespace std; int N,ans,minid,least[2001]={0},mind; char s[2001][8]; int dis(int x, int y) { int dif=0; for(int i=0;i<6;i++) if(s[x][i]!=s[y][i])dif++; return dif; } int main() { #ifndef ONLINE_JUDGE freopen("PKU_20120224_1789.in","r",stdin); freopen("PKU_20120224_1789.out","w",stdout); #endif while(~scanf("%d\n",&N)) { if(!N)return 0; ans=0; for(int i=0;i<N;i++) gets(s[i]); for(int i=1;i<N;i++) least[i]=dis(0,i); for(int n=0;n<N-1;n++) { mind = MAXN; for(int i=0;i<N;i++) if(least[i]<mind && least[i]>0) { mind = least[i]; minid = i; } ans+=mind; least[minid] = -1; for(int i=0;i<N;i++) if(least[i]>0) if(dis(i,minid)<least[i]) least[i]=dis(i,minid); } printf("The highest possible quality is 1/%d.\n",ans); } return 0; }
[ "cheeseonhead@gmail.com" ]
cheeseonhead@gmail.com
56015f7916338bac09edf3f55bbe3100a4b5febf
ed10dc841d5b4f6a038e8f24f603750992d9fae9
/clang/lib/Sema/SemaStmt.cpp
e85fa34596f7a566d096e858b6d1427ef61f14c1
[ "Apache-2.0", "LLVM-exception", "NCSA" ]
permissive
WYK15/swift-Ollvm10
90c2f0ade099a1cc545183eba5c5a69765320401
ea68224ab23470963b68dfcc28b5ac769a070ea3
refs/heads/main
2023-03-30T20:02:58.305792
2021-04-07T02:41:01
2021-04-07T02:41:01
355,189,226
5
0
null
null
null
null
UTF-8
C++
false
false
170,107
cpp
//===--- SemaStmt.cpp - Semantic Analysis for Statements ------------------===// // // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. // See https://llvm.org/LICENSE.txt for license information. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception // //===----------------------------------------------------------------------===// // // This file implements semantic analysis for statements. // //===----------------------------------------------------------------------===// #include "clang/AST/ASTContext.h" #include "clang/AST/ASTDiagnostic.h" #include "clang/AST/ASTLambda.h" #include "clang/AST/CharUnits.h" #include "clang/AST/CXXInheritance.h" #include "clang/AST/CharUnits.h" #include "clang/AST/DeclObjC.h" #include "clang/AST/EvaluatedExprVisitor.h" #include "clang/AST/ExprCXX.h" #include "clang/AST/ExprObjC.h" #include "clang/AST/RecursiveASTVisitor.h" #include "clang/AST/StmtCXX.h" #include "clang/AST/StmtObjC.h" #include "clang/AST/TypeLoc.h" #include "clang/AST/TypeOrdering.h" #include "clang/Basic/TargetInfo.h" #include "clang/Edit/RefactoringFixits.h" #include "clang/Lex/Preprocessor.h" #include "clang/Sema/Initialization.h" #include "clang/Sema/Lookup.h" #include "clang/Sema/Ownership.h" #include "clang/Sema/Scope.h" #include "clang/Sema/ScopeInfo.h" #include "clang/Sema/SemaInternal.h" #include "llvm/ADT/ArrayRef.h" #include "llvm/ADT/DenseMap.h" #include "llvm/ADT/STLExtras.h" #include "llvm/ADT/SmallPtrSet.h" #include "llvm/ADT/SmallString.h" #include "llvm/ADT/SmallVector.h" using namespace clang; using namespace sema; StmtResult Sema::ActOnExprStmt(ExprResult FE, bool DiscardedValue) { if (FE.isInvalid()) return StmtError(); FE = ActOnFinishFullExpr(FE.get(), FE.get()->getExprLoc(), DiscardedValue); if (FE.isInvalid()) return StmtError(); // C99 6.8.3p2: The expression in an expression statement is evaluated as a // void expression for its side effects. Conversion to void allows any // operand, even incomplete types. // Same thing in for stmt first clause (when expr) and third clause. return StmtResult(FE.getAs<Stmt>()); } StmtResult Sema::ActOnExprStmtError() { DiscardCleanupsInEvaluationContext(); return StmtError(); } StmtResult Sema::ActOnNullStmt(SourceLocation SemiLoc, bool HasLeadingEmptyMacro) { return new (Context) NullStmt(SemiLoc, HasLeadingEmptyMacro); } StmtResult Sema::ActOnDeclStmt(DeclGroupPtrTy dg, SourceLocation StartLoc, SourceLocation EndLoc) { DeclGroupRef DG = dg.get(); // If we have an invalid decl, just return an error. if (DG.isNull()) return StmtError(); return new (Context) DeclStmt(DG, StartLoc, EndLoc); } void Sema::ActOnForEachDeclStmt(DeclGroupPtrTy dg) { DeclGroupRef DG = dg.get(); // If we don't have a declaration, or we have an invalid declaration, // just return. if (DG.isNull() || !DG.isSingleDecl()) return; Decl *decl = DG.getSingleDecl(); if (!decl || decl->isInvalidDecl()) return; // Only variable declarations are permitted. VarDecl *var = dyn_cast<VarDecl>(decl); if (!var) { Diag(decl->getLocation(), diag::err_non_variable_decl_in_for); decl->setInvalidDecl(); return; } // foreach variables are never actually initialized in the way that // the parser came up with. var->setInit(nullptr); // In ARC, we don't need to retain the iteration variable of a fast // enumeration loop. Rather than actually trying to catch that // during declaration processing, we remove the consequences here. if (getLangOpts().ObjCAutoRefCount) { QualType type = var->getType(); // Only do this if we inferred the lifetime. Inferred lifetime // will show up as a local qualifier because explicit lifetime // should have shown up as an AttributedType instead. if (type.getLocalQualifiers().getObjCLifetime() == Qualifiers::OCL_Strong) { // Add 'const' and mark the variable as pseudo-strong. var->setType(type.withConst()); var->setARCPseudoStrong(true); } } } /// Diagnose unused comparisons, both builtin and overloaded operators. /// For '==' and '!=', suggest fixits for '=' or '|='. /// /// Adding a cast to void (or other expression wrappers) will prevent the /// warning from firing. static bool DiagnoseUnusedComparison(Sema &S, const Expr *E) { SourceLocation Loc; bool CanAssign; enum { Equality, Inequality, Relational, ThreeWay } Kind; if (const BinaryOperator *Op = dyn_cast<BinaryOperator>(E)) { if (!Op->isComparisonOp()) return false; if (Op->getOpcode() == BO_EQ) Kind = Equality; else if (Op->getOpcode() == BO_NE) Kind = Inequality; else if (Op->getOpcode() == BO_Cmp) Kind = ThreeWay; else { assert(Op->isRelationalOp()); Kind = Relational; } Loc = Op->getOperatorLoc(); CanAssign = Op->getLHS()->IgnoreParenImpCasts()->isLValue(); } else if (const CXXOperatorCallExpr *Op = dyn_cast<CXXOperatorCallExpr>(E)) { switch (Op->getOperator()) { case OO_EqualEqual: Kind = Equality; break; case OO_ExclaimEqual: Kind = Inequality; break; case OO_Less: case OO_Greater: case OO_GreaterEqual: case OO_LessEqual: Kind = Relational; break; case OO_Spaceship: Kind = ThreeWay; break; default: return false; } Loc = Op->getOperatorLoc(); CanAssign = Op->getArg(0)->IgnoreParenImpCasts()->isLValue(); } else { // Not a typo-prone comparison. return false; } // Suppress warnings when the operator, suspicious as it may be, comes from // a macro expansion. if (S.SourceMgr.isMacroBodyExpansion(Loc)) return false; S.Diag(Loc, diag::warn_unused_comparison) << (unsigned)Kind << E->getSourceRange(); // If the LHS is a plausible entity to assign to, provide a fixit hint to // correct common typos. if (CanAssign) { if (Kind == Inequality) S.Diag(Loc, diag::note_inequality_comparison_to_or_assign) << FixItHint::CreateReplacement(Loc, "|="); else if (Kind == Equality) S.Diag(Loc, diag::note_equality_comparison_to_assign) << FixItHint::CreateReplacement(Loc, "="); } return true; } static bool DiagnoseNoDiscard(Sema &S, const WarnUnusedResultAttr *A, SourceLocation Loc, SourceRange R1, SourceRange R2, bool IsCtor) { if (!A) return false; StringRef Msg = A->getMessage(); if (Msg.empty()) { if (IsCtor) return S.Diag(Loc, diag::warn_unused_constructor) << A << R1 << R2; return S.Diag(Loc, diag::warn_unused_result) << A << R1 << R2; } if (IsCtor) return S.Diag(Loc, diag::warn_unused_constructor_msg) << A << Msg << R1 << R2; return S.Diag(Loc, diag::warn_unused_result_msg) << A << Msg << R1 << R2; } void Sema::DiagnoseUnusedExprResult(const Stmt *S) { if (const LabelStmt *Label = dyn_cast_or_null<LabelStmt>(S)) return DiagnoseUnusedExprResult(Label->getSubStmt()); const Expr *E = dyn_cast_or_null<Expr>(S); if (!E) return; // If we are in an unevaluated expression context, then there can be no unused // results because the results aren't expected to be used in the first place. if (isUnevaluatedContext()) return; SourceLocation ExprLoc = E->IgnoreParenImpCasts()->getExprLoc(); // In most cases, we don't want to warn if the expression is written in a // macro body, or if the macro comes from a system header. If the offending // expression is a call to a function with the warn_unused_result attribute, // we warn no matter the location. Because of the order in which the various // checks need to happen, we factor out the macro-related test here. bool ShouldSuppress = SourceMgr.isMacroBodyExpansion(ExprLoc) || SourceMgr.isInSystemMacro(ExprLoc); const Expr *WarnExpr; SourceLocation Loc; SourceRange R1, R2; if (!E->isUnusedResultAWarning(WarnExpr, Loc, R1, R2, Context)) return; // If this is a GNU statement expression expanded from a macro, it is probably // unused because it is a function-like macro that can be used as either an // expression or statement. Don't warn, because it is almost certainly a // false positive. if (isa<StmtExpr>(E) && Loc.isMacroID()) return; // Check if this is the UNREFERENCED_PARAMETER from the Microsoft headers. // That macro is frequently used to suppress "unused parameter" warnings, // but its implementation makes clang's -Wunused-value fire. Prevent this. if (isa<ParenExpr>(E->IgnoreImpCasts()) && Loc.isMacroID()) { SourceLocation SpellLoc = Loc; if (findMacroSpelling(SpellLoc, "UNREFERENCED_PARAMETER")) return; } // Okay, we have an unused result. Depending on what the base expression is, // we might want to make a more specific diagnostic. Check for one of these // cases now. unsigned DiagID = diag::warn_unused_expr; if (const FullExpr *Temps = dyn_cast<FullExpr>(E)) E = Temps->getSubExpr(); if (const CXXBindTemporaryExpr *TempExpr = dyn_cast<CXXBindTemporaryExpr>(E)) E = TempExpr->getSubExpr(); if (DiagnoseUnusedComparison(*this, E)) return; E = WarnExpr; if (const auto *Cast = dyn_cast<CastExpr>(E)) if (Cast->getCastKind() == CK_NoOp || Cast->getCastKind() == CK_ConstructorConversion) E = Cast->getSubExpr()->IgnoreImpCasts(); if (const CallExpr *CE = dyn_cast<CallExpr>(E)) { if (E->getType()->isVoidType()) return; if (DiagnoseNoDiscard(*this, cast_or_null<WarnUnusedResultAttr>( CE->getUnusedResultAttr(Context)), Loc, R1, R2, /*isCtor=*/false)) return; // If the callee has attribute pure, const, or warn_unused_result, warn with // a more specific message to make it clear what is happening. If the call // is written in a macro body, only warn if it has the warn_unused_result // attribute. if (const Decl *FD = CE->getCalleeDecl()) { if (ShouldSuppress) return; if (FD->hasAttr<PureAttr>()) { Diag(Loc, diag::warn_unused_call) << R1 << R2 << "pure"; return; } if (FD->hasAttr<ConstAttr>()) { Diag(Loc, diag::warn_unused_call) << R1 << R2 << "const"; return; } } } else if (const auto *CE = dyn_cast<CXXConstructExpr>(E)) { if (const CXXConstructorDecl *Ctor = CE->getConstructor()) { const auto *A = Ctor->getAttr<WarnUnusedResultAttr>(); A = A ? A : Ctor->getParent()->getAttr<WarnUnusedResultAttr>(); if (DiagnoseNoDiscard(*this, A, Loc, R1, R2, /*isCtor=*/true)) return; } } else if (const auto *ILE = dyn_cast<InitListExpr>(E)) { if (const TagDecl *TD = ILE->getType()->getAsTagDecl()) { if (DiagnoseNoDiscard(*this, TD->getAttr<WarnUnusedResultAttr>(), Loc, R1, R2, /*isCtor=*/false)) return; } } else if (ShouldSuppress) return; E = WarnExpr; if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(E)) { if (getLangOpts().ObjCAutoRefCount && ME->isDelegateInitCall()) { Diag(Loc, diag::err_arc_unused_init_message) << R1; return; } const ObjCMethodDecl *MD = ME->getMethodDecl(); if (MD) { if (DiagnoseNoDiscard(*this, MD->getAttr<WarnUnusedResultAttr>(), Loc, R1, R2, /*isCtor=*/false)) return; } } else if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E)) { const Expr *Source = POE->getSyntacticForm(); if (isa<ObjCSubscriptRefExpr>(Source)) DiagID = diag::warn_unused_container_subscript_expr; else DiagID = diag::warn_unused_property_expr; } else if (const CXXFunctionalCastExpr *FC = dyn_cast<CXXFunctionalCastExpr>(E)) { const Expr *E = FC->getSubExpr(); if (const CXXBindTemporaryExpr *TE = dyn_cast<CXXBindTemporaryExpr>(E)) E = TE->getSubExpr(); if (isa<CXXTemporaryObjectExpr>(E)) return; if (const CXXConstructExpr *CE = dyn_cast<CXXConstructExpr>(E)) if (const CXXRecordDecl *RD = CE->getType()->getAsCXXRecordDecl()) if (!RD->getAttr<WarnUnusedAttr>()) return; } // Diagnose "(void*) blah" as a typo for "(void) blah". else if (const CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(E)) { TypeSourceInfo *TI = CE->getTypeInfoAsWritten(); QualType T = TI->getType(); // We really do want to use the non-canonical type here. if (T == Context.VoidPtrTy) { PointerTypeLoc TL = TI->getTypeLoc().castAs<PointerTypeLoc>(); Diag(Loc, diag::warn_unused_voidptr) << FixItHint::CreateRemoval(TL.getStarLoc()); return; } } // Tell the user to assign it into a variable to force a volatile load if this // isn't an array. if (E->isGLValue() && E->getType().isVolatileQualified() && !E->getType()->isArrayType()) { Diag(Loc, diag::warn_unused_volatile) << R1 << R2; return; } DiagRuntimeBehavior(Loc, nullptr, PDiag(DiagID) << R1 << R2); } void Sema::ActOnStartOfCompoundStmt(bool IsStmtExpr) { PushCompoundScope(IsStmtExpr); } void Sema::ActOnFinishOfCompoundStmt() { PopCompoundScope(); } sema::CompoundScopeInfo &Sema::getCurCompoundScope() const { return getCurFunction()->CompoundScopes.back(); } StmtResult Sema::ActOnCompoundStmt(SourceLocation L, SourceLocation R, ArrayRef<Stmt *> Elts, bool isStmtExpr) { const unsigned NumElts = Elts.size(); // If we're in C89 mode, check that we don't have any decls after stmts. If // so, emit an extension diagnostic. if (!getLangOpts().C99 && !getLangOpts().CPlusPlus) { // Note that __extension__ can be around a decl. unsigned i = 0; // Skip over all declarations. for (; i != NumElts && isa<DeclStmt>(Elts[i]); ++i) /*empty*/; // We found the end of the list or a statement. Scan for another declstmt. for (; i != NumElts && !isa<DeclStmt>(Elts[i]); ++i) /*empty*/; if (i != NumElts) { Decl *D = *cast<DeclStmt>(Elts[i])->decl_begin(); Diag(D->getLocation(), diag::ext_mixed_decls_code); } } // Check for suspicious empty body (null statement) in `for' and `while' // statements. Don't do anything for template instantiations, this just adds // noise. if (NumElts != 0 && !CurrentInstantiationScope && getCurCompoundScope().HasEmptyLoopBodies) { for (unsigned i = 0; i != NumElts - 1; ++i) DiagnoseEmptyLoopBody(Elts[i], Elts[i + 1]); } return CompoundStmt::Create(Context, Elts, L, R); } ExprResult Sema::ActOnCaseExpr(SourceLocation CaseLoc, ExprResult Val) { if (!Val.get()) return Val; if (DiagnoseUnexpandedParameterPack(Val.get())) return ExprError(); // If we're not inside a switch, let the 'case' statement handling diagnose // this. Just clean up after the expression as best we can. if (getCurFunction()->SwitchStack.empty()) return ActOnFinishFullExpr(Val.get(), Val.get()->getExprLoc(), false, getLangOpts().CPlusPlus11); Expr *CondExpr = getCurFunction()->SwitchStack.back().getPointer()->getCond(); if (!CondExpr) return ExprError(); QualType CondType = CondExpr->getType(); auto CheckAndFinish = [&](Expr *E) { if (CondType->isDependentType() || E->isTypeDependent()) return ExprResult(E); if (getLangOpts().CPlusPlus11) { // C++11 [stmt.switch]p2: the constant-expression shall be a converted // constant expression of the promoted type of the switch condition. llvm::APSInt TempVal; return CheckConvertedConstantExpression(E, CondType, TempVal, CCEK_CaseValue); } ExprResult ER = E; if (!E->isValueDependent()) ER = VerifyIntegerConstantExpression(E); if (!ER.isInvalid()) ER = DefaultLvalueConversion(ER.get()); if (!ER.isInvalid()) ER = ImpCastExprToType(ER.get(), CondType, CK_IntegralCast); if (!ER.isInvalid()) ER = ActOnFinishFullExpr(ER.get(), ER.get()->getExprLoc(), false); return ER; }; ExprResult Converted = CorrectDelayedTyposInExpr(Val, CheckAndFinish); if (Converted.get() == Val.get()) Converted = CheckAndFinish(Val.get()); return Converted; } StmtResult Sema::ActOnCaseStmt(SourceLocation CaseLoc, ExprResult LHSVal, SourceLocation DotDotDotLoc, ExprResult RHSVal, SourceLocation ColonLoc) { assert((LHSVal.isInvalid() || LHSVal.get()) && "missing LHS value"); assert((DotDotDotLoc.isInvalid() ? RHSVal.isUnset() : RHSVal.isInvalid() || RHSVal.get()) && "missing RHS value"); if (getCurFunction()->SwitchStack.empty()) { Diag(CaseLoc, diag::err_case_not_in_switch); return StmtError(); } if (LHSVal.isInvalid() || RHSVal.isInvalid()) { getCurFunction()->SwitchStack.back().setInt(true); return StmtError(); } auto *CS = CaseStmt::Create(Context, LHSVal.get(), RHSVal.get(), CaseLoc, DotDotDotLoc, ColonLoc); getCurFunction()->SwitchStack.back().getPointer()->addSwitchCase(CS); return CS; } /// ActOnCaseStmtBody - This installs a statement as the body of a case. void Sema::ActOnCaseStmtBody(Stmt *S, Stmt *SubStmt) { cast<CaseStmt>(S)->setSubStmt(SubStmt); } StmtResult Sema::ActOnDefaultStmt(SourceLocation DefaultLoc, SourceLocation ColonLoc, Stmt *SubStmt, Scope *CurScope) { if (getCurFunction()->SwitchStack.empty()) { Diag(DefaultLoc, diag::err_default_not_in_switch); return SubStmt; } DefaultStmt *DS = new (Context) DefaultStmt(DefaultLoc, ColonLoc, SubStmt); getCurFunction()->SwitchStack.back().getPointer()->addSwitchCase(DS); return DS; } StmtResult Sema::ActOnLabelStmt(SourceLocation IdentLoc, LabelDecl *TheDecl, SourceLocation ColonLoc, Stmt *SubStmt) { // If the label was multiply defined, reject it now. if (TheDecl->getStmt()) { Diag(IdentLoc, diag::err_redefinition_of_label) << TheDecl->getDeclName(); Diag(TheDecl->getLocation(), diag::note_previous_definition); return SubStmt; } // Otherwise, things are good. Fill in the declaration and return it. LabelStmt *LS = new (Context) LabelStmt(IdentLoc, TheDecl, SubStmt); TheDecl->setStmt(LS); if (!TheDecl->isGnuLocal()) { TheDecl->setLocStart(IdentLoc); if (!TheDecl->isMSAsmLabel()) { // Don't update the location of MS ASM labels. These will result in // a diagnostic, and changing the location here will mess that up. TheDecl->setLocation(IdentLoc); } } return LS; } StmtResult Sema::ActOnAttributedStmt(SourceLocation AttrLoc, ArrayRef<const Attr*> Attrs, Stmt *SubStmt) { // Fill in the declaration and return it. AttributedStmt *LS = AttributedStmt::Create(Context, AttrLoc, Attrs, SubStmt); return LS; } namespace { class CommaVisitor : public EvaluatedExprVisitor<CommaVisitor> { typedef EvaluatedExprVisitor<CommaVisitor> Inherited; Sema &SemaRef; public: CommaVisitor(Sema &SemaRef) : Inherited(SemaRef.Context), SemaRef(SemaRef) {} void VisitBinaryOperator(BinaryOperator *E) { if (E->getOpcode() == BO_Comma) SemaRef.DiagnoseCommaOperator(E->getLHS(), E->getExprLoc()); EvaluatedExprVisitor<CommaVisitor>::VisitBinaryOperator(E); } }; } StmtResult Sema::ActOnIfStmt(SourceLocation IfLoc, bool IsConstexpr, Stmt *InitStmt, ConditionResult Cond, Stmt *thenStmt, SourceLocation ElseLoc, Stmt *elseStmt) { if (Cond.isInvalid()) Cond = ConditionResult( *this, nullptr, MakeFullExpr(new (Context) OpaqueValueExpr(SourceLocation(), Context.BoolTy, VK_RValue), IfLoc), false); Expr *CondExpr = Cond.get().second; // Only call the CommaVisitor when not C89 due to differences in scope flags. if ((getLangOpts().C99 || getLangOpts().CPlusPlus) && !Diags.isIgnored(diag::warn_comma_operator, CondExpr->getExprLoc())) CommaVisitor(*this).Visit(CondExpr); if (!elseStmt) DiagnoseEmptyStmtBody(CondExpr->getEndLoc(), thenStmt, diag::warn_empty_if_body); return BuildIfStmt(IfLoc, IsConstexpr, InitStmt, Cond, thenStmt, ElseLoc, elseStmt); } StmtResult Sema::BuildIfStmt(SourceLocation IfLoc, bool IsConstexpr, Stmt *InitStmt, ConditionResult Cond, Stmt *thenStmt, SourceLocation ElseLoc, Stmt *elseStmt) { if (Cond.isInvalid()) return StmtError(); if (IsConstexpr || isa<ObjCAvailabilityCheckExpr>(Cond.get().second)) setFunctionHasBranchProtectedScope(); return IfStmt::Create(Context, IfLoc, IsConstexpr, InitStmt, Cond.get().first, Cond.get().second, thenStmt, ElseLoc, elseStmt); } namespace { struct CaseCompareFunctor { bool operator()(const std::pair<llvm::APSInt, CaseStmt*> &LHS, const llvm::APSInt &RHS) { return LHS.first < RHS; } bool operator()(const std::pair<llvm::APSInt, CaseStmt*> &LHS, const std::pair<llvm::APSInt, CaseStmt*> &RHS) { return LHS.first < RHS.first; } bool operator()(const llvm::APSInt &LHS, const std::pair<llvm::APSInt, CaseStmt*> &RHS) { return LHS < RHS.first; } }; } /// CmpCaseVals - Comparison predicate for sorting case values. /// static bool CmpCaseVals(const std::pair<llvm::APSInt, CaseStmt*>& lhs, const std::pair<llvm::APSInt, CaseStmt*>& rhs) { if (lhs.first < rhs.first) return true; if (lhs.first == rhs.first && lhs.second->getCaseLoc().getRawEncoding() < rhs.second->getCaseLoc().getRawEncoding()) return true; return false; } /// CmpEnumVals - Comparison predicate for sorting enumeration values. /// static bool CmpEnumVals(const std::pair<llvm::APSInt, EnumConstantDecl*>& lhs, const std::pair<llvm::APSInt, EnumConstantDecl*>& rhs) { return lhs.first < rhs.first; } /// EqEnumVals - Comparison preficate for uniqing enumeration values. /// static bool EqEnumVals(const std::pair<llvm::APSInt, EnumConstantDecl*>& lhs, const std::pair<llvm::APSInt, EnumConstantDecl*>& rhs) { return lhs.first == rhs.first; } /// GetTypeBeforeIntegralPromotion - Returns the pre-promotion type of /// potentially integral-promoted expression @p expr. static QualType GetTypeBeforeIntegralPromotion(const Expr *&E) { if (const auto *FE = dyn_cast<FullExpr>(E)) E = FE->getSubExpr(); while (const auto *ImpCast = dyn_cast<ImplicitCastExpr>(E)) { if (ImpCast->getCastKind() != CK_IntegralCast) break; E = ImpCast->getSubExpr(); } return E->getType(); } ExprResult Sema::CheckSwitchCondition(SourceLocation SwitchLoc, Expr *Cond) { class SwitchConvertDiagnoser : public ICEConvertDiagnoser { Expr *Cond; public: SwitchConvertDiagnoser(Expr *Cond) : ICEConvertDiagnoser(/*AllowScopedEnumerations*/true, false, true), Cond(Cond) {} SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc, QualType T) override { return S.Diag(Loc, diag::err_typecheck_statement_requires_integer) << T; } SemaDiagnosticBuilder diagnoseIncomplete( Sema &S, SourceLocation Loc, QualType T) override { return S.Diag(Loc, diag::err_switch_incomplete_class_type) << T << Cond->getSourceRange(); } SemaDiagnosticBuilder diagnoseExplicitConv( Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override { return S.Diag(Loc, diag::err_switch_explicit_conversion) << T << ConvTy; } SemaDiagnosticBuilder noteExplicitConv( Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override { return S.Diag(Conv->getLocation(), diag::note_switch_conversion) << ConvTy->isEnumeralType() << ConvTy; } SemaDiagnosticBuilder diagnoseAmbiguous(Sema &S, SourceLocation Loc, QualType T) override { return S.Diag(Loc, diag::err_switch_multiple_conversions) << T; } SemaDiagnosticBuilder noteAmbiguous( Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override { return S.Diag(Conv->getLocation(), diag::note_switch_conversion) << ConvTy->isEnumeralType() << ConvTy; } SemaDiagnosticBuilder diagnoseConversion( Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override { llvm_unreachable("conversion functions are permitted"); } } SwitchDiagnoser(Cond); ExprResult CondResult = PerformContextualImplicitConversion(SwitchLoc, Cond, SwitchDiagnoser); if (CondResult.isInvalid()) return ExprError(); // FIXME: PerformContextualImplicitConversion doesn't always tell us if it // failed and produced a diagnostic. Cond = CondResult.get(); if (!Cond->isTypeDependent() && !Cond->getType()->isIntegralOrEnumerationType()) return ExprError(); // C99 6.8.4.2p5 - Integer promotions are performed on the controlling expr. return UsualUnaryConversions(Cond); } StmtResult Sema::ActOnStartOfSwitchStmt(SourceLocation SwitchLoc, Stmt *InitStmt, ConditionResult Cond) { Expr *CondExpr = Cond.get().second; assert((Cond.isInvalid() || CondExpr) && "switch with no condition"); if (CondExpr && !CondExpr->isTypeDependent()) { // We have already converted the expression to an integral or enumeration // type, when we parsed the switch condition. If we don't have an // appropriate type now, enter the switch scope but remember that it's // invalid. assert(CondExpr->getType()->isIntegralOrEnumerationType() && "invalid condition type"); if (CondExpr->isKnownToHaveBooleanValue()) { // switch(bool_expr) {...} is often a programmer error, e.g. // switch(n && mask) { ... } // Doh - should be "n & mask". // One can always use an if statement instead of switch(bool_expr). Diag(SwitchLoc, diag::warn_bool_switch_condition) << CondExpr->getSourceRange(); } } setFunctionHasBranchIntoScope(); auto *SS = SwitchStmt::Create(Context, InitStmt, Cond.get().first, CondExpr); getCurFunction()->SwitchStack.push_back( FunctionScopeInfo::SwitchInfo(SS, false)); return SS; } static void AdjustAPSInt(llvm::APSInt &Val, unsigned BitWidth, bool IsSigned) { Val = Val.extOrTrunc(BitWidth); Val.setIsSigned(IsSigned); } /// Check the specified case value is in range for the given unpromoted switch /// type. static void checkCaseValue(Sema &S, SourceLocation Loc, const llvm::APSInt &Val, unsigned UnpromotedWidth, bool UnpromotedSign) { // In C++11 onwards, this is checked by the language rules. if (S.getLangOpts().CPlusPlus11) return; // If the case value was signed and negative and the switch expression is // unsigned, don't bother to warn: this is implementation-defined behavior. // FIXME: Introduce a second, default-ignored warning for this case? if (UnpromotedWidth < Val.getBitWidth()) { llvm::APSInt ConvVal(Val); AdjustAPSInt(ConvVal, UnpromotedWidth, UnpromotedSign); AdjustAPSInt(ConvVal, Val.getBitWidth(), Val.isSigned()); // FIXME: Use different diagnostics for overflow in conversion to promoted // type versus "switch expression cannot have this value". Use proper // IntRange checking rather than just looking at the unpromoted type here. if (ConvVal != Val) S.Diag(Loc, diag::warn_case_value_overflow) << Val.toString(10) << ConvVal.toString(10); } } typedef SmallVector<std::pair<llvm::APSInt, EnumConstantDecl*>, 64> EnumValsTy; /// Returns true if we should emit a diagnostic about this case expression not /// being a part of the enum used in the switch controlling expression. static bool ShouldDiagnoseSwitchCaseNotInEnum(const Sema &S, const EnumDecl *ED, const Expr *CaseExpr, EnumValsTy::iterator &EI, EnumValsTy::iterator &EIEnd, const llvm::APSInt &Val) { if (!ED->isClosed()) return false; if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(CaseExpr->IgnoreParenImpCasts())) { if (const VarDecl *VD = dyn_cast<VarDecl>(DRE->getDecl())) { QualType VarType = VD->getType(); QualType EnumType = S.Context.getTypeDeclType(ED); if (VD->hasGlobalStorage() && VarType.isConstQualified() && S.Context.hasSameUnqualifiedType(EnumType, VarType)) return false; } } if (ED->hasAttr<FlagEnumAttr>()) return !S.IsValueInFlagEnum(ED, Val, false); while (EI != EIEnd && EI->first < Val) EI++; if (EI != EIEnd && EI->first == Val) return false; return true; } static void checkEnumTypesInSwitchStmt(Sema &S, const Expr *Cond, const Expr *Case) { QualType CondType = Cond->getType(); QualType CaseType = Case->getType(); const EnumType *CondEnumType = CondType->getAs<EnumType>(); const EnumType *CaseEnumType = CaseType->getAs<EnumType>(); if (!CondEnumType || !CaseEnumType) return; // Ignore anonymous enums. if (!CondEnumType->getDecl()->getIdentifier() && !CondEnumType->getDecl()->getTypedefNameForAnonDecl()) return; if (!CaseEnumType->getDecl()->getIdentifier() && !CaseEnumType->getDecl()->getTypedefNameForAnonDecl()) return; if (S.Context.hasSameUnqualifiedType(CondType, CaseType)) return; S.Diag(Case->getExprLoc(), diag::warn_comparison_of_mixed_enum_types_switch) << CondType << CaseType << Cond->getSourceRange() << Case->getSourceRange(); } StmtResult Sema::ActOnFinishSwitchStmt(SourceLocation SwitchLoc, Stmt *Switch, Stmt *BodyStmt) { SwitchStmt *SS = cast<SwitchStmt>(Switch); bool CaseListIsIncomplete = getCurFunction()->SwitchStack.back().getInt(); assert(SS == getCurFunction()->SwitchStack.back().getPointer() && "switch stack missing push/pop!"); getCurFunction()->SwitchStack.pop_back(); if (!BodyStmt) return StmtError(); SS->setBody(BodyStmt, SwitchLoc); Expr *CondExpr = SS->getCond(); if (!CondExpr) return StmtError(); QualType CondType = CondExpr->getType(); // C++ 6.4.2.p2: // Integral promotions are performed (on the switch condition). // // A case value unrepresentable by the original switch condition // type (before the promotion) doesn't make sense, even when it can // be represented by the promoted type. Therefore we need to find // the pre-promotion type of the switch condition. const Expr *CondExprBeforePromotion = CondExpr; QualType CondTypeBeforePromotion = GetTypeBeforeIntegralPromotion(CondExprBeforePromotion); // Get the bitwidth of the switched-on value after promotions. We must // convert the integer case values to this width before comparison. bool HasDependentValue = CondExpr->isTypeDependent() || CondExpr->isValueDependent(); unsigned CondWidth = HasDependentValue ? 0 : Context.getIntWidth(CondType); bool CondIsSigned = CondType->isSignedIntegerOrEnumerationType(); // Get the width and signedness that the condition might actually have, for // warning purposes. // FIXME: Grab an IntRange for the condition rather than using the unpromoted // type. unsigned CondWidthBeforePromotion = HasDependentValue ? 0 : Context.getIntWidth(CondTypeBeforePromotion); bool CondIsSignedBeforePromotion = CondTypeBeforePromotion->isSignedIntegerOrEnumerationType(); // Accumulate all of the case values in a vector so that we can sort them // and detect duplicates. This vector contains the APInt for the case after // it has been converted to the condition type. typedef SmallVector<std::pair<llvm::APSInt, CaseStmt*>, 64> CaseValsTy; CaseValsTy CaseVals; // Keep track of any GNU case ranges we see. The APSInt is the low value. typedef std::vector<std::pair<llvm::APSInt, CaseStmt*> > CaseRangesTy; CaseRangesTy CaseRanges; DefaultStmt *TheDefaultStmt = nullptr; bool CaseListIsErroneous = false; for (SwitchCase *SC = SS->getSwitchCaseList(); SC && !HasDependentValue; SC = SC->getNextSwitchCase()) { if (DefaultStmt *DS = dyn_cast<DefaultStmt>(SC)) { if (TheDefaultStmt) { Diag(DS->getDefaultLoc(), diag::err_multiple_default_labels_defined); Diag(TheDefaultStmt->getDefaultLoc(), diag::note_duplicate_case_prev); // FIXME: Remove the default statement from the switch block so that // we'll return a valid AST. This requires recursing down the AST and // finding it, not something we are set up to do right now. For now, // just lop the entire switch stmt out of the AST. CaseListIsErroneous = true; } TheDefaultStmt = DS; } else { CaseStmt *CS = cast<CaseStmt>(SC); Expr *Lo = CS->getLHS(); if (Lo->isValueDependent()) { HasDependentValue = true; break; } // We already verified that the expression has a constant value; // get that value (prior to conversions). const Expr *LoBeforePromotion = Lo; GetTypeBeforeIntegralPromotion(LoBeforePromotion); llvm::APSInt LoVal = LoBeforePromotion->EvaluateKnownConstInt(Context); // Check the unconverted value is within the range of possible values of // the switch expression. checkCaseValue(*this, Lo->getBeginLoc(), LoVal, CondWidthBeforePromotion, CondIsSignedBeforePromotion); // FIXME: This duplicates the check performed for warn_not_in_enum below. checkEnumTypesInSwitchStmt(*this, CondExprBeforePromotion, LoBeforePromotion); // Convert the value to the same width/sign as the condition. AdjustAPSInt(LoVal, CondWidth, CondIsSigned); // If this is a case range, remember it in CaseRanges, otherwise CaseVals. if (CS->getRHS()) { if (CS->getRHS()->isValueDependent()) { HasDependentValue = true; break; } CaseRanges.push_back(std::make_pair(LoVal, CS)); } else CaseVals.push_back(std::make_pair(LoVal, CS)); } } if (!HasDependentValue) { // If we don't have a default statement, check whether the // condition is constant. llvm::APSInt ConstantCondValue; bool HasConstantCond = false; if (!TheDefaultStmt) { Expr::EvalResult Result; HasConstantCond = CondExpr->EvaluateAsInt(Result, Context, Expr::SE_AllowSideEffects); if (Result.Val.isInt()) ConstantCondValue = Result.Val.getInt(); assert(!HasConstantCond || (ConstantCondValue.getBitWidth() == CondWidth && ConstantCondValue.isSigned() == CondIsSigned)); } bool ShouldCheckConstantCond = HasConstantCond; // Sort all the scalar case values so we can easily detect duplicates. llvm::stable_sort(CaseVals, CmpCaseVals); if (!CaseVals.empty()) { for (unsigned i = 0, e = CaseVals.size(); i != e; ++i) { if (ShouldCheckConstantCond && CaseVals[i].first == ConstantCondValue) ShouldCheckConstantCond = false; if (i != 0 && CaseVals[i].first == CaseVals[i-1].first) { // If we have a duplicate, report it. // First, determine if either case value has a name StringRef PrevString, CurrString; Expr *PrevCase = CaseVals[i-1].second->getLHS()->IgnoreParenCasts(); Expr *CurrCase = CaseVals[i].second->getLHS()->IgnoreParenCasts(); if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(PrevCase)) { PrevString = DeclRef->getDecl()->getName(); } if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(CurrCase)) { CurrString = DeclRef->getDecl()->getName(); } SmallString<16> CaseValStr; CaseVals[i-1].first.toString(CaseValStr); if (PrevString == CurrString) Diag(CaseVals[i].second->getLHS()->getBeginLoc(), diag::err_duplicate_case) << (PrevString.empty() ? StringRef(CaseValStr) : PrevString); else Diag(CaseVals[i].second->getLHS()->getBeginLoc(), diag::err_duplicate_case_differing_expr) << (PrevString.empty() ? StringRef(CaseValStr) : PrevString) << (CurrString.empty() ? StringRef(CaseValStr) : CurrString) << CaseValStr; Diag(CaseVals[i - 1].second->getLHS()->getBeginLoc(), diag::note_duplicate_case_prev); // FIXME: We really want to remove the bogus case stmt from the // substmt, but we have no way to do this right now. CaseListIsErroneous = true; } } } // Detect duplicate case ranges, which usually don't exist at all in // the first place. if (!CaseRanges.empty()) { // Sort all the case ranges by their low value so we can easily detect // overlaps between ranges. llvm::stable_sort(CaseRanges); // Scan the ranges, computing the high values and removing empty ranges. std::vector<llvm::APSInt> HiVals; for (unsigned i = 0, e = CaseRanges.size(); i != e; ++i) { llvm::APSInt &LoVal = CaseRanges[i].first; CaseStmt *CR = CaseRanges[i].second; Expr *Hi = CR->getRHS(); const Expr *HiBeforePromotion = Hi; GetTypeBeforeIntegralPromotion(HiBeforePromotion); llvm::APSInt HiVal = HiBeforePromotion->EvaluateKnownConstInt(Context); // Check the unconverted value is within the range of possible values of // the switch expression. checkCaseValue(*this, Hi->getBeginLoc(), HiVal, CondWidthBeforePromotion, CondIsSignedBeforePromotion); // Convert the value to the same width/sign as the condition. AdjustAPSInt(HiVal, CondWidth, CondIsSigned); // If the low value is bigger than the high value, the case is empty. if (LoVal > HiVal) { Diag(CR->getLHS()->getBeginLoc(), diag::warn_case_empty_range) << SourceRange(CR->getLHS()->getBeginLoc(), Hi->getEndLoc()); CaseRanges.erase(CaseRanges.begin()+i); --i; --e; continue; } if (ShouldCheckConstantCond && LoVal <= ConstantCondValue && ConstantCondValue <= HiVal) ShouldCheckConstantCond = false; HiVals.push_back(HiVal); } // Rescan the ranges, looking for overlap with singleton values and other // ranges. Since the range list is sorted, we only need to compare case // ranges with their neighbors. for (unsigned i = 0, e = CaseRanges.size(); i != e; ++i) { llvm::APSInt &CRLo = CaseRanges[i].first; llvm::APSInt &CRHi = HiVals[i]; CaseStmt *CR = CaseRanges[i].second; // Check to see whether the case range overlaps with any // singleton cases. CaseStmt *OverlapStmt = nullptr; llvm::APSInt OverlapVal(32); // Find the smallest value >= the lower bound. If I is in the // case range, then we have overlap. CaseValsTy::iterator I = llvm::lower_bound(CaseVals, CRLo, CaseCompareFunctor()); if (I != CaseVals.end() && I->first < CRHi) { OverlapVal = I->first; // Found overlap with scalar. OverlapStmt = I->second; } // Find the smallest value bigger than the upper bound. I = std::upper_bound(I, CaseVals.end(), CRHi, CaseCompareFunctor()); if (I != CaseVals.begin() && (I-1)->first >= CRLo) { OverlapVal = (I-1)->first; // Found overlap with scalar. OverlapStmt = (I-1)->second; } // Check to see if this case stmt overlaps with the subsequent // case range. if (i && CRLo <= HiVals[i-1]) { OverlapVal = HiVals[i-1]; // Found overlap with range. OverlapStmt = CaseRanges[i-1].second; } if (OverlapStmt) { // If we have a duplicate, report it. Diag(CR->getLHS()->getBeginLoc(), diag::err_duplicate_case) << OverlapVal.toString(10); Diag(OverlapStmt->getLHS()->getBeginLoc(), diag::note_duplicate_case_prev); // FIXME: We really want to remove the bogus case stmt from the // substmt, but we have no way to do this right now. CaseListIsErroneous = true; } } } // Complain if we have a constant condition and we didn't find a match. if (!CaseListIsErroneous && !CaseListIsIncomplete && ShouldCheckConstantCond) { // TODO: it would be nice if we printed enums as enums, chars as // chars, etc. Diag(CondExpr->getExprLoc(), diag::warn_missing_case_for_condition) << ConstantCondValue.toString(10) << CondExpr->getSourceRange(); } // Check to see if switch is over an Enum and handles all of its // values. We only issue a warning if there is not 'default:', but // we still do the analysis to preserve this information in the AST // (which can be used by flow-based analyes). // const EnumType *ET = CondTypeBeforePromotion->getAs<EnumType>(); // If switch has default case, then ignore it. if (!CaseListIsErroneous && !CaseListIsIncomplete && !HasConstantCond && ET && ET->getDecl()->isCompleteDefinition()) { const EnumDecl *ED = ET->getDecl(); EnumValsTy EnumVals; // Gather all enum values, set their type and sort them, // allowing easier comparison with CaseVals. for (auto *EDI : ED->enumerators()) { llvm::APSInt Val = EDI->getInitVal(); AdjustAPSInt(Val, CondWidth, CondIsSigned); EnumVals.push_back(std::make_pair(Val, EDI)); } llvm::stable_sort(EnumVals, CmpEnumVals); auto EI = EnumVals.begin(), EIEnd = std::unique(EnumVals.begin(), EnumVals.end(), EqEnumVals); // See which case values aren't in enum. for (CaseValsTy::const_iterator CI = CaseVals.begin(); CI != CaseVals.end(); CI++) { Expr *CaseExpr = CI->second->getLHS(); if (ShouldDiagnoseSwitchCaseNotInEnum(*this, ED, CaseExpr, EI, EIEnd, CI->first)) Diag(CaseExpr->getExprLoc(), diag::warn_not_in_enum) << CondTypeBeforePromotion; } // See which of case ranges aren't in enum EI = EnumVals.begin(); for (CaseRangesTy::const_iterator RI = CaseRanges.begin(); RI != CaseRanges.end(); RI++) { Expr *CaseExpr = RI->second->getLHS(); if (ShouldDiagnoseSwitchCaseNotInEnum(*this, ED, CaseExpr, EI, EIEnd, RI->first)) Diag(CaseExpr->getExprLoc(), diag::warn_not_in_enum) << CondTypeBeforePromotion; llvm::APSInt Hi = RI->second->getRHS()->EvaluateKnownConstInt(Context); AdjustAPSInt(Hi, CondWidth, CondIsSigned); CaseExpr = RI->second->getRHS(); if (ShouldDiagnoseSwitchCaseNotInEnum(*this, ED, CaseExpr, EI, EIEnd, Hi)) Diag(CaseExpr->getExprLoc(), diag::warn_not_in_enum) << CondTypeBeforePromotion; } // Check which enum vals aren't in switch auto CI = CaseVals.begin(); auto RI = CaseRanges.begin(); bool hasCasesNotInSwitch = false; SmallVector<DeclarationName,8> UnhandledNames; for (EI = EnumVals.begin(); EI != EIEnd; EI++) { // Don't warn about omitted unavailable EnumConstantDecls. switch (EI->second->getAvailability()) { case AR_Deprecated: // Omitting a deprecated constant is ok; it should never materialize. case AR_Unavailable: continue; case AR_NotYetIntroduced: // Partially available enum constants should be present. Note that we // suppress -Wunguarded-availability diagnostics for such uses. case AR_Available: break; } if (EI->second->hasAttr<UnusedAttr>()) continue; // Drop unneeded case values while (CI != CaseVals.end() && CI->first < EI->first) CI++; if (CI != CaseVals.end() && CI->first == EI->first) continue; // Drop unneeded case ranges for (; RI != CaseRanges.end(); RI++) { llvm::APSInt Hi = RI->second->getRHS()->EvaluateKnownConstInt(Context); AdjustAPSInt(Hi, CondWidth, CondIsSigned); if (EI->first <= Hi) break; } if (RI == CaseRanges.end() || EI->first < RI->first) { hasCasesNotInSwitch = true; UnhandledNames.push_back(EI->second->getDeclName()); } } if (TheDefaultStmt && UnhandledNames.empty() && ED->isClosedNonFlag()) Diag(TheDefaultStmt->getDefaultLoc(), diag::warn_unreachable_default); // Produce a nice diagnostic if multiple values aren't handled. if (!UnhandledNames.empty()) { { DiagnosticBuilder DB = Diag(CondExpr->getExprLoc(), TheDefaultStmt ? diag::warn_def_missing_case : diag::warn_missing_case) << (int)UnhandledNames.size(); for (size_t I = 0, E = std::min(UnhandledNames.size(), (size_t)3); I != E; ++I) DB << UnhandledNames[I]; } auto DB = Diag(CondExpr->getExprLoc(), diag::note_fill_in_missing_cases); edit::fillInMissingSwitchEnumCases( Context, SS, ED, CurContext, [&](const FixItHint &Hint) { DB << Hint; }); } if (!hasCasesNotInSwitch) SS->setAllEnumCasesCovered(); } } if (BodyStmt) DiagnoseEmptyStmtBody(CondExpr->getEndLoc(), BodyStmt, diag::warn_empty_switch_body); // FIXME: If the case list was broken is some way, we don't have a good system // to patch it up. Instead, just return the whole substmt as broken. if (CaseListIsErroneous) return StmtError(); return SS; } void Sema::DiagnoseAssignmentEnum(QualType DstType, QualType SrcType, Expr *SrcExpr) { if (Diags.isIgnored(diag::warn_not_in_enum_assignment, SrcExpr->getExprLoc())) return; if (const EnumType *ET = DstType->getAs<EnumType>()) if (!Context.hasSameUnqualifiedType(SrcType, DstType) && SrcType->isIntegerType()) { if (!SrcExpr->isTypeDependent() && !SrcExpr->isValueDependent() && SrcExpr->isIntegerConstantExpr(Context)) { // Get the bitwidth of the enum value before promotions. unsigned DstWidth = Context.getIntWidth(DstType); bool DstIsSigned = DstType->isSignedIntegerOrEnumerationType(); llvm::APSInt RhsVal = SrcExpr->EvaluateKnownConstInt(Context); AdjustAPSInt(RhsVal, DstWidth, DstIsSigned); const EnumDecl *ED = ET->getDecl(); if (!ED->isClosed()) return; if (ED->hasAttr<FlagEnumAttr>()) { if (!IsValueInFlagEnum(ED, RhsVal, true)) Diag(SrcExpr->getExprLoc(), diag::warn_not_in_enum_assignment) << DstType.getUnqualifiedType(); } else { typedef SmallVector<std::pair<llvm::APSInt, EnumConstantDecl *>, 64> EnumValsTy; EnumValsTy EnumVals; // Gather all enum values, set their type and sort them, // allowing easier comparison with rhs constant. for (auto *EDI : ED->enumerators()) { llvm::APSInt Val = EDI->getInitVal(); AdjustAPSInt(Val, DstWidth, DstIsSigned); EnumVals.push_back(std::make_pair(Val, EDI)); } if (EnumVals.empty()) return; llvm::stable_sort(EnumVals, CmpEnumVals); EnumValsTy::iterator EIend = std::unique(EnumVals.begin(), EnumVals.end(), EqEnumVals); // See which values aren't in the enum. EnumValsTy::const_iterator EI = EnumVals.begin(); while (EI != EIend && EI->first < RhsVal) EI++; if (EI == EIend || EI->first != RhsVal) { Diag(SrcExpr->getExprLoc(), diag::warn_not_in_enum_assignment) << DstType.getUnqualifiedType(); } } } } } StmtResult Sema::ActOnWhileStmt(SourceLocation WhileLoc, ConditionResult Cond, Stmt *Body) { if (Cond.isInvalid()) return StmtError(); auto CondVal = Cond.get(); CheckBreakContinueBinding(CondVal.second); if (CondVal.second && !Diags.isIgnored(diag::warn_comma_operator, CondVal.second->getExprLoc())) CommaVisitor(*this).Visit(CondVal.second); if (isa<NullStmt>(Body)) getCurCompoundScope().setHasEmptyLoopBodies(); return WhileStmt::Create(Context, CondVal.first, CondVal.second, Body, WhileLoc); } StmtResult Sema::ActOnDoStmt(SourceLocation DoLoc, Stmt *Body, SourceLocation WhileLoc, SourceLocation CondLParen, Expr *Cond, SourceLocation CondRParen) { assert(Cond && "ActOnDoStmt(): missing expression"); CheckBreakContinueBinding(Cond); ExprResult CondResult = CheckBooleanCondition(DoLoc, Cond); if (CondResult.isInvalid()) return StmtError(); Cond = CondResult.get(); CondResult = ActOnFinishFullExpr(Cond, DoLoc, /*DiscardedValue*/ false); if (CondResult.isInvalid()) return StmtError(); Cond = CondResult.get(); // Only call the CommaVisitor for C89 due to differences in scope flags. if (Cond && !getLangOpts().C99 && !getLangOpts().CPlusPlus && !Diags.isIgnored(diag::warn_comma_operator, Cond->getExprLoc())) CommaVisitor(*this).Visit(Cond); return new (Context) DoStmt(Body, Cond, DoLoc, WhileLoc, CondRParen); } namespace { // Use SetVector since the diagnostic cares about the ordering of the Decl's. using DeclSetVector = llvm::SetVector<VarDecl *, llvm::SmallVector<VarDecl *, 8>, llvm::SmallPtrSet<VarDecl *, 8>>; // This visitor will traverse a conditional statement and store all // the evaluated decls into a vector. Simple is set to true if none // of the excluded constructs are used. class DeclExtractor : public EvaluatedExprVisitor<DeclExtractor> { DeclSetVector &Decls; SmallVectorImpl<SourceRange> &Ranges; bool Simple; public: typedef EvaluatedExprVisitor<DeclExtractor> Inherited; DeclExtractor(Sema &S, DeclSetVector &Decls, SmallVectorImpl<SourceRange> &Ranges) : Inherited(S.Context), Decls(Decls), Ranges(Ranges), Simple(true) {} bool isSimple() { return Simple; } // Replaces the method in EvaluatedExprVisitor. void VisitMemberExpr(MemberExpr* E) { Simple = false; } // Any Stmt not whitelisted will cause the condition to be marked complex. void VisitStmt(Stmt *S) { Simple = false; } void VisitBinaryOperator(BinaryOperator *E) { Visit(E->getLHS()); Visit(E->getRHS()); } void VisitCastExpr(CastExpr *E) { Visit(E->getSubExpr()); } void VisitUnaryOperator(UnaryOperator *E) { // Skip checking conditionals with derefernces. if (E->getOpcode() == UO_Deref) Simple = false; else Visit(E->getSubExpr()); } void VisitConditionalOperator(ConditionalOperator *E) { Visit(E->getCond()); Visit(E->getTrueExpr()); Visit(E->getFalseExpr()); } void VisitParenExpr(ParenExpr *E) { Visit(E->getSubExpr()); } void VisitBinaryConditionalOperator(BinaryConditionalOperator *E) { Visit(E->getOpaqueValue()->getSourceExpr()); Visit(E->getFalseExpr()); } void VisitIntegerLiteral(IntegerLiteral *E) { } void VisitFloatingLiteral(FloatingLiteral *E) { } void VisitCXXBoolLiteralExpr(CXXBoolLiteralExpr *E) { } void VisitCharacterLiteral(CharacterLiteral *E) { } void VisitGNUNullExpr(GNUNullExpr *E) { } void VisitImaginaryLiteral(ImaginaryLiteral *E) { } void VisitDeclRefExpr(DeclRefExpr *E) { VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()); if (!VD) { // Don't allow unhandled Decl types. Simple = false; return; } Ranges.push_back(E->getSourceRange()); Decls.insert(VD); } }; // end class DeclExtractor // DeclMatcher checks to see if the decls are used in a non-evaluated // context. class DeclMatcher : public EvaluatedExprVisitor<DeclMatcher> { DeclSetVector &Decls; bool FoundDecl; public: typedef EvaluatedExprVisitor<DeclMatcher> Inherited; DeclMatcher(Sema &S, DeclSetVector &Decls, Stmt *Statement) : Inherited(S.Context), Decls(Decls), FoundDecl(false) { if (!Statement) return; Visit(Statement); } void VisitReturnStmt(ReturnStmt *S) { FoundDecl = true; } void VisitBreakStmt(BreakStmt *S) { FoundDecl = true; } void VisitGotoStmt(GotoStmt *S) { FoundDecl = true; } void VisitCastExpr(CastExpr *E) { if (E->getCastKind() == CK_LValueToRValue) CheckLValueToRValueCast(E->getSubExpr()); else Visit(E->getSubExpr()); } void CheckLValueToRValueCast(Expr *E) { E = E->IgnoreParenImpCasts(); if (isa<DeclRefExpr>(E)) { return; } if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) { Visit(CO->getCond()); CheckLValueToRValueCast(CO->getTrueExpr()); CheckLValueToRValueCast(CO->getFalseExpr()); return; } if (BinaryConditionalOperator *BCO = dyn_cast<BinaryConditionalOperator>(E)) { CheckLValueToRValueCast(BCO->getOpaqueValue()->getSourceExpr()); CheckLValueToRValueCast(BCO->getFalseExpr()); return; } Visit(E); } void VisitDeclRefExpr(DeclRefExpr *E) { if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl())) if (Decls.count(VD)) FoundDecl = true; } void VisitPseudoObjectExpr(PseudoObjectExpr *POE) { // Only need to visit the semantics for POE. // SyntaticForm doesn't really use the Decal. for (auto *S : POE->semantics()) { if (auto *OVE = dyn_cast<OpaqueValueExpr>(S)) // Look past the OVE into the expression it binds. Visit(OVE->getSourceExpr()); else Visit(S); } } bool FoundDeclInUse() { return FoundDecl; } }; // end class DeclMatcher void CheckForLoopConditionalStatement(Sema &S, Expr *Second, Expr *Third, Stmt *Body) { // Condition is empty if (!Second) return; if (S.Diags.isIgnored(diag::warn_variables_not_in_loop_body, Second->getBeginLoc())) return; PartialDiagnostic PDiag = S.PDiag(diag::warn_variables_not_in_loop_body); DeclSetVector Decls; SmallVector<SourceRange, 10> Ranges; DeclExtractor DE(S, Decls, Ranges); DE.Visit(Second); // Don't analyze complex conditionals. if (!DE.isSimple()) return; // No decls found. if (Decls.size() == 0) return; // Don't warn on volatile, static, or global variables. for (auto *VD : Decls) if (VD->getType().isVolatileQualified() || VD->hasGlobalStorage()) return; if (DeclMatcher(S, Decls, Second).FoundDeclInUse() || DeclMatcher(S, Decls, Third).FoundDeclInUse() || DeclMatcher(S, Decls, Body).FoundDeclInUse()) return; // Load decl names into diagnostic. if (Decls.size() > 4) { PDiag << 0; } else { PDiag << (unsigned)Decls.size(); for (auto *VD : Decls) PDiag << VD->getDeclName(); } for (auto Range : Ranges) PDiag << Range; S.Diag(Ranges.begin()->getBegin(), PDiag); } // If Statement is an incemement or decrement, return true and sets the // variables Increment and DRE. bool ProcessIterationStmt(Sema &S, Stmt* Statement, bool &Increment, DeclRefExpr *&DRE) { if (auto Cleanups = dyn_cast<ExprWithCleanups>(Statement)) if (!Cleanups->cleanupsHaveSideEffects()) Statement = Cleanups->getSubExpr(); if (UnaryOperator *UO = dyn_cast<UnaryOperator>(Statement)) { switch (UO->getOpcode()) { default: return false; case UO_PostInc: case UO_PreInc: Increment = true; break; case UO_PostDec: case UO_PreDec: Increment = false; break; } DRE = dyn_cast<DeclRefExpr>(UO->getSubExpr()); return DRE; } if (CXXOperatorCallExpr *Call = dyn_cast<CXXOperatorCallExpr>(Statement)) { FunctionDecl *FD = Call->getDirectCallee(); if (!FD || !FD->isOverloadedOperator()) return false; switch (FD->getOverloadedOperator()) { default: return false; case OO_PlusPlus: Increment = true; break; case OO_MinusMinus: Increment = false; break; } DRE = dyn_cast<DeclRefExpr>(Call->getArg(0)); return DRE; } return false; } // A visitor to determine if a continue or break statement is a // subexpression. class BreakContinueFinder : public ConstEvaluatedExprVisitor<BreakContinueFinder> { SourceLocation BreakLoc; SourceLocation ContinueLoc; bool InSwitch = false; public: BreakContinueFinder(Sema &S, const Stmt* Body) : Inherited(S.Context) { Visit(Body); } typedef ConstEvaluatedExprVisitor<BreakContinueFinder> Inherited; void VisitContinueStmt(const ContinueStmt* E) { ContinueLoc = E->getContinueLoc(); } void VisitBreakStmt(const BreakStmt* E) { if (!InSwitch) BreakLoc = E->getBreakLoc(); } void VisitSwitchStmt(const SwitchStmt* S) { if (const Stmt *Init = S->getInit()) Visit(Init); if (const Stmt *CondVar = S->getConditionVariableDeclStmt()) Visit(CondVar); if (const Stmt *Cond = S->getCond()) Visit(Cond); // Don't return break statements from the body of a switch. InSwitch = true; if (const Stmt *Body = S->getBody()) Visit(Body); InSwitch = false; } void VisitForStmt(const ForStmt *S) { // Only visit the init statement of a for loop; the body // has a different break/continue scope. if (const Stmt *Init = S->getInit()) Visit(Init); } void VisitWhileStmt(const WhileStmt *) { // Do nothing; the children of a while loop have a different // break/continue scope. } void VisitDoStmt(const DoStmt *) { // Do nothing; the children of a while loop have a different // break/continue scope. } void VisitCXXForRangeStmt(const CXXForRangeStmt *S) { // Only visit the initialization of a for loop; the body // has a different break/continue scope. if (const Stmt *Init = S->getInit()) Visit(Init); if (const Stmt *Range = S->getRangeStmt()) Visit(Range); if (const Stmt *Begin = S->getBeginStmt()) Visit(Begin); if (const Stmt *End = S->getEndStmt()) Visit(End); } void VisitObjCForCollectionStmt(const ObjCForCollectionStmt *S) { // Only visit the initialization of a for loop; the body // has a different break/continue scope. if (const Stmt *Element = S->getElement()) Visit(Element); if (const Stmt *Collection = S->getCollection()) Visit(Collection); } bool ContinueFound() { return ContinueLoc.isValid(); } bool BreakFound() { return BreakLoc.isValid(); } SourceLocation GetContinueLoc() { return ContinueLoc; } SourceLocation GetBreakLoc() { return BreakLoc; } }; // end class BreakContinueFinder // Emit a warning when a loop increment/decrement appears twice per loop // iteration. The conditions which trigger this warning are: // 1) The last statement in the loop body and the third expression in the // for loop are both increment or both decrement of the same variable // 2) No continue statements in the loop body. void CheckForRedundantIteration(Sema &S, Expr *Third, Stmt *Body) { // Return when there is nothing to check. if (!Body || !Third) return; if (S.Diags.isIgnored(diag::warn_redundant_loop_iteration, Third->getBeginLoc())) return; // Get the last statement from the loop body. CompoundStmt *CS = dyn_cast<CompoundStmt>(Body); if (!CS || CS->body_empty()) return; Stmt *LastStmt = CS->body_back(); if (!LastStmt) return; bool LoopIncrement, LastIncrement; DeclRefExpr *LoopDRE, *LastDRE; if (!ProcessIterationStmt(S, Third, LoopIncrement, LoopDRE)) return; if (!ProcessIterationStmt(S, LastStmt, LastIncrement, LastDRE)) return; // Check that the two statements are both increments or both decrements // on the same variable. if (LoopIncrement != LastIncrement || LoopDRE->getDecl() != LastDRE->getDecl()) return; if (BreakContinueFinder(S, Body).ContinueFound()) return; S.Diag(LastDRE->getLocation(), diag::warn_redundant_loop_iteration) << LastDRE->getDecl() << LastIncrement; S.Diag(LoopDRE->getLocation(), diag::note_loop_iteration_here) << LoopIncrement; } } // end namespace void Sema::CheckBreakContinueBinding(Expr *E) { if (!E || getLangOpts().CPlusPlus) return; BreakContinueFinder BCFinder(*this, E); Scope *BreakParent = CurScope->getBreakParent(); if (BCFinder.BreakFound() && BreakParent) { if (BreakParent->getFlags() & Scope::SwitchScope) { Diag(BCFinder.GetBreakLoc(), diag::warn_break_binds_to_switch); } else { Diag(BCFinder.GetBreakLoc(), diag::warn_loop_ctrl_binds_to_inner) << "break"; } } else if (BCFinder.ContinueFound() && CurScope->getContinueParent()) { Diag(BCFinder.GetContinueLoc(), diag::warn_loop_ctrl_binds_to_inner) << "continue"; } } StmtResult Sema::ActOnForStmt(SourceLocation ForLoc, SourceLocation LParenLoc, Stmt *First, ConditionResult Second, FullExprArg third, SourceLocation RParenLoc, Stmt *Body) { if (Second.isInvalid()) return StmtError(); if (!getLangOpts().CPlusPlus) { if (DeclStmt *DS = dyn_cast_or_null<DeclStmt>(First)) { // C99 6.8.5p3: The declaration part of a 'for' statement shall only // declare identifiers for objects having storage class 'auto' or // 'register'. for (auto *DI : DS->decls()) { VarDecl *VD = dyn_cast<VarDecl>(DI); if (VD && VD->isLocalVarDecl() && !VD->hasLocalStorage()) VD = nullptr; if (!VD) { Diag(DI->getLocation(), diag::err_non_local_variable_decl_in_for); DI->setInvalidDecl(); } } } } CheckBreakContinueBinding(Second.get().second); CheckBreakContinueBinding(third.get()); if (!Second.get().first) CheckForLoopConditionalStatement(*this, Second.get().second, third.get(), Body); CheckForRedundantIteration(*this, third.get(), Body); if (Second.get().second && !Diags.isIgnored(diag::warn_comma_operator, Second.get().second->getExprLoc())) CommaVisitor(*this).Visit(Second.get().second); Expr *Third = third.release().getAs<Expr>(); if (isa<NullStmt>(Body)) getCurCompoundScope().setHasEmptyLoopBodies(); return new (Context) ForStmt(Context, First, Second.get().second, Second.get().first, Third, Body, ForLoc, LParenLoc, RParenLoc); } /// In an Objective C collection iteration statement: /// for (x in y) /// x can be an arbitrary l-value expression. Bind it up as a /// full-expression. StmtResult Sema::ActOnForEachLValueExpr(Expr *E) { // Reduce placeholder expressions here. Note that this rejects the // use of pseudo-object l-values in this position. ExprResult result = CheckPlaceholderExpr(E); if (result.isInvalid()) return StmtError(); E = result.get(); ExprResult FullExpr = ActOnFinishFullExpr(E, /*DiscardedValue*/ false); if (FullExpr.isInvalid()) return StmtError(); return StmtResult(static_cast<Stmt*>(FullExpr.get())); } ExprResult Sema::CheckObjCForCollectionOperand(SourceLocation forLoc, Expr *collection) { if (!collection) return ExprError(); ExprResult result = CorrectDelayedTyposInExpr(collection); if (!result.isUsable()) return ExprError(); collection = result.get(); // Bail out early if we've got a type-dependent expression. if (collection->isTypeDependent()) return collection; // Perform normal l-value conversion. result = DefaultFunctionArrayLvalueConversion(collection); if (result.isInvalid()) return ExprError(); collection = result.get(); // The operand needs to have object-pointer type. // TODO: should we do a contextual conversion? const ObjCObjectPointerType *pointerType = collection->getType()->getAs<ObjCObjectPointerType>(); if (!pointerType) return Diag(forLoc, diag::err_collection_expr_type) << collection->getType() << collection->getSourceRange(); // Check that the operand provides // - countByEnumeratingWithState:objects:count: const ObjCObjectType *objectType = pointerType->getObjectType(); ObjCInterfaceDecl *iface = objectType->getInterface(); // If we have a forward-declared type, we can't do this check. // Under ARC, it is an error not to have a forward-declared class. if (iface && (getLangOpts().ObjCAutoRefCount ? RequireCompleteType(forLoc, QualType(objectType, 0), diag::err_arc_collection_forward, collection) : !isCompleteType(forLoc, QualType(objectType, 0)))) { // Otherwise, if we have any useful type information, check that // the type declares the appropriate method. } else if (iface || !objectType->qual_empty()) { IdentifierInfo *selectorIdents[] = { &Context.Idents.get("countByEnumeratingWithState"), &Context.Idents.get("objects"), &Context.Idents.get("count") }; Selector selector = Context.Selectors.getSelector(3, &selectorIdents[0]); ObjCMethodDecl *method = nullptr; // If there's an interface, look in both the public and private APIs. if (iface) { method = iface->lookupInstanceMethod(selector); if (!method) method = iface->lookupPrivateMethod(selector); } // Also check protocol qualifiers. if (!method) method = LookupMethodInQualifiedType(selector, pointerType, /*instance*/ true); // If we didn't find it anywhere, give up. if (!method) { Diag(forLoc, diag::warn_collection_expr_type) << collection->getType() << selector << collection->getSourceRange(); } // TODO: check for an incompatible signature? } // Wrap up any cleanups in the expression. return collection; } StmtResult Sema::ActOnObjCForCollectionStmt(SourceLocation ForLoc, Stmt *First, Expr *collection, SourceLocation RParenLoc) { setFunctionHasBranchProtectedScope(); ExprResult CollectionExprResult = CheckObjCForCollectionOperand(ForLoc, collection); if (First) { QualType FirstType; if (DeclStmt *DS = dyn_cast<DeclStmt>(First)) { if (!DS->isSingleDecl()) return StmtError(Diag((*DS->decl_begin())->getLocation(), diag::err_toomany_element_decls)); VarDecl *D = dyn_cast<VarDecl>(DS->getSingleDecl()); if (!D || D->isInvalidDecl()) return StmtError(); FirstType = D->getType(); // C99 6.8.5p3: The declaration part of a 'for' statement shall only // declare identifiers for objects having storage class 'auto' or // 'register'. if (!D->hasLocalStorage()) return StmtError(Diag(D->getLocation(), diag::err_non_local_variable_decl_in_for)); // If the type contained 'auto', deduce the 'auto' to 'id'. if (FirstType->getContainedAutoType()) { OpaqueValueExpr OpaqueId(D->getLocation(), Context.getObjCIdType(), VK_RValue); Expr *DeducedInit = &OpaqueId; if (DeduceAutoType(D->getTypeSourceInfo(), DeducedInit, FirstType) == DAR_Failed) DiagnoseAutoDeductionFailure(D, DeducedInit); if (FirstType.isNull()) { D->setInvalidDecl(); return StmtError(); } D->setType(FirstType); if (!inTemplateInstantiation()) { SourceLocation Loc = D->getTypeSourceInfo()->getTypeLoc().getBeginLoc(); Diag(Loc, diag::warn_auto_var_is_id) << D->getDeclName(); } } } else { Expr *FirstE = cast<Expr>(First); if (!FirstE->isTypeDependent() && !FirstE->isLValue()) return StmtError( Diag(First->getBeginLoc(), diag::err_selector_element_not_lvalue) << First->getSourceRange()); FirstType = static_cast<Expr*>(First)->getType(); if (FirstType.isConstQualified()) Diag(ForLoc, diag::err_selector_element_const_type) << FirstType << First->getSourceRange(); } if (!FirstType->isDependentType() && !FirstType->isObjCObjectPointerType() && !FirstType->isBlockPointerType()) return StmtError(Diag(ForLoc, diag::err_selector_element_type) << FirstType << First->getSourceRange()); } if (CollectionExprResult.isInvalid()) return StmtError(); CollectionExprResult = ActOnFinishFullExpr(CollectionExprResult.get(), /*DiscardedValue*/ false); if (CollectionExprResult.isInvalid()) return StmtError(); return new (Context) ObjCForCollectionStmt(First, CollectionExprResult.get(), nullptr, ForLoc, RParenLoc); } /// Finish building a variable declaration for a for-range statement. /// \return true if an error occurs. static bool FinishForRangeVarDecl(Sema &SemaRef, VarDecl *Decl, Expr *Init, SourceLocation Loc, int DiagID) { if (Decl->getType()->isUndeducedType()) { ExprResult Res = SemaRef.CorrectDelayedTyposInExpr(Init); if (!Res.isUsable()) { Decl->setInvalidDecl(); return true; } Init = Res.get(); } // Deduce the type for the iterator variable now rather than leaving it to // AddInitializerToDecl, so we can produce a more suitable diagnostic. QualType InitType; if ((!isa<InitListExpr>(Init) && Init->getType()->isVoidType()) || SemaRef.DeduceAutoType(Decl->getTypeSourceInfo(), Init, InitType) == Sema::DAR_Failed) SemaRef.Diag(Loc, DiagID) << Init->getType(); if (InitType.isNull()) { Decl->setInvalidDecl(); return true; } Decl->setType(InitType); // In ARC, infer lifetime. // FIXME: ARC may want to turn this into 'const __unsafe_unretained' if // we're doing the equivalent of fast iteration. if (SemaRef.getLangOpts().ObjCAutoRefCount && SemaRef.inferObjCARCLifetime(Decl)) Decl->setInvalidDecl(); SemaRef.AddInitializerToDecl(Decl, Init, /*DirectInit=*/false); SemaRef.FinalizeDeclaration(Decl); SemaRef.CurContext->addHiddenDecl(Decl); return false; } namespace { // An enum to represent whether something is dealing with a call to begin() // or a call to end() in a range-based for loop. enum BeginEndFunction { BEF_begin, BEF_end }; /// Produce a note indicating which begin/end function was implicitly called /// by a C++11 for-range statement. This is often not obvious from the code, /// nor from the diagnostics produced when analysing the implicit expressions /// required in a for-range statement. void NoteForRangeBeginEndFunction(Sema &SemaRef, Expr *E, BeginEndFunction BEF) { CallExpr *CE = dyn_cast<CallExpr>(E); if (!CE) return; FunctionDecl *D = dyn_cast<FunctionDecl>(CE->getCalleeDecl()); if (!D) return; SourceLocation Loc = D->getLocation(); std::string Description; bool IsTemplate = false; if (FunctionTemplateDecl *FunTmpl = D->getPrimaryTemplate()) { Description = SemaRef.getTemplateArgumentBindingsText( FunTmpl->getTemplateParameters(), *D->getTemplateSpecializationArgs()); IsTemplate = true; } SemaRef.Diag(Loc, diag::note_for_range_begin_end) << BEF << IsTemplate << Description << E->getType(); } /// Build a variable declaration for a for-range statement. VarDecl *BuildForRangeVarDecl(Sema &SemaRef, SourceLocation Loc, QualType Type, StringRef Name) { DeclContext *DC = SemaRef.CurContext; IdentifierInfo *II = &SemaRef.PP.getIdentifierTable().get(Name); TypeSourceInfo *TInfo = SemaRef.Context.getTrivialTypeSourceInfo(Type, Loc); VarDecl *Decl = VarDecl::Create(SemaRef.Context, DC, Loc, Loc, II, Type, TInfo, SC_None); Decl->setImplicit(); return Decl; } } static bool ObjCEnumerationCollection(Expr *Collection) { return !Collection->isTypeDependent() && Collection->getType()->getAs<ObjCObjectPointerType>() != nullptr; } /// ActOnCXXForRangeStmt - Check and build a C++11 for-range statement. /// /// C++11 [stmt.ranged]: /// A range-based for statement is equivalent to /// /// { /// auto && __range = range-init; /// for ( auto __begin = begin-expr, /// __end = end-expr; /// __begin != __end; /// ++__begin ) { /// for-range-declaration = *__begin; /// statement /// } /// } /// /// The body of the loop is not available yet, since it cannot be analysed until /// we have determined the type of the for-range-declaration. StmtResult Sema::ActOnCXXForRangeStmt(Scope *S, SourceLocation ForLoc, SourceLocation CoawaitLoc, Stmt *InitStmt, Stmt *First, SourceLocation ColonLoc, Expr *Range, SourceLocation RParenLoc, BuildForRangeKind Kind) { if (!First) return StmtError(); if (Range && ObjCEnumerationCollection(Range)) { // FIXME: Support init-statements in Objective-C++20 ranged for statement. if (InitStmt) return Diag(InitStmt->getBeginLoc(), diag::err_objc_for_range_init_stmt) << InitStmt->getSourceRange(); return ActOnObjCForCollectionStmt(ForLoc, First, Range, RParenLoc); } DeclStmt *DS = dyn_cast<DeclStmt>(First); assert(DS && "first part of for range not a decl stmt"); if (!DS->isSingleDecl()) { Diag(DS->getBeginLoc(), diag::err_type_defined_in_for_range); return StmtError(); } Decl *LoopVar = DS->getSingleDecl(); if (LoopVar->isInvalidDecl() || !Range || DiagnoseUnexpandedParameterPack(Range, UPPC_Expression)) { LoopVar->setInvalidDecl(); return StmtError(); } // Build the coroutine state immediately and not later during template // instantiation if (!CoawaitLoc.isInvalid()) { if (!ActOnCoroutineBodyStart(S, CoawaitLoc, "co_await")) return StmtError(); } // Build auto && __range = range-init // Divide by 2, since the variables are in the inner scope (loop body). const auto DepthStr = std::to_string(S->getDepth() / 2); SourceLocation RangeLoc = Range->getBeginLoc(); VarDecl *RangeVar = BuildForRangeVarDecl(*this, RangeLoc, Context.getAutoRRefDeductType(), std::string("__range") + DepthStr); if (FinishForRangeVarDecl(*this, RangeVar, Range, RangeLoc, diag::err_for_range_deduction_failure)) { LoopVar->setInvalidDecl(); return StmtError(); } // Claim the type doesn't contain auto: we've already done the checking. DeclGroupPtrTy RangeGroup = BuildDeclaratorGroup(MutableArrayRef<Decl *>((Decl **)&RangeVar, 1)); StmtResult RangeDecl = ActOnDeclStmt(RangeGroup, RangeLoc, RangeLoc); if (RangeDecl.isInvalid()) { LoopVar->setInvalidDecl(); return StmtError(); } return BuildCXXForRangeStmt( ForLoc, CoawaitLoc, InitStmt, ColonLoc, RangeDecl.get(), /*BeginStmt=*/nullptr, /*EndStmt=*/nullptr, /*Cond=*/nullptr, /*Inc=*/nullptr, DS, RParenLoc, Kind); } /// Create the initialization, compare, and increment steps for /// the range-based for loop expression. /// This function does not handle array-based for loops, /// which are created in Sema::BuildCXXForRangeStmt. /// /// \returns a ForRangeStatus indicating success or what kind of error occurred. /// BeginExpr and EndExpr are set and FRS_Success is returned on success; /// CandidateSet and BEF are set and some non-success value is returned on /// failure. static Sema::ForRangeStatus BuildNonArrayForRange(Sema &SemaRef, Expr *BeginRange, Expr *EndRange, QualType RangeType, VarDecl *BeginVar, VarDecl *EndVar, SourceLocation ColonLoc, SourceLocation CoawaitLoc, OverloadCandidateSet *CandidateSet, ExprResult *BeginExpr, ExprResult *EndExpr, BeginEndFunction *BEF) { DeclarationNameInfo BeginNameInfo( &SemaRef.PP.getIdentifierTable().get("begin"), ColonLoc); DeclarationNameInfo EndNameInfo(&SemaRef.PP.getIdentifierTable().get("end"), ColonLoc); LookupResult BeginMemberLookup(SemaRef, BeginNameInfo, Sema::LookupMemberName); LookupResult EndMemberLookup(SemaRef, EndNameInfo, Sema::LookupMemberName); auto BuildBegin = [&] { *BEF = BEF_begin; Sema::ForRangeStatus RangeStatus = SemaRef.BuildForRangeBeginEndCall(ColonLoc, ColonLoc, BeginNameInfo, BeginMemberLookup, CandidateSet, BeginRange, BeginExpr); if (RangeStatus != Sema::FRS_Success) { if (RangeStatus == Sema::FRS_DiagnosticIssued) SemaRef.Diag(BeginRange->getBeginLoc(), diag::note_in_for_range) << ColonLoc << BEF_begin << BeginRange->getType(); return RangeStatus; } if (!CoawaitLoc.isInvalid()) { // FIXME: getCurScope() should not be used during template instantiation. // We should pick up the set of unqualified lookup results for operator // co_await during the initial parse. *BeginExpr = SemaRef.ActOnCoawaitExpr(SemaRef.getCurScope(), ColonLoc, BeginExpr->get()); if (BeginExpr->isInvalid()) return Sema::FRS_DiagnosticIssued; } if (FinishForRangeVarDecl(SemaRef, BeginVar, BeginExpr->get(), ColonLoc, diag::err_for_range_iter_deduction_failure)) { NoteForRangeBeginEndFunction(SemaRef, BeginExpr->get(), *BEF); return Sema::FRS_DiagnosticIssued; } return Sema::FRS_Success; }; auto BuildEnd = [&] { *BEF = BEF_end; Sema::ForRangeStatus RangeStatus = SemaRef.BuildForRangeBeginEndCall(ColonLoc, ColonLoc, EndNameInfo, EndMemberLookup, CandidateSet, EndRange, EndExpr); if (RangeStatus != Sema::FRS_Success) { if (RangeStatus == Sema::FRS_DiagnosticIssued) SemaRef.Diag(EndRange->getBeginLoc(), diag::note_in_for_range) << ColonLoc << BEF_end << EndRange->getType(); return RangeStatus; } if (FinishForRangeVarDecl(SemaRef, EndVar, EndExpr->get(), ColonLoc, diag::err_for_range_iter_deduction_failure)) { NoteForRangeBeginEndFunction(SemaRef, EndExpr->get(), *BEF); return Sema::FRS_DiagnosticIssued; } return Sema::FRS_Success; }; if (CXXRecordDecl *D = RangeType->getAsCXXRecordDecl()) { // - if _RangeT is a class type, the unqualified-ids begin and end are // looked up in the scope of class _RangeT as if by class member access // lookup (3.4.5), and if either (or both) finds at least one // declaration, begin-expr and end-expr are __range.begin() and // __range.end(), respectively; SemaRef.LookupQualifiedName(BeginMemberLookup, D); if (BeginMemberLookup.isAmbiguous()) return Sema::FRS_DiagnosticIssued; SemaRef.LookupQualifiedName(EndMemberLookup, D); if (EndMemberLookup.isAmbiguous()) return Sema::FRS_DiagnosticIssued; if (BeginMemberLookup.empty() != EndMemberLookup.empty()) { // Look up the non-member form of the member we didn't find, first. // This way we prefer a "no viable 'end'" diagnostic over a "i found // a 'begin' but ignored it because there was no member 'end'" // diagnostic. auto BuildNonmember = [&]( BeginEndFunction BEFFound, LookupResult &Found, llvm::function_ref<Sema::ForRangeStatus()> BuildFound, llvm::function_ref<Sema::ForRangeStatus()> BuildNotFound) { LookupResult OldFound = std::move(Found); Found.clear(); if (Sema::ForRangeStatus Result = BuildNotFound()) return Result; switch (BuildFound()) { case Sema::FRS_Success: return Sema::FRS_Success; case Sema::FRS_NoViableFunction: CandidateSet->NoteCandidates( PartialDiagnosticAt(BeginRange->getBeginLoc(), SemaRef.PDiag(diag::err_for_range_invalid) << BeginRange->getType() << BEFFound), SemaRef, OCD_AllCandidates, BeginRange); LLVM_FALLTHROUGH; case Sema::FRS_DiagnosticIssued: for (NamedDecl *D : OldFound) { SemaRef.Diag(D->getLocation(), diag::note_for_range_member_begin_end_ignored) << BeginRange->getType() << BEFFound; } return Sema::FRS_DiagnosticIssued; } llvm_unreachable("unexpected ForRangeStatus"); }; if (BeginMemberLookup.empty()) return BuildNonmember(BEF_end, EndMemberLookup, BuildEnd, BuildBegin); return BuildNonmember(BEF_begin, BeginMemberLookup, BuildBegin, BuildEnd); } } else { // - otherwise, begin-expr and end-expr are begin(__range) and // end(__range), respectively, where begin and end are looked up with // argument-dependent lookup (3.4.2). For the purposes of this name // lookup, namespace std is an associated namespace. } if (Sema::ForRangeStatus Result = BuildBegin()) return Result; return BuildEnd(); } /// Speculatively attempt to dereference an invalid range expression. /// If the attempt fails, this function will return a valid, null StmtResult /// and emit no diagnostics. static StmtResult RebuildForRangeWithDereference(Sema &SemaRef, Scope *S, SourceLocation ForLoc, SourceLocation CoawaitLoc, Stmt *InitStmt, Stmt *LoopVarDecl, SourceLocation ColonLoc, Expr *Range, SourceLocation RangeLoc, SourceLocation RParenLoc) { // Determine whether we can rebuild the for-range statement with a // dereferenced range expression. ExprResult AdjustedRange; { Sema::SFINAETrap Trap(SemaRef); AdjustedRange = SemaRef.BuildUnaryOp(S, RangeLoc, UO_Deref, Range); if (AdjustedRange.isInvalid()) return StmtResult(); StmtResult SR = SemaRef.ActOnCXXForRangeStmt( S, ForLoc, CoawaitLoc, InitStmt, LoopVarDecl, ColonLoc, AdjustedRange.get(), RParenLoc, Sema::BFRK_Check); if (SR.isInvalid()) return StmtResult(); } // The attempt to dereference worked well enough that it could produce a valid // loop. Produce a fixit, and rebuild the loop with diagnostics enabled, in // case there are any other (non-fatal) problems with it. SemaRef.Diag(RangeLoc, diag::err_for_range_dereference) << Range->getType() << FixItHint::CreateInsertion(RangeLoc, "*"); return SemaRef.ActOnCXXForRangeStmt( S, ForLoc, CoawaitLoc, InitStmt, LoopVarDecl, ColonLoc, AdjustedRange.get(), RParenLoc, Sema::BFRK_Rebuild); } namespace { /// RAII object to automatically invalidate a declaration if an error occurs. struct InvalidateOnErrorScope { InvalidateOnErrorScope(Sema &SemaRef, Decl *D, bool Enabled) : Trap(SemaRef.Diags), D(D), Enabled(Enabled) {} ~InvalidateOnErrorScope() { if (Enabled && Trap.hasErrorOccurred()) D->setInvalidDecl(); } DiagnosticErrorTrap Trap; Decl *D; bool Enabled; }; } /// BuildCXXForRangeStmt - Build or instantiate a C++11 for-range statement. StmtResult Sema::BuildCXXForRangeStmt(SourceLocation ForLoc, SourceLocation CoawaitLoc, Stmt *InitStmt, SourceLocation ColonLoc, Stmt *RangeDecl, Stmt *Begin, Stmt *End, Expr *Cond, Expr *Inc, Stmt *LoopVarDecl, SourceLocation RParenLoc, BuildForRangeKind Kind) { // FIXME: This should not be used during template instantiation. We should // pick up the set of unqualified lookup results for the != and + operators // in the initial parse. // // Testcase (accepts-invalid): // template<typename T> void f() { for (auto x : T()) {} } // namespace N { struct X { X begin(); X end(); int operator*(); }; } // bool operator!=(N::X, N::X); void operator++(N::X); // void g() { f<N::X>(); } Scope *S = getCurScope(); DeclStmt *RangeDS = cast<DeclStmt>(RangeDecl); VarDecl *RangeVar = cast<VarDecl>(RangeDS->getSingleDecl()); QualType RangeVarType = RangeVar->getType(); DeclStmt *LoopVarDS = cast<DeclStmt>(LoopVarDecl); VarDecl *LoopVar = cast<VarDecl>(LoopVarDS->getSingleDecl()); // If we hit any errors, mark the loop variable as invalid if its type // contains 'auto'. InvalidateOnErrorScope Invalidate(*this, LoopVar, LoopVar->getType()->isUndeducedType()); StmtResult BeginDeclStmt = Begin; StmtResult EndDeclStmt = End; ExprResult NotEqExpr = Cond, IncrExpr = Inc; if (RangeVarType->isDependentType()) { // The range is implicitly used as a placeholder when it is dependent. RangeVar->markUsed(Context); // Deduce any 'auto's in the loop variable as 'DependentTy'. We'll fill // them in properly when we instantiate the loop. if (!LoopVar->isInvalidDecl() && Kind != BFRK_Check) { if (auto *DD = dyn_cast<DecompositionDecl>(LoopVar)) for (auto *Binding : DD->bindings()) Binding->setType(Context.DependentTy); LoopVar->setType(SubstAutoType(LoopVar->getType(), Context.DependentTy)); } } else if (!BeginDeclStmt.get()) { SourceLocation RangeLoc = RangeVar->getLocation(); const QualType RangeVarNonRefType = RangeVarType.getNonReferenceType(); ExprResult BeginRangeRef = BuildDeclRefExpr(RangeVar, RangeVarNonRefType, VK_LValue, ColonLoc); if (BeginRangeRef.isInvalid()) return StmtError(); ExprResult EndRangeRef = BuildDeclRefExpr(RangeVar, RangeVarNonRefType, VK_LValue, ColonLoc); if (EndRangeRef.isInvalid()) return StmtError(); QualType AutoType = Context.getAutoDeductType(); Expr *Range = RangeVar->getInit(); if (!Range) return StmtError(); QualType RangeType = Range->getType(); if (RequireCompleteType(RangeLoc, RangeType, diag::err_for_range_incomplete_type)) return StmtError(); // Build auto __begin = begin-expr, __end = end-expr. // Divide by 2, since the variables are in the inner scope (loop body). const auto DepthStr = std::to_string(S->getDepth() / 2); VarDecl *BeginVar = BuildForRangeVarDecl(*this, ColonLoc, AutoType, std::string("__begin") + DepthStr); VarDecl *EndVar = BuildForRangeVarDecl(*this, ColonLoc, AutoType, std::string("__end") + DepthStr); // Build begin-expr and end-expr and attach to __begin and __end variables. ExprResult BeginExpr, EndExpr; if (const ArrayType *UnqAT = RangeType->getAsArrayTypeUnsafe()) { // - if _RangeT is an array type, begin-expr and end-expr are __range and // __range + __bound, respectively, where __bound is the array bound. If // _RangeT is an array of unknown size or an array of incomplete type, // the program is ill-formed; // begin-expr is __range. BeginExpr = BeginRangeRef; if (!CoawaitLoc.isInvalid()) { BeginExpr = ActOnCoawaitExpr(S, ColonLoc, BeginExpr.get()); if (BeginExpr.isInvalid()) return StmtError(); } if (FinishForRangeVarDecl(*this, BeginVar, BeginRangeRef.get(), ColonLoc, diag::err_for_range_iter_deduction_failure)) { NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin); return StmtError(); } // Find the array bound. ExprResult BoundExpr; if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(UnqAT)) BoundExpr = IntegerLiteral::Create( Context, CAT->getSize(), Context.getPointerDiffType(), RangeLoc); else if (const VariableArrayType *VAT = dyn_cast<VariableArrayType>(UnqAT)) { // For a variably modified type we can't just use the expression within // the array bounds, since we don't want that to be re-evaluated here. // Rather, we need to determine what it was when the array was first // created - so we resort to using sizeof(vla)/sizeof(element). // For e.g. // void f(int b) { // int vla[b]; // b = -1; <-- This should not affect the num of iterations below // for (int &c : vla) { .. } // } // FIXME: This results in codegen generating IR that recalculates the // run-time number of elements (as opposed to just using the IR Value // that corresponds to the run-time value of each bound that was // generated when the array was created.) If this proves too embarrassing // even for unoptimized IR, consider passing a magic-value/cookie to // codegen that then knows to simply use that initial llvm::Value (that // corresponds to the bound at time of array creation) within // getelementptr. But be prepared to pay the price of increasing a // customized form of coupling between the two components - which could // be hard to maintain as the codebase evolves. ExprResult SizeOfVLAExprR = ActOnUnaryExprOrTypeTraitExpr( EndVar->getLocation(), UETT_SizeOf, /*IsType=*/true, CreateParsedType(VAT->desugar(), Context.getTrivialTypeSourceInfo( VAT->desugar(), RangeLoc)) .getAsOpaquePtr(), EndVar->getSourceRange()); if (SizeOfVLAExprR.isInvalid()) return StmtError(); ExprResult SizeOfEachElementExprR = ActOnUnaryExprOrTypeTraitExpr( EndVar->getLocation(), UETT_SizeOf, /*IsType=*/true, CreateParsedType(VAT->desugar(), Context.getTrivialTypeSourceInfo( VAT->getElementType(), RangeLoc)) .getAsOpaquePtr(), EndVar->getSourceRange()); if (SizeOfEachElementExprR.isInvalid()) return StmtError(); BoundExpr = ActOnBinOp(S, EndVar->getLocation(), tok::slash, SizeOfVLAExprR.get(), SizeOfEachElementExprR.get()); if (BoundExpr.isInvalid()) return StmtError(); } else { // Can't be a DependentSizedArrayType or an IncompleteArrayType since // UnqAT is not incomplete and Range is not type-dependent. llvm_unreachable("Unexpected array type in for-range"); } // end-expr is __range + __bound. EndExpr = ActOnBinOp(S, ColonLoc, tok::plus, EndRangeRef.get(), BoundExpr.get()); if (EndExpr.isInvalid()) return StmtError(); if (FinishForRangeVarDecl(*this, EndVar, EndExpr.get(), ColonLoc, diag::err_for_range_iter_deduction_failure)) { NoteForRangeBeginEndFunction(*this, EndExpr.get(), BEF_end); return StmtError(); } } else { OverloadCandidateSet CandidateSet(RangeLoc, OverloadCandidateSet::CSK_Normal); BeginEndFunction BEFFailure; ForRangeStatus RangeStatus = BuildNonArrayForRange( *this, BeginRangeRef.get(), EndRangeRef.get(), RangeType, BeginVar, EndVar, ColonLoc, CoawaitLoc, &CandidateSet, &BeginExpr, &EndExpr, &BEFFailure); if (Kind == BFRK_Build && RangeStatus == FRS_NoViableFunction && BEFFailure == BEF_begin) { // If the range is being built from an array parameter, emit a // a diagnostic that it is being treated as a pointer. if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Range)) { if (ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) { QualType ArrayTy = PVD->getOriginalType(); QualType PointerTy = PVD->getType(); if (PointerTy->isPointerType() && ArrayTy->isArrayType()) { Diag(Range->getBeginLoc(), diag::err_range_on_array_parameter) << RangeLoc << PVD << ArrayTy << PointerTy; Diag(PVD->getLocation(), diag::note_declared_at); return StmtError(); } } } // If building the range failed, try dereferencing the range expression // unless a diagnostic was issued or the end function is problematic. StmtResult SR = RebuildForRangeWithDereference(*this, S, ForLoc, CoawaitLoc, InitStmt, LoopVarDecl, ColonLoc, Range, RangeLoc, RParenLoc); if (SR.isInvalid() || SR.isUsable()) return SR; } // Otherwise, emit diagnostics if we haven't already. if (RangeStatus == FRS_NoViableFunction) { Expr *Range = BEFFailure ? EndRangeRef.get() : BeginRangeRef.get(); CandidateSet.NoteCandidates( PartialDiagnosticAt(Range->getBeginLoc(), PDiag(diag::err_for_range_invalid) << RangeLoc << Range->getType() << BEFFailure), *this, OCD_AllCandidates, Range); } // Return an error if no fix was discovered. if (RangeStatus != FRS_Success) return StmtError(); } assert(!BeginExpr.isInvalid() && !EndExpr.isInvalid() && "invalid range expression in for loop"); // C++11 [dcl.spec.auto]p7: BeginType and EndType must be the same. // C++1z removes this restriction. QualType BeginType = BeginVar->getType(), EndType = EndVar->getType(); if (!Context.hasSameType(BeginType, EndType)) { Diag(RangeLoc, getLangOpts().CPlusPlus17 ? diag::warn_for_range_begin_end_types_differ : diag::ext_for_range_begin_end_types_differ) << BeginType << EndType; NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin); NoteForRangeBeginEndFunction(*this, EndExpr.get(), BEF_end); } BeginDeclStmt = ActOnDeclStmt(ConvertDeclToDeclGroup(BeginVar), ColonLoc, ColonLoc); EndDeclStmt = ActOnDeclStmt(ConvertDeclToDeclGroup(EndVar), ColonLoc, ColonLoc); const QualType BeginRefNonRefType = BeginType.getNonReferenceType(); ExprResult BeginRef = BuildDeclRefExpr(BeginVar, BeginRefNonRefType, VK_LValue, ColonLoc); if (BeginRef.isInvalid()) return StmtError(); ExprResult EndRef = BuildDeclRefExpr(EndVar, EndType.getNonReferenceType(), VK_LValue, ColonLoc); if (EndRef.isInvalid()) return StmtError(); // Build and check __begin != __end expression. NotEqExpr = ActOnBinOp(S, ColonLoc, tok::exclaimequal, BeginRef.get(), EndRef.get()); if (!NotEqExpr.isInvalid()) NotEqExpr = CheckBooleanCondition(ColonLoc, NotEqExpr.get()); if (!NotEqExpr.isInvalid()) NotEqExpr = ActOnFinishFullExpr(NotEqExpr.get(), /*DiscardedValue*/ false); if (NotEqExpr.isInvalid()) { Diag(RangeLoc, diag::note_for_range_invalid_iterator) << RangeLoc << 0 << BeginRangeRef.get()->getType(); NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin); if (!Context.hasSameType(BeginType, EndType)) NoteForRangeBeginEndFunction(*this, EndExpr.get(), BEF_end); return StmtError(); } // Build and check ++__begin expression. BeginRef = BuildDeclRefExpr(BeginVar, BeginRefNonRefType, VK_LValue, ColonLoc); if (BeginRef.isInvalid()) return StmtError(); IncrExpr = ActOnUnaryOp(S, ColonLoc, tok::plusplus, BeginRef.get()); if (!IncrExpr.isInvalid() && CoawaitLoc.isValid()) // FIXME: getCurScope() should not be used during template instantiation. // We should pick up the set of unqualified lookup results for operator // co_await during the initial parse. IncrExpr = ActOnCoawaitExpr(S, CoawaitLoc, IncrExpr.get()); if (!IncrExpr.isInvalid()) IncrExpr = ActOnFinishFullExpr(IncrExpr.get(), /*DiscardedValue*/ false); if (IncrExpr.isInvalid()) { Diag(RangeLoc, diag::note_for_range_invalid_iterator) << RangeLoc << 2 << BeginRangeRef.get()->getType() ; NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin); return StmtError(); } // Build and check *__begin expression. BeginRef = BuildDeclRefExpr(BeginVar, BeginRefNonRefType, VK_LValue, ColonLoc); if (BeginRef.isInvalid()) return StmtError(); ExprResult DerefExpr = ActOnUnaryOp(S, ColonLoc, tok::star, BeginRef.get()); if (DerefExpr.isInvalid()) { Diag(RangeLoc, diag::note_for_range_invalid_iterator) << RangeLoc << 1 << BeginRangeRef.get()->getType(); NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin); return StmtError(); } // Attach *__begin as initializer for VD. Don't touch it if we're just // trying to determine whether this would be a valid range. if (!LoopVar->isInvalidDecl() && Kind != BFRK_Check) { AddInitializerToDecl(LoopVar, DerefExpr.get(), /*DirectInit=*/false); if (LoopVar->isInvalidDecl()) NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin); } } // Don't bother to actually allocate the result if we're just trying to // determine whether it would be valid. if (Kind == BFRK_Check) return StmtResult(); // In OpenMP loop region loop control variable must be private. Perform // analysis of first part (if any). if (getLangOpts().OpenMP >= 50 && BeginDeclStmt.isUsable()) ActOnOpenMPLoopInitialization(ForLoc, BeginDeclStmt.get()); return new (Context) CXXForRangeStmt( InitStmt, RangeDS, cast_or_null<DeclStmt>(BeginDeclStmt.get()), cast_or_null<DeclStmt>(EndDeclStmt.get()), NotEqExpr.get(), IncrExpr.get(), LoopVarDS, /*Body=*/nullptr, ForLoc, CoawaitLoc, ColonLoc, RParenLoc); } /// FinishObjCForCollectionStmt - Attach the body to a objective-C foreach /// statement. StmtResult Sema::FinishObjCForCollectionStmt(Stmt *S, Stmt *B) { if (!S || !B) return StmtError(); ObjCForCollectionStmt * ForStmt = cast<ObjCForCollectionStmt>(S); ForStmt->setBody(B); return S; } // Warn when the loop variable is a const reference that creates a copy. // Suggest using the non-reference type for copies. If a copy can be prevented // suggest the const reference type that would do so. // For instance, given "for (const &Foo : Range)", suggest // "for (const Foo : Range)" to denote a copy is made for the loop. If // possible, also suggest "for (const &Bar : Range)" if this type prevents // the copy altogether. static void DiagnoseForRangeReferenceVariableCopies(Sema &SemaRef, const VarDecl *VD, QualType RangeInitType) { const Expr *InitExpr = VD->getInit(); if (!InitExpr) return; QualType VariableType = VD->getType(); if (auto Cleanups = dyn_cast<ExprWithCleanups>(InitExpr)) if (!Cleanups->cleanupsHaveSideEffects()) InitExpr = Cleanups->getSubExpr(); const MaterializeTemporaryExpr *MTE = dyn_cast<MaterializeTemporaryExpr>(InitExpr); // No copy made. if (!MTE) return; const Expr *E = MTE->getSubExpr()->IgnoreImpCasts(); // Searching for either UnaryOperator for dereference of a pointer or // CXXOperatorCallExpr for handling iterators. while (!isa<CXXOperatorCallExpr>(E) && !isa<UnaryOperator>(E)) { if (const CXXConstructExpr *CCE = dyn_cast<CXXConstructExpr>(E)) { E = CCE->getArg(0); } else if (const CXXMemberCallExpr *Call = dyn_cast<CXXMemberCallExpr>(E)) { const MemberExpr *ME = cast<MemberExpr>(Call->getCallee()); E = ME->getBase(); } else { const MaterializeTemporaryExpr *MTE = cast<MaterializeTemporaryExpr>(E); E = MTE->getSubExpr(); } E = E->IgnoreImpCasts(); } bool ReturnsReference = false; if (isa<UnaryOperator>(E)) { ReturnsReference = true; } else { const CXXOperatorCallExpr *Call = cast<CXXOperatorCallExpr>(E); const FunctionDecl *FD = Call->getDirectCallee(); QualType ReturnType = FD->getReturnType(); ReturnsReference = ReturnType->isReferenceType(); } if (ReturnsReference) { // Loop variable creates a temporary. Suggest either to go with // non-reference loop variable to indicate a copy is made, or // the correct time to bind a const reference. SemaRef.Diag(VD->getLocation(), diag::warn_for_range_const_reference_copy) << VD << VariableType << E->getType(); QualType NonReferenceType = VariableType.getNonReferenceType(); NonReferenceType.removeLocalConst(); QualType NewReferenceType = SemaRef.Context.getLValueReferenceType(E->getType().withConst()); SemaRef.Diag(VD->getBeginLoc(), diag::note_use_type_or_non_reference) << NonReferenceType << NewReferenceType << VD->getSourceRange() << FixItHint::CreateRemoval(VD->getTypeSpecEndLoc()); } else if (!VariableType->isRValueReferenceType()) { // The range always returns a copy, so a temporary is always created. // Suggest removing the reference from the loop variable. // If the type is a rvalue reference do not warn since that changes the // semantic of the code. SemaRef.Diag(VD->getLocation(), diag::warn_for_range_variable_always_copy) << VD << RangeInitType; QualType NonReferenceType = VariableType.getNonReferenceType(); NonReferenceType.removeLocalConst(); SemaRef.Diag(VD->getBeginLoc(), diag::note_use_non_reference_type) << NonReferenceType << VD->getSourceRange() << FixItHint::CreateRemoval(VD->getTypeSpecEndLoc()); } } // Warns when the loop variable can be changed to a reference type to // prevent a copy. For instance, if given "for (const Foo x : Range)" suggest // "for (const Foo &x : Range)" if this form does not make a copy. static void DiagnoseForRangeConstVariableCopies(Sema &SemaRef, const VarDecl *VD) { const Expr *InitExpr = VD->getInit(); if (!InitExpr) return; QualType VariableType = VD->getType(); if (const CXXConstructExpr *CE = dyn_cast<CXXConstructExpr>(InitExpr)) { if (!CE->getConstructor()->isCopyConstructor()) return; } else if (const CastExpr *CE = dyn_cast<CastExpr>(InitExpr)) { if (CE->getCastKind() != CK_LValueToRValue) return; } else { return; } // TODO: Determine a maximum size that a POD type can be before a diagnostic // should be emitted. Also, only ignore POD types with trivial copy // constructors. if (VariableType.isPODType(SemaRef.Context)) return; // Suggest changing from a const variable to a const reference variable // if doing so will prevent a copy. SemaRef.Diag(VD->getLocation(), diag::warn_for_range_copy) << VD << VariableType << InitExpr->getType(); SemaRef.Diag(VD->getBeginLoc(), diag::note_use_reference_type) << SemaRef.Context.getLValueReferenceType(VariableType) << VD->getSourceRange() << FixItHint::CreateInsertion(VD->getLocation(), "&"); } /// DiagnoseForRangeVariableCopies - Diagnose three cases and fixes for them. /// 1) for (const foo &x : foos) where foos only returns a copy. Suggest /// using "const foo x" to show that a copy is made /// 2) for (const bar &x : foos) where bar is a temporary initialized by bar. /// Suggest either "const bar x" to keep the copying or "const foo& x" to /// prevent the copy. /// 3) for (const foo x : foos) where x is constructed from a reference foo. /// Suggest "const foo &x" to prevent the copy. static void DiagnoseForRangeVariableCopies(Sema &SemaRef, const CXXForRangeStmt *ForStmt) { if (SemaRef.Diags.isIgnored(diag::warn_for_range_const_reference_copy, ForStmt->getBeginLoc()) && SemaRef.Diags.isIgnored(diag::warn_for_range_variable_always_copy, ForStmt->getBeginLoc()) && SemaRef.Diags.isIgnored(diag::warn_for_range_copy, ForStmt->getBeginLoc())) { return; } const VarDecl *VD = ForStmt->getLoopVariable(); if (!VD) return; QualType VariableType = VD->getType(); if (VariableType->isIncompleteType()) return; const Expr *InitExpr = VD->getInit(); if (!InitExpr) return; if (VariableType->isReferenceType()) { DiagnoseForRangeReferenceVariableCopies(SemaRef, VD, ForStmt->getRangeInit()->getType()); } else if (VariableType.isConstQualified()) { DiagnoseForRangeConstVariableCopies(SemaRef, VD); } } /// FinishCXXForRangeStmt - Attach the body to a C++0x for-range statement. /// This is a separate step from ActOnCXXForRangeStmt because analysis of the /// body cannot be performed until after the type of the range variable is /// determined. StmtResult Sema::FinishCXXForRangeStmt(Stmt *S, Stmt *B) { if (!S || !B) return StmtError(); if (isa<ObjCForCollectionStmt>(S)) return FinishObjCForCollectionStmt(S, B); CXXForRangeStmt *ForStmt = cast<CXXForRangeStmt>(S); ForStmt->setBody(B); DiagnoseEmptyStmtBody(ForStmt->getRParenLoc(), B, diag::warn_empty_range_based_for_body); DiagnoseForRangeVariableCopies(*this, ForStmt); return S; } StmtResult Sema::ActOnGotoStmt(SourceLocation GotoLoc, SourceLocation LabelLoc, LabelDecl *TheDecl) { setFunctionHasBranchIntoScope(); TheDecl->markUsed(Context); return new (Context) GotoStmt(TheDecl, GotoLoc, LabelLoc); } StmtResult Sema::ActOnIndirectGotoStmt(SourceLocation GotoLoc, SourceLocation StarLoc, Expr *E) { // Convert operand to void* if (!E->isTypeDependent()) { QualType ETy = E->getType(); QualType DestTy = Context.getPointerType(Context.VoidTy.withConst()); ExprResult ExprRes = E; AssignConvertType ConvTy = CheckSingleAssignmentConstraints(DestTy, ExprRes); if (ExprRes.isInvalid()) return StmtError(); E = ExprRes.get(); if (DiagnoseAssignmentResult(ConvTy, StarLoc, DestTy, ETy, E, AA_Passing)) return StmtError(); } ExprResult ExprRes = ActOnFinishFullExpr(E, /*DiscardedValue*/ false); if (ExprRes.isInvalid()) return StmtError(); E = ExprRes.get(); setFunctionHasIndirectGoto(); return new (Context) IndirectGotoStmt(GotoLoc, StarLoc, E); } static void CheckJumpOutOfSEHFinally(Sema &S, SourceLocation Loc, const Scope &DestScope) { if (!S.CurrentSEHFinally.empty() && DestScope.Contains(*S.CurrentSEHFinally.back())) { S.Diag(Loc, diag::warn_jump_out_of_seh_finally); } } StmtResult Sema::ActOnContinueStmt(SourceLocation ContinueLoc, Scope *CurScope) { Scope *S = CurScope->getContinueParent(); if (!S) { // C99 6.8.6.2p1: A break shall appear only in or as a loop body. return StmtError(Diag(ContinueLoc, diag::err_continue_not_in_loop)); } CheckJumpOutOfSEHFinally(*this, ContinueLoc, *S); return new (Context) ContinueStmt(ContinueLoc); } StmtResult Sema::ActOnBreakStmt(SourceLocation BreakLoc, Scope *CurScope) { Scope *S = CurScope->getBreakParent(); if (!S) { // C99 6.8.6.3p1: A break shall appear only in or as a switch/loop body. return StmtError(Diag(BreakLoc, diag::err_break_not_in_loop_or_switch)); } if (S->isOpenMPLoopScope()) return StmtError(Diag(BreakLoc, diag::err_omp_loop_cannot_use_stmt) << "break"); CheckJumpOutOfSEHFinally(*this, BreakLoc, *S); return new (Context) BreakStmt(BreakLoc); } /// Determine whether the given expression is a candidate for /// copy elision in either a return statement or a throw expression. /// /// \param ReturnType If we're determining the copy elision candidate for /// a return statement, this is the return type of the function. If we're /// determining the copy elision candidate for a throw expression, this will /// be a NULL type. /// /// \param E The expression being returned from the function or block, or /// being thrown. /// /// \param CESK Whether we allow function parameters or /// id-expressions that could be moved out of the function to be considered NRVO /// candidates. C++ prohibits these for NRVO itself, but we re-use this logic to /// determine whether we should try to move as part of a return or throw (which /// does allow function parameters). /// /// \returns The NRVO candidate variable, if the return statement may use the /// NRVO, or NULL if there is no such candidate. VarDecl *Sema::getCopyElisionCandidate(QualType ReturnType, Expr *E, CopyElisionSemanticsKind CESK) { // - in a return statement in a function [where] ... // ... the expression is the name of a non-volatile automatic object ... DeclRefExpr *DR = dyn_cast<DeclRefExpr>(E->IgnoreParens()); if (!DR || DR->refersToEnclosingVariableOrCapture()) return nullptr; VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl()); if (!VD) return nullptr; if (isCopyElisionCandidate(ReturnType, VD, CESK)) return VD; return nullptr; } bool Sema::isCopyElisionCandidate(QualType ReturnType, const VarDecl *VD, CopyElisionSemanticsKind CESK) { QualType VDType = VD->getType(); // - in a return statement in a function with ... // ... a class return type ... if (!ReturnType.isNull() && !ReturnType->isDependentType()) { if (!ReturnType->isRecordType()) return false; // ... the same cv-unqualified type as the function return type ... // When considering moving this expression out, allow dissimilar types. if (!(CESK & CES_AllowDifferentTypes) && !VDType->isDependentType() && !Context.hasSameUnqualifiedType(ReturnType, VDType)) return false; } // ...object (other than a function or catch-clause parameter)... if (VD->getKind() != Decl::Var && !((CESK & CES_AllowParameters) && VD->getKind() == Decl::ParmVar)) return false; if (!(CESK & CES_AllowExceptionVariables) && VD->isExceptionVariable()) return false; // ...automatic... if (!VD->hasLocalStorage()) return false; // Return false if VD is a __block variable. We don't want to implicitly move // out of a __block variable during a return because we cannot assume the // variable will no longer be used. if (VD->hasAttr<BlocksAttr>()) return false; if (CESK & CES_AllowDifferentTypes) return true; // ...non-volatile... if (VD->getType().isVolatileQualified()) return false; // Variables with higher required alignment than their type's ABI // alignment cannot use NRVO. if (!VD->getType()->isDependentType() && VD->hasAttr<AlignedAttr>() && Context.getDeclAlign(VD) > Context.getTypeAlignInChars(VD->getType())) return false; return true; } /// Try to perform the initialization of a potentially-movable value, /// which is the operand to a return or throw statement. /// /// This routine implements C++14 [class.copy]p32, which attempts to treat /// returned lvalues as rvalues in certain cases (to prefer move construction), /// then falls back to treating them as lvalues if that failed. /// /// \param ConvertingConstructorsOnly If true, follow [class.copy]p32 and reject /// resolutions that find non-constructors, such as derived-to-base conversions /// or `operator T()&&` member functions. If false, do consider such /// conversion sequences. /// /// \param Res We will fill this in if move-initialization was possible. /// If move-initialization is not possible, such that we must fall back to /// treating the operand as an lvalue, we will leave Res in its original /// invalid state. static void TryMoveInitialization(Sema& S, const InitializedEntity &Entity, const VarDecl *NRVOCandidate, QualType ResultType, Expr *&Value, bool ConvertingConstructorsOnly, ExprResult &Res) { ImplicitCastExpr AsRvalue(ImplicitCastExpr::OnStack, Value->getType(), CK_NoOp, Value, VK_XValue); Expr *InitExpr = &AsRvalue; InitializationKind Kind = InitializationKind::CreateCopy( Value->getBeginLoc(), Value->getBeginLoc()); InitializationSequence Seq(S, Entity, Kind, InitExpr); if (!Seq) return; for (const InitializationSequence::Step &Step : Seq.steps()) { if (Step.Kind != InitializationSequence::SK_ConstructorInitialization && Step.Kind != InitializationSequence::SK_UserConversion) continue; FunctionDecl *FD = Step.Function.Function; if (ConvertingConstructorsOnly) { if (isa<CXXConstructorDecl>(FD)) { // C++14 [class.copy]p32: // [...] If the first overload resolution fails or was not performed, // or if the type of the first parameter of the selected constructor // is not an rvalue reference to the object's type (possibly // cv-qualified), overload resolution is performed again, considering // the object as an lvalue. const RValueReferenceType *RRefType = FD->getParamDecl(0)->getType()->getAs<RValueReferenceType>(); if (!RRefType) break; if (!S.Context.hasSameUnqualifiedType(RRefType->getPointeeType(), NRVOCandidate->getType())) break; } else { continue; } } else { if (isa<CXXConstructorDecl>(FD)) { // Check that overload resolution selected a constructor taking an // rvalue reference. If it selected an lvalue reference, then we // didn't need to cast this thing to an rvalue in the first place. if (!isa<RValueReferenceType>(FD->getParamDecl(0)->getType())) break; } else if (isa<CXXMethodDecl>(FD)) { // Check that overload resolution selected a conversion operator // taking an rvalue reference. if (cast<CXXMethodDecl>(FD)->getRefQualifier() != RQ_RValue) break; } else { continue; } } // Promote "AsRvalue" to the heap, since we now need this // expression node to persist. Value = ImplicitCastExpr::Create(S.Context, Value->getType(), CK_NoOp, Value, nullptr, VK_XValue); // Complete type-checking the initialization of the return type // using the constructor we found. Res = Seq.Perform(S, Entity, Kind, Value); } } /// Perform the initialization of a potentially-movable value, which /// is the result of return value. /// /// This routine implements C++14 [class.copy]p32, which attempts to treat /// returned lvalues as rvalues in certain cases (to prefer move construction), /// then falls back to treating them as lvalues if that failed. ExprResult Sema::PerformMoveOrCopyInitialization(const InitializedEntity &Entity, const VarDecl *NRVOCandidate, QualType ResultType, Expr *Value, bool AllowNRVO) { // C++14 [class.copy]p32: // When the criteria for elision of a copy/move operation are met, but not for // an exception-declaration, and the object to be copied is designated by an // lvalue, or when the expression in a return statement is a (possibly // parenthesized) id-expression that names an object with automatic storage // duration declared in the body or parameter-declaration-clause of the // innermost enclosing function or lambda-expression, overload resolution to // select the constructor for the copy is first performed as if the object // were designated by an rvalue. ExprResult Res = ExprError(); if (AllowNRVO) { bool AffectedByCWG1579 = false; if (!NRVOCandidate) { NRVOCandidate = getCopyElisionCandidate(ResultType, Value, CES_Default); if (NRVOCandidate && !getDiagnostics().isIgnored(diag::warn_return_std_move_in_cxx11, Value->getExprLoc())) { const VarDecl *NRVOCandidateInCXX11 = getCopyElisionCandidate(ResultType, Value, CES_FormerDefault); AffectedByCWG1579 = (!NRVOCandidateInCXX11); } } if (NRVOCandidate) { TryMoveInitialization(*this, Entity, NRVOCandidate, ResultType, Value, true, Res); } if (!Res.isInvalid() && AffectedByCWG1579) { QualType QT = NRVOCandidate->getType(); if (QT.getNonReferenceType() .getUnqualifiedType() .isTriviallyCopyableType(Context)) { // Adding 'std::move' around a trivially copyable variable is probably // pointless. Don't suggest it. } else { // Common cases for this are returning unique_ptr<Derived> from a // function of return type unique_ptr<Base>, or returning T from a // function of return type Expected<T>. This is totally fine in a // post-CWG1579 world, but was not fine before. assert(!ResultType.isNull()); SmallString<32> Str; Str += "std::move("; Str += NRVOCandidate->getDeclName().getAsString(); Str += ")"; Diag(Value->getExprLoc(), diag::warn_return_std_move_in_cxx11) << Value->getSourceRange() << NRVOCandidate->getDeclName() << ResultType << QT; Diag(Value->getExprLoc(), diag::note_add_std_move_in_cxx11) << FixItHint::CreateReplacement(Value->getSourceRange(), Str); } } else if (Res.isInvalid() && !getDiagnostics().isIgnored(diag::warn_return_std_move, Value->getExprLoc())) { const VarDecl *FakeNRVOCandidate = getCopyElisionCandidate(QualType(), Value, CES_AsIfByStdMove); if (FakeNRVOCandidate) { QualType QT = FakeNRVOCandidate->getType(); if (QT->isLValueReferenceType()) { // Adding 'std::move' around an lvalue reference variable's name is // dangerous. Don't suggest it. } else if (QT.getNonReferenceType() .getUnqualifiedType() .isTriviallyCopyableType(Context)) { // Adding 'std::move' around a trivially copyable variable is probably // pointless. Don't suggest it. } else { ExprResult FakeRes = ExprError(); Expr *FakeValue = Value; TryMoveInitialization(*this, Entity, FakeNRVOCandidate, ResultType, FakeValue, false, FakeRes); if (!FakeRes.isInvalid()) { bool IsThrow = (Entity.getKind() == InitializedEntity::EK_Exception); SmallString<32> Str; Str += "std::move("; Str += FakeNRVOCandidate->getDeclName().getAsString(); Str += ")"; Diag(Value->getExprLoc(), diag::warn_return_std_move) << Value->getSourceRange() << FakeNRVOCandidate->getDeclName() << IsThrow; Diag(Value->getExprLoc(), diag::note_add_std_move) << FixItHint::CreateReplacement(Value->getSourceRange(), Str); } } } } } // Either we didn't meet the criteria for treating an lvalue as an rvalue, // above, or overload resolution failed. Either way, we need to try // (again) now with the return value expression as written. if (Res.isInvalid()) Res = PerformCopyInitialization(Entity, SourceLocation(), Value); return Res; } /// Determine whether the declared return type of the specified function /// contains 'auto'. static bool hasDeducedReturnType(FunctionDecl *FD) { const FunctionProtoType *FPT = FD->getTypeSourceInfo()->getType()->castAs<FunctionProtoType>(); return FPT->getReturnType()->isUndeducedType(); } /// ActOnCapScopeReturnStmt - Utility routine to type-check return statements /// for capturing scopes. /// StmtResult Sema::ActOnCapScopeReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp) { // If this is the first return we've seen, infer the return type. // [expr.prim.lambda]p4 in C++11; block literals follow the same rules. CapturingScopeInfo *CurCap = cast<CapturingScopeInfo>(getCurFunction()); QualType FnRetType = CurCap->ReturnType; LambdaScopeInfo *CurLambda = dyn_cast<LambdaScopeInfo>(CurCap); bool HasDeducedReturnType = CurLambda && hasDeducedReturnType(CurLambda->CallOperator); if (ExprEvalContexts.back().Context == ExpressionEvaluationContext::DiscardedStatement && (HasDeducedReturnType || CurCap->HasImplicitReturnType)) { if (RetValExp) { ExprResult ER = ActOnFinishFullExpr(RetValExp, ReturnLoc, /*DiscardedValue*/ false); if (ER.isInvalid()) return StmtError(); RetValExp = ER.get(); } return ReturnStmt::Create(Context, ReturnLoc, RetValExp, /* NRVOCandidate=*/nullptr); } if (HasDeducedReturnType) { // In C++1y, the return type may involve 'auto'. // FIXME: Blocks might have a return type of 'auto' explicitly specified. FunctionDecl *FD = CurLambda->CallOperator; if (CurCap->ReturnType.isNull()) CurCap->ReturnType = FD->getReturnType(); AutoType *AT = CurCap->ReturnType->getContainedAutoType(); assert(AT && "lost auto type from lambda return type"); if (DeduceFunctionTypeFromReturnExpr(FD, ReturnLoc, RetValExp, AT)) { FD->setInvalidDecl(); return StmtError(); } CurCap->ReturnType = FnRetType = FD->getReturnType(); } else if (CurCap->HasImplicitReturnType) { // For blocks/lambdas with implicit return types, we check each return // statement individually, and deduce the common return type when the block // or lambda is completed. // FIXME: Fold this into the 'auto' codepath above. if (RetValExp && !isa<InitListExpr>(RetValExp)) { ExprResult Result = DefaultFunctionArrayLvalueConversion(RetValExp); if (Result.isInvalid()) return StmtError(); RetValExp = Result.get(); // DR1048: even prior to C++14, we should use the 'auto' deduction rules // when deducing a return type for a lambda-expression (or by extension // for a block). These rules differ from the stated C++11 rules only in // that they remove top-level cv-qualifiers. if (!CurContext->isDependentContext()) FnRetType = RetValExp->getType().getUnqualifiedType(); else FnRetType = CurCap->ReturnType = Context.DependentTy; } else { if (RetValExp) { // C++11 [expr.lambda.prim]p4 bans inferring the result from an // initializer list, because it is not an expression (even // though we represent it as one). We still deduce 'void'. Diag(ReturnLoc, diag::err_lambda_return_init_list) << RetValExp->getSourceRange(); } FnRetType = Context.VoidTy; } // Although we'll properly infer the type of the block once it's completed, // make sure we provide a return type now for better error recovery. if (CurCap->ReturnType.isNull()) CurCap->ReturnType = FnRetType; } assert(!FnRetType.isNull()); if (auto *CurBlock = dyn_cast<BlockScopeInfo>(CurCap)) { if (CurBlock->FunctionType->castAs<FunctionType>()->getNoReturnAttr()) { Diag(ReturnLoc, diag::err_noreturn_block_has_return_expr); return StmtError(); } } else if (auto *CurRegion = dyn_cast<CapturedRegionScopeInfo>(CurCap)) { Diag(ReturnLoc, diag::err_return_in_captured_stmt) << CurRegion->getRegionName(); return StmtError(); } else { assert(CurLambda && "unknown kind of captured scope"); if (CurLambda->CallOperator->getType() ->castAs<FunctionType>() ->getNoReturnAttr()) { Diag(ReturnLoc, diag::err_noreturn_lambda_has_return_expr); return StmtError(); } } // Otherwise, verify that this result type matches the previous one. We are // pickier with blocks than for normal functions because we don't have GCC // compatibility to worry about here. const VarDecl *NRVOCandidate = nullptr; if (FnRetType->isDependentType()) { // Delay processing for now. TODO: there are lots of dependent // types we can conclusively prove aren't void. } else if (FnRetType->isVoidType()) { if (RetValExp && !isa<InitListExpr>(RetValExp) && !(getLangOpts().CPlusPlus && (RetValExp->isTypeDependent() || RetValExp->getType()->isVoidType()))) { if (!getLangOpts().CPlusPlus && RetValExp->getType()->isVoidType()) Diag(ReturnLoc, diag::ext_return_has_void_expr) << "literal" << 2; else { Diag(ReturnLoc, diag::err_return_block_has_expr); RetValExp = nullptr; } } } else if (!RetValExp) { return StmtError(Diag(ReturnLoc, diag::err_block_return_missing_expr)); } else if (!RetValExp->isTypeDependent()) { // we have a non-void block with an expression, continue checking // C99 6.8.6.4p3(136): The return statement is not an assignment. The // overlap restriction of subclause 6.5.16.1 does not apply to the case of // function return. // In C++ the return statement is handled via a copy initialization. // the C version of which boils down to CheckSingleAssignmentConstraints. NRVOCandidate = getCopyElisionCandidate(FnRetType, RetValExp, CES_Strict); InitializedEntity Entity = InitializedEntity::InitializeResult(ReturnLoc, FnRetType, NRVOCandidate != nullptr); ExprResult Res = PerformMoveOrCopyInitialization(Entity, NRVOCandidate, FnRetType, RetValExp); if (Res.isInvalid()) { // FIXME: Cleanup temporaries here, anyway? return StmtError(); } RetValExp = Res.get(); CheckReturnValExpr(RetValExp, FnRetType, ReturnLoc); } else { NRVOCandidate = getCopyElisionCandidate(FnRetType, RetValExp, CES_Strict); } if (RetValExp) { ExprResult ER = ActOnFinishFullExpr(RetValExp, ReturnLoc, /*DiscardedValue*/ false); if (ER.isInvalid()) return StmtError(); RetValExp = ER.get(); } auto *Result = ReturnStmt::Create(Context, ReturnLoc, RetValExp, NRVOCandidate); // If we need to check for the named return value optimization, // or if we need to infer the return type, // save the return statement in our scope for later processing. if (CurCap->HasImplicitReturnType || NRVOCandidate) FunctionScopes.back()->Returns.push_back(Result); if (FunctionScopes.back()->FirstReturnLoc.isInvalid()) FunctionScopes.back()->FirstReturnLoc = ReturnLoc; return Result; } namespace { /// Marks all typedefs in all local classes in a type referenced. /// /// In a function like /// auto f() { /// struct S { typedef int a; }; /// return S(); /// } /// /// the local type escapes and could be referenced in some TUs but not in /// others. Pretend that all local typedefs are always referenced, to not warn /// on this. This isn't necessary if f has internal linkage, or the typedef /// is private. class LocalTypedefNameReferencer : public RecursiveASTVisitor<LocalTypedefNameReferencer> { public: LocalTypedefNameReferencer(Sema &S) : S(S) {} bool VisitRecordType(const RecordType *RT); private: Sema &S; }; bool LocalTypedefNameReferencer::VisitRecordType(const RecordType *RT) { auto *R = dyn_cast<CXXRecordDecl>(RT->getDecl()); if (!R || !R->isLocalClass() || !R->isLocalClass()->isExternallyVisible() || R->isDependentType()) return true; for (auto *TmpD : R->decls()) if (auto *T = dyn_cast<TypedefNameDecl>(TmpD)) if (T->getAccess() != AS_private || R->hasFriends()) S.MarkAnyDeclReferenced(T->getLocation(), T, /*OdrUse=*/false); return true; } } TypeLoc Sema::getReturnTypeLoc(FunctionDecl *FD) const { return FD->getTypeSourceInfo() ->getTypeLoc() .getAsAdjusted<FunctionProtoTypeLoc>() .getReturnLoc(); } /// Deduce the return type for a function from a returned expression, per /// C++1y [dcl.spec.auto]p6. bool Sema::DeduceFunctionTypeFromReturnExpr(FunctionDecl *FD, SourceLocation ReturnLoc, Expr *&RetExpr, AutoType *AT) { // If this is the conversion function for a lambda, we choose to deduce it // type from the corresponding call operator, not from the synthesized return // statement within it. See Sema::DeduceReturnType. if (isLambdaConversionOperator(FD)) return false; TypeLoc OrigResultType = getReturnTypeLoc(FD); QualType Deduced; if (RetExpr && isa<InitListExpr>(RetExpr)) { // If the deduction is for a return statement and the initializer is // a braced-init-list, the program is ill-formed. Diag(RetExpr->getExprLoc(), getCurLambda() ? diag::err_lambda_return_init_list : diag::err_auto_fn_return_init_list) << RetExpr->getSourceRange(); return true; } if (FD->isDependentContext()) { // C++1y [dcl.spec.auto]p12: // Return type deduction [...] occurs when the definition is // instantiated even if the function body contains a return // statement with a non-type-dependent operand. assert(AT->isDeduced() && "should have deduced to dependent type"); return false; } if (RetExpr) { // Otherwise, [...] deduce a value for U using the rules of template // argument deduction. DeduceAutoResult DAR = DeduceAutoType(OrigResultType, RetExpr, Deduced); if (DAR == DAR_Failed && !FD->isInvalidDecl()) Diag(RetExpr->getExprLoc(), diag::err_auto_fn_deduction_failure) << OrigResultType.getType() << RetExpr->getType(); if (DAR != DAR_Succeeded) return true; // If a local type is part of the returned type, mark its fields as // referenced. LocalTypedefNameReferencer Referencer(*this); Referencer.TraverseType(RetExpr->getType()); } else { // In the case of a return with no operand, the initializer is considered // to be void(). // // Deduction here can only succeed if the return type is exactly 'cv auto' // or 'decltype(auto)', so just check for that case directly. if (!OrigResultType.getType()->getAs<AutoType>()) { Diag(ReturnLoc, diag::err_auto_fn_return_void_but_not_auto) << OrigResultType.getType(); return true; } // We always deduce U = void in this case. Deduced = SubstAutoType(OrigResultType.getType(), Context.VoidTy); if (Deduced.isNull()) return true; } // CUDA: Kernel function must have 'void' return type. if (getLangOpts().CUDA) if (FD->hasAttr<CUDAGlobalAttr>() && !Deduced->isVoidType()) { Diag(FD->getLocation(), diag::err_kern_type_not_void_return) << FD->getType() << FD->getSourceRange(); return true; } // If a function with a declared return type that contains a placeholder type // has multiple return statements, the return type is deduced for each return // statement. [...] if the type deduced is not the same in each deduction, // the program is ill-formed. QualType DeducedT = AT->getDeducedType(); if (!DeducedT.isNull() && !FD->isInvalidDecl()) { AutoType *NewAT = Deduced->getContainedAutoType(); // It is possible that NewAT->getDeducedType() is null. When that happens, // we should not crash, instead we ignore this deduction. if (NewAT->getDeducedType().isNull()) return false; CanQualType OldDeducedType = Context.getCanonicalFunctionResultType( DeducedT); CanQualType NewDeducedType = Context.getCanonicalFunctionResultType( NewAT->getDeducedType()); if (!FD->isDependentContext() && OldDeducedType != NewDeducedType) { const LambdaScopeInfo *LambdaSI = getCurLambda(); if (LambdaSI && LambdaSI->HasImplicitReturnType) { Diag(ReturnLoc, diag::err_typecheck_missing_return_type_incompatible) << NewAT->getDeducedType() << DeducedT << true /*IsLambda*/; } else { Diag(ReturnLoc, diag::err_auto_fn_different_deductions) << (AT->isDecltypeAuto() ? 1 : 0) << NewAT->getDeducedType() << DeducedT; } return true; } } else if (!FD->isInvalidDecl()) { // Update all declarations of the function to have the deduced return type. Context.adjustDeducedFunctionResultType(FD, Deduced); } return false; } StmtResult Sema::ActOnReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp, Scope *CurScope) { // Correct typos, in case the containing function returns 'auto' and // RetValExp should determine the deduced type. ExprResult RetVal = CorrectDelayedTyposInExpr(RetValExp); if (RetVal.isInvalid()) return StmtError(); StmtResult R = BuildReturnStmt(ReturnLoc, RetVal.get()); if (R.isInvalid() || ExprEvalContexts.back().Context == ExpressionEvaluationContext::DiscardedStatement) return R; if (VarDecl *VD = const_cast<VarDecl*>(cast<ReturnStmt>(R.get())->getNRVOCandidate())) { CurScope->addNRVOCandidate(VD); } else { CurScope->setNoNRVO(); } CheckJumpOutOfSEHFinally(*this, ReturnLoc, *CurScope->getFnParent()); return R; } StmtResult Sema::BuildReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp) { // Check for unexpanded parameter packs. if (RetValExp && DiagnoseUnexpandedParameterPack(RetValExp)) return StmtError(); if (isa<CapturingScopeInfo>(getCurFunction())) return ActOnCapScopeReturnStmt(ReturnLoc, RetValExp); QualType FnRetType; QualType RelatedRetType; const AttrVec *Attrs = nullptr; bool isObjCMethod = false; if (const FunctionDecl *FD = getCurFunctionDecl()) { FnRetType = FD->getReturnType(); if (FD->hasAttrs()) Attrs = &FD->getAttrs(); if (FD->isNoReturn()) Diag(ReturnLoc, diag::warn_noreturn_function_has_return_expr) << FD->getDeclName(); if (FD->isMain() && RetValExp) if (isa<CXXBoolLiteralExpr>(RetValExp)) Diag(ReturnLoc, diag::warn_main_returns_bool_literal) << RetValExp->getSourceRange(); } else if (ObjCMethodDecl *MD = getCurMethodDecl()) { FnRetType = MD->getReturnType(); isObjCMethod = true; if (MD->hasAttrs()) Attrs = &MD->getAttrs(); if (MD->hasRelatedResultType() && MD->getClassInterface()) { // In the implementation of a method with a related return type, the // type used to type-check the validity of return statements within the // method body is a pointer to the type of the class being implemented. RelatedRetType = Context.getObjCInterfaceType(MD->getClassInterface()); RelatedRetType = Context.getObjCObjectPointerType(RelatedRetType); } } else // If we don't have a function/method context, bail. return StmtError(); // C++1z: discarded return statements are not considered when deducing a // return type. if (ExprEvalContexts.back().Context == ExpressionEvaluationContext::DiscardedStatement && FnRetType->getContainedAutoType()) { if (RetValExp) { ExprResult ER = ActOnFinishFullExpr(RetValExp, ReturnLoc, /*DiscardedValue*/ false); if (ER.isInvalid()) return StmtError(); RetValExp = ER.get(); } return ReturnStmt::Create(Context, ReturnLoc, RetValExp, /* NRVOCandidate=*/nullptr); } // FIXME: Add a flag to the ScopeInfo to indicate whether we're performing // deduction. if (getLangOpts().CPlusPlus14) { if (AutoType *AT = FnRetType->getContainedAutoType()) { FunctionDecl *FD = cast<FunctionDecl>(CurContext); if (DeduceFunctionTypeFromReturnExpr(FD, ReturnLoc, RetValExp, AT)) { FD->setInvalidDecl(); return StmtError(); } else { FnRetType = FD->getReturnType(); } } } bool HasDependentReturnType = FnRetType->isDependentType(); ReturnStmt *Result = nullptr; if (FnRetType->isVoidType()) { if (RetValExp) { if (isa<InitListExpr>(RetValExp)) { // We simply never allow init lists as the return value of void // functions. This is compatible because this was never allowed before, // so there's no legacy code to deal with. NamedDecl *CurDecl = getCurFunctionOrMethodDecl(); int FunctionKind = 0; if (isa<ObjCMethodDecl>(CurDecl)) FunctionKind = 1; else if (isa<CXXConstructorDecl>(CurDecl)) FunctionKind = 2; else if (isa<CXXDestructorDecl>(CurDecl)) FunctionKind = 3; Diag(ReturnLoc, diag::err_return_init_list) << CurDecl->getDeclName() << FunctionKind << RetValExp->getSourceRange(); // Drop the expression. RetValExp = nullptr; } else if (!RetValExp->isTypeDependent()) { // C99 6.8.6.4p1 (ext_ since GCC warns) unsigned D = diag::ext_return_has_expr; if (RetValExp->getType()->isVoidType()) { NamedDecl *CurDecl = getCurFunctionOrMethodDecl(); if (isa<CXXConstructorDecl>(CurDecl) || isa<CXXDestructorDecl>(CurDecl)) D = diag::err_ctor_dtor_returns_void; else D = diag::ext_return_has_void_expr; } else { ExprResult Result = RetValExp; Result = IgnoredValueConversions(Result.get()); if (Result.isInvalid()) return StmtError(); RetValExp = Result.get(); RetValExp = ImpCastExprToType(RetValExp, Context.VoidTy, CK_ToVoid).get(); } // return of void in constructor/destructor is illegal in C++. if (D == diag::err_ctor_dtor_returns_void) { NamedDecl *CurDecl = getCurFunctionOrMethodDecl(); Diag(ReturnLoc, D) << CurDecl->getDeclName() << isa<CXXDestructorDecl>(CurDecl) << RetValExp->getSourceRange(); } // return (some void expression); is legal in C++. else if (D != diag::ext_return_has_void_expr || !getLangOpts().CPlusPlus) { NamedDecl *CurDecl = getCurFunctionOrMethodDecl(); int FunctionKind = 0; if (isa<ObjCMethodDecl>(CurDecl)) FunctionKind = 1; else if (isa<CXXConstructorDecl>(CurDecl)) FunctionKind = 2; else if (isa<CXXDestructorDecl>(CurDecl)) FunctionKind = 3; Diag(ReturnLoc, D) << CurDecl->getDeclName() << FunctionKind << RetValExp->getSourceRange(); } } if (RetValExp) { ExprResult ER = ActOnFinishFullExpr(RetValExp, ReturnLoc, /*DiscardedValue*/ false); if (ER.isInvalid()) return StmtError(); RetValExp = ER.get(); } } Result = ReturnStmt::Create(Context, ReturnLoc, RetValExp, /* NRVOCandidate=*/nullptr); } else if (!RetValExp && !HasDependentReturnType) { FunctionDecl *FD = getCurFunctionDecl(); unsigned DiagID; if (getLangOpts().CPlusPlus11 && FD && FD->isConstexpr()) { // C++11 [stmt.return]p2 DiagID = diag::err_constexpr_return_missing_expr; FD->setInvalidDecl(); } else if (getLangOpts().C99) { // C99 6.8.6.4p1 (ext_ since GCC warns) DiagID = diag::ext_return_missing_expr; } else { // C90 6.6.6.4p4 DiagID = diag::warn_return_missing_expr; } if (FD) Diag(ReturnLoc, DiagID) << FD->getIdentifier() << 0 /*fn*/ << FD->isConsteval(); else Diag(ReturnLoc, DiagID) << getCurMethodDecl()->getDeclName() << 1/*meth*/; Result = ReturnStmt::Create(Context, ReturnLoc, /* RetExpr=*/nullptr, /* NRVOCandidate=*/nullptr); } else { assert(RetValExp || HasDependentReturnType); const VarDecl *NRVOCandidate = nullptr; QualType RetType = RelatedRetType.isNull() ? FnRetType : RelatedRetType; // C99 6.8.6.4p3(136): The return statement is not an assignment. The // overlap restriction of subclause 6.5.16.1 does not apply to the case of // function return. // In C++ the return statement is handled via a copy initialization, // the C version of which boils down to CheckSingleAssignmentConstraints. if (RetValExp) NRVOCandidate = getCopyElisionCandidate(FnRetType, RetValExp, CES_Strict); if (!HasDependentReturnType && !RetValExp->isTypeDependent()) { // we have a non-void function with an expression, continue checking InitializedEntity Entity = InitializedEntity::InitializeResult(ReturnLoc, RetType, NRVOCandidate != nullptr); ExprResult Res = PerformMoveOrCopyInitialization(Entity, NRVOCandidate, RetType, RetValExp); if (Res.isInvalid()) { // FIXME: Clean up temporaries here anyway? return StmtError(); } RetValExp = Res.getAs<Expr>(); // If we have a related result type, we need to implicitly // convert back to the formal result type. We can't pretend to // initialize the result again --- we might end double-retaining // --- so instead we initialize a notional temporary. if (!RelatedRetType.isNull()) { Entity = InitializedEntity::InitializeRelatedResult(getCurMethodDecl(), FnRetType); Res = PerformCopyInitialization(Entity, ReturnLoc, RetValExp); if (Res.isInvalid()) { // FIXME: Clean up temporaries here anyway? return StmtError(); } RetValExp = Res.getAs<Expr>(); } CheckReturnValExpr(RetValExp, FnRetType, ReturnLoc, isObjCMethod, Attrs, getCurFunctionDecl()); } if (RetValExp) { ExprResult ER = ActOnFinishFullExpr(RetValExp, ReturnLoc, /*DiscardedValue*/ false); if (ER.isInvalid()) return StmtError(); RetValExp = ER.get(); } Result = ReturnStmt::Create(Context, ReturnLoc, RetValExp, NRVOCandidate); } // If we need to check for the named return value optimization, save the // return statement in our scope for later processing. if (Result->getNRVOCandidate()) FunctionScopes.back()->Returns.push_back(Result); if (FunctionScopes.back()->FirstReturnLoc.isInvalid()) FunctionScopes.back()->FirstReturnLoc = ReturnLoc; return Result; } StmtResult Sema::ActOnObjCAtCatchStmt(SourceLocation AtLoc, SourceLocation RParen, Decl *Parm, Stmt *Body) { VarDecl *Var = cast_or_null<VarDecl>(Parm); if (Var && Var->isInvalidDecl()) return StmtError(); return new (Context) ObjCAtCatchStmt(AtLoc, RParen, Var, Body); } StmtResult Sema::ActOnObjCAtFinallyStmt(SourceLocation AtLoc, Stmt *Body) { return new (Context) ObjCAtFinallyStmt(AtLoc, Body); } StmtResult Sema::ActOnObjCAtTryStmt(SourceLocation AtLoc, Stmt *Try, MultiStmtArg CatchStmts, Stmt *Finally) { if (!getLangOpts().ObjCExceptions) Diag(AtLoc, diag::err_objc_exceptions_disabled) << "@try"; setFunctionHasBranchProtectedScope(); unsigned NumCatchStmts = CatchStmts.size(); return ObjCAtTryStmt::Create(Context, AtLoc, Try, CatchStmts.data(), NumCatchStmts, Finally); } StmtResult Sema::BuildObjCAtThrowStmt(SourceLocation AtLoc, Expr *Throw) { if (Throw) { ExprResult Result = DefaultLvalueConversion(Throw); if (Result.isInvalid()) return StmtError(); Result = ActOnFinishFullExpr(Result.get(), /*DiscardedValue*/ false); if (Result.isInvalid()) return StmtError(); Throw = Result.get(); QualType ThrowType = Throw->getType(); // Make sure the expression type is an ObjC pointer or "void *". if (!ThrowType->isDependentType() && !ThrowType->isObjCObjectPointerType()) { const PointerType *PT = ThrowType->getAs<PointerType>(); if (!PT || !PT->getPointeeType()->isVoidType()) return StmtError(Diag(AtLoc, diag::err_objc_throw_expects_object) << Throw->getType() << Throw->getSourceRange()); } } return new (Context) ObjCAtThrowStmt(AtLoc, Throw); } StmtResult Sema::ActOnObjCAtThrowStmt(SourceLocation AtLoc, Expr *Throw, Scope *CurScope) { if (!getLangOpts().ObjCExceptions) Diag(AtLoc, diag::err_objc_exceptions_disabled) << "@throw"; if (!Throw) { // @throw without an expression designates a rethrow (which must occur // in the context of an @catch clause). Scope *AtCatchParent = CurScope; while (AtCatchParent && !AtCatchParent->isAtCatchScope()) AtCatchParent = AtCatchParent->getParent(); if (!AtCatchParent) return StmtError(Diag(AtLoc, diag::err_rethrow_used_outside_catch)); } return BuildObjCAtThrowStmt(AtLoc, Throw); } ExprResult Sema::ActOnObjCAtSynchronizedOperand(SourceLocation atLoc, Expr *operand) { ExprResult result = DefaultLvalueConversion(operand); if (result.isInvalid()) return ExprError(); operand = result.get(); // Make sure the expression type is an ObjC pointer or "void *". QualType type = operand->getType(); if (!type->isDependentType() && !type->isObjCObjectPointerType()) { const PointerType *pointerType = type->getAs<PointerType>(); if (!pointerType || !pointerType->getPointeeType()->isVoidType()) { if (getLangOpts().CPlusPlus) { if (RequireCompleteType(atLoc, type, diag::err_incomplete_receiver_type)) return Diag(atLoc, diag::err_objc_synchronized_expects_object) << type << operand->getSourceRange(); ExprResult result = PerformContextuallyConvertToObjCPointer(operand); if (result.isInvalid()) return ExprError(); if (!result.isUsable()) return Diag(atLoc, diag::err_objc_synchronized_expects_object) << type << operand->getSourceRange(); operand = result.get(); } else { return Diag(atLoc, diag::err_objc_synchronized_expects_object) << type << operand->getSourceRange(); } } } // The operand to @synchronized is a full-expression. return ActOnFinishFullExpr(operand, /*DiscardedValue*/ false); } StmtResult Sema::ActOnObjCAtSynchronizedStmt(SourceLocation AtLoc, Expr *SyncExpr, Stmt *SyncBody) { // We can't jump into or indirect-jump out of a @synchronized block. setFunctionHasBranchProtectedScope(); return new (Context) ObjCAtSynchronizedStmt(AtLoc, SyncExpr, SyncBody); } /// ActOnCXXCatchBlock - Takes an exception declaration and a handler block /// and creates a proper catch handler from them. StmtResult Sema::ActOnCXXCatchBlock(SourceLocation CatchLoc, Decl *ExDecl, Stmt *HandlerBlock) { // There's nothing to test that ActOnExceptionDecl didn't already test. return new (Context) CXXCatchStmt(CatchLoc, cast_or_null<VarDecl>(ExDecl), HandlerBlock); } StmtResult Sema::ActOnObjCAutoreleasePoolStmt(SourceLocation AtLoc, Stmt *Body) { setFunctionHasBranchProtectedScope(); return new (Context) ObjCAutoreleasePoolStmt(AtLoc, Body); } namespace { class CatchHandlerType { QualType QT; unsigned IsPointer : 1; // This is a special constructor to be used only with DenseMapInfo's // getEmptyKey() and getTombstoneKey() functions. friend struct llvm::DenseMapInfo<CatchHandlerType>; enum Unique { ForDenseMap }; CatchHandlerType(QualType QT, Unique) : QT(QT), IsPointer(false) {} public: /// Used when creating a CatchHandlerType from a handler type; will determine /// whether the type is a pointer or reference and will strip off the top /// level pointer and cv-qualifiers. CatchHandlerType(QualType Q) : QT(Q), IsPointer(false) { if (QT->isPointerType()) IsPointer = true; if (IsPointer || QT->isReferenceType()) QT = QT->getPointeeType(); QT = QT.getUnqualifiedType(); } /// Used when creating a CatchHandlerType from a base class type; pretends the /// type passed in had the pointer qualifier, does not need to get an /// unqualified type. CatchHandlerType(QualType QT, bool IsPointer) : QT(QT), IsPointer(IsPointer) {} QualType underlying() const { return QT; } bool isPointer() const { return IsPointer; } friend bool operator==(const CatchHandlerType &LHS, const CatchHandlerType &RHS) { // If the pointer qualification does not match, we can return early. if (LHS.IsPointer != RHS.IsPointer) return false; // Otherwise, check the underlying type without cv-qualifiers. return LHS.QT == RHS.QT; } }; } // namespace namespace llvm { template <> struct DenseMapInfo<CatchHandlerType> { static CatchHandlerType getEmptyKey() { return CatchHandlerType(DenseMapInfo<QualType>::getEmptyKey(), CatchHandlerType::ForDenseMap); } static CatchHandlerType getTombstoneKey() { return CatchHandlerType(DenseMapInfo<QualType>::getTombstoneKey(), CatchHandlerType::ForDenseMap); } static unsigned getHashValue(const CatchHandlerType &Base) { return DenseMapInfo<QualType>::getHashValue(Base.underlying()); } static bool isEqual(const CatchHandlerType &LHS, const CatchHandlerType &RHS) { return LHS == RHS; } }; } namespace { class CatchTypePublicBases { ASTContext &Ctx; const llvm::DenseMap<CatchHandlerType, CXXCatchStmt *> &TypesToCheck; const bool CheckAgainstPointer; CXXCatchStmt *FoundHandler; CanQualType FoundHandlerType; public: CatchTypePublicBases( ASTContext &Ctx, const llvm::DenseMap<CatchHandlerType, CXXCatchStmt *> &T, bool C) : Ctx(Ctx), TypesToCheck(T), CheckAgainstPointer(C), FoundHandler(nullptr) {} CXXCatchStmt *getFoundHandler() const { return FoundHandler; } CanQualType getFoundHandlerType() const { return FoundHandlerType; } bool operator()(const CXXBaseSpecifier *S, CXXBasePath &) { if (S->getAccessSpecifier() == AccessSpecifier::AS_public) { CatchHandlerType Check(S->getType(), CheckAgainstPointer); const auto &M = TypesToCheck; auto I = M.find(Check); if (I != M.end()) { FoundHandler = I->second; FoundHandlerType = Ctx.getCanonicalType(S->getType()); return true; } } return false; } }; } /// ActOnCXXTryBlock - Takes a try compound-statement and a number of /// handlers and creates a try statement from them. StmtResult Sema::ActOnCXXTryBlock(SourceLocation TryLoc, Stmt *TryBlock, ArrayRef<Stmt *> Handlers) { // Don't report an error if 'try' is used in system headers. if (!getLangOpts().CXXExceptions && !getSourceManager().isInSystemHeader(TryLoc) && !getLangOpts().CUDA) { // Delay error emission for the OpenMP device code. targetDiag(TryLoc, diag::err_exceptions_disabled) << "try"; } // Exceptions aren't allowed in CUDA device code. if (getLangOpts().CUDA) CUDADiagIfDeviceCode(TryLoc, diag::err_cuda_device_exceptions) << "try" << CurrentCUDATarget(); if (getCurScope() && getCurScope()->isOpenMPSimdDirectiveScope()) Diag(TryLoc, diag::err_omp_simd_region_cannot_use_stmt) << "try"; sema::FunctionScopeInfo *FSI = getCurFunction(); // C++ try is incompatible with SEH __try. if (!getLangOpts().Borland && FSI->FirstSEHTryLoc.isValid()) { Diag(TryLoc, diag::err_mixing_cxx_try_seh_try); Diag(FSI->FirstSEHTryLoc, diag::note_conflicting_try_here) << "'__try'"; } const unsigned NumHandlers = Handlers.size(); assert(!Handlers.empty() && "The parser shouldn't call this if there are no handlers."); llvm::DenseMap<CatchHandlerType, CXXCatchStmt *> HandledTypes; for (unsigned i = 0; i < NumHandlers; ++i) { CXXCatchStmt *H = cast<CXXCatchStmt>(Handlers[i]); // Diagnose when the handler is a catch-all handler, but it isn't the last // handler for the try block. [except.handle]p5. Also, skip exception // declarations that are invalid, since we can't usefully report on them. if (!H->getExceptionDecl()) { if (i < NumHandlers - 1) return StmtError(Diag(H->getBeginLoc(), diag::err_early_catch_all)); continue; } else if (H->getExceptionDecl()->isInvalidDecl()) continue; // Walk the type hierarchy to diagnose when this type has already been // handled (duplication), or cannot be handled (derivation inversion). We // ignore top-level cv-qualifiers, per [except.handle]p3 CatchHandlerType HandlerCHT = (QualType)Context.getCanonicalType(H->getCaughtType()); // We can ignore whether the type is a reference or a pointer; we need the // underlying declaration type in order to get at the underlying record // decl, if there is one. QualType Underlying = HandlerCHT.underlying(); if (auto *RD = Underlying->getAsCXXRecordDecl()) { if (!RD->hasDefinition()) continue; // Check that none of the public, unambiguous base classes are in the // map ([except.handle]p1). Give the base classes the same pointer // qualification as the original type we are basing off of. This allows // comparison against the handler type using the same top-level pointer // as the original type. CXXBasePaths Paths; Paths.setOrigin(RD); CatchTypePublicBases CTPB(Context, HandledTypes, HandlerCHT.isPointer()); if (RD->lookupInBases(CTPB, Paths)) { const CXXCatchStmt *Problem = CTPB.getFoundHandler(); if (!Paths.isAmbiguous(CTPB.getFoundHandlerType())) { Diag(H->getExceptionDecl()->getTypeSpecStartLoc(), diag::warn_exception_caught_by_earlier_handler) << H->getCaughtType(); Diag(Problem->getExceptionDecl()->getTypeSpecStartLoc(), diag::note_previous_exception_handler) << Problem->getCaughtType(); } } } // Add the type the list of ones we have handled; diagnose if we've already // handled it. auto R = HandledTypes.insert(std::make_pair(H->getCaughtType(), H)); if (!R.second) { const CXXCatchStmt *Problem = R.first->second; Diag(H->getExceptionDecl()->getTypeSpecStartLoc(), diag::warn_exception_caught_by_earlier_handler) << H->getCaughtType(); Diag(Problem->getExceptionDecl()->getTypeSpecStartLoc(), diag::note_previous_exception_handler) << Problem->getCaughtType(); } } FSI->setHasCXXTry(TryLoc); return CXXTryStmt::Create(Context, TryLoc, TryBlock, Handlers); } StmtResult Sema::ActOnSEHTryBlock(bool IsCXXTry, SourceLocation TryLoc, Stmt *TryBlock, Stmt *Handler) { assert(TryBlock && Handler); sema::FunctionScopeInfo *FSI = getCurFunction(); // SEH __try is incompatible with C++ try. Borland appears to support this, // however. if (!getLangOpts().Borland) { if (FSI->FirstCXXTryLoc.isValid()) { Diag(TryLoc, diag::err_mixing_cxx_try_seh_try); Diag(FSI->FirstCXXTryLoc, diag::note_conflicting_try_here) << "'try'"; } } FSI->setHasSEHTry(TryLoc); // Reject __try in Obj-C methods, blocks, and captured decls, since we don't // track if they use SEH. DeclContext *DC = CurContext; while (DC && !DC->isFunctionOrMethod()) DC = DC->getParent(); FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(DC); if (FD) FD->setUsesSEHTry(true); else Diag(TryLoc, diag::err_seh_try_outside_functions); // Reject __try on unsupported targets. if (!Context.getTargetInfo().isSEHTrySupported()) Diag(TryLoc, diag::err_seh_try_unsupported); return SEHTryStmt::Create(Context, IsCXXTry, TryLoc, TryBlock, Handler); } StmtResult Sema::ActOnSEHExceptBlock(SourceLocation Loc, Expr *FilterExpr, Stmt *Block) { assert(FilterExpr && Block); QualType FTy = FilterExpr->getType(); if (!FTy->isIntegerType() && !FTy->isDependentType()) { return StmtError( Diag(FilterExpr->getExprLoc(), diag::err_filter_expression_integral) << FTy); } return SEHExceptStmt::Create(Context, Loc, FilterExpr, Block); } void Sema::ActOnStartSEHFinallyBlock() { CurrentSEHFinally.push_back(CurScope); } void Sema::ActOnAbortSEHFinallyBlock() { CurrentSEHFinally.pop_back(); } StmtResult Sema::ActOnFinishSEHFinallyBlock(SourceLocation Loc, Stmt *Block) { assert(Block); CurrentSEHFinally.pop_back(); return SEHFinallyStmt::Create(Context, Loc, Block); } StmtResult Sema::ActOnSEHLeaveStmt(SourceLocation Loc, Scope *CurScope) { Scope *SEHTryParent = CurScope; while (SEHTryParent && !SEHTryParent->isSEHTryScope()) SEHTryParent = SEHTryParent->getParent(); if (!SEHTryParent) return StmtError(Diag(Loc, diag::err_ms___leave_not_in___try)); CheckJumpOutOfSEHFinally(*this, Loc, *SEHTryParent); return new (Context) SEHLeaveStmt(Loc); } StmtResult Sema::BuildMSDependentExistsStmt(SourceLocation KeywordLoc, bool IsIfExists, NestedNameSpecifierLoc QualifierLoc, DeclarationNameInfo NameInfo, Stmt *Nested) { return new (Context) MSDependentExistsStmt(KeywordLoc, IsIfExists, QualifierLoc, NameInfo, cast<CompoundStmt>(Nested)); } StmtResult Sema::ActOnMSDependentExistsStmt(SourceLocation KeywordLoc, bool IsIfExists, CXXScopeSpec &SS, UnqualifiedId &Name, Stmt *Nested) { return BuildMSDependentExistsStmt(KeywordLoc, IsIfExists, SS.getWithLocInContext(Context), GetNameFromUnqualifiedId(Name), Nested); } RecordDecl* Sema::CreateCapturedStmtRecordDecl(CapturedDecl *&CD, SourceLocation Loc, unsigned NumParams) { DeclContext *DC = CurContext; while (!(DC->isFunctionOrMethod() || DC->isRecord() || DC->isFileContext())) DC = DC->getParent(); RecordDecl *RD = nullptr; if (getLangOpts().CPlusPlus) RD = CXXRecordDecl::Create(Context, TTK_Struct, DC, Loc, Loc, /*Id=*/nullptr); else RD = RecordDecl::Create(Context, TTK_Struct, DC, Loc, Loc, /*Id=*/nullptr); RD->setCapturedRecord(); DC->addDecl(RD); RD->setImplicit(); RD->startDefinition(); assert(NumParams > 0 && "CapturedStmt requires context parameter"); CD = CapturedDecl::Create(Context, CurContext, NumParams); DC->addDecl(CD); return RD; } static bool buildCapturedStmtCaptureList(Sema &S, CapturedRegionScopeInfo *RSI, SmallVectorImpl<CapturedStmt::Capture> &Captures, SmallVectorImpl<Expr *> &CaptureInits) { for (const sema::Capture &Cap : RSI->Captures) { if (Cap.isInvalid()) continue; // Form the initializer for the capture. ExprResult Init = S.BuildCaptureInit(Cap, Cap.getLocation(), RSI->CapRegionKind == CR_OpenMP); // FIXME: Bail out now if the capture is not used and the initializer has // no side-effects. // Create a field for this capture. FieldDecl *Field = S.BuildCaptureField(RSI->TheRecordDecl, Cap); // Add the capture to our list of captures. if (Cap.isThisCapture()) { Captures.push_back(CapturedStmt::Capture(Cap.getLocation(), CapturedStmt::VCK_This)); } else if (Cap.isVLATypeCapture()) { Captures.push_back( CapturedStmt::Capture(Cap.getLocation(), CapturedStmt::VCK_VLAType)); } else { assert(Cap.isVariableCapture() && "unknown kind of capture"); if (S.getLangOpts().OpenMP && RSI->CapRegionKind == CR_OpenMP) S.setOpenMPCaptureKind(Field, Cap.getVariable(), RSI->OpenMPLevel); Captures.push_back(CapturedStmt::Capture(Cap.getLocation(), Cap.isReferenceCapture() ? CapturedStmt::VCK_ByRef : CapturedStmt::VCK_ByCopy, Cap.getVariable())); } CaptureInits.push_back(Init.get()); } return false; } void Sema::ActOnCapturedRegionStart(SourceLocation Loc, Scope *CurScope, CapturedRegionKind Kind, unsigned NumParams) { CapturedDecl *CD = nullptr; RecordDecl *RD = CreateCapturedStmtRecordDecl(CD, Loc, NumParams); // Build the context parameter DeclContext *DC = CapturedDecl::castToDeclContext(CD); IdentifierInfo *ParamName = &Context.Idents.get("__context"); QualType ParamType = Context.getPointerType(Context.getTagDeclType(RD)); auto *Param = ImplicitParamDecl::Create(Context, DC, Loc, ParamName, ParamType, ImplicitParamDecl::CapturedContext); DC->addDecl(Param); CD->setContextParam(0, Param); // Enter the capturing scope for this captured region. PushCapturedRegionScope(CurScope, CD, RD, Kind); if (CurScope) PushDeclContext(CurScope, CD); else CurContext = CD; PushExpressionEvaluationContext( ExpressionEvaluationContext::PotentiallyEvaluated); } void Sema::ActOnCapturedRegionStart(SourceLocation Loc, Scope *CurScope, CapturedRegionKind Kind, ArrayRef<CapturedParamNameType> Params, unsigned OpenMPCaptureLevel) { CapturedDecl *CD = nullptr; RecordDecl *RD = CreateCapturedStmtRecordDecl(CD, Loc, Params.size()); // Build the context parameter DeclContext *DC = CapturedDecl::castToDeclContext(CD); bool ContextIsFound = false; unsigned ParamNum = 0; for (ArrayRef<CapturedParamNameType>::iterator I = Params.begin(), E = Params.end(); I != E; ++I, ++ParamNum) { if (I->second.isNull()) { assert(!ContextIsFound && "null type has been found already for '__context' parameter"); IdentifierInfo *ParamName = &Context.Idents.get("__context"); QualType ParamType = Context.getPointerType(Context.getTagDeclType(RD)) .withConst() .withRestrict(); auto *Param = ImplicitParamDecl::Create(Context, DC, Loc, ParamName, ParamType, ImplicitParamDecl::CapturedContext); DC->addDecl(Param); CD->setContextParam(ParamNum, Param); ContextIsFound = true; } else { IdentifierInfo *ParamName = &Context.Idents.get(I->first); auto *Param = ImplicitParamDecl::Create(Context, DC, Loc, ParamName, I->second, ImplicitParamDecl::CapturedContext); DC->addDecl(Param); CD->setParam(ParamNum, Param); } } assert(ContextIsFound && "no null type for '__context' parameter"); if (!ContextIsFound) { // Add __context implicitly if it is not specified. IdentifierInfo *ParamName = &Context.Idents.get("__context"); QualType ParamType = Context.getPointerType(Context.getTagDeclType(RD)); auto *Param = ImplicitParamDecl::Create(Context, DC, Loc, ParamName, ParamType, ImplicitParamDecl::CapturedContext); DC->addDecl(Param); CD->setContextParam(ParamNum, Param); } // Enter the capturing scope for this captured region. PushCapturedRegionScope(CurScope, CD, RD, Kind, OpenMPCaptureLevel); if (CurScope) PushDeclContext(CurScope, CD); else CurContext = CD; PushExpressionEvaluationContext( ExpressionEvaluationContext::PotentiallyEvaluated); } void Sema::ActOnCapturedRegionError() { DiscardCleanupsInEvaluationContext(); PopExpressionEvaluationContext(); PopDeclContext(); PoppedFunctionScopePtr ScopeRAII = PopFunctionScopeInfo(); CapturedRegionScopeInfo *RSI = cast<CapturedRegionScopeInfo>(ScopeRAII.get()); RecordDecl *Record = RSI->TheRecordDecl; Record->setInvalidDecl(); SmallVector<Decl*, 4> Fields(Record->fields()); ActOnFields(/*Scope=*/nullptr, Record->getLocation(), Record, Fields, SourceLocation(), SourceLocation(), ParsedAttributesView()); } StmtResult Sema::ActOnCapturedRegionEnd(Stmt *S) { // Leave the captured scope before we start creating captures in the // enclosing scope. DiscardCleanupsInEvaluationContext(); PopExpressionEvaluationContext(); PopDeclContext(); PoppedFunctionScopePtr ScopeRAII = PopFunctionScopeInfo(); CapturedRegionScopeInfo *RSI = cast<CapturedRegionScopeInfo>(ScopeRAII.get()); SmallVector<CapturedStmt::Capture, 4> Captures; SmallVector<Expr *, 4> CaptureInits; if (buildCapturedStmtCaptureList(*this, RSI, Captures, CaptureInits)) return StmtError(); CapturedDecl *CD = RSI->TheCapturedDecl; RecordDecl *RD = RSI->TheRecordDecl; CapturedStmt *Res = CapturedStmt::Create( getASTContext(), S, static_cast<CapturedRegionKind>(RSI->CapRegionKind), Captures, CaptureInits, CD, RD); CD->setBody(Res->getCapturedStmt()); RD->completeDefinition(); return Res; }
[ "wangyankun@ishumei.com" ]
wangyankun@ishumei.com
eea1fff89142c5ab42489be27930058bfc690a26
2070bbef01a4e6865b384647532de509c76def17
/代码/VMD/vmdWriter.h
d860300121985f058ca21bc95a6d85a26d2c669d
[]
no_license
KIE9542c/3D-Motion-Tracking-and-Output
a8343609cad43aeb04eb7d29caf8404326db21b5
45ae4d38f5d4ec73f13610d415aa44a08fe293b0
refs/heads/master
2020-05-31T23:05:53.707801
2019-07-17T09:25:50
2019-07-17T09:25:50
190,531,486
0
0
null
null
null
null
GB18030
C++
false
false
1,104
h
//#pragma once #include <iostream> #include <fstream> #include <string> #include <vector> #include <json\json.h> #include <QtGui\qquaternion.h> #include <QtGui\qvector3d.h> class vmdWriter { public: vmdWriter(std::string filename, std::string modelname, bool type); bool readPosition(); bool isOpenMMD(); void setBoneIndex(); void transferCoordinate(); void processRotaion(int index); void processPosition(int index); void writeFile(); void test(); private: char version[30] = "Vocaloid Motion Data 0002"; char modelName[20]; uint32_t keyFrameNumber; uint32_t frameTime; float position[4][3]; //0~3分别是其他骨骼,センター,左足IK,右足IK float rotation[10][4]; //0~9分别是センター,下半身,上半身,首,左腕,左ひじ,右腕,右ひじ,左足IK,右足IK uint32_t XCurve[4]; uint32_t YCurve[4]; uint32_t ZCurve[4]; uint32_t RCurve[4]; bool isopenMMD; //true表示输入的骨骼坐标是openMMD导出的,否则为Vnect导出的 int boneIndex[17]; std::string fileName; std::vector<std::vector<QVector3D>> gPosition; };
[ "51349604+scutWu@users.noreply.github.com" ]
51349604+scutWu@users.noreply.github.com
6726f97200d0787bfaad09d7b9fb781b3e7d7d7b
65025edce8120ec0c601bd5e6485553697c5c132
/Engine/addons/myguiengine/src/MyGUI_SkinItem.cpp
2fd27e264a854438134b454b1cf07cba6968c38b
[ "MIT" ]
permissive
stonejiang/genesis-3d
babfc99cfc9085527dff35c7c8662d931fbb1780
df5741e7003ba8e21d21557d42f637cfe0f6133c
refs/heads/master
2020-12-25T18:22:32.752912
2013-12-13T07:45:17
2013-12-13T07:45:17
15,157,071
4
4
null
null
null
null
UTF-8
C++
false
false
4,799
cpp
/*! @file @author Albert Semenov @date 06/2008 */ /* This file is part of MyGUI. MyGUI is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. MyGUI is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with MyGUI. If not, see <http://www.gnu.org/licenses/>. */ #include "MyGUI_Precompiled.h" #include "MyGUI_SkinItem.h" #include "MyGUI_FactoryManager.h" #include "MyGUI_Widget.h" #include "MyGUI_RenderManager.h" namespace MyGUI { SkinItem::SkinItem() : mText(nullptr), mMainSkin(nullptr), mTexture(nullptr), mSubSkinsVisible(true) { } void SkinItem::_setSkinItemAlign(const IntSize& _size) { for (VectorSubWidget::iterator skin = mSubSkinChild.begin(); skin != mSubSkinChild.end(); ++skin) (*skin)->_setAlign(_size); } void SkinItem::_setSkinItemVisible(bool _value) { for (VectorSubWidget::iterator skin = mSubSkinChild.begin(); skin != mSubSkinChild.end(); ++skin) (*skin)->setVisible(_value); } void SkinItem::_setSkinItemColour(const Colour& _value) { for (VectorSubWidget::iterator skin = mSubSkinChild.begin(); skin != mSubSkinChild.end(); ++skin) { ISubWidgetRect* rect = (*skin)->castType<ISubWidgetRect>(false); if (rect) rect->_setColour(_value); } } void SkinItem::_setSkinItemAlpha(float _value) { for (VectorSubWidget::iterator skin = mSubSkinChild.begin(); skin != mSubSkinChild.end(); ++skin) (*skin)->setAlpha(_value); } void SkinItem::_correctSkinItemView() { for (VectorSubWidget::iterator skin = mSubSkinChild.begin(); skin != mSubSkinChild.end(); ++skin) (*skin)->_correctView(); } void SkinItem::_updateSkinItemView() { for (VectorSubWidget::iterator skin = mSubSkinChild.begin(); skin != mSubSkinChild.end(); ++skin) (*skin)->_updateView(); } bool SkinItem::_setSkinItemState(const std::string& _state) { MapWidgetStateInfo::const_iterator iter = mStateInfo.find(_state); if (iter == mStateInfo.end()) return false; size_t index = 0; for (VectorSubWidget::iterator skin = mSubSkinChild.begin(); skin != mSubSkinChild.end(); ++skin, ++index) { IStateInfo* data = (*iter).second[index]; if (data != nullptr) (*skin)->setStateData(data); } return true; } void SkinItem::_createSkinItem(ResourceSkin* _info) { mStateInfo = _info->getStateInfo(); // все что с текстурой можно тоже перенести в скин айтем и setRenderItemTexture mTextureName = _info->getTextureName(); mTexture = RenderManager::getInstance().getTexture(mTextureName); setRenderItemTexture(mTexture); // загружаем кирпичики виджета FactoryManager& factory = FactoryManager::getInstance(); for (VectorSubWidgetInfo::const_iterator iter = _info->getBasisInfo().begin(); iter != _info->getBasisInfo().end(); ++iter) { IObject* object = factory.createObject("BasisSkin", (*iter).type); if (object == nullptr) continue; ISubWidget* sub = object->castType<ISubWidget>(); sub->_setCroppedParent(static_cast<Widget*>(this)); sub->setCoord((*iter).coord); sub->setAlign((*iter).align); mSubSkinChild.push_back(sub); addRenderItem(sub); // ищем дефолтные сабвиджеты if (mMainSkin == nullptr) mMainSkin = sub->castType<ISubWidgetRect>(false); if (mText == nullptr) mText = sub->castType<ISubWidgetText>(false); } _setSkinItemState("normal"); } void SkinItem::_deleteSkinItem() { mTexture = nullptr; mStateInfo.clear(); removeAllRenderItems(); // удаляем все сабскины mMainSkin = nullptr; mText = nullptr; for (VectorSubWidget::iterator skin = mSubSkinChild.begin(); skin != mSubSkinChild.end(); ++skin) delete (*skin); mSubSkinChild.clear(); } void SkinItem::_setTextureName(const std::string& _texture) { mTextureName = _texture; mTexture = RenderManager::getInstance().getTexture(mTextureName); setRenderItemTexture(mTexture); } const std::string& SkinItem::_getTextureName() const { return mTextureName; } void SkinItem::_setSubSkinVisible(bool _visible) { if (mSubSkinsVisible == _visible) return; mSubSkinsVisible = _visible; _updateSkinItemView(); } ISubWidgetText* SkinItem::getSubWidgetText() { return mText; } ISubWidgetRect* SkinItem::getSubWidgetMain() { return mMainSkin; } } // namespace MyGUI
[ "jiangtao@tao-studio.net" ]
jiangtao@tao-studio.net
33eaf7aee5d94513a89b93675781f339d1ce494b
a998bfde47dc0f18382741212edd56e07c035070
/cc/layers/layer_impl_unittest.cc
8d120bef621d19b9f40f424451858278f6ed743b
[ "BSD-3-Clause" ]
permissive
dalecurtis/mojo
92c8ce2e339ae923d387e2bdab4591f2165a9e25
e8ee0eb8a26abe43299b95054275939da9defd14
refs/heads/master
2021-01-15T11:44:31.238006
2014-10-23T18:48:50
2014-10-23T18:48:50
null
0
0
null
null
null
null
UTF-8
C++
false
false
32,383
cc
// Copyright 2011 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 "cc/layers/layer_impl.h" #include "cc/layers/painted_scrollbar_layer_impl.h" #include "cc/output/filter_operation.h" #include "cc/output/filter_operations.h" #include "cc/test/fake_impl_proxy.h" #include "cc/test/fake_layer_tree_host_impl.h" #include "cc/test/fake_output_surface.h" #include "cc/test/geometry_test_utils.h" #include "cc/test/test_shared_bitmap_manager.h" #include "cc/trees/layer_tree_impl.h" #include "cc/trees/single_thread_proxy.h" #include "testing/gmock/include/gmock/gmock.h" #include "testing/gtest/include/gtest/gtest.h" #include "third_party/skia/include/effects/SkBlurImageFilter.h" namespace cc { namespace { #define EXECUTE_AND_VERIFY_SUBTREE_CHANGED(code_to_test) \ root->ResetAllChangeTrackingForSubtree(); \ code_to_test; \ EXPECT_TRUE(root->needs_push_properties()); \ EXPECT_FALSE(child->needs_push_properties()); \ EXPECT_FALSE(grand_child->needs_push_properties()); \ EXPECT_TRUE(root->LayerPropertyChanged()); \ EXPECT_TRUE(child->LayerPropertyChanged()); \ EXPECT_TRUE(grand_child->LayerPropertyChanged()); #define EXECUTE_AND_VERIFY_SUBTREE_DID_NOT_CHANGE(code_to_test) \ root->ResetAllChangeTrackingForSubtree(); \ code_to_test; \ EXPECT_FALSE(root->needs_push_properties()); \ EXPECT_FALSE(child->needs_push_properties()); \ EXPECT_FALSE(grand_child->needs_push_properties()); \ EXPECT_FALSE(root->LayerPropertyChanged()); \ EXPECT_FALSE(child->LayerPropertyChanged()); \ EXPECT_FALSE(grand_child->LayerPropertyChanged()); #define EXECUTE_AND_VERIFY_NEEDS_PUSH_PROPERTIES_AND_SUBTREE_DID_NOT_CHANGE( \ code_to_test) \ root->ResetAllChangeTrackingForSubtree(); \ code_to_test; \ EXPECT_TRUE(root->needs_push_properties()); \ EXPECT_FALSE(child->needs_push_properties()); \ EXPECT_FALSE(grand_child->needs_push_properties()); \ EXPECT_FALSE(root->LayerPropertyChanged()); \ EXPECT_FALSE(child->LayerPropertyChanged()); \ EXPECT_FALSE(grand_child->LayerPropertyChanged()); #define EXECUTE_AND_VERIFY_ONLY_LAYER_CHANGED(code_to_test) \ root->ResetAllChangeTrackingForSubtree(); \ code_to_test; \ EXPECT_TRUE(root->needs_push_properties()); \ EXPECT_FALSE(child->needs_push_properties()); \ EXPECT_FALSE(grand_child->needs_push_properties()); \ EXPECT_TRUE(root->LayerPropertyChanged()); \ EXPECT_FALSE(child->LayerPropertyChanged()); \ EXPECT_FALSE(grand_child->LayerPropertyChanged()); #define VERIFY_NEEDS_UPDATE_DRAW_PROPERTIES(code_to_test) \ root->ResetAllChangeTrackingForSubtree(); \ host_impl.ForcePrepareToDraw(); \ EXPECT_FALSE(host_impl.active_tree()->needs_update_draw_properties()); \ code_to_test; \ EXPECT_TRUE(host_impl.active_tree()->needs_update_draw_properties()); #define VERIFY_NO_NEEDS_UPDATE_DRAW_PROPERTIES(code_to_test) \ root->ResetAllChangeTrackingForSubtree(); \ host_impl.ForcePrepareToDraw(); \ EXPECT_FALSE(host_impl.active_tree()->needs_update_draw_properties()); \ code_to_test; \ EXPECT_FALSE(host_impl.active_tree()->needs_update_draw_properties()); TEST(LayerImplTest, VerifyLayerChangesAreTrackedProperly) { // // This test checks that layerPropertyChanged() has the correct behavior. // // The constructor on this will fake that we are on the correct thread. // Create a simple LayerImpl tree: FakeImplProxy proxy; TestSharedBitmapManager shared_bitmap_manager; FakeLayerTreeHostImpl host_impl(&proxy, &shared_bitmap_manager); EXPECT_TRUE(host_impl.InitializeRenderer(FakeOutputSurface::Create3d())); scoped_ptr<LayerImpl> root_clip = LayerImpl::Create(host_impl.active_tree(), 1); scoped_ptr<LayerImpl> root_ptr = LayerImpl::Create(host_impl.active_tree(), 2); LayerImpl* root = root_ptr.get(); root_clip->AddChild(root_ptr.Pass()); scoped_ptr<LayerImpl> scroll_parent = LayerImpl::Create(host_impl.active_tree(), 3); LayerImpl* scroll_child = LayerImpl::Create(host_impl.active_tree(), 4).get(); std::set<LayerImpl*>* scroll_children = new std::set<LayerImpl*>(); scroll_children->insert(scroll_child); scroll_children->insert(root); scoped_ptr<LayerImpl> clip_parent = LayerImpl::Create(host_impl.active_tree(), 5); LayerImpl* clip_child = LayerImpl::Create(host_impl.active_tree(), 6).get(); std::set<LayerImpl*>* clip_children = new std::set<LayerImpl*>(); clip_children->insert(clip_child); clip_children->insert(root); root->AddChild(LayerImpl::Create(host_impl.active_tree(), 7)); LayerImpl* child = root->children()[0]; child->AddChild(LayerImpl::Create(host_impl.active_tree(), 8)); LayerImpl* grand_child = child->children()[0]; root->SetScrollClipLayer(root_clip->id()); // Adding children is an internal operation and should not mark layers as // changed. EXPECT_FALSE(root->LayerPropertyChanged()); EXPECT_FALSE(child->LayerPropertyChanged()); EXPECT_FALSE(grand_child->LayerPropertyChanged()); gfx::PointF arbitrary_point_f = gfx::PointF(0.125f, 0.25f); gfx::Point3F arbitrary_point_3f = gfx::Point3F(0.125f, 0.25f, 0.f); float arbitrary_number = 0.352f; gfx::Size arbitrary_size = gfx::Size(111, 222); gfx::Point arbitrary_point = gfx::Point(333, 444); gfx::Vector2d arbitrary_vector2d = gfx::Vector2d(111, 222); gfx::Rect arbitrary_rect = gfx::Rect(arbitrary_point, arbitrary_size); gfx::RectF arbitrary_rect_f = gfx::RectF(arbitrary_point_f, gfx::SizeF(1.234f, 5.678f)); SkColor arbitrary_color = SkColorSetRGB(10, 20, 30); gfx::Transform arbitrary_transform; arbitrary_transform.Scale3d(0.1f, 0.2f, 0.3f); FilterOperations arbitrary_filters; arbitrary_filters.Append(FilterOperation::CreateOpacityFilter(0.5f)); SkXfermode::Mode arbitrary_blend_mode = SkXfermode::kMultiply_Mode; // These properties are internal, and should not be considered "change" when // they are used. EXECUTE_AND_VERIFY_NEEDS_PUSH_PROPERTIES_AND_SUBTREE_DID_NOT_CHANGE( root->SetUpdateRect(arbitrary_rect)); EXECUTE_AND_VERIFY_ONLY_LAYER_CHANGED(root->SetBounds(arbitrary_size)); // Changing these properties affects the entire subtree of layers. EXECUTE_AND_VERIFY_SUBTREE_CHANGED( root->SetTransformOrigin(arbitrary_point_3f)); EXECUTE_AND_VERIFY_SUBTREE_CHANGED(root->SetFilters(arbitrary_filters)); EXECUTE_AND_VERIFY_SUBTREE_CHANGED(root->SetFilters(FilterOperations())); EXECUTE_AND_VERIFY_SUBTREE_CHANGED( root->SetMaskLayer(LayerImpl::Create(host_impl.active_tree(), 9))); EXECUTE_AND_VERIFY_SUBTREE_CHANGED(root->SetMasksToBounds(true)); EXECUTE_AND_VERIFY_SUBTREE_CHANGED(root->SetContentsOpaque(true)); EXECUTE_AND_VERIFY_SUBTREE_CHANGED( root->SetReplicaLayer(LayerImpl::Create(host_impl.active_tree(), 10))); EXECUTE_AND_VERIFY_SUBTREE_CHANGED(root->SetPosition(arbitrary_point_f)); EXECUTE_AND_VERIFY_SUBTREE_CHANGED(root->SetShouldFlattenTransform(false)); EXECUTE_AND_VERIFY_SUBTREE_CHANGED(root->Set3dSortingContextId(1)); EXECUTE_AND_VERIFY_SUBTREE_CHANGED( root->SetDoubleSided(false)); // constructor initializes it to "true". EXECUTE_AND_VERIFY_SUBTREE_CHANGED(root->ScrollBy(arbitrary_vector2d)); EXECUTE_AND_VERIFY_SUBTREE_CHANGED(root->SetScrollDelta(gfx::Vector2d())); EXECUTE_AND_VERIFY_SUBTREE_CHANGED( root->SetScrollOffset(gfx::ScrollOffset(arbitrary_vector2d))); EXECUTE_AND_VERIFY_SUBTREE_CHANGED(root->SetHideLayerAndSubtree(true)); EXECUTE_AND_VERIFY_SUBTREE_CHANGED(root->SetOpacity(arbitrary_number)); EXECUTE_AND_VERIFY_SUBTREE_CHANGED(root->SetBlendMode(arbitrary_blend_mode)); EXECUTE_AND_VERIFY_SUBTREE_CHANGED(root->SetTransform(arbitrary_transform)); // Changing these properties only affects the layer itself. EXECUTE_AND_VERIFY_ONLY_LAYER_CHANGED(root->SetContentBounds(arbitrary_size)); EXECUTE_AND_VERIFY_ONLY_LAYER_CHANGED( root->SetContentsScale(arbitrary_number, arbitrary_number)); EXECUTE_AND_VERIFY_ONLY_LAYER_CHANGED(root->SetDrawsContent(true)); EXECUTE_AND_VERIFY_ONLY_LAYER_CHANGED( root->SetBackgroundColor(arbitrary_color)); EXECUTE_AND_VERIFY_ONLY_LAYER_CHANGED( root->SetBackgroundFilters(arbitrary_filters)); // Special case: check that SetBounds changes behavior depending on // masksToBounds. root->SetMasksToBounds(false); EXECUTE_AND_VERIFY_ONLY_LAYER_CHANGED(root->SetBounds(gfx::Size(135, 246))); root->SetMasksToBounds(true); // Should be a different size than previous call, to ensure it marks tree // changed. EXECUTE_AND_VERIFY_SUBTREE_CHANGED(root->SetBounds(arbitrary_size)); // Changing this property does not cause the layer to be marked as changed // but does cause the layer to need to push properties. EXECUTE_AND_VERIFY_NEEDS_PUSH_PROPERTIES_AND_SUBTREE_DID_NOT_CHANGE( root->SetIsRootForIsolatedGroup(true)); // Changing these properties should cause the layer to need to push properties EXECUTE_AND_VERIFY_NEEDS_PUSH_PROPERTIES_AND_SUBTREE_DID_NOT_CHANGE( root->SetScrollParent(scroll_parent.get())); EXECUTE_AND_VERIFY_NEEDS_PUSH_PROPERTIES_AND_SUBTREE_DID_NOT_CHANGE( root->SetScrollChildren(scroll_children)); EXECUTE_AND_VERIFY_NEEDS_PUSH_PROPERTIES_AND_SUBTREE_DID_NOT_CHANGE( root->SetClipParent(clip_parent.get())); EXECUTE_AND_VERIFY_NEEDS_PUSH_PROPERTIES_AND_SUBTREE_DID_NOT_CHANGE( root->SetClipChildren(clip_children)); EXECUTE_AND_VERIFY_NEEDS_PUSH_PROPERTIES_AND_SUBTREE_DID_NOT_CHANGE( root->SetNumDescendantsThatDrawContent(10)); // After setting all these properties already, setting to the exact same // values again should not cause any change. EXECUTE_AND_VERIFY_SUBTREE_DID_NOT_CHANGE( root->SetTransformOrigin(arbitrary_point_3f)); EXECUTE_AND_VERIFY_SUBTREE_DID_NOT_CHANGE(root->SetMasksToBounds(true)); EXECUTE_AND_VERIFY_SUBTREE_DID_NOT_CHANGE( root->SetPosition(arbitrary_point_f)); EXECUTE_AND_VERIFY_SUBTREE_DID_NOT_CHANGE( root->SetShouldFlattenTransform(false)); EXECUTE_AND_VERIFY_SUBTREE_DID_NOT_CHANGE(root->Set3dSortingContextId(1)); EXECUTE_AND_VERIFY_SUBTREE_DID_NOT_CHANGE( root->SetTransform(arbitrary_transform)); EXECUTE_AND_VERIFY_SUBTREE_DID_NOT_CHANGE( root->SetDoubleSided(false)); // constructor initializes it to "true". EXECUTE_AND_VERIFY_SUBTREE_DID_NOT_CHANGE( root->SetScrollDelta(gfx::Vector2d())); EXECUTE_AND_VERIFY_SUBTREE_DID_NOT_CHANGE( root->SetScrollOffset(gfx::ScrollOffset(arbitrary_vector2d))); EXECUTE_AND_VERIFY_SUBTREE_DID_NOT_CHANGE( root->SetContentBounds(arbitrary_size)); EXECUTE_AND_VERIFY_SUBTREE_DID_NOT_CHANGE( root->SetContentsScale(arbitrary_number, arbitrary_number)); EXECUTE_AND_VERIFY_SUBTREE_DID_NOT_CHANGE(root->SetContentsOpaque(true)); EXECUTE_AND_VERIFY_SUBTREE_DID_NOT_CHANGE(root->SetOpacity(arbitrary_number)); EXECUTE_AND_VERIFY_SUBTREE_DID_NOT_CHANGE( root->SetBlendMode(arbitrary_blend_mode)); EXECUTE_AND_VERIFY_SUBTREE_DID_NOT_CHANGE( root->SetIsRootForIsolatedGroup(true)); EXECUTE_AND_VERIFY_SUBTREE_DID_NOT_CHANGE(root->SetDrawsContent(true)); EXECUTE_AND_VERIFY_SUBTREE_DID_NOT_CHANGE(root->SetBounds(arbitrary_size)); EXECUTE_AND_VERIFY_SUBTREE_DID_NOT_CHANGE( root->SetScrollParent(scroll_parent.get())); EXECUTE_AND_VERIFY_SUBTREE_DID_NOT_CHANGE( root->SetScrollChildren(scroll_children)); EXECUTE_AND_VERIFY_SUBTREE_DID_NOT_CHANGE( root->SetClipParent(clip_parent.get())); EXECUTE_AND_VERIFY_SUBTREE_DID_NOT_CHANGE( root->SetClipChildren(clip_children)); } TEST(LayerImplTest, VerifyNeedsUpdateDrawProperties) { FakeImplProxy proxy; TestSharedBitmapManager shared_bitmap_manager; FakeLayerTreeHostImpl host_impl(&proxy, &shared_bitmap_manager); EXPECT_TRUE(host_impl.InitializeRenderer(FakeOutputSurface::Create3d())); host_impl.active_tree()->SetRootLayer( LayerImpl::Create(host_impl.active_tree(), 1)); LayerImpl* root = host_impl.active_tree()->root_layer(); scoped_ptr<LayerImpl> layer_ptr = LayerImpl::Create(host_impl.active_tree(), 2); LayerImpl* layer = layer_ptr.get(); root->AddChild(layer_ptr.Pass()); layer->SetScrollClipLayer(root->id()); DCHECK(host_impl.CanDraw()); gfx::PointF arbitrary_point_f = gfx::PointF(0.125f, 0.25f); float arbitrary_number = 0.352f; gfx::Size arbitrary_size = gfx::Size(111, 222); gfx::Point arbitrary_point = gfx::Point(333, 444); gfx::Vector2d arbitrary_vector2d = gfx::Vector2d(111, 222); gfx::Size large_size = gfx::Size(1000, 1000); gfx::Rect arbitrary_rect = gfx::Rect(arbitrary_point, arbitrary_size); gfx::RectF arbitrary_rect_f = gfx::RectF(arbitrary_point_f, gfx::SizeF(1.234f, 5.678f)); SkColor arbitrary_color = SkColorSetRGB(10, 20, 30); gfx::Transform arbitrary_transform; arbitrary_transform.Scale3d(0.1f, 0.2f, 0.3f); FilterOperations arbitrary_filters; arbitrary_filters.Append(FilterOperation::CreateOpacityFilter(0.5f)); SkXfermode::Mode arbitrary_blend_mode = SkXfermode::kMultiply_Mode; // Related filter functions. VERIFY_NEEDS_UPDATE_DRAW_PROPERTIES(layer->SetFilters(arbitrary_filters)); VERIFY_NO_NEEDS_UPDATE_DRAW_PROPERTIES(layer->SetFilters(arbitrary_filters)); VERIFY_NEEDS_UPDATE_DRAW_PROPERTIES(layer->SetFilters(FilterOperations())); VERIFY_NEEDS_UPDATE_DRAW_PROPERTIES(layer->SetFilters(arbitrary_filters)); // Related scrolling functions. VERIFY_NEEDS_UPDATE_DRAW_PROPERTIES(layer->SetBounds(large_size)); VERIFY_NO_NEEDS_UPDATE_DRAW_PROPERTIES(layer->SetBounds(large_size)); VERIFY_NEEDS_UPDATE_DRAW_PROPERTIES(layer->ScrollBy(arbitrary_vector2d)); VERIFY_NO_NEEDS_UPDATE_DRAW_PROPERTIES(layer->ScrollBy(gfx::Vector2d())); layer->SetScrollDelta(gfx::Vector2d(0, 0)); host_impl.ForcePrepareToDraw(); VERIFY_NEEDS_UPDATE_DRAW_PROPERTIES( layer->SetScrollDelta(arbitrary_vector2d)); VERIFY_NO_NEEDS_UPDATE_DRAW_PROPERTIES( layer->SetScrollDelta(arbitrary_vector2d)); VERIFY_NEEDS_UPDATE_DRAW_PROPERTIES( layer->SetScrollOffset(gfx::ScrollOffset(arbitrary_vector2d))); VERIFY_NO_NEEDS_UPDATE_DRAW_PROPERTIES( layer->SetScrollOffset(gfx::ScrollOffset(arbitrary_vector2d))); // Unrelated functions, always set to new values, always set needs update. VERIFY_NEEDS_UPDATE_DRAW_PROPERTIES( layer->SetMaskLayer(LayerImpl::Create(host_impl.active_tree(), 4))); VERIFY_NEEDS_UPDATE_DRAW_PROPERTIES(layer->SetMasksToBounds(true)); VERIFY_NEEDS_UPDATE_DRAW_PROPERTIES(layer->SetContentsOpaque(true)); VERIFY_NEEDS_UPDATE_DRAW_PROPERTIES( layer->SetReplicaLayer(LayerImpl::Create(host_impl.active_tree(), 5))); VERIFY_NEEDS_UPDATE_DRAW_PROPERTIES(layer->SetPosition(arbitrary_point_f)); VERIFY_NEEDS_UPDATE_DRAW_PROPERTIES(layer->SetShouldFlattenTransform(false)); VERIFY_NEEDS_UPDATE_DRAW_PROPERTIES(layer->Set3dSortingContextId(1)); VERIFY_NEEDS_UPDATE_DRAW_PROPERTIES( layer->SetDoubleSided(false)); // constructor initializes it to "true". VERIFY_NEEDS_UPDATE_DRAW_PROPERTIES(layer->SetContentBounds(arbitrary_size)); VERIFY_NEEDS_UPDATE_DRAW_PROPERTIES( layer->SetContentsScale(arbitrary_number, arbitrary_number)); VERIFY_NEEDS_UPDATE_DRAW_PROPERTIES(layer->SetDrawsContent(true)); VERIFY_NEEDS_UPDATE_DRAW_PROPERTIES( layer->SetBackgroundColor(arbitrary_color)); VERIFY_NEEDS_UPDATE_DRAW_PROPERTIES( layer->SetBackgroundFilters(arbitrary_filters)); VERIFY_NEEDS_UPDATE_DRAW_PROPERTIES(layer->SetOpacity(arbitrary_number)); VERIFY_NEEDS_UPDATE_DRAW_PROPERTIES( layer->SetBlendMode(arbitrary_blend_mode)); VERIFY_NEEDS_UPDATE_DRAW_PROPERTIES(layer->SetTransform(arbitrary_transform)); VERIFY_NEEDS_UPDATE_DRAW_PROPERTIES(layer->SetBounds(arbitrary_size)); // Unrelated functions, set to the same values, no needs update. VERIFY_NO_NEEDS_UPDATE_DRAW_PROPERTIES( layer->SetIsRootForIsolatedGroup(true)); VERIFY_NO_NEEDS_UPDATE_DRAW_PROPERTIES(layer->SetFilters(arbitrary_filters)); VERIFY_NO_NEEDS_UPDATE_DRAW_PROPERTIES(layer->SetMasksToBounds(true)); VERIFY_NO_NEEDS_UPDATE_DRAW_PROPERTIES(layer->SetContentsOpaque(true)); VERIFY_NO_NEEDS_UPDATE_DRAW_PROPERTIES(layer->SetPosition(arbitrary_point_f)); VERIFY_NO_NEEDS_UPDATE_DRAW_PROPERTIES(layer->Set3dSortingContextId(1)); VERIFY_NO_NEEDS_UPDATE_DRAW_PROPERTIES( layer->SetDoubleSided(false)); // constructor initializes it to "true". VERIFY_NO_NEEDS_UPDATE_DRAW_PROPERTIES( layer->SetContentBounds(arbitrary_size)); VERIFY_NO_NEEDS_UPDATE_DRAW_PROPERTIES( layer->SetContentsScale(arbitrary_number, arbitrary_number)); VERIFY_NO_NEEDS_UPDATE_DRAW_PROPERTIES(layer->SetDrawsContent(true)); VERIFY_NO_NEEDS_UPDATE_DRAW_PROPERTIES( layer->SetBackgroundColor(arbitrary_color)); VERIFY_NO_NEEDS_UPDATE_DRAW_PROPERTIES( layer->SetBackgroundFilters(arbitrary_filters)); VERIFY_NO_NEEDS_UPDATE_DRAW_PROPERTIES(layer->SetOpacity(arbitrary_number)); VERIFY_NO_NEEDS_UPDATE_DRAW_PROPERTIES( layer->SetBlendMode(arbitrary_blend_mode)); VERIFY_NO_NEEDS_UPDATE_DRAW_PROPERTIES( layer->SetIsRootForIsolatedGroup(true)); VERIFY_NO_NEEDS_UPDATE_DRAW_PROPERTIES( layer->SetTransform(arbitrary_transform)); VERIFY_NO_NEEDS_UPDATE_DRAW_PROPERTIES(layer->SetBounds(arbitrary_size)); } TEST(LayerImplTest, SafeOpaqueBackgroundColor) { FakeImplProxy proxy; TestSharedBitmapManager shared_bitmap_manager; FakeLayerTreeHostImpl host_impl(&proxy, &shared_bitmap_manager); EXPECT_TRUE(host_impl.InitializeRenderer(FakeOutputSurface::Create3d())); scoped_ptr<LayerImpl> layer = LayerImpl::Create(host_impl.active_tree(), 1); for (int contents_opaque = 0; contents_opaque < 2; ++contents_opaque) { for (int layer_opaque = 0; layer_opaque < 2; ++layer_opaque) { for (int host_opaque = 0; host_opaque < 2; ++host_opaque) { layer->SetContentsOpaque(!!contents_opaque); layer->SetBackgroundColor(layer_opaque ? SK_ColorRED : SK_ColorTRANSPARENT); host_impl.active_tree()->set_background_color( host_opaque ? SK_ColorRED : SK_ColorTRANSPARENT); SkColor safe_color = layer->SafeOpaqueBackgroundColor(); if (contents_opaque) { EXPECT_EQ(SkColorGetA(safe_color), 255u) << "Flags: " << contents_opaque << ", " << layer_opaque << ", " << host_opaque << "\n"; } else { EXPECT_NE(SkColorGetA(safe_color), 255u) << "Flags: " << contents_opaque << ", " << layer_opaque << ", " << host_opaque << "\n"; } } } } } TEST(LayerImplTest, TransformInvertibility) { FakeImplProxy proxy; TestSharedBitmapManager shared_bitmap_manager; FakeLayerTreeHostImpl host_impl(&proxy, &shared_bitmap_manager); scoped_ptr<LayerImpl> layer = LayerImpl::Create(host_impl.active_tree(), 1); EXPECT_TRUE(layer->transform().IsInvertible()); EXPECT_TRUE(layer->transform_is_invertible()); gfx::Transform transform; transform.Scale3d( SkDoubleToMScalar(1.0), SkDoubleToMScalar(1.0), SkDoubleToMScalar(0.0)); layer->SetTransform(transform); EXPECT_FALSE(layer->transform().IsInvertible()); EXPECT_FALSE(layer->transform_is_invertible()); transform.MakeIdentity(); transform.ApplyPerspectiveDepth(SkDoubleToMScalar(100.0)); transform.RotateAboutZAxis(75.0); transform.RotateAboutXAxis(32.2); transform.RotateAboutZAxis(-75.0); transform.Translate3d(SkDoubleToMScalar(50.5), SkDoubleToMScalar(42.42), SkDoubleToMScalar(-100.25)); layer->SetTransform(transform); EXPECT_TRUE(layer->transform().IsInvertible()); EXPECT_TRUE(layer->transform_is_invertible()); } class LayerImplScrollTest : public testing::Test { public: LayerImplScrollTest() : host_impl_(settings(), &proxy_, &shared_bitmap_manager_), root_id_(7) { host_impl_.active_tree()->SetRootLayer( LayerImpl::Create(host_impl_.active_tree(), root_id_)); host_impl_.active_tree()->root_layer()->AddChild( LayerImpl::Create(host_impl_.active_tree(), root_id_ + 1)); layer()->SetScrollClipLayer(root_id_); // Set the max scroll offset by noting that the root layer has bounds (1,1), // thus whatever bounds are set for the layer will be the max scroll // offset plus 1 in each direction. host_impl_.active_tree()->root_layer()->SetBounds(gfx::Size(1, 1)); gfx::Vector2d max_scroll_offset(51, 81); layer()->SetBounds(gfx::Size(max_scroll_offset.x(), max_scroll_offset.y())); } LayerImpl* layer() { return host_impl_.active_tree()->root_layer()->children()[0]; } LayerTreeImpl* tree() { return host_impl_.active_tree(); } LayerTreeSettings settings() { LayerTreeSettings settings; settings.use_pinch_virtual_viewport = true; return settings; } private: FakeImplProxy proxy_; TestSharedBitmapManager shared_bitmap_manager_; FakeLayerTreeHostImpl host_impl_; int root_id_; }; TEST_F(LayerImplScrollTest, ScrollByWithZeroOffset) { // Test that LayerImpl::ScrollBy only affects ScrollDelta and total scroll // offset is bounded by the range [0, max scroll offset]. EXPECT_VECTOR_EQ(gfx::Vector2dF(), layer()->TotalScrollOffset()); EXPECT_VECTOR_EQ(gfx::Vector2dF(), layer()->scroll_offset()); EXPECT_VECTOR_EQ(gfx::Vector2dF(), layer()->ScrollDelta()); layer()->ScrollBy(gfx::Vector2dF(-100, 100)); EXPECT_VECTOR_EQ(gfx::Vector2dF(0, 80), layer()->TotalScrollOffset()); EXPECT_VECTOR_EQ(layer()->ScrollDelta(), layer()->TotalScrollOffset()); EXPECT_VECTOR_EQ(gfx::Vector2dF(), layer()->scroll_offset()); layer()->ScrollBy(gfx::Vector2dF(100, -100)); EXPECT_VECTOR_EQ(gfx::Vector2dF(50, 0), layer()->TotalScrollOffset()); EXPECT_VECTOR_EQ(layer()->ScrollDelta(), layer()->TotalScrollOffset()); EXPECT_VECTOR_EQ(gfx::Vector2dF(), layer()->scroll_offset()); } TEST_F(LayerImplScrollTest, ScrollByWithNonZeroOffset) { gfx::ScrollOffset scroll_offset(10, 5); layer()->SetScrollOffset(scroll_offset); EXPECT_VECTOR_EQ(scroll_offset, layer()->TotalScrollOffset()); EXPECT_VECTOR_EQ(scroll_offset, layer()->scroll_offset()); EXPECT_VECTOR_EQ(gfx::Vector2dF(), layer()->ScrollDelta()); layer()->ScrollBy(gfx::Vector2dF(-100, 100)); EXPECT_VECTOR_EQ(gfx::Vector2dF(0, 80), layer()->TotalScrollOffset()); EXPECT_VECTOR_EQ(gfx::ScrollOffsetWithDelta(scroll_offset, layer()->ScrollDelta()), layer()->TotalScrollOffset()); EXPECT_VECTOR_EQ(scroll_offset, layer()->scroll_offset()); layer()->ScrollBy(gfx::Vector2dF(100, -100)); EXPECT_VECTOR_EQ(gfx::Vector2dF(50, 0), layer()->TotalScrollOffset()); EXPECT_VECTOR_EQ(gfx::ScrollOffsetWithDelta(scroll_offset, layer()->ScrollDelta()), layer()->TotalScrollOffset()); EXPECT_VECTOR_EQ(scroll_offset, layer()->scroll_offset()); } class ScrollDelegateIgnore : public LayerImpl::ScrollOffsetDelegate { public: void SetTotalScrollOffset(const gfx::ScrollOffset& new_value) override {} gfx::ScrollOffset GetTotalScrollOffset() override { return gfx::ScrollOffset(fixed_offset_); } bool IsExternalFlingActive() const override { return false; } void set_fixed_offset(const gfx::Vector2dF& fixed_offset) { fixed_offset_ = fixed_offset; } private: gfx::Vector2dF fixed_offset_; }; TEST_F(LayerImplScrollTest, ScrollByWithIgnoringDelegate) { gfx::ScrollOffset scroll_offset(10, 5); layer()->SetScrollOffset(scroll_offset); EXPECT_VECTOR_EQ(scroll_offset, layer()->TotalScrollOffset()); EXPECT_VECTOR_EQ(scroll_offset, layer()->scroll_offset()); EXPECT_VECTOR_EQ(gfx::Vector2dF(), layer()->ScrollDelta()); ScrollDelegateIgnore delegate; gfx::Vector2dF fixed_offset(32, 12); delegate.set_fixed_offset(fixed_offset); layer()->SetScrollOffsetDelegate(&delegate); EXPECT_VECTOR_EQ(fixed_offset, layer()->TotalScrollOffset()); EXPECT_VECTOR_EQ(scroll_offset, layer()->scroll_offset()); layer()->ScrollBy(gfx::Vector2dF(-100, 100)); EXPECT_VECTOR_EQ(fixed_offset, layer()->TotalScrollOffset()); EXPECT_VECTOR_EQ(scroll_offset, layer()->scroll_offset()); layer()->SetScrollOffsetDelegate(nullptr); EXPECT_VECTOR_EQ(fixed_offset, layer()->TotalScrollOffset()); EXPECT_VECTOR_EQ(scroll_offset, layer()->scroll_offset()); gfx::Vector2dF scroll_delta(1, 1); layer()->ScrollBy(scroll_delta); EXPECT_VECTOR_EQ(fixed_offset + scroll_delta, layer()->TotalScrollOffset()); EXPECT_VECTOR_EQ(scroll_offset, layer()->scroll_offset()); } class ScrollDelegateAccept : public LayerImpl::ScrollOffsetDelegate { public: void SetTotalScrollOffset(const gfx::ScrollOffset& new_value) override { current_offset_ = new_value; } gfx::ScrollOffset GetTotalScrollOffset() override { return current_offset_; } bool IsExternalFlingActive() const override { return false; } private: gfx::ScrollOffset current_offset_; }; TEST_F(LayerImplScrollTest, ScrollByWithAcceptingDelegate) { gfx::ScrollOffset scroll_offset(10, 5); layer()->SetScrollOffset(scroll_offset); EXPECT_VECTOR_EQ(scroll_offset, layer()->TotalScrollOffset()); EXPECT_VECTOR_EQ(scroll_offset, layer()->scroll_offset()); EXPECT_VECTOR_EQ(gfx::Vector2dF(), layer()->ScrollDelta()); ScrollDelegateAccept delegate; layer()->SetScrollOffsetDelegate(&delegate); EXPECT_VECTOR_EQ(scroll_offset, layer()->TotalScrollOffset()); EXPECT_VECTOR_EQ(scroll_offset, layer()->scroll_offset()); EXPECT_VECTOR_EQ(gfx::Vector2dF(), layer()->ScrollDelta()); layer()->ScrollBy(gfx::Vector2dF(-100, 100)); EXPECT_VECTOR_EQ(gfx::Vector2dF(0, 80), layer()->TotalScrollOffset()); EXPECT_VECTOR_EQ(scroll_offset, layer()->scroll_offset()); layer()->SetScrollOffsetDelegate(nullptr); EXPECT_VECTOR_EQ(gfx::Vector2dF(0, 80), layer()->TotalScrollOffset()); EXPECT_VECTOR_EQ(scroll_offset, layer()->scroll_offset()); gfx::Vector2dF scroll_delta(1, 1); layer()->ScrollBy(scroll_delta); EXPECT_VECTOR_EQ(gfx::Vector2dF(1, 80), layer()->TotalScrollOffset()); EXPECT_VECTOR_EQ(scroll_offset, layer()->scroll_offset()); } TEST_F(LayerImplScrollTest, ApplySentScrollsNoDelegate) { gfx::ScrollOffset scroll_offset(10, 5); gfx::Vector2dF scroll_delta(20.5f, 8.5f); gfx::Vector2d sent_scroll_delta(12, -3); layer()->SetScrollOffset(scroll_offset); layer()->ScrollBy(scroll_delta); layer()->SetSentScrollDelta(sent_scroll_delta); EXPECT_VECTOR_EQ(gfx::ScrollOffsetWithDelta(scroll_offset, scroll_delta), layer()->TotalScrollOffset()); EXPECT_VECTOR_EQ(scroll_delta, layer()->ScrollDelta()); EXPECT_VECTOR_EQ(scroll_offset, layer()->scroll_offset()); EXPECT_VECTOR_EQ(sent_scroll_delta, layer()->sent_scroll_delta()); layer()->ApplySentScrollDeltasFromAbortedCommit(); EXPECT_VECTOR_EQ(gfx::ScrollOffsetWithDelta(scroll_offset, scroll_delta), layer()->TotalScrollOffset()); EXPECT_VECTOR_EQ(scroll_delta - sent_scroll_delta, layer()->ScrollDelta()); EXPECT_VECTOR_EQ(gfx::ScrollOffsetWithDelta(scroll_offset, sent_scroll_delta), layer()->scroll_offset()); EXPECT_VECTOR_EQ(gfx::Vector2d(), layer()->sent_scroll_delta()); } TEST_F(LayerImplScrollTest, ApplySentScrollsWithIgnoringDelegate) { gfx::ScrollOffset scroll_offset(10, 5); gfx::Vector2d sent_scroll_delta(12, -3); gfx::Vector2dF fixed_offset(32, 12); layer()->SetScrollOffset(scroll_offset); ScrollDelegateIgnore delegate; delegate.set_fixed_offset(fixed_offset); layer()->SetScrollOffsetDelegate(&delegate); layer()->SetSentScrollDelta(sent_scroll_delta); EXPECT_VECTOR_EQ(fixed_offset, layer()->TotalScrollOffset()); EXPECT_VECTOR_EQ(scroll_offset, layer()->scroll_offset()); EXPECT_VECTOR_EQ(sent_scroll_delta, layer()->sent_scroll_delta()); layer()->ApplySentScrollDeltasFromAbortedCommit(); EXPECT_VECTOR_EQ(fixed_offset, layer()->TotalScrollOffset()); EXPECT_VECTOR_EQ(gfx::ScrollOffsetWithDelta(scroll_offset, sent_scroll_delta), layer()->scroll_offset()); EXPECT_VECTOR_EQ(gfx::Vector2d(), layer()->sent_scroll_delta()); } TEST_F(LayerImplScrollTest, ApplySentScrollsWithAcceptingDelegate) { gfx::ScrollOffset scroll_offset(10, 5); gfx::Vector2d sent_scroll_delta(12, -3); gfx::Vector2dF scroll_delta(20.5f, 8.5f); layer()->SetScrollOffset(scroll_offset); ScrollDelegateAccept delegate; layer()->SetScrollOffsetDelegate(&delegate); layer()->ScrollBy(scroll_delta); layer()->SetSentScrollDelta(sent_scroll_delta); EXPECT_VECTOR_EQ(gfx::ScrollOffsetWithDelta(scroll_offset, scroll_delta), layer()->TotalScrollOffset()); EXPECT_VECTOR_EQ(scroll_offset, layer()->scroll_offset()); EXPECT_VECTOR_EQ(sent_scroll_delta, layer()->sent_scroll_delta()); layer()->ApplySentScrollDeltasFromAbortedCommit(); EXPECT_VECTOR_EQ(gfx::ScrollOffsetWithDelta(scroll_offset, scroll_delta), layer()->TotalScrollOffset()); EXPECT_VECTOR_EQ(gfx::ScrollOffsetWithDelta(scroll_offset, sent_scroll_delta), layer()->scroll_offset()); EXPECT_VECTOR_EQ(gfx::Vector2d(), layer()->sent_scroll_delta()); } TEST_F(LayerImplScrollTest, ScrollUserUnscrollableLayer) { gfx::ScrollOffset scroll_offset(10, 5); gfx::Vector2dF scroll_delta(20.5f, 8.5f); layer()->set_user_scrollable_vertical(false); layer()->SetScrollOffset(scroll_offset); gfx::Vector2dF unscrolled = layer()->ScrollBy(scroll_delta); EXPECT_VECTOR_EQ(gfx::Vector2dF(0, 8.5f), unscrolled); EXPECT_VECTOR_EQ(gfx::Vector2dF(30.5f, 5), layer()->TotalScrollOffset()); } TEST_F(LayerImplScrollTest, SetNewScrollbarParameters) { gfx::ScrollOffset scroll_offset(10, 5); layer()->SetScrollOffset(scroll_offset); scoped_ptr<PaintedScrollbarLayerImpl> vertical_scrollbar( PaintedScrollbarLayerImpl::Create(tree(), 100, VERTICAL)); vertical_scrollbar->SetScrollLayerAndClipLayerByIds( layer()->id(), tree()->root_layer()->id()); int expected_vertical_maximum = layer()->bounds().height() - tree()->root_layer()->bounds().height(); EXPECT_EQ(expected_vertical_maximum, vertical_scrollbar->maximum()); EXPECT_EQ(scroll_offset.y(), vertical_scrollbar->current_pos()); scoped_ptr<PaintedScrollbarLayerImpl> horizontal_scrollbar( PaintedScrollbarLayerImpl::Create(tree(), 101, HORIZONTAL)); horizontal_scrollbar->SetScrollLayerAndClipLayerByIds( layer()->id(), tree()->root_layer()->id()); int expected_horizontal_maximum = layer()->bounds().width() - tree()->root_layer()->bounds().width(); EXPECT_EQ(expected_horizontal_maximum, horizontal_scrollbar->maximum()); EXPECT_EQ(scroll_offset.x(), horizontal_scrollbar->current_pos()); } } // namespace } // namespace cc
[ "jamesr@chromium.org" ]
jamesr@chromium.org
c6c5168f579c610a3e93a72598fa375028052fa4
25509aa66ad1a65663d42bf4ddbe9d1fa295fdab
/MyOpenGL/RendererPlayer.h
f3eccb68d467d7c6bd5da6e248393fa544f98d92
[]
no_license
NathanVss/Noxel-OpenGL
24b5d820d9df48bd5b68048a58ec056a3b93d28e
c48203cefc0e4eeaccb78868bd2609b2762666e0
refs/heads/master
2016-09-06T14:09:01.472705
2015-02-27T17:41:24
2015-02-27T17:41:24
29,501,753
0
0
null
null
null
null
UTF-8
C++
false
false
454
h
#pragma once #include "Object.h" #include <YuEngine\EventTimer.h> class Player; class RendererPlayer : public Object { public: RendererPlayer(void); RendererPlayer(Container* c, Player* player); ~RendererPlayer(void); void update(); void render(); void renderArm(); float getPixelSize() { return pixelSize; } private: float pixelSize; float armAngle; bool armAnglePhase; Player* player; YuEngine::EventTimer legsAnimationTimer; };
[ "nathan.vasse@gmail.com" ]
nathan.vasse@gmail.com
2ff190919f3c980c1cae116aa885d2e951501482
f9485b64c2f0632572423e3c29d4911846849c6c
/src/PaymentServer.cpp
af5b188bd9874b80d093fee2344bb776c2e1b0b4
[ "MIT" ]
permissive
prascoin/prascoinwallet
55928aabaa1360099cf42a58e69436e4269f9d50
27bae19ded60a9b72c71cfe6471c9cc27a38eb99
refs/heads/master
2020-03-08T23:54:08.453684
2018-04-06T22:14:19
2018-04-06T22:14:19
128,367,020
0
0
null
null
null
null
UTF-8
C++
false
false
4,238
cpp
// Copyright (c) 2009-2012 The Bitcoin developers // Copyright (c) 2016 The PrasCoin developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include <QApplication> #include <cstdlib> #include <QByteArray> #include <QDataStream> #include <QDebug> #include <QFileOpenEvent> #include <QLocalServer> #include <QLocalSocket> #include <QStringList> #if QT_VERSION < 0x050000 #include <QUrl> #endif #include "PaymentServer.h" #include "Settings.h" #include "CurrencyAdapter.h" using namespace boost; using namespace WalletGui; const int BITCOIN_IPC_CONNECT_TIMEOUT = 1000; // milliseconds const QString BITCOIN_IPC_PREFIX("prascoin:"); static QString ipcServerName() { QString name("PrasCoin"); return name; } // // This stores payment requests received before // the main GUI window is up and ready to ask the user // to send payment. // static QStringList savedPaymentRequests; // // Sending to the server is done synchronously, at startup. // If the server isn't already running, startup continues, // and the items in savedPaymentRequest will be handled // when uiReady() is called. // bool PaymentServer::ipcSendCommandLine() { bool fResult = false; const QStringList& args = qApp->arguments(); for (int i = 1; i < args.size(); i++) { if (!args[i].startsWith(BITCOIN_IPC_PREFIX, Qt::CaseInsensitive)) continue; savedPaymentRequests.append(args[i]); } foreach (const QString& arg, savedPaymentRequests) { QLocalSocket* socket = new QLocalSocket(); socket->connectToServer(ipcServerName(), QIODevice::WriteOnly); if (!socket->waitForConnected(BITCOIN_IPC_CONNECT_TIMEOUT)) return false; QByteArray block; QDataStream out(&block, QIODevice::WriteOnly); out.setVersion(QDataStream::Qt_4_0); out << arg; out.device()->seek(0); socket->write(block); socket->flush(); socket->waitForBytesWritten(BITCOIN_IPC_CONNECT_TIMEOUT); socket->disconnectFromServer(); delete socket; fResult = true; } return fResult; } PaymentServer::PaymentServer(QApplication* parent) : QObject(parent), saveURIs(true) { // Install global event filter to catch QFileOpenEvents on the mac (sent when you click bitcoin: links) parent->installEventFilter(this); QString name = ipcServerName(); // Clean up old socket leftover from a crash: QLocalServer::removeServer(name); uriServer = new QLocalServer(this); if (!uriServer->listen(name)) qDebug() << tr("Cannot start prascoin: click-to-pay handler"); else connect(uriServer, SIGNAL(newConnection()), this, SLOT(handleURIConnection())); } bool PaymentServer::eventFilter(QObject *object, QEvent *event) { // clicking on prascoin: URLs creates FileOpen events on the Mac: if (event->type() == QEvent::FileOpen) { QFileOpenEvent* fileEvent = static_cast<QFileOpenEvent*>(event); if (!fileEvent->url().isEmpty()) { if (saveURIs) // Before main window is ready: savedPaymentRequests.append(fileEvent->url().toString()); else Q_EMIT receivedURI(fileEvent->url().toString()); return true; } } return false; } void PaymentServer::uiReady() { saveURIs = false; foreach (const QString& s, savedPaymentRequests) Q_EMIT receivedURI(s); savedPaymentRequests.clear(); } void PaymentServer::handleURIConnection() { QLocalSocket *clientConnection = uriServer->nextPendingConnection(); while (clientConnection->bytesAvailable() < (int)sizeof(quint32)) clientConnection->waitForReadyRead(); connect(clientConnection, SIGNAL(disconnected()), clientConnection, SLOT(deleteLater())); QDataStream in(clientConnection); in.setVersion(QDataStream::Qt_4_0); if (clientConnection->bytesAvailable() < (int)sizeof(quint16)) { return; } QString message; in >> message; if (saveURIs) savedPaymentRequests.append(message); else Q_EMIT receivedURI(message); }
[ "prascoin@prascoin.com" ]
prascoin@prascoin.com
40e7b6c68a55e42d298282bba70c15edda5727d9
dccd1058e723b6617148824dc0243dbec4c9bd48
/codeforces/1092D2.cpp
c0a17b25f584401bb4966e57ce346629370f3fbf
[]
no_license
imulan/procon
488e49de3bcbab36c624290cf9e370abfc8735bf
2a86f47614fe0c34e403ffb35108705522785092
refs/heads/master
2021-05-22T09:24:19.691191
2021-01-02T14:27:13
2021-01-02T14:27:13
46,834,567
7
1
null
null
null
null
UTF-8
C++
false
false
2,553
cpp
#include <bits/stdc++.h> using namespace std; using ll = long long; #define rep(i,n) for(int (i)=0;(i)<(int)(n);++(i)) #define all(x) (x).begin(),(x).end() #define pb push_back #define fi first #define se second #define dbg(x) cout<<#x" = "<<((x))<<endl template<class T,class U> ostream& operator<<(ostream& o, const pair<T,U> &p){o<<"("<<p.fi<<","<<p.se<<")";return o;} template<class T> ostream& operator<<(ostream& o, const vector<T> &v){o<<"[";for(T t:v){o<<t<<",";}o<<"]";return o;} struct UF{ int n; //正だったらその頂点の親,負だったら根で連結成分の個数 vector<int> d; UF() {} UF(int N):n(N), d(N,-1){} int root(int v){ if(d[v]<0) return v; return d[v]=root(d[v]); } bool unite(int X,int Y){ X=root(X); Y=root(Y); if(X==Y) return false; // if(size(X) < size(Y)) swap(X,Y); d[X]+=d[Y]; d[Y]=X; return true; } int size(int v){ return -d[root(v)]; } bool same(int X,int Y){ return root(X)==root(Y); } }; const int INF = 1e9+19191919; struct R{ int val,len,lh,rh; }; bool solve(){ int n; scanf(" %d", &n); vector<int> a(n); rep(i,n) scanf(" %d", &a[i]); int V = 0; vector<R> v; int s = 0; while(s<n){ int e = s; while(e<n && a[s] == a[e]) ++e; v.pb({a[s], e-s, V-1, V+1}); ++V; s = e; } UF uf(V); int L = -1, R = V; using pi = pair<int,int>; set<pi> ms; rep(i,V){ ms.insert({v[i].val, i}); } while(1){ pi pp = *ms.begin(); int idx = pp.se; int l = v[idx].lh, r = v[idx].rh; // printf(" %d %d %d\n",idx,l,r); if(l==L && r==R) break; if(v[idx].len%2 == 1) return false; if(l!=L) l = uf.root(l); if(r!=R) r = uf.root(r); // printf(" cv lr %d %d\n", l,r); int tgt = INF; if(l!=L) tgt = min(tgt, v[l].val); if(r!=R) tgt = min(tgt, v[r].val); ms.erase(pp); v[idx].val = tgt; if(l!=L && v[l].val == tgt){ v[idx].len += v[l].len; v[idx].lh = v[l].lh; ms.erase({v[l].val, l}); uf.unite(idx,l); } if(r!=R && v[r].val == tgt){ v[idx].len += v[r].len; v[idx].rh = v[r].rh; ms.erase({v[r].val, r}); uf.unite(idx,r); } ms.insert({v[idx].val, idx}); } return true; } int main(){ cout << (solve()?"YES":"NO") << endl; return 0; }
[ "k0223.teru@gmail.com" ]
k0223.teru@gmail.com
ba02245772a933678a716b061ffbacb20c345c8e
a816e8ab3043f8775f20776e0f48072c379dbbc3
/labs/lab3/E.cpp
f1966ed8c1825f6701198b385ed99e71b4e747f7
[]
no_license
AruzhanBazarbai/pp1
1dee51b6ef09a094072f89359883600937faf558
317d488a1ffec9108d71e8bf976a9a1c0896745e
refs/heads/master
2023-07-16T14:37:20.131167
2021-08-25T17:08:41
2021-08-25T17:08:41
399,890,781
0
0
null
null
null
null
UTF-8
C++
false
false
356
cpp
//Given an array consisting of integers. // Write a program, which finds sum of all elements #include <iostream> using namespace std; int main(){ int n; cin >> n; int a[n]; long long sum=0; for(int i=0; i<n; i++){ cin >> a[i]; } for(int i=0; i<n; i++){ sum+=a[i]; } cout << sum << "\n"; return 0; }
[ "aruzhanart2003@mail.ru" ]
aruzhanart2003@mail.ru
a77f243423384769fdec1b4382a2e0f27517a617
88ae8695987ada722184307301e221e1ba3cc2fa
/third_party/pdfium/fxjs/cjs_font.cpp
fcf69ac02900d66cc5de386b8a84de3d0d640289
[ "Apache-2.0", "LGPL-2.0-or-later", "MIT", "GPL-1.0-or-later", "BSD-3-Clause" ]
permissive
iridium-browser/iridium-browser
71d9c5ff76e014e6900b825f67389ab0ccd01329
5ee297f53dc7f8e70183031cff62f37b0f19d25f
refs/heads/master
2023-08-03T16:44:16.844552
2023-07-20T15:17:00
2023-07-23T16:09:30
220,016,632
341
40
BSD-3-Clause
2021-08-13T13:54:45
2019-11-06T14:32:31
null
UTF-8
C++
false
false
1,318
cpp
// Copyright 2017 The PDFium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // Original code copyright 2014 Foxit Software Inc. http://www.foxitsoftware.com #include "fxjs/cjs_font.h" const JSConstSpec CJS_Font::ConstSpecs[] = { {"Times", JSConstSpec::String, 0, "Times-Roman"}, {"TimesB", JSConstSpec::String, 0, "Times-Bold"}, {"TimesI", JSConstSpec::String, 0, "Times-Italic"}, {"TimesBI", JSConstSpec::String, 0, "Times-BoldItalic"}, {"Helv", JSConstSpec::String, 0, "Helvetica"}, {"HelvB", JSConstSpec::String, 0, "Helvetica-Bold"}, {"HelvI", JSConstSpec::String, 0, "Helvetica-Oblique"}, {"HelvBI", JSConstSpec::String, 0, "Helvetica-BoldOblique"}, {"Cour", JSConstSpec::String, 0, "Courier"}, {"CourB", JSConstSpec::String, 0, "Courier-Bold"}, {"CourI", JSConstSpec::String, 0, "Courier-Oblique"}, {"CourBI", JSConstSpec::String, 0, "Courier-BoldOblique"}, {"Symbol", JSConstSpec::String, 0, "Symbol"}, {"ZapfD", JSConstSpec::String, 0, "ZapfDingbats"}}; uint32_t CJS_Font::ObjDefnID = 0; // static void CJS_Font::DefineJSObjects(CFXJS_Engine* pEngine) { ObjDefnID = pEngine->DefineObj("font", FXJSOBJTYPE_STATIC, nullptr, nullptr); DefineConsts(pEngine, ObjDefnID, ConstSpecs); }
[ "jengelh@inai.de" ]
jengelh@inai.de
e2b7eb25d4c63e72d05fcf11d64a1dca32d6c8d1
be806ebbf0f1a7d05f1a24101ba957c450f2e902
/src/libmilkcat.cc
6d655c55e48c92cb582d8fa9074945b8af474c61
[ "MIT" ]
permissive
kasuganosora/MilkCat
2e97d271ed4cd1e57a4b38c6f2c36a6eb4b29ea4
e0d137ff830f2e2abd749a9106609b0d7307b337
refs/heads/master
2020-12-31T03:55:53.659000
2015-01-17T08:57:01
2015-01-17T08:57:01
null
0
0
null
null
null
null
UTF-8
C++
false
false
12,271
cc
// // The MIT License (MIT) // // Copyright 2013-2014 The MilkCat Project Developers // // 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. // // libyaca.cc // libmilkcat.cc --- Created at 2013-09-03 // #include "include/milkcat.h" #include "libmilkcat.h" #include <stdio.h> #include <string.h> #include <string> #include <utility> #include <vector> #include "common/model_impl.h" #include "ml/crf_tagger.h" #include "segmenter/bigram_segmenter.h" #include "segmenter/mixed_segmenter.h" #include "segmenter/out_of_vocabulary_word_recognition.h" #include "segmenter/term_instance.h" #include "tagger/crf_part_of_speech_tagger.h" #include "tagger/hmm_part_of_speech_tagger.h" #include "tagger/part_of_speech_tag_instance.h" #include "parser/beam_arceager_dependency_parser.h" #include "parser/dependency_parser.h" #include "parser/tree_instance.h" #include "tokenizer/tokenizer.h" #include "tokenizer/token_instance.h" #include "utils/utils.h" namespace milkcat { // This enum represents the type or the algorithm of Parser. It could be // kDefault which indicates using the default algorithm for segmentation and // part-of-speech tagging. Meanwhile, it could also be // kTextTokenizer | kBigramSegmenter | kHmmTagger // which indicates using bigram segmenter for segmentation, using HMM model // for part-of-speech tagging. enum ParserType { // Tokenizer type kTextTokenizer = 0, // Segmenter type kMixedSegmenter = 0x00000000, kCrfSegmenter = 0x00000010, kUnigramSegmenter = 0x00000020, kBigramSegmenter = 0x00000030, // Part-of-speech tagger type kMixedTagger = 0x00000000, kHmmTagger = 0x00001000, kCrfTagger = 0x00002000, kNoTagger = 0x000ff000, // Depengency parser type kArcEagerParser = 0x00100000, kNoParser = 0x00000000, }; Tokenization *TokenizerFactory(int analyzer_type) { int tokenizer_type = analyzer_type & kTokenizerMask; switch (tokenizer_type) { case kTextTokenizer: return new Tokenization(); default: return NULL; } } Segmenter *SegmenterFactory(Model::Impl *factory, int analyzer_type, Status *status) { int segmenter_type = analyzer_type & kSegmenterMask; switch (segmenter_type) { case kBigramSegmenter: return BigramSegmenter::New(factory, true, status); case kUnigramSegmenter: return BigramSegmenter::New(factory, false, status); case kCrfSegmenter: return CRFSegmenter::New(factory, status); case kMixedSegmenter: return MixedSegmenter::New(factory, status); default: *status = Status::NotImplemented("Invalid segmenter type"); return NULL; } } PartOfSpeechTagger *PartOfSpeechTaggerFactory(Model::Impl *factory, int analyzer_type, Status *status) { const CRFModel *crf_pos_model = NULL; const HMMModel *hmm_pos_model = NULL; int tagger_type = analyzer_type & kPartOfSpeechTaggerMask; switch (tagger_type) { case kCrfTagger: if (status->ok()) crf_pos_model = factory->CRFPosModel(status); if (status->ok()) { return CRFPartOfSpeechTagger::New(crf_pos_model, NULL, status); } else { return NULL; } case kHmmTagger: if (status->ok()) { return HMMPartOfSpeechTagger::New(factory, status); } else { return NULL; } case kMixedTagger: if (status->ok()) crf_pos_model = factory->CRFPosModel(status); if (status->ok()) hmm_pos_model = factory->HMMPosModel(status); if (status->ok()) { return CRFPartOfSpeechTagger::New(crf_pos_model, hmm_pos_model, status); } else { return NULL; } case kNoTagger: return NULL; default: *status = Status::NotImplemented("Invalid Part-of-speech tagger type"); return NULL; } } DependencyParser *DependencyParserFactory(Model::Impl *factory, int parser_type, Status *status) { parser_type = kParserMask & parser_type; switch (parser_type) { case kArcEagerParser: if (status->ok()) { return BeamArceagerDependencyParser::New(factory, status); } else { return NULL; } case kNoParser: return NULL; default: *status = Status::NotImplemented("Invalid parser type"); return NULL; } } // The global state saves the current of model and analyzer. // If any errors occured, global_status != Status::OK() Status global_status; // ----------------------------- Parser::Iterator ----------------------------- Parser::Iterator::Impl::Impl(): parser_(NULL), tokenizer_(TokenizerFactory(kTextTokenizer)), token_instance_(new TokenInstance()), term_instance_(new TermInstance()), tree_instance_(new TreeInstance()), part_of_speech_tag_instance_(new PartOfSpeechTagInstance()), sentence_length_(0), current_position_(0), end_(false) { } Parser::Iterator::Impl::~Impl() { delete tokenizer_; tokenizer_ = NULL; delete token_instance_; token_instance_ = NULL; delete term_instance_; term_instance_ = NULL; delete part_of_speech_tag_instance_; part_of_speech_tag_instance_ = NULL; delete tree_instance_; tree_instance_ = NULL; parser_ = NULL; } void Parser::Iterator::Impl::Scan(const char *text) { tokenizer_->Scan(text); sentence_length_ = 0; current_position_ = 0; end_ = false; } void Parser::Iterator::Impl::Next() { if (End()) return ; current_position_++; if (current_position_ > sentence_length_ - 1) { // If reached the end of current sentence if (tokenizer_->GetSentence(token_instance_) == false) { end_ = true; } else { parser_->segmenter()->Segment(term_instance_, token_instance_); // If the parser have part-of-speech tagger, tag the term_instance if (parser_->part_of_speech_tagger()) { parser_->part_of_speech_tagger()->Tag(part_of_speech_tag_instance_, term_instance_); } // Dependency Parsing if (parser_->dependency_parser()) { parser_->dependency_parser()->Parse(tree_instance_, term_instance_, part_of_speech_tag_instance_); } sentence_length_ = term_instance_->size(); current_position_ = 0; is_begin_of_sentence_ = true; } } else { is_begin_of_sentence_ = false; } } Parser::Iterator::Iterator() { impl_ = new Parser::Iterator::Impl(); } Parser::Iterator::~Iterator() { delete impl_; impl_ = NULL; } bool Parser::Iterator::End() { return impl_->End(); } void Parser::Iterator::Next() { impl_->Next(); } const char *Parser::Iterator::word() const { return impl_->word(); } const char *Parser::Iterator::part_of_speech_tag() const { return impl_->part_of_speech_tag(); } int Parser::Iterator::type() const { return impl_->type(); } int Parser::Iterator::head_node() const { return impl_->head_node(); } const char *Parser::Iterator::dependency_type() const { return impl_->dependency_type(); } bool Parser::Iterator::is_begin_of_sentence() const { return impl_->is_begin_of_sentence(); } // ----------------------------- Parser -------------------------------------- Parser::Impl::Impl(): segmenter_(NULL), part_of_speech_tagger_(NULL), dependency_parser_(NULL), model_impl_(NULL), own_model_(false), iterator_alloced_(0) { } Parser::Impl::~Impl() { delete segmenter_; segmenter_ = NULL; delete part_of_speech_tagger_; part_of_speech_tagger_ = NULL; delete dependency_parser_; dependency_parser_ = NULL; if (own_model_) delete model_impl_; model_impl_ = NULL; } Parser::Impl *Parser::Impl::New(const Options &options, Model *model) { global_status = Status::OK(); Impl *self = new Parser::Impl(); int type = options.TypeValue(); Model::Impl *model_impl = model? model->impl(): NULL; if (model_impl == NULL) { self->model_impl_ = new Model::Impl(MODEL_PATH); self->own_model_ = true; } else { self->model_impl_ = model_impl; self->own_model_ = false; } if (global_status.ok()) self->segmenter_ = SegmenterFactory( self->model_impl_, type, &global_status); if (global_status.ok()) self->part_of_speech_tagger_ = PartOfSpeechTaggerFactory( self->model_impl_, type, &global_status); if (global_status.ok()) self->dependency_parser_ = DependencyParserFactory( self->model_impl_, type, &global_status); if (!global_status.ok()) { delete self; return NULL; } else { return self; } } void Parser::Impl::Parse(const char *text, Parser::Iterator *iterator) { iterator->impl()->set_parser(this); iterator->impl()->Scan(text); iterator->Next(); } Parser::Parser(): impl_(NULL) { } Parser::~Parser() { delete impl_; impl_ = NULL; } Parser *Parser::New() { return New(Options(), NULL); } Parser *Parser::New(const Options &options) { return New(options, NULL); } Parser *Parser::New(const Options &options, Model *model) { Parser *self = new Parser(); self->impl_ = Impl::New(options, model); if (self->impl_) { return self; } else { delete self; return NULL; } } void Parser::Parse(const char *text, Parser::Iterator *iterator) { return impl_->Parse(text, iterator); } Parser::Options::Options(): segmenter_type_(kMixedSegmenter), tagger_type_(kMixedTagger), parser_type_(kNoParser) { } void Parser::Options::UseMixedSegmenter() { segmenter_type_ = kMixedSegmenter; } void Parser::Options::UseCrfSegmenter() { segmenter_type_ = kCrfSegmenter; } void Parser::Options::UseUnigramSegmenter() { segmenter_type_ = kUnigramSegmenter; } void Parser::Options::UseBigramSegmenter() { segmenter_type_ = kBigramSegmenter; } void Parser::Options::UseMixedPOSTagger() { tagger_type_ = kMixedTagger; } void Parser::Options::UseHmmPOSTagger() { tagger_type_ = kHmmTagger; } void Parser::Options::UseCrfPOSTagger() { tagger_type_ = kCrfTagger; } void Parser::Options::NoPOSTagger() { tagger_type_ = kNoTagger; } void Parser::Options::UseArcEagerDependencyParser() { if (tagger_type_ == kNoTagger) tagger_type_ = kMixedTagger; parser_type_ = kArcEagerParser; } void Parser::Options::NoDependencyParser() { parser_type_ = kNoParser; } int Parser::Options::TypeValue() const { return segmenter_type_ | tagger_type_ | parser_type_; } // ------------------------------- Model ------------------------------------- Model::Model(): impl_(NULL) { } Model::~Model() { delete impl_; impl_ = NULL; } Model *Model::New(const char *model_dir) { Model *self = new Model(); self->impl_ = new Model::Impl(model_dir? model_dir: MODEL_PATH); return self; } bool Model::SetUserDictionary(const char *userdict_path) { return impl_->SetUserDictionary(userdict_path); } const char *LastError() { return global_status.what(); } } // namespace milkcat
[ "ling032x@gmail.com" ]
ling032x@gmail.com
d8e6b93ad77248d2d4fa2cf879f4c420eb2e6804
0dc405a395af56e01cd4efb699ab00b192ac0a0c
/1day/dfs.cpp
585ed7e157d74accb3232058c3f9be5a32a50c1a
[]
no_license
DanielYe1/winterSchool
fb336ebd2692f13840aabe4e529fc89df09089e8
d91adb91fabc64ac32bce573889d9fb5713e6a91
refs/heads/master
2021-06-21T19:30:52.883509
2017-08-25T02:37:24
2017-08-25T02:37:24
101,393,883
0
0
null
null
null
null
UTF-8
C++
false
false
627
cpp
#include <iostream> using namespace std; const int timer = 0; int color[10]; void dfs(int node) { color[node] = 1; } const int max_log = 20; const int size = 100000; int par[size][size]; int depth[size]; void dfsAnt(int node, int h, int p) { par[node][0] = p; depth[node] = h; for (int i = 0; i < max_log; ++i) { par[node][i] = -1; if (par[node][i - 1] != -1) { par[node][i] = par[par[node][i - 1]][i - 1]; } } for (int j = 0; j <; ++j) { if (viz != p) { dfsAnt(viz, h + w[node][j], node); } } } int main() { return 0; }
[ "danielxinxin1@gmail.com" ]
danielxinxin1@gmail.com
7958fc141f8fdd76c1ba8f708b692f49d0a56b20
999f5f1f2aa209f44b9e7e7f143282d7ab6a25c0
/devel/include/slam_tutorials/test.h
7b4939c94a0510a13df3044a5762c043fff114e8
[]
no_license
MenethilArthas/catkin_ws
ac9ebcece01f7011208e34f58659f715215ccc73
ade8ab3982466414ce69052ae3654485e1375a10
refs/heads/master
2021-01-20T07:22:58.774464
2017-03-15T02:09:06
2017-03-15T02:09:06
83,886,383
0
0
null
null
null
null
UTF-8
C++
false
false
4,383
h
// Generated by gencpp from file slam_tutorials/test.msg // DO NOT EDIT! #ifndef SLAM_TUTORIALS_MESSAGE_TEST_H #define SLAM_TUTORIALS_MESSAGE_TEST_H #include <string> #include <vector> #include <map> #include <ros/types.h> #include <ros/serialization.h> #include <ros/builtin_message_traits.h> #include <ros/message_operations.h> namespace slam_tutorials { template <class ContainerAllocator> struct test_ { typedef test_<ContainerAllocator> Type; test_() { } test_(const ContainerAllocator& _alloc) { (void)_alloc; } typedef boost::shared_ptr< ::slam_tutorials::test_<ContainerAllocator> > Ptr; typedef boost::shared_ptr< ::slam_tutorials::test_<ContainerAllocator> const> ConstPtr; }; // struct test_ typedef ::slam_tutorials::test_<std::allocator<void> > test; typedef boost::shared_ptr< ::slam_tutorials::test > testPtr; typedef boost::shared_ptr< ::slam_tutorials::test const> testConstPtr; // constants requiring out of line definition template<typename ContainerAllocator> std::ostream& operator<<(std::ostream& s, const ::slam_tutorials::test_<ContainerAllocator> & v) { ros::message_operations::Printer< ::slam_tutorials::test_<ContainerAllocator> >::stream(s, "", v); return s; } } // namespace slam_tutorials namespace ros { namespace message_traits { // BOOLTRAITS {'IsFixedSize': True, 'IsMessage': True, 'HasHeader': False} // {'slam_tutorials': ['/home/action/catkin_ws/src/slam_tutorials/msg']} // !!!!!!!!!!! ['__class__', '__delattr__', '__dict__', '__doc__', '__eq__', '__format__', '__getattribute__', '__hash__', '__init__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', '_parsed_fields', 'constants', 'fields', 'full_name', 'has_header', 'header_present', 'names', 'package', 'parsed_fields', 'short_name', 'text', 'types'] template <class ContainerAllocator> struct IsFixedSize< ::slam_tutorials::test_<ContainerAllocator> > : TrueType { }; template <class ContainerAllocator> struct IsFixedSize< ::slam_tutorials::test_<ContainerAllocator> const> : TrueType { }; template <class ContainerAllocator> struct IsMessage< ::slam_tutorials::test_<ContainerAllocator> > : TrueType { }; template <class ContainerAllocator> struct IsMessage< ::slam_tutorials::test_<ContainerAllocator> const> : TrueType { }; template <class ContainerAllocator> struct HasHeader< ::slam_tutorials::test_<ContainerAllocator> > : FalseType { }; template <class ContainerAllocator> struct HasHeader< ::slam_tutorials::test_<ContainerAllocator> const> : FalseType { }; template<class ContainerAllocator> struct MD5Sum< ::slam_tutorials::test_<ContainerAllocator> > { static const char* value() { return "d41d8cd98f00b204e9800998ecf8427e"; } static const char* value(const ::slam_tutorials::test_<ContainerAllocator>&) { return value(); } static const uint64_t static_value1 = 0xd41d8cd98f00b204ULL; static const uint64_t static_value2 = 0xe9800998ecf8427eULL; }; template<class ContainerAllocator> struct DataType< ::slam_tutorials::test_<ContainerAllocator> > { static const char* value() { return "slam_tutorials/test"; } static const char* value(const ::slam_tutorials::test_<ContainerAllocator>&) { return value(); } }; template<class ContainerAllocator> struct Definition< ::slam_tutorials::test_<ContainerAllocator> > { static const char* value() { return "\n\ "; } static const char* value(const ::slam_tutorials::test_<ContainerAllocator>&) { return value(); } }; } // namespace message_traits } // namespace ros namespace ros { namespace serialization { template<class ContainerAllocator> struct Serializer< ::slam_tutorials::test_<ContainerAllocator> > { template<typename Stream, typename T> inline static void allInOne(Stream&, T) {} ROS_DECLARE_ALLINONE_SERIALIZER }; // struct test_ } // namespace serialization } // namespace ros namespace ros { namespace message_operations { template<class ContainerAllocator> struct Printer< ::slam_tutorials::test_<ContainerAllocator> > { template<typename Stream> static void stream(Stream&, const std::string&, const ::slam_tutorials::test_<ContainerAllocator>&) {} }; } // namespace message_operations } // namespace ros #endif // SLAM_TUTORIALS_MESSAGE_TEST_H
[ "690540319@qq.com" ]
690540319@qq.com
164e3f64688101f50169012a6e0885936cb808bf
fca16f6b7838bd515de786cf6e8c01aee348c1f9
/fps2015aels/uilibgp2015/OGL/GRect/GRect.cpp
0fdec020dd3808dee38e3a1b500c24bc9208fc7c
[]
no_license
antoinechene/FPS-openGL
0de726658ffa278289fd89c1410c490b3dad7f54
c7b3cbca8c6dc4f190dc92a273fe1b8ed74b7900
refs/heads/master
2020-04-06T07:01:17.983451
2012-09-06T14:06:25
2012-09-06T14:06:25
null
0
0
null
null
null
null
UTF-8
C++
false
false
918
cpp
#include "GRect.h" #include "../Draw_Geometry/Draw_Geometry_Rect.h" ID::GRect::GRect(int16_t w, int16_t h, bool f, ID::Color* color) : /*__w(w), __h(h),*/ __fulfil(f), __color(*color) { this->_w = w; this->_h = h; } ID::GRect::~GRect() { } void ID::GRect::SetDimension(int16_t w, int16_t h) { this->_w = w; this->_h = h; } void ID::GRect::SetFulfil(bool f) { this->__fulfil = f; } void ID::GRect::SetColor(uint32_t c) { this->__color = c; } void ID::GRect::SetColor(ID::Color c) { this->__color = c; } int ID::GRect::RefreshToSurface(Surface* s, int x, int y) { if (this->GetOnScreen() == false) return 0; if (s == NULL) return 0; ID::Draw_Geometry_Rect::GetInstance()->Draw(s, x + this->_x, y + this->_y, this->GetWidth(), this->GetHeight(), this->__fulfil, this->__color.ConvertToInt()); return 0; }
[ "antoinechene@hotmail.fr" ]
antoinechene@hotmail.fr
11b5436479da047d576381bb86fcb1dcbed4581b
f76792be9b6b12ccde8a6ab64c0462846039cfa5
/287_find_the_duplicate_number.cpp
06681de8d5d3ee4ec86a73a685cadba6cb1af966
[]
no_license
netario/leetcode-solutions
844c0fbf7f97a71eba3b59e7643c7104cef4a590
b289891115927d90bd59ec53f173121a1158e524
refs/heads/master
2021-01-19T12:52:15.653561
2017-09-16T23:28:52
2017-09-16T23:28:52
100,814,944
0
0
null
null
null
null
UTF-8
C++
false
false
475
cpp
class Solution { public: int findDuplicate(vector<int>& nums) { int ret = -1, p = 1, q = (int)nums.size() - 1; while (p <= q) { int mid = p + (q - p) / 2, cnt = 0; for (auto& num : nums) cnt += num <= mid; if (cnt >= mid + 1) { ret = mid; q = mid - 1; } else { p = mid + 1; } } return ret; } };
[ "fycanyue@163.com" ]
fycanyue@163.com
8ef0f75eb73dfdcaf7b2c7e11819d9da523b6251
09a4f7e32a0efb2b18c1fcd3c501ecc6becb0852
/Builder/main.cpp
40f1995b85e3e640d7691f210a3b0845ded6ef3c
[]
no_license
IngwarSV/Patterns
8a230005ac37ab699217c3cb5ae5d81b857ace4c
a557aa9532f95d6c12dcea836d4e614ed5a326b3
refs/heads/master
2020-12-26T07:20:01.572200
2020-02-12T09:13:20
2020-02-12T09:13:20
237,431,316
0
0
null
null
null
null
UTF-8
C++
false
false
946
cpp
#include <iostream> #include "Smith.h" #include "Sword.h" // #include "SwordTemplate.h" #include "GladiusTemplate.h" #include "LongSwordTemplate.h" #include "LongSword.h" int main() { Smith* blacksmith = new Smith(); GladiusTemplate* gTemplate = new GladiusTemplate(); LongSwordTemplate* lsTemplate = new LongSwordTemplate(); blacksmith->setSwordTemplate(gTemplate); Sword* arm1 = blacksmith->createSword(); std::cout << *arm1 << std::endl; std::cout << "----------------------" << std::endl; blacksmith->setSwordTemplate(lsTemplate); Sword* arm2 = blacksmith->createSword(); std::cout << *arm2 << std::endl; std::cout << "----------------------" << std::endl; arm1->info(); arm2->info(); std::cout << "----------------------" << std::endl; delete (blacksmith); delete(gTemplate); delete(lsTemplate); delete (arm1); delete (arm2); return 0; }
[ "sviatskyi@gmail.com" ]
sviatskyi@gmail.com
c6792841f799c8bb25b92f74e39839ba58a2147f
e99887d75f79aace37b6fd99b7bdb0a739321aa9
/src/fixpoint/branch_conditions.h
e6c563dda71507121e43c74b97215beeef919ae9
[ "MIT" ]
permissive
peterrum/po-lab-2018
e14f98e876c91ee2bb381ff07c0ac04f2d84802e
e4547288c582f36bd73d94157ea157b0a631c4ae
refs/heads/master
2021-07-13T18:01:14.035456
2018-11-24T10:13:58
2018-11-24T10:13:58
136,142,467
3
4
null
2018-11-24T10:13:18
2018-06-05T08:06:06
C++
UTF-8
C++
false
false
1,114
h
#ifndef PROJECT_BRANCH_CONDITIONS_H #define PROJECT_BRANCH_CONDITIONS_H #include "../abstract_domain/AbstractDomain.h" #include "state.h" #include "llvm/IR/Value.h" #include "llvm/Support/raw_ostream.h" #include <map> #include <memory> #include <utility> using namespace llvm; namespace pcpo { class BranchConditions { public: BranchConditions(std::map<BasicBlock *, State> &programPoints); bool isBasicBlockReachable(BasicBlock *pred, BasicBlock *bb); // apply conditions and return true if non of the variables are bottom bool applyCondition(BasicBlock *pred, BasicBlock *bb); void unApplyCondition(BasicBlock *pred); void putBranchConditions(BasicBlock *pred, BasicBlock *bb, Value *val, std::shared_ptr<AbstractDomain> ad); private: std::map<BasicBlock *, State> &programPoints; std::map<BasicBlock *, std::map<BasicBlock *, std::map<Value *, std::shared_ptr<AbstractDomain>>>> branchConditions; std::map<Value *, std::shared_ptr<AbstractDomain>> conditionCache; bool conditionCacheUsed; }; } /// namespace #endif
[ "peterrmuench@aol.com" ]
peterrmuench@aol.com
e5f9ca3dfdc9526dec098c4cf84dd89bf05e7534
435f79cf136034f86850780796536c82efebc83f
/src/qt/transactiontablemodel.h
5f4f01e73c1566a888ea69bae72f4635b01799f1
[ "MIT" ]
permissive
KazuPay/kazusilver
d7d3946cd677cf0f49c8c0d944544194df8bb0b4
fc81623ed5fd5f9f9fd9ce85139201ece6a2332e
refs/heads/master
2020-04-15T08:55:32.528511
2019-01-13T13:34:41
2019-01-13T13:34:41
null
0
0
null
null
null
null
UTF-8
C++
false
false
4,332
h
// Copyright (c) 2011-2015 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #ifndef KSLVCOIN_QT_TRANSACTIONTABLEMODEL_H #define KSLVCOIN_QT_TRANSACTIONTABLEMODEL_H #include "kazusilverunits.h" #include <QAbstractTableModel> #include <QStringList> class PlatformStyle; class TransactionRecord; class TransactionTablePriv; class WalletModel; class CWallet; /** UI model for the transaction table of a wallet. */ class TransactionTableModel : public QAbstractTableModel { Q_OBJECT public: explicit TransactionTableModel(const PlatformStyle *platformStyle, CWallet* wallet, WalletModel *parent = 0); ~TransactionTableModel(); enum ColumnIndex { Status = 0, Watchonly = 1, Date = 2, Type = 3, ToAddress = 4, Amount = 5 }; /** Roles to get specific information from a transaction row. These are independent of column. */ enum RoleIndex { /** Type of transaction */ TypeRole = Qt::UserRole, /** Date and time this transaction was created */ DateRole, /** Watch-only boolean */ WatchonlyRole, /** Watch-only icon */ WatchonlyDecorationRole, /** Long description (HTML format) */ LongDescriptionRole, /** Address of transaction */ AddressRole, /** Label of address related to transaction */ LabelRole, /** Net amount of transaction */ AmountRole, /** Unique identifier */ TxIDRole, /** Transaction hash */ TxHashRole, /** Transaction data, hex-encoded */ TxHexRole, /** Whole transaction as plain text */ TxPlainTextRole, /** Is transaction confirmed? */ ConfirmedRole, /** Formatted amount, without brackets when unconfirmed */ FormattedAmountRole, /** Transaction status (TransactionRecord::Status) */ StatusRole, /** Unprocessed icon */ RawDecorationRole, }; int rowCount(const QModelIndex &parent) const; int columnCount(const QModelIndex &parent) const; QVariant data(const QModelIndex &index, int role) const; QVariant headerData(int section, Qt::Orientation orientation, int role) const; QModelIndex index(int row, int column, const QModelIndex & parent = QModelIndex()) const; bool processingQueuedTransactions() { return fProcessingQueuedTransactions; } private: CWallet* wallet; WalletModel *walletModel; QStringList columns; TransactionTablePriv *priv; bool fProcessingQueuedTransactions; const PlatformStyle *platformStyle; void subscribeToCoreSignals(); void unsubscribeFromCoreSignals(); QString lookupAddress(const std::string &address, bool tooltip) const; QVariant addressColor(const TransactionRecord *wtx) const; QString formatTxStatus(const TransactionRecord *wtx) const; QString formatTxDate(const TransactionRecord *wtx) const; QString formatTxType(const TransactionRecord *wtx) const; QString formatTxToAddress(const TransactionRecord *wtx, bool tooltip) const; QString formatTxAmount(const TransactionRecord *wtx, bool showUnconfirmed=true, KazuSilverUnits::SeparatorStyle separators=KazuSilverUnits::separatorStandard) const; QString formatTooltip(const TransactionRecord *rec) const; QVariant txStatusDecoration(const TransactionRecord *wtx) const; QVariant txWatchonlyDecoration(const TransactionRecord *wtx) const; QVariant txAddressDecoration(const TransactionRecord *wtx) const; public Q_SLOTS: /* New transaction, or transaction changed status */ void updateTransaction(const QString &hash, int status, bool showTransaction); void updateConfirmations(); void updateDisplayUnit(); /** Updates the column title to "Amount (DisplayUnit)" and emits headerDataChanged() signal for table headers to react. */ void updateAmountColumnTitle(); /* Needed to update fProcessingQueuedTransactions through a QueuedConnection */ void setProcessingQueuedTransactions(bool value) { fProcessingQueuedTransactions = value; } friend class TransactionTablePriv; }; #endif // KSLVCOIN_QT_TRANSACTIONTABLEMODEL_H
[ "mike@altilly.com" ]
mike@altilly.com
45a7ddd357d5fc069b48636f5c17bdabd8ef399f
f3b3bf886392024e0bbddf2ca2c4f59ed067008d
/code/day3/day2.cpp
d473d3f5a8ae4ef4573e950ea9caefc299c5d69e
[]
no_license
Cuong-star/30daysofcode
b8a03e908966c887cfefcf46dd0b25b1c29a10e1
255c7a680ae9b9c09d1e14f9e0586209def042ce
refs/heads/master
2020-12-18T21:05:23.759728
2020-01-22T03:50:49
2020-01-22T03:50:49
null
0
0
null
null
null
null
UTF-8
C++
false
false
722
cpp
#include <bits/stdc++.h> #include <cmath> using namespace std; // Complete the solve function below. void solve(double meal_cost, int tip_percent, int tax_percent) { double tip,tax,total; tip = meal_cost * tip_percent/100; tax = meal_cost * tax_percent/100; total = meal_cost + tip + tax; cout << round(total); } int main() { double meal_cost; cin >> meal_cost; cin.ignore(numeric_limits<streamsize>::max(), '\n'); int tip_percent; cin >> tip_percent; cin.ignore(numeric_limits<streamsize>::max(), '\n'); int tax_percent; cin >> tax_percent; cin.ignore(numeric_limits<streamsize>::max(), '\n'); solve(meal_cost, tip_percent, tax_percent); return 0; }
[ "pduongpdu99@gmail.com" ]
pduongpdu99@gmail.com
cbe589d93f3f6beaab6f602ffc9583e3cf1eabcc
7f69e98afe43db75c3d33f7e99dbba702a37a0a7
/src/plugins/thirdParty/LLVM/lib/IR/IRBuilder.cpp
af1b2fbfadfaf56cdc1792d5410847e2c080f7a1
[ "Apache-2.0" ]
permissive
hsorby/opencor
ce1125ba6a6cd86a811d13d4b54fb12a53a3cc7c
4ce3332fed67069bd093a6215aeaf81be81c9933
refs/heads/master
2021-01-19T07:23:07.743445
2015-11-08T13:17:29
2015-11-08T13:17:29
null
0
0
null
null
null
null
UTF-8
C++
false
false
14,578
cpp
//===---- IRBuilder.cpp - Builder for LLVM Instrs -------------------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file implements the IRBuilder class, which is used as a convenient way // to create LLVM instructions with a consistent and simplified interface. // //===----------------------------------------------------------------------===// #include "llvm/IR/Function.h" #include "llvm/IR/GlobalVariable.h" #include "llvm/IR/IRBuilder.h" #include "llvm/IR/Intrinsics.h" #include "llvm/IR/LLVMContext.h" #include "llvm/IR/Statepoint.h" using namespace llvm; /// CreateGlobalString - Make a new global variable with an initializer that /// has array of i8 type filled in with the nul terminated string value /// specified. If Name is specified, it is the name of the global variable /// created. GlobalVariable *IRBuilderBase::CreateGlobalString(StringRef Str, const Twine &Name, unsigned AddressSpace) { Constant *StrConstant = ConstantDataArray::getString(Context, Str); Module &M = *BB->getParent()->getParent(); GlobalVariable *GV = new GlobalVariable(M, StrConstant->getType(), true, GlobalValue::PrivateLinkage, StrConstant, Name, nullptr, GlobalVariable::NotThreadLocal, AddressSpace); GV->setUnnamedAddr(true); return GV; } Type *IRBuilderBase::getCurrentFunctionReturnType() const { assert(BB && BB->getParent() && "No current function!"); return BB->getParent()->getReturnType(); } Value *IRBuilderBase::getCastedInt8PtrValue(Value *Ptr) { PointerType *PT = cast<PointerType>(Ptr->getType()); if (PT->getElementType()->isIntegerTy(8)) return Ptr; // Otherwise, we need to insert a bitcast. PT = getInt8PtrTy(PT->getAddressSpace()); BitCastInst *BCI = new BitCastInst(Ptr, PT, ""); BB->getInstList().insert(InsertPt, BCI); SetInstDebugLocation(BCI); return BCI; } static CallInst *createCallHelper(Value *Callee, ArrayRef<Value *> Ops, IRBuilderBase *Builder, const Twine& Name="") { CallInst *CI = CallInst::Create(Callee, Ops, Name); Builder->GetInsertBlock()->getInstList().insert(Builder->GetInsertPoint(),CI); Builder->SetInstDebugLocation(CI); return CI; } static InvokeInst *createInvokeHelper(Value *Invokee, BasicBlock *NormalDest, BasicBlock *UnwindDest, ArrayRef<Value *> Ops, IRBuilderBase *Builder, const Twine &Name = "") { InvokeInst *II = InvokeInst::Create(Invokee, NormalDest, UnwindDest, Ops, Name); Builder->GetInsertBlock()->getInstList().insert(Builder->GetInsertPoint(), II); Builder->SetInstDebugLocation(II); return II; } CallInst *IRBuilderBase:: CreateMemSet(Value *Ptr, Value *Val, Value *Size, unsigned Align, bool isVolatile, MDNode *TBAATag, MDNode *ScopeTag, MDNode *NoAliasTag) { Ptr = getCastedInt8PtrValue(Ptr); Value *Ops[] = { Ptr, Val, Size, getInt32(Align), getInt1(isVolatile) }; Type *Tys[] = { Ptr->getType(), Size->getType() }; Module *M = BB->getParent()->getParent(); Value *TheFn = Intrinsic::getDeclaration(M, Intrinsic::memset, Tys); CallInst *CI = createCallHelper(TheFn, Ops, this); // Set the TBAA info if present. if (TBAATag) CI->setMetadata(LLVMContext::MD_tbaa, TBAATag); if (ScopeTag) CI->setMetadata(LLVMContext::MD_alias_scope, ScopeTag); if (NoAliasTag) CI->setMetadata(LLVMContext::MD_noalias, NoAliasTag); return CI; } CallInst *IRBuilderBase:: CreateMemCpy(Value *Dst, Value *Src, Value *Size, unsigned Align, bool isVolatile, MDNode *TBAATag, MDNode *TBAAStructTag, MDNode *ScopeTag, MDNode *NoAliasTag) { Dst = getCastedInt8PtrValue(Dst); Src = getCastedInt8PtrValue(Src); Value *Ops[] = { Dst, Src, Size, getInt32(Align), getInt1(isVolatile) }; Type *Tys[] = { Dst->getType(), Src->getType(), Size->getType() }; Module *M = BB->getParent()->getParent(); Value *TheFn = Intrinsic::getDeclaration(M, Intrinsic::memcpy, Tys); CallInst *CI = createCallHelper(TheFn, Ops, this); // Set the TBAA info if present. if (TBAATag) CI->setMetadata(LLVMContext::MD_tbaa, TBAATag); // Set the TBAA Struct info if present. if (TBAAStructTag) CI->setMetadata(LLVMContext::MD_tbaa_struct, TBAAStructTag); if (ScopeTag) CI->setMetadata(LLVMContext::MD_alias_scope, ScopeTag); if (NoAliasTag) CI->setMetadata(LLVMContext::MD_noalias, NoAliasTag); return CI; } CallInst *IRBuilderBase:: CreateMemMove(Value *Dst, Value *Src, Value *Size, unsigned Align, bool isVolatile, MDNode *TBAATag, MDNode *ScopeTag, MDNode *NoAliasTag) { Dst = getCastedInt8PtrValue(Dst); Src = getCastedInt8PtrValue(Src); Value *Ops[] = { Dst, Src, Size, getInt32(Align), getInt1(isVolatile) }; Type *Tys[] = { Dst->getType(), Src->getType(), Size->getType() }; Module *M = BB->getParent()->getParent(); Value *TheFn = Intrinsic::getDeclaration(M, Intrinsic::memmove, Tys); CallInst *CI = createCallHelper(TheFn, Ops, this); // Set the TBAA info if present. if (TBAATag) CI->setMetadata(LLVMContext::MD_tbaa, TBAATag); if (ScopeTag) CI->setMetadata(LLVMContext::MD_alias_scope, ScopeTag); if (NoAliasTag) CI->setMetadata(LLVMContext::MD_noalias, NoAliasTag); return CI; } CallInst *IRBuilderBase::CreateLifetimeStart(Value *Ptr, ConstantInt *Size) { assert(isa<PointerType>(Ptr->getType()) && "lifetime.start only applies to pointers."); Ptr = getCastedInt8PtrValue(Ptr); if (!Size) Size = getInt64(-1); else assert(Size->getType() == getInt64Ty() && "lifetime.start requires the size to be an i64"); Value *Ops[] = { Size, Ptr }; Module *M = BB->getParent()->getParent(); Value *TheFn = Intrinsic::getDeclaration(M, Intrinsic::lifetime_start); return createCallHelper(TheFn, Ops, this); } CallInst *IRBuilderBase::CreateLifetimeEnd(Value *Ptr, ConstantInt *Size) { assert(isa<PointerType>(Ptr->getType()) && "lifetime.end only applies to pointers."); Ptr = getCastedInt8PtrValue(Ptr); if (!Size) Size = getInt64(-1); else assert(Size->getType() == getInt64Ty() && "lifetime.end requires the size to be an i64"); Value *Ops[] = { Size, Ptr }; Module *M = BB->getParent()->getParent(); Value *TheFn = Intrinsic::getDeclaration(M, Intrinsic::lifetime_end); return createCallHelper(TheFn, Ops, this); } CallInst *IRBuilderBase::CreateAssumption(Value *Cond) { assert(Cond->getType() == getInt1Ty() && "an assumption condition must be of type i1"); Value *Ops[] = { Cond }; Module *M = BB->getParent()->getParent(); Value *FnAssume = Intrinsic::getDeclaration(M, Intrinsic::assume); return createCallHelper(FnAssume, Ops, this); } /// Create a call to a Masked Load intrinsic. /// Ptr - the base pointer for the load /// Align - alignment of the source location /// Mask - an vector of booleans which indicates what vector lanes should /// be accessed in memory /// PassThru - a pass-through value that is used to fill the masked-off lanes /// of the result /// Name - name of the result variable CallInst *IRBuilderBase::CreateMaskedLoad(Value *Ptr, unsigned Align, Value *Mask, Value *PassThru, const Twine &Name) { assert(Ptr->getType()->isPointerTy() && "Ptr must be of pointer type"); // DataTy is the overloaded type Type *DataTy = cast<PointerType>(Ptr->getType())->getElementType(); assert(DataTy->isVectorTy() && "Ptr should point to a vector"); if (!PassThru) PassThru = UndefValue::get(DataTy); Value *Ops[] = { Ptr, getInt32(Align), Mask, PassThru}; return CreateMaskedIntrinsic(Intrinsic::masked_load, Ops, DataTy, Name); } /// Create a call to a Masked Store intrinsic. /// Val - the data to be stored, /// Ptr - the base pointer for the store /// Align - alignment of the destination location /// Mask - an vector of booleans which indicates what vector lanes should /// be accessed in memory CallInst *IRBuilderBase::CreateMaskedStore(Value *Val, Value *Ptr, unsigned Align, Value *Mask) { Value *Ops[] = { Val, Ptr, getInt32(Align), Mask }; // Type of the data to be stored - the only one overloaded type return CreateMaskedIntrinsic(Intrinsic::masked_store, Ops, Val->getType()); } /// Create a call to a Masked intrinsic, with given intrinsic Id, /// an array of operands - Ops, and one overloaded type - DataTy CallInst *IRBuilderBase::CreateMaskedIntrinsic(Intrinsic::ID Id, ArrayRef<Value *> Ops, Type *DataTy, const Twine &Name) { Module *M = BB->getParent()->getParent(); Type *OverloadedTypes[] = { DataTy }; Value *TheFn = Intrinsic::getDeclaration(M, Id, OverloadedTypes); return createCallHelper(TheFn, Ops, this, Name); } static std::vector<Value *> getStatepointArgs(IRBuilderBase &B, uint64_t ID, uint32_t NumPatchBytes, Value *ActualCallee, ArrayRef<Value *> CallArgs, ArrayRef<Value *> DeoptArgs, ArrayRef<Value *> GCArgs) { std::vector<Value *> Args; Args.push_back(B.getInt64(ID)); Args.push_back(B.getInt32(NumPatchBytes)); Args.push_back(ActualCallee); Args.push_back(B.getInt32(CallArgs.size())); Args.push_back(B.getInt32((unsigned)StatepointFlags::None)); Args.insert(Args.end(), CallArgs.begin(), CallArgs.end()); Args.push_back(B.getInt32(0 /* no transition args */)); Args.push_back(B.getInt32(DeoptArgs.size())); Args.insert(Args.end(), DeoptArgs.begin(), DeoptArgs.end()); Args.insert(Args.end(), GCArgs.begin(), GCArgs.end()); return Args; } CallInst *IRBuilderBase::CreateGCStatepointCall( uint64_t ID, uint32_t NumPatchBytes, Value *ActualCallee, ArrayRef<Value *> CallArgs, ArrayRef<Value *> DeoptArgs, ArrayRef<Value *> GCArgs, const Twine &Name) { // Extract out the type of the callee. PointerType *FuncPtrType = cast<PointerType>(ActualCallee->getType()); assert(isa<FunctionType>(FuncPtrType->getElementType()) && "actual callee must be a callable value"); Module *M = BB->getParent()->getParent(); // Fill in the one generic type'd argument (the function is also vararg) Type *ArgTypes[] = { FuncPtrType }; Function *FnStatepoint = Intrinsic::getDeclaration(M, Intrinsic::experimental_gc_statepoint, ArgTypes); std::vector<llvm::Value *> Args = getStatepointArgs( *this, ID, NumPatchBytes, ActualCallee, CallArgs, DeoptArgs, GCArgs); return createCallHelper(FnStatepoint, Args, this, Name); } CallInst *IRBuilderBase::CreateGCStatepointCall( uint64_t ID, uint32_t NumPatchBytes, Value *ActualCallee, ArrayRef<Use> CallArgs, ArrayRef<Value *> DeoptArgs, ArrayRef<Value *> GCArgs, const Twine &Name) { std::vector<Value *> VCallArgs; for (auto &U : CallArgs) VCallArgs.push_back(U.get()); return CreateGCStatepointCall(ID, NumPatchBytes, ActualCallee, VCallArgs, DeoptArgs, GCArgs, Name); } InvokeInst *IRBuilderBase::CreateGCStatepointInvoke( uint64_t ID, uint32_t NumPatchBytes, Value *ActualInvokee, BasicBlock *NormalDest, BasicBlock *UnwindDest, ArrayRef<Value *> InvokeArgs, ArrayRef<Value *> DeoptArgs, ArrayRef<Value *> GCArgs, const Twine &Name) { // Extract out the type of the callee. PointerType *FuncPtrType = cast<PointerType>(ActualInvokee->getType()); assert(isa<FunctionType>(FuncPtrType->getElementType()) && "actual callee must be a callable value"); Module *M = BB->getParent()->getParent(); // Fill in the one generic type'd argument (the function is also vararg) Function *FnStatepoint = Intrinsic::getDeclaration( M, Intrinsic::experimental_gc_statepoint, {FuncPtrType}); std::vector<llvm::Value *> Args = getStatepointArgs( *this, ID, NumPatchBytes, ActualInvokee, InvokeArgs, DeoptArgs, GCArgs); return createInvokeHelper(FnStatepoint, NormalDest, UnwindDest, Args, this, Name); } InvokeInst *IRBuilderBase::CreateGCStatepointInvoke( uint64_t ID, uint32_t NumPatchBytes, Value *ActualInvokee, BasicBlock *NormalDest, BasicBlock *UnwindDest, ArrayRef<Use> InvokeArgs, ArrayRef<Value *> DeoptArgs, ArrayRef<Value *> GCArgs, const Twine &Name) { std::vector<Value *> VCallArgs; for (auto &U : InvokeArgs) VCallArgs.push_back(U.get()); return CreateGCStatepointInvoke(ID, NumPatchBytes, ActualInvokee, NormalDest, UnwindDest, VCallArgs, DeoptArgs, GCArgs, Name); } CallInst *IRBuilderBase::CreateGCResult(Instruction *Statepoint, Type *ResultType, const Twine &Name) { Intrinsic::ID ID = Intrinsic::experimental_gc_result; Module *M = BB->getParent()->getParent(); Type *Types[] = {ResultType}; Value *FnGCResult = Intrinsic::getDeclaration(M, ID, Types); Value *Args[] = {Statepoint}; return createCallHelper(FnGCResult, Args, this, Name); } CallInst *IRBuilderBase::CreateGCRelocate(Instruction *Statepoint, int BaseOffset, int DerivedOffset, Type *ResultType, const Twine &Name) { Module *M = BB->getParent()->getParent(); Type *Types[] = {ResultType}; Value *FnGCRelocate = Intrinsic::getDeclaration(M, Intrinsic::experimental_gc_relocate, Types); Value *Args[] = {Statepoint, getInt32(BaseOffset), getInt32(DerivedOffset)}; return createCallHelper(FnGCRelocate, Args, this, Name); }
[ "agarny@hellix.com" ]
agarny@hellix.com
08b5f4a0a22efbe3acd3f24866346d75184ba44a
63ff954260ac9de2ac5420875f1bf7cf41eba2ff
/2019_06_30_Gunbird/2019_06_30_Gunbird/CSpriteDib.cpp
df17d5e96b71f2b1627c345a9fee55f9bb19d7dc
[]
no_license
kmj91/kmj-api
179b76e4d08c0654f074fadcfd8caae8832d7d7d
9a65e7b395199f8058ad615a4377973f53604305
refs/heads/master
2021-05-18T12:56:44.498606
2020-04-16T13:49:56
2020-04-16T13:49:56
251,250,883
0
0
null
null
null
null
UTF-8
C++
false
false
30,386
cpp
#include "stdafx.h" #include <windows.h> #include "CSpriteDib.h" #include "stdio.h" CSpriteDib::CSpriteDib() { int iCount; //----------------------------------------------------------------- // 최대 읽어올 개수 만큼 미리 할당 받는다. //----------------------------------------------------------------- m_iMaxSprite = 100; m_dwColorKey = 0x00ff00ff; m_stpSprite = new st_SPRITE[100]; // 초기화 iCount = 0; while (iCount < 100) { m_stpSprite[iCount].bypImage = NULL; ++iCount; } //기본 카메라 위치 m_iCameraPosX = 0; m_iCameraPosY = 0; } //////////////////////////////////////////////////////////////////// // 생성자, 파괴자. // // Parameters: (int)최대 스프라이트 개수. (DWORD)투명칼라. //////////////////////////////////////////////////////////////////// CSpriteDib::CSpriteDib(int iMaxSprite, DWORD dwColorKey) { int iCount; //----------------------------------------------------------------- // 최대 읽어올 개수 만큼 미리 할당 받는다. //----------------------------------------------------------------- m_iMaxSprite = iMaxSprite; m_dwColorKey = dwColorKey; m_stpSprite = new st_SPRITE[iMaxSprite]; // 초기화 iCount = 0; while (iCount < iMaxSprite) { m_stpSprite[iCount].bypImage = NULL; ++iCount; } //기본 카메라 위치 m_iCameraPosX = 0; m_iCameraPosY = 0; } CSpriteDib::~CSpriteDib() { int iCount; //----------------------------------------------------------------- // 전체를 돌면서 모두 지우자. //----------------------------------------------------------------- for (iCount = 0; iCount < m_iMaxSprite; iCount++) { ReleaseSprite(iCount); } delete[] m_stpSprite; } /////////////////////////////////////////////////////// // LoadDibSprite. // BMP파일을 읽어서 하나의 프레임으로 저장한다. // // Parameters: (int)SpriteIndex. (const wchar_t *)FileName. (int)CenterPointX. (int)CenterPointY. // Return: (BOOL)TRUE, FALSE. /////////////////////////////////////////////////////// BOOL CSpriteDib::LoadDibSprite(int iSpriteIndex, const wchar_t * szFileName, int iCenterPointX, int iCenterPointY) { //HANDLE hFile; //DWORD dwRead; int iPitch; size_t iImageSize; BITMAPFILEHEADER stFileHeader; BITMAPINFOHEADER stInfoHeader; FILE *fp; int err; int iCount; //----------------------------------------------------------------- // 비트맵 헤더를 열어 BMP 파일 확인. //----------------------------------------------------------------- err = _wfopen_s(&fp, szFileName, L"rb"); if (err != 0) { return 0; } fread(&stFileHeader, sizeof(BITMAPFILEHEADER), 1, fp); if (stFileHeader.bfType != 0x4d42) { return 0; } //----------------------------------------------------------------- // 한줄, 한줄의 피치값을 구한다. //----------------------------------------------------------------- fread(&stInfoHeader, sizeof(BITMAPINFOHEADER), 1, fp); iPitch = (stInfoHeader.biWidth * (stInfoHeader.biBitCount / 8) + 3) & ~3; //----------------------------------------------------------------- // 스프라이트 구조체에 크기 저장. //----------------------------------------------------------------- m_stpSprite[iSpriteIndex].iWidth = stInfoHeader.biWidth; m_stpSprite[iSpriteIndex].iHeight = stInfoHeader.biHeight; m_stpSprite[iSpriteIndex].iPitch = iPitch; m_stpSprite[iSpriteIndex].iCenterPointX = iCenterPointX; m_stpSprite[iSpriteIndex].iCenterPointY = iCenterPointY; //----------------------------------------------------------------- // 이미지에 대한 전체 크기를 구하고, 메모리 할당. //----------------------------------------------------------------- iImageSize = iPitch * stInfoHeader.biHeight; m_stpSprite[iSpriteIndex].bypImage = new BYTE[iImageSize]; //----------------------------------------------------------------- // 이미지 부분은 스프라이트 버퍼로 읽어온다. // DIB 는 뒤집어져 있으므로 이를 다시 뒤집자. // 임시 버퍼에 읽은 뒤에 뒤집으면서 복사한다. //----------------------------------------------------------------- BYTE *buffer = new BYTE[iImageSize]; BYTE *tempBuffer; BYTE *tempSprite = m_stpSprite[iSpriteIndex].bypImage; fread(buffer, iImageSize, 1, fp); tempBuffer = buffer +(iPitch * (stInfoHeader.biHeight - 1)); for (iCount = 0; iCount < stInfoHeader.biHeight; iCount++) { memcpy(tempSprite, tempBuffer, stInfoHeader.biWidth * 4); tempBuffer = tempBuffer - iPitch; tempSprite = tempSprite + iPitch; } delete[] buffer; fclose(fp); //CloseHandle(hFile); return FALSE; } /////////////////////////////////////////////////////// // ReleaseSprite. // 해당 스프라이트 해제. // // Parameters: (int)SpriteIndex. // Return: (BOOL)TRUE, FALSE. /////////////////////////////////////////////////////// void CSpriteDib::ReleaseSprite(int iSpriteIndex) { //----------------------------------------------------------------- // 최대 할당된 스프라이트를 넘어서면 안되지롱 //----------------------------------------------------------------- if (m_iMaxSprite <= iSpriteIndex) return; if (NULL != m_stpSprite[iSpriteIndex].bypImage) { //----------------------------------------------------------------- // 삭제 후 초기화. //----------------------------------------------------------------- delete[] m_stpSprite[iSpriteIndex].bypImage; memset(&m_stpSprite[iSpriteIndex], 0, sizeof(st_SPRITE)); } } /////////////////////////////////////////////////////// // DrawSprite. // 특정 메모리 위치에 스프라이트를 출력한다. (클리핑 처리) // 체력바 처리 // /////////////////////////////////////////////////////// void CSpriteDib::DrawSprite(int iSpriteIndex, int iDrawX, int iDrawY, BYTE *bypDest, int iDestWidth, int iDestHeight, int iDestPitch) { //----------------------------------------------------------------- // 최대 스프라이트 개수를 초과 하거나, 로드되지 않는 스프라이트라면 무시 //----------------------------------------------------------------- if (m_iMaxSprite < iSpriteIndex) return; if (m_stpSprite[iSpriteIndex].bypImage == NULL) return; //----------------------------------------------------------------- // 지역변수로 필요정보 셋팅 //----------------------------------------------------------------- st_SPRITE *stpSprite = &m_stpSprite[iSpriteIndex]; int iCountY; int iCountX; int iSpriteHeight = stpSprite->iHeight; int iSpriteWidth = stpSprite->iWidth; int iSpritePitch = stpSprite->iPitch; int iSpriteCenterX = stpSprite->iCenterPointX; int iSpriteCenterY = stpSprite->iCenterPointY; DWORD *dwpSprite = (DWORD *)stpSprite->bypImage; DWORD *dwpDest = (DWORD *)bypDest; BYTE *bypTempSprite; BYTE *bypTempDest; //----------------------------------------------------------------- // 출력 중점으로 좌표 계산 //----------------------------------------------------------------- iDrawX = iDrawX - iSpriteCenterX; iDrawY = iDrawY - iSpriteCenterY; //----------------------------------------------------------------- // 상단 에 대한 스프라이트 출력 위치 계산. (상단 클리핑) // 하단에 사이즈 계산. (하단 클리핑) // 왼쪽 출력 위치 계산. (좌측 클리핑) // 오른쪽 출력 위치 계산. (우측 클리핑) //----------------------------------------------------------------- //2018.02.08 //카메라 기준으로 스프라이트 값 클리핑 처리 int clippingY; int clippingX; if (iDrawY < m_iCameraPosY) { //2018.02.08 clippingY = m_iCameraPosY - iDrawY; iSpriteHeight = iSpriteHeight - clippingY; if (iSpriteHeight > 0) { dwpSprite = (DWORD *)((BYTE *)dwpSprite + iSpritePitch * clippingY); } iDrawY = m_iCameraPosY; } if (iDrawY + iSpriteHeight >= m_iCameraPosY + iDestHeight) { iSpriteHeight = iSpriteHeight - ((iDrawY + iSpriteHeight) - (m_iCameraPosY + iDestHeight)); } if (iDrawX < m_iCameraPosX) { //2018.02.08 clippingX = m_iCameraPosX - iDrawX; iSpriteWidth = iSpriteWidth - clippingX; if (iSpriteWidth > 0) { dwpSprite = dwpSprite + clippingX; } iDrawX = m_iCameraPosX; } if (iDrawX + iSpriteWidth >= m_iCameraPosX + iDestWidth) { iSpriteWidth = iSpriteWidth - ((iDrawX + iSpriteWidth) - (m_iCameraPosX + iDestWidth)); } if (iSpriteWidth <= 0 || iSpriteHeight <= 0) { return; } //2018.02.08 //카메라 기준으로 iDrawX iDrawY 값 좌표 맞추기 iDrawX = iDrawX - m_iCameraPosX; iDrawY = iDrawY - m_iCameraPosY; //----------------------------------------------------------------- // 화면에 찍을 위치로 이동한다. //----------------------------------------------------------------- dwpDest = (DWORD *)((BYTE *)(dwpDest + iDrawX) + (iDrawY * iDestPitch)); bypTempSprite = (BYTE *)dwpSprite; bypTempDest = (BYTE *)dwpDest; //----------------------------------------------------------------- // 전체 크기를 돌면서 픽셀마다 투명색 처리를 하며 그림 출력. //----------------------------------------------------------------- for (iCountY = 0; iSpriteHeight > iCountY; iCountY++) { for (iCountX = 0; iSpriteWidth > iCountX; iCountX++) { if (m_dwColorKey != (*dwpSprite & 0x00ffffff)) { *dwpDest = *dwpSprite; } //다음칸 이동 ++dwpDest; ++dwpSprite; } //----------------------------------------------------------------- // 다음줄로 이동, 화면과 스프라이트 모두.. //----------------------------------------------------------------- bypTempDest = bypTempDest + iDestPitch; bypTempSprite = bypTempSprite + iSpritePitch; dwpDest = (DWORD *)bypTempDest; dwpSprite = (DWORD *)bypTempSprite; } } void CSpriteDib::DrawImage(int iSpriteIndex, int iDrawX, int iDrawY, BYTE *bypDest, int iDestWidth, int iDestHeight, int iDestPitch) { //----------------------------------------------------------------- // 최대 스프라이트 개수를 초과 하거나, 로드되지 않는 스프라이트라면 무시 //----------------------------------------------------------------- if (m_iMaxSprite < iSpriteIndex) return; if (m_stpSprite[iSpriteIndex].bypImage == NULL) return; //----------------------------------------------------------------- // 지역변수로 필요정보 셋팅 //----------------------------------------------------------------- st_SPRITE *stpSprite = &m_stpSprite[iSpriteIndex]; int iCountY; int iCountX; int iSpriteHeight = stpSprite->iHeight; int iSpriteWidth = stpSprite->iWidth; int iSpritePitch = stpSprite->iPitch; int iSpriteCenterX = stpSprite->iCenterPointX; int iSpriteCenterY = stpSprite->iCenterPointY; DWORD *dwpSprite = (DWORD *)stpSprite->bypImage; DWORD *dwpDest = (DWORD *)bypDest; BYTE *bypTempSprite; BYTE *bypTempDest; //----------------------------------------------------------------- // 출력 중점으로 좌표 계산 //----------------------------------------------------------------- iDrawX = iDrawX - iSpriteCenterX; iDrawY = iDrawY - iSpriteCenterY; //----------------------------------------------------------------- // 상단 에 대한 스프라이트 출력 위치 계산. (상단 클리핑) // 하단에 사이즈 계산. (하단 클리핑) // 왼쪽 출력 위치 계산. (좌측 클리핑) // 오른쪽 출력 위치 계산. (우측 클리핑) //----------------------------------------------------------------- //2018.02.08 //카메라 기준으로 스프라이트 값 클리핑 처리 int clippingY; int clippingX; if (iDrawY < m_iCameraPosY) { //2018.02.08 clippingY = m_iCameraPosY - iDrawY; iSpriteHeight = iSpriteHeight - clippingY; if (iSpriteHeight > 0) { dwpSprite = (DWORD *)((BYTE *)dwpSprite + iSpritePitch * clippingY); } iDrawY = m_iCameraPosY; } if (iDrawY + iSpriteHeight >= m_iCameraPosY + iDestHeight) { iSpriteHeight = iSpriteHeight - ((iDrawY + iSpriteHeight) - (m_iCameraPosY + iDestHeight)); } if (iDrawX < m_iCameraPosX) { //2018.02.08 clippingX = m_iCameraPosX - iDrawX; iSpriteWidth = iSpriteWidth - clippingX; if (iSpriteWidth > 0) { dwpSprite = dwpSprite + clippingX; } iDrawX = m_iCameraPosX; } if (iDrawX + iSpriteWidth >= m_iCameraPosX + iDestWidth) { iSpriteWidth = iSpriteWidth - ((iDrawX + iSpriteWidth) - (m_iCameraPosX + iDestWidth)); } if (iSpriteWidth <= 0 || iSpriteHeight <= 0) { return; } //2018.02.08 //카메라 기준으로 iDrawX iDrawY 값 좌표 맞추기 iDrawX = iDrawX - m_iCameraPosX; iDrawY = iDrawY - m_iCameraPosY; //----------------------------------------------------------------- // 화면에 찍을 위치로 이동한다. //----------------------------------------------------------------- dwpDest = (DWORD *)((BYTE *)(dwpDest + iDrawX) + (iDrawY * iDestPitch)); bypTempSprite = (BYTE *)dwpSprite; bypTempDest = (BYTE *)dwpDest; //----------------------------------------------------------------- // 전체 크기를 돌면서 픽셀마다 그림 출력. //----------------------------------------------------------------- for (iCountY = 0; iSpriteHeight > iCountY; iCountY++) { for (iCountX = 0; iSpriteWidth > iCountX; iCountX++) { *dwpDest = *dwpSprite; //다음칸 이동 ++dwpDest; ++dwpSprite; } //----------------------------------------------------------------- // 다음줄로 이동, 화면과 스프라이트 모두.. //----------------------------------------------------------------- bypTempDest = bypTempDest + iDestPitch; bypTempSprite = bypTempSprite + iSpritePitch; dwpDest = (DWORD *)bypTempDest; dwpSprite = (DWORD *)bypTempSprite; } } /********************************* DrawSpriteRed 빨간색 톤으로 이미지 출력 **********************************/ void CSpriteDib::DrawSpriteRed(int iSpriteIndex, int iDrawX, int iDrawY, BYTE *bypDest, int iDestWidth, int iDestHeight, int iDestPitch) { //----------------------------------------------------------------- // 최대 스프라이트 개수를 초과 하거나, 로드되지 않는 스프라이트라면 무시 //----------------------------------------------------------------- if (m_iMaxSprite < iSpriteIndex) return; if (m_stpSprite[iSpriteIndex].bypImage == NULL) return; //----------------------------------------------------------------- // 지역변수로 필요정보 셋팅 //----------------------------------------------------------------- st_SPRITE *stpSprite = &m_stpSprite[iSpriteIndex]; int iCountY; int iCountX; int iSpriteHeight = stpSprite->iHeight; int iSpriteWidth = stpSprite->iWidth; int iSpritePitch = stpSprite->iPitch; int iSpriteCenterX = stpSprite->iCenterPointX; int iSpriteCenterY = stpSprite->iCenterPointY; DWORD *dwpSprite = (DWORD *)stpSprite->bypImage; DWORD *dwpDest = (DWORD *)bypDest; BYTE *bypTempSprite; BYTE *bypTempDest; //----------------------------------------------------------------- // 출력 중점으로 좌표 계산 //----------------------------------------------------------------- iDrawX = iDrawX - iSpriteCenterX; iDrawY = iDrawY - iSpriteCenterY; //----------------------------------------------------------------- // 상단 에 대한 스프라이트 출력 위치 계산. (상단 클리핑) // 하단에 사이즈 계산. (하단 클리핑) // 왼쪽 출력 위치 계산. (좌측 클리핑) // 오른쪽 출력 위치 계산. (우측 클리핑) //----------------------------------------------------------------- //2018.02.08 //카메라 기준으로 스프라이트 값 클리핑 처리 int clippingY; int clippingX; if (iDrawY < m_iCameraPosY) { //2018.02.08 clippingY = m_iCameraPosY - iDrawY; iSpriteHeight = iSpriteHeight - clippingY; if (iSpriteHeight > 0) { dwpSprite = (DWORD *)((BYTE *)dwpSprite + iSpritePitch * clippingY); } iDrawY = m_iCameraPosY; } if (iDrawY + iSpriteHeight >= m_iCameraPosY + iDestHeight) { iSpriteHeight = iSpriteHeight - ((iDrawY + iSpriteHeight) - (m_iCameraPosY + iDestHeight)); } if (iDrawX < m_iCameraPosX) { //2018.02.08 clippingX = m_iCameraPosX - iDrawX; iSpriteWidth = iSpriteWidth - clippingX; if (iSpriteWidth > 0) { dwpSprite = dwpSprite + clippingX; } iDrawX = m_iCameraPosX; } if (iDrawX + iSpriteWidth >= m_iCameraPosX + iDestWidth) { iSpriteWidth = iSpriteWidth - ((iDrawX + iSpriteWidth) - (m_iCameraPosX + iDestWidth)); } if (iSpriteWidth <= 0 || iSpriteHeight <= 0) { return; } //2018.02.08 //카메라 기준으로 iDrawX iDrawY 값 좌표 맞추기 iDrawX = iDrawX - m_iCameraPosX; iDrawY = iDrawY - m_iCameraPosY; //----------------------------------------------------------------- // 화면에 찍을 위치로 이동한다. //----------------------------------------------------------------- dwpDest = (DWORD *)((BYTE *)(dwpDest + iDrawX) + (iDrawY * iDestPitch)); bypTempSprite = (BYTE *)dwpSprite; bypTempDest = (BYTE *)dwpDest; //----------------------------------------------------------------- // 전체 크기를 돌면서 픽셀마다 투명색 처리를 하며 그림 출력. //----------------------------------------------------------------- for (iCountY = 0; iSpriteHeight > iCountY; iCountY++) { for (iCountX = 0; iSpriteWidth > iCountX; iCountX++) { if (m_dwColorKey != (*dwpSprite & 0x00ffffff)) { *((BYTE *)dwpDest + 2) = *((BYTE *)dwpSprite + 2); *((BYTE *)dwpDest + 1) = *((BYTE *)dwpSprite + 1) / 2; *((BYTE *)dwpDest + 0) = *((BYTE *)dwpSprite + 0) / 2; } //다음칸 이동 ++dwpDest; ++dwpSprite; } //----------------------------------------------------------------- // 다음줄로 이동, 화면과 스프라이트 모두.. //----------------------------------------------------------------- bypTempDest = bypTempDest + iDestPitch; bypTempSprite = bypTempSprite + iSpritePitch; dwpDest = (DWORD *)bypTempDest; dwpSprite = (DWORD *)bypTempSprite; } } /********************************* DrawSpriteCompose 합성 출력 **********************************/ void CSpriteDib::DrawSpriteCompose(int iSpriteIndex, int iDrawX, int iDrawY, BYTE *bypDest, int iDestWidth, int iDestHeight, int iDestPitch) { //----------------------------------------------------------------- // 최대 스프라이트 개수를 초과 하거나, 로드되지 않는 스프라이트라면 무시 //----------------------------------------------------------------- if (m_iMaxSprite < iSpriteIndex) return; if (m_stpSprite[iSpriteIndex].bypImage == NULL) return; //----------------------------------------------------------------- // 지역변수로 필요정보 셋팅 //----------------------------------------------------------------- st_SPRITE *stpSprite = &m_stpSprite[iSpriteIndex]; int iCountY; int iCountX; int iSpriteHeight = stpSprite->iHeight; int iSpriteWidth = stpSprite->iWidth; int iSpritePitch = stpSprite->iPitch; int iSpriteCenterX = stpSprite->iCenterPointX; int iSpriteCenterY = stpSprite->iCenterPointY; DWORD *dwpSprite = (DWORD *)stpSprite->bypImage; DWORD *dwpDest = (DWORD *)bypDest; BYTE *bypTempSprite; BYTE *bypTempDest; //----------------------------------------------------------------- // 출력 중점으로 좌표 계산 //----------------------------------------------------------------- iDrawX = iDrawX - iSpriteCenterX; iDrawY = iDrawY - iSpriteCenterY; //----------------------------------------------------------------- // 상단 에 대한 스프라이트 출력 위치 계산. (상단 클리핑) // 하단에 사이즈 계산. (하단 클리핑) // 왼쪽 출력 위치 계산. (좌측 클리핑) // 오른쪽 출력 위치 계산. (우측 클리핑) //----------------------------------------------------------------- //2018.02.08 //카메라 기준으로 스프라이트 값 클리핑 처리 int clippingY; int clippingX; if (iDrawY < m_iCameraPosY) { //2018.02.08 clippingY = m_iCameraPosY - iDrawY; iSpriteHeight = iSpriteHeight - clippingY; if (iSpriteHeight > 0) { dwpSprite = (DWORD *)((BYTE *)dwpSprite + iSpritePitch * clippingY); } iDrawY = m_iCameraPosY; } if (iDrawY + iSpriteHeight >= m_iCameraPosY + iDestHeight) { iSpriteHeight = iSpriteHeight - ((iDrawY + iSpriteHeight) - (m_iCameraPosY + iDestHeight)); } if (iDrawX < m_iCameraPosX) { //2018.02.08 clippingX = m_iCameraPosX - iDrawX; iSpriteWidth = iSpriteWidth - clippingX; if (iSpriteWidth > 0) { dwpSprite = dwpSprite + clippingX; } iDrawX = m_iCameraPosX; } if (iDrawX + iSpriteWidth >= m_iCameraPosX + iDestWidth) { iSpriteWidth = iSpriteWidth - ((iDrawX + iSpriteWidth) - (m_iCameraPosX + iDestWidth)); } if (iSpriteWidth <= 0 || iSpriteHeight <= 0) { return; } //2018.02.08 //카메라 기준으로 iDrawX iDrawY 값 좌표 맞추기 iDrawX = iDrawX - m_iCameraPosX; iDrawY = iDrawY - m_iCameraPosY; //----------------------------------------------------------------- // 화면에 찍을 위치로 이동한다. //----------------------------------------------------------------- dwpDest = (DWORD *)((BYTE *)(dwpDest + iDrawX) + (iDrawY * iDestPitch)); bypTempSprite = (BYTE *)dwpSprite; bypTempDest = (BYTE *)dwpDest; //----------------------------------------------------------------- // 전체 크기를 돌면서 픽셀마다 투명색 처리를 하며 그림 출력. //----------------------------------------------------------------- for (iCountY = 0; iSpriteHeight > iCountY; iCountY++) { for (iCountX = 0; iSpriteWidth > iCountX; iCountX++) { if (m_dwColorKey != (*dwpSprite & 0x00ffffff)) { *((BYTE *)dwpDest + 2) = (*((BYTE *)dwpSprite + 2) / 2) + (*((BYTE *)dwpDest + 2) / 2); *((BYTE *)dwpDest + 1) = (*((BYTE *)dwpSprite + 1) / 2) + (*((BYTE *)dwpDest + 1) / 2); *((BYTE *)dwpDest + 0) = (*((BYTE *)dwpSprite + 0) / 2) + (*((BYTE *)dwpDest + 0) / 2); } //다음칸 이동 ++dwpDest; ++dwpSprite; } //----------------------------------------------------------------- // 다음줄로 이동, 화면과 스프라이트 모두.. //----------------------------------------------------------------- bypTempDest = bypTempDest + iDestPitch; bypTempSprite = bypTempSprite + iSpritePitch; dwpDest = (DWORD *)bypTempDest; dwpSprite = (DWORD *)bypTempSprite; } } // 체력바 용 void CSpriteDib::DrawPercentage(int iSpriteIndex, int iDrawX, int iDrawY, BYTE *bypDest, int iDestWidth, int iDestHeight, int iDestPitch, int iPercentage) { //----------------------------------------------------------------- // 최대 스프라이트 개수를 초과 하거나, 로드되지 않는 스프라이트라면 무시 //----------------------------------------------------------------- if (m_iMaxSprite < iSpriteIndex) return; if (m_stpSprite[iSpriteIndex].bypImage == NULL) return; //----------------------------------------------------------------- // 지역변수로 필요정보 셋팅 //----------------------------------------------------------------- st_SPRITE *stpSprite = &m_stpSprite[iSpriteIndex]; int iCountY; int iCountX; int iSpriteHeight = stpSprite->iHeight; int iSpriteWidth = stpSprite->iWidth; int iSpritePitch = stpSprite->iPitch; int iSpriteCenterX = stpSprite->iCenterPointX; int iSpriteCenterY = stpSprite->iCenterPointY; DWORD *dwpSprite = (DWORD *)stpSprite->bypImage; DWORD *dwpDest = (DWORD *)bypDest; BYTE *bypTempSprite; BYTE *bypTempDest; //----------------------------------------------------------------- // 출력 중점으로 좌표 계산 //----------------------------------------------------------------- iDrawX = iDrawX - iSpriteCenterX; iDrawY = iDrawY - iSpriteCenterY; //----------------------------------------------------------------- // 상단 에 대한 스프라이트 출력 위치 계산. (상단 클리핑) // 하단에 사이즈 계산. (하단 클리핑) // 왼쪽 출력 위치 계산. (좌측 클리핑) // 오른쪽 출력 위치 계산. (우측 클리핑) //----------------------------------------------------------------- //2018.02.08 //카메라 기준으로 스프라이트 값 클리핑 처리 int clippingY; int clippingX; if (iDrawY < m_iCameraPosY) { //2018.02.08 clippingY = m_iCameraPosY - iDrawY; iSpriteHeight = iSpriteHeight - clippingY; if (iSpriteHeight > 0) { dwpSprite = (DWORD *)((BYTE *)dwpSprite + iSpritePitch * clippingY); } iDrawY = m_iCameraPosY; } if (iDrawY + iSpriteHeight >= m_iCameraPosY + iDestHeight) { iSpriteHeight = iSpriteHeight - ((iDrawY + iSpriteHeight) - (m_iCameraPosY + iDestHeight)); } if (iDrawX < m_iCameraPosX) { //2018.02.08 clippingX = m_iCameraPosX - iDrawX; iSpriteWidth = iSpriteWidth - clippingX; if (iSpriteWidth > 0) { dwpSprite = dwpSprite + clippingX; } iDrawX = m_iCameraPosX; } if (iDrawX + iSpriteWidth >= m_iCameraPosX + iDestWidth) { iSpriteWidth = iSpriteWidth - ((iDrawX + iSpriteWidth) - (m_iCameraPosX + iDestWidth)); } if (iSpriteWidth <= 0 || iSpriteHeight <= 0) { return; } //2018.02.08 //카메라 기준으로 iDrawX iDrawY 값 좌표 맞추기 iDrawX = iDrawX - m_iCameraPosX; iDrawY = iDrawY - m_iCameraPosY; //----------------------------------------------------------------- // 화면에 찍을 위치로 이동한다. //----------------------------------------------------------------- dwpDest = (DWORD *)((BYTE *)(dwpDest + iDrawX) + (iDrawY * iDestPitch)); bypTempSprite = (BYTE *)dwpSprite; bypTempDest = (BYTE *)dwpDest; //----------------------------------------------------------------- // 전체 크기를 돌면서 픽셀마다 투명색 처리를 하며 그림 출력. //----------------------------------------------------------------- for (iCountY = 0; iSpriteHeight > iCountY; iCountY++) { for (iCountX = 0; iSpriteWidth - ((100 - iPercentage) * ((double)iSpriteWidth / (double)100)) > iCountX; iCountX++) { if (m_dwColorKey != (*dwpSprite & 0x00ffffff)) { *dwpDest = *dwpSprite; } //다음칸 이동 ++dwpDest; ++dwpSprite; } //----------------------------------------------------------------- // 다음줄로 이동, 화면과 스프라이트 모두.. //----------------------------------------------------------------- bypTempDest = bypTempDest + iDestPitch; bypTempSprite = bypTempSprite + iSpritePitch; dwpDest = (DWORD *)bypTempDest; dwpSprite = (DWORD *)bypTempSprite; } } // 테스트 용 void CSpriteDib::DrawTextID(int iSpriteIndex, int iDrawX, int iDrawY, BYTE *bypDest, int iDestWidth, int iDestHeight, int iDestPitch, HWND hWnd, UINT id) { //----------------------------------------------------------------- // 최대 스프라이트 개수를 초과 하거나, 로드되지 않는 스프라이트라면 무시 //----------------------------------------------------------------- if (m_iMaxSprite < iSpriteIndex) return; if (m_stpSprite[iSpriteIndex].bypImage == NULL) return; //----------------------------------------------------------------- // 지역변수로 필요정보 셋팅 //----------------------------------------------------------------- st_SPRITE *stpSprite = &m_stpSprite[iSpriteIndex]; int iSpriteHeight = stpSprite->iHeight; int iSpriteWidth = stpSprite->iWidth; int iSpritePitch = stpSprite->iPitch; int iSpriteCenterX = stpSprite->iCenterPointX; int iSpriteCenterY = stpSprite->iCenterPointY; DWORD *dwpSprite = (DWORD *)stpSprite->bypImage; DWORD *dwpDest = (DWORD *)bypDest; //----------------------------------------------------------------- // 출력 중점으로 좌표 계산 //----------------------------------------------------------------- iDrawX = iDrawX - iSpriteCenterX; iDrawY = iDrawY - iSpriteCenterY; //----------------------------------------------------------------- // 상단 에 대한 스프라이트 출력 위치 계산. (상단 클리핑) // 하단에 사이즈 계산. (하단 클리핑) // 왼쪽 출력 위치 계산. (좌측 클리핑) // 오른쪽 출력 위치 계산. (우측 클리핑) //----------------------------------------------------------------- //2018.02.08 //카메라 기준으로 스프라이트 값 클리핑 처리 int clippingY; int clippingX; if (iDrawY < m_iCameraPosY) { //2018.02.08 clippingY = m_iCameraPosY - iDrawY; iSpriteHeight = iSpriteHeight - clippingY; if (iSpriteHeight > 0) { dwpSprite = (DWORD *)((BYTE *)dwpSprite + iSpritePitch * clippingY); } iDrawY = m_iCameraPosY; } if (iDrawY + iSpriteHeight >= m_iCameraPosY + iDestHeight) { iSpriteHeight = iSpriteHeight - ((iDrawY + iSpriteHeight) - (m_iCameraPosY + iDestHeight)); } if (iDrawX < m_iCameraPosX) { //2018.02.08 clippingX = m_iCameraPosX - iDrawX; iSpriteWidth = iSpriteWidth - clippingX; if (iSpriteWidth > 0) { dwpSprite = dwpSprite + clippingX; } iDrawX = m_iCameraPosX; } if (iDrawX + iSpriteWidth >= m_iCameraPosX + iDestWidth) { iSpriteWidth = iSpriteWidth - ((iDrawX + iSpriteWidth) - (m_iCameraPosX + iDestWidth)); } if (iSpriteWidth <= 0 || iSpriteHeight <= 0) { return; } //2018.02.08 //카메라 기준으로 iDrawX iDrawY 값 좌표 맞추기 iDrawX = iDrawX - m_iCameraPosX; iDrawY = iDrawY - m_iCameraPosY; HDC hdc; RECT DCRect; GetClientRect(hWnd, &DCRect); hdc = GetDC(hWnd); WCHAR wchString[32]; wsprintfW(wchString, L"%d", id); TextOut(hdc, iDrawX, iDrawY, wchString, wcslen(wchString)); ReleaseDC(hWnd, hdc); } //카메라 위치 void CSpriteDib::SetCameraPosition(int iPosX, int iPosY) { m_iCameraPosX = iPosX; m_iCameraPosY = iPosY; } void CSpriteDib::Reset(int iMaxSprite, DWORD dwColorKey) { int iCount; //----------------------------------------------------------------- // 전체를 돌면서 모두 지우자. //----------------------------------------------------------------- for (iCount = 0; iCount < m_iMaxSprite; iCount++) { ReleaseSprite(iCount); } delete[] m_stpSprite; //----------------------------------------------------------------- // 최대 읽어올 개수 만큼 미리 할당 받는다. //----------------------------------------------------------------- m_iMaxSprite = iMaxSprite; m_dwColorKey = dwColorKey; m_stpSprite = new st_SPRITE[iMaxSprite]; // 초기화 iCount = 0; while (iCount < iMaxSprite) { m_stpSprite[iCount].bypImage = NULL; ++iCount; } //기본 카메라 위치 m_iCameraPosX = 0; m_iCameraPosY = 0; }
[ "lethita0302@gmail.com" ]
lethita0302@gmail.com
66eab72d4240498f0d725f66e39c7412f4c2d645
565b4e773bd7892364e078195752af8428b0516c
/A09/A09_Source.cpp
697649ec908ecf520ed9f8f19c2ecc31a5254d7e
[]
no_license
xavigp98/CppProjects_XavierGracia
be348f8e113f18f921461c020c9e57ff7bd89f66
b29bdeda35a6c540b8568f2608c81e1d7b117335
refs/heads/master
2021-01-22T03:48:46.442263
2017-09-12T09:41:50
2017-09-12T09:41:50
81,460,048
0
0
null
null
null
null
UTF-8
C++
false
false
172
cpp
#include "myStack.h" int main() { myStack uno; uno.push(3); int tres = uno.top(); int size = uno.size(); uno.pop(); bool isEmpty = uno.isEmpty(); return 0; }
[ "xaviergraciapereniguez@enti.cat" ]
xaviergraciapereniguez@enti.cat
c4a71455f1d402c94becd68c25466b04b147297a
7b00c6e83083727e455e40cbfc00b2fc035f6f86
/shaka/src/js/navigator.cc
3fa72e5534bbbbe11f87ebb5025dd02e52ebb4c5
[ "Apache-2.0", "BSD-3-Clause" ]
permissive
nextsux/shaka-player-embedded
150ad30ce2dda8c1552027022cd185f2d0c78c40
dccd0bbe7f326e73ef4841700b9a65ded6353564
refs/heads/master
2023-01-08T05:17:09.681606
2020-10-23T21:49:30
2020-10-23T21:59:03
310,596,930
0
0
NOASSERTION
2020-11-06T12:53:50
2020-11-06T12:53:50
null
UTF-8
C++
false
false
2,742
cc
// Copyright 2016 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 // // https://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 "src/js/navigator.h" #include <utility> #include "src/core/js_manager_impl.h" #include "src/js/eme/search_registry.h" #include "src/js/js_error.h" namespace shaka { namespace js { Navigator::Navigator() {} // \cond Doxygen_Skip Navigator::~Navigator() {} // \endcond Doxygen_Skip Promise Navigator::RequestMediaKeySystemAccess( std::string key_system, std::vector<eme::MediaKeySystemConfiguration> configs) { // 1. If keySystem is the empty string, return a promise rejected with a // newly created TypeError. if (key_system.empty()) { return Promise::Rejected( JsError::TypeError("The keySystem parameter is empty.")); } // 2. If supportedConfigurations is empty, return a promise rejected with a // newly created TypeError. if (configs.empty()) { return Promise::Rejected( JsError::TypeError("The configuration parameter is empty.")); } // NA: 3. Let document be the calling context's Document. // NA: 4. Let origin be the origin of document. // 5. Let promise be a new Promise. Promise promise = Promise::PendingPromise(); // 6. Run the following steps in parallel: JsManagerImpl::Instance()->MainThread()->AddInternalTask( TaskPriority::Internal, "search eme registry", eme::SearchRegistry(promise, std::move(key_system), std::move(configs))); // 7. Return promise. return promise; } NavigatorFactory::NavigatorFactory() { AddReadOnlyProperty("appName", &Navigator::app_name); AddReadOnlyProperty("appCodeName", &Navigator::app_code_name); AddReadOnlyProperty("appVersion", &Navigator::app_version); AddReadOnlyProperty("platform", &Navigator::platform); AddReadOnlyProperty("product", &Navigator::product); AddReadOnlyProperty("productSub", &Navigator::product_sub); AddReadOnlyProperty("vendor", &Navigator::vendor); AddReadOnlyProperty("vendorSub", &Navigator::vendor_sub); AddReadOnlyProperty("userAgent", &Navigator::user_agent); AddMemberFunction("requestMediaKeySystemAccess", &Navigator::RequestMediaKeySystemAccess); } NavigatorFactory::~NavigatorFactory() {} } // namespace js } // namespace shaka
[ "modmaker@google.com" ]
modmaker@google.com
7309947f55e1483fe44ebd5a720b883d07bf0fa1
a5223041f795bea49dc3917b24fbd1a5aa371876
/BankUI/BankUIDlg.cpp
9bb9d51b0cf892c91a0f4cb347ade17cb182ca77
[]
no_license
arkssss/BankSystem
72bd9fb97af63f14701404d7b9659b02a9ead9b5
3a2f901e0fd2e68a85291109562d24a53c3b7eca
refs/heads/master
2020-03-09T17:44:29.854007
2018-06-05T02:15:37
2018-06-05T02:15:37
128,915,215
2
0
null
null
null
null
GB18030
C++
false
false
7,467
cpp
// BankUIDlg.cpp : 实现文件 // #include "stdafx.h" #include "BankUI.h" #include "BankUIDlg.h" #include "afxdialogex.h" #include "LogInMenu.h" #include "MysqlForBank.h" #include "Function.h" #include "CLanguage.h" #ifdef _DEBUG #define new DEBUG_NEW #endif //-------静态成员变量初始化 int CBankUIDlg::m_LogInTimes=0; C_AIVoice CBankUIDlg::AIVoice; CCard CBankUIDlg::CurrentCard; Mysql_Op CBankUIDlg::DB; CLanguage CBankUIDlg::Language; //用户的语言选择 1英文 0中文 int CBankUIDlg::m_LanguageChose; // 用于应用程序“关于”菜单项的 CAboutDlg 对话框 LogInInfo CBankUIDlg::LogInfo; MYsql CBankUIDlg::My_Mysql; //-------- class CAboutDlg : public CDialogEx { public: CAboutDlg(); // 对话框数据 enum { IDD = IDD_ABOUTBOX }; protected: virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV 支持 // 实现 protected: DECLARE_MESSAGE_MAP() }; CAboutDlg::CAboutDlg() : CDialogEx(CAboutDlg::IDD) { MessageBox(_T("111")); } void CAboutDlg::DoDataExchange(CDataExchange* pDX) { CDialogEx::DoDataExchange(pDX); } BEGIN_MESSAGE_MAP(CAboutDlg, CDialogEx) END_MESSAGE_MAP() // CBankUIDlg 对话框 CBankUIDlg::CBankUIDlg(CWnd* pParent /*=NULL*/) : CDialogEx(CBankUIDlg::IDD, pParent) , CardNumber(_T("")) , CardPassWrod(_T("")) { m_hIcon = AfxGetApp()->LoadIcon(IDR_MAINFRAME); } void CBankUIDlg::DoDataExchange(CDataExchange* pDX) { CDialogEx::DoDataExchange(pDX); DDX_Text(pDX, IDC_CardNumber, CardNumber); DDX_Text(pDX, IDC_PassWord, CardPassWrod); DDX_Control(pDX, IDC_COMBO_language, m_cb); DDX_Control(pDX, IDC_COMBO_language, m_cb); } BEGIN_MESSAGE_MAP(CBankUIDlg, CDialogEx) ON_WM_SYSCOMMAND() ON_WM_PAINT() ON_WM_QUERYDRAGICON() ON_BN_CLICKED(IDB_LOGIN, &CBankUIDlg::OnBnClickedButton1) ON_EN_CHANGE(IDC_CardNumber, &CBankUIDlg::OnEnChangeEdit1) ON_CBN_SELCHANGE(IDC_COMBO_language, &CBankUIDlg::OnCbnSelchangeCombolanguage) ON_WM_CTLCOLOR() END_MESSAGE_MAP() // CBankUIDlg 消息处理程序 BOOL CBankUIDlg::OnInitDialog() { CDialogEx::OnInitDialog(); // 将“关于...”菜单项添加到系统菜单中。 // IDM_ABOUTBOX 必须在系统命令范围内。 ASSERT((IDM_ABOUTBOX & 0xFFF0) == IDM_ABOUTBOX); ASSERT(IDM_ABOUTBOX < 0xF000); CMenu* pSysMenu = GetSystemMenu(FALSE); if (pSysMenu != NULL) { BOOL bNameValid; CString strAboutMenu; bNameValid = strAboutMenu.LoadString(IDS_ABOUTBOX); ASSERT(bNameValid); if (!strAboutMenu.IsEmpty()) { pSysMenu->AppendMenu(MF_SEPARATOR); pSysMenu->AppendMenu(MF_STRING, IDM_ABOUTBOX, strAboutMenu); } } // 设置此对话框的图标。当应用程序主窗口不是对话框时,框架将自动 // 执行此操作 SetIcon(m_hIcon, TRUE); // 设置大图标 SetIcon(m_hIcon, FALSE); // 设置小图标 // TODO: 在此添加额外的初始化代码 m_cb.InsertString(0,_T("中文")); m_cb.InsertString(1,_T("English")); //Status tmp=Log_In; AIVoice.PlayThisVoice(Log_In); //初始化为次数 m_LogInTimes=0; //语言直接初始化为中文 Language(0); return TRUE; // 除非将焦点设置到控件,否则返回 TRUE } void CBankUIDlg::OnSysCommand(UINT nID, LPARAM lParam) { if ((nID & 0xFFF0) == IDM_ABOUTBOX) { CAboutDlg dlgAbout; dlgAbout.DoModal(); } else { CDialogEx::OnSysCommand(nID, lParam); } } // 如果向对话框添加最小化按钮,则需要下面的代码 // 来绘制该图标。对于使用文档/视图模型的 MFC 应用程序, // 这将由框架自动完成。 void CBankUIDlg::OnPaint() { if (IsIconic()) { CPaintDC dc(this); // 用于绘制的设备上下文 SendMessage(WM_ICONERASEBKGND, reinterpret_cast<WPARAM>(dc.GetSafeHdc()), 0); // 使图标在工作区矩形中居中 int cxIcon = GetSystemMetrics(SM_CXICON); int cyIcon = GetSystemMetrics(SM_CYICON); CRect rect; GetClientRect(&rect); int x = (rect.Width() - cxIcon + 1) / 2; int y = (rect.Height() - cyIcon + 1) / 2; // 绘制图标 dc.DrawIcon(x, y, m_hIcon); } else { CDialogEx::OnPaint(); } } //当用户拖动最小化窗口时系统调用此函数取得光标 //显示。 HCURSOR CBankUIDlg::OnQueryDragIcon() { return static_cast<HCURSOR>(m_hIcon); } void CBankUIDlg::OnBnClickedButton1() { // TODO: 在此添加控件通知处理程序代码 UpdateData(true); int status; if(m_LogInTimes==0){ //说明是新账号登陆 //则跟BeForeCardNum 赋值 BeforeCardNum=CardNumber; } if(CardNumber!=BeforeCardNum){ //登陆的为新账号 m_LogInTimes=0; BeforeCardNum=CardNumber; //同样的赋值 } if(CMysqlForBank::Login(CardNumber,CardPassWrod,status)){ //登陆成功 显示菜单界面 //AIVoice.PlayThisVoice(Login_Successful); OnOK(); CLogInMenu Menu; Menu.DoModal(); }else{ AIVoice.PlayThisVoice(Login_Fail); if(status==3){ if(!m_LanguageChose){ //中文 MessageBox(_T("账号不存在!")); }else{ MessageBox(_T("Account or password is not correct!")); } }else if(status==1){ //冻结 if(!m_LanguageChose){ //中文 MessageBox(_T("该账号被冻结")); }else{ MessageBox(_T("This account has been frozen!")); } }else if(status==2 && m_LogInTimes<3){ //密码错误 CString chi; chi.Format(_T("密码输入错误 !!您还有%d次输入机会"),3-m_LogInTimes); CString eng; eng.Format(_T("Incorrect password ! ! You also have %d chances to enter"),3-m_LogInTimes); if(!m_LanguageChose){ //中文 MessageBox(chi); }else{ MessageBox(eng); } }else if(status==2 && m_LogInTimes==3){ if(CMysqlForBank::FreezenCard(CardNumber)){ if(!m_LanguageChose){ //中文 MessageBox(_T("该账号被冻结")); }else{ MessageBox(_T("This account has been frozen!")); } }else{ if(!m_LanguageChose){ //中文 MessageBox(_T("服务器忙")); }else{ MessageBox(_T("Server busy!")); } } } } } void CBankUIDlg::OnEnChangeEdit1() { // TODO: 如果该控件是 RICHEDIT 控件,它将不 // 发送此通知,除非重写 CDialogEx::OnInitDialog() // 函数并调用 CRichEditCtrl().SetEventMask(), // 同时将 ENM_CHANGE 标志“或”运算到掩码中。 // TODO: 在此添加控件通知处理程序代码 } bool CBankUIDlg::KeyDown(MSG* pMsg){ if (WM_KEYFIRST <= pMsg->message && pMsg->message <= WM_KEYLAST) { MessageBox(_T("111")); } return true; } void CBankUIDlg::OnCbnSelchangeCombo1() { // TODO: 在此添加控件通知处理程序代码 } //下拉框的选择 void CBankUIDlg::OnCbnSelchangeCombolanguage() { // TODO: 在此添加控件通知处理程序代码 int nIndex = m_cb.GetCurSel(); //中文 0 英文 1 //m_cb.GetLBText( nIndex, strCBText); //MessageBox(strCBText); m_LanguageChose=nIndex; Language(m_LanguageChose); //设置语言 GetDlgItem(IDC_STATIC_Id)->SetWindowText(Language.BankCardId); GetDlgItem(IDC_STATIC_pwd)->SetWindowText(Language.Password); GetDlgItem(IDB_LOGIN)->SetWindowText(Language.Login); } BOOL CBankUIDlg::PreTranslateMessage(MSG* pMsg) { // TODO: 在此添加专用代码和/或调用基类 if(pMsg->message == WM_KEYDOWN) { switch(pMsg->wParam) { case VK_RETURN: // 屏蔽回车 OnBnClickedButton1(); return true; } } return CDialogEx::PreTranslateMessage(pMsg); }
[ "522500442@qq.com" ]
522500442@qq.com
1d7c30b6465d13ebfd960b3f28870b5dcd155869
a523c6bd27af78a3d4e177d50fb0ef5cbd09f938
/atcoder/cpp/abc098/D.cpp
7640f7e336d0d1a8d4b81cabdb359c96736637a2
[]
no_license
darshimo/CompetitiveProgramming
ab032aefd03a26e65b8f6b3052cbeb0099857096
9ae43d0eac8111917bdf9496522f1f130bdd17b6
refs/heads/master
2020-08-11T02:40:57.444768
2019-10-11T15:56:26
2019-10-11T15:56:26
214,474,282
0
0
null
null
null
null
UTF-8
C++
false
false
1,054
cpp
#include <cstdio> #include <cstdlib> char *zero(){ char *p = (char *)malloc(sizeof(char)*20); for(int i=0;i<20;i++)p[i]=0; return p; } void add(char *a1, char *a2){ for(int i=0;i<20;i++)a1[i]+=a2[i]; return; } void sub(char *a1, char *a2){ for(int i=0;i<20;i++)a1[i]-=a2[i]; return; } bool ok(char *a1, char *a2){ for(int i=0;i<20;i++){ if(a1[i]*a2[i])return false; } return true; } char *setbit(int A){ char *p = (char *)malloc(sizeof(char)*20); for(int i=0;i<20;i++){ p[i]=A%2; A/=2; } return p; } int main(){ int i,n; scanf("%d",&n); int *A = (int *)malloc(sizeof(int)*n); char **a = (char **)malloc(sizeof(char *)*n); for(i=0;i<n;i++){ scanf("%d",A+i); a[i] = setbit(A[i]); } int j = 0; int c = 0; char *tmp=zero(); for(i=0;i<n;i++){ while(j<n&&ok(tmp,a[j])){ add(tmp,a[j]); j++; } sub(tmp,a[i]); c+=j-i; } printf("%d\n",c); return 0; }
[ "takumishimoda7623@gmail.com" ]
takumishimoda7623@gmail.com
1b5f00e8c6c953ec6ea7d1b41825a792ff2a2d19
30bdd8ab897e056f0fb2f9937dcf2f608c1fd06a
/CodesNew/474.cpp
a3e49cdb8a5e99cf31d431f7c040a6a8ed2987e7
[]
no_license
thegamer1907/Code_Analysis
0a2bb97a9fb5faf01d983c223d9715eb419b7519
48079e399321b585efc8a2c6a84c25e2e7a22a61
refs/heads/master
2020-05-27T01:20:55.921937
2019-11-20T11:15:11
2019-11-20T11:15:11
188,403,594
2
1
null
null
null
null
UTF-8
C++
false
false
603
cpp
#include <iostream> using namespace std; long long n,t,l=1,r=1,a[100005],sum=0,ans=0; int main() { cin>>n>>t; for(int i=1;i<=n;i++){ cin>>a[i]; } for(int i=1;i<=n;i++){ a[i]+=a[i-1]; } while(r<=n && l<=n){ sum=a[r]-a[l-1]; if(sum<=t){ ans=max(ans,r-(l-1)); r++; } else{ if (l==r) { r++; l++; } else l++; } } cout<<ans; return 0; }
[ "harshitagar1907@gmail.com" ]
harshitagar1907@gmail.com
03d64891c57f9d51659b155b825158464012e608
19e78b53f3b7c4e135f272a478d47df3d4a42cae
/source/common/utility/hash_table.h
10e1e6e1806f9ce249c4506a37a69b789cbb25ff
[]
no_license
Gumgo/WaveLang
5eaaa2f5d7876805fd5b353e1d885e630580d124
c993b4303de0889f63dda10a0fd4169aaa59d400
refs/heads/master
2021-06-17T23:24:07.827945
2021-03-12T18:22:19
2021-03-12T18:22:19
37,759,958
2
3
null
2015-07-18T11:54:16
2015-06-20T06:10:50
C++
UTF-8
C++
false
false
1,292
h
#pragma once #include "common/common.h" #include "common/utility/pod.h" #include <new> #include <vector> // This hash table preallocates its memory template<typename t_key, typename t_value, typename t_hash> class c_hash_table { public: c_hash_table(); ~c_hash_table(); // $TODO add move constructor void initialize(size_t bucket_count, size_t element_count); void terminate(); // Returns pointer to the value if successful, null pointer otherwise // $TODO add versions taking rvalue references t_value *insert(const t_key &key); // Uses default constructor for value t_value *insert(const t_key &key, const t_value &value); bool remove(const t_key &key); t_value *find(const t_key &key); const t_value *find(const t_key &key) const; private: static constexpr size_t k_invalid_element_index = static_cast<size_t>(-1); using s_pod_key = s_pod<t_key>; using s_pod_value = s_pod<t_value>; struct s_bucket { size_t first_element_index; }; struct s_element { size_t next_element_index; s_pod_key key; s_pod_value value; }; size_t get_bucket_index(const t_key &key) const; s_element *insert_internal(const t_key &key); std::vector<s_bucket> m_buckets; std::vector<s_element> m_elements; size_t m_free_list; }; #include "common/utility/hash_table.inl"
[ "gumgo1@gmail.com" ]
gumgo1@gmail.com
4e1eb034bb57014b4a7c62aee8eb1f41584c5b80
37464ad43bcd0e263e1bf50c248a1e13e4ba8cf6
/MrRipPlug/FMT/0wwmix/misc/xif_file.h
ae0ba7b9b7bdc7e086d1b48d71d9f36fccc25e26
[]
no_license
crom83/cromfarplugs
5d3a65273433c655d63ef649ac3a3f3618d2ca82
666c3cafa35d8c7ca84a6ca5fc3ff7c69430bf0e
refs/heads/master
2021-01-21T04:26:34.123420
2016-08-11T14:47:51
2016-08-11T14:47:51
54,393,015
3
2
null
2016-08-11T14:47:51
2016-03-21T13:54:32
C++
UTF-8
C++
false
false
922
h
// xif_file.h: interface for the Cxif_file class. // ////////////////////////////////////////////////////////////////////// #if !defined(AFX_XIF_FILE_H__93731940_3FA3_11D4_B606_0000B4936994__INCLUDED_) #define AFX_XIF_FILE_H__93731940_3FA3_11D4_B606_0000B4936994__INCLUDED_ #if _MSC_VER > 1000 #pragma once #endif // _MSC_VER > 1000 #include "cc_file_sh.h" #include "cc_structures.h" #include "xif_key.h" class Cxif_file: public Ccc_file_sh<t_xif_header> { public: bool is_valid() const { int size = get_size(); const t_xif_header& header = *get_header(); return !(sizeof(t_xif_header) > size || header.id != file_id || header.version != file_version_old && header.version != file_version_new); } int decode(Cxif_key& key) { return key.load_key(get_data(), get_size()); } }; #endif // !defined(AFX_XIF_FILE_H__93731940_3FA3_11D4_B606_0000B4936994__INCLUDED_)
[ "crom83@mail.ru" ]
crom83@mail.ru
7bc87cb23bb2eadadf5120b1eb9709bb13b65362
1d7f8363324c092b0f04144515bf0e46a0a14940
/2017/C语言课程设计/提交报告/16040310037朱云韬/elevator.cpp
e8e30b5463607b332921c589a402c1903caac313
[]
no_license
jtrfid/C-Repositories
ddd7f6ca82c275d299b8ffaca0b44b76c945f33d
c285cb308d23a07e1503c20def32b571876409be
refs/heads/master
2021-01-23T09:02:12.113799
2019-05-02T05:00:46
2019-05-02T05:00:46
38,694,237
0
0
null
null
null
null
GB18030
C++
false
false
3,845
cpp
#include "stdafx.h" #include <stdio.h> #include <stdlib.h> #include <math.h> #include "ElevatorLib.h" /********************************************** * Idle状态,电梯停止在某楼层,门是关闭的,处于静止状态,等待相关事件的发生,从而转换到下一个状态。 **********************************************/ void StateIdle(int *state) { int floor; bool up; floor = IdleWhatFloorToGoTo(&up); if (floor > 0 && up) { SetMotorPower(1); *state = MovingUp; printf("Transition: from Idle to MovingUp.\n"); } if (floor>0&&!up) { SetMotorPower(-1); *state = MovingDown; printf("Transition: from Idle to MovingDowm.\n"); } if (GetOpenDoorLight()||GetCallLight(GetNearestFloor(), true)||GetCallLight( GetNearestFloor(), false)) { SetDoor(floor,true); *state = DoorOpen; printf("Transition: from Idle to DoorOpen.\n"); SetOpenDoorLight(false); SetCallLight(GetNearestFloor(), true, false); SetCallLight(GetNearestFloor(), false, false); } if (GetCloseDoorLight()) { SetCloseDoorLight(false); return; } } void StateMovingUp(int *state) { int floor; floor = GoingUpToFloor(); if (fabs(GetFloor() - floor) < Lib_FloorTolerance) { SetMotorPower(0); SetDoor(floor, true); *state = DoorOpen; printf("Transition: from MovingUp to DoorOpen.\n"); floor = GetNearestFloor(); SetCallLight(floor, true, false); SetCallLight(floor, false, false); SetPanelFloorLight(GetNearestFloor(), false); } if (GetOpenDoorLight() || GetCloseDoorLight()) { SetOpenDoorLight(false); SetCloseDoorLight(false); } } void StateMovingDown(int *state) { int floor; floor = GoingDownToFloor(); if (fabs(GetFloor() - floor) < Lib_FloorTolerance) { SetMotorPower(0); SetDoor(floor, true); *state = DoorOpen; printf("Transition: from MovingDown to DoorOpen.\n"); SetCallLight(floor, true, false); SetCallLight(floor, false, false); SetPanelFloorLight(floor,false); } if (GetOpenDoorLight() || GetCloseDoorLight()) { SetOpenDoorLight(false); SetCloseDoorLight(false); } } void StateDoorOpen(int *state) { if (GetCloseDoorLight()) { SetCloseDoorLight(false); SetDoor(GetNearestFloor(), false); *state = DoorClosing; printf("Transition: from DoorOpen to DoorClosing.\n"); } if (IsDoorOpen(GetNearestFloor())) { SetDoor(GetNearestFloor(), false); *state = DoorClosing; printf("Transition: from MovingUp to DoorClosing.\n"); } if (GetOpenDoorLight()) { SetOpenDoorLight(false); } } void StateDoorClosing(int *state) { if (GetOpenDoorLight()) { SetOpenDoorLight(false); SetDoor(GetNearestFloor(), true); *state = DoorOpen; printf("Transition: from DoorClosing to DoorOpen.\n"); } if (GetCloseDoorLight()) { SetCloseDoorLight(false); } if (IsBeamBroken()) { SetDoor(GetNearestFloor(), true); *state = DoorOpen; printf("Transition: from DoorClosing to DoorOpen.\n"); } if (IsDoorClosed(GetNearestFloor())) { *state = Idle; } } /*********************************************** * 状态机,每隔一定时间(如,100ms)被调用一次,采集系统的运行状态 ***********************************************/ void main_control(int *state) { if(IsElevatorRunning()) // 仿真正在运行 { switch(*state) { case Idle: // Idle状态,一定时间无动作,自动到一楼 if(GetNearestFloor() !=1 ) { AutoTo1Floor(); } StateIdle(state); break; case MovingUp: CancelTo1Floor(); // 其它状态,取消自动到一楼 StateMovingUp(state); break; case MovingDown: CancelTo1Floor(); StateMovingDown(state); break; case DoorOpen: CancelTo1Floor(); StateDoorOpen(state); break; case DoorClosing: CancelTo1Floor(); StateDoorClosing(state); break; default: printf("没有这种状态!!!\n"); } } }
[ "jtrfid@qq.com" ]
jtrfid@qq.com
11667f7a97a70b3d0a3a4a68df2dab613128c891
f6695e04d3188c96f0e8f08b8bfdcd362056b451
/xtwse/FT/source/bxDR/backup/bxRptWorker.cpp
b0973626b5d639ede0e47d4b54de1f9b7eadf030
[]
no_license
sp557371/TwseNewFix
28772048ff9150ba978ec591aec22b855ae6250a
5ed5146f221a0e38512e4056c2c4ea52dbd32dcd
refs/heads/master
2020-04-17T03:18:03.493560
2019-01-17T08:40:46
2019-01-17T08:40:46
166,175,913
0
0
null
null
null
null
BIG5
C++
false
false
4,459
cpp
#ifdef __BORLANDC__ #pragma hdrstop #pragma package(smart_init) #endif //--------------------------------------------------------------------------- #include "bxRptWorker.h" #include "bxRpt.h" #include "TwStk.h" #include "bxRptSes.h" //--------------------------------------------------------------------------- using namespace Kway::Tw::Bx; using namespace Kway::Tw::Bx::Rpt; ///////////////////////////////////////////////////////////////////////////// K_mf(int) TWork_RPT::GetPacketSize(TbxSesBase& aSes, const TbxData& aPkt) { switch(aPkt.GetFun()) { case ckRPTLink: switch(aPkt.GetMsg()) { case mgR1: // same as R2 case mgR2: return sizeof(TR1R2); case mgR4: // same as R5 case mgR5: return sizeof(TR4R5); } break; case ckRPTData: return sizeof(TControlHead) + sizeof(TLength); case ckRPTEnd: return sizeof(TR6); } return 0; } //--------------------------------------------------------------------------- K_mf(int) TWork_RPT::BeforeAPacket(TbxSesBase& aSes, const TbxData& aPkt) { if(aPkt.GetFun() == ckRPTData) { const TControlHead* head = static_cast<const TControlHead*>(&aPkt); const TR3 *r3 = static_cast<const TR3*>(head); return szTR3_Head + r3->BodyLength_.as_int(); } return 0; } //--------------------------------------------------------------------------- K_mf(bool) TWork_RPT::APacket(TbxSesBase& aSes, const TbxData& aPkt) { TbxRptSes* ses = dynamic_cast<TbxRptSes*>(&aSes); const TControlHead* head = static_cast<const TControlHead*>(&aPkt); size_t sz = GetPacketSize(aSes, aPkt); ses->WriteLog(reinterpret_cast<const char*>(&aPkt), sz, ses->GetPvcID()); return OnRptPkt(*ses, *head); } //--------------------------------------------------------------------------- K_mf(bool) TWork_RPT::DoReq(TbxSesBase& aSes, const TBxMsg aMsg, const TControlHead& aPkt) { TbxRptSes* ses = dynamic_cast<TbxRptSes*>(&aSes); return DoRptReq(*ses, aMsg, aPkt); } ///////////////////////////////////////////////////////////////////////////// K_mf(bool) TWork_R5000::OnRptPkt(TbxRptSes& aSes, const TControlHead& aPkt) { switch(aPkt.GetMsg()) { case mgR2: // R2 起始作業訊息 aSes.SetState(TbxRptSes::rpt_RptReply, "R2"); aSes.StartRptTimer(); break; case mgR4: // R4 連線作業訊息 if(aSes.DoWorker(aSes.GetWorkKey(ckRPTLink), mgR5, aPkt)) //送出 R5 { aSes.SetState(TbxRptSes::rpt_LinkChk, "R5"); aSes.StartRptTimer(); } break; default: return false; } return true; } //--------------------------------------------------------------------------- K_mf(bool) TWork_R5000::DoRptReq(TbxRptSes& aSes, const TBxMsg aMsg, const TControlHead& aPkt) { TR1R2 r1; TR4R5 r5; switch(aMsg) { case mgR1: r1.SetHead(GetWorkKey(), aMsg, aPkt.GetCode()); r1.BrkID_ = aSes.GetBrokerID(); r1.StartSeq_ = aSes.GetNextSeqNo(); return aSes.SendPkt(r1); case mgR5: r5.SetHead(GetWorkKey(), aMsg, aPkt.GetCode()); return aSes.SendPkt(r5); } return false; } ///////////////////////////////////////////////////////////////////////////// K_mf(bool) TWork_R5010::OnRptPkt(TbxRptSes& aSes, const TControlHead& aPkt) { // 如果STATE是rpt_Starting, 表示在重新要求R1, 此時放棄該成交資料 if(aSes.GetSesState() == TbxRptSes::rpt_Starting) return true; if(aPkt.GetMsg() == mgR3) { aSes.SetState(TbxRptSes::rpt_Data, "R3"); const TR3* r3 = static_cast<const TR3*>(&aPkt); int count = r3->BodyCount_.as_int(); for(int i=0;i<count;i++) aSes.WritePmach(r3->Body_[i]); return true; } return false; } ///////////////////////////////////////////////////////////////////////////// K_mf(bool) TWork_R5020::OnRptPkt(TbxRptSes& aSes, const TControlHead& aPkt) { if(aPkt.GetFun() == mgR6) { TRptBody body; const TR6* r6 = static_cast<const TR6*>(&aPkt); aSes.StopRptTimer(); aSes.SetState(TbxRptSes::rpt_Logout, "R6"); body.ExcCode_.assign("0"); body.OrdNo_.assign(" "); body.StkNo_.assign(" "); body.BSCode_.assign(" "); body.OrdType_.assign("0"); body.SeqNo_.assign(r6->TotalRec_.as_string()); body.BrkID_.assign(" "); aSes.WritePmach(body); aSes.CheckRptCount(r6->TotalRec_.as_int()); } return false; } //---------------------------------------------------------------------------
[ "xtwse@mail.kway.com.tw" ]
xtwse@mail.kway.com.tw
b4f41faea6150792a3e0c4130bcd4f58bd2739f4
8d4b95617d3db5e3346a6dae77e9315dfb0c2eef
/joystick.cpp
6cfe317ee26da90f45841cbb5f453d22e35c645a
[]
no_license
steaphangreene/user
8f4a0816e3b211ecbae6b07feb1032381b3cbe6d
4b11c4675a3a51f0d61488ce83abebf055e855ad
refs/heads/master
2021-01-13T02:19:33.118694
2014-02-04T07:39:52
2014-02-04T07:41:44
null
0
0
null
null
null
null
UTF-8
C++
false
false
4,895
cpp
#include "config.h" #include "input.h" #include <stdio.h> #include <string.h> #include <unistd.h> #include <sys/time.h> #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include <linux/joystick.h> #include <ctype.h> #include "screen.h" #include "joystick.h" extern Screen *__Da_Screen; extern Joystick *__Da_Joystick[16]; extern InputQueue *__Da_InputQueue; extern char *U2_JoyDev[16]; Joystick::Joystick() { for(jnum = 0; jnum < 16; ++jnum) { if(__Da_Joystick[jnum] == NULL) break; } Create(U2_JoyDev[jnum]); } Joystick::Joystick(const char *devfl) { Create(devfl); } void Joystick::Create(const char *devfl) { if(__Da_Screen == NULL) U2_Exit(-1, "Must create Screen before Joystick!\n"); memset(AxisRemap, 0, 16*(sizeof(Sprite *))); memset(ButtonRemap, 0, 16*(sizeof(Sprite *))); memset((char *)AxisStats, 0, 16*sizeof(int)); memset((char *)ButtonStats, 0, 16*sizeof(char)); jdev = open(devfl, O_RDONLY|O_NONBLOCK); if(jdev < 0) { printf("Can not open Joystick device \"%s\"\n", devfl); printf("There will be no Joystick support.\n"); return; } crit = 0; for(jnum = 0; jnum < 16; ++jnum) { if(__Da_Joystick[jnum] == NULL) { __Da_Joystick[jnum] = this; break; } } if(jnum >= 16) { U2_Exit(-1, "More then 16 Joysticks unsupported!\n"); } } Joystick::~Joystick() { __Da_Joystick[jnum] = NULL; } void Joystick::Update() { if(crit) return; #ifdef X_WINDOWS struct js_event je; while(read(jdev, &je, sizeof(struct js_event)) > 0) { if(je.type == JS_EVENT_BUTTON) { ButtonStats[je.number] = je.value; } else if(je.type == JS_EVENT_AXIS) { AxisStats[je.number] = je.value; } // else if(je.type == JS_EVENT_INIT|JS_EVENT_BUTTON) { // ButtonStats[je.number] = je.value; // } // else if(je.type == JS_EVENT_INIT|JS_EVENT_AXIS) { // AxisStats[je.number] = je.value; // } } #endif } int Joystick::IsPressed(int k) { Update(); if(k >= JS_BUTTON && k < JS_BUTTON_MAX) { return ButtonStats[k-JS_BUTTON]; } else if(k >= JS_AXIS && k < JS_AXIS_MAX) { return AxisStats[k-JS_AXIS]; } else return 0; } unsigned int Joystick::Buttons() { int ctr; unsigned long ret = 0; for(ctr = 0; ctr < (JS_BUTTON_MAX-JS_BUTTON); ++ctr) { if(ButtonStats[ctr]) ret |= (1<<ctr); } return ret; } int Joystick::WaitForAction() { // crit = 1; // int ret = GetAKey(); // if(__Da_Screen == NULL) // while(ret==0) { ret = GetAKey(); } // else // while(ret==0) { __Da_Screen->RefreshFast(); ret = GetAKey(); } // crit = 0; // return ret; return 0; } int Joystick::GetAction(int t) { crit = 1; // int ret = GetAKey(); // if(__Da_Screen == NULL) // while(t>0&&ret==0) { t-=100; usleep(100000); ret = GetAKey(); } // else { // time_t dest; long udest; // timeval tv; // gettimeofday(&tv, NULL); // dest = t/1000; // udest = (t-dest*1000)*1000; // dest += tv.tv_sec; // udest += tv.tv_usec; // if(udest > 1000000) { udest -= 1000000; dest += 1; } // while((tv.tv_sec<dest ||(tv.tv_sec==dest && tv.tv_usec<udest)) && ret==0) { // __Da_Screen->RefreshFast(); ret = GetAKey(); gettimeofday(&tv, NULL); // } // } // crit = 0; // return ret; return 0; } int Joystick::GetAction() { int ret=0; //#ifdef X_WINDOWS // XEvent e; // XFlush(__Da_Screen->_Xdisplay); // while(ret == 0 && XCheckMaskEvent(__Da_Screen->_Xdisplay, // KeyPressMask|KeyReleaseMask, &e)) { // if(e.type == KeyPress) { // ret = XKeycodeToKeysym(__Da_Screen->_Xdisplay, e.xkey.keycode, 0); // key_stat[ret] = 1; // } // else { // key_stat[XKeycodeToKeysym(__Da_Screen->_Xdisplay, e.xkey.keycode, 0)]=0; // } // } //#endif return ret; } void Joystick::DisableQueue() { queue_actions=0; } void Joystick::EnableQueue() { queue_actions=1; } void Joystick::MapActionToControl(int k, Control &c) { MapActionToControl(k, &c); } void Joystick::MapActionToControl(int k, Control *c) { if(k >= JS_BUTTON && k < JS_BUTTON_MAX) ButtonRemap[k-JS_BUTTON] = c; else if(k >= JS_AXIS && k < JS_AXIS_MAX) AxisRemap[k-JS_AXIS] = c; } void Joystick::MapActionToControl(int k, int c) { if(__Da_Screen != NULL) MapActionToControl(k, (Control *)__Da_Screen->GetSpriteByNumber(c)); } /* void Joystick::Down(int k) { if(key_stat[k] == 1) return; key_stat[k] = 1; InputAction a; a.k.type = INPUTACTION_KEYDOWN; a.k.modkeys = ModKeys(); a.k.key = k; a.k.chr = KeyToChar(k); if(__Da_InputQueue != NULL) __Da_InputQueue->ActionOccurs(&a); } void Joystick::Up(int k) { if(key_stat[k] == 0) return; key_stat[k] = 0; InputAction a; a.k.type = INPUTACTION_KEYUP; a.k.modkeys = ModKeys(); a.k.key = k; a.k.chr = 0; if(__Da_InputQueue != NULL) __Da_InputQueue->ActionOccurs(&a); } */
[ "steaphan@gmail.com" ]
steaphan@gmail.com
c4040d99ddf76fa5f8bbf6c60e2c31d9d0241927
91b19ebb15c3f07785929b7f7a4972ca8f89c847
/Classes/HatGacha.cpp
aea8c69e18c32821e23ec745e8501daa4597d657
[]
no_license
droidsde/DrawGirlsDiary
85519ac806bca033c09d8b60fd36624f14d93c2e
738e3cee24698937c8b21bd85517c9e10989141e
refs/heads/master
2020-04-08T18:55:14.160915
2015-01-07T05:33:16
2015-01-07T05:33:16
null
0
0
null
null
null
null
UTF-8
C++
false
false
14,724
cpp
#include "HatGacha.h" #include <random> #include "GachaShowReward.h" const int kFakeItemTag = 0x43534; class CCNodeFrames : public CCNode { protected: std::vector<CCNode*> m_nodes; int m_currentIndex; float m_delay; float m_timer; public: void runAnimation(float delay) { m_timer = 0; m_delay = delay; for(auto i : m_nodes) { i->setVisible(false); } scheduleUpdate(); } void update(float dt) { m_timer += dt; if(m_timer > m_delay) { m_nodes[m_currentIndex]->setVisible(false); m_currentIndex++; if(m_nodes.size() == m_currentIndex) { m_currentIndex = 0; } m_nodes[m_currentIndex]->setVisible(true); while(m_timer > m_delay) { m_timer -= m_delay; } } } void appendNode(CCNode* n) { m_nodes.push_back(n); addChild(n); } static CCNodeFrames* create() { CCNodeFrames* nf = new CCNodeFrames(); nf->init(); nf->autorelease(); return nf; } }; bool HatGachaSub::init(KSAlertView* av, std::function<void(void)> callback, const vector<RewardSprite*>& rs, GachaPurchaseStartMode gsm, GachaCategory gc) { CCLayer::init(); m_gachaCategory = gc; m_gachaMode = gsm; m_fakeRewards = rs; setTouchEnabled(true); CCSprite* dimed = CCSprite::create(); dimed->setTextureRect(CCRectMake(0, 0, 600, 400)); dimed->setColor(ccc3(0, 0, 0)); dimed->setOpacity(180); dimed->setPosition(ccp(240, 160)); addChild(dimed, 0); CCSprite* commonBack = CCSprite::create("hat_stage.png"); commonBack->setPosition(ccp(240, 140)); addChild(commonBack, 0); m_parent = av; m_callback = callback; // setContentSize(av->getViewSize()); m_internalMenu = CCMenuLambda::create(); m_internalMenu->setPosition(ccp(0, 0)); m_internalMenu->setTouchPriority(INT_MIN); m_internalMenu->setTouchEnabled(true); addChild(m_internalMenu); m_menu = CCMenuLambda::create(); m_menu->setPosition(ccp(0, 0)); m_menu->setTouchPriority(INT_MIN); m_menu->setTouchEnabled(false); addChild(m_menu); m_disableMenu = CCMenuLambda::create(); m_disableMenu->setPosition(ccp(0, 0)); addChild(m_disableMenu); for(int i=0; i<360; i+=45) { // 모자 추가 CCMenuItemImageLambda* hatTopOpen = CCMenuItemImageLambda::create("hat_open_01.png", "hat_open_01.png", nullptr); CCMenuItemImageLambda* hatBottomOpen = CCMenuItemImageLambda::create("hat_open_02.png", "hat_open_02.png", nullptr); CCMenuItemImageLambda* hatTopClose = CCMenuItemImageLambda::create("hat_close_01.png", "hat_close_01.png", nullptr); CCMenuItemImageLambda* hatBottomClose = CCMenuItemImageLambda::create("hat_close_02.png", "hat_close_02.png", nullptr); ((CCSprite*)hatTopOpen->getNormalImage())->getTexture()->setAliasTexParameters(); ((CCSprite*)hatBottomOpen->getNormalImage())->getTexture()->setAliasTexParameters(); ((CCSprite*)hatTopClose->getNormalImage())->getTexture()->setAliasTexParameters(); ((CCSprite*)hatBottomClose->getNormalImage())->getTexture()->setAliasTexParameters(); // CCSprite* t; // t->getTexture()->set CCMenuItemToggleWithTopHatLambda* hatBottom = CCMenuItemToggleWithTopHatLambda::createWithTarget ( [=](CCObject* _item) { m_menu->setTouchEnabled(false); CCMenuItemToggleWithTopHatLambda* item = dynamic_cast<CCMenuItemToggleWithTopHatLambda*>(_item); CCLOG("%d", item->getSelectedIndex()); if(m_state == SceneState::kStopHat) { m_selectComment->removeFromParent(); item->m_hatTop->setSelectedIndex(0); item->setSelectedIndex(0); m_state = SceneState::kSelectedHatMoving; m_selectedHat = item; CCPoint centerPosition; if(m_parent) centerPosition = ccp(m_parent->getViewSize().width / 2.f, m_parent->getViewSize().height / 2.f) + ccp(0, 50); else centerPosition = ccp(240, 160); this->addChild(KSGradualValue<CCPoint>::create (m_selectedHat->getPosition(), centerPosition, 0.8f, [=](CCPoint pt) { m_selectedHat->setPosition(pt); topFollowBottom(); // 모자 위가 모자 밑둥을 따라감 }, [=](CCPoint pt) { // 상품을 모자에 맞추고 모자를 열고 상품을 보여줌. addChild(KSTimer::create(1.f, [=]() { for(auto i : m_hats) { i.first->m_reward->setScale(i.first->getScale()); i.first->m_reward->setPosition(i.first->getPosition()); i.first->setSelectedIndex(1); i.first->m_hatTop->setSelectedIndex(1); i.first->m_reward->setVisible(true); if(i.first == m_selectedHat) { // KS::KSLog("kind % value %", (int)i.first->m_reward->m_kind, ); m_state = SceneState::kShowReward1; this->addChild(KSGradualValue<float>::create (1.f, 2.f, 1.f, [=](float t) { i.first->m_reward->setScale(t); }, [=](float t) { CCLOG("end!!"); m_state = SceneState::kShowReward2; // content->addChild(CCSprite::create(i.first->m_reward->m_spriteStr.c_str())); // // // 가격 표시 // content->addChild(CCLabelTTF::create // (CCString::createWithFormat // ("+%d", // i.first->m_reward->m_value)->getCString(), mySGD->getFont().c_str(), 25)); RewardKind kind = i.first->m_reward->m_kind; int selectedItemValue = i.first->m_reward->m_value; std::function<void(void)> replayFunction; CCNode* parentPointer = getParent(); if(m_gachaMode == kGachaPurchaseStartMode_select){ // 선택으로 들어온 거라면 다시 하기가 가능함. replayFunction = [=]() { auto retryGame = [=](){ auto tempKind = i.first->m_reward->m_kind; auto value = i.first->m_reward->m_value; auto spriteStr = i.first->m_reward->m_spriteStr; auto weight = i.first->m_reward->m_weight; std::vector<RewardSprite*> rewards; for(auto i : m_rewards) { rewards.push_back(RewardSprite::create(tempKind, value, spriteStr, weight)); } parentPointer->addChild(HatGachaSub::create(m_callback, rewards, m_gachaMode, m_gachaCategory), this->getZOrder()); this->removeFromParent(); }; // 선택으로 들어온 거라면 다시 하기가 가능함. if(m_gachaCategory == GachaCategory::kRubyGacha) { if(mySGD->getGoodsValue(kGoodsType_ruby) >= mySGD->getGachaRubyFeeRetry()) { // mySGD->setStar(mySGD->getGoodsValue(kGoodsType_ruby) - mySGD->getGachaRubyFeeRetry()); // myDSH->saveUserData({kSaveUserData_Key_star}, [=](Json::Value v) { // // }); retryGame(); } else { CCLOG("돈 없음"); } } else if(m_gachaCategory == GachaCategory::kGoldGacha) { if(mySGD->getGoodsValue(kGoodsType_gold) >= mySGD->getGachaGoldFeeRetry()) { // mySGD->setGold(mySGD->getGoodsValue(kGoodsType_gold) - mySGD->getGachaGoldFeeRetry()); // myDSH->saveUserData({kSaveUserData_Key_gold}, [=](Json::Value v) { // // }); retryGame(); } else { CCLOG("돈 없음"); } } }; }else{ replayFunction = nullptr; }; std::string againFileName; if(m_gachaCategory == GachaCategory::kRubyGacha) { againFileName = "Ruby"; } else if(m_gachaCategory == GachaCategory::kGoldGacha) { againFileName = "Gold"; } GachaShowReward* gachaShowReward = GachaShowReward::create(replayFunction, m_callback, CCSprite::create(i.first->m_reward->m_spriteStr.c_str()), CCString::createWithFormat("%d", i.first->m_reward->m_value)->getCString(), kind, selectedItemValue, againFileName, m_gachaCategory ); addChild(gachaShowReward, 30); })); CCSprite* hatBack = CCSprite::create("hat_back.png"); hatBack->setScale(2.f); CCPoint centerPosition; if(m_parent) centerPosition = ccp(m_parent->getViewSize().width / 2.f, m_parent->getViewSize().height / 2.f) + ccp(0, 50); else centerPosition = ccp(240, 160); hatBack->setPosition(centerPosition); this->addChild(hatBack, 0); this->addChild(KSGradualValue<float>::create (0, 180.f * 99999.f, 99999.f, [=](float t) { hatBack->setRotation(t); }, [=](float t) { CCLOG("qq"); })); } topFollowBottom(); // 모자 위가 모자 밑둥을 따라감 } })); })); } // if(m_state == SceneState::kStopHat) // { // item->m_reward->setVisible(true); // } CCLOG("open!!"); }, hatBottomClose, hatBottomOpen, 0); CCMenuItemToggleLambda* hatTop = CCMenuItemToggleLambda::createWithTarget (nullptr, hatTopClose, hatTopOpen, 0); m_menu->addChild(hatBottom); m_disableMenu->addChild(hatTop); //// m_menu hatBottom->setPosition(retOnTheta(i * M_PI / 180.f)); hatBottom->m_hatTop = hatTop; hatTop->setAnchorPoint(ccp(0.5f, 0.0f)); hatTop->setPosition(ccp(hatBottom->getPositionX(), hatBottom->getPositionY() + hatBottom->getContentSize().height / 2.f)); m_hats.push_back(std::make_pair(hatBottom, i)); } ProbSelector ps; for(auto i : m_fakeRewards) { ps.pushProb(i->m_weight); } for(int i=0; i<8; i++) { int index = ps.getResult(); RewardSprite* temp_rs = m_fakeRewards[index]; RewardSprite* rs = RewardSprite::create(temp_rs->m_kind, temp_rs->m_value, temp_rs->m_spriteStr, temp_rs->m_weight); std::string valueStr = CCString::createWithFormat("%d", temp_rs->m_value)->getCString(); valueStr = std::string("+") + KS::insert_separator(valueStr); CCLabelBMFont* value = CCLabelBMFont::create(valueStr.c_str(), "allfont.fnt"); rs->addChild(value); value->setPosition(ccp(rs->getContentSize().width, rs->getContentSize().height) / 2.f); // rs->setColor(ccc3(255, 0, 0)); KS::setOpacity(rs, 0); // rs->setOpacity(0); addChild(rs, 20); m_rewards.push_back(rs); CCNodeFrames* nf = CCNodeFrames::create(); std::vector<int> randomIndex; for(int i=0; i<m_fakeRewards.size(); i++) { randomIndex.push_back(i); } random_device rd; mt19937 rEngine(rd()); random_shuffle(randomIndex.begin(), randomIndex.end(), [&rEngine](int n) { uniform_int_distribution<> distribution(0, n-1); return distribution(rEngine); }); // 페이크 에니메이션 돌림. for(auto iter : randomIndex) { RewardSprite* temp_rs = m_fakeRewards[iter]; RewardSprite* fakeItem = RewardSprite::create(temp_rs->m_kind, temp_rs->m_value, temp_rs->m_spriteStr, temp_rs->m_weight); std::string valueStr = CCString::createWithFormat("%d", temp_rs->m_value)->getCString(); valueStr = std::string("+") + KS::insert_separator(valueStr); CCLabelBMFont* value = CCLabelBMFont::create(valueStr.c_str(), "allfont.fnt"); fakeItem->addChild(value); value->setPosition(ccp(rs->getContentSize().width, fakeItem->getContentSize().height) / 2.f); nf->appendNode(fakeItem); } nf->runAnimation(0.05f); nf->setTag(kFakeItemTag); rs->addChild(nf); // nf->setPosition(rs->getPosition()); nf->setPosition(ccp(rs->getContentSize().width, rs->getContentSize().height) / 2.f); } // 모자와 똑같은 위치에 상품 넣음. { // 상품 연결 std::random_shuffle(m_rewards.begin(), m_rewards.end(), [=](int i) { return m_well512.GetValue(0, i-1); }); for(int i=0; i<m_hats.size(); i++) { m_hats[i].first->m_reward = m_rewards[i]; } } repositionHat(); for(auto i : m_hats) { i.first->setSelectedIndex(1); // 다 열음 i.first->m_hatTop->setSelectedIndex(1); } // m_rewardFollowHat = false; CCMenuItemImageLambda* startBtn = CCMenuItemImageLambda::create("gacha4_stop.png", "gacha4_stop.png"); startBtn->setPosition(ccp(240, 40)); // startBtn->setVisible(false); startBtn->setTarget([=](CCObject*) { // m_state = SceneState::kRun; startBtn->setVisible(false); for(auto i : m_rewards) { KS::setOpacity(i, 255); i->getChildByTag(kFakeItemTag)->removeFromParent(); } addChild(KSTimer::create(2.f, [=]() { m_state = SceneState::kCoveringHat; })); }); m_state = SceneState::kBeforeCoveringHat; m_internalMenu->addChild(startBtn); scheduleUpdate(); return true; } //HatGacha::HatGacha() //{ //} //HatGacha::~HatGacha() //{ //CCLOG("~hatgacha"); //} ////void HatGacha::registerWithTouchDispatcher() ////{ //// CCTouchDispatcher::sharedDispatcher()->addTargetedDelegate(this, 0, false); ////} ////bool HatGacha::ccTouchBegan(CCTouch* pTouch, CCEvent* pEvent) ////{ //// CCTouch* touch = pTouch; //// //// CCPoint location(ccp(0, 0)); //// location = CCDirector::sharedDirector()->convertToGL(touch->locationInView()); //// //// return true; ////} //bool HatGacha::init(std::function<void(void)> closeCallback) //{ //CCLayer::init(); //KSAlertView* av = KSAlertView::create(); //HatGachaSub* gs = HatGachaSub::create(av, { //RewardSprite::create(RewardKind::kRuby, 20, "price_ruby_img.png", 1), //RewardSprite::create(RewardKind::kGold, 500, "price_gold_img.png", 2), //RewardSprite::create(RewardKind::kSpecialAttack, 1, "item1.png", 5), //RewardSprite::create(RewardKind::kDash, 1, "item4.png", 5), //RewardSprite::create(RewardKind::kSlience, 1, "item8.png", 5), //RewardSprite::create(RewardKind::kRentCard, 1, "item16.png", 5), //RewardSprite::create(RewardKind::kSubMonsterOneKill, 1, "item9.png", 5), //RewardSprite::create(RewardKind::kGold, 1000, "price_gold_img.png", 5) //}); //av->setContentNode(gs); //av->setBack9(CCScale9Sprite::create("popup2_case_back.png", CCRectMake(0,0, 150, 150), CCRectMake(13, 45, 122, 92))); //// av->setContentBorder(CCScale9Sprite::create("popup2_content_back.png", CCRectMake(0,0, 150, 150), CCRectMake(6, 6, 144-6, 144-6))); //av->setBorderScale(0.9f); //av->setButtonHeight(0); //av->setCloseOnPress(false); //// av->setTitleStr("지금 열기"); //addChild(av, 1); //// con2->alignItemsVerticallyWithPadding(30); //av->show(closeCallback); //av->getContainerScrollView()->setTouchEnabled(false); //return true; //}
[ "seo88youngho@gmail.com" ]
seo88youngho@gmail.com
ccac8e7a659f19ab9e5195acc2908eab162e211a
8af716c46074aabf43d6c8856015d8e44e863576
/src/qt/privacydialog.cpp
d95d965639e6ed7984f1693667db622905ce598c
[ "MIT" ]
permissive
coinwebfactory/acrecore
089bc945becd76fee47429c20be444d7b2460f34
cba71d56d2a3036be506a982f23661e9de33b03b
refs/heads/master
2020-03-23T06:44:27.396884
2018-07-17T03:32:27
2018-07-17T03:32:27
141,226,622
0
0
null
null
null
null
UTF-8
C++
false
false
28,237
cpp
// Copyright (c) 2011-2014 The Bitcoin developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "privacydialog.h" #include "ui_privacydialog.h" #include "addressbookpage.h" #include "addresstablemodel.h" #include "bitcoinunits.h" #include "coincontroldialog.h" #include "libzerocoin/Denominations.h" #include "optionsmodel.h" #include "sendcoinsentry.h" #include "walletmodel.h" #include "coincontrol.h" #include "zcivcontroldialog.h" #include "spork.h" #include <QClipboard> #include <QSettings> #include <utilmoneystr.h> #include <QtWidgets> PrivacyDialog::PrivacyDialog(QWidget* parent) : QDialog(parent), ui(new Ui::PrivacyDialog), walletModel(0), currentBalance(-1) { nDisplayUnit = 0; // just make sure it's not unitialized ui->setupUi(this); // "Spending 999999 zACRE ought to be enough for anybody." - Bill Gates, 2017 ui->zACREpayAmount->setValidator( new QDoubleValidator(0.0, 21000000.0, 20, this) ); ui->labelMintAmountValue->setValidator( new QIntValidator(0, 999999, this) ); // Default texts for (mini-) coincontrol ui->labelCoinControlQuantity->setText (tr("Coins automatically selected")); ui->labelCoinControlAmount->setText (tr("Coins automatically selected")); ui->labelzACRESyncStatus->setText("(" + tr("out of sync") + ")"); // Sunken frame for minting messages ui->TEMintStatus->setFrameStyle(QFrame::StyledPanel | QFrame::Sunken); ui->TEMintStatus->setLineWidth (2); ui->TEMintStatus->setMidLineWidth (2); ui->TEMintStatus->setPlainText(tr("Mint Status: Okay")); // Coin Control signals connect(ui->pushButtonCoinControl, SIGNAL(clicked()), this, SLOT(coinControlButtonClicked())); // Coin Control: clipboard actions QAction* clipboardQuantityAction = new QAction(tr("Copy quantity"), this); QAction* clipboardAmountAction = new QAction(tr("Copy amount"), this); connect(clipboardQuantityAction, SIGNAL(triggered()), this, SLOT(coinControlClipboardQuantity())); connect(clipboardAmountAction, SIGNAL(triggered()), this, SLOT(coinControlClipboardAmount())); ui->labelCoinControlQuantity->addAction(clipboardQuantityAction); ui->labelCoinControlAmount->addAction(clipboardAmountAction); // Denomination labels ui->labelzDenom1Text->setText("Denom. with value <b>1</b>:"); ui->labelzDenom2Text->setText("Denom. with value <b>5</b>:"); ui->labelzDenom3Text->setText("Denom. with value <b>10</b>:"); ui->labelzDenom4Text->setText("Denom. with value <b>50</b>:"); ui->labelzDenom5Text->setText("Denom. with value <b>100</b>:"); ui->labelzDenom6Text->setText("Denom. with value <b>500</b>:"); ui->labelzDenom7Text->setText("Denom. with value <b>1000</b>:"); ui->labelzDenom8Text->setText("Denom. with value <b>5000</b>:"); // Acre settings QSettings settings; if (!settings.contains("nSecurityLevel")){ nSecurityLevel = 42; settings.setValue("nSecurityLevel", nSecurityLevel); } else{ nSecurityLevel = settings.value("nSecurityLevel").toInt(); } if (!settings.contains("fMinimizeChange")){ fMinimizeChange = false; settings.setValue("fMinimizeChange", fMinimizeChange); } else{ fMinimizeChange = settings.value("fMinimizeChange").toBool(); } ui->checkBoxMinimizeChange->setChecked(fMinimizeChange); // Start with displaying the "out of sync" warnings showOutOfSyncWarning(true); // Hide those placeholder elements needed for CoinControl interaction ui->WarningLabel->hide(); // Explanatory text visible in QT-Creator ui->dummyHideWidget->hide(); // Dummy widget with elements to hide //temporary disable for maintenance if(GetAdjustedTime() > GetSporkValue(SPORK_16_ZEROCOIN_MAINTENANCE_MODE)) { ui->pushButtonMintzACRE->setEnabled(false); ui->pushButtonMintzACRE->setToolTip(tr("zACRE is currently disabled due to maintenance.")); ui->pushButtonSpendzACRE->setEnabled(false); ui->pushButtonSpendzACRE->setToolTip(tr("zACRE is currently disabled due to maintenance.")); } } PrivacyDialog::~PrivacyDialog() { delete ui; } void PrivacyDialog::setModel(WalletModel* walletModel) { this->walletModel = walletModel; if (walletModel && walletModel->getOptionsModel()) { // Keep up to date with wallet setBalance(walletModel->getBalance(), walletModel->getUnconfirmedBalance(), walletModel->getImmatureBalance(), walletModel->getZerocoinBalance(), walletModel->getUnconfirmedZerocoinBalance(), walletModel->getImmatureZerocoinBalance(), walletModel->getWatchBalance(), walletModel->getWatchUnconfirmedBalance(), walletModel->getWatchImmatureBalance()); connect(walletModel, SIGNAL(balanceChanged(CAmount, CAmount, CAmount, CAmount, CAmount, CAmount, CAmount, CAmount, CAmount)), this, SLOT(setBalance(CAmount, CAmount, CAmount, CAmount, CAmount, CAmount, CAmount, CAmount, CAmount))); ui->securityLevel->setValue(nSecurityLevel); } } void PrivacyDialog::on_pasteButton_clicked() { // Paste text from clipboard into recipient field ui->payTo->setText(QApplication::clipboard()->text()); } void PrivacyDialog::on_addressBookButton_clicked() { if (!walletModel) return; AddressBookPage dlg(AddressBookPage::ForSelection, AddressBookPage::SendingTab, this); dlg.setModel(walletModel->getAddressTableModel()); if (dlg.exec()) { ui->payTo->setText(dlg.getReturnValue()); ui->zACREpayAmount->setFocus(); } } void PrivacyDialog::on_pushButtonMintzACRE_clicked() { if (!walletModel || !walletModel->getOptionsModel()) return; if(GetAdjustedTime() > GetSporkValue(SPORK_16_ZEROCOIN_MAINTENANCE_MODE)) { QMessageBox::information(this, tr("Mint Zerocoin"), tr("zACRE is currently undergoing maintenance."), QMessageBox::Ok, QMessageBox::Ok); return; } // Reset message text ui->TEMintStatus->setPlainText(tr("Mint Status: Okay")); // Request unlock if wallet was locked or unlocked for mixing: WalletModel::EncryptionStatus encStatus = walletModel->getEncryptionStatus(); if (encStatus == walletModel->Locked) { WalletModel::UnlockContext ctx(walletModel->requestUnlock(true)); if (!ctx.isValid()) { // Unlock wallet was cancelled ui->TEMintStatus->setPlainText(tr("Error: Your wallet is locked. Please enter the wallet passphrase first.")); return; } } QString sAmount = ui->labelMintAmountValue->text(); CAmount nAmount = sAmount.toInt() * COIN; // Minting amount must be > 0 if(nAmount <= 0){ ui->TEMintStatus->setPlainText(tr("Message: Enter an amount > 0.")); return; } ui->TEMintStatus->setPlainText(tr("Minting ") + ui->labelMintAmountValue->text() + " zACRE..."); ui->TEMintStatus->repaint (); int64_t nTime = GetTimeMillis(); CWalletTx wtx; vector<CZerocoinMint> vMints; string strError = pwalletMain->MintZerocoin(nAmount, wtx, vMints, CoinControlDialog::coinControl); // Return if something went wrong during minting if (strError != ""){ ui->TEMintStatus->setPlainText(QString::fromStdString(strError)); return; } double fDuration = (double)(GetTimeMillis() - nTime)/1000.0; // Minting successfully finished. Show some stats for entertainment. QString strStatsHeader = tr("Successfully minted ") + ui->labelMintAmountValue->text() + tr(" zACRE in ") + QString::number(fDuration) + tr(" sec. Used denominations:\n"); // Clear amount to avoid double spending when accidentally clicking twice ui->labelMintAmountValue->setText ("0"); QString strStats = ""; ui->TEMintStatus->setPlainText(strStatsHeader); for (CZerocoinMint mint : vMints) { boost::this_thread::sleep(boost::posix_time::milliseconds(100)); strStats = strStats + QString::number(mint.GetDenomination()) + " "; ui->TEMintStatus->setPlainText(strStatsHeader + strStats); ui->TEMintStatus->repaint (); } // Available balance isn't always updated, so force it. setBalance(walletModel->getBalance(), walletModel->getUnconfirmedBalance(), walletModel->getImmatureBalance(), walletModel->getZerocoinBalance(), walletModel->getUnconfirmedZerocoinBalance(), walletModel->getImmatureZerocoinBalance(), walletModel->getWatchBalance(), walletModel->getWatchUnconfirmedBalance(), walletModel->getWatchImmatureBalance()); coinControlUpdateLabels(); return; } void PrivacyDialog::on_pushButtonMintReset_clicked() { if (!walletModel || !walletModel->getOptionsModel()) return; ui->TEMintStatus->setPlainText(tr("Starting ResetMintZerocoin: rescanning complete blockchain, this will need up to 30 minutes depending on your hardware. \nPlease be patient...")); ui->TEMintStatus->repaint (); int64_t nTime = GetTimeMillis(); string strResetMintResult = pwalletMain->ResetMintZerocoin(false); // do not do the extended search from GUI double fDuration = (double)(GetTimeMillis() - nTime)/1000.0; ui->TEMintStatus->setPlainText(QString::fromStdString(strResetMintResult) + tr("Duration: ") + QString::number(fDuration) + tr(" sec.\n")); ui->TEMintStatus->repaint (); return; } void PrivacyDialog::on_pushButtonSpentReset_clicked() { if (!walletModel || !walletModel->getOptionsModel()) return; ui->TEMintStatus->setPlainText(tr("Starting ResetSpentZerocoin: ")); ui->TEMintStatus->repaint (); int64_t nTime = GetTimeMillis(); string strResetSpentResult = pwalletMain->ResetSpentZerocoin(); double fDuration = (double)(GetTimeMillis() - nTime)/1000.0; ui->TEMintStatus->setPlainText(QString::fromStdString(strResetSpentResult) + tr("Duration: ") + QString::number(fDuration) + tr(" sec.\n")); ui->TEMintStatus->repaint (); return; } void PrivacyDialog::on_pushButtonSpendzACRE_clicked() { if (!walletModel || !walletModel->getOptionsModel() || !pwalletMain) return; if(GetAdjustedTime() > GetSporkValue(SPORK_16_ZEROCOIN_MAINTENANCE_MODE)) { QMessageBox::information(this, tr("Mint Zerocoin"), tr("zACRE is currently undergoing maintenance."), QMessageBox::Ok, QMessageBox::Ok); return; } // Request unlock if wallet was locked or unlocked for mixing: WalletModel::EncryptionStatus encStatus = walletModel->getEncryptionStatus(); if (encStatus == walletModel->Locked || encStatus == walletModel->UnlockedForAnonymizationOnly) { WalletModel::UnlockContext ctx(walletModel->requestUnlock(true)); if (!ctx.isValid()) { // Unlock wallet was cancelled return; } // Wallet is unlocked now, sedn zACRE sendzACRE(); return; } // Wallet already unlocked or not encrypted at all, send zACRE sendzACRE(); } void PrivacyDialog::on_pushButtonZCivControl_clicked() { ZCivControlDialog* zCivControl = new ZCivControlDialog(this); zCivControl->setModel(walletModel); zCivControl->exec(); } void PrivacyDialog::setZCivControlLabels(int64_t nAmount, int nQuantity) { ui->labelzCivSelected_int->setText(QString::number(nAmount)); ui->labelQuantitySelected_int->setText(QString::number(nQuantity)); } static inline int64_t roundint64(double d) { return (int64_t)(d > 0 ? d + 0.5 : d - 0.5); } void PrivacyDialog::sendzACRE() { QSettings settings; // Handle 'Pay To' address options CBitcoinAddress address(ui->payTo->text().toStdString()); if(ui->payTo->text().isEmpty()){ QMessageBox::information(this, tr("Spend Zerocoin"), tr("No 'Pay To' address provided, creating local payment"), QMessageBox::Ok, QMessageBox::Ok); } else{ if (!address.IsValid()) { QMessageBox::warning(this, tr("Spend Zerocoin"), tr("Invalid Acre Address"), QMessageBox::Ok, QMessageBox::Ok); ui->payTo->setFocus(); return; } } // Double is allowed now double dAmount = ui->zACREpayAmount->text().toDouble(); CAmount nAmount = roundint64(dAmount* COIN); // Check amount validity if (!MoneyRange(nAmount) || nAmount <= 0.0) { QMessageBox::warning(this, tr("Spend Zerocoin"), tr("Invalid Send Amount"), QMessageBox::Ok, QMessageBox::Ok); ui->zACREpayAmount->setFocus(); return; } // Convert change to zACRE bool fMintChange = ui->checkBoxMintChange->isChecked(); // Persist minimize change setting fMinimizeChange = ui->checkBoxMinimizeChange->isChecked(); settings.setValue("fMinimizeChange", fMinimizeChange); // Warn for additional fees if amount is not an integer and change as zACRE is requested bool fWholeNumber = floor(dAmount) == dAmount; double dzFee = 0.0; if(!fWholeNumber) dzFee = 1.0 - (dAmount - floor(dAmount)); if(!fWholeNumber && fMintChange){ QString strFeeWarning = "You've entered an amount with fractional digits and want the change to be converted to Zerocoin.<br /><br /><b>"; strFeeWarning += QString::number(dzFee, 'f', 8) + " ACRE </b>will be added to the standard transaction fees!<br />"; QMessageBox::StandardButton retval = QMessageBox::question(this, tr("Confirm additional Fees"), strFeeWarning, QMessageBox::Yes | QMessageBox::Cancel, QMessageBox::Cancel); if (retval != QMessageBox::Yes) { // Sending canceled ui->zACREpayAmount->setFocus(); return; } } // Persist Security Level for next start nSecurityLevel = ui->securityLevel->value(); settings.setValue("nSecurityLevel", nSecurityLevel); // Spend confirmation message box // Add address info if available QString strAddressLabel = ""; if(!ui->payTo->text().isEmpty() && !ui->addAsLabel->text().isEmpty()){ strAddressLabel = "<br />(" + ui->addAsLabel->text() + ") "; } // General info QString strQuestionString = tr("Are you sure you want to send?<br /><br />"); QString strAmount = "<b>" + QString::number(dAmount, 'f', 8) + " zACRE</b>"; QString strAddress = tr(" to address ") + QString::fromStdString(address.ToString()) + strAddressLabel + " <br />"; if(ui->payTo->text().isEmpty()){ // No address provided => send to local address strAddress = tr(" to a newly generated (unused and therefore anonymous) local address <br />"); } QString strSecurityLevel = tr("with Security Level ") + ui->securityLevel->text() + " ?"; strQuestionString += strAmount + strAddress + strSecurityLevel; // Display message box QMessageBox::StandardButton retval = QMessageBox::question(this, tr("Confirm send coins"), strQuestionString, QMessageBox::Yes | QMessageBox::Cancel, QMessageBox::Cancel); if (retval != QMessageBox::Yes) { // Sending canceled return; } int64_t nTime = GetTimeMillis(); ui->TEMintStatus->setPlainText(tr("Spending Zerocoin.\nComputationally expensive, might need several minutes depending on the selected Security Level and your hardware. \nPlease be patient...")); ui->TEMintStatus->repaint(); // use mints from zCiv selector if applicable vector<CZerocoinMint> vMintsSelected; if (!ZCivControlDialog::listSelectedMints.empty()) { vMintsSelected = ZCivControlDialog::GetSelectedMints(); } // Spend zACRE CWalletTx wtxNew; CZerocoinSpendReceipt receipt; bool fSuccess = false; if(ui->payTo->text().isEmpty()){ // Spend to newly generated local address fSuccess = pwalletMain->SpendZerocoin(nAmount, nSecurityLevel, wtxNew, receipt, vMintsSelected, fMintChange, fMinimizeChange); } else { // Spend to supplied destination address fSuccess = pwalletMain->SpendZerocoin(nAmount, nSecurityLevel, wtxNew, receipt, vMintsSelected, fMintChange, fMinimizeChange, &address); } // Display errors during spend if (!fSuccess) { int nNeededSpends = receipt.GetNeededSpends(); // Number of spends we would need for this transaction const int nMaxSpends = Params().Zerocoin_MaxSpendsPerTransaction(); // Maximum possible spends for one zACRE transaction if (nNeededSpends > nMaxSpends) { QString strStatusMessage = tr("Too much inputs (") + QString::number(nNeededSpends, 10) + tr(") needed. \nMaximum allowed: ") + QString::number(nMaxSpends, 10); strStatusMessage += tr("\nEither mint higher denominations (so fewer inputs are needed) or reduce the amount to spend."); QMessageBox::warning(this, tr("Spend Zerocoin"), strStatusMessage.toStdString().c_str(), QMessageBox::Ok, QMessageBox::Ok); ui->TEMintStatus->setPlainText(tr("Spend Zerocoin failed with status = ") +QString::number(receipt.GetStatus(), 10) + "\n" + "Message: " + QString::fromStdString(strStatusMessage.toStdString())); } else { QMessageBox::warning(this, tr("Spend Zerocoin"), receipt.GetStatusMessage().c_str(), QMessageBox::Ok, QMessageBox::Ok); ui->TEMintStatus->setPlainText(tr("Spend Zerocoin failed with status = ") +QString::number(receipt.GetStatus(), 10) + "\n" + "Message: " + QString::fromStdString(receipt.GetStatusMessage())); } ui->zACREpayAmount->setFocus(); ui->TEMintStatus->repaint(); return; } // Clear zciv selector in case it was used ZCivControlDialog::listSelectedMints.clear(); // Some statistics for entertainment QString strStats = ""; CAmount nValueIn = 0; int nCount = 0; for (CZerocoinSpend spend : receipt.GetSpends()) { strStats += tr("zCiv Spend #: ") + QString::number(nCount) + ", "; strStats += tr("denomination: ") + QString::number(spend.GetDenomination()) + ", "; strStats += tr("serial: ") + spend.GetSerial().ToString().c_str() + "\n"; strStats += tr("Spend is 1 of : ") + QString::number(spend.GetMintCount()) + " mints in the accumulator\n"; nValueIn += libzerocoin::ZerocoinDenominationToAmount(spend.GetDenomination()); } CAmount nValueOut = 0; for (const CTxOut& txout: wtxNew.vout) { strStats += tr("value out: ") + FormatMoney(txout.nValue).c_str() + " Civ, "; nValueOut += txout.nValue; strStats += tr("address: "); CTxDestination dest; if(txout.scriptPubKey.IsZerocoinMint()) strStats += tr("zCiv Mint"); else if(ExtractDestination(txout.scriptPubKey, dest)) strStats += tr(CBitcoinAddress(dest).ToString().c_str()); strStats += "\n"; } double fDuration = (double)(GetTimeMillis() - nTime)/1000.0; strStats += tr("Duration: ") + QString::number(fDuration) + tr(" sec.\n"); strStats += tr("Sending successful, return code: ") + QString::number(receipt.GetStatus()) + "\n"; QString strReturn; strReturn += tr("txid: ") + wtxNew.GetHash().ToString().c_str() + "\n"; strReturn += tr("fee: ") + QString::fromStdString(FormatMoney(nValueIn-nValueOut)) + "\n"; strReturn += strStats; // Clear amount to avoid double spending when accidentally clicking twice ui->zACREpayAmount->setText ("0"); ui->TEMintStatus->setPlainText(strReturn); ui->TEMintStatus->repaint(); } void PrivacyDialog::on_payTo_textChanged(const QString& address) { updateLabel(address); } // Coin Control: copy label "Quantity" to clipboard void PrivacyDialog::coinControlClipboardQuantity() { GUIUtil::setClipboard(ui->labelCoinControlQuantity->text()); } // Coin Control: copy label "Amount" to clipboard void PrivacyDialog::coinControlClipboardAmount() { GUIUtil::setClipboard(ui->labelCoinControlAmount->text().left(ui->labelCoinControlAmount->text().indexOf(" "))); } // Coin Control: button inputs -> show actual coin control dialog void PrivacyDialog::coinControlButtonClicked() { CoinControlDialog dlg; dlg.setModel(walletModel); dlg.exec(); coinControlUpdateLabels(); } // Coin Control: update labels void PrivacyDialog::coinControlUpdateLabels() { if (!walletModel || !walletModel->getOptionsModel() || !walletModel->getOptionsModel()->getCoinControlFeatures()) return; // set pay amounts CoinControlDialog::payAmounts.clear(); if (CoinControlDialog::coinControl->HasSelected()) { // Actual coin control calculation CoinControlDialog::updateLabels(walletModel, this); } else { ui->labelCoinControlQuantity->setText (tr("Coins automatically selected")); ui->labelCoinControlAmount->setText (tr("Coins automatically selected")); } } bool PrivacyDialog::updateLabel(const QString& address) { if (!walletModel) return false; // Fill in label from address book, if address has an associated label QString associatedLabel = walletModel->getAddressTableModel()->labelForAddress(address); if (!associatedLabel.isEmpty()) { ui->addAsLabel->setText(associatedLabel); return true; } return false; } void PrivacyDialog::setBalance(const CAmount& balance, const CAmount& unconfirmedBalance, const CAmount& immatureBalance, const CAmount& zerocoinBalance, const CAmount& unconfirmedZerocoinBalance, const CAmount& immatureZerocoinBalance, const CAmount& watchOnlyBalance, const CAmount& watchUnconfBalance, const CAmount& watchImmatureBalance) { currentBalance = balance; currentUnconfirmedBalance = unconfirmedBalance; currentImmatureBalance = immatureBalance; currentZerocoinBalance = zerocoinBalance; currentUnconfirmedZerocoinBalance = unconfirmedZerocoinBalance; currentImmatureZerocoinBalance = immatureZerocoinBalance; currentWatchOnlyBalance = watchOnlyBalance; currentWatchUnconfBalance = watchUnconfBalance; currentWatchImmatureBalance = watchImmatureBalance; CWalletDB walletdb(pwalletMain->strWalletFile); list<CZerocoinMint> listMints = walletdb.ListMintedCoins(true, false, true); std::map<libzerocoin::CoinDenomination, CAmount> mapDenomBalances; std::map<libzerocoin::CoinDenomination, int> mapUnconfirmed; std::map<libzerocoin::CoinDenomination, int> mapImmature; for (const auto& denom : libzerocoin::zerocoinDenomList){ mapDenomBalances.insert(make_pair(denom, 0)); mapUnconfirmed.insert(make_pair(denom, 0)); mapImmature.insert(make_pair(denom, 0)); } int nBestHeight = chainActive.Height(); for (auto& mint : listMints){ // All denominations mapDenomBalances.at(mint.GetDenomination())++; if (!mint.GetHeight() || chainActive.Height() - mint.GetHeight() <= Params().Zerocoin_MintRequiredConfirmations()) { // All unconfirmed denominations mapUnconfirmed.at(mint.GetDenomination())++; } else { // After a denomination is confirmed it might still be immature because < 1 of the same denomination were minted after it CBlockIndex *pindex = chainActive[mint.GetHeight() + 1]; int nHeight2CheckpointsDeep = nBestHeight - (nBestHeight % 10) - 20; int nMintsAdded = 0; while (pindex->nHeight < nHeight2CheckpointsDeep) { //at least 2 checkpoints from the top block nMintsAdded += count(pindex->vMintDenominationsInBlock.begin(), pindex->vMintDenominationsInBlock.end(), mint.GetDenomination()); if (nMintsAdded >= Params().Zerocoin_RequiredAccumulation()) break; pindex = chainActive[pindex->nHeight + 1]; } if (nMintsAdded < Params().Zerocoin_RequiredAccumulation()){ // Immature denominations mapImmature.at(mint.GetDenomination())++; } } } int64_t nCoins = 0; int64_t nSumPerCoin = 0; int64_t nUnconfirmed = 0; int64_t nImmature = 0; QString strDenomStats, strUnconfirmed = ""; for (const auto& denom : libzerocoin::zerocoinDenomList) { nCoins = libzerocoin::ZerocoinDenominationToInt(denom); nSumPerCoin = nCoins * mapDenomBalances.at(denom); nUnconfirmed = mapUnconfirmed.at(denom); nImmature = mapImmature.at(denom); strUnconfirmed = ""; if (nUnconfirmed) { strUnconfirmed += QString::number(nUnconfirmed) + QString(" unconf. "); } if(nImmature) { strUnconfirmed += QString::number(nImmature) + QString(" immature "); } if(nImmature || nUnconfirmed) { strUnconfirmed = QString("( ") + strUnconfirmed + QString(") "); } strDenomStats = strUnconfirmed + QString::number(mapDenomBalances.at(denom)) + " x " + QString::number(nCoins) + " = <b>" + QString::number(nSumPerCoin) + " zACRE </b>"; switch (nCoins) { case libzerocoin::CoinDenomination::ZQ_ONE: ui->labelzDenom1Amount->setText(strDenomStats); break; case libzerocoin::CoinDenomination::ZQ_FIVE: ui->labelzDenom2Amount->setText(strDenomStats); break; case libzerocoin::CoinDenomination::ZQ_TEN: ui->labelzDenom3Amount->setText(strDenomStats); break; case libzerocoin::CoinDenomination::ZQ_FIFTY: ui->labelzDenom4Amount->setText(strDenomStats); break; case libzerocoin::CoinDenomination::ZQ_ONE_HUNDRED: ui->labelzDenom5Amount->setText(strDenomStats); break; case libzerocoin::CoinDenomination::ZQ_FIVE_HUNDRED: ui->labelzDenom6Amount->setText(strDenomStats); break; case libzerocoin::CoinDenomination::ZQ_ONE_THOUSAND: ui->labelzDenom7Amount->setText(strDenomStats); break; case libzerocoin::CoinDenomination::ZQ_FIVE_THOUSAND: ui->labelzDenom8Amount->setText(strDenomStats); break; default: // Error Case: don't update display break; } } CAmount matureZerocoinBalance = zerocoinBalance - immatureZerocoinBalance; CAmount nLockedBalance = 0; if (walletModel) { nLockedBalance = walletModel->getLockedBalance(); } ui->labelzAvailableAmount->setText(QString::number(zerocoinBalance/COIN) + QString(" zACRE ")); ui->labelzAvailableAmount_2->setText(QString::number(matureZerocoinBalance/COIN) + QString(" zACRE ")); ui->labelzACREAmountValue->setText(BitcoinUnits::floorHtmlWithUnit(nDisplayUnit, balance - immatureBalance - nLockedBalance, false, BitcoinUnits::separatorAlways)); } void PrivacyDialog::updateDisplayUnit() { if (walletModel && walletModel->getOptionsModel()) { nDisplayUnit = walletModel->getOptionsModel()->getDisplayUnit(); if (currentBalance != -1) setBalance(currentBalance, currentUnconfirmedBalance, currentImmatureBalance, currentZerocoinBalance, currentUnconfirmedZerocoinBalance, currentImmatureZerocoinBalance, currentWatchOnlyBalance, currentWatchUnconfBalance, currentWatchImmatureBalance); } } void PrivacyDialog::showOutOfSyncWarning(bool fShow) { ui->labelzACRESyncStatus->setVisible(fShow); } void PrivacyDialog::keyPressEvent(QKeyEvent* event) { if (event->key() != Qt::Key_Escape) // press esc -> ignore { this->QDialog::keyPressEvent(event); } else { event->ignore(); } }
[ "root@vultr.guest" ]
root@vultr.guest
f50bca1fee08ce6fc2eee1d35a664b8b63406682
a39da85f9c1abe0c21673cd0777f2ba6188d75ce
/Client/Client/Client.cpp
bf23e9056f21d84765e73ab13342f5355a34e101
[]
no_license
AndrewSavchuk1410/ServerTranslatorPrototype
ec4d84bd1ee8ea578ab193fc94151920f77ed4e5
8f859365f0e363c9f1cdf59ed236174f4c53aee7
refs/heads/master
2023-01-24T12:08:35.188481
2020-12-03T18:38:56
2020-12-03T18:38:56
318,287,067
0
0
null
null
null
null
UTF-8
C++
false
false
1,173
cpp
#pragma comment (lib, "ws2_32.lib") #include <WinSock2.h> #include <iostream> #pragma warning(disable: 4996) int main(int argc, char* argv[]) { setlocale(LC_ALL, "Ukrainian"); WSADATA wsaData; WORD DLLVersion = MAKEWORD(2, 1); if (WSAStartup(DLLVersion, &wsaData) != 0) { std::cout << "Error" << std::endl; exit(1); } SOCKADDR_IN addr; int sizeofaddr = sizeof(addr); addr.sin_addr.s_addr = inet_addr("127.0.0.1"); addr.sin_port = htons(1487); addr.sin_family = AF_INET; SOCKET Connection = socket(AF_INET, SOCK_STREAM, NULL); if (connect(Connection, (SOCKADDR*)&addr, sizeof(addr)) != 0) { std::cout << "Error: failed connect to server.\n"; return 1; } std::cout << "Connected!\n"; while (true) { //std::string word; std::cout << "Enter the word in English: "; //std::cin >> word; char msg[256]; std::cin >> msg; //for (int i = 0; i < word.length(); i++) { // msg[i] = word[i]; //} char res[256]; send(Connection, msg, sizeof(msg), NULL); recv(Connection, res, sizeof(res), NULL); std::cout << "Слово " << msg << ' ' << "перекладється, як: " << res << '\n'; } system("pause"); return 0; }
[ "48767019+AndrewSavchuk1410@users.noreply.github.com" ]
48767019+AndrewSavchuk1410@users.noreply.github.com
aef07905830e29af2c7e6550a0e2cfdfdd56aad8
d86aedd0eb141b8d5fbaf30f41425ff97c17d6f4
/src/utiltime.h
96332926f2a3aaaf50ba2779cd7d0855dc2a6d50
[ "MIT" ]
permissive
catscoinofficial/src
277f6d4458e8ee3332ea415e0ed8b5253d22071b
eb9053362c3e9c90fe2cac09a65fad7d64d5f417
refs/heads/master
2023-02-28T10:39:10.685012
2021-02-07T10:54:28
2021-02-07T10:54:28
336,761,478
0
2
null
null
null
null
UTF-8
C++
false
false
666
h
// Copyright (c) 2009-2010 Satoshi Nakamoto // Copyright (c) 2009-2014 The Bitcoin developers // Copyright (c) 2016-2017 The CATSCOIN developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #ifndef BITCOIN_UTILTIME_H #define BITCOIN_UTILTIME_H #include <stdint.h> #include <string> int64_t GetTime(); int64_t GetTimeMillis(); int64_t GetTimeMicros(); void SetMockTime(int64_t nMockTimeIn); void MilliSleep(int64_t n); std::string DateTimeStrFormat(const char* pszFormat, int64_t nTime); std::string DurationToDHMS(int64_t nDurationTime); #endif // BITCOIN_UTILTIME_H
[ "64649630+catscoinofficial@users.noreply.github.com" ]
64649630+catscoinofficial@users.noreply.github.com
1d8e4feaeaf84034162c44d42bc2d8cc0a3684d4
bdda98f269400b13dfb277d52da4cb234fd4305c
/CVGCom/Units/Devices/dev_CVGx48.cpp
d87e2b2b5837aa06555dd2f308aa7db09d1bd47c
[]
no_license
fangxuetian/sources_old
75883b556c2428142e3323e676bea46a1191c775
7b1b0f585c688cb89bd4a23d46067f1dca2a17b2
refs/heads/master
2021-05-11T01:26:02.180353
2012-09-05T20:20:16
2012-09-05T20:20:16
null
0
0
null
null
null
null
WINDOWS-1251
C++
false
false
4,528
cpp
//=========================================================================== #include "pmPCH.h" #pragma hdrstop //=========================================================================== #include "dev_CVGx48.h" //=========================================================================== CCVGx48::CCVGx48() { // ----- Частоты на которых работаем в непрерывном режиме выдачи информации ------ SamplingFreqsRate.Clear( ); SamplingFreqsRate.Add( 1); SamplingFreqsRate.Add( 5); SamplingFreqsRate.Add( 10); SamplingFreqsRate.Add( 20); SamplingFreqsRate.Add( 50); SamplingFreqsRate.Add(100); SamplingFreqsRate.Add(200); SerialPort->BaudRate = 115200; SerialPort->ByteSize = 8; ExtendedParamCount = 0; ExtendedParamValues[0] = 200; ExtendedParamNames[0] = strdup("UART_Frequncy:"); ExtendedParamValues[2] = 48; //ExtendedParamValues[2] = 64; Parent_ThreadType = 1; // -------- LoadFromRegistry("CVGx48"); } //=========================================================================== CCVGx48::~CCVGx48() { SaveDataToRegistry("CVGx48"); } //=========================================================================== int CCVGx48::Start() { // ---------- SaveDataToRegistry("CVGx48"); // ---------- UART_Frequency = ExtendedParamValues[0]; PackedLength = ExtendedParamValues[2]; InfoPackedLength = ExtendedParamValues[2]; SummationCount = UART_Frequency / SamplingFreq; if ( SummationCount < 1 ) SummationCount = 1; SummationCount_invert = 1.0 / (double)SummationCount; CurrentSummationPoint = 0; Storage->file_Param.StorageT0[0] = SummationCount / (double) UART_Frequency; // ---- Сэтапю каналы ---- CountUARTValues = 11; Storage->SetItemsCount(CountUARTValues + 0); //Storage->SetItemsCount(11); Storage->Items[ 0]->SetName("GyroOut"); Storage->Items[ 1]->SetName("Temperature"); Storage->Items[ 2]->SetName("AntiNodePeriod"); Storage->Items[ 3]->SetName("ExcitationDelay"); Storage->Items[ 4]->SetName("AntiNodeAmplitude"); Storage->Items[ 5]->SetName("ExcitationAmpl"); Storage->Items[ 6]->SetName("QuadratureAmpl"); Storage->Items[ 7]->SetName("QuadratureError"); Storage->Items[ 8]->SetName("CoriolisError"); Storage->Items[ 9]->SetName("NodeAmplitude"); Storage->Items[10]->SetName("GyroOut_RAW"); memset(fSliderBuffer, 0, sizeof(fSliderBuffer)); SliderArraySize = 120 * SamplingFreq; isSliderBufferInited = false; // ------------- if ( CBaseDevice::Start() == -1 ) return -1; if( OpenDataSaveFile( &h_file[0], Storage ) == -1 ) return -2; // ----- return 0; } //=========================================================================== void CCVGx48::Stop() { CBaseDevice::Stop(); } //=========================================================================== void CCVGx48::DeCompositeData() { // ---- в ---- gd->LastGoodReadValue[i] --- Находяться последние прочитанные данные с пакета ---- // ---- в ---- gd->SumValues [i] --- Находиться сумма на временном пакете ---- // ---- в ---- CountSumPoint --- Находиться количкство сумм ---- if ( Storage->Items[0]->ValuesCount >= SliderArraySize && isSliderBufferInited == false ) { if ( h_file[0] != NULL) fclose( h_file[0] ); h_file[0] = NULL; OpenDataSaveFile( &h_file[0], Storage ); Sleep(300); isSliderBufferInited = true; for (int i = 0; i < Storage->ItemsCount; i++) Storage->Items[i]->Clear(); } // ------- for (int i = 0; i < Storage->ItemsCount; i++) { memmove(&fSliderBuffer[i][1], &fSliderBuffer[i][0], SliderArraySize*sizeof(double)); fSliderBuffer[i][0] = ParentSummValues[i] / float(SummationCount); if ( isSliderBufferInited == true ) { double SumVal = 0; for ( int k = 0; k < SliderArraySize; k++) SumVal = SumVal + fSliderBuffer[i][k]; Storage->Items[i]->Add( SumVal / SliderArraySize ); } else Storage->Items[i]->Add(fSliderBuffer[i][0]); } }
[ "pm@pm.(none)" ]
pm@pm.(none)
dab6e471f3dc6a3d0fd52432a1c94d113f63333f
52a3c93c38bef127eaee4420f36a89d929a321c5
/SDK/SoT_BP_SmallShipNetProxy_classes.hpp
e394e766d8552097eb57e693973fc443d964f472
[]
no_license
RDTCREW/SoT-SDK_2_0_7_reserv
8e921275508d09e5f81b10f9a43e47597223cb35
db6a5fc4cdb9348ddfda88121ebe809047aa404a
refs/heads/master
2020-07-24T17:18:40.537329
2019-09-11T18:53:58
2019-09-11T18:53:58
207,991,316
0
0
null
null
null
null
UTF-8
C++
false
false
1,493
hpp
#pragma once // Sea of Thieves (2.0) SDK #ifdef _MSC_VER #pragma pack(push, 0x8) #endif #include "SoT_BP_SmallShipNetProxy_structs.hpp" namespace SDK { //--------------------------------------------------------------------------- //Classes //--------------------------------------------------------------------------- // BlueprintGeneratedClass BP_SmallShipNetProxy.BP_SmallShipNetProxy_C // 0x0018 (0x0538 - 0x0520) class ABP_SmallShipNetProxy_C : public AShipNetProxy { public: struct FPointerToUberGraphFrame UberGraphFrame; // 0x0520(0x0008) (ZeroConstructor, Transient, DuplicateTransient) TArray<class UMaterialInstanceDynamic*> Dynamic_Materials; // 0x0528(0x0010) (Edit, BlueprintVisible, ZeroConstructor) static UClass* StaticClass() { static auto ptr = UObject::FindObject<UClass>(_xor_("BlueprintGeneratedClass BP_SmallShipNetProxy.BP_SmallShipNetProxy_C")); return ptr; } void Set_Colour_on_All_Materials(const struct FName& ParameterName, const struct FLinearColor& Value); void Set_Value_on_All_Materials(const struct FName& Variable_Name, float Value); void Apply_Bits_to_Lanterns(int Bits); void Create_Dynamic_Materials(); void UserConstructionScript(); void ReceiveBeginPlay(); void OnLanternStateChanged(int LanternStateBits); void ExecuteUbergraph_BP_SmallShipNetProxy(int EntryPoint); }; } #ifdef _MSC_VER #pragma pack(pop) #endif
[ "igromanru@yahoo.de" ]
igromanru@yahoo.de
4956cec3c49e64d7e64efe25f84a62e1cbaea5cc
e1e43f3e90aa96d758be7b7a8356413a61a2716f
/datacommsserver/esockserver/test/TE_ESock/EsockTestSection1.cpp
127f5edfdade5df4f41368d9a6a63c9107cd6ce6
[]
no_license
SymbianSource/oss.FCL.sf.os.commsfw
76b450b5f52119f6bf23ae8a5974c9a09018fdfa
bc8ac1a6d5273cbfa7852bbb8ce27d6ddc076984
refs/heads/master
2021-01-18T23:55:06.285537
2010-10-03T23:21:43
2010-10-03T23:21:43
72,773,202
0
1
null
null
null
null
UTF-8
C++
false
false
13,403
cpp
// Copyright (c) 2001-2009 Nokia Corporation and/or its subsidiary(-ies). // All rights reserved. // This component and the accompanying materials are made available // under the terms of "Eclipse Public License v1.0" // which accompanies this distribution, and is available // at the URL "http://www.eclipse.org/legal/epl-v10.html". // // Initial Contributors: // Nokia Corporation - initial contribution. // // Contributors: // // Description: // This contains ESock Test cases from section 1 // // // EPOC includes #include <e32base.h> #include <in_sock.h> // Test system includes #include "EsockTestSection1.h" // Test step 1.1 const TDesC& CEsockTest1_1::GetTestName() { // store the name of this test case _LIT(ret,"Test1.1"); return ret; } CEsockTest1_1::~CEsockTest1_1() { } enum TVerdict CEsockTest1_1::easyTestStepL() { // get number of sockets from script TInt nSockets; // number of sockets to open TESTL(GetIntFromConfig(SectionName(_L("Test_1.1")), _L("numSockets"), nSockets)); Logger().WriteFormat(_L("Open %d blank socket(s)"), nSockets); TInt ret = OpenSockets(nSockets); TESTEL(KErrNone == ret, ret); return EPass; } // Test step 1.2 const TDesC& CEsockTest1_2::GetTestName() { // store the name of this test case _LIT(ret,"Test1.2"); return ret; } CEsockTest1_2::~CEsockTest1_2() { } enum TVerdict CEsockTest1_2::easyTestStepL() { // get number of sockets from script TInt nSockets; // number of sockets to open TESTL(GetIntFromConfig(SectionName(_L("Test_1.2")), _L("numSockets"), nSockets)); Logger().WriteFormat(_L("Open %d TCP socket(s)"), nSockets); TInt ret = OpenSockets(KAfInet, KSockStream, KProtocolInetTcp, nSockets); TESTEL(KErrNone == ret, ret); TInetAddr addr; TBuf<32> buf; for (TInt i = 0; i < nSockets; i++) { // Get local address of the socket (Empty) (iEsockSuite->GetSocketHandle(i + 1)).LocalName(addr); // Check length of buffer, should be set to (Zero) addr.OutputWithScope(buf); TESTL(buf.Length() == 0); } return EPass; } // Test step 1.3 const TDesC& CEsockTest1_3::GetTestName() { // store the name of this test case _LIT(ret,"Test1.3"); return ret; } CEsockTest1_3::~CEsockTest1_3() { } enum TVerdict CEsockTest1_3::easyTestStepL() { // get number of sockets from script TInt nSockets; // number of sockets to open TESTL(GetIntFromConfig(SectionName(_L("Test_1.3")), _L("numSockets"), nSockets)); Logger().WriteFormat(_L("Open %d UDP socket(s)"), nSockets); TInt ret = OpenSockets(KAfInet, KSockDatagram, KProtocolInetUdp, nSockets); TESTEL(KErrNone == ret, ret); TInetAddr addr; TBuf<39> buf; for (TInt i = 0; i < nSockets; i++) { // Get local address of the socket (Empty) (iEsockSuite->GetSocketHandle(i + 1)).LocalName(addr); // Check length of buffer, should be set to (Zero) addr.OutputWithScope(buf); TESTL(buf.Length() == 0); } return EPass; } // Test step 1.4 const TDesC& CEsockTest1_4::GetTestName() { // store the name of this test case _LIT(ret,"Test1.4"); return ret; } CEsockTest1_4::~CEsockTest1_4() { } enum TVerdict CEsockTest1_4::easyTestStepL() { // Open n ICMP sockets // get number of sockets from script TInt nSockets; // number of sockets to open TESTL(GetIntFromConfig(SectionName(_L("Test_1.4")), _L("numSockets"), nSockets)); Logger().WriteFormat(_L("Open %d ICMP socket(s)"), nSockets); TInt ret = OpenSockets(KAfInet, KSockDatagram, KProtocolInetIcmp, nSockets); TESTEL(KErrNone == ret, ret); TInetAddr addr; TBuf<32> buf; for (TInt i = 0; i < nSockets; i++) { // Get local address of the socket (Empty) iEsockSuite->GetSocketHandle(i + 1).LocalName(addr); // Check length of buffer, should be set to (Zero) addr.OutputWithScope(buf); TESTL(buf.Length() == KErrNone); } return EPass; } // Test step 1.5 const TDesC& CEsockTest1_5::GetTestName() { // store the name of this test case _LIT(ret,"Test1.5"); return ret; } CEsockTest1_5::~CEsockTest1_5() { } enum TVerdict CEsockTest1_5::easyTestStepL() { // Open n IP sockets // get number of sockets from script TInt nSockets; // number of sockets to open TESTL(GetIntFromConfig(SectionName(_L("Test_1.5")), _L("numSockets"), nSockets)); Logger().WriteFormat(_L("Open %d IP socket(s)"), nSockets); TInt ret = OpenSockets(KAfInet, KSockDatagram, KProtocolInetIp, nSockets); TESTEL(KErrNone == ret, ret); TInetAddr addr; TBuf<32> buf; for (TInt i = 0; i < nSockets; i++) { // Get local address of the socket (Empty) iEsockSuite->GetSocketHandle(i + 1).LocalName(addr); // Check length of buffer, should be set to (Zero) addr.OutputWithScope(buf); TESTL(buf.Length() == KErrNone); } return EPass; } // Test step 1.6 const TDesC& CEsockTest1_6::GetTestName() { // store the name of this test case _LIT(ret,"Test1.6"); return ret; } CEsockTest1_6::~CEsockTest1_6() { } enum TVerdict CEsockTest1_6::easyTestStepL() { // get number of sockets from script TInt nSockets; // number of sockets to open TESTL(GetIntFromConfig(SectionName(_L("Test_1.6")), _L("numSockets"), nSockets)); Logger().WriteFormat(_L("Open %d TCP socket(s) by name"), nSockets); TInt ret = OpenSockets(_L("tcp"), nSockets); TESTEL(KErrNone == ret, ret); TInetAddr addr; TBuf<32> buf; for (TInt i = 0; i < nSockets; i++) { // Get local address of the socket (Empty) iEsockSuite->GetSocketHandle(i + 1).LocalName(addr); // Check length of buffer, should be set to (Zero) addr.OutputWithScope(buf); TESTL(buf.Length() == KErrNone); } return EPass; } // Test step 1.7 const TDesC& CEsockTest1_7::GetTestName() { // store the name of this test case _LIT(ret,"Test1.7"); return ret; } CEsockTest1_7::~CEsockTest1_7() { } enum TVerdict CEsockTest1_7::easyTestStepL() { // get number of sockets from script TInt nSockets; // number of sockets to open TESTL(GetIntFromConfig(SectionName(_L("Test_1.7")), _L("numSockets"), nSockets)); Logger().WriteFormat(_L("Open %d UDP socket(s) by name"), nSockets); TInt ret = OpenSockets(_L("udp"), nSockets); TESTEL(KErrNone == ret, ret); TInetAddr addr; TBuf<32> buf; for (TInt i = 0; i < nSockets; i++) { // Get local address of the socket (Empty) iEsockSuite->GetSocketHandle(i + 1).LocalName(addr); // Check length of buffer, should be set to (Zero) addr.OutputWithScope(buf); TESTL(buf.Length() == KErrNone); } return EPass; } // Test step 1.8 const TDesC& CEsockTest1_8::GetTestName() { // store the name of this test case _LIT(ret,"Test1.8"); return ret; } CEsockTest1_8::~CEsockTest1_8() { } enum TVerdict CEsockTest1_8::easyTestStepL() { // get number of sockets from script TInt nSockets; // number of sockets to open TESTL(GetIntFromConfig(SectionName(_L("Test_1.8")), _L("numSockets"), nSockets)); Logger().WriteFormat(_L("Open %d ICMP socket(s) by name"), nSockets); TInt ret = OpenSockets(_L("icmp"), nSockets); TESTEL(KErrNone == ret, ret); TInetAddr addr; TBuf<32> buf; for (TInt i = 0; i < nSockets; i++) { // Get local address of the socket (Empty) iEsockSuite->GetSocketHandle(i + 1).LocalName(addr); // Check length of buffer, should be set to (Zero) addr.OutputWithScope(buf); TESTL(buf.Length() == 0); } return EPass; } // Test step 1.9 const TDesC& CEsockTest1_9::GetTestName() { // store the name of this test case _LIT(ret,"Test1.9"); return ret; } CEsockTest1_9::~CEsockTest1_9() { } enum TVerdict CEsockTest1_9::easyTestStepL() { // get number of sockets from script TInt nSockets; // number of sockets to open TESTL(GetIntFromConfig(SectionName(_L("Test_1.9")), _L("numSockets"), nSockets)); Logger().WriteFormat(_L("Open %d IP sockets by name"), nSockets); TInt ret = OpenSockets(_L("ip"), nSockets); TESTEL(KErrNone == ret, ret); TInetAddr addr; TBuf<32> buf; for (TInt i = 0; i < nSockets; i++) { // Get local address of the socket (Empty) iEsockSuite->GetSocketHandle(i + 1).LocalName(addr); // Check length of buffer, should be set to (Zero) addr.OutputWithScope(buf); TESTL(buf.Length() == KErrNone); } return EPass; } // Test step 1.10 const TDesC& CEsockTest1_10::GetTestName() { // store the name of this test case _LIT(ret,"Test1.10"); return ret; } CEsockTest1_10::~CEsockTest1_10() { } enum TVerdict CEsockTest1_10::easyTestStepL() { // Open a TCP socket with invalid socket type Logger().WriteFormat(_L("Open socket, of invalid type, for TCP")); RSocket sock; CleanupClosePushL(sock); TInt ret = sock.Open(iEsockSuite->iSocketServer, KAfInet, 0, KProtocolInetTcp); TESTEL(ret==KErrBadName, ret); // Open a UDP socket with invalid socket type Logger().WriteFormat(_L("Open socket, of invalid type, for UDP")); RSocket sock2; CleanupClosePushL(sock2); ret = sock2.Open(iEsockSuite->iSocketServer, KAfInet, 12, KProtocolInetUdp); TESTEL(ret==KErrBadName, ret); CleanupStack::PopAndDestroy(2, &sock); return EPass; } // Test step 1.11 const TDesC& CEsockTest1_11::GetTestName() { // store the name of this test case _LIT(ret,"Test1.11"); return ret; } CEsockTest1_11::~CEsockTest1_11() { } enum TVerdict CEsockTest1_11::easyTestStepL() { // open sockets with an invalid protocol // get protocol id's from script TInt protocol1, protocol2; TESTL(GetIntFromConfig(SectionName(_L("Test_1.11")), _L("protocolId1"), protocol1)); TESTL(GetIntFromConfig(SectionName(_L("Test_1.11")), _L("protocolId2"), protocol2)); Logger().WriteFormat(_L("Open stream socket for invalid protocol")); RSocket sock; CleanupClosePushL(sock); TInt ret = sock.Open(iEsockSuite->iSocketServer, KAfInet, KSockStream, protocol1); TESTEL(ret==KErrBadName, ret); Logger().WriteFormat(_L("Open datagram socket for invalid protocol")); RSocket sock2; CleanupClosePushL(sock2); ret = sock2.Open(iEsockSuite->iSocketServer, KAfInet, KSockDatagram, protocol2); TESTEL(ret==KErrBadName, ret); CleanupStack::PopAndDestroy(2, &sock); return EPass; } // Test step 1.12 const TDesC& CEsockTest1_12::GetTestName() { // store the name of this test case _LIT(ret,"Test1.12"); return ret; } CEsockTest1_12::~CEsockTest1_12() { } enum TVerdict CEsockTest1_12::easyTestStepL() { Logger().WriteFormat(_L("Open stream socket for UDP")); RSocket sock; CleanupClosePushL(sock); TInt ret = sock.Open(iEsockSuite->iSocketServer, KAfInet, KSockStream, KProtocolInetUdp); TESTEL(ret==KErrBadName, ret); CleanupStack::PopAndDestroy(); return EPass; } // Test step 1.13 const TDesC& CEsockTest1_13::GetTestName() { // store the name of this test case _LIT(ret,"Test1.13"); return ret; } CEsockTest1_13::~CEsockTest1_13() { } enum TVerdict CEsockTest1_13::easyTestStepL() { Logger().WriteFormat(_L("Open datagram socket for TCP")); RSocket sock; CleanupClosePushL(sock); TInt ret = sock.Open(iEsockSuite->iSocketServer, KAfInet, KSockDatagram, KProtocolInetTcp); TESTEL(ret==KErrBadName, ret); CleanupStack::PopAndDestroy(); return EPass; } // Test step 1.14 const TDesC& CEsockTest1_14::GetTestName() { // store the name of this test case _LIT(ret,"Test1.14"); return ret; } CEsockTest1_14::~CEsockTest1_14() { } enum TVerdict CEsockTest1_14::easyTestStepL() { Logger().WriteFormat(_L("Open socket for invalid protocol by name")); RSocket sock; CleanupClosePushL(sock); TInt ret =sock.Open(iEsockSuite->iSocketServer, _L("abc")); TESTEL(ret==KErrNotFound, ret); CleanupStack::PopAndDestroy(); return EPass; } // Test step 1.15 const TDesC& CEsockTest1_15::GetTestName() { // store the name of this test case _LIT(ret,"Test1.15"); return ret; } CEsockTest1_15::~CEsockTest1_15() { } enum TVerdict CEsockTest1_15::easyTestStepL() { CloseSockets(2); return EPass; } // Test step 1.16 const TDesC& CEsockTest1_16::GetTestName() { // store the name of this test case _LIT(ret,"Test1.16"); return ret; } CEsockTest1_16::~CEsockTest1_16() { } enum TVerdict CEsockTest1_16::easyTestStepPreambleL() { TInt ret = OpenSockets(KAfInet, KSockDatagram, KProtocolInetUdp); Logger().WriteFormat(_L("Open a UDP socket, returned %d"), ret); if (KErrNone != ret) { return EFail; } return EPass; } enum TVerdict CEsockTest1_16::easyTestStepL() { TESTL(EPass == TestStepResult()); if (iEsockSuite->GetSocketListCount() < 1) { return EInconclusive; } const TInt KBufferLength = 10; TBuf8<KBufferLength> buffer; buffer.SetMax(); buffer.FillZ(); TInetAddr destAddr; TRequestStatus status; Logger().WriteFormat(_L("Issuing 'SendTo' with invalid destination...")); iEsockSuite->GetSocketHandle(1).SendTo(buffer, destAddr, 0, status); User::WaitForRequest(status); Logger().WriteFormat(_L("...which returned %d\n"), status.Int()); // Should return '-2' TESTEL(status == KErrGeneral, EFail); // Test 1.15 Close socket return EPass; } // Test step 1.17 // Open a socket using the RawIp protocol const TDesC& CEsockTest1_17::GetTestName() { // store the name of this test case _LIT(ret, "Test1.17"); return ret; } CEsockTest1_17::~CEsockTest1_17() { } enum TVerdict CEsockTest1_17::easyTestStepL() { Logger().WriteFormat(_L("Open a RawIP socket")); _LIT(KRawIp, "rawip"); TInt ret = OpenSockets(KRawIp); TESTEL(ret == KErrNone, ret); return EPass; }
[ "kirill.dremov@nokia.com" ]
kirill.dremov@nokia.com
33408a23097072f760f0534104fa50728e5dd28e
92c0f53e43881f8c384ab344a44a16fd5eac54fd
/packetWin7/NPFInstall/NPFInstall/LoopbackRecord.cpp
7312c53f56fd6f755d5fb2f3200d6b91db1251f9
[ "LicenseRef-scancode-unknown-license-reference", "HPND", "BSD-4-Clause-UC", "BSD-3-Clause", "LicenseRef-scancode-warranty-disclaimer", "LicenseRef-scancode-carnegie-mellon", "BSD-4.3TAHOE", "BSD-2-Clause", "LicenseRef-scancode-bsd-new-tcpdump" ]
permissive
vaginessa/npcap
65301289cfb8c25872695824d90267392562e675
391e71e54f72aadd41f5556174c7324af0047c73
refs/heads/master
2021-01-18T08:51:30.985915
2016-06-04T18:26:14
2016-06-04T18:26:14
60,437,309
0
0
NOASSERTION
2019-01-18T08:41:12
2016-06-05T01:09:20
C
UTF-8
C++
false
false
7,092
cpp
/*++ Copyright (c) Nmap.org. All rights reserved. Module Name: LoopbackRecord.cpp Abstract: This is used for enumerating our "Npcap Loopback Adapter" using NetCfg API, if found, we changed its name from "Ethernet X" or "Local Network Area" to "Npcap Loopback Adapter". Also, we need to make a flag in registry to let the Npcap driver know that "this adapter is ours", so send the loopback traffic to it. --*/ #pragma warning(disable: 4311 4312) #include <Netcfgx.h> #include <iostream> #include <atlbase.h> // CComPtr #include <devguid.h> // GUID_DEVCLASS_NET, ... #include "LoopbackRecord.h" #include "LoopbackRename.h" #include "RegUtil.h" #define NPCAP_LOOPBACK_ADAPTER_NAME NPF_DRIVER_NAME_NORMAL_WIDECHAR L" Loopback Adapter" #define NPCAP_LOOPBACK_APP_NAME NPF_DRIVER_NAME_NORMAL_WIDECHAR L"_Loopback" int g_NpcapAdapterID = -1; // RAII helper class class COM { public: COM(); ~COM(); }; COM::COM() { HRESULT hr = CoInitializeEx(NULL, COINIT_MULTITHREADED); if(!SUCCEEDED(hr)) { _tprintf(_T("ERROR: CoInitializeEx() failed. Error code: 0x%08x\n"), hr); } } COM::~COM() { CoUninitialize(); } // RAII helper class class NetCfg { CComPtr<INetCfg> m_pINetCfg; CComPtr<INetCfgLock> m_pLock; public: NetCfg(); ~NetCfg(); // Displays all network adapters, clients, transport protocols and services. // For each client, transport protocol and service (network features) // shows adpater(s) they are bound to. BOOL GetNetworkConfiguration(); }; NetCfg::NetCfg() : m_pINetCfg(0) { HRESULT hr = S_OK; hr = m_pINetCfg.CoCreateInstance(CLSID_CNetCfg); if(!SUCCEEDED(hr)) { _tprintf(_T("ERROR: CoCreateInstance() failed. Error code: 0x%08x\n"), hr); throw 1; } hr = m_pINetCfg.QueryInterface(&m_pLock); if (!SUCCEEDED(hr)) { _tprintf(_T("QueryInterface(INetCfgLock) 0x%08x\n"), hr); throw 2; } // Note that this call can block. hr = m_pLock->AcquireWriteLock(INFINITE, NPCAP_LOOPBACK_APP_NAME, NULL); if (!SUCCEEDED(hr)) { _tprintf(_T("INetCfgLock::AcquireWriteLock 0x%08x\n"), hr); throw 3; } hr = m_pINetCfg->Initialize(NULL); if(!SUCCEEDED(hr)) { _tprintf(_T("ERROR: Initialize() failed. Error code: 0x%08x\n"), hr); throw 4; } } NetCfg::~NetCfg() { HRESULT hr = S_OK; if(m_pINetCfg) { hr = m_pINetCfg->Uninitialize(); if(!SUCCEEDED(hr)) { _tprintf(_T("ERROR: Uninitialize() failed. Error code: 0x%08x\n"), hr); } hr = m_pLock->ReleaseWriteLock(); if (!SUCCEEDED(hr)) { _tprintf(_T("INetCfgLock::ReleaseWriteLock 0x%08x\n"), hr); } } } BOOL EnumerateComponents(CComPtr<INetCfg>& pINetCfg, const GUID* pguidClass) { /* cout << "\n\nEnumerating " << GUID2Str(pguidClass) << " class:\n" << endl;*/ // IEnumNetCfgComponent provides methods that enumerate the INetCfgComponent interfaces // for network components of a particular type installed on the operating system. // Types of network components include network cards, protocols, services, and clients. CComPtr<IEnumNetCfgComponent> pIEnumNetCfgComponent; // get enumeration containing network components of the provided class (GUID) HRESULT hr = pINetCfg->EnumComponents(pguidClass, &pIEnumNetCfgComponent); if(!SUCCEEDED(hr)) { _tprintf(_T("ERROR: Failed to get IEnumNetCfgComponent interface pointer\n")); throw 1; } // INetCfgComponent interface provides methods that control and retrieve // information about a network component. CComPtr<INetCfgComponent> pINetCfgComponent; unsigned int nIndex = 1; BOOL bFound = FALSE; BOOL bFailed = FALSE; // retrieve the next specified number of INetCfgComponent interfaces in the enumeration sequence. while(pIEnumNetCfgComponent->Next(1, &pINetCfgComponent, 0) == S_OK) { /* cout << GUID2Desc(pguidClass) << " "<< nIndex++ << ":\n";*/ // LPWSTR pszDisplayName = NULL; // pINetCfgComponent->GetDisplayName(&pszDisplayName); // wcout << L"\tDisplay name: " << wstring(pszDisplayName) << L'\n'; // CoTaskMemFree(pszDisplayName); LPWSTR pszBindName = NULL; pINetCfgComponent->GetBindName(&pszBindName); // wcout << L"\tBind name: " << wstring(pszBindName) << L'\n'; // DWORD dwCharacteristics = 0; // pINetCfgComponent->GetCharacteristics(&dwCharacteristics); // cout << "\tCharacteristics: " << dwCharacteristics << '\n'; // // GUID guid; // pINetCfgComponent->GetClassGuid(&guid); // cout << "\tClass GUID: " << guid.Data1 << '-' << guid.Data2 << '-' // << guid.Data3 << '-' << (unsigned int) guid.Data4 << '\n'; // // ULONG ulDeviceStatus = 0; // pINetCfgComponent->GetDeviceStatus(&ulDeviceStatus); // cout << "\tDevice Status: " << ulDeviceStatus << '\n'; // // LPWSTR pszHelpText = NULL; // pINetCfgComponent->GetHelpText(&pszHelpText); // wcout << L"\tHelp Text: " << wstring(pszHelpText) << L'\n'; // CoTaskMemFree(pszHelpText); // // LPWSTR pszID = NULL; // pINetCfgComponent->GetId(&pszID); // wcout << L"\tID: " << wstring(pszID) << L'\n'; // CoTaskMemFree(pszID); // // pINetCfgComponent->GetInstanceGuid(&guid); // cout << "\tInstance GUID: " << guid.Data1 << '-' << guid.Data2 << '-' // << guid.Data3 << '-' << (unsigned int) guid.Data4 << '\n'; LPWSTR pszPndDevNodeId = NULL; pINetCfgComponent->GetPnpDevNodeId(&pszPndDevNodeId); // wcout << L"\tPNP Device Node ID: " << wstring(pszPndDevNodeId) << L'\n'; int iDevID = getIntDevID(pszPndDevNodeId); if (g_NpcapAdapterID == iDevID) { bFound = TRUE; hr = pINetCfgComponent->SetDisplayName(NPCAP_LOOPBACK_ADAPTER_NAME); if (hr != S_OK) { bFailed = TRUE; } if (!AddFlagToRegistry(pszBindName)) { bFailed = TRUE; } // if (!AddFlagToRegistry_Service(pszBindName)) // { // bFailed = TRUE; // } if (!RenameLoopbackNetwork(pszBindName)) { bFailed = TRUE; } } CoTaskMemFree(pszBindName); CoTaskMemFree(pszPndDevNodeId); pINetCfgComponent.Release(); if (bFound) { if (bFailed) { return FALSE; } else { return TRUE; } } } return FALSE; } BOOL NetCfg::GetNetworkConfiguration() { // get enumeration containing GUID_DEVCLASS_NET class of network components return EnumerateComponents(m_pINetCfg, &GUID_DEVCLASS_NET); } int getIntDevID(TCHAR strDevID[]) //DevID is in form like: "ROOT\\NET\\0008" { int iDevID; _stscanf_s(strDevID, _T("ROOT\\NET\\%04d"), &iDevID); return iDevID; } BOOL AddFlagToRegistry(tstring strDeviceName) { return WriteStrToRegistry(NPCAP_REG_KEY_NAME, NPCAP_REG_LOOPBACK_VALUE_NAME, tstring(_T("\\Device\\") + strDeviceName).c_str(), KEY_WRITE | KEY_WOW64_32KEY); } BOOL AddFlagToRegistry_Service(tstring strDeviceName) { return WriteStrToRegistry(NPCAP_SERVICE_REG_KEY_NAME, NPCAP_REG_LOOPBACK_VALUE_NAME, tstring(_T("\\Device\\") + strDeviceName).c_str(), KEY_WRITE); } BOOL RecordLoopbackDevice(int iNpcapAdapterID) { g_NpcapAdapterID = iNpcapAdapterID; try { COM com; NetCfg netCfg; if (!netCfg.GetNetworkConfiguration()) { return FALSE; } } catch(...) { _tprintf(_T("ERROR: main() caught exception\n")); return FALSE; } return TRUE; }
[ "hsluoyz@qq.com" ]
hsluoyz@qq.com
c90db25310eb3414b659e6dc8ada7ecdd37b32db
79546e9feb03644ba7b99e26e2cfb4e34341712a
/obj.cpp
2dc39df39032dd6646565cc9640d7d3e4cdaef6c
[]
no_license
kagasan/cg
f261a793e327cb263c5e135d678d274efaa320f8
64179c65e086f6184417bfb5b271cbfff7562bca
refs/heads/master
2020-03-11T03:01:27.305331
2018-04-17T04:34:23
2018-04-17T04:34:23
129,734,697
0
0
null
null
null
null
UTF-8
C++
false
false
607
cpp
#include "obj.h" #include <sstream> OBJ::OBJ(const std::string &filename){ read(filename); } void OBJ::read(const std::string &filename){ vertex.resize(1); face.clear(); ifs.open(filename); for (std::string line; getline(ifs, line);){ if (line[0] == '#')continue; else if (line[0] == 'v'){ std::stringstream ss; ss << line; char keyword; Point3d p; ss >> keyword >> p.x >> p.y >> p.z; vertex.push_back(p); } else if (line[0] == 'f'){ std::stringstream ss; ss << line; char keyword; Point3i p; ss >> keyword >> p.x >> p.y >> p.z; face.push_back(p); } } }
[ "ghghkaja@gmail.com" ]
ghghkaja@gmail.com
d1f913c328321f6f2d4f523934632f9ef08fd825
ba34acc11d45cf644d7ce462c5694ce9662c34c2
/Classes/gesture/PathWriter.h
119c62dbe67c0eae9f12e021b2242195a7a2810e
[]
no_license
mspenn/Sketch2D
acce625c4631313ba2ef47a5c8f8eadcd332719b
ae7d9f00814ac68fbd8e3fcb39dfac34edfc9883
refs/heads/master
2021-01-12T13:26:35.864853
2019-01-09T12:45:11
2019-01-09T12:45:11
69,162,221
8
7
null
null
null
null
UTF-8
C++
false
false
885
h
#ifndef _PathWriterIncluded_ #define _PathWriterIncluded_ #include <fstream> #include <string> #include "GeometricRecognizerTypes.h" using namespace std; namespace DollarRecognizer { class PathWriter { public: static bool writeToFile( Path2D path, const string fileName = "savedPath.txt", const string gestureName = "DefaultName") { fstream file(fileName.c_str(), ios::out); file << "Path2D getGesture" << gestureName << "()" << endl; file << "{" << endl; file << "\t" << "Path2D path;" << endl; Path2D::const_iterator i; for (i = path.begin(); i != path.end(); i++) { Point2D point = *i; file << "\t" << "path.push_back(Point2D(" << point.x << "," << point.y << "));" << endl; } file << endl; file << "\t" << "return path;" << endl; file << "}" << endl; file.close(); return true; } }; } #endif
[ "microsmadio@hotmail.com" ]
microsmadio@hotmail.com
5f1175bc34336a949304ecb72472445e6a1954b5
877fff5bb313ccd23d1d01bf23b1e1f2b13bb85a
/app/src/main/cpp/dir35435/dir35536/dir35859/dir36113/dir36250/file36306.cpp
70084755b8420d5ef4fd5e8c3d7a6f51bc3c5de5
[]
no_license
tgeng/HugeProject
829c3bdfb7cbaf57727c41263212d4a67e3eb93d
4488d3b765e8827636ce5e878baacdf388710ef2
refs/heads/master
2022-08-21T16:58:54.161627
2020-05-28T01:54:03
2020-05-28T01:54:03
267,468,475
0
0
null
null
null
null
UTF-8
C++
false
false
115
cpp
#ifndef file36306 #error "macro file36306 must be defined" #endif static const char* file36306String = "file36306";
[ "tgeng@google.com" ]
tgeng@google.com
3752f4c245d77673509375e1ba397421ba0a720e
a6bf86c0474c78626adad1e00247938cf80b378a
/src/UdpSrv.cpp
200c72e9d34944c4eb148bc7462ba7c826cf294b
[]
no_license
vslavav/RPiHelper
dcea32d07bdd7c7d855a02fab7e7323619ad0d49
1a68fb18fe3f7e779d9455b414bbab8d19d1fbdb
refs/heads/master
2020-04-25T13:02:10.242121
2019-03-10T14:47:44
2019-03-10T14:47:44
172,793,970
0
0
null
null
null
null
UTF-8
C++
false
false
1,531
cpp
/* * UdpSrv.cpp * * Created on: 2019-01-29 * Author: pi */ #include "UdpSrv.h" #include <thread> #include <unistd.h> #include <string.h> ////https://www.ibm.com/support/knowledgecenter/en/SSLTBW_2.3.0/com.ibm.zos.v2r3.hala001/xsocudp.htm void Thread_Run(UdpSrv* pUdpSrv) { while(1) { //UdpSrv* pUdpSrv = static_cast<UdpSrv*> (pUdpSrv); //UdpSrv* pUdpSrv = (UdpSrv*) pUdpSrv; pUdpSrv->Run(); } } UdpSrv::UdpSrv() { // TODO Auto-generated constructor stub } UdpSrv::~UdpSrv() { // TODO Auto-generated destructor stub close(_socket); } void UdpSrv::Init() { unsigned short shPort = 14010; _socket = socket(AF_INET, SOCK_DGRAM, 0); _server.sin_family = AF_INET; /* Server is in Internet Domain */ _server.sin_port = htons(shPort); _server.sin_addr.s_addr = INADDR_ANY;/* Server's Internet Address */ if (bind(_socket, (struct sockaddr *)&_server, sizeof(_server)) < 0) { return; } thread t(Thread_Run,this); t.detach(); } void UdpSrv::Run() { char buff[1024]; memset(buff,0,1024); int client_address_size = sizeof(_client); while(1) { int nError = recvfrom(_socket, buff, sizeof(buff), 0, (struct sockaddr *) &_client, (socklen_t*)&client_address_size) ; if(nError < 0) { perror("recvfrom()"); return; } string sMsg = buff; memset(buff,0,1024); SetMessage( sMsg ); } } void UdpSrv::SetMessage(string sMsg) { _sMessage = sMsg; } string UdpSrv::GetMessage() { string sMsg = _sMessage; _sMessage = ""; return sMsg; }
[ "SlavaV@hotmail.com" ]
SlavaV@hotmail.com
96faf3b4158967d8bb5be713b178a220d91353a0
567ee72bfdd5b1dd0aa0f94ddf08f0900ba9cffe
/solarsystem.cpp
12d7ba84d4908d2a057d698c6d43065fa990829f
[ "MIT" ]
permissive
SunilRao01/SpaceSim
d387f5273f3450687eb328997efcbb3837961aa2
f7dcd44b5f80ab8d34955c2c7e1d21dc2c144f74
refs/heads/master
2021-01-22T05:16:33.258105
2015-03-30T13:28:59
2015-03-30T13:28:59
27,149,572
0
0
null
null
null
null
UTF-8
C++
false
false
1,385
cpp
#include "solarsystem.h" void solarsystem::renderSolarSystem() { if (!changingParameters) { glPushMatrix(); // Center solar system glTranslatef(centerX, centerY, 0.0f); // Render sun sun.renderPlanet(0, 0); // Render planets for (int i = 0; i < numPlanets; i++) { // Rotate planets //glTranslatef(centerX, centerY, 0.0f); glRotatef(planets[i].angle, 0.0f, 0.0f, 1.0f); if (i == 0) { planets[i].renderPlanet(0, -60); } else { planets[i].renderPlanet(0, (i+1) * (-60)); } } glPopMatrix(); } } // TODO: Change rotation so it doesn't always rotate around (0, 0) void solarsystem::rotatePlanets() { if (!changingParameters) { for(int i = 0; i < numPlanets; i++) { planets[i].angle += (360.0f / 60) * (getRotationSpeed()); // Cap angle if (planets[i].angle >= 360.0f) { planets[i].angle -= 360.0f; } } } } void solarsystem::shuffle() { changingParameters = true; free(planets); numPlanets = rand() % maxNumPlanets + minNumPlanets; planets = (planet *) malloc(numPlanets * 100); rotationSpeed = 0.05f + static_cast <float> (rand()) /( static_cast <float> (RAND_MAX/(0.5f-0.05f))); for (int i = 0; i < numPlanets; i++) { planet tempPlanet(5, 15); planets[i] = tempPlanet; } changingParameters = false; } float solarsystem::getRotationSpeed() { return rotationSpeed; }
[ "slysunil101@gmail.com" ]
slysunil101@gmail.com
343f663010a279fe57586156eb3c2aa1840d4084
594e646453b7255104f721a9f9da84f752a733b8
/labs/kurs/samples/02_raytrace_plane/FrameBuffer.cpp
fc0988097c03e93b0b7c47146540d9e90b369ba3
[]
no_license
alexey-malov/cg
50068a19b8dc5d8259092e14ce2fdfa45400eac9
ca189f7e850a4d6f94103eabdb7840679f366d93
refs/heads/master
2020-12-30T15:41:35.575926
2018-06-19T11:26:35
2018-06-19T11:26:35
91,160,585
1
0
null
null
null
null
UTF-8
C++
false
false
279
cpp
#include "stdafx.h" #include "FrameBuffer.h" CFrameBuffer::CFrameBuffer(unsigned width, unsigned height) :m_pixels(width * height) ,m_width(width) ,m_height(height) { } void CFrameBuffer::Clear(boost::uint32_t color) { std::fill(m_pixels.begin(), m_pixels.end(), color); }
[ "alexey.malov@cpslabs.net" ]
alexey.malov@cpslabs.net
579bda5db9646c8e96b42221f422a0f52fb7230f
c75feeaa3f66d56c81b319648c210cd84caa403f
/InverseKinematic/src/Texture.h
165b72192407355e5dc6132f6656c90215d5191a
[]
no_license
hachihao792001/InverseKinematicOpenGL
2ef6da7203640dd82306c775ceee236d5a4ffa32
228993ff38d724f718357d7c3c2c36c473f9e735
refs/heads/master
2023-07-22T21:55:39.048705
2021-09-03T03:35:48
2021-09-03T03:35:48
402,010,870
0
0
null
null
null
null
UTF-8
C++
false
false
424
h
#pragma once #include "Renderer.h" class Texture { private: unsigned int m_RendererID; std::string m_FilePath; unsigned char* m_LocalBuffer; int m_Width, m_Height, m_BPP; //bits per pixel public: Texture(const std::string& path); ~Texture(); void Bind(unsigned int slot = 0) const; void Unbind() const; inline int GetWitdth() const { return m_Width; } inline int GetHeight() const { return m_Height; } };
[ "40560981+hachihao792001@users.noreply.github.com" ]
40560981+hachihao792001@users.noreply.github.com
b6c6832b2a70463a80978150dd6e79de3dcd2ce4
c57819bebe1a3e1d305ae0cb869cdcc48c7181d1
/src/qt/src/gui/widgets/qtoolbar.h
daa14fd77a9f595547f576b31fc47c833e24a386
[ "LGPL-2.1-only", "Qt-LGPL-exception-1.1", "LicenseRef-scancode-generic-exception", "GPL-3.0-only", "GPL-1.0-or-later", "GFDL-1.3-only", "BSD-3-Clause" ]
permissive
blowery/phantomjs
255829570e90a28d1cd597192e20314578ef0276
f929d2b04a29ff6c3c5b47cd08a8f741b1335c72
refs/heads/master
2023-04-08T01:22:35.426692
2012-10-11T17:43:24
2012-10-11T17:43:24
6,177,895
1
0
BSD-3-Clause
2023-04-03T23:09:40
2012-10-11T17:39:25
C++
UTF-8
C++
false
false
6,257
h
/**************************************************************************** ** ** Copyright (C) 2012 Nokia Corporation and/or its subsidiary(-ies). ** All rights reserved. ** Contact: Nokia Corporation (qt-info@nokia.com) ** ** This file is part of the QtGui module of the Qt Toolkit. ** ** $QT_BEGIN_LICENSE:LGPL$ ** GNU Lesser General Public License Usage ** This file may be used under the terms of the GNU Lesser General Public ** License version 2.1 as published by the Free Software Foundation and ** appearing in the file LICENSE.LGPL included in the packaging of this ** file. Please review the following information to ensure the GNU Lesser ** General Public License version 2.1 requirements will be met: ** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Nokia gives you certain additional ** rights. These rights are described in the Nokia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ** GNU General Public License Usage ** Alternatively, this file may be used under the terms of the GNU General ** Public License version 3.0 as published by the Free Software Foundation ** and appearing in the file LICENSE.GPL included in the packaging of this ** file. Please review the following information to ensure the GNU General ** Public License version 3.0 requirements will be met: ** http://www.gnu.org/copyleft/gpl.html. ** ** Other Usage ** Alternatively, this file may be used in accordance with the terms and ** conditions contained in a signed written agreement between you and Nokia. ** ** ** ** ** ** $QT_END_LICENSE$ ** ****************************************************************************/ #ifndef QDYNAMICTOOLBAR_H #define QDYNAMICTOOLBAR_H #include <QtGui/qwidget.h> QT_BEGIN_HEADER QT_BEGIN_NAMESPACE QT_MODULE(Gui) #ifndef QT_NO_TOOLBAR class QToolBarPrivate; class QAction; class QIcon; class QMainWindow; class QStyleOptionToolBar; class Q_GUI_EXPORT QToolBar : public QWidget { Q_OBJECT Q_PROPERTY(bool movable READ isMovable WRITE setMovable DESIGNABLE (qobject_cast<QMainWindow *>(parentWidget()) != 0) NOTIFY movableChanged) Q_PROPERTY(Qt::ToolBarAreas allowedAreas READ allowedAreas WRITE setAllowedAreas DESIGNABLE (qobject_cast<QMainWindow *>(parentWidget()) != 0) NOTIFY allowedAreasChanged) Q_PROPERTY(Qt::Orientation orientation READ orientation WRITE setOrientation DESIGNABLE (qobject_cast<QMainWindow *>(parentWidget()) == 0) NOTIFY orientationChanged) Q_PROPERTY(QSize iconSize READ iconSize WRITE setIconSize NOTIFY iconSizeChanged) Q_PROPERTY(Qt::ToolButtonStyle toolButtonStyle READ toolButtonStyle WRITE setToolButtonStyle NOTIFY toolButtonStyleChanged) Q_PROPERTY(bool floating READ isFloating) Q_PROPERTY(bool floatable READ isFloatable WRITE setFloatable) public: explicit QToolBar(const QString &title, QWidget *parent = 0); explicit QToolBar(QWidget *parent = 0); ~QToolBar(); void setMovable(bool movable); bool isMovable() const; void setAllowedAreas(Qt::ToolBarAreas areas); Qt::ToolBarAreas allowedAreas() const; inline bool isAreaAllowed(Qt::ToolBarArea area) const { return (allowedAreas() & area) == area; } void setOrientation(Qt::Orientation orientation); Qt::Orientation orientation() const; void clear(); #ifdef Q_NO_USING_KEYWORD inline void addAction(QAction *action) { QWidget::addAction(action); } #else using QWidget::addAction; #endif QAction *addAction(const QString &text); QAction *addAction(const QIcon &icon, const QString &text); QAction *addAction(const QString &text, const QObject *receiver, const char* member); QAction *addAction(const QIcon &icon, const QString &text, const QObject *receiver, const char* member); QAction *addSeparator(); QAction *insertSeparator(QAction *before); QAction *addWidget(QWidget *widget); QAction *insertWidget(QAction *before, QWidget *widget); QRect actionGeometry(QAction *action) const; QAction *actionAt(const QPoint &p) const; inline QAction *actionAt(int x, int y) const; QAction *toggleViewAction() const; QSize iconSize() const; Qt::ToolButtonStyle toolButtonStyle() const; QWidget *widgetForAction(QAction *action) const; bool isFloatable() const; void setFloatable(bool floatable); bool isFloating() const; public Q_SLOTS: void setIconSize(const QSize &iconSize); void setToolButtonStyle(Qt::ToolButtonStyle toolButtonStyle); Q_SIGNALS: void actionTriggered(QAction *action); void movableChanged(bool movable); void allowedAreasChanged(Qt::ToolBarAreas allowedAreas); void orientationChanged(Qt::Orientation orientation); void iconSizeChanged(const QSize &iconSize); void toolButtonStyleChanged(Qt::ToolButtonStyle toolButtonStyle); void topLevelChanged(bool topLevel); void visibilityChanged(bool visible); protected: void actionEvent(QActionEvent *event); void changeEvent(QEvent *event); void childEvent(QChildEvent *event); void paintEvent(QPaintEvent *event); void resizeEvent(QResizeEvent *event); bool event(QEvent *event); void initStyleOption(QStyleOptionToolBar *option) const; #ifdef QT3_SUPPORT public: QT3_SUPPORT_CONSTRUCTOR QToolBar(QWidget *parent, const char *name); inline QT3_SUPPORT void setLabel(const QString &label) { setWindowTitle(label); } inline QT3_SUPPORT QString label() const { return windowTitle(); } #endif private: Q_DECLARE_PRIVATE(QToolBar) Q_DISABLE_COPY(QToolBar) Q_PRIVATE_SLOT(d_func(), void _q_toggleView(bool)) Q_PRIVATE_SLOT(d_func(), void _q_updateIconSize(const QSize &)) Q_PRIVATE_SLOT(d_func(), void _q_updateToolButtonStyle(Qt::ToolButtonStyle)) friend class QMainWindow; friend class QMainWindowLayout; friend class QToolBarLayout; friend class QToolBarAreaLayout; }; inline QAction *QToolBar::actionAt(int ax, int ay) const { return actionAt(QPoint(ax, ay)); } #endif // QT_NO_TOOLBAR QT_END_NAMESPACE QT_END_HEADER #endif // QDYNAMICTOOLBAR_H
[ "ariya.hidayat@gmail.com" ]
ariya.hidayat@gmail.com
8c6b01bbcbc12ef85dde52892409c76cd8a5ef5c
ad780787315490d1deb31c2d550fe671c8d9777e
/GameLogic.cpp
2a8a55c0b33aee7fe164713316dfa91d03694e75
[]
no_license
nkwleroux/Proftaak2.4_A1_Word_Raiders
369c27989cbc7a12ba990e439f89b470125cb188
bc413dadb4d1d81be70fabce15588c2ca6e7a072
refs/heads/master
2023-05-29T11:49:50.951100
2021-06-14T08:45:33
2021-06-14T08:45:33
366,298,443
0
0
null
null
null
null
UTF-8
C++
false
false
4,204
cpp
#include "GameLogic.h" #include "WordLoader.h" #include "Scene.h" #include "LetterModelComponent.h" GameLogic::GameLogic() { // Initiate variables to standard values gameStarted = false; reset = false; currentWordLength = 5; currentWordAmount = 3; currentWordIndex = -1; // Initiate timers gameTimer = new Timer(90); oneSecondTimer = new Timer(1); // Load words from json file wordLoader = new WordLoader(); checkForStartingConditions(); } GameLogic::~GameLogic() {} void GameLogic::checkForStartingConditions() { //check if it is the start of the game if (!gameStarted) { gameStarted = true; wordsToGuess = wordLoader->loadWords(currentWordLength, currentWordAmount); currentWord = wordsToGuess[chosenWordsAmount]; gameTimer->start(); oneSecondTimer->start(); correctLetters = std::vector<char>(currentWordLength); shotLetters = std::vector<char>(currentWordLength); } } bool GameLogic::update(bool* redDetected) { checkForStartingConditions(); // If the currentWordIndex == -1 we know a new word is the current word if (currentWordIndex == -1) { fillVector(); currentWordIndex = 0; // todo remove for debugging std::cout << currentWord->getWord() << std::endl; return false; } //TODO --> check for lives //TODO --> check for timer // Check if the player want to fire if (*redDetected) { *redDetected = false; // Check if the player can fire if (oneSecondTimer->hasFinished()) { oneSecondTimer->start(); // Check if an objcet is selected if (selectedObject != nullptr) { // If the object is a letter model if (selectedObject->getComponent<LetterModelComponent>()) { // Get the letter of that lettermodel and shoot it char shotLetter = selectedObject->getComponent<LetterModelComponent>()->getLetter(); shootLetter(shotLetter); } } // If we have shot as many letters as the wordLength if (currentWordIndex == currentWordLength) { // Check the word if it is correct if (checkWord()) { // If it is correct we delete the word and set the new current word wordsToGuess.pop_back(); if (wordsToGuess.size() > 0) { currentWord = wordsToGuess[wordsToGuess.size() - 1]; reset = true; } // If there are no words left we are done and return true else { return true; } } // We remove all the shot characters else { currentWordIndex = 0; shotWord = ""; clearVector(&shotLetters); } } } } shotWord = ""; //clear the shotWord string for (int i = 0; i < shotLetters.size(); i++) { shotWord += shotLetters[i]; //fill the string with the letters of the vector } correctWord = ""; //clear the correctWord string for (int i = 0; i < correctLetters.size(); i++) { correctWord += correctLetters[i]; //fill the string with the letters of the vector } return false; } std::string GameLogic::getShotWord() { return shotWord; } std::string GameLogic::getCorrectWord() { return correctWord; } Word* GameLogic::getCurrentWord() { return currentWord; } Timer* GameLogic::getGameTimer() { return gameTimer; } void GameLogic::clearVector(std::vector<char>* vector) { for (int i = 0; i < vector->size(); i++) { vector->at(i) = '_'; } } /* * This function fills 2 vectors with letters or an _ */ void GameLogic::fillVector() { for (int i = 0; i < correctLetters.size(); i++) { shotLetters.at(i) = '_'; //fill the shotLetter vector with _ if (i == 0) { correctLetters.at(i) = currentWord->getFirstLetter(); //fill the vector with the first letter of the current word } else { correctLetters.at(i) = '_'; //fill the other indexes with an _ } } } bool GameLogic::checkWord() { int correctLettersAmount = 0; for (int i = 0; i < currentWordLength; i++) { if (currentWord->getWord()[i] == shotLetters.at(i)) { correctLetters.at(i) = currentWord->getWord()[i]; correctLettersAmount++; } } if (correctLettersAmount == currentWordLength) { clearVector(&correctLetters); currentWordIndex = -1; return true; } else { return false; } } void GameLogic::shootLetter(char shotLetter) { shotLetters.at(currentWordIndex) = shotLetter; currentWordIndex++; }
[ "rik.vos01@gmail.com" ]
rik.vos01@gmail.com
cecc114659f5dfed4ee527cb83e30191f3554955
2769085a50899819e8af0c0f28020cd42bbb5ed3
/src/ui_interface.h
bd67f38c5b831fda2aafe3c30d8adc609264a0af
[ "MIT" ]
permissive
CarbonTradingcoin/CarbonTradingcoin
ec188762cc06e1d1d963c10650e0427352c830af
0f824ee580b0ec7042abd607f581055bf68db0f9
refs/heads/master
2016-08-07T20:08:30.010797
2014-06-01T03:08:15
2014-06-01T03:08:15
null
0
0
null
null
null
null
UTF-8
C++
false
false
4,375
h
// Copyright (c) 2010 Satoshi Nakamoto // Copyright (c) 2012 The Carbonemissiontradecoin developers // Copyright (c) 2013-2079 CT DEV // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #ifndef CARBONEMISSIONTRADECOIN_UI_INTERFACE_H #define CARBONEMISSIONTRADECOIN_UI_INTERFACE_H #include <string> #include "util.h" // for int64 #include <boost/signals2/signal.hpp> #include <boost/signals2/last_value.hpp> class CBasicKeyStore; class CWallet; class uint256; /** General change type (added, updated, removed). */ enum ChangeType { CT_NEW, CT_UPDATED, CT_DELETED }; /** Signals for UI communication. */ class CClientUIInterface { public: /** Flags for CClientUIInterface::ThreadSafeMessageBox */ enum MessageBoxFlags { ICON_INFORMATION = 0, ICON_WARNING = (1U << 0), ICON_ERROR = (1U << 1), /** * Mask of all available icons in CClientUIInterface::MessageBoxFlags * This needs to be updated, when icons are changed there! */ ICON_MASK = (ICON_INFORMATION | ICON_WARNING | ICON_ERROR), /** These values are taken from qmessagebox.h "enum StandardButton" to be directly usable */ BTN_OK = 0x00000400U, // QMessageBox::Ok BTN_YES = 0x00004000U, // QMessageBox::Yes BTN_NO = 0x00010000U, // QMessageBox::No BTN_ABORT = 0x00040000U, // QMessageBox::Abort BTN_RETRY = 0x00080000U, // QMessageBox::Retry BTN_IGNORE = 0x00100000U, // QMessageBox::Ignore BTN_CLOSE = 0x00200000U, // QMessageBox::Close BTN_CANCEL = 0x00400000U, // QMessageBox::Cancel BTN_DISCARD = 0x00800000U, // QMessageBox::Discard BTN_HELP = 0x01000000U, // QMessageBox::Help BTN_APPLY = 0x02000000U, // QMessageBox::Apply BTN_RESET = 0x04000000U, // QMessageBox::Reset /** * Mask of all available buttons in CClientUIInterface::MessageBoxFlags * This needs to be updated, when buttons are changed there! */ BTN_MASK = (BTN_OK | BTN_YES | BTN_NO | BTN_ABORT | BTN_RETRY | BTN_IGNORE | BTN_CLOSE | BTN_CANCEL | BTN_DISCARD | BTN_HELP | BTN_APPLY | BTN_RESET), /** Force blocking, modal message box dialog (not just OS notification) */ MODAL = 0x10000000U, /** Predefined combinations for certain default usage cases */ MSG_INFORMATION = ICON_INFORMATION, MSG_WARNING = (ICON_WARNING | BTN_OK | MODAL), MSG_ERROR = (ICON_ERROR | BTN_OK | MODAL) }; /** Show message box. */ boost::signals2::signal<bool (const std::string& message, const std::string& caption, unsigned int style), boost::signals2::last_value<bool> > ThreadSafeMessageBox; /** Ask the user whether they want to pay a fee or not. */ boost::signals2::signal<bool (int64 nFeeRequired), boost::signals2::last_value<bool> > ThreadSafeAskFee; /** Handle a URL passed at the command line. */ boost::signals2::signal<void (const std::string& strURI)> ThreadSafeHandleURI; /** Progress message during initialization. */ boost::signals2::signal<void (const std::string &message)> InitMessage; /** Translate a message to the native language of the user. */ boost::signals2::signal<std::string (const char* psz)> Translate; /** Block chain changed. */ boost::signals2::signal<void ()> NotifyBlocksChanged; /** Number of network connections changed. */ boost::signals2::signal<void (int newNumConnections)> NotifyNumConnectionsChanged; /** * New, updated or cancelled alert. * @note called with lock cs_mapAlerts held. */ boost::signals2::signal<void (const uint256 &hash, ChangeType status)> NotifyAlertChanged; boost::signals2::signal<void (const uint256 &hash, ChangeType status)> NotifyNewsMessageChanged; }; extern CClientUIInterface uiInterface; /** * Translation function: Call Translate signal on UI interface, which returns a boost::optional result. * If no translation slot is registered, nothing is returned, and simply return the input. */ inline std::string _(const char* psz) { boost::optional<std::string> rv = uiInterface.Translate(psz); return rv ? (*rv) : psz; } #endif
[ "CarbonTradingcoin@gmail.com" ]
CarbonTradingcoin@gmail.com
bd906faaf244c2c79671bc7dbe48351b2f229369
33d55fd020dfa888c4b81c524ec10f27cacc31fe
/Tarde/main.cpp
e7dcb360f1009e3a4d963879712f43453d74ad95
[]
no_license
Melchyore/softwares
a24933da06dc70d20d4d408b5fb093aa06aaf6c3
4ab94ca88003a2ba62b720a581c91a7f827ca366
refs/heads/master
2021-05-28T04:21:54.443121
2014-05-22T19:58:09
2014-05-22T19:58:09
null
0
0
null
null
null
null
UTF-8
C++
false
false
500
cpp
#include <QApplication> #include "MainWindow.h" int main(int argc, char *argv[]) { QApplication application(argc, argv); MainWindow window; QPalette* palette = new QPalette(); QLinearGradient linearGradient(0, 0, 0, window.height()); linearGradient.setColorAt(0, "#242424"); linearGradient.setColorAt(1, "#090808"); palette->setBrush(QPalette::Window, *(new QBrush(linearGradient))); window.setPalette(*palette); window.show(); return application.exec(); }
[ "rider-2000@hotmail.com" ]
rider-2000@hotmail.com
a155374aa950a76ad976b6339a071c30b3a691f5
713c3e5f7b4126bb5d57edf795580320d0b72e66
/App/ATFGenerator/src/CPU/SimpsonHalfIterateIntegrator.cpp
e6c4d315375b05b3f7f95d9e330518d15e2b1808
[]
no_license
rustanitu/TFG
b40ed59295e9d490dbd2724a5e86ee3697d6c787
0570d8cfe0d48edc19cf76c9771b14beb03f9fc4
refs/heads/master
2020-04-04T06:12:18.445176
2016-09-15T18:37:06
2016-09-15T18:37:06
54,929,706
0
0
null
null
null
null
UTF-8
C++
false
false
46,542
cpp
//Internal Error Half, External Half #include "SimpsonHalfIterateIntegrator.h" #include "VolumeEvaluator.h" #include "SimpsonEvaluation.h" #include <iostream> #include <fstream> #include <cmath> #include <cerrno> #include <cfenv> #include <cstring> #ifdef ANALYSIS__RGBA_ALONG_THE_RAY void SimpsonHalfIterateIntegrator::PrintExternalStepSize (double h) { if (file_ext) { (*file_ext) << std::setprecision (30) << anchor << '\t' << std::setprecision (30) << anchor + h << '\t' << std::setprecision (30) << h << '\t' << std::setprecision (30) << color.x << '\t' << std::setprecision (30) << color.y << '\t' << std::setprecision (30) << color.z << '\t' << std::setprecision (30) << color.w << '\n'; } } void SimpsonHalfIterateIntegrator::PrintInternalStepSize (double h) { if (file_int) { (*file_int) << std::setprecision (30) << anchor << '\t' << std::setprecision (30) << anchor + h << '\t' << std::setprecision (30) << h << '\t'; } } void SimpsonHalfIterateIntegrator::PrintInternalColor () { if (file_int) { (*file_int) << std::setprecision (30) << pre_integrated << '\n'; } } #endif SimpsonHalfIterateIntegrator::SimpsonHalfIterateIntegrator (VolumeEvaluator* veva) : SimpsonIntegrator (veva) {} SimpsonHalfIterateIntegrator::~SimpsonHalfIterateIntegrator () { Reset (); } void SimpsonHalfIterateIntegrator::Reset () { #ifdef COMPUTE_STEPS_ALONG_EVALUATION m_steps_evaluation[0] = 0; m_steps_evaluation[1] = 0; m_steps_evaluation[2] = 0; m_steps_evaluation[3] = 0; m_steps_evaluation[4] = 0; m_steps_evaluation[5] = 0; m_steps_evaluation[6] = 0; m_steps_evaluation[7] = 0; m_steps_evaluation[8] = 0; m_steps_evaluation[9] = 0; m_steps_evaluation[10] = 0; #endif } void SimpsonHalfIterateIntegrator::PrintStepsEvaluation () { #ifdef COMPUTE_STEPS_ALONG_EVALUATION printf ("Steps evaluation:\n"); for (int i = 0; i < 11; i++) printf ("%d h < %d\n", m_steps_evaluation[i], i + 1); #endif } void SimpsonHalfIterateIntegrator::Init (lqc::Vector3d minp, lqc::Vector3d maxp, vr::Volume* vol, vr::TransferFunction* tf) { SimpsonIntegrator::Init (minp, maxp, vol, tf); #ifdef ANALYSIS__RGBA_ALONG_THE_RAY file_ext = file_int = NULL; #endif } void SimpsonHalfIterateIntegrator::IntegrateSimple (double s0, double s1, double tol, double h0, double hmin, double hmax) { tol = 15.0 * tol; double tol_int = tol, tol_ext = tol, h = h0; anchor = s0; anchor_color = GetFromTransferFunction (anchor); float Salfa, S2alfa; lqc::Vector4d S, S2; float b, c, d, e; lqc::Vector4d tf_d, tf_c, tf_e, tf_b, S2S; lqc::Vector4d tf_ad, tf_ae; lqc::Vector4d F_d, F_c, F_e, F_b; lqc::Vector4d F_a = lqc::Vector4d (anchor_color.w * anchor_color.x, anchor_color.w * anchor_color.y, anchor_color.w * anchor_color.z, anchor_color.w); double hproj = h; double h_6, h_12, S2left; lqc::Vector4d S2Eleft; double tol_multiplier = tol_int / s1; while (s1 > anchor) { h = std::max (hproj, hmin); h = std::min (std::min (h, hmax), s1 - anchor); tol = tol_multiplier * h; //Integral Interna tf_d = GetFromTransferFunction (anchor + h * 0.25); tf_c = GetFromTransferFunction (anchor + h * 0.50); tf_e = GetFromTransferFunction (anchor + h * 0.75); tf_b = GetFromTransferFunction (anchor + h); h_6 = h / 6.00; h_12 = h_6 * 0.5; Salfa = h_6 * (anchor_color.w + 4.0 * tf_c.w + tf_b.w); S2left = h_12 * (anchor_color.w + 4.0 * tf_d.w + tf_c.w); S2alfa = S2left + (h_12 * (tf_c.w + 4.0 * tf_e.w + tf_b.w)); if (abs (S2alfa - Salfa) <= tol || h <= hmin) hproj = 2.0 * h; else { do { h = h * 0.5; tol = tol * 0.5; h_12 = h_12 * 0.5; tf_b = tf_c; tf_c = tf_d; tf_d = GetFromTransferFunction (anchor + h * 0.25); tf_e = GetFromTransferFunction (anchor + h * 0.75); Salfa = S2left; S2left = h_12 * (anchor_color.w + 4.0 * tf_d.w + tf_c.w); S2alfa = S2left + (h_12 * (tf_c.w + 4.0 * tf_e.w + tf_b.w)); } while (abs (S2alfa - Salfa) > tol && h > hmin); hproj = h; h_6 = h_12 * 2.0; } #ifdef COMPUTE_STEPS_ALONG_EVALUATION m_steps_evaluation[(int)h]++; #endif #ifdef ANALYSIS__RGBA_ALONG_THE_RAY PrintInternalStepSize (h); #endif double se1 = anchor + h; h_6 = h / 6.00; h_12 = h_6 * 0.5; tol = tol_multiplier * h; while (true) { b = anchor + h; c = anchor + h * 0.5; d = anchor + h * 0.25; e = anchor + h * 0.75; tf_d = GetFromTransferFunction (d); tf_c = GetFromTransferFunction (c); tf_e = GetFromTransferFunction (e); tf_b = GetFromTransferFunction (b); F_d = ExternalEvaluation (d, tf_d, GetFromTransferFunction (anchor + h * 0.125).w); F_c = ExternalEvaluation (c, tf_c, tf_d.w); F_e = ExternalEvaluation (e, tf_e, GetFromTransferFunction (anchor + h * 0.375).w); F_b = ExternalEvaluation (b, tf_b, tf_c.w); S = h_6 * (F_a + 4.0 * F_c + F_b); S2Eleft = h_12 * (F_a + 4.0 * F_d + F_c); S2 = S2Eleft + h_12 * (F_c + 4.0 * F_e + F_b); S2S = S2 - S; if ((tol >= abs (S2S.w) && tol >= abs (S2S.x) && tol >= abs (S2S.y) && tol >= abs (S2S.z)) || h <= hmin) { color += S2 + S2S / 15.0; S2alfa = h_12 * (anchor_color.w + 4.0 * tf_d.w + 2.0 * tf_c.w + 4.0 * tf_e.w + tf_b.w); pre_integrated = pre_integrated + (S2alfa + (S2alfa - h_6 * (anchor_color.w + 4.0 * tf_c.w + tf_b.w)) / 15.0); #ifdef ANALYSIS__RGBA_ALONG_THE_RAY PrintExternalStepSize (h); #endif anchor_color = tf_b; anchor = anchor + h; F_a = F_b; if (se1 == anchor) break; h = std::min (h * 2.0, se1 - anchor); tol = tol_multiplier * h; h_6 = h / 6.00; h_12 = h_6 * 0.5; } else { do { h = h * 0.5; tol = tol * 0.5; h_6 = h_12; h_12 = h_12 * 0.5; tf_b = tf_c; tf_c = tf_d; d = anchor + h * 0.25; e = anchor + h * 0.75; tf_d = GetFromTransferFunction (d); tf_e = GetFromTransferFunction (e); F_b = F_c; F_c = F_d; F_d = ExternalEvaluation (d, tf_d, GetFromTransferFunction ((anchor + d) * 0.5).w); F_e = ExternalEvaluation (e, tf_e, GetFromTransferFunction ((anchor + e) * 0.5).w); S = S2Eleft; S2Eleft = h_12 * (F_a + 4.0 * F_d + F_c); S2 = S2Eleft + h_12 * (F_c + 4.0 * F_e + F_b); S2S = S2 - S; } while (!((tol >= abs (S2S.w) && tol >= abs (S2S.x) && tol >= abs (S2S.y) && tol >= abs (S2S.z)) || h <= hmin)); color += S2 + S2S / 15.0; S2alfa = h_12 * (anchor_color.w + 4.0 * tf_d.w + 2.0 * tf_c.w + 4.0 * tf_e.w + tf_b.w); pre_integrated = pre_integrated + (S2alfa + (S2alfa - h_6 * (anchor_color.w + 4.0 * tf_c.w + tf_b.w)) / 15.0); #ifdef ANALYSIS__RGBA_ALONG_THE_RAY PrintExternalStepSize (h); #endif anchor_color = tf_b; anchor = anchor + h; F_a = F_b; } } #ifdef ANALYSIS__RGBA_ALONG_THE_RAY PrintInternalColor (); #endif } } void SimpsonHalfIterateIntegrator::IntegrateSimpleExtStep (double s0, double s1, double tol, double h0, double hmin, double hmax) { tol = 15.0 * tol; double tol_int = tol, tol_ext = tol, h = h0; anchor = s0; anchor_color = GetFromTransferFunction (anchor); float Salfa, S2alfa; lqc::Vector4d S, S2; float b, c, d, e; lqc::Vector4d tf_d, tf_c, tf_e, tf_b, S2S; lqc::Vector4d tf_ad, tf_ae; lqc::Vector4d F_d, F_c, F_e, F_b; lqc::Vector4d F_a = lqc::Vector4d (anchor_color.w * anchor_color.x, anchor_color.w * anchor_color.y, anchor_color.w * anchor_color.z, anchor_color.w); double hproj = h; double hext = h; double h_6, h_12, S2left; lqc::Vector4d S2Eleft; double tol_multiplier = tol_int / s1; while (s1 > anchor) { h = std::max (hproj, hmin); h = std::min (std::min (h, hmax), s1 - anchor); tol = tol_multiplier * h; //Integral Interna tf_d = GetFromTransferFunction (anchor + h * 0.25); tf_c = GetFromTransferFunction (anchor + h * 0.50); tf_e = GetFromTransferFunction (anchor + h * 0.75); tf_b = GetFromTransferFunction (anchor + h); h_6 = h / 6.00; h_12 = h_6 * 0.5; Salfa = h_6 * (anchor_color.w + 4.0 * tf_c.w + tf_b.w); S2left = h_12 * (anchor_color.w + 4.0 * tf_d.w + tf_c.w); S2alfa = S2left + (h_12 * (tf_c.w + 4.0 * tf_e.w + tf_b.w)); if (abs (S2alfa - Salfa) <= tol || h <= hmin) hproj = 2.0 * h; else { do { h = h * 0.5; tol = tol * 0.5; h_12 = h_12 * 0.5; tf_b = tf_c; tf_c = tf_d; tf_d = GetFromTransferFunction (anchor + h * 0.25); tf_e = GetFromTransferFunction (anchor + h * 0.75); Salfa = S2left; S2left = h_12 * (anchor_color.w + 4.0 * tf_d.w + tf_c.w); S2alfa = S2left + (h_12 * (tf_c.w + 4.0 * tf_e.w + tf_b.w)); } while (abs (S2alfa - Salfa) > tol && h > hmin); hproj = h; h_6 = h_12 * 2.0; } #ifdef COMPUTE_STEPS_ALONG_EVALUATION m_steps_evaluation[(int)h]++; #endif #ifdef ANALYSIS__RGBA_ALONG_THE_RAY PrintInternalStepSize (h); #endif double se1 = anchor + h; if (h <= hext) { hext = h; } else h = hext; h_6 = h / 6.00; h_12 = h_6 * 0.5; tol = tol_multiplier * h; while (true) { b = anchor + h; c = anchor + h * 0.5; d = anchor + h * 0.25; e = anchor + h * 0.75; tf_d = GetFromTransferFunction (d); tf_c = GetFromTransferFunction (c); tf_e = GetFromTransferFunction (e); tf_b = GetFromTransferFunction (b); F_d = ExternalEvaluation (d, tf_d, GetFromTransferFunction (anchor + h * 0.125).w); F_c = ExternalEvaluation (c, tf_c, tf_d.w); F_e = ExternalEvaluation (e, tf_e, GetFromTransferFunction (anchor + h * 0.375).w); F_b = ExternalEvaluation (b, tf_b, tf_c.w); S = h_6 * (F_a + 4.0 * F_c + F_b); S2Eleft = h_12 * (F_a + 4.0 * F_d + F_c); S2 = S2Eleft + h_12 * (F_c + 4.0 * F_e + F_b); S2S = S2 - S; if ((tol >= abs (S2S.w) && tol >= abs (S2S.x) && tol >= abs (S2S.y) && tol >= abs (S2S.z)) || h <= hmin) { color += S2 + S2S / 15.0; S2alfa = h_12 * (anchor_color.w + 4.0 * tf_d.w + 2.0 * tf_c.w + 4.0 * tf_e.w + tf_b.w); pre_integrated = pre_integrated + (S2alfa + (S2alfa - h_6 * (anchor_color.w + 4.0 * tf_c.w + tf_b.w)) / 15.0); #ifdef ANALYSIS__RGBA_ALONG_THE_RAY PrintExternalStepSize (h); #endif anchor_color = tf_b; anchor = anchor + h; F_a = F_b; if (se1 == anchor) break; hext = 2.0 * h; h = std::min (h * 2.0, se1 - anchor); tol = tol_multiplier * h; h_6 = h / 6.00; h_12 = h_6 * 0.5; } else { do { h = h * 0.5; tol = tol * 0.5; h_6 = h_12; h_12 = h_12 * 0.5; tf_b = tf_c; tf_c = tf_d; d = anchor + h * 0.25; e = anchor + h * 0.75; tf_d = GetFromTransferFunction (d); tf_e = GetFromTransferFunction (e); F_b = F_c; F_c = F_d; F_d = ExternalEvaluation (d, tf_d, GetFromTransferFunction ((anchor + d) * 0.5).w); F_e = ExternalEvaluation (e, tf_e, GetFromTransferFunction ((anchor + e) * 0.5).w); S = S2Eleft; S2Eleft = h_12 * (F_a + 4.0 * F_d + F_c); S2 = S2Eleft + h_12 * (F_c + 4.0 * F_e + F_b); S2S = S2 - S; } while (!((tol >= abs (S2S.w) && tol >= abs (S2S.x) && tol >= abs (S2S.y) && tol >= abs (S2S.z)) || h <= hmin)); color += S2 + S2S / 15.0; S2alfa = h_12 * (anchor_color.w + 4.0 * tf_d.w + 2.0 * tf_c.w + 4.0 * tf_e.w + tf_b.w); pre_integrated = pre_integrated + (S2alfa + (S2alfa - h_6 * (anchor_color.w + 4.0 * tf_c.w + tf_b.w)) / 15.0); #ifdef ANALYSIS__RGBA_ALONG_THE_RAY PrintExternalStepSize (h); #endif anchor_color = tf_b; anchor = anchor + h; F_a = F_b; hext = h; } } #ifdef ANALYSIS__RGBA_ALONG_THE_RAY PrintInternalColor (); #endif } } void SimpsonHalfIterateIntegrator::IntegrateComplexExtStep (double s0, double s1, double tol, double h0, double hmin, double hmax) { tol = 15.0 * tol; double tol_int = tol, tol_ext = tol, h = h0; anchor = s0; anchor_color = GetFromTransferFunction (anchor); float Salfa, S2alfa; lqc::Vector4d S, S2; float b, c, d, e; lqc::Vector4d tf_d, tf_c, tf_e, tf_b, S2S; lqc::Vector4d tf_ad, tf_ae; lqc::Vector4d F_d, F_c, F_e, F_b; lqc::Vector4d F_a = lqc::Vector4d (anchor_color.w * anchor_color.x, anchor_color.w * anchor_color.y, anchor_color.w * anchor_color.z, anchor_color.w); double hproj = h; double hext = h; double h_6, h_12, S2left; lqc::Vector4d S2Eleft; double tol_multiplier = tol_int / s1; while (s1 > anchor) { h = std::max (hproj, hmin); h = std::min (std::min (h, hmax), s1 - anchor); tol = tol_multiplier * h; //Integral Interna tf_d = GetFromTransferFunction (anchor + h * 0.25); tf_c = GetFromTransferFunction (anchor + h * 0.50); tf_e = GetFromTransferFunction (anchor + h * 0.75); tf_b = GetFromTransferFunction (anchor + h); h_6 = h / 6.00; h_12 = h_6 * 0.5; Salfa = h_6 * (anchor_color.w + 4.0 * tf_c.w + tf_b.w); S2left = h_12 * (anchor_color.w + 4.0 * tf_d.w + tf_c.w); S2alfa = S2left + (h_12 * (tf_c.w + 4.0 * tf_e.w + tf_b.w)); if (abs (S2alfa - Salfa) <= tol || h <= hmin) hproj = 2.0 * h; else { do { h = h * 0.5; tol = tol * 0.5; h_12 = h_12 * 0.5; tf_b = tf_c; tf_c = tf_d; tf_d = GetFromTransferFunction (anchor + h * 0.25); tf_e = GetFromTransferFunction (anchor + h * 0.75); Salfa = S2left; S2left = h_12 * (anchor_color.w + 4.0 * tf_d.w + tf_c.w); S2alfa = S2left + (h_12 * (tf_c.w + 4.0 * tf_e.w + tf_b.w)); } while (abs (S2alfa - Salfa) > tol && h > hmin); hproj = h; h_6 = h_12 * 2.0; } #ifdef COMPUTE_STEPS_ALONG_EVALUATION m_steps_evaluation[(int)h]++; #endif #ifdef ANALYSIS__RGBA_ALONG_THE_RAY PrintInternalStepSize (h); #endif double se1 = anchor + h; //O passo que deve ser integrado deve ser igual ao passo // feito na integral interna if (h <= hext) { hext = hproj; if (S2alfa == 0.0) { #ifdef ANALYSIS__RGBA_ALONG_THE_RAY PrintExternalStepSize (h); #endif anchor_color = tf_b; anchor = anchor + h; F_a = lqc::Vector4d (0.0); } else { b = anchor + h; c = anchor + h * 0.5; d = anchor + h * 0.25; e = anchor + h * 0.75; F_d = ExternalEvaluation (d, tf_d, GetFromTransferFunction (anchor + h * 0.125).w); F_c = ExternalEvaluation (c, tf_c, tf_d.w); F_e = ExternalEvaluation (e, tf_e, GetFromTransferFunction (anchor + h * 0.375).w); F_b = ExternalEvaluation (b, tf_b, tf_c.w); S = h_6 * (F_a + 4.0 * F_c + F_b); S2Eleft = h_12 * (F_a + 4.0 * F_d + F_c); S2 = S2Eleft + h_12 * (F_c + 4.0 * F_e + F_b); S2S = S2 - S; if ((tol >= abs (S2S.w) && tol >= abs (S2S.x) && tol >= abs (S2S.y) && tol >= abs (S2S.z)) || h <= hmin) { color += S2 + S2S / 15.0; pre_integrated = pre_integrated + (S2alfa + (S2alfa - Salfa) / 15.0); #ifdef ANALYSIS__RGBA_ALONG_THE_RAY PrintExternalStepSize (h); #endif anchor_color = tf_b; anchor = anchor + h; F_a = F_b; } else { double se1 = anchor + h; do { h = h * 0.5; tol = tol * 0.5; h_6 = h_12; h_12 = h_12 * 0.5; tf_b = tf_c; tf_c = tf_d; d = anchor + h * 0.25; e = anchor + h * 0.75; tf_d = GetFromTransferFunction (d); tf_e = GetFromTransferFunction (e); F_b = F_c; F_c = F_d; F_d = ExternalEvaluation (d, tf_d, GetFromTransferFunction ((anchor + d) * 0.5).w); F_e = ExternalEvaluation (e, tf_e, GetFromTransferFunction ((anchor + e) * 0.5).w); S = S2Eleft; S2Eleft = h_12 * (F_a + 4.0 * F_d + F_c); S2 = S2Eleft + h_12 * (F_c + 4.0 * F_e + F_b); S2S = S2 - S; } while (!((tol >= abs (S2S.w) && tol >= abs (S2S.x) && tol >= abs (S2S.y) && tol >= abs (S2S.z)) || h <= hmin)); color += S2 + S2S / 15.0; S2alfa = h_12 * (anchor_color.w + 4.0 * tf_d.w + 2.0 * tf_c.w + 4.0 * tf_e.w + tf_b.w); pre_integrated = pre_integrated + (S2alfa + (S2alfa - h_6 * (anchor_color.w + 4.0 * tf_c.w + tf_b.w)) / 15.0); #ifdef ANALYSIS__RGBA_ALONG_THE_RAY PrintExternalStepSize (h); #endif anchor_color = tf_b; anchor = anchor + h; F_a = F_b; hext = h; while (true) { b = anchor + h; c = anchor + h * 0.5; d = anchor + h * 0.25; e = anchor + h * 0.75; tf_d = GetFromTransferFunction (d); tf_c = GetFromTransferFunction (c); tf_e = GetFromTransferFunction (e); tf_b = GetFromTransferFunction (b); F_d = ExternalEvaluation (d, tf_d, GetFromTransferFunction (anchor + h * 0.125).w); F_c = ExternalEvaluation (c, tf_c, tf_d.w); F_e = ExternalEvaluation (e, tf_e, GetFromTransferFunction (anchor + h * 0.375).w); F_b = ExternalEvaluation (b, tf_b, tf_c.w); h_6 = h / 6.00; h_12 = h_6 * 0.5; S = h_6 * (F_a + 4.0 * F_c + F_b); S2Eleft = h_12 * (F_a + 4.0 * F_d + F_c); S2 = S2Eleft + h_12 * (F_c + 4.0 * F_e + F_b); S2S = S2 - S; if ((tol >= abs (S2S.w) && tol >= abs (S2S.x) && tol >= abs (S2S.y) && tol >= abs (S2S.z)) || h <= hmin) { color += S2 + S2S / 15.0; S2alfa = h_12 * (anchor_color.w + 4.0 * tf_d.w + 2.0 * tf_c.w + 4.0 * tf_e.w + tf_b.w); pre_integrated = pre_integrated + (S2alfa + (S2alfa - h_6 * (anchor_color.w + 4.0 * tf_c.w + tf_b.w)) / 15.0); #ifdef ANALYSIS__RGBA_ALONG_THE_RAY PrintExternalStepSize (h); #endif anchor_color = tf_b; anchor = anchor + h; F_a = F_b; if (se1 <= anchor) break; h = std::min (h * 2.0, se1 - anchor); tol = tol_multiplier * h; } else { do { h = h * 0.5; tol = tol * 0.5; h_6 = h_12; h_12 = h_12 * 0.5; tf_b = tf_c; tf_c = tf_d; d = anchor + h * 0.25; e = anchor + h * 0.75; tf_d = GetFromTransferFunction (d); tf_e = GetFromTransferFunction (e); F_b = F_c; F_c = F_d; F_d = ExternalEvaluation (d, tf_d, GetFromTransferFunction ((anchor + d) * 0.5).w); F_e = ExternalEvaluation (e, tf_e, GetFromTransferFunction ((anchor + e) * 0.5).w); S = S2Eleft; S2Eleft = h_12 * (F_a + 4.0 * F_d + F_c); S2 = S2Eleft + h_12 * (F_c + 4.0 * F_e + F_b); S2S = S2 - S; } while (!((tol >= abs (S2S.w) && tol >= abs (S2S.x) && tol >= abs (S2S.y) && tol >= abs (S2S.z)) || h <= hmin)); color += S2 + S2S / 15.0; S2alfa = h_12 * (anchor_color.w + 4.0 * tf_d.w + 2.0 * tf_c.w + 4.0 * tf_e.w + tf_b.w); pre_integrated = pre_integrated + (S2alfa + (S2alfa - h_6 * (anchor_color.w + 4.0 * tf_c.w + tf_b.w)) / 15.0); #ifdef ANALYSIS__RGBA_ALONG_THE_RAY PrintExternalStepSize (h); #endif anchor_color = tf_b; anchor = anchor + h; F_a = F_b; hext = h; } } } } } //O passo que deve ser integrado deve ser menor ao passo // feito na integral interna else { h = hext; h_6 = h / 6.00; h_12 = h_6 * 0.5; tol = tol_multiplier * h; while (true) { b = anchor + h; c = anchor + h * 0.5; d = anchor + h * 0.25; e = anchor + h * 0.75; tf_d = GetFromTransferFunction (d); tf_c = GetFromTransferFunction (c); tf_e = GetFromTransferFunction (e); tf_b = GetFromTransferFunction (b); F_d = ExternalEvaluation (d, tf_d, GetFromTransferFunction (anchor + h * 0.125).w); F_c = ExternalEvaluation (c, tf_c, tf_d.w); F_e = ExternalEvaluation (e, tf_e, GetFromTransferFunction (anchor + h * 0.375).w); F_b = ExternalEvaluation (b, tf_b, tf_c.w); S = h_6 * (F_a + 4.0 * F_c + F_b); S2Eleft = h_12 * (F_a + 4.0 * F_d + F_c); S2 = S2Eleft + h_12 * (F_c + 4.0 * F_e + F_b); S2S = S2 - S; if ((tol >= abs (S2S.w) && tol >= abs (S2S.x) && tol >= abs (S2S.y) && tol >= abs (S2S.z)) || h <= hmin) { color += S2 + S2S / 15.0; S2alfa = h_12 * (anchor_color.w + 4.0 * tf_d.w + 2.0 * tf_c.w + 4.0 * tf_e.w + tf_b.w); pre_integrated = pre_integrated + (S2alfa + (S2alfa - h_6 * (anchor_color.w + 4.0 * tf_c.w + tf_b.w)) / 15.0); #ifdef ANALYSIS__RGBA_ALONG_THE_RAY PrintExternalStepSize (h); #endif anchor_color = tf_b; anchor = anchor + h; F_a = F_b; if (se1 == anchor) break; hext = 2.0 * h; h = std::min (h * 2.0, se1 - anchor); tol = tol_multiplier * h; h_6 = h / 6.00; h_12 = h_6 * 0.5; } else { do { h = h * 0.5; tol = tol * 0.5; h_6 = h_12; h_12 = h_12 * 0.5; tf_b = tf_c; tf_c = tf_d; d = anchor + h * 0.25; e = anchor + h * 0.75; tf_d = GetFromTransferFunction (d); tf_e = GetFromTransferFunction (e); F_b = F_c; F_c = F_d; F_d = ExternalEvaluation (d, tf_d, GetFromTransferFunction ((anchor + d) * 0.5).w); F_e = ExternalEvaluation (e, tf_e, GetFromTransferFunction ((anchor + e) * 0.5).w); S = S2Eleft; S2Eleft = h_12 * (F_a + 4.0 * F_d + F_c); S2 = S2Eleft + h_12 * (F_c + 4.0 * F_e + F_b); S2S = S2 - S; } while (!((tol >= abs (S2S.w) && tol >= abs (S2S.x) && tol >= abs (S2S.y) && tol >= abs (S2S.z)) || h <= hmin)); color += S2 + S2S / 15.0; S2alfa = h_12 * (anchor_color.w + 4.0 * tf_d.w + 2.0 * tf_c.w + 4.0 * tf_e.w + tf_b.w); pre_integrated = pre_integrated + (S2alfa + (S2alfa - h_6 * (anchor_color.w + 4.0 * tf_c.w + tf_b.w)) / 15.0); #ifdef ANALYSIS__RGBA_ALONG_THE_RAY PrintExternalStepSize (h); #endif anchor_color = tf_b; anchor = anchor + h; F_a = F_b; hext = h; } } } #ifdef ANALYSIS__RGBA_ALONG_THE_RAY PrintInternalColor (); #endif } } void SimpsonHalfIterateIntegrator::IntegrateExp (double s0, double s1, double tol, double h0, double hmin, double hmax) { tol = 15.0 * tol; pre_integrated = 1.0; double tol_int = tol, tol_ext = tol, h = h0; anchor = s0; anchor_color = GetFromTransferFunction (anchor); float Salfa, S2alfa; lqc::Vector4d S, S2; float b, c, d, e; lqc::Vector4d tf_d, tf_c, tf_e, tf_b, S2S; lqc::Vector4d F_d, F_c, F_e, F_b; lqc::Vector4d F_a = lqc::Vector4d (anchor_color.w * anchor_color.x, anchor_color.w * anchor_color.y, anchor_color.w * anchor_color.z, anchor_color.w); double hproj = h; double h_6, h_12, S2left; lqc::Vector4d S2Eleft; double tol_multiplier = tol_int / s1; while (s1 > anchor) { h = std::max (hproj, hmin); h = std::min (std::min (h, hmax), s1 - anchor); tol = tol_multiplier * h; //Integral Interna tf_d = GetFromTransferFunction (anchor + h * 0.25); tf_c = GetFromTransferFunction (anchor + h * 0.50); tf_e = GetFromTransferFunction (anchor + h * 0.75); tf_b = GetFromTransferFunction (anchor + h); h_6 = h / 6.00; h_12 = h_6 * 0.5; Salfa = h_6 * (anchor_color.w + 4.0 * tf_c.w + tf_b.w); S2left = h_12 * (anchor_color.w + 4.0 * tf_d.w + tf_c.w); S2alfa = S2left + (h_12 * (tf_c.w + 4.0 * tf_e.w + tf_b.w)); if (abs (S2alfa - Salfa) <= tol || h <= hmin) hproj = 2.0 * h; else { do { h = h * 0.5; tol = tol * 0.5; h_12 = h_12 * 0.5; tf_b = tf_c; tf_c = tf_d; tf_d = GetFromTransferFunction (anchor + h * 0.25); tf_e = GetFromTransferFunction (anchor + h * 0.75); Salfa = S2left; S2left = h_12 * (anchor_color.w + 4.0 * tf_d.w + tf_c.w); S2alfa = S2left + (h_12 * (tf_c.w + 4.0 * tf_e.w + tf_b.w)); } while (abs (S2alfa - Salfa) > tol && h > hmin); hproj = h; h_6 = h_12 * 2.0; } #ifdef COMPUTE_STEPS_ALONG_EVALUATION m_steps_evaluation[(int)h]++; #endif if (anchor_color.w + tf_d.w + tf_c.w + tf_e.w + tf_b.w == 0.0) { anchor_color = tf_b; anchor = anchor + h; F_a = lqc::Vector4d (0.0); } else { b = anchor + h; c = anchor + h * 0.5; d = anchor + h * 0.25; e = anchor + h * 0.75; F_d = ExternalEvaluationApprox (d, tf_d, GetFromTransferFunction (anchor + h * 0.125).w); F_c = ExternalEvaluationApprox (c, tf_c, tf_d.w); F_e = ExternalEvaluationApprox (e, tf_e, GetFromTransferFunction (anchor + h * 0.375).w); F_b = ExternalEvaluationApprox (b, tf_b, tf_c.w); S = h_6 * (F_a + 4.0 * F_c + F_b); S2Eleft = h_12 * (F_a + 4.0 * F_d + F_c); S2 = S2Eleft + h_12 * (F_c + 4.0 * F_e + F_b); S2S = S2 - S; if ((tol >= abs (S2S.w) && tol >= abs (S2S.x) && tol >= abs (S2S.y) && tol >= abs (S2S.z)) || h <= hmin) { color += S2 + S2S / 15.0; double x = -h_12 * (anchor_color.w + 4.0 * tf_d.w + 2.0 * tf_c.w + 4.0 * tf_e.w + tf_b.w); pre_integrated = pre_integrated * (1.0 + x + (x*x) / 2.0 + (x*x*x) / 6.0); anchor_color = tf_b; anchor = anchor + h; F_a = F_b; } else { double se1 = anchor + h; h = h * 0.5; tol = tol * 0.5; while (se1 > anchor) { b = anchor + h; c = anchor + h * 0.5; d = anchor + h * 0.25; e = anchor + h * 0.75; tf_d = GetFromTransferFunction (d); tf_c = GetFromTransferFunction (c); tf_e = GetFromTransferFunction (e); tf_b = GetFromTransferFunction (b); F_d = ExternalEvaluationApprox (d, tf_d, GetFromTransferFunction (anchor + h * 0.125).w); F_c = ExternalEvaluationApprox (c, tf_c, tf_d.w); F_e = ExternalEvaluationApprox (e, tf_e, GetFromTransferFunction (anchor + h * 0.375).w); F_b = ExternalEvaluationApprox (b, tf_b, tf_c.w); h_6 = h / 6.00; h_12 = h_6 * 0.5; S = h_6 * (F_a + 4.0 * F_c + F_b); S2Eleft = h_12 * (F_a + 4.0 * F_d + F_c); S2 = S2Eleft + h_12 * (F_c + 4.0 * F_e + F_b); S2S = S2 - S; if ((tol >= abs (S2S.w) && tol >= abs (S2S.x) && tol >= abs (S2S.y) && tol >= abs (S2S.z)) || h <= hmin) { color += S2 + S2S / 15.0; double x = -h_12 * (anchor_color.w + 4.0 * tf_d.w + 2.0 * tf_c.w + 4.0 * tf_e.w + tf_b.w); pre_integrated = pre_integrated * (1.0 + x + (x*x) / 2.0 + (x*x*x) / 6.0); anchor_color = tf_b; anchor = anchor + h; F_a = F_b; h = std::min (h * 2.0, se1 - anchor); tol = tol_multiplier * h; } else { do { h = h * 0.5; tol = tol * 0.5; h_6 = h_12; h_12 = h_12 * 0.5; tf_b = tf_c; tf_c = tf_d; d = anchor + h * 0.25; e = anchor + h * 0.75; tf_d = GetFromTransferFunction (d); tf_e = GetFromTransferFunction (e); F_b = F_c; F_c = F_d; F_d = ExternalEvaluationApprox (d, tf_d, GetFromTransferFunction ((anchor + d) * 0.5).w); F_e = ExternalEvaluationApprox (e, tf_e, GetFromTransferFunction ((anchor + e) * 0.5).w); S = S2Eleft; S2Eleft = h_12 * (F_a + 4.0 * F_d + F_c); S2 = S2Eleft + h_12 * (F_c + 4.0 * F_e + F_b); S2S = S2 - S; } while (!((tol >= abs (S2S.w) && tol >= abs (S2S.x) && tol >= abs (S2S.y) && tol >= abs (S2S.z)) || h <= hmin)); color += S2 + S2S / 15.0; double x = -h_12 * (anchor_color.w + 4.0 * tf_d.w + 2.0 * tf_c.w + 4.0 * tf_e.w + tf_b.w); pre_integrated = pre_integrated * (1.0 + x + (x*x) / 2.0 + (x*x*x) / 6.0); anchor_color = tf_b; anchor = anchor + h; F_a = F_b; } } } } } } void SimpsonHalfIterateIntegrator::IntegrateSeparated (double s0, double s1, double tol, double h0, double hmin, double hmax) { tol = 15.0 * tol; double tol_int = tol, tol_ext = tol, hext = h0, hint = h0, hproj = h0; anchor = s0; anchor_color = GetFromTransferFunction (anchor); lqc::Vector4d F_a = ExternalEvaluationAnchor (); double tol_int_multiplier = tol_int / s1; double tol_ext_multiplier = tol_ext / s1; double b, c, d, e, h_6, h_12, Salfa, S2alfa, S2left; lqc::Vector4d tf_d, tf_c, tf_e, tf_b, F_d, F_c, F_e, F_b, S, S2, S2S, S2Eleft; while (s1 > anchor) { ///////////////////////////////////////////////// //Integral Interna { hint = std::max (hproj, hmin); hint = std::min (std::min (hint, hmax), s1 - anchor); tol = tol_int_multiplier * hint; tf_d = GetFromTransferFunction (anchor + hint * 0.25); tf_c = GetFromTransferFunction (anchor + hint * 0.50); tf_e = GetFromTransferFunction (anchor + hint * 0.75); tf_b = GetFromTransferFunction (anchor + hint); h_6 = hint / 6.0; h_12 = h_6 * 0.5; Salfa = h_6 * (anchor_color.w + 4.0 * tf_c.w + tf_b.w); S2left = h_12 * (anchor_color.w + 4.0 * tf_d.w + tf_c.w); S2alfa = S2left + (h_12 * (tf_c.w + 4.0 * tf_e.w + tf_b.w)); if (abs (S2alfa - Salfa) <= tol || hint <= hmin) hproj = 2.0 * hint; else { do { hint = hint * 0.5; if (hint <= hmin) { hint = hmin; tol = tol_int_multiplier * hint; tf_d = GetFromTransferFunction (anchor + hint * 0.25); tf_c = GetFromTransferFunction (anchor + hint * 0.50); tf_e = GetFromTransferFunction (anchor + hint * 0.75); tf_b = GetFromTransferFunction (anchor + hint); h_12 = hint / 12.0; Salfa = (h_12 * 2.0) * (anchor_color.w + 4.0 * tf_c.w + tf_b.w); S2left = h_12 * (anchor_color.w + 4.0 * tf_d.w + tf_c.w); S2alfa = S2left + (h_12 * (tf_c.w + 4.0 * tf_e.w + tf_b.w)); break; } tol = tol * 0.5; h_12 = h_12 * 0.5; tf_b = tf_c; tf_c = tf_d; tf_d = GetFromTransferFunction (anchor + hint * 0.25); tf_e = GetFromTransferFunction (anchor + hint * 0.75); Salfa = S2left; S2left = h_12 * (anchor_color.w + 4.0 * tf_d.w + tf_c.w); S2alfa = S2left + (h_12 * (tf_c.w + 4.0 * tf_e.w + tf_b.w)); } while (abs (S2alfa - Salfa) > tol); hproj = hint; } } #ifdef ANALYSIS__RGBA_ALONG_THE_RAY PrintInternalStepSize (hint); #endif ///////////////////////////////////////////////// //Integral Externa { double h = hext; //Caso o intervalo da integral externa for maior // que o intervalo da integral interna if (hint <= h) { h = hint; if (S2alfa == 0.0) { #ifdef ANALYSIS__RGBA_ALONG_THE_RAY PrintExternalStepSize (h); #endif anchor_color = tf_b; anchor = anchor + h; F_a = lqc::Vector4d (0.0); hext = std::max (hext, hproj); continue; } else { h_6 = h_12 * 2.0; b = anchor + h; c = anchor + h * 0.5; d = anchor + h * 0.25; e = anchor + h * 0.75; F_d = ExternalEvaluation (d, tf_d, GetFromTransferFunction (anchor + h * 0.125).w); F_c = ExternalEvaluation (c, tf_c, tf_d.w); F_e = ExternalEvaluation (e, tf_e, GetFromTransferFunction (anchor + h * 0.375).w); F_b = ExternalEvaluation (b, tf_b, tf_c.w); S = h_6 * (F_a + 4.0 * F_c + F_b); S2Eleft = h_12 * (F_a + 4.0 * F_d + F_c); S2 = S2Eleft + h_12 * (F_c + 4.0 * F_e + F_b); S2S = S2 - S; if ((tol >= abs (S2S.w) && tol >= abs (S2S.x) && tol >= abs (S2S.y) && tol >= abs (S2S.z)) || h <= hmin) { color += S2 + S2S / 15.0; pre_integrated = pre_integrated + (S2alfa + (S2alfa - Salfa) / 15.0); #ifdef ANALYSIS__RGBA_ALONG_THE_RAY PrintExternalStepSize (h); #endif anchor_color = tf_b; anchor = anchor + h; F_a = F_b; hext = std::max (hext, hproj); continue; } } h = h * 0.5; } //O passo que deve ser integrado deve ser menor ao passo // feito na integral interna tol = tol_ext_multiplier * h; h_6 = h / 6.0; h_12 = h_6 * 0.5; double s1 = anchor + hint; while (true) { b = anchor + h; c = anchor + h * 0.5; d = anchor + h * 0.25; e = anchor + h * 0.75; tf_d = GetFromTransferFunction (d); tf_c = GetFromTransferFunction (c); tf_e = GetFromTransferFunction (e); tf_b = GetFromTransferFunction (b); F_d = ExternalEvaluation (d, tf_d, GetFromTransferFunction (anchor + h * 0.125).w); F_c = ExternalEvaluation (c, tf_c, tf_d.w); F_e = ExternalEvaluation (e, tf_e, GetFromTransferFunction (anchor + h * 0.375).w); F_b = ExternalEvaluation (b, tf_b, tf_c.w); S = h_6 * (F_a + 4.0 * F_c + F_b); S2Eleft = h_12 * (F_a + 4.0 * F_d + F_c); S2 = S2Eleft + h_12 * (F_c + 4.0 * F_e + F_b); S2S = S2 - S; if ((tol >= abs (S2S.w) && tol >= abs (S2S.x) && tol >= abs (S2S.y) && tol >= abs (S2S.z)) || h <= hmin) { color += S2 + S2S / 15.0; double S2alfa = h_12 * (anchor_color.w + 4.0 * tf_d.w + 2.0 * tf_c.w + 4.0 * tf_e.w + tf_b.w); pre_integrated = pre_integrated + (S2alfa + (S2alfa - h_6 * (anchor_color.w + 4.0 * tf_c.w + tf_b.w)) / 15.0); #ifdef ANALYSIS__RGBA_ALONG_THE_RAY PrintExternalStepSize (h); #endif anchor_color = tf_b; anchor = anchor + h; F_a = F_b; if (s1 <= anchor) break; double h_2 = 2.0 * h; double s1_anchor = s1 - anchor; hext = h_2; h = std::min (h_2, s1_anchor); h_6 = h / 6.0; h_12 = h_6 * 0.5; tol = tol_ext_multiplier * h; } else { do { h = h * 0.5; if (h <= hmin) { h = hmin; tol = tol_ext_multiplier * h; b = anchor + h; c = anchor + h * 0.5; d = anchor + h * 0.25; e = anchor + h * 0.75; tf_d = GetFromTransferFunction (d); tf_c = GetFromTransferFunction (c); tf_e = GetFromTransferFunction (e); tf_b = GetFromTransferFunction (b); F_d = ExternalEvaluation (d, tf_d, GetFromTransferFunction (anchor + h * 0.125).w); F_c = ExternalEvaluation (c, tf_c, tf_d.w); F_e = ExternalEvaluation (e, tf_e, GetFromTransferFunction (anchor + h * 0.375).w); F_b = ExternalEvaluation (b, tf_b, tf_c.w); h_12 = h / 12.0; S = (h_12 * 2.0) * (F_a + 4.0 * F_c + F_b); S2Eleft = h_12 * (F_a + 4.0 * F_d + F_c); S2 = S2Eleft + h_12 * (F_c + 4.0 * F_e + F_b); S2S = S2 - S; break; } tol = tol * 0.5; h_12 = h_12 * 0.5; tf_b = tf_c; tf_c = tf_d; d = anchor + h * 0.25; e = anchor + h * 0.75; tf_d = GetFromTransferFunction (d); tf_e = GetFromTransferFunction (e); F_b = F_c; F_c = F_d; F_d = ExternalEvaluation (d, tf_d, GetFromTransferFunction ((anchor + d) * 0.5).w); F_e = ExternalEvaluation (e, tf_e, GetFromTransferFunction ((anchor + e) * 0.5).w); S = S2Eleft; S2Eleft = h_12 * (F_a + 4.0 * F_d + F_c); S2 = S2Eleft + h_12 * (F_c + 4.0 * F_e + F_b); S2S = S2 - S; } while (!((tol >= abs (S2S.w) && tol >= abs (S2S.x) && tol >= abs (S2S.y) && tol >= abs (S2S.z)))); color += S2 + S2S / 15.0; h_6 = h_12 * 2.0; double S2alfa = h_12 * (anchor_color.w + 4.0 * tf_d.w + 2.0 * tf_c.w + 4.0 * tf_e.w + tf_b.w); pre_integrated = pre_integrated + (S2alfa + (S2alfa - h_6 * (anchor_color.w + 4.0 * tf_c.w + tf_b.w)) / 15.0); #ifdef ANALYSIS__RGBA_ALONG_THE_RAY PrintExternalStepSize (h); #endif anchor_color = tf_b; anchor = anchor + h; F_a = F_b; hext = h; } } } #ifdef ANALYSIS__RGBA_ALONG_THE_RAY PrintInternalColor (); #endif } } void SimpsonHalfIterateIntegrator::IntegrateScount (double s0, double s1, double tol, double h0, double hmin, double hmax) { tol = 15.0 * tol; double tol_int = tol, tol_ext = tol, h = h0; anchor = s0; anchor_color = GetFromTransferFunction (anchor); float Salfa, S2alfa; lqc::Vector4d S, S2; float b, c, d, e; lqc::Vector4d tf_d, tf_c, tf_e, tf_b, S2S; lqc::Vector4d tf_ad, tf_ae; lqc::Vector4d F_d, F_c, F_e, F_b; lqc::Vector4d F_a = lqc::Vector4d (anchor_color.w * anchor_color.x, anchor_color.w * anchor_color.y, anchor_color.w * anchor_color.z, anchor_color.w); double hproj = h; double h_6, h_12, S2left; lqc::Vector4d S2Eleft; double tol_multiplier = tol_int / s1; while (s1 > anchor) { h = std::max (hproj, hmin); h = std::min (std::min (h, hmax), s1 - anchor); tol = tol_multiplier * h; //Integral Interna tf_d = GetFromTransferFunction (anchor + h * 0.25); tf_c = GetFromTransferFunction (anchor + h * 0.50); tf_e = GetFromTransferFunction (anchor + h * 0.75); tf_b = GetFromTransferFunction (anchor + h); h_6 = h / 6.00; h_12 = h_6 * 0.5; Salfa = h_6 * (anchor_color.w + 4.0 * tf_c.w + tf_b.w); S2left = h_12 * (anchor_color.w + 4.0 * tf_d.w + tf_c.w); S2alfa = S2left + (h_12 * (tf_c.w + 4.0 * tf_e.w + tf_b.w)); if (abs (S2alfa - Salfa) <= tol || h <= hmin) hproj = 2.0 * h; else { do { h = h * 0.5; if (h <= hmin) { h = hmin; tol = tol_multiplier * h; tf_d = GetFromTransferFunction (anchor + h * 0.25); tf_c = GetFromTransferFunction (anchor + h * 0.50); tf_e = GetFromTransferFunction (anchor + h * 0.75); tf_b = GetFromTransferFunction (anchor + h); h_12 = h / 12.0; h_6 = h_12 * 2.0; Salfa = h_6 * (anchor_color.w + 4.0 * tf_c.w + tf_b.w); S2left = h_12 * (anchor_color.w + 4.0 * tf_d.w + tf_c.w); S2alfa = S2left + (h_12 * (tf_c.w + 4.0 * tf_e.w + tf_b.w)); break; } tol = tol * 0.5; h_12 = h_12 * 0.5; tf_b = tf_c; tf_c = tf_d; tf_d = GetFromTransferFunction (anchor + h * 0.25); tf_e = GetFromTransferFunction (anchor + h * 0.75); Salfa = h_6 * (anchor_color.w + 4.0 * tf_c.w + tf_b.w); S2left = h_12 * (anchor_color.w + 4.0 * tf_d.w + tf_c.w); S2alfa = S2left + (h_12 * (tf_c.w + 4.0 * tf_e.w + tf_b.w)); } while (abs (S2alfa - Salfa) > tol); hproj = h; h_6 = h_12 * 2.0; } #ifdef COMPUTE_STEPS_ALONG_EVALUATION m_steps_evaluation[(int)h]++; #endif #ifdef ANALYSIS__RGBA_ALONG_THE_RAY PrintInternalStepSize (h); #endif if (anchor_color.w + tf_d.w + tf_c.w + tf_e.w + tf_b.w == 0.0) { #ifdef ANALYSIS__RGBA_ALONG_THE_RAY PrintExternalStepSize (h); #endif anchor_color = tf_b; anchor = anchor + h; F_a = lqc::Vector4d (0.0); } else { b = anchor + h; c = anchor + h * 0.5; d = anchor + h * 0.25; e = anchor + h * 0.75; F_d = ExternalEvaluation (d, tf_d, GetFromTransferFunction (anchor + h * 0.125).w); F_c = ExternalEvaluation (c, tf_c, tf_d.w); F_e = ExternalEvaluation (e, tf_e, GetFromTransferFunction (anchor + h * 0.375).w); F_b = ExternalEvaluation (b, tf_b, tf_c.w); S = h_6 * (F_a + 4.0 * F_c + F_b); S2Eleft = h_12 * (F_a + 4.0 * F_d + F_c); S2 = S2Eleft + h_12 * (F_c + 4.0 * F_e + F_b); S2S = S2 - S; if ((tol >= abs (S2S.w) && tol >= abs (S2S.x) && tol >= abs (S2S.y) && tol >= abs (S2S.z)) || h <= hmin) { color += S2 + S2S / 15.0; pre_integrated = pre_integrated + (S2alfa + (S2alfa - Salfa) / 15.0); #ifdef ANALYSIS__RGBA_ALONG_THE_RAY PrintExternalStepSize (h); #endif anchor_color = tf_b; anchor = anchor + h; F_a = F_b; } else { double se1 = anchor + h; h = h * 0.5; tol = tol * 0.5; while (true) { b = anchor + h; c = anchor + h * 0.5; d = anchor + h * 0.25; e = anchor + h * 0.75; tf_d = GetFromTransferFunction (d); tf_c = GetFromTransferFunction (c); tf_e = GetFromTransferFunction (e); tf_b = GetFromTransferFunction (b); F_d = ExternalEvaluation (d, tf_d, GetFromTransferFunction (anchor + h * 0.125).w); F_c = ExternalEvaluation (c, tf_c, tf_d.w); F_e = ExternalEvaluation (e, tf_e, GetFromTransferFunction (anchor + h * 0.375).w); F_b = ExternalEvaluation (b, tf_b, tf_c.w); h_6 = h / 6.00; h_12 = h_6 * 0.5; S = h_6 * (F_a + 4.0 * F_c + F_b); S2Eleft = h_12 * (F_a + 4.0 * F_d + F_c); S2 = S2Eleft + h_12 * (F_c + 4.0 * F_e + F_b); S2S = S2 - S; if ((tol >= abs (S2S.w) && tol >= abs (S2S.x) && tol >= abs (S2S.y) && tol >= abs (S2S.z)) || h <= hmin) { color += S2 + S2S / 15.0; S2alfa = h_12 * (anchor_color.w + 4.0 * tf_d.w + 2.0 * tf_c.w + 4.0 * tf_e.w + tf_b.w); pre_integrated = pre_integrated + (S2alfa + (S2alfa - h_6 * (anchor_color.w + 4.0 * tf_c.w + tf_b.w)) / 15.0); #ifdef ANALYSIS__RGBA_ALONG_THE_RAY PrintExternalStepSize (h); #endif anchor_color = tf_b; anchor = anchor + h; F_a = F_b; if (se1 <= anchor) break; h = std::min (h * 2.0, se1 - anchor); tol = tol_multiplier * h; } else { do { h = h * 0.5; if (h <= hmin) { h = hmin; tol = tol_multiplier * h; b = anchor + h; c = anchor + h * 0.5; d = anchor + h * 0.25; e = anchor + h * 0.75; tf_d = GetFromTransferFunction (d); tf_c = GetFromTransferFunction (c); tf_e = GetFromTransferFunction (e); tf_b = GetFromTransferFunction (b); F_d = ExternalEvaluation (d, tf_d, GetFromTransferFunction (anchor + h * 0.125).w); F_c = ExternalEvaluation (c, tf_c, tf_d.w); F_e = ExternalEvaluation (e, tf_e, GetFromTransferFunction (anchor + h * 0.375).w); F_b = ExternalEvaluation (b, tf_b, tf_c.w); h_12 = h / 12.0; h_6 = h_12 * 2.0; S = h_6 * (F_a + 4.0 * F_c + F_b); S2Eleft = h_12 * (F_a + 4.0 * F_d + F_c); S2 = S2Eleft + h_12 * (F_c + 4.0 * F_e + F_b); S2S = S2 - S; break; } tol = tol * 0.5; h_6 = h_12; h_12 = h_12 * 0.5; tf_b = tf_c; tf_c = tf_d; d = anchor + h * 0.25; e = anchor + h * 0.75; tf_d = GetFromTransferFunction (d); tf_e = GetFromTransferFunction (e); F_b = F_c; F_c = F_d; F_d = ExternalEvaluation (d, tf_d, GetFromTransferFunction ((anchor + d) * 0.5).w); F_e = ExternalEvaluation (e, tf_e, GetFromTransferFunction ((anchor + e) * 0.5).w); S = S2Eleft; S2Eleft = h_12 * (F_a + 4.0 * F_d + F_c); S2 = S2Eleft + h_12 * (F_c + 4.0 * F_e + F_b); S2S = S2 - S; } while (!((tol >= abs (S2S.w) && tol >= abs (S2S.x) && tol >= abs (S2S.y) && tol >= abs (S2S.z)))); color += S2 + S2S / 15.0; S2alfa = h_12 * (anchor_color.w + 4.0 * tf_d.w + 2.0 * tf_c.w + 4.0 * tf_e.w + tf_b.w); pre_integrated = pre_integrated + (S2alfa + (S2alfa - h_6 * (anchor_color.w + 4.0 * tf_c.w + tf_b.w)) / 15.0); #ifdef ANALYSIS__RGBA_ALONG_THE_RAY PrintExternalStepSize (h); #endif anchor_color = tf_b; anchor = anchor + h; F_a = F_b; } } } } #ifdef ANALYSIS__RGBA_ALONG_THE_RAY PrintInternalColor (); #endif } }
[ "rustanitus@gmail.com" ]
rustanitus@gmail.com
1a80c0e537b2db3edb3866fea5fb0462a60f5491
8c8820fb84dea70d31c1e31dd57d295bd08dd644
/Online/BuildPatchServices/Private/Generation/ChunkMatchProcessor.h
f542b09eeb6d28177bd1b41832353bb39b05010b
[]
no_license
redisread/UE-Runtime
e1a56df95a4591e12c0fd0e884ac6e54f69d0a57
48b9e72b1ad04458039c6ddeb7578e4fc68a7bac
refs/heads/master
2022-11-15T08:30:24.570998
2020-06-20T06:37:55
2020-06-20T06:37:55
274,085,558
3
0
null
null
null
null
UTF-8
C++
false
false
815
h
// Copyright Epic Games, Inc. All Rights Reserved. #pragma once #include "CoreTypes.h" #include "Containers/Array.h" #include "Templates/Tuple.h" #include "Core/BlockRange.h" #include "Core/BlockStructure.h" #include "Generation/DataScanner.h" namespace BuildPatchServices { struct FMatchEntry { FChunkMatch ChunkMatch; FBlockStructure BlockStructure; }; class IChunkMatchProcessor { public: virtual ~IChunkMatchProcessor() {} virtual void ProcessMatch(const int32 Layer, const FChunkMatch& Match, FBlockStructure BuildSpace) = 0; virtual void FlushLayer(const int32 Layer, const uint64 UpToByteOffset) = 0; virtual FBlockRange CollectLayer(const int32 Layer, TArray<FMatchEntry>& OutData) = 0; }; class FChunkMatchProcessorFactory { public: static IChunkMatchProcessor* Create(); }; }
[ "wujiahong19981022@outlook.com" ]
wujiahong19981022@outlook.com
dfa16b76f2c626b10138e6f5b0b0f33885843470
19b14d0280be480be7f4642079419c3a584db2b0
/programa 8/main.cpp
a74cd1d68f92da42483cdbd2646f3a64268e77e6
[]
no_license
juanfernandorl/ProgramacionII-Codeblocks
2664f4e6c7e22a099401c9ca8f709ef45db6554b
a515252d320ac2acb45ae0afa11c21466befbb0c
refs/heads/master
2021-01-10T22:07:22.539437
2013-10-17T17:34:33
2013-10-17T17:34:33
null
0
0
null
null
null
null
UTF-8
C++
false
false
915
cpp
#include <iostream> using namespace std; /* Se tiene que ingresar el nombre, la nota y el progreso del alumno con las siguientes observaciones 1-59 reprobado 60-80 bueno 81-90 muy bueno 91-100 sobresaliente. usar condiciones donde apliquemos el and */ int main() { char nombre[30]; int nota; cout<<"Ingresar nombre del alumno:"; cin.getline(nombre,30); cout<<"Nota del alumno:>"; cin>>nota; if ((nota>=0)and (nota<60)) { cout<<"Reprobado"<<"\n"; } else if ((nota>060) and (nota <=80)) { cout<<"Bueno"<<"\n"; } else if ((nota>=81) and (nota<=90)) { cout<<"Muy bueno"<<"\n"; } else if ((nota>=91) and (nota<=100)) { cout<<"Sobresaliente"<<"\n"; } else { cout<<"nota incorrecta"; } return 0; }
[ "juanfernando.rl@unitec.edu" ]
juanfernando.rl@unitec.edu
70d0cc99258adda5afe687dbceb14ee0aca9235b
c73422c07bff58108ff9cc528c71c22533263f99
/src/proxy_handler.cc
4095ee291efeb918761e64331bbdb1e3d471a9c0
[]
no_license
UCLA-CS130/Just-Enough
6b048b8bf48223a9bcb7afd9505d7f139d270ea7
66d2d50af6e6796c40a97e6ce7af9cfb273db7d6
refs/heads/master
2021-01-20T12:06:23.871282
2017-03-13T18:10:53
2017-03-13T18:10:53
79,513,574
0
4
null
2017-03-13T18:10:54
2017-01-20T01:37:03
C++
UTF-8
C++
false
false
5,771
cc
#include "proxy_handler.h" #include <string> RequestHandler::Status ProxyHandler::Init(const std::string& uri_prefix, const NginxConfig& config) { uri_prefix_ = uri_prefix; /* * We can accept one of two formats inside of the ProxyHandler's block. * Format 1: * remote_host website.com; * remote_port 80; * Format 2: * remote_port 80; * remote_host website.com; * The variable server_location specifies which format in terms of the * server-specifying statement's location in config.statements_. */ int server_location = 0; if (config.statements_[0]->tokens_[0] == "remote_port") { server_location = 1; } remote_host_ = config.statements_[server_location]->tokens_[1]; remote_port_ = config.statements_[1-server_location]->tokens_[1]; return RequestHandler::OK; } RequestHandler::Status ProxyHandler::HandleRequest(const Request& request, Response* response) { if (!redirect_) { mtx_.lock(); } else { redirect_ = false; } std::string host; if (remote_host_.size() == 0 || remote_port_.size() == 0) { std::cerr << "ProxyHandler::HandleRequest: remote_host_ or "; std::cerr << "remote_port_ are empty. Cannot serve request."; std::cerr << std::endl; mtx_.unlock(); return RequestHandler::Error; } if (redirect_host_.size() > 0) { host = redirect_host_; redirect_host_ = ""; } else { host = remote_host_; } Request proxied_req(request); proxied_req.set_uri(request.uri().substr(uri_prefix_.size())); if (proxied_req.uri().size() == 0) { proxied_req.set_uri("/"); } // make sure keep alive is off proxied_req.remove_header("Connection"); proxied_req.add_header("Connection", "Close"); // update host proxied_req.remove_header("Host"); proxied_req.add_header("Host", host + ":" + remote_port_); if (!client_->Connect(host, remote_port_)) { std::cerr << "ProxyHandler::HandleRequest failed to connect to "; std::cerr << host << ":" << remote_port_ << std::endl; mtx_.unlock(); return RequestHandler::Error; } if (!client_->Write(proxied_req.raw_request())) { std::cerr << "ProxyHandler::HandleRequest failed to write to "; std::cerr << host << ":" << remote_port_ << std::endl; mtx_.unlock(); return RequestHandler::Error; } std::string response_str(1024, 0); if (!client_->Read(response_str)) { std::cerr << "ProxyHandler::HandleRequest failed to read from "; std::cerr << host << ":" << remote_port_ << std::endl; mtx_.unlock(); return RequestHandler::Error; } // copy parsed response into given response *response = ParseRawResponse(response_str); if (redirect_) { Request redirect_request(request); redirect_request.set_uri(redirect_uri_); redirect_request.remove_header("Host"); redirect_request.add_header("Host", redirect_host_header_); uri_prefix_ = ""; // sub-call will unlock mtx_ return HandleRequest(redirect_request, response); } mtx_.unlock(); return RequestHandler::OK; } // TODO: this assume raw_response is valid HTTP // TODO: factor this out into a more appropriate location Response ProxyHandler::ParseRawResponse(const std::string& raw_response) { Response response; // for a given substring, start points to first char, end points to 1 // position past the end size_t start = 0, end; // get response code start = raw_response.find(" ") + 1; // skip version end = raw_response.find(" ", start); int raw_response_code = std::stoi(raw_response.substr(start, end - start)); auto rc = (Response::ResponseCode) raw_response_code; response.SetStatus(rc); // get all headers std::string header_name, header_value; end = raw_response.find("\r\n", start); while (true) { start = end + 2; // if next \r\n is right after current one, we're done with the headers if (raw_response.find("\r\n", start) == start) { start += 2; break; } end = raw_response.find(":", start); header_name = raw_response.substr(start, end - start); start = end + 1; // skip over whitespace while (raw_response[start] == ' ') { start++; } end = raw_response.find("\r\n", start); header_value = raw_response.substr(start, end - start); if ((rc == Response::code_302_found || rc == Response::code_301_moved) && header_name == "Location") { redirect_ = true; if (header_value[0] == '/') { // new URI on same host redirect_uri_ = header_value; } else { // new host // extract new host, uri size_t uri_pos = 0; redirect_host_ = header_value; if (redirect_host_.find("http://") == 0) { redirect_host_ = redirect_host_.substr(strlen("http://")); uri_pos += strlen("http://"); } uri_pos = header_value.find("/", uri_pos); redirect_host_header_ = header_value.substr(0, uri_pos); redirect_uri_ = header_value.substr(uri_pos); redirect_host_ = redirect_host_.substr( 0, redirect_host_.find(redirect_uri_)); } } response.AddHeader(header_name, header_value); } response.SetBody(raw_response.substr(start, raw_response.size() - start)); return response; }
[ "jevbburton@gmail.com" ]
jevbburton@gmail.com
907a7d0e2be12d3a1289668c4cefc629e9d306ce
b9bd8a0bb3e107acdc61de13e18777c6045adfdf
/src/mail.cpp
ff77c908a2d057ff5497432dc7443e7cbd74cd9e
[]
no_license
Chrps/super-pack
8765f4a64f4d08055b9b7afa849349efab5a1638
78680ebe5e5e9ab6368b794507dfe1c7ef6b5be3
refs/heads/master
2021-01-10T18:20:24.376175
2015-10-29T07:53:18
2015-10-29T07:53:18
45,168,669
0
0
null
null
null
null
UTF-8
C++
false
false
47
cpp
void main (void){ // Nothing happens return; }
[ "Christoffer.chrps@gmail.com" ]
Christoffer.chrps@gmail.com
4f94d5e77d3b5c4a69717f6acbccdbe31fe67713
0615fd17ae28bdb62918b8b275b72e098f9d1078
/Classes/DB_Emoji.h
08325aac95951ffdb3f5c8e6076c8b416d08b810
[ "MIT" ]
permissive
InternationalDefy/AdvenTri-Cocos
7c7f072af3f6872fae9e430714de16de80f0f1f9
966ef8112a350b6ddb0ed22f33c14abed35b51b5
refs/heads/main
2022-12-30T04:11:24.554959
2020-10-26T13:02:38
2020-10-26T13:02:38
307,361,154
1
0
null
null
null
null
UTF-8
C++
false
false
454
h
#ifndef __DB_EMOJI__ #define __DB_EMOJI__ #include "Ref_DataBase.h" class SD_Emoji; using namespace cocos2d; class DB_Emoji :public DB { private: SD_Emoji* tempSD; std::string tempName; Map<std::string, SD_Emoji*> _table; public: std::string useString(){ return "Table_Emoji.csv"; } void getLine(const std::string& data); static DB_Emoji* create(); static DB_Emoji* getInstance(); SD_Emoji* getEmojiSD(const std::string& name); }; #endif
[ "DTEye1533014901@126.com" ]
DTEye1533014901@126.com
918cc665e564bdd2c1c9251e03f210a7b5f39b38
0efb71923c02367a1194a9b47779e8def49a7b9f
/Oblig1/les/0.26/uniform/time
a9c9de75ed607099f405984fdd0c64ff6341f5eb
[]
no_license
andergsv/blandet
bbff505e8663c7547b5412700f51e3f42f088d78
f648b164ea066c918e297001a8049dd5e6f786f9
refs/heads/master
2021-01-17T13:23:44.372215
2016-06-14T21:32:00
2016-06-14T21:32:00
41,495,450
0
0
null
null
null
null
UTF-8
C++
false
false
982
/*--------------------------------*- C++ -*----------------------------------*\ | ========= | | | \\ / F ield | OpenFOAM: The Open Source CFD Toolbox | | \\ / O peration | Version: 2.4.0 | | \\ / A nd | Web: www.OpenFOAM.org | | \\/ M anipulation | | \*---------------------------------------------------------------------------*/ FoamFile { version 2.0; format ascii; class dictionary; location "0.26/uniform"; object time; } // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // value 0.26; name "0.26"; index 2600; deltaT 0.0001; deltaT0 0.0001; // ************************************************************************* //
[ "g.svenn@online.no" ]
g.svenn@online.no