blob_id
stringlengths
40
40
directory_id
stringlengths
40
40
path
stringlengths
2
247
content_id
stringlengths
40
40
detected_licenses
listlengths
0
57
license_type
stringclasses
2 values
repo_name
stringlengths
4
111
snapshot_id
stringlengths
40
40
revision_id
stringlengths
40
40
branch_name
stringlengths
4
58
visit_date
timestamp[ns]date
2015-07-25 18:16:41
2023-09-06 10:45:08
revision_date
timestamp[ns]date
1970-01-14 14:03:36
2023-09-06 06:22:19
committer_date
timestamp[ns]date
1970-01-14 14:03:36
2023-09-06 06:22:19
github_id
int64
3.89k
689M
star_events_count
int64
0
209k
fork_events_count
int64
0
110k
gha_license_id
stringclasses
25 values
gha_event_created_at
timestamp[ns]date
2012-06-07 00:51:45
2023-09-14 21:58:52
gha_created_at
timestamp[ns]date
2008-03-27 23:40:48
2023-08-24 19:49:39
gha_language
stringclasses
159 values
src_encoding
stringclasses
34 values
language
stringclasses
1 value
is_vendor
bool
1 class
is_generated
bool
2 classes
length_bytes
int64
7
10.5M
extension
stringclasses
111 values
filename
stringlengths
1
195
text
stringlengths
7
10.5M
c9cc05487c3d540114fb22848c33fc0563560c7e
4db9da754b1ae73d9074367ff273f827b95b2cb8
/GoogleCodeJam/GCJ_2015_1A_B/main.cpp
4045f99b9f2529998c1775f1c2277dcd18d2eb6d
[]
no_license
sergii-yatsuk/codejam
9ba5e3d3d27c7d5c66ab093add90f465b46f3e79
06184086ce54329744c81e85875871099cbd2424
refs/heads/master
2021-09-13T12:02:14.077337
2018-04-29T18:41:00
2018-04-29T18:41:00
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,009
cpp
main.cpp
#define _CRT_SECURE_NO_WARNINGS #include <algorithm> #include <fstream> #include <list> #include <map> #include <numeric> #include <set> #include <sstream> #include <string> #include <vector> #include <queue> #include <iostream> #include <iomanip> #include <array> #include <cmath> #include <limits> #include <cassert> #include <math.h> #include <memory.h> //#pragma comment(linker, "/STACK:134217728") using namespace std; using namespace tr1; #define all(c) (c).begin(), (c).end() #define CLEAR(x) memset(x,0,sizeof x) typedef long long ll; typedef unsigned long long ull; ll gcd(ll a, ll b) { if (b == 0) return a; return gcd(b, a%b); } ll findLCM(vector<int>& vec) { ll ans = vec[0]; for (ll i = 1; i < vec.size(); i++) ans = (((vec[i] * ans)) / (gcd(vec[i], ans))); return ans; } void solve(ll test) { printf("Case #%d: ", test + 1); ll B, N; cin >> B; cin >> N; int minT = 100000; int newMinT = 100000; vector<int> m(B); for (int i = 0; i < B; ++i) { cin >> m[i]; minT = min(minT, m[i]); } ll processed = 0; ll lcm = findLCM(m); for (int i = 0; i < B; ++i) { processed += lcm / m[i]; } N = N % processed; if (N == 0) { printf("%d\n", B); return; } vector<int> q(B); int lastI = -1; while (N > 0) { // place people for (ll i = 0; i < B && N>0; ++i) { if (q[i] == 0) { q[i] = m[i]; --N; lastI = i; } } // make haircut newMinT = 100000; for (int i = 0; i < B; ++i) { q[i] = q[i] - minT; newMinT = min(newMinT, q[i]); } minT = newMinT; } printf("%d\n", lastI+1); } int main() { freopen("input.txt", "r", stdin); freopen("output.txt", "w", stdout); int tests; scanf("%d", &tests); for (int test = 0; test < tests; ++test) { fprintf(stderr, "Solving %d/%d\n", test + 1, tests); solve(test); } return 0; }
bf3ceeb9490fc9fdb26db949be8938c281aac071
0a7c429c78853d865ff19f2a75f26690b8e61b9c
/Images/Algorithms/Grayscale.h
3f2eb25e04e1adc9aba214f8f7e9288ee0568553
[]
no_license
perryiv/cadkit
2a896c569b1b66ea995000773f3e392c0936c5c0
723db8ac4802dd8d83ca23f058b3e8ba9e603f1a
refs/heads/master
2020-04-06T07:43:30.169164
2018-11-13T03:58:57
2018-11-13T03:58:57
157,283,008
2
2
null
null
null
null
UTF-8
C++
false
false
2,330
h
Grayscale.h
/////////////////////////////////////////////////////////////////////////////// // // Copyright (c) 2005, Adam Kubach // All rights reserved. // BSD License: http://www.opensource.org/licenses/bsd-license.html // /////////////////////////////////////////////////////////////////////////////// #ifndef __IMAGES_GRAYSCALE_H__ #define __IMAGES_GRAYSCALE_H__ #include "usul/Exceptions/Thrower.h" #include <algorithm> #include <numeric> namespace Images { namespace Algorithms { /////////////////////////////////////////////////////////////////////////////// // // Convert the image to grayscale. Changes the pixel values in place, and // returns the end of the valid values. // /////////////////////////////////////////////////////////////////////////////// template < class Channels > void grayScale ( bool hasAlpha, Channels &channels ) { typedef typename Channels::value_type Channel; // Handle trivial case. if ( channels.empty() ) return; // Needed below. const unsigned int size ( channels.at(0).size() ); // RGBA if ( true == hasAlpha && 4 == channels.size() ) { // Get shortcuts to the channels. Channel &c0 ( channels.at(0) ); Channel &c1 ( channels.at(1) ); Channel &c2 ( channels.at(2) ); Channel &c3 ( channels.at(3) ); // Make sure they are the proper size. c0.resize ( size ); c1.resize ( size ); c2.resize ( size ); c3.resize ( size ); // Loop through the values. for ( unsigned int i = 0; i < size; ++i ) { // Red gets average color. c0[i] = ( c0[i] + c1[i] + c2[i] ) / 3; // Assign alpha. c1[i] = c3[i]; } // Now resize. channels.resize ( 2 ); } // RGB else if ( false == hasAlpha && 3 == channels.size() ) { // Get shortcuts to the channels. Channel &c0 ( channels.at(0) ); Channel &c1 ( channels.at(1) ); Channel &c2 ( channels.at(2) ); // Make sure they are the proper size. c0.resize ( size ); c1.resize ( size ); c2.resize ( size ); // Loop through the values. for ( unsigned int i = 0; i < size; ++i ) { // Red gets average color. c0[i] = ( c0[i] + c1[i] + c2[i] ) / 3; } // Now resize. channels.resize ( 1 ); } } } // namespace Algorithms } // namespace Images #endif // __IMAGES_GRAYSCALE_H__
989d0a2ca3b725b8d0f48f205b8270b1d9b558cd
f1ce39f9e7a3534fcba8c7c6be64700f069eb70b
/RFID/SerialCommApp.h
ce3be3c02095d79cdc8d203c8996ddb21e1acd6e
[ "MIT" ]
permissive
JohnAgapeyev/COMP3980A3
2289413c9d0f127d878fff13c739d74c986b484f
681880c37154e99f25c3c6cbaccc6f772eac4e7f
refs/heads/master
2021-01-19T02:10:56.611363
2016-11-16T00:53:53
2016-11-16T00:53:53
73,436,464
0
0
null
null
null
null
UTF-8
C++
false
false
1,736
h
SerialCommApp.h
#pragma once #define _CRT_SECURE_NO_WARNINGS #include <Windows.h> #include <string> #include <sstream> #include "SerialCommPort.h" using std::string; class SerialCommApp { public: SerialCommApp(); void setConnect(HWND); void setDisconnect(); HWND getConnectButton(); HWND getDisconnectButton(); SerialCommPort * getSerialCommPort(); void repaintWindow(HWND hwnd); void init(HWND); void processKeyboardInput(HWND, UINT, WPARAM); LPCSTR processComConfigSettings(HWND hwnd, WPARAM wParam); private: BOOL createUIWindows(HWND hwnd); void displayChar(HWND hwnd, WPARAM wParam); void processChar(HWND hwnd, WPARAM wParam); void writeInputCharToComPort(HWND hwnd, WPARAM wParam); void displayErrorMessageBox(LPCTSTR text); //DATA MEMBERS static const DWORD BUFF_SIZE = 256; static const DWORD TEXTBOX_HEIGTH = 200; static const DWORD TEXTBOX_WIDTH = 400; static const DWORD USERINPUT_TEXTBOX_START_X = 190; static const DWORD USERINPUT_TEXTBOX_START_Y = 10; static const DWORD READINPUT_TEXTBOX_START_X = 190; static const DWORD READINPUT_TEXTBOX_START_Y = 220; static const DWORD BUTTON_WIDTH = 100; static const DWORD BUTTON_HEIGHT = 30; static const DWORD DISCONNECT_BUTTON_X = 50; static const DWORD DISCONNECT_BUTTON_Y = 150; static const DWORD CONNECT_BUTTON_X = 50; static const DWORD CONNECT_BUTTON_Y = 250; SerialCommPort serialCommPort; HDC hdc; TEXTMETRIC tm; HWND userInputTextBox; HWND readInputTextBox; HWND hConnectButton; HWND hDisconnectButton; HWND hComConfigsButton; int char_pos_userInputTextBox[2]; char input[BUFF_SIZE]; char inputStr[BUFF_SIZE]; };
d8119f3207f02cdaa3d57f4498c2eb8b826e83c0
6dcda687bc386b58c6391d150a3816adf43c7cea
/SDK/Vanas_AnimBlueprint_classes.h
2d796e2c11e24eccf928c4e0cfbc23f16a9e8b6d
[]
no_license
firebiteLR/PavlovVR-SDK
813f49c03140c46c318cae15fd5a03be77a80c05
0d31dec9aa671f0e9a2fbc37a9be34a9854e06a4
refs/heads/master
2023-07-23T11:28:43.963982
2021-02-18T15:06:38
2021-02-18T15:06:38
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,202
h
Vanas_AnimBlueprint_classes.h
#pragma once // Name: , Version: 1.0.0 #ifdef _MSC_VER #pragma pack(push, 0x8) #endif namespace SDK { //--------------------------------------------------------------------------- // Classes //--------------------------------------------------------------------------- // AnimBlueprintGeneratedClass Vanas_AnimBlueprint.Vanas_AnimBlueprint_C // 0x0718 (0x0B58 - 0x0440) class UVanas_AnimBlueprint_C : public UVRGunAnimInstance { public: struct FPointerToUberGraphFrame UberGraphFrame; // 0x0440(0x0008) (ZeroConstructor, Transient, DuplicateTransient) struct FAnimNode_Root AnimGraphNode_Root_8D2297A8483A4DBB2F5E338E4F6D59B7; // 0x0448(0x0040) struct FAnimNode_ConvertLocalToComponentSpace AnimGraphNode_LocalToComponentSpace_235738164811373A13D23D9121D50E74;// 0x0488(0x0040) struct FAnimNode_RefPose AnimGraphNode_LocalRefPose_E5AB933944A17236DCFB9A8282B482E2;// 0x04C8(0x0038) struct FAnimNode_ModifyBone AnimGraphNode_ModifyBone_2B27560D4E49996141680F8079286813;// 0x0500(0x0138) struct FAnimNode_ConvertComponentToLocalSpace AnimGraphNode_ComponentToLocalSpace_E48FDF64464A61E0928CC7B08F37E1DA;// 0x0638(0x0040) struct FAnimNode_ModifyBone AnimGraphNode_ModifyBone_74BFBF0C468047A03700698DBC4A7A30;// 0x0678(0x0138) struct FAnimNode_ModifyBone AnimGraphNode_ModifyBone_5397B45B409E88305D543F856E0B88A2;// 0x07B0(0x0138) struct FAnimNode_ModifyBone AnimGraphNode_ModifyBone_98E6982A4CBC33BD0739A2950879FB12;// 0x08E8(0x0138) struct FAnimNode_ModifyBone AnimGraphNode_ModifyBone_BC78D8C943C1D42C613F0AB4D24D4543;// 0x0A20(0x0138) static UClass* StaticClass() { static auto ptr = UObject::FindClass("AnimBlueprintGeneratedClass Vanas_AnimBlueprint.Vanas_AnimBlueprint_C"); return ptr; } void EvaluateGraphExposedInputs_ExecuteUbergraph_Vanas_AnimBlueprint_AnimGraphNode_ModifyBone_5397B45B409E88305D543F856E0B88A2(); void ExecuteUbergraph_Vanas_AnimBlueprint(int EntryPoint); }; } #ifdef _MSC_VER #pragma pack(pop) #endif
ce13e488a137e0b99fa414458892338602929a9b
2053e0ec782db1f74eba0c210fcc3ab381e7f152
/leetcode/695maxareaOfIsland.cpp
f3cd8a8827d39653d3360ee393d01b7b422546c4
[]
no_license
danielsamfdo/codingAlgo
86d18b0265c4f5edb323d01ac52f24a2b88599d4
0a8e5b67d814ddedcb604f4588e6d959c8958c0b
refs/heads/master
2021-05-15T10:46:18.941263
2017-11-01T02:42:40
2017-11-01T02:42:40
108,208,650
0
0
null
null
null
null
UTF-8
C++
false
false
962
cpp
695maxareaOfIsland.cpp
//https://leetcode.com/problems/max-area-of-island/description/ class Solution { public: int MARKER = -1; void dfs(vector<vector<int>>& grid, int i, int j, int &cnt, int &maxans){ if(i<0 || i>=grid.size() || j<0 || j>=grid[i].size()|| grid[i][j]!=1 ) return; if(grid[i][j]==1){ grid[i][j]=-1; cnt+=1; maxans = max(maxans,cnt); vector<int> posx = {-1,0,0,1}; vector<int> posy = {0,-1,1,0}; for(int k=0;k<posx.size();k++){ dfs(grid,posx[k]+i,posy[k]+j,cnt,maxans); } } } int maxAreaOfIsland(vector<vector<int>>& grid) { int maxans = 0; for(int i=0;i<grid.size();i++){ for(int j=0;j<grid[i].size();j++){ int cnt=0; if(grid[i][j]==1) dfs(grid,i,j,cnt,maxans); } } return maxans; } };
99623e6cf8d5456d0db5a85814d41cc3fbb35f42
b5c32572e3551214734aa81244939973f91da1c5
/Plutonium_v2/Plutonium/Source/pu/ui/ui_Dialog.cpp
01eabf1a4448192aa60fd994ff89f9f6798d5154
[ "MIT" ]
permissive
wetor/ONS-Switch-GUI
16cd251b00de89f3280854bceba824d8ac5d384f
536e247a2d97c06e14575a48cfd9d792a6156839
refs/heads/master
2021-08-07T08:15:29.479803
2021-07-03T05:51:27
2021-07-03T05:51:27
185,741,318
4
2
null
null
null
null
UTF-8
C++
false
false
9,984
cpp
ui_Dialog.cpp
#include <pu/ui/ui_Dialog.hpp> #include <pu/ui/ui_Application.hpp> #include <cmath> namespace pu::ui { Dialog::Dialog(String Title, String Content) { this->tfont = render::LoadDefaultFont(30); this->cfont = render::LoadDefaultFont(20); this->ofont = render::LoadDefaultFont(18); this->stitle = Title; this->scnt = Content; this->title = render::RenderText(this->tfont, Title, { 10, 10, 10, 255 }); this->cnt = render::RenderText(this->cfont, Content, { 20, 20, 20, 255 }); this->osel = 0; this->prevosel = 0; this->selfact = 255; this->pselfact = 0; this->hicon = false; this->cancel = false; this->hcancel = false; } Dialog::~Dialog() { if(this->title != NULL) { render::DeleteTexture(this->title); this->title = NULL; } if(this->cnt != NULL) { render::DeleteTexture(this->cnt); this->cnt = NULL; } if(this->hicon && (this->icon != NULL)) { render::DeleteTexture(this->icon); this->icon = NULL; this->hicon = false; } for(auto &opt: this->opts) render::DeleteTexture(opt); } void Dialog::AddOption(String Name) { this->opts.push_back(render::RenderText(this->ofont, Name, { 10, 10, 10, 255 })); this->sopts.push_back(Name); } void Dialog::SetCancelOption(String Name) { this->hcancel = true; this->scancel = Name; } void Dialog::RemoveCancelOption() { this->hcancel = false; this->scancel = ""; } bool Dialog::HasCancelOption() { return this->hcancel; } void Dialog::SetIcon(std::string Icon) { if(this->hicon) render::DeleteTexture(this->icon); this->icon = render::LoadImage(Icon); this->hicon = true; } bool Dialog::Hasicon() { return this->hicon; } s32 Dialog::Show(render::Renderer::Ref &Drawer, void *App) { if(this->hcancel) this->AddOption(this->scancel); if(this->opts.empty()) return 0; s32 dw = (20 * (this->opts.size() - 1)) + 250; for(s32 i = 0; i < this->opts.size(); i++) { s32 tw = render::GetTextWidth(this->ofont, this->sopts[i]); dw += tw + 20; } if(dw > 1280) dw = 1280; s32 icm = 30; s32 elemh = 60; s32 tdw = render::GetTextWidth(this->cfont, this->scnt) + 90; if(tdw > dw) dw = tdw; tdw = render::GetTextWidth(this->tfont, this->stitle) + 90; if(tdw > dw) dw = tdw; s32 ely = render::GetTextHeight(this->tfont, this->stitle) + render::GetTextHeight(this->cfont, this->scnt) + 140; if(this->hicon) { s32 tely = render::GetTextureHeight(this->icon) + icm + 25; if(tely > ely) ely = tely; tdw = render::GetTextWidth(this->cfont, this->scnt) + 90 + render::GetTextureWidth(this->icon) + 20; if(tdw > dw) dw = tdw; tdw = render::GetTextWidth(this->tfont, this->stitle) + 90 + render::GetTextureWidth(this->icon) + 20; if(tdw > dw) dw = tdw; } if(dw > 1280) dw = 1280; s32 dh = ely + elemh + 30; if(dh > 720) dh = 720; s32 dx = (1280 - dw) / 2; s32 dy = (720 - dh) / 2; ely += dy; s32 elemw = ((dw - (20 * (this->opts.size() + 1))) / this->opts.size()); s32 elx = dx + ((dw - ((elemw * this->opts.size()) + (20 * (this->opts.size() - 1)))) / 2); s32 r = 35; s32 nr = 180; s32 ng = 180; s32 nb = 200; bool end = false; s32 initfact = 0; while(true) { bool ok = ((Application*)App)->CallForRenderWithRenderOver([&](render::Renderer::Ref &Drawer) -> bool { u64 k = hidKeysDown(CONTROLLER_P1_AUTO); u64 h = hidKeysHeld(CONTROLLER_P1_AUTO); if((k & KEY_DLEFT) || (k & KEY_LSTICK_LEFT) || (h & KEY_RSTICK_LEFT)) { if(this->osel > 0) { this->prevosel = this->osel; this->osel--; for(s32 i = 0; i < this->opts.size(); i++) { if(i == this->osel) this->selfact = 0; else if(i == this->prevosel) this->pselfact = 255; } } } else if((k & KEY_DRIGHT) || (k & KEY_LSTICK_RIGHT) || (h & KEY_RSTICK_RIGHT)) { if(this->osel < (this->opts.size() - 1)) { this->prevosel = this->osel; this->osel++; for(s32 i = 0; i < this->opts.size(); i++) { if(i == this->osel) this->selfact = 0; else if(i == this->prevosel) this->pselfact = 255; } } } else if(k & KEY_A) { this->cancel = false; end = true; } else if(k & KEY_B) { this->cancel = true; end = true; } else if(hidKeysDown(CONTROLLER_HANDHELD) & KEY_TOUCH) { touchPosition tch; hidTouchRead(&tch, 0); for(s32 i = 0; i < this->opts.size(); i++) { String txt = this->sopts[i]; s32 rx = elx + ((elemw + 20) * i); s32 ry = ely; if(((rx + elemw) > tch.px) && (tch.px > rx) && ((ry + elemh) > tch.py) && (tch.py > ry)) { this->osel = i; this->cancel = false; end = true; } } } s32 bw = dw; s32 bh = dh; s32 fw = bw - (r * 2); s32 fh = bh - (r * 2); Color clr = { 225, 225, 225, initfact }; s32 aclr = initfact; if(aclr < 0) aclr = 0; if(aclr > 125) aclr = 125; Drawer->RenderRectangleFill({ 0, 0, 0, (u8)aclr }, 0, 0, 1280, 720); Drawer->RenderRoundedRectangleFill(clr, dx, dy, bw, bh, r); render::SetAlphaValue(this->title, initfact); render::SetAlphaValue(this->cnt, initfact); Drawer->RenderTexture(this->title, (dx + 45), (dy + 55)); Drawer->RenderTexture(this->cnt, (dx + 45), (dy + 140)); if(this->hicon) { s32 icw = render::GetTextureWidth(this->icon); s32 icx = dx + (dw - (icw + icm)); s32 icy = dy + icm; Drawer->RenderTexture(this->icon, icx, icy, initfact); } for(s32 i = 0; i < this->opts.size(); i++) { String txt = this->sopts[i]; s32 tw = render::GetTextWidth(this->ofont, txt); s32 th = render::GetTextHeight(this->ofont, txt); s32 tx = elx + ((elemw - tw) / 2) + ((elemw + 20) * i); s32 ty = ely + ((elemh - th) / 2); s32 rx = elx + ((elemw + 20) * i); s32 ry = ely; s32 rr = (elemh / 2); Color dclr = { nr, ng, nb, initfact }; if(this->osel == i) { if(this->selfact < 255) { dclr = { nr, ng, nb, this->selfact }; Drawer->RenderRoundedRectangleFill(dclr, rx, ry, elemw, elemh, rr); this->selfact += 48; } else { dclr = { nr, ng, nb, initfact }; Drawer->RenderRoundedRectangleFill(dclr, rx, ry, elemw, elemh, rr); } } else if(this->prevosel == i) { if(this->pselfact > 0) { dclr = { nr, ng, nb, this->pselfact }; Drawer->RenderRoundedRectangleFill(dclr, rx, ry, elemw, elemh, rr); this->pselfact -= 48; } } render::SetAlphaValue(this->opts[i], initfact); Drawer->RenderTexture(this->opts[i], tx, ty); } if(end) { if(initfact == 0) return false; if(initfact > 0) initfact -= 25; if(initfact < 0) initfact = 0; } else { if(initfact < 255) initfact += 25; if(initfact > 255) initfact = 255; } return true; }); if(!ok) { ((Application*)App)->CallForRenderWithRenderOver([&](render::Renderer::Ref &Drawer) -> bool {}); break; } } return this->osel; } bool Dialog::UserCancelled() { return this->cancel; } bool Dialog::IsOk() { bool ok = true; if(this->cancel) ok = false; if(this->hcancel && (this->osel == (this->opts.size() - 1))) ok = false; return ok; } }
a3329796f08550993a0f14c5cc3c4f5a425ef32c
c8fc4407862b838f1f1a94482338da5abeaca983
/rtree/rtree.cpp
705ebc64b21c1b61a5f7911e516c04962702c66f
[]
no_license
yyaoyu/Reverse_TopK
d075223fe82f48ed0308c587c5db39279c17f36a
70967a72170bd52f9836c94b9174f1b9726270ab
refs/heads/master
2022-03-28T14:25:49.853625
2017-11-05T09:03:59
2017-11-05T09:03:59
null
0
0
null
null
null
null
GB18030
C++
false
false
121,173
cpp
rtree.cpp
/*rtree.cpp this file implements the RTree class*/ // switch to turn on/off debugging information //#define FILE_DEBUG // output to files. #define CMD_DEBUG // output to the screen. #define _CRTDBG_MAP_ALLOC #include<stdlib.h> #include<crtdbg.h> #include <vector> #include <math.h> #include <float.h> #include <string> #include "rtree.h" #include "entry.h" #include "rtnode.h" #include "../blockfile/cache.h" #include "../blockfile/blk_file.h" #include "../linlist/linlist.h" #include "../heap/heap.h" #include "../func/matlabEngine.h" #include <algorithm> #include <fstream> #include <iostream> #include <iomanip> #include <queue> #include <time.h> using namespace std; //#include <afxwin.h> extern string rslt_fname; //------------------------------------------------------------ RTree::RTree(char *fname, int _b_length, Cache *c, int _dimension) //use this constructor to build a new tree { file = new BlockFile(fname, _b_length); cache = c; re_data_cands = new LinList(); deletelist = new LinList(); dimension = _dimension; root = 0; root_ptr = NULL; root_is_data = TRUE; num_of_data = num_of_inodes = num_of_dnodes = 0; root_ptr = new RTNode(this); //note that when a tree is constructed, the root is automatically created //though at this time there is no entry in the root yet. num_of_dnodes++; root_ptr->level = 0; root = root_ptr->block; } //------------------------------------------------------------ RTree::RTree(char *fname, Cache *c) //use this constructor to restore a tree from a file { int j; file = new BlockFile(fname, 0); cache = c; re_data_cands = new LinList(); deletelist = new LinList(); char *header = new char[file->get_blocklength()]; file->read_header(header); read_header(header); delete[] header; root_ptr = NULL; } //------------------------------------------------------------ RTree::RTree(char *inpname, char *fname, int _b_length, Cache *c, int _dimension) // construct new R-tree from a specified input textfile with rectangles { Entry *d; FILE *fp; file = new BlockFile(fname, _b_length); cache = c; re_data_cands = new LinList(); deletelist = new LinList(); /* char *header = new char [file->get_blocklength()]; read_header(header); delete [] header; */ dimension = _dimension; root = 0; root_ptr = NULL; root_is_data = TRUE; num_of_data = num_of_inodes = num_of_dnodes = 0; root_ptr = new RTNode(this); num_of_dnodes++; root_ptr->level = 0; root = root_ptr->block; int record_count = 0; if ((fp = fopen(inpname, "r")) == NULL) { delete this; error("Cannot open R-Tree text file", TRUE); } else { int id = 0; long type; float x0, y0, x1, y1; while (!feof(fp)) { record_count++; //id ++; //disable this variable if the id comes with the dataset if (record_count % 100 == 0) { for (int i = 0; i < 79; i++) //clear a line printf("\b"); printf("inserting object %d", record_count); } fscanf(fp, "%d ", &id); d = new Entry(dimension, NULL); d->son = id; for (int i = 0; i<dimension; i++) { //fscanf(fp, "%f %f ", &(d->bounces[2*i]), &(d->bounces[2*i+1])); fscanf(fp, "%f ", &(d->bounces[2 * i])); d->bounces[2 * i + 1] = d->bounces[2 * i]; } d->type = -1; insert(d); //d will be deleted in insert() } } fclose(fp); printf("\n"); // AfxMessageBox(_T("OK")); printf("This R-Tree contains %d internal, %d data nodes and %d data\n", num_of_inodes, num_of_dnodes, num_of_data); delete root_ptr; root_ptr = NULL; } /* RTree::RTree(vector<CInfoPoint> points, char *trname, int _blength, Cache* c, int _dimension) //construct a new tree from the vector "points" { FILE* f; Entry *d; file = new BlockFile(trname, _blength); cache =c; re_data_cands = new LinList(); deletelist = new LinList(); char *header = new char [file->get_blocklength()]; read_header(header); delete [] header; dimension = _dimension; root = 0; root_ptr = NULL; root_is_data = TRUE; num_of_data = num_of_inodes = num_of_dnodes = 0; root_ptr = new RTNode(this); num_of_dnodes++; root_ptr -> level = 0; root = root_ptr->block; int record_count = 0; if(points.empty()) { delete this; error("There is no data in vector!", TRUE); } else { int id=0; //float x0,y0,x1,y1; vector<CInfoPoint>::iterator pos; for (pos = points.begin();pos != points.end(); ++pos) { record_count ++; if (record_count%100 == 0) { CWnd* processBar = ::AfxGetMainWnd()->GetWindow(GW_CHILD)->GetWindow(GW_CHILD); processBar->SendMessage(WM_SET_PROGRESS, record_count, points.size()); } d = new Entry(dimension, NULL); d -> son = pos->id; d->type=pos->type; for(int i = 0; i < dimension; i++) { d->bounces[i] = pos->x; d->bounces[i+dimension] = pos->y; } insert(d); //d will be deleted in insert() } } // fclose(fp); //test for(int i = 0; i < 10; i++) na[i] = 0; delete root_ptr; root_ptr = NULL; } */ //------------------------------------------------------------ RTree::~RTree() { int j; char *header = new char[file->get_blocklength()]; write_header(header); file->set_header(header); delete[] header; if (root_ptr != NULL) { delete root_ptr; root_ptr = NULL; } if (cache) cache->flush(); delete file; delete re_data_cands; delete deletelist; // printf("This R-Tree contains %d internal, %d data nodes and %d data\n", // num_of_inodes, num_of_dnodes, num_of_data); } //------------------------------------------------------------ bool RTree::delete_entry(Entry *d) { load_root(); R_DELETE del_ret; del_ret = root_ptr->delete_entry(d); if (del_ret == NOTFOUND) return false; if (del_ret == ERASED) error("RTree::delete_entry--The root has been deleted\n", true); if (root_ptr->level > 0 && root_ptr->num_entries == 1) //there is only one entry in the root but the root //is not leaf. in this case, the child of the root is exhalted to root { root = root_ptr->entries[0].son; delete root_ptr; root_ptr = NULL; load_root(); num_of_inodes--; } num_of_data--; //Now will reinsert the entries while (deletelist->get_num() > 0) { Linkable *e; e = deletelist->get_first(); Entry *new_e = new Entry(dimension, NULL); new_e->set_from_Linkable(e); deletelist->erase(); insert(new_e); num_of_data--; } delete root_ptr; root_ptr = NULL; return true; } //------------------------------------------------------------ bool RTree::FindLeaf(Entry *e) { load_root(); return root_ptr->FindLeaf(e); } //------------------------------------------------------------ void RTree::insert(Entry* d) { int i, j; RTNode *sn; RTNode *nroot_ptr; int nroot; Entry *de; R_OVERFLOW split_root; Entry *dc; float *nmbr; // load root into memory load_root(); // no overflow occured until now re_level = new bool[root_ptr->level + 1]; for (i = 0; i <= root_ptr->level; i++) re_level[i] = FALSE; // insert d into re_data_cands as the first entry to insert // make a copy of d because it should be erased later Linkable *new_link; new_link = d->gen_Linkable(); re_data_cands->insert(new_link); delete d; //we follow the convention that the entry will be deleted when insertion finishes j = -1; while (re_data_cands->get_num() > 0) { // first try to insert data, then directory entries Linkable *d_cand; d_cand = re_data_cands->get_first(); if (d_cand != NULL) { // since "erase" deletes the data itself from the // list, we should make a copy of the data before // erasing it dc = new Entry(dimension, NULL); dc->set_from_Linkable(d_cand); re_data_cands->erase(); // start recursive insert with root split_root = root_ptr->insert(dc, &sn);//error here! type in root_ptr doesn't changed } else error("RTree::insert: inconsistent list re_data_cands", TRUE); if (split_root == SPLIT) // insert has lead to split --> new root-page with two sons (i.e. root and sn) { nroot_ptr = new RTNode(this); nroot_ptr->level = root_ptr->level + 1; num_of_inodes++; nroot = nroot_ptr->block; de = new Entry(dimension, this); nmbr = root_ptr->get_mbr(); memcpy(de->bounces, nmbr, 2 * dimension*sizeof(float)); delete[] nmbr; de->son = root_ptr->block; de->son_ptr = root_ptr; nroot_ptr->enter(de); de = new Entry(dimension, this); nmbr = sn->get_mbr(); memcpy(de->bounces, nmbr, 2 * dimension*sizeof(float)); delete[] nmbr; de->son = sn->block; de->son_ptr = sn; nroot_ptr->enter(de); root = nroot; root_ptr = nroot_ptr; root_is_data = FALSE; } j++; } num_of_data++; delete[] re_level; delete root_ptr; root_ptr = NULL; } //------------------------------------------------------------ void RTree::load_root() { if (root_ptr == NULL) root_ptr = new RTNode(this, root); } //------------------------------------------------------------ void RTree::NNQuery(float *QueryPoint, SortedLinList *res) { float nearest_distanz; // load root node into main memory load_root(); nearest_distanz = MAXREAL; root_ptr->NNSearch(QueryPoint, res, &nearest_distanz); delete root_ptr; root_ptr = NULL; } //------------------------------------------------------------ void RTree::rangeQuery(float *mbr, SortedLinList *res) { load_root(); root_ptr->rangeQuery(mbr, res); delete root_ptr; root_ptr = NULL; } void RTree::rangeQuery(float * mbr, SortedLinList * res, long type) { load_root(); root_ptr->rangeQuery(mbr, res, type); delete root_ptr; root_ptr = NULL; } //------------------------------------------------------------ void RTree::read_header(char *buffer) { int i; memcpy(&dimension, buffer, sizeof(dimension)); i = sizeof(dimension); memcpy(&num_of_data, &buffer[i], sizeof(num_of_data)); i += sizeof(num_of_data); memcpy(&num_of_dnodes, &buffer[i], sizeof(num_of_dnodes)); i += sizeof(num_of_dnodes); memcpy(&num_of_inodes, &buffer[i], sizeof(num_of_inodes)); i += sizeof(num_of_inodes); memcpy(&root_is_data, &buffer[i], sizeof(root_is_data)); i += sizeof(root_is_data); memcpy(&root, &buffer[i], sizeof(root)); i += sizeof(root); } //------------------------------------------------------------ void RTree::write_header(char *buffer) { int i; memcpy(buffer, &dimension, sizeof(dimension)); i = sizeof(dimension); memcpy(&buffer[i], &num_of_data, sizeof(num_of_data)); i += sizeof(num_of_data); memcpy(&buffer[i], &num_of_dnodes, sizeof(num_of_dnodes)); i += sizeof(num_of_dnodes); memcpy(&buffer[i], &num_of_inodes, sizeof(num_of_inodes)); i += sizeof(num_of_inodes); memcpy(&buffer[i], &root_is_data, sizeof(root_is_data)); i += sizeof(root_is_data); memcpy(&buffer[i], &root, sizeof(root)); i += sizeof(root); } /***************************************************************** this function gets the score of an entry with respect to a linear preference function para: e: the leaf entry weight: the prefrence vector dimension: dimensionality *****************************************************************/ float RTree::get_score_linear(Entry *_e, float *_weight, int _dimension) { float max_score = -MAXREAL; //this is the score to be returned // float *tuple=new float[dimension]; //this is the instantiation //of a tuple (from one of the cornor points of the MBR) //decide the final counter when the for loop ends------------- float end_cnt = 1; for (int k = 0; k<_dimension; k++) end_cnt *= 2; //now we implement a for loop with dimension layers----------- for (int i = 0; i<end_cnt; i++) { //now instantiate the tuple and get its score------------- int modseed = 1; float score = 0; for (int j = 0; j<_dimension; j++) { int sub = i / modseed % 2; // tuple[j]=_e[2*j+sub]; score += _e->bounces[2 * j + sub] * _weight[j]; modseed *= 2; } //update the max_score if necessary----------------------- if (score>max_score) max_score = score; //-------------------------------------------------------- } //------------------------------------------------------------ // delete [] tuple; return max_score; } float RTree::get_score_linear(float *_mbr, float *_weight, int _dimension) { float max_score = -MAXREAL; //this is the score to be returned // float *tuple=new float[dimension]; //this is the instantiation //of a tuple (from one of the cornor points of the MBR) //decide the final counter when the for loop ends------------- float end_cnt = 1; for (int k = 0; k<_dimension; k++) end_cnt *= 2; //now we implement a for loop with dimension layers----------- for (int i = 0; i<end_cnt; i++) { //now instantiate the tuple and get its score------------- int modseed = 1; float score = 0; for (int j = 0; j<_dimension; j++) { int sub = i / modseed % 2; // tuple[j]=_e[2*j+sub]; score += _mbr[2 * j + sub] * _weight[j]; modseed *= 2; } //update the max_score if necessary----------------------- if (score>max_score) max_score = score; //-------------------------------------------------------- } //------------------------------------------------------------ // delete [] tuple; return max_score; } float RTree::get_score_linear(Entry *_e, float *_weight, int _dimension, float SCORE_FUNC(const float *, const float *, int)) { float max_score = -MAXREAL; //this is the score to be returned float *tuple = new float[dimension]; //this is the instantiation //of a tuple (from one of the cornor points of the MBR) //decide the final counter when the for loop ends------------- float end_cnt = 1; for (int k = 0; k<_dimension; k++) end_cnt *= 2; //now we implement a for loop with dimension layers----------- for (int i = 0; i<end_cnt; i++) { //now instantiate the tuple and get its score------------- int modseed = 1; float score = 0; for (int j = 0; j<_dimension; j++) { int sub = i / modseed % 2; tuple[j] = _e->bounces[2 * j + sub]; modseed *= 2; } score = SCORE_FUNC(tuple, _weight, _dimension); //update the max_score if necessary----------------------- if (score>max_score) max_score = score; //-------------------------------------------------------- } //------------------------------------------------------------ delete[] tuple; return max_score; } /***************************************************************** this function gets the score range of an entry with respect to a linear preference function para: e: the leaf entry weight: the prefrence vector dimension: dimensionality range: the range returned *****************************************************************/ float RTree::get_score_range(Entry *_e, float *_weight, int _dimension, float *_range) { float max_score = -MAXREAL; //this is the score to be returned float min_score = MAXREAL; // float *tuple=new float[dimension]; //this is the instantiation //of a tuple (from one of the cornor points of the MBR) //decide the final counter when the for loop ends------------- float end_cnt = 1; for (int k = 0; k<_dimension; k++) end_cnt *= 2; //now we implement a for loop with dimension layers----------- for (int i = 0; i<end_cnt; i++) { //now instantiate the tuple and get its score------------- int modseed = 1; float score = 0; for (int j = 0; j<_dimension; j++) { int sub = i / modseed % 2; // tuple[j]=_e[2*j+sub]; score += _e->bounces[2 * j + sub] * _weight[j]; modseed *= 2; } //update the max/min_score if necessary------------------- if (score>max_score) max_score = score; if (score<min_score) min_score = score; //-------------------------------------------------------- } //------------------------------------------------------------ // delete [] tuple; _range[0] = min_score; _range[1] = max_score; return max_score; } /***************************************************************** this function performs a rank-inquiry query with linear function using the breadth-first search. para: weight: an array (with size equal to the dimensionality) storing the query vector qscore: the query score rslt: the link list storing the ids of the returned tuples (disabled for the time being) Coded by Yufei Tao 05/04/02 *****************************************************************/ void RTree::rank_qry_inquiry(float *_weight, float _qscore, int *_rslt) { //clear the node access summary----------------------------------- for (int i = 0; i<10; i++) na[i] = 0; //---------------------------------------------------------------- load_root(); root_ptr->rank_qry_inquiry(_weight, _qscore, _rslt); delete root_ptr; root_ptr = NULL; } /***************************************************************** this function performs a constrain ranked query with linear function using the breadth-first search. para: weight: an array (with size equal to the dimensionality) storing the query vector qmbr: the query mbr k: top "k" query hp: the heap for the breadth-first search rslt: the link list storing the ids of the returned tuples Coded by Yufei Tao 05/04/02 *****************************************************************/ void RTree::rank_qry_constr_linear(float *_weight, float *_qmbr, int _k, Heap *_hp, int *_rslt) { int found_cnt = 0; //clear the node access summary----------------------------------- for (int i = 0; i<10; i++) na[i] = 0; //---------------------------------------------------------------- //first insert the root into the heap------------------------- HeapEntry *he = new HeapEntry(); he->son1 = root; he->key = 0; he->level = 1; //this is not important but make sure it is greather than 0 _hp->insert(he); delete he; //------------------------------------------------------------ while (_hp->used>0) { //remove the top heap------------------------------------- HeapEntry *he = new HeapEntry(); _hp->remove(he); int son = he->son1; int level = he->level; delete he; //-------------------------------------------------------- if (level == 0) { _rslt[found_cnt] = son; found_cnt++; if (found_cnt == _k) return; } else //non-leaf entry { RTNode *child = new RTNode(this, son); for (int i = 0; i<child->num_entries; i++) { float *ovrp = overlapRect(dimension, child->entries[i].bounces, _qmbr); if (ovrp) { //evaluate the score of this entry---------------- //using the intersection area float score = get_score_linear(ovrp, _weight, dimension); delete[]ovrp; //now init a new heap entry----------------------- HeapEntry *he = new HeapEntry(); he->son1 = child->entries[i].son; he->level = child->level; he->key = -score; //since the heap sorts the entries in increasing order, //and we need to visit the entries by decreasing order //of their scores, we take the negative. _hp->insert(he); delete he; //------------------------------------------------ } } na[child->level]++; delete child; } } } /***************************************************************** this function performs a ranked query with linear function using the breadth-first search. para: weight: an array (with size equal to the dimensionality) storing the query vector k: top "k" query hp: the heap for the breadth-first search rslt: the link list storing the ids of the returned tuples Coded by Yufei Tao 20/03/02 *****************************************************************/ void RTree::rank_qry_linear(float *_weight, int _k, Heap *_hp, int *_rslt) { int found_cnt = 0; //clear the node access summary----------------------------------- for (int i = 0; i<10; i++) na[i] = 0; //---------------------------------------------------------------- //first insert the root into the heap------------------------- HeapEntry *he = new HeapEntry(); he->son1 = root; he->key = 0; he->level = 1; //this is not important but make sure it is greather than 0 _hp->insert(he); delete he; //------------------------------------------------------------ while (_hp->used>0) { //remove the top heap------------------------------------- HeapEntry *he = new HeapEntry(); _hp->remove(he); int son = he->son1; int level = he->level; delete he; //-------------------------------------------------------- if (level == 0) { _rslt[found_cnt] = son; found_cnt++; if (found_cnt == _k) return; } else { RTNode *child = new RTNode(this, son); for (int i = 0; i<child->num_entries; i++) { //evaluate the score of this entry---------------- float score = get_score_linear(&(child->entries[i]), _weight, dimension); //now init a new heap entry----------------------- HeapEntry *he = new HeapEntry(); he->son1 = child->entries[i].son; he->level = child->level; he->key = -score; //since the heap sorts the entries in increasing order, //and we need to visit the entries by decreasing order //of their scores, we take the negative. _hp->insert(he); delete he; //------------------------------------------------ } na[child->level]++; delete child; } } } /***************************************************************** this function performs a ranked query with a monotone function using the breadth-first search. para: weight: an array (with size equal to the dimensionality) storing the query vector k: top "k" query hp: the heap for the breadth-first search rslt: the link list storing the ids of the returned tuples SCORE_FUNC: the score function used to evaluate a tuple Coded by Yufei Tao 20/03/02 *****************************************************************/ void RTree::rank_qry_monotone(float *_weight, int _k, Heap *_hp, int *_rslt, float SCORE_FUNC(const float *, const float *, int)) { int found_cnt = 0; //clear the node access summary----------------------------------- for (int i = 0; i<10; i++) na[i] = 0; //---------------------------------------------------------------- //first insert the root into the heap------------------------- HeapEntry *he = new HeapEntry(); he->son1 = root; he->key = 0; he->level = 1; //this is not important but make sure it is greather than 0 _hp->insert(he); delete he; //------------------------------------------------------------ while (_hp->used>0) { //remove the top heap------------------------------------- HeapEntry *he = new HeapEntry(); _hp->remove(he); int son = he->son1; int level = he->level; delete he; //-------------------------------------------------------- if (level == 0) { _rslt[found_cnt] = son; found_cnt++; if (found_cnt == _k) return; } else { RTNode *child = new RTNode(this, son); for (int i = 0; i<child->num_entries; i++) { //evaluate the score of this entry---------------- float score = get_score_linear(&(child->entries[i]), _weight, dimension, SCORE_FUNC); //now init a new heap entry----------------------- HeapEntry *he = new HeapEntry(); he->son1 = child->entries[i].son; he->level = child->level; he->key = -score; //since the heap sorts the entries in increasing order, //and we need to visit the entries by decreasing order //of their scores, we take the negative. _hp->insert(he); delete he; //------------------------------------------------ } na[child->level]++; delete child; } } } /***************************************************************** this function performs a kNN search using the best-first algo. para: q: the query point k: top "k" query hp: the heap for the best-first search fardist: the farthest distance from the query to the k-th NN Coded by Yufei Tao 16/12/02 *****************************************************************/ /* Modified by Jeff, Dec 2006 */ /* void RTree::kNN(float *_q, int _k, Heap *_hp, float &fardist, vector<CInfoPoint>& _rslt,long query_type) { fardist=MAXREAL; int found_cnt=0; //clear the node access summary----------------------------------- for (int i=0; i<10; i++) na[i]=0; //---------------------------------------------------------------- //first insert the root into the heap------------------------- HeapEntry *he=new HeapEntry(); he->son1=root; he->key=0; he->father = -1; he->level=1; //this is not important but make sure it is greather than 0 he->init_HeapEntry(dimension); for (int j = 0; j < 2 * dimension; j ++) he->bounces[j] = 0.0; _hp->insert(he); // delete he; // ------------------------------------------------------------ while(_hp->used>0) { //remove the top heap------------------------------------- HeapEntry *he=new HeapEntry(); he->init_HeapEntry(dimension); //for (int j = 0; j < 2 * dimension; j ++) // he->bounces[j] = 0.0; _hp->remove(he); int son=he->son1; int level=he->level; if (level==0) fardist=he->key; // delete he; // -------------------------------------------------------- if (level==0) { RTNode *child=new RTNode(this, he->father); for(int i = 0; i < child->num_entries; i++) { if (child->entries[i].son == son) { if (query_type == -1) { CInfoPoint point; point.id = son; point.x = child->entries[i].bounces[0]; point.y = child->entries[i].bounces[dimension]; point.type = child->entries[i].type; _rslt.push_back(point); found_cnt++; break; } else if (query_type == child->entries[i].type) { CInfoPoint point; point.id = son; point.x = child->entries[i].bounces[0]; point.y = child->entries[i].bounces[dimension]; point.type = child->entries[i].type; _rslt.push_back(point); found_cnt++; break; } } } //_rslt.push_back(son); //found_cnt++; delete child; delete he; if (found_cnt==_k) return; } else { delete he; RTNode *child=new RTNode(this, son); for (int i=0; i<child->num_entries; i++) { //now init a new heap entry----------------------- HeapEntry *he=new HeapEntry(); he->son1=child->entries[i].son; he->level=child->level; he->key=MINDIST(_q, child->entries[i].bounces, dimension); he->father = son; he->init_HeapEntry(dimension); for (int j = 0; j < 2 * dimension; j ++) he->bounces[j] = 0.0; _hp->insert(he); delete he; //------------------------------------------------ } na[child->level]++; delete child; } } } */ ////////////////////////////////////////////////////////////////////////// // functions added for skyline ////////////////////////////////////////////////////////////////////////// //============================================================= // BBS for computing the skyline in a subspace // _hp: heap to be used // _rslt: result skyline list to be used // _active_dim: a boolean array whose size equals the dimensionality of the R-tree // the i-th element equals 'true' if the i-th dimension is involved in the subspace // this function was based on the bbs algorithm written by Greg, and later modified by yufei tao. // coded by yufei tao, may 2005 //============================================================= void RTree::bbs_subspace(Heap *_hp, float *_rslt, int &_rsltcnt, bool *_active_dim) { int i, j; _rsltcnt = 0; //first insert the root into the heap------------------------- _hp->used = 0; HeapEntry *he = new HeapEntry(); he->dim = dimension; he->son1 = root; he->key = 0; he->level = 1; //this is not important but make sure it is greather than 0 he->bounces = new float[2 * dimension]; for (j = 0; j < 2 * dimension; j++) he->bounces[j] = 0.0; _hp->insert(he); // delete he; //------------------------------------------------------------ while (_hp->used > 0) { //remove the top heap------------------------------------- // HeapEntry *he = new HeapEntry(); // he->init_HeapEntry(dimension); _hp->remove(he); int son = he->son1; int level = he->level; float *bounces = new float[dimension]; for (int i = 0; i < dimension; i++) { if (_active_dim[i]) bounces[i] = he->bounces[2 * i]; else bounces[i] = 0; } // delete he; //-------------------------------------------------------- if (level == 0) { if (!sky_dom(dimension, _rslt, _rsltcnt, bounces)) { memcpy(&_rslt[dimension * _rsltcnt], bounces, sizeof(float) * dimension); _rsltcnt++; } } else { if (!sky_dom(dimension, _rslt, _rsltcnt, bounces)) { RTNode *child = new RTNode(this, son); for (i = 0; i < child->num_entries; i++) { /* if (child -> level == 1) { int cnt = 0; for (j = 0; j < dimension; j ++) if (_active_dim[j]) { printf("dim: %d: [%.1f, %.1f]\n", cnt, child->entries[i].bounces[2 * j], child->entries[i].bounces[2 * j + 1]); cnt++; } printf("\n"); } */ float *b = new float[dimension]; for (j = 0; j < dimension; j++) { if (_active_dim[j]) b[j] = child->entries[i].bounces[2 * j]; else b[j] = 0; } if (!sky_dom(dimension, _rslt, _rsltcnt, b)) { //HeapEntry *he = new HeapEntry(); he->dim = dimension; he->son1 = child->entries[i].son; he->level = child->level; for (int j = 0; j < dimension; j++) if (_active_dim[j]) { he->key = b[j]; break; } //he->bounces = new float[2 * dimension]; for (j = 0; j < dimension; j++) he->bounces[2 * j] = b[j]; _hp->insert(he); //delete he; //------------------------------------------------ } delete[] b; } delete child; } } delete[] bounces; } return; } //============================================================= //this function checks whether the new point is dominated by any //skyline point already found //dim: //rslt: an array with size dim * rsltcnt. the first dim numbers capture // the coordinates of the first point, the next dim numbers for the // the next point, and so on. //rsltcnt: number of skyline points so far //pt: the point being tested //coded by yufei tao, may 2005 //============================================================= bool dominate(int _dim, float *_pt1, float *_pt2) { bool ret = true; for (int i = 0; i < _dim; i++) { if (_pt1[i] > _pt2[i]) { ret = false; break; } } return ret; } bool RTree::sky_dom(int _dim, float *_rslt, int _rsltcnt, float *_pt) { bool ret = false; for (int i = 0; i < _rsltcnt; i++) { float *s_pt = &_rslt[i * _dim]; if (dominate(_dim, s_pt, _pt)) { ret = true; break; } } return ret; } //============================================================= // BBS for computing the skyline // _hp: heap to be used // _rslt: result skyline list to be used // _rsltcnt: number of skyline points // this function was modified from the bbs_subspace algorithm written by yufei tao. // modified by Junfeng Hu, Sep 27, 2007 //============================================================= void RTree::bbs(Heap *_hp, float *_rslt, int &_rsltcnt) { int i, j; _rsltcnt = 0; //first insert the root into the heap------------------------- _hp->used = 0; HeapEntry *he = new HeapEntry(); he->dim = dimension; he->son1 = root; he->key = 0; he->level = 1; //this is not important but make sure it is greather than 0 he->bounces = new float[2 * dimension]; for (j = 0; j < 2 * dimension; j++) he->bounces[j] = 0.0; _hp->insert(he); while (_hp->used > 0) { //remove the top heap------------------------------------- _hp->remove(he); int son = he->son1; int level = he->level; float *bounces = new float[dimension]; for (int i = 0; i < dimension; i++) bounces[i] = he->bounces[2 * i]; if (level == 0) { if (!sky_dom(dimension, _rslt, _rsltcnt, bounces)) { memcpy(&_rslt[dimension * _rsltcnt], bounces, sizeof(float) * dimension); _rsltcnt++; } } else { if (!sky_dom(dimension, _rslt, _rsltcnt, bounces)) { RTNode *child = new RTNode(this, son); for (i = 0; i < child->num_entries; i++) { float *b = new float[dimension]; for (j = 0; j < dimension; j++) b[j] = child->entries[i].bounces[2 * j]; if (!sky_dom(dimension, _rslt, _rsltcnt, b)) { he->dim = dimension; he->son1 = child->entries[i].son; he->level = child->level; he->key = sky_mindist(dimension, b); for (j = 0; j < 2 * dimension; j++) he->bounces[j] = child->entries[i].bounces[j]; _hp->insert(he); } delete[] b; } delete child; } } delete[] bounces; } delete he; } float sky_mindist(int _dim, float *_bounces) { float ret = 0.0; for (int i = 0; i < _dim; i++) ret += _bounces[i]; return ret; } void RTree::bbs_topk(Heap *_hp, float *_rslt, int &_rsltcnt, float* _qry_pt, float* weighting, int k) { int i, j; _rsltcnt = 0; //first insert the root into the heap------------------------- _hp->used = 0; HeapEntry *he = new HeapEntry(); he->dim = dimension; he->son1 = root; he->key = 0; he->level = 1; //this is not important but make sure it is greather than 0 he->bounces = new float[2 * dimension]; for (j = 0; j < 2 * dimension; j++) he->bounces[j] = 0.0; _hp->insert(he); while (_hp->used > 0) { //remove the top heap------------------------------------- _hp->remove(he); int son = he->son1; int level = he->level; float *bounces = new float[dimension * 2]; for (int i = 0; i < 2 * dimension; i++) bounces[i] = he->bounces[i]; if (level == 0) { if (_rsltcnt < k) { memcpy(&_rslt[dimension * _rsltcnt], bounces, sizeof(float) * dimension); _rsltcnt++; } if (_rsltcnt == k) break; } else { RTNode *child = new RTNode(this, son); for (i = 0; i < child->num_entries; i++) { he->dim = dimension; he->son1 = child->entries[i].son; he->level = child->level; memcpy(he->bounces, child->entries[i].bounces, sizeof(float) * 2 * dimension); for (j = 0; j < dimension; j++) { he->key += weighting[j] * he->bounces[j]; } _hp->insert(he); } delete child; } delete[] bounces; } delete he; } //void RTree::bbs_topkth(Heap *_hp, float *_rslt, float* _qry_pt, float* weighting, int k) //{ // int i, j; // int _rsltcnt = 0; // // //first insert the root into the heap------------------------- // _hp->used=0; // HeapEntry *he=new HeapEntry(); // he->dim = dimension; // he->son1 = root; // he->key = 0; // he->level = 1; //this is not important but make sure it is greather than 0 // he->bounces = new float[2 * dimension]; // for (j = 0; j < 2 * dimension; j ++) // he->bounces[j] = 0.0; // _hp->insert(he); // // while(_hp->used > 0) // { // //remove the top heap------------------------------------- // // _hp->remove(he); // int son = he->son1; // int level = he->level; // float *bounces = new float[dimension*2]; // for (int i = 0; i < 2 *dimension; i ++) // bounces[i] = he->bounces[i]; // // if (level==0) // { // if ( _rsltcnt < k ) // { // //memcpy(&_rslt[dimension * _rsltcnt], bounces, sizeof(float) * dimension); // _rsltcnt ++; // } // // if (_rsltcnt == k) // { // memcpy(_rslt, bounces, sizeof(float) * dimension); // break; // } // } // else // { // RTNode *child = new RTNode(this, son); // // for (i = 0; i < child->num_entries; i ++) // { // he->dim = dimension; // he->son1 = child->entries[i].son; // he->level = child->level; // // memcpy(he->bounces, child->entries[i].bounces, sizeof(float)*2*dimension); // // for (j = 0; j < dimension; j ++) // { // he->key += weighting[j] * he->bounces[j]; // } // // _hp->insert(he); // } // delete child; // // } // delete [] bounces; // } // delete he; //} void RTree::bbs_topkth(Heap *_hp, float *_rslt, float* _qry_pt, float* weighting, int k) { int i, j; int _rsltcnt = 0; //first insert the root into the heap------------------------- _hp->used = 0; HeapEntry *he = new HeapEntry(); he->dim = dimension; he->son1 = root; he->key = 0; he->level = 1; //this is not important but make sure it is greather than 0 he->bounces = new float[2 * dimension]; for (j = 0; j < 2 * dimension; j++) he->bounces[j] = 0.0; _hp->insert(he); while (_hp->used > 0) { //remove the top heap------------------------------------- _hp->remove(he); int son = he->son1; int level = he->level; float *bounces = new float[dimension * 2]; for (int i = 0; i < 2 * dimension; i++) bounces[i] = he->bounces[i]; if (level == 0) { _rsltcnt++; if (_rsltcnt == k) { for (i = 0; i < dimension; i++) _rslt[i] = bounces[2 * i]; break; } } else { RTNode *child = new RTNode(this, son); for (i = 0; i < child->num_entries; i++) { he->dim = dimension; he->son1 = child->entries[i].son; he->level = child->level; he->key = 0; memcpy(he->bounces, child->entries[i].bounces, 2 * (sizeof(float)* dimension)); for (j = 0; j < dimension; j++) { he->key += weighting[j] * he->bounces[j * 2]; } _hp->insert(he); } delete child; } delete[] bounces; } delete he; } /* _rslt:不可比点集合 个数 查询点 一个矢量 在不可比的点集中,查询点在此向量下的rank。 ranking_querypoint + bedominatnum + 1 = 查询点在整个数据集中于此矢量下的rank */ void RTree::bbs_ranking_querypoint(float *_rslt, int &_rsltcnt, float* _qry_pt, float* weighting, int &ranking_querypoint)//_rslt是不可比点的数组,_rsltcnt是不可比点的个数,_qry_pt是查询点,weighting是目前样本权重集,ranking_querypoint是在这些不可比点中查询点的排名,最终返回给上层调用者 { int i, j; ranking_querypoint = 0; //--------------- //ofstream outfile(".\\rankingResult.txt"); //if(outfile.is_open() ) // cout<<"open"; // outfile<<"weighting: "<<weighting[0]<<" "<<weighting[1]<<" "<<weighting[2]<<endl; //outfile<<"_qry_pt: "<<_qry_pt[0]<<" "<<_qry_pt[1]<<" "<<_qry_pt[2]<<endl; float score_querypoint = 0.0, score_incompoint; for (j = 0; j < dimension; j++) { score_querypoint += weighting[j] * _qry_pt[j]; } //查询点在当前权重下的分数。 // outfile<<"score_querypoint: "<<score_querypoint<<endl; for (j = 0; j < _rsltcnt; j++) { score_incompoint = 0; for (i = 0; i < dimension; i++) { score_incompoint += weighting[i] * _rslt[j*dimension + i]; } /* outfile<<"_rslt[j*dimension]: "<<_rslt[j*dimension]<<" "<<_rslt[j*dimension+1]<<" "<<_rslt[j*dimension+2]<<endl; outfile<<"score_incompoint: "<<score_incompoint<<endl;*/ if (score_incompoint<score_querypoint) ranking_querypoint++; } } void RTree::traverse_points(Heap *_hp, float *_rslt, int &_rsltcnt, float* _qry_pt, int &bedominatnum) { int i, j; _rsltcnt = 0; bedominatnum = 0; //first insert the root into the heap------------------------- _hp->used = 0; HeapEntry *he = new HeapEntry(); he->dim = dimension; he->son1 = root; he->key = 0; he->level = 1; //this is not important but make sure it is greather than 0 he->bounces = new float[2 * dimension]; for (j = 0; j < 2 * dimension; j++) he->bounces[j] = 0.0; _hp->insert(he); ofstream outfile("allData.txt"); while (_hp->used > 0) { //remove the top heap------------------------------------- _hp->remove(he); int son = he->son1; int level = he->level; float *bounces_left = new float[dimension]; float *bounces_right = new float[dimension]; if (level == 0) { for (int i = 0; i < dimension; i++) { bounces_left[i] = he->bounces[i * 2]; bounces_right[i] = he->bounces[i * 2 + 1]; } outfile << bounces_left[0] << " " << bounces_left[1] << " " << bounces_left[2] << endl; } else { RTNode *child = new RTNode(this, son); for (i = 0; i < child->num_entries; i++) { he->dim = dimension; he->son1 = child->entries[i].son; he->level = child->level; memcpy(he->bounces, child->entries[i].bounces, 2 * (sizeof(float)* dimension)); he->key = 0; _hp->insert(he); } delete child; } delete[] bounces_left; delete[] bounces_right; } delete he; } /* hp: _rslt:不可比点的集合 _rsltcnt:不可比点的个数 _qry_pt:查询点 bedominatnum:求得的支配q点的点的个数 */ void RTree::incomparable_points(Heap *_hp, float *_rslt, int &_rsltcnt, float* _qry_pt, int &bedominatnum) { int i, j; _rsltcnt = 0; bedominatnum = 0; //first insert the root into the heap------------------------- _hp->used = 0; HeapEntry *he = new HeapEntry(); he->dim = dimension; he->son1 = root; he->key = 0; he->level = 1; //this is not important but make sure it is greather than 0 he->bounces = new float[2 * dimension]; //------------------------------------------------ memset(he->bounces, 0.0, 2 * dimension * sizeof(float)); /*for (j = 0; j < 2 * dimension; j ++) he->bounces[j] = 0.0;*/ //------------------------------------------------ _hp->insert(he); //ofstream outfile(".\\incmpResult.txt"); //outfile<<"_qry_pt "<<_qry_pt[0]<<" "<<_qry_pt[1]<<" "<<_qry_pt[2]<<endl; while (_hp->used > 0) { //remove the top heap------------------------------------- _hp->remove(he); int son = he->son1; int level = he->level; float *bounces_left = new float[dimension]; float *bounces_right = new float[dimension]; for (i = 0; i < dimension; i++) { bounces_left[i] = he->bounces[i * 2]; bounces_right[i] = he->bounces[i * 2 + 1]; } /* outfile<<"bounces_left "<<bounces_left[0]<<" "<<bounces_left[1]<<" "<<bounces_left[2]<<endl; outfile<<"bounces_right "<<bounces_right[0]<<" "<<bounces_right[1]<<" "<<bounces_right[2]<<endl;*/ if (level == 0) { if (dominate(dimension, bounces_right, _qry_pt))//if (!dominate(dimension, bounces_right, _qry_pt)&&!dominate(dimension,_qry_pt , bounces_left)) { bedominatnum++; } else if (!dominate(dimension, _qry_pt, bounces_left)) { memcpy(&_rslt[dimension * _rsltcnt], bounces_left, sizeof(float) * dimension); _rsltcnt++; } } else { if (!dominate(dimension, _qry_pt, bounces_left)) { RTNode *child = new RTNode(this, son); float *left = new float[dimension]; for (i = 0; i < child->num_entries; i++) { he->dim = dimension; he->son1 = child->entries[i].son; he->level = child->level; memcpy(he->bounces, child->entries[i].bounces, 2 * sizeof(float)* dimension); he->key = MINDIST(_qry_pt, child->entries[i].bounces, dimension); _hp->insert(he); } delete child; delete[] left; } } delete[] bounces_left; delete[] bounces_right; } delete he; } //对每个查询点找出why-not权重矢量,并把 notCount whynot矢量的个数 个矢量返回,要求查询点的rank 为ranks中的一个 /* * Description: 判断一个点是否满足条件:在权重向量中存在 count 个向量,使得该点是这些向量的第top-k' */ float* RTree::checkQueryPoint(Heap *_hp, float* _qry_pt, float* weightSet, int weightCount, int dimension, int missCnt, int* ranks, char* dataSetName) { int count = 0; int incomNum, bedominatnum, rank; float* incompPoints = new float[3000000]; float* whynWeightSet = new float[missCnt * dimension]; // 找出不可比的点集 incomparable_points(_hp, incompPoints, incomNum, _qry_pt, bedominatnum); //traverse_points( _hp, incompPoints, _rsltcnt, _qry_pt, bedominatnum); char qFileName[100]; memset(qFileName, '\0', 100); sprintf(qFileName, ".\\%d_%d_%s", *ranks, missCnt, dataSetName); ofstream outfile(qFileName, ios::app); outfile << "查询点: "; for (int qry_pos = 0; qry_pos < dimension; qry_pos++) outfile << _qry_pt[qry_pos] << '\t'; outfile << endl; //对一个矢量计算查询点的等级 for (int i = 3; i < weightCount; i++) { bbs_ranking_querypoint(incompPoints, incomNum, _qry_pt, &weightSet[i * dimension], rank); outfile << "weight: " << setw(12); for (int w_pos = 0; w_pos < dimension; w_pos++) outfile << weightSet[i * dimension + w_pos] << ' '; outfile << "\trank: " << rank + bedominatnum + 1 << endl; //如果查询点的rank 为所要求的,说明这个查询点满足 int drift = 3; if (ranks[count] == 11) drift = 0; if (rank + bedominatnum + 1 <= ranks[count] + drift && rank + bedominatnum + 1 >= ranks[count] - drift) { memcpy(&whynWeightSet[count * dimension], &weightSet[i * dimension], sizeof(float) * dimension); count++; // 若满足要求的向量个数和whynot的个数相同 if (count == missCnt) { for (int cnt = 0; cnt < count; cnt++) { outfile << "weight: "; for (int dim = 0; dim < dimension; dim++) outfile << " " << whynWeightSet[cnt * dimension + dim]; outfile << endl; } outfile << "-------------rank+bedominatnum+1:\t" << rank + bedominatnum + 1 << "---------------------" << endl; outfile << "--------------------------ranks[count] :\t" << ranks[count - 1] << "---------------------" << endl; outfile.close(); delete incompPoints; return whynWeightSet; } } } outfile << "--------------------------------------------------------------" << endl; outfile.close(); delete incompPoints; return NULL; } void RTree::SampleWeightsbyq(float quality_of_answer, float probability_guarantee, float *sample, float *quwey_lower, float *quwey_upper) { long samplesize; //int dimension = w_origin.weighting.size(); //srand ( time(NULL) ); samplesize = (long)(log(1 - probability_guarantee) / log(1 - quality_of_answer / 100)) + 1; for (int i = 0; i < samplesize; i++) { for (int j = 0; j < dimension; j++) { //==========真实数据集用==================================== /* int int_r = rand(); long base = RAND_MAX-1; float f_r = ((float) int_r) / base; float temp = (quwey_upper[j] - quwey_lower[j]) * f_r + quwey_lower[j];*/ //============================================= //=============================合成时用 float temp = (float)(quwey_lower[j] + rand() % (int)(quwey_upper[j] - quwey_lower[j] + 1)); sample[i*dimension + j] = temp; } //cout << endl; } } /* * Description: 在满足( 不可比的点 - 查询点 ) * 权重矢量 = 0 的边界上选取权重矢量样本 * Author: zll * Parameters: * sampleSize: 在此平面取样的大小 * sample: 存放取样后的矢量,个数为 sampleSize 个 * incomparable_point: 与查询点不可比的所有点 * _qry_pt: 查询点 */ void RTree::SampleWeights(int sampleSize, float *sample, float* incomPoints, int incomnum, float* _qry_pt) { int samplePos = 0; float* factors = new float[dimension]; float* variables = new float[dimension];// 一个等式各变量的取值 // count:表示在一个边界上要取的点的个数,最小为1 int count = ceil((float)sampleSize / incomnum); bool flag = true; // 不可比点的个数,即边界数,在每个边界上求得 count 个 向量 for (int boundIndex = 0; boundIndex < incomnum && flag; boundIndex++) { // 计算系数,将两点的各维相减,并排序 for (int dim = 0; dim < dimension; dim++) factors[dim] = incomPoints[boundIndex * dimension + dim] - _qry_pt[dim]; sort(factors, factors + dimension); if (count * (boundIndex + 1) > sampleSize) { count = sampleSize - boundIndex * count; flag = false; } // 在边界上每次取一个向量 for (int vecIndex = 0; vecIndex < count; vecIndex++) { float sum = 0.0; // 一个向量各维度的和 float x = 0.0; // 随机生成 变量的取值 SampleWeights(variables, 1, dimension - 1, false); // 求最后一个变量 for (int dim = 0; dim < dimension - 1; dim++) { // 先计算系数为负数相加的结果 if (factors[dim] < 0) x = x - factors[dim] * variables[dim]; else { // variables[ dim ] 的取值应该比 ( 当前所得的结果 / 当前变量对应的系数 ) 小,否则可能导致其它系数为正且未设置的变量只能取负值。 if (variables[dim] * factors[dim] > x) variables[dim] = ((float)rand() / RAND_MAX) * (x / factors[dim]); x = x - variables[dim] * factors[dim]; } sum += variables[dim]; } variables[dimension - 1] = x / factors[dimension - 1]; sum += variables[dimension - 1]; // 对取样的向量各维进行重新计算,使得各维的和为1 for (int dim = 0; dim < dimension; dim++) { sample[samplePos] = variables[dim] / sum; samplePos++; } } } delete factors; delete variables; } /* * Description: 随机生成一个权重矢量集合, 矢量各维度值的和为1 * Author: zll * Parameters: * sample: 随机生成的权重矢量集合 * dimension: 矢量的维度 * sampleSize: 矢量个数 * Return: */ void RTree::SampleWeights(float* sample, int dimension, int sampleSize, bool isWeight) { for (int i = 0; i < sampleSize; i++) { float sum = 0; for (int j = 0; j < dimension; j++) { float temp = (float)(rand()) / RAND_MAX; sample[i*dimension + j] = temp; sum += temp; } if (isWeight) for (int j = 0; j < dimension; j++) sample[i*dimension + j] = sample[i*dimension + j] / sum; } } void RTree::modifyWandK_approximate(Heap *_hp, float *modifyweight, int &modifyk, float &penalty, float* _qry_pt, float* weightset, int &weightnum, int k, float quality_of_answer, float probability_guarantee, float& pruning) {//modifyweight, modifyk存放结果, int bedomnum, i, j, incomnum; //incomnum是incomparable点的个数,bedomnum是dominate查询点q的点的个数, float *incomparable = new float[3000000]; incomparable_points(_hp, incomparable, incomnum, _qry_pt, bedomnum); //求incomparable点的集合,放在数组incomparable中,并求出incomnum和 bedomnum的值 int qminrank; qminrank = bedomnum + 1; //qmaxrank = incomnum + bedomnum + 1; //求出查询点q可能的排序的范围 long samplesize = (long)(log(1 - probability_guarantee) / log(1 - quality_of_answer / 100)) + 1; //样本大小 float *sampleweight = new float[samplesize * dimension]; if (incomnum != 0) SampleWeights(samplesize, sampleweight, incomparable, incomnum, _qry_pt); //( quality_of_answer, probability_guarantee, sampleweight); //取样,放在数组sampleweight中; else SampleWeights(sampleweight, dimension, samplesize, true); //( quality_of_answer, probability_guarantee, sampleweight); //取样,放在数组sampleweight中; int *rankofq = new int[samplesize]; //用来记录查询点q在每个样本权重下的排序位置 float *currentweight = new float[dimension]; int ranking; for (i = 0; i<samplesize; i++) //对于每个样本向量下查询点q的排序 { //------------------------------------------------------------- memcpy(currentweight, &sampleweight[i * dimension], dimension * sizeof(float)); /*for (j = 0; j < dimension; j ++) { currentweight[j] = sampleweight[ i * dimension + j]; }*/ //-------------------------------------------------------------- bbs_ranking_querypoint(incomparable, incomnum, _qry_pt, currentweight, ranking); rankofq[i] = ranking + bedomnum + 1; } int qmaxrank_real = 0; /*ofstream outfile(".\\parax.txt", ios::app);*/ //===================这个地方可以直接通过传入一个参数来得到,不用再进行查询!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!=== for (i = 0; i<weightnum; i++) //对于每个why-not向量下查询点q的排序 { //------------------------------------------------------- memcpy(currentweight, &weightset[i * dimension], sizeof(float) * dimension); /* for (j = 0; j < dimension; j ++) { currentweight[j] = weightset[ i * dimension + j]; }*/ //------------------------------------------------------- bbs_ranking_querypoint(incomparable, incomnum, _qry_pt, currentweight, ranking); /*outfile<<"_qry_pt "<<endl; for( int dd = 0; dd < dimension; dd++ ) outfile<<_qry_pt[dd]<<" ";*/ //outfile<<endl; //outfile<<"currentweight"<<currentweight[0]<<endl; //outfile<<"ranking+bedomnum+1 "<<ranking+bedomnum+1<<endl; if (qmaxrank_real<ranking + bedomnum + 1) qmaxrank_real = ranking + bedomnum + 1; } //=================================================================== float parameter_k, parameter_w = 0, ww = 0; parameter_k = 0.5 / (qmaxrank_real - k); for (i = 0; i<weightnum; i++) { ww = 0; for (j = 0; j < dimension; j++) ww += weightset[i * dimension + j] * weightset[i * dimension + j]; ww += 1; ww = sqrt(ww); parameter_w += ww; } parameter_w = 0.5 / parameter_w; /*outfile<<"parameter_w "<<parameter_w<<endl;*/ int minrank, id, x; float *temptweight = new float[samplesize * dimension]; int *temptrankofq = new int[samplesize]; //根据查询点q在样本权重下排序的位置对样本进行排序,从小到大,排序后的权重放在temptweight,对应的q的排序放在temptrankofq;看看是否可以优化 for (i = 0; i<samplesize; i++) { minrank = 100000; id = 0; for (j = 0; j < samplesize; j++) { if (rankofq[j] != 0 && rankofq[j] < minrank) { id = j; minrank = rankofq[j]; } } //-------------------------------------------------------------- memcpy(&temptweight[i * dimension], &sampleweight[id * dimension], sizeof(float) * dimension); //for (x = 0; x < dimension; x ++) //{ // temptweight[i * dimension + x] = sampleweight[ id * dimension + x]; //} //-------------------------------------------------------------- temptrankofq[i] = minrank; rankofq[id] = 0; //cout << temptrankofq[i] << ", "; } //float *modifyweight = new float[1000]; float *mindeltaweight = new float[weightnum * dimension]; //用来存放k小于等于某个值时,每个why-not向量delta值最小所对应的样本向量 float *mindelta = new float[weightnum]; //用来存放k小于等于某个值时,每个why-not向量最小的delta值 //int modifyk; float deltaw, currentpenalty; bool tag; penalty = 0; //----------------------------------- memset(mindelta, 0, sizeof(float) * weightnum); /*for(i = 0; i < weightnum; i ++) { mindelta[i] = 0; }*/ //----------------------------------- //for(i = 0; i < weightnum; i ++) //用temptrankofq最小的那个向量来初始化modifyweight,modifyk, mindeltaweight和mindelta //{ // //------------------------------------------------------ // memcpy( &modifyweight [i * dimension], temptweight, sizeof( float ) * dimension ); // memcpy( &mindeltaweight[i * dimension], temptweight, sizeof( float ) * dimension ); // //------------------------------------------------------ // for(x = 0; x < dimension; x ++) // { // //------------------------------------------------------------------ // //modify0 // //minde1ltaweight[i * dimension + x] = temptweight[ x ]; // //------------------------------------------------------------------- // mindelta[i] = mindelta[i] + (modifyweight[i * dimension + x] - weightset[i * dimension + x])*(modifyweight[i * dimension + x] - weightset[i * dimension + x]); // //cout << modifyweight[i * dimension + x] << ", "; // } // //cout << endl; // mindelta[i] = sqrt(mindelta[i]); // penalty += mindelta[i]; //} //penalty = penalty * parameter_w; //======================================== // 以 why -not 向量初始化 penalty modifyk = qmaxrank_real; if (modifyk > k) penalty = (modifyk - k) * parameter_k; //=================================== memcpy(modifyweight, weightset, sizeof(float) * dimension * weightnum); for (int mindeltaNum = 0; mindeltaNum < weightnum; mindeltaNum++) mindelta[mindeltaNum] = 5.0; //if(modifyk>k) // penalty += (modifyk - k) * parameter_k; //计算penalty //cout << "penalty: " << penalty << endl; //for(int wnum = 0; wnum < weightnum; wnum ++) //用temptrankofq最小的那个向量来初始化modifyweight,modifyk, mindeltaweight和mindelta //{ // //------------------------------------------------------ // //memcpy( &modifyweight [wnum * dimension], temptweight, sizeof( float ) * dimension ); // //memcpy( &mindeltaweight[wnum * dimension], temptweight, sizeof( float ) * dimension ); // //------------------------------------------------------ // for(x = 0; x < dimension; x ++) // { // //------------------------------------------------------------------ // //modify0 // //minde1ltaweight[i * dimension + x] = temptweight[ x ]; // //------------------------------------------------------------------- // mindelta[wnum] = mindelta[wnum] + (temptweight[wnum * dimension + x] - weightset[wnum * dimension + x])*(temptweight[wnum * dimension + x] - weightset[wnum * dimension + x]); // //cout << modifyweight[i * dimension + x] << ", "; // } //} for (i = 0; i<samplesize; i++) //找delta最小的W和k { if (temptrankofq[i] > qmaxrank_real) //提前终止 { //outfile<<"samplesize - i"<<samplesize - i<<endl; pruning = (samplesize - i) / (float)samplesize; break; } tag = false; for (j = 0; j < weightnum; j++)//更新mindeltaweight { deltaw = 0; for (x = 0; x < dimension; x++) { deltaw = deltaw + (temptweight[i * dimension + x] - weightset[j * dimension + x]) * (temptweight[i * dimension + x] - weightset[j * dimension + x]); } deltaw = sqrt(deltaw); //更新mindeltaweight if (deltaw < mindelta[j]) { tag = true; mindelta[j] = deltaw; //--------------------------------------------------------- memcpy(&mindeltaweight[j * dimension], &temptweight[i * dimension], sizeof(float) * dimension); /*for(x = 0; x < dimension; x ++) { mindeltaweight[j * dimension + x] = temptweight[ i * dimension + x ]; }*/ //--------------------------------------------------------- } } if (tag == false) continue; deltaw = 0; for (j = 0; j < weightnum; j++) //如果更新后mindeltaweight包含k等于某个值时对应的向量,需计算penalty,验证其是否是解 deltaw = deltaw + mindelta[j]; float pp; if (temptrankofq[i] > k) pp = deltaw * parameter_w + (temptrankofq[i] - k) * parameter_k; else pp = deltaw * parameter_w; if (penalty > pp) { //------------------------------------------------------- memcpy(modifyweight, mindeltaweight, sizeof(float) * dimension * weightnum); //for(j = 0; j < weightnum; j ++) //{ // for(x = 0; x < dimension; x ++) // { // modifyweight[j * dimension + x] = mindeltaweight[j * dimension + x]; // //cout << modifyweight[j * dimension + x] << ", "; // } // // //cout << endl; //} //------------------------------------------ modifyk = temptrankofq[i]; penalty = pp; //cout << "penalty" <<penalty<< endl; } } delete incomparable; delete sampleweight; delete rankofq; delete currentweight; delete temptweight; delete temptrankofq; delete mindeltaweight; delete mindelta; } void RTree::modifyQ_accurate(Heap *_hp, float* _qry_pt, float* weightset, int weightnum, int k, float *&qpmodified) { int i; float *currentweight = new float[dimension]; float *kthpoint = new float[dimension]; float *kthpoints = new float[weightnum * dimension]; //存放每个why-not向量下ranking是k的那个点 for (i = 0; i < weightnum; i++) //求每个why-not向量下ranking是k的那个点 { //----------------------------------------------- memcpy(currentweight, &weightset[i * dimension], dimension * sizeof(float)); /*for (j = 0; j < dimension; j ++) { currentweight[j] = weightset[ i * dimension + j]; }*/ //----------------------------------------------- bbs_topkth(_hp, kthpoint, _qry_pt, currentweight, k); memcpy(&kthpoints[dimension * i], kthpoint, sizeof(float) * dimension); } qpmodified = q_Quadprog(_qry_pt, weightset, kthpoints, weightnum, dimension); delete[] currentweight; delete[] kthpoint; } void RTree::modifyQ_approximate(Heap *_hp, float* _qry_pt, float* weightset, int &weightnum, int k, float *qpmodified) { int i, j; float *currentweight = new float[dimension]; float *kthpoint = new float[dimension]; float *kthnearest = new float[dimension]; //--------------------------------------- memcpy(qpmodified, _qry_pt, dimension * sizeof(float)); /*for (j = 0; j < dimension; j ++) { qpmodified[j] = _qry_pt[j]; }*/ //---------------------------------------- for (i = 0; i < weightnum; i++) { memcpy(currentweight, &weightset[i * dimension], sizeof(float) * dimension); //---------------------------------------------------- /*for (j = 0; j < dimension; j ++) { currentweight[j] = weightset[ i * dimension + j]; }*/ //------------------------------------------------------ bbs_topkth(_hp, kthpoint, _qry_pt, currentweight, k); point_nearest_q(kthnearest, _qry_pt, currentweight, kthpoint);//求平面上到查询点q最近的点 for (j = 0; j < dimension; j++) { if (kthnearest[j] < qpmodified[j]) qpmodified[j] = kthnearest[j]; } } delete[] currentweight; delete[] kthpoint; delete[] kthnearest; } //void RTree::point_nearest_q( float *_rslt, float* _qry_pt, float* weight, float *kthpoint) //{ // // int i, j; // float para, para1,para2; // // para=0.0; // para1=0.0; // para2=0.0; // // for(i = 0; i <dimension; i ++) // { // para1 += weight[i] * (_qry_pt[i] - kthpoint[i]); // para2 += weight[i] * weight[i]; // } // // para = para1/para2; // // for(i = 0; i <dimension; i ++) // { // _rslt[i] = _qry_pt[i] - weight[i] * para; // _rslt[i] = ( _rslt[i] < 0 ? 0 : _rslt[i] ); // } //} void RTree::point_nearest_q(float *_rslt, float* _qry_pt, float* weight, float *kthpoint) { int i, j; bool tag; float para, para1, para2, para3;; float *point_on_plane = new float[dimension]; int *tag1 = new int[dimension]; tag = false; para = 0.0; para1 = 0.0; para2 = 0.0; para3 = 0.0; for (i = 0; i <dimension; i++) { para1 += weight[i] * (_qry_pt[i] - kthpoint[i]); para2 += weight[i] * weight[i]; tag1[i] = 1; para3 += weight[i] * kthpoint[i]; } para = para1 / para2; for (i = 0; i <dimension; i++) { _rslt[i] = _qry_pt[i] - weight[i] * para; if (_rslt[i] < 0) { _rslt[i] = 0; tag1[i] = 0; tag = true; } } while (tag == true) { para = 0.0; para1 = 0.0; para2 = 0.0; tag = false; for (i = 0; i <dimension; i++) point_on_plane[i] = 0.0; for (i = 0; i <dimension; i++) { if (tag1[i] == 1) { point_on_plane[i] = para3 / weight[i]; break; } } for (i = 0; i <dimension; i++) { if (tag1[i] == 1) { para1 += weight[i] * (_qry_pt[i] - point_on_plane[i]); para2 += weight[i] * weight[i]; } } para = para1 / para2; for (i = 0; i <dimension; i++) { if (tag1[i] == 1) { _rslt[i] = _qry_pt[i] - weight[i] * para; if (_rslt[i] < 0) { _rslt[i] = 0; tag1[i] = 0; tag = true; } } } } /* for(i = 0; i <dimension; i ++) { para1 += weight[i] * (_qry_pt[i] - kthpoint[i]); para2 += weight[i] * weight[i]; tag1[i] =1; point_on_plane[i] =0.0; para3 += weight[i] * kthpoint[i]; } para = para1/para2; for(i = 0; i <dimension; i ++) { _rslt[i] = _qry_pt[i] - weight[i] * para; if(_rslt[i] < 0) { _rslt[i]=0; tag1[i]=0; tag = true; } } if(tag==true) { para=0.0; para1=0.0; para2=0.0; for(i = 0; i <dimension; i ++) { if(tag1[i]==1) { point_on_plane[i]=para3/weight[i]; break; } } for(i = 0; i <dimension; i ++) { if(tag1[i]==1) { para1 += weight[i] * (_qry_pt[i] - point_on_plane[i]); para2 += weight[i] * weight[i]; } } para = para1/para2; for(i = 0; i <dimension; i ++) { if(tag1[i]==1) _rslt[i] = _qry_pt[i] - weight[i] * para; } } */ delete[] point_on_plane; delete[] tag1; } void RTree::modify_k_W_Q(Heap *_hp, float* _qry_pt, float* _qry_pt1, float* weightset, int &weightnum, int k, float *qpmodified, float* modifyweight, int &modifyk, float quality_of_answer, float probability_guarantee, float &penalty, float& pruning) { penalty = 100000.0; float samplesize = (long)(log(1 - probability_guarantee) / log(1 - quality_of_answer / 100)) + 1; //样本大小 float *samplepoint = new float[samplesize * dimension]; //SampleWeights( quality_of_answer, probability_guarantee, samplepoint); //取样,放在数组samplepoint中; SampleWeightsbyq(quality_of_answer, probability_guarantee, samplepoint, _qry_pt1, _qry_pt); float *tempmodifyweight = new float[weightnum * dimension]; int tempmodifyk; float temppenalty; float *tempt_qry_pt = new float[dimension]; float pruning_tmp = 0.0; float qqmodify = 0.0; float qqmin = 0.0; for (int i = 0; i<samplesize; i++) { //------------------------------------------------------------------------- memcpy(tempt_qry_pt, &samplepoint[i*dimension], dimension * sizeof(float)); //for(j=0;j <dimension; j ++) //{ // tempt_qry_pt[j]=samplepoint[i*dimension+j]; //} //----------------------------------------------------------------------------- modifyWandK_approximate(_hp, tempmodifyweight, tempmodifyk, temppenalty, tempt_qry_pt, weightset, weightnum, k, quality_of_answer, probability_guarantee, pruning); pruning_tmp += pruning; for (int q_pos = 0; q_pos < dimension; q_pos++) { qqmodify += (_qry_pt[q_pos] - tempt_qry_pt[q_pos]) * (_qry_pt[q_pos] - tempt_qry_pt[q_pos]); qqmin += (_qry_pt[q_pos] - _qry_pt1[q_pos]) * (_qry_pt[q_pos] - _qry_pt1[q_pos]); } qqmodify = sqrt(qqmodify); qqmin = sqrt(qqmin); temppenalty = temppenalty * 0.5; temppenalty += 0.5 * qqmodify / qqmin; if (temppenalty < penalty) { modifyk = tempmodifyk; penalty = temppenalty; //------------------------------------------------------------------------------------------------- memcpy(modifyweight, tempmodifyweight, sizeof(float) * dimension*weightnum); //for(j = 0; j < weightnum; j ++)//能否用memcpy(modifyweight,tempmodifyweight, sizeof(float) * dimension*weightnum); //{ // for(x = 0; x < dimension; x ++) // { // modifyweight[j * dimension + x] = tempmodifyweight[j * dimension + x]; // } //} //----------------------------------------------------------------------------------------------------- //-------------------------------------------------------------------------------------------------------- memcpy(qpmodified, tempt_qry_pt, sizeof(float) * dimension); //for(x = 0; x < dimension; x ++)//能否用memcpy(qpmodified,tempt_qry_pt, sizeof(float) * dimension); //{ // qpmodified[x] =tempt_qry_pt[ x]; //} //--------------------------------------------------------------------------------------------------- } } delete samplepoint; delete tempmodifyweight; delete tempt_qry_pt; pruning = pruning_tmp / samplesize; } //============================================================= // BBS for computing the skyline in a constrained space // _hp: heap to be used // _rslt: result skyline list to be used // _rsltcnt: number of skyline points // this function was modified from the bbs_subspace algorithm written by yufei tao. // modified by Junfeng Hu, Sep 27, 2007 //============================================================= void RTree::bbs_constrained(Heap *_hp, float *_rslt, int &_rsltcnt, float *_bounces) { int i, j; _rsltcnt = 0; //first insert the root into the heap------------------------- _hp->used = 0; HeapEntry *he = new HeapEntry(); he->dim = dimension; he->son1 = root; he->key = 0; he->level = 1; //this is not important but make sure it is greather than 0 he->bounces = new float[2 * dimension]; for (j = 0; j < 2 * dimension; j++) he->bounces[j] = 0.0; _hp->insert(he); // delete he; //------------------------------------------------------------ while (_hp->used > 0) { //remove the top heap------------------------------------- // HeapEntry *he = new HeapEntry(); // he->init_HeapEntry(dimension); _hp->remove(he); int son = he->son1; int level = he->level; float *bounces = new float[dimension]; for (int i = 0; i < dimension; i++) bounces[i] = he->bounces[2 * i]; // delete he; //-------------------------------------------------------- if (level == 0) { //checked if this point is in the constrained space if (MINDIST(bounces, _bounces, dimension) > FLOATZERO) { delete bounces; continue; } if (!sky_dom(dimension, _rslt, _rsltcnt, bounces)) { memcpy(&_rslt[dimension * _rsltcnt], bounces, sizeof(float) * dimension); _rsltcnt++; } } else { if (!sky_dom(dimension, _rslt, _rsltcnt, bounces)) { RTNode *child = new RTNode(this, son); for (i = 0; i < child->num_entries; i++) { float *b = new float[dimension]; for (j = 0; j < dimension; j++) b[j] = child->entries[i].bounces[2 * j]; //checked if this entry is in the constrained subspace if (MbrMINDIST(child->entries[i].bounces, _bounces, dimension) > FLOATZERO) { delete b; continue; } if (!sky_dom(dimension, _rslt, _rsltcnt, b)) { //HeapEntry *he = new HeapEntry(); he->dim = dimension; he->son1 = child->entries[i].son; he->level = child->level; he->key = sky_mindist(dimension, b); //he->bounces = new float[2 * dimension]; for (j = 0; j < 2 * dimension; j++) he->bounces[j] = child->entries[i].bounces[j]; _hp->insert(he); //delete he; //------------------------------------------------ } delete[] b; } delete child; } } delete[] bounces; } return; } ////////////////////////////////////////////////////////////////////////// // functions added for reverse skyline ////////////////////////////////////////////////////////////////////////// //============================================================= // BBRS algorithm for reverse skyline queries // _hp: heap to be used // _rslt: reverse skyline points list // _rsltcnt: number of reverse skyline points // _qry_pt: query point // coded by Junfeng Hu, on Nov. 3, 2007 //============================================================= void RTree::bbrs(Heap *_hp, float *_rslt, int &_rsltcnt, float* _qry_pt) { int i, j; _rsltcnt = 0; Heap *brq_hp = new Heap(); // heap for bool range query brq_hp->init(dimension, 1000); float *global_skyline_pts = new float[MAX_SKYLINE_RESULT]; // set of global skyline points int global_skyline_cnt = 0; // number of global skyline points // insert all entries of the root in the Heap _hp sorted by distance from query point _hp->used = 0; HeapEntry *he = new HeapEntry(); he->dim = dimension; he->son1 = root; he->key = 0; he->level = 1; // not important, but make sure it's greater than 0 he->bounces = new float[2 * dimension]; for (i = 0; i < 2 * dimension; i++) he->bounces[i] = 0.0; _hp->insert(he); while (_hp->used > 0) { // remove top entry _hp->remove(he); int son = he->son1; int level = he->level; // if the top entry is globally dominated by some global skyline points found yet // then we discard it. if (global_dom(dimension, global_skyline_pts, global_skyline_cnt, he->bounces, _qry_pt)) continue; if (level == 0) { // a new global skyline point is found // (1) insert it into global skyline list float *gpt = new float[dimension]; // the new global skyline point for (i = 0; i < dimension; i++) gpt[i] = he->bounces[2 * i]; memcpy(&global_skyline_pts[dimension*global_skyline_cnt], gpt, sizeof(float)*dimension); global_skyline_cnt++; // (2) execute a window query based on gpt and the query point _qry_pt float *range = new float[2 * dimension]; for (i = 0; i < dimension; i++) { if (gpt[i] < _qry_pt[i]) { range[2 * i] = _qry_pt[i] + 2 * (gpt[i] - _qry_pt[i]); range[2 * i + 1] = _qry_pt[i]; } else { range[2 * i] = _qry_pt[i]; range[2 * i + 1] = _qry_pt[i] + 2 * (gpt[i] - _qry_pt[i]); } } brq_hp->used = 0; if (!bool_range_query(brq_hp, range, gpt)) // if bool range query return false { // a new reverse skyline point is found memcpy(&_rslt[dimension*_rsltcnt], gpt, sizeof(float)*dimension); _rsltcnt++; } delete[] range; delete[] gpt; } else { RTNode *child = new RTNode(this, son); for (i = 0; i < child->num_entries; i++) { if (!global_dom(dimension, global_skyline_pts, global_skyline_cnt , child->entries[i].bounces, _qry_pt)) { he->dim = dimension; he->son1 = child->entries[i].son; he->level = child->level; he->key = MINDIST(_qry_pt, child->entries[i].bounces, dimension); memcpy(he->bounces, child->entries[i].bounces, sizeof(float) * 2 * dimension); _hp->insert(he); } } delete child; } } delete brq_hp; delete he; delete[] global_skyline_pts; } //============================================================= // supporting function used to test whether a mbr (including a // point) is globally dominated by a list of points // _dim: number of dimensions // _skyline: list of points, which usually are skyline points // _skylinecnt: number of points in _skyline // _mbr: the mbr to be tested // _qry_pt: query point of reverse skyline // coded by Junfeng Hu, on Nov. 3, 2007 //============================================================= bool RTree::global_dom(int _dim, float *_skyline, int _skylinecnt, float *_mbr, float *_qry_pt) { int i, j; bool ret = false; for (i = 0; i < _skylinecnt; i++) { bool flag = true; for (j = 0; j < _dim; j++) { if ((_skyline[i*_dim + j] - _qry_pt[j])*(_mbr[2 * j] - _qry_pt[j]) < 0 || (_skyline[i*_dim + j] - _qry_pt[j])*(_mbr[2 * j + 1] - _qry_pt[j]) < 0) { flag = false; break; } } if (flag) { // this point, with its coordinates transformed, is to be checked if it is globally dominated float *pt = new float[_dim]; for (j = 0; j < _dim; j++) { if ((_mbr[2 * j] - _qry_pt[j]) < (_mbr[2 * j + 1] - _qry_pt[j])) pt[j] = _mbr[2 * j] - _qry_pt[j]; else pt[j] = _mbr[2 * j + 1] - _qry_pt[j]; if (pt[j] < 0) pt[j] = (-1)*pt[j]; // make sure it's positive } // the global skyline point whose coordinates are transformed float *gpt = new float[_dim]; for (j = 0; j < _dim; j++) { gpt[j] = _skyline[i*_dim + j] - _qry_pt[j]; if (gpt[j] < 0) gpt[j] = (-1)*gpt[j]; // make sure it's positive } if (dominate(_dim, gpt, pt)) { ret = true; break; } delete[] gpt; delete[] pt; } } return ret; } //============================================================= // Algorithm for boolean range query // _hp: heap to be used // _mbr: range to be tested // _gpt: center of _mbr, which should be ignored in bbrs alogrithm // coded by Junfeng Hu, on Nov. 9, 2007 //============================================================= bool RTree::bool_range_query(Heap *_hp, float *_mbr, float *_gpt) { int i, j; // construct the root node HeapEntry *he = new HeapEntry(); he->dim = dimension; he->son1 = root; he->key = 0; he->level = 1; //make sure it is greater than 0 he->bounces = new float[2 * dimension]; // it will be released in the destructor of he for (i = 0; i < 2 * dimension; i++) he->bounces[i] = 0.0; // insert the root node into the heap _hp->used = 0; _hp->insert(he); while (_hp->used > 0) { // remove the top heap _hp->remove(he); int son = he->son1; int level = he->level; if (level == 0) // it is a leaf node { // pruning the global skyline itself bool is_center = true; for (j = 0; j < dimension; j++) { if ((he->bounces[2 * j] - _gpt[j]) > FLOATZERO || (_gpt[j] - he->bounces[2 * j]) > FLOATZERO) { is_center = false; break; } } if (is_center) continue; float *pt = new float[dimension]; // the point in this leaf node for (i = 0; i < dimension; i++) pt[i] = he->bounces[2 * i]; // check if this point is in the range _mbr if (MINDIST(pt, _mbr, dimension) < FLOATZERO) { // then return true, since a point is found in the range delete[] pt; delete he; return true; } delete[] pt; } else // it is an internal node { float *bottom_left = new float[dimension]; // the bottom-left corner of mbr float *top_right = new float[dimension]; // the top-right corner of mbr // check if at least one edge of bounces is in the range RTNode *child = new RTNode(this, son); for (i = 0; i < child->num_entries; i++) { // pruning all the entries that do not intersect with our range if (MbrMINDIST(child->entries[i].bounces, _mbr, dimension) > FLOATZERO) continue; // pruning the global skyline itself if (child->level == 0) { bool is_center = true; for (j = 0; j < dimension; j++) { if ((child->entries[i].bounces[2 * j] - _gpt[j]) > FLOATZERO || (_gpt[j] - child->entries[i].bounces[2 * j]) > FLOATZERO) { is_center = false; break; } } if (is_center) continue; } bool flag = false; // this flag is true if _gpt is at one edge of current mbr for (j = 0; j < dimension; j++) { bottom_left[j] = child->entries[i].bounces[2 * j]; top_right[j] = child->entries[i].bounces[2 * j + 1]; if (((bottom_left[j] - _gpt[j]) < FLOATZERO && (_gpt[j] - bottom_left[j]) < FLOATZERO) || ((top_right[j] - _gpt[j]) < FLOATZERO && (_gpt[j] - top_right[j]) < FLOATZERO)) { flag = true; break; } } bool rslt = false; if (!flag) { // Both the bottom-left corner and the top-right corner is in the range if (MINDIST(bottom_left, _mbr, dimension) < FLOATZERO && MINDIST(top_right, _mbr, dimension) < FLOATZERO) { rslt = true; // There's at least one point in the range } // Only the bottom-left corner is in the range else if (MINDIST(bottom_left, _mbr, dimension) < FLOATZERO) { float *pt = new float[dimension]; for (j = 0; j < dimension; j++) { memcpy(pt, top_right, sizeof(float) * dimension); pt[j] = bottom_left[j]; if (MINDIST(pt, _mbr, dimension) < FLOATZERO) { rslt = true; // There's at least one point in the range break; } } delete[] pt; } // Only the top-right corner is in the range else if (MINDIST(top_right, _mbr, dimension) < FLOATZERO) { float *pt = new float[dimension]; for (j = 0; j < dimension; j++) { memcpy(pt, bottom_left, sizeof(float) * dimension); pt[j] = top_right[j]; if (MINDIST(pt, _mbr, dimension) < FLOATZERO) { rslt = true; // There's at least one point in the range break; } } delete[] pt; } } if (rslt) // There's at least one point in the range { delete[] bottom_left; delete[] top_right; delete he; return true; } else { he->dim = dimension; he->son1 = child->entries[i].son; he->level = child->level; he->key = 0; // it dosen't matter for (j = 0; j < 2 * dimension; j++) he->bounces[j] = child->entries[i].bounces[j]; _hp->insert(he); } } delete[] bottom_left; delete[] top_right; } } delete he; return false; } //============================================================= // Algorithm for dynamic skyline query // _hp: heap to be used // _rslt: list of dynamic skyline points // _rsltcnt: number of dynamic skyline points // _qry_pt: query point // coded by Junfeng Hu, on Nov. 14, 2007 //============================================================= void RTree::dynamic_bbs(Heap *_hp, float *_rslt, int &_rsltcnt, float *_qry_pt) { int i, j; _rsltcnt = 0; //first insert the root into the heap------------------------- _hp->used = 0; HeapEntry *he = new HeapEntry(); he->dim = dimension; he->son1 = root; he->key = 0; he->level = 1; //this is not important but make sure it is greather than 0 he->bounces = new float[2 * dimension]; for (j = 0; j < dimension; j++) { he->bounces[2 * j] = 0.0; he->bounces[2 * j + 1] = 10000.0; } _hp->insert(he); while (_hp->used > 0) { //remove the top heap------------------------------------- _hp->remove(he); int son = he->son1; int level = he->level; if (dynamic_dom(dimension, _rslt, _rsltcnt, he->bounces, _qry_pt)) continue; if (level == 0) { float *pt = new float[dimension]; for (i = 0; i < dimension; i++) pt[i] = he->bounces[2 * i]; bool is_querypoint = true; for (i = 0; i < dimension; i++) { if ((_qry_pt[i] - pt[i]) > FLOATZERO || (pt[i] - _qry_pt[i]) > FLOATZERO) { is_querypoint = false; break; } } if (!is_querypoint) // not query point { memcpy(&_rslt[dimension * _rsltcnt], pt, sizeof(float) * dimension); _rsltcnt++; } delete[] pt; } else { RTNode *child = new RTNode(this, son); for (i = 0; i < child->num_entries; i++) { if (!dynamic_dom(dimension, _rslt, _rsltcnt, child->entries[i].bounces, _qry_pt)) { he->dim = dimension; he->son1 = child->entries[i].son; he->level = child->level; he->key = dynamic_mindist(dimension, child->entries[i].bounces, _qry_pt); for (j = 0; j < 2 * dimension; j++) he->bounces[j] = child->entries[i].bounces[j]; _hp->insert(he); } } delete child; } } delete he; /* int i, j; // (1) transforming space ofstream outfile("transformed_space.tmp"); if (!outfile) { cerr << "creating transformed_space.tmp failed!" << endl; exit(1); } int data_count = 0; HeapEntry *he = new HeapEntry(); he->init_HeapEntry(dimension); // it initials dim and bounces he->son1 = root; he->level = 1; he->key = 0; for (i = 0; i < 2*dimension; i++) he->bounces[i] = 0.0; _hp->used = 0; _hp->insert(he); while (_hp->used > 0) { _hp->remove(he); int son = he->son1; int level = he->level; if (level == 0) // it is a leaf node { float *pt = new float[dimension]; for (i = 0; i < dimension; i++) { pt[i] = he->bounces[2*i] - _qry_pt[i]; if (pt[i] < 0) pt[i] = (-1)*pt[i]; // ensure that it's positive } outfile << data_count++; for (i = 0; i < dimension; i++) outfile << " " << fixed << setprecision(6) << pt[i]; outfile << "\n"; delete[] pt; } else // it is an internal node { RTNode *child = new RTNode(this, son); for (i = 0; i < child->num_entries; i++) { he->dim = dimension; he->son1 = child->entries[i].son; he->level = child->level; he->key = 0; memcpy(he->bounces, child->entries[i].bounces, sizeof(float)*2*dimension); _hp->insert(he); } delete child; } } outfile.close(); delete he; */ // (2) building a new R-Tree // (3) using bbs to compute skyline based on the new R-Tree } float dynamic_mindist(int _dim, float *_bounces, float *_qry_pt) { float ret = 0.0; int i; for (i = 0; i < _dim; i++) { float d1 = _bounces[2 * i] - _qry_pt[i]; float d2 = _bounces[2 * i + 1] - _qry_pt[i]; if (d1 * d2 < 0) // since _bounces[2*i] >= _bounces[2*i+1], here d2 > 0 and d1 < 0 ret += 0.0; else // d1 >= 0 and d2 >= 0, or d1 <= 0 and d2 <= 0 { if (d1 < 0) d1 *= (-1); if (d2 < 0) d2 *= (-1); ret += d1 < d2 ? d1 : d2; // the smaller of d1 or d2 } } return ret; } bool dynamic_dom(int _dim, float *_rslt, int _rsltcnt, float *_bounces, float *_qry_pt) { int i, j; float *tfpt = new float[_dim]; // lowest corner of mbr with coordinates transformed for (i = 0; i < _dim; i++) { float d1 = _bounces[2 * i] - _qry_pt[i]; float d2 = _bounces[2 * i + 1] - _qry_pt[i]; if (d1 * d2 < 0) // since _bounces[2*i] >= _bounces[2*i+1], here d2 > 0 and d1 < 0 tfpt[i] = 0.0; else // d1 >= 0 and d2 >= 0, or d1 <= 0 and d2 <= 0 { if (d1 < 0) d1 *= (-1); if (d2 < 0) d2 *= (-1); tfpt[i] = d1 < d2 ? d1 : d2; // the smaller of d1 or d2 } } bool ret = false; float *s_pt = new float[_dim]; // one skyline point for (i = 0; i < _rsltcnt; i++) { for (j = 0; j < _dim; j++) { s_pt[j] = _rslt[i*_dim + j] - _qry_pt[j]; if (s_pt[j] < 0) s_pt[j] *= (-1); // ensure is is positive } if (dominate(_dim, s_pt, tfpt)) { ret = true; break; } } delete[] s_pt; delete[] tfpt; return ret; } void RTree::reverse_skyline(Heap *_hp, float *_rslt, int &_rsltcnt, float *_qry_pt) { int i, j; _rsltcnt = 0; float *dynamic_skyline = new float[MAX_SKYLINE_RESULT]; // set of dynamic skyline points Heap *dynamic_hp = new Heap(); // heap for dynamic skyline query dynamic_hp->init(dimension, 1000); float *global_skyline_pts = new float[MAX_SKYLINE_RESULT]; // set of global skyline points int global_skyline_cnt = 0; // number of global skyline points // insert all entries of the root in the Heap _hp sorted by distance from query point _hp->used = 0; HeapEntry *he = new HeapEntry(); he->dim = dimension; he->son1 = root; he->key = 0; he->level = 1; // not important, but make sure it's greater than 0 he->bounces = new float[2 * dimension]; for (i = 0; i < 2 * dimension; i++) he->bounces[i] = 0.0; _hp->insert(he); while (_hp->used > 0) { // remove top entry _hp->remove(he); int son = he->son1; int level = he->level; // if the top entry is globally dominated by some global skyline points found yet // then we discard it. if (global_dom(dimension, global_skyline_pts, global_skyline_cnt, he->bounces, _qry_pt)) continue; if (level == 0) { // a new global skyline point is found // (1) insert it into global skyline list float *gpt = new float[dimension]; // the new global skyline point for (i = 0; i < dimension; i++) gpt[i] = he->bounces[2 * i]; memcpy(&global_skyline_pts[dimension*global_skyline_cnt], gpt, sizeof(float)*dimension); global_skyline_cnt++; int dynamic_skyline_cnt = 0; // number of dynamic skyline points // compute the dynamic skyline, as gpt is the query point dynamic_hp->used = 0; dynamic_bbs(dynamic_hp, dynamic_skyline, dynamic_skyline_cnt, gpt); float *b = new float[2 * dimension]; for (i = 0; i < dimension; i++) { b[2 * i] = _qry_pt[i]; b[2 * i + 1] = _qry_pt[i]; } if (!dynamic_dom(dimension, dynamic_skyline, dynamic_skyline_cnt, b, gpt)) { // a new reverse skyline is found memcpy(&_rslt[dimension*_rsltcnt], gpt, sizeof(float)*dimension); _rsltcnt++; } delete[] b; delete[] gpt; } else { RTNode *child = new RTNode(this, son); for (i = 0; i < child->num_entries; i++) { if (!global_dom(dimension, global_skyline_pts, global_skyline_cnt , child->entries[i].bounces, _qry_pt)) { he->dim = dimension; he->son1 = child->entries[i].son; he->level = child->level; he->key = MINDIST(_qry_pt, child->entries[i].bounces, dimension); memcpy(he->bounces, child->entries[i].bounces, sizeof(float) * 2 * dimension); _hp->insert(he); } } delete child; } } delete dynamic_hp; delete he; delete[] global_skyline_pts; delete[] dynamic_skyline; } //============================================================= // RSSA algorithm for reverse skyline queries // _hp: heap to be used // _rslt: reverse skyline points list // _rsltcnt: number of reverse skyline points // _qry_pt: query point // coded by Junfeng Hu, on Nov. 27, 2007 //============================================================= void RTree::rssa(Heap *_hp, float *_rslt, int &_rsltcnt, float* _qry_pt) { int i, j; _rsltcnt = 0; Heap *brq_hp = new Heap(); // heap for bool range query brq_hp->init(dimension, 1000); float *global_skyline_pts = new float[MAX_SKYLINE_RESULT]; // set of global skyline points int global_skyline_cnt = 0; // number of global skyline points // insert all entries of the root in the Heap _hp sorted by distance from query point _hp->used = 0; HeapEntry *he = new HeapEntry(); he->dim = dimension; he->son1 = root; he->key = 0; he->level = 1; // not important, but make sure it's greater than 0 he->bounces = new float[2 * dimension]; for (i = 0; i < 2 * dimension; i++) he->bounces[i] = 0.0; _hp->insert(he); while (_hp->used > 0) { // remove top entry _hp->remove(he); int son = he->son1; int level = he->level; // if the top entry is globally dominated by some global skyline points found yet // then we discard it. if (global_dom(dimension, global_skyline_pts, global_skyline_cnt, he->bounces, _qry_pt)) continue; if (level == 0) { // a new global skyline point is found // (1) insert it into global skyline list float *gpt = new float[dimension]; // the new global skyline point for (i = 0; i < dimension; i++) gpt[i] = he->bounces[2 * i]; memcpy(&global_skyline_pts[dimension*global_skyline_cnt], gpt, sizeof(float)*dimension); global_skyline_cnt++; // (2) filter step if (DDR(gpt, _qry_pt)) { //TODO... } else if (DADR(gpt, _qry_pt)) { //TODO... } else { // (3) refinement step //TODO... } delete[] gpt; } else { RTNode *child = new RTNode(this, son); for (i = 0; i < child->num_entries; i++) { if (!global_dom(dimension, global_skyline_pts, global_skyline_cnt , child->entries[i].bounces, _qry_pt)) { he->dim = dimension; he->son1 = child->entries[i].son; he->level = child->level; he->key = MINDIST(_qry_pt, child->entries[i].bounces, dimension); memcpy(he->bounces, child->entries[i].bounces, sizeof(float) * 2 * dimension); _hp->insert(he); } } delete child; } } delete brq_hp; delete he; delete[] global_skyline_pts; } bool RTree::DDR(float* _p, float *_q) { // TODO... return true; } bool RTree::DADR(float* _p, float *_q) { // TODO... return true; } ////////////////////////////////////////////////////////////////////////// // functions added for variations of reverse skyline ////////////////////////////////////////////////////////////////////////// //============================================================= // BBRS algorithm for reverse skyline queries in a constrained // space // _hp: heap to be used // _rslt: reverse skyline points list // _rsltcnt: number of reverse skyline points // _qry_pt: query point // _bounces: constrained region // coded by Junfeng Hu, on Nov. 28, 2007 //============================================================= void RTree::bbrs_constrained(Heap *_hp, float *_rslt, int &_rsltcnt, float* _qry_pt, float *_bounces) { int i, j; _rsltcnt = 0; Heap *brq_hp = new Heap(); // heap for bool range query brq_hp->init(dimension, 1000); float *global_skyline_pts = new float[MAX_SKYLINE_RESULT]; // set of global skyline points int global_skyline_cnt = 0; // number of global skyline points // insert all entries of the root in the Heap _hp sorted by distance from query point _hp->used = 0; HeapEntry *he = new HeapEntry(); he->dim = dimension; he->son1 = root; he->key = 0; he->level = 1; // not important, but make sure it's greater than 0 he->bounces = new float[2 * dimension]; for (i = 0; i < 2 * dimension; i++) he->bounces[i] = 0.0; _hp->insert(he); while (_hp->used > 0) { // remove top entry _hp->remove(he); int son = he->son1; int level = he->level; // if the top entry is globally dominated by some global skyline points found yet // then we discard it. if (global_dom(dimension, global_skyline_pts, global_skyline_cnt, he->bounces, _qry_pt)) continue; if (level == 0) { // a new global skyline point is found // (1) insert it into global skyline list float *gpt = new float[dimension]; // the new global skyline point for (i = 0; i < dimension; i++) gpt[i] = he->bounces[2 * i]; // check if this point is in the constrained space if (MINDIST(gpt, _bounces, dimension) > FLOATZERO) { delete gpt; continue; } memcpy(&global_skyline_pts[dimension*global_skyline_cnt], gpt, sizeof(float)*dimension); global_skyline_cnt++; // (2) execute a window query based on gpt and the query point _qry_pt float *range = new float[2 * dimension]; for (i = 0; i < dimension; i++) { if (gpt[i] < _qry_pt[i]) { range[2 * i] = _qry_pt[i] + 2 * (gpt[i] - _qry_pt[i]); range[2 * i + 1] = _qry_pt[i]; } else { range[2 * i] = _qry_pt[i]; range[2 * i + 1] = _qry_pt[i] + 2 * (gpt[i] - _qry_pt[i]); } } brq_hp->used = 0; if (!bool_range_query(brq_hp, range, gpt)) // if bool range query return false { // a new reverse skyline point is found memcpy(&_rslt[dimension*_rsltcnt], gpt, sizeof(float)*dimension); _rsltcnt++; } delete[] range; delete[] gpt; } else { RTNode *child = new RTNode(this, son); for (i = 0; i < child->num_entries; i++) { //checked if this entry is in the constrained subspace if (MbrMINDIST(child->entries[i].bounces, _bounces, dimension) > FLOATZERO) { continue; } if (!global_dom(dimension, global_skyline_pts, global_skyline_cnt , child->entries[i].bounces, _qry_pt)) { he->dim = dimension; he->son1 = child->entries[i].son; he->level = child->level; he->key = MINDIST(_qry_pt, child->entries[i].bounces, dimension); memcpy(he->bounces, child->entries[i].bounces, sizeof(float) * 2 * dimension); _hp->insert(he); } } delete child; } } delete brq_hp; delete he; delete[] global_skyline_pts; } void RTree::rssa_constrained(Heap *_hp, float *_rslt, int &_rsltcnt, float* _qry_pt, float *_bounces) { // TODO... } bool cmp_value_p(const struct value_skyline_point &x, const struct value_skyline_point &y) { return x.num > y.num; } void RTree::bbrs_enum(Heap *_hp, float *_rslt, int &_rsltcnt, float* _qry_pt, int _k) { int i, j; _rsltcnt = 0; float *reverse_skyline_pts = new float[MAX_SKYLINE_RESULT]; // set of reverse skyline points int reverse_skyline_cnt = 0; Heap *brq_hp = new Heap(); // heap for bool range query brq_hp->init(dimension, 1000); float *global_skyline_pts = new float[MAX_SKYLINE_RESULT]; // set of global skyline points int global_skyline_cnt = 0; // number of global skyline points // insert all entries of the root in the Heap _hp sorted by distance from query point _hp->used = 0; HeapEntry *he = new HeapEntry(); he->dim = dimension; he->son1 = root; he->key = 0; he->level = 1; // not important, but make sure it's greater than 0 he->bounces = new float[2 * dimension]; for (i = 0; i < 2 * dimension; i++) he->bounces[i] = 0.0; _hp->insert(he); while (_hp->used > 0) { // remove top entry _hp->remove(he); int son = he->son1; int level = he->level; // if the top entry is globally dominated by some global skyline points found yet // then we discard it. if (global_dom(dimension, global_skyline_pts, global_skyline_cnt, he->bounces, _qry_pt)) continue; if (level == 0) { // a new global skyline point is found // (1) insert it into global skyline list float *gpt = new float[dimension]; // the new global skyline point for (i = 0; i < dimension; i++) gpt[i] = he->bounces[2 * i]; memcpy(&global_skyline_pts[dimension*global_skyline_cnt], gpt, sizeof(float)*dimension); global_skyline_cnt++; // (2) execute a window query based on gpt and the query point _qry_pt float *range = new float[2 * dimension]; for (i = 0; i < dimension; i++) { if (gpt[i] < _qry_pt[i]) { range[2 * i] = _qry_pt[i] + 2 * (gpt[i] - _qry_pt[i]); range[2 * i + 1] = _qry_pt[i]; } else { range[2 * i] = _qry_pt[i]; range[2 * i + 1] = _qry_pt[i] + 2 * (gpt[i] - _qry_pt[i]); } } brq_hp->used = 0; if (!bool_range_query(brq_hp, range, gpt)) // if bool range query return false { // a new reverse skyline point is found memcpy(&reverse_skyline_pts[dimension*reverse_skyline_cnt], gpt, sizeof(float)*dimension); reverse_skyline_cnt++; } delete[] range; delete[] gpt; } else { RTNode *child = new RTNode(this, son); for (i = 0; i < child->num_entries; i++) { if (!global_dom(dimension, global_skyline_pts, global_skyline_cnt , child->entries[i].bounces, _qry_pt)) { he->dim = dimension; he->son1 = child->entries[i].son; he->level = child->level; he->key = MINDIST(_qry_pt, child->entries[i].bounces, dimension); memcpy(he->bounces, child->entries[i].bounces, sizeof(float) * 2 * dimension); _hp->insert(he); } } delete child; } } vector<struct value_skyline_point> enum_reverse_skyline; float *range = new float[2 * dimension]; float *reverse_spt = new float[dimension]; for (i = 0; i < reverse_skyline_cnt; i++) { struct value_skyline_point p; p.i = i; brq_hp->used = 0; for (j = 0; j < dimension; j++) { range[2 * j] = reverse_skyline_pts[i*dimension + j]; range[2 * j + 1] = 10000.0; reverse_spt[2 * j] = reverse_skyline_pts[i*dimension + j]; } p.num = enum_range_query(brq_hp, range, reverse_spt); enum_reverse_skyline.push_back(p); } delete[] range; delete[] reverse_spt; // sort skyline points using the compare function cmp_value_p. sort(enum_reverse_skyline.begin(), enum_reverse_skyline.end(), cmp_value_p); for (i = 0; i < _k; i++) for (j = 0; j < dimension; j++) _rslt[dimension*i + j] = reverse_skyline_pts[dimension*(enum_reverse_skyline[i].i) + j]; _rsltcnt = reverse_skyline_cnt; delete brq_hp; delete he; delete[] global_skyline_pts; delete[] reverse_skyline_pts; } void RTree::rssa_enum(Heap *_hp, float *_rslt, int &_rsltcnt, float* _qry_pt, int _k) { // TODO... } //============================================================= // Algorithm for enumeration range query, which return number // of points in the range. // _hp: heap to be used // _mbr: range to be tested // _gpt: center of _mbr, which should be ignored in bbrs alogrithm // coded by Junfeng Hu, on Nov. 29, 2007 //============================================================= int RTree::enum_range_query(Heap *_hp, float *_mbr, float *_gpt) { int i, j; int num = 0; // construct the root node HeapEntry *he = new HeapEntry(); he->dim = dimension; he->son1 = root; he->key = 0; he->level = 1; //make sure it is greater than 0 he->bounces = new float[2 * dimension]; // it will be released in the destructor of he for (i = 0; i < 2 * dimension; i++) he->bounces[i] = 0.0; // insert the root node into the heap _hp->used = 0; _hp->insert(he); while (_hp->used > 0) { // remove the top heap _hp->remove(he); int son = he->son1; int level = he->level; if (level == 0) // it is a leaf node { // pruning the global skyline itself bool is_center = true; for (j = 0; j < dimension; j++) { if ((he->bounces[2 * j] - _gpt[j]) > FLOATZERO || (_gpt[j] - he->bounces[2 * j]) > FLOATZERO) { is_center = false; break; } } if (is_center) continue; float *pt = new float[dimension]; // the point in this leaf node for (i = 0; i < dimension; i++) pt[i] = he->bounces[2 * i]; // check if this point is in the range _mbr if (MINDIST(pt, _mbr, dimension) < FLOATZERO) { // then return true, since a point is found in the range // delete[] pt; // delete he; // return true; num++; } delete[] pt; } else // it is an internal node { RTNode *child = new RTNode(this, son); float *bounces = new float[dimension]; // the point in this leaf node for (i = 0; i < 2 * dimension; i++) bounces[i] = he->bounces[i]; // check if the internal node is completely in _mbr bool flag = true; for (i = 0; i < dimension; i++) { if (bounces[2 * i] < _mbr[2 * i] || bounces[2 * i + 1] > _mbr[2 * i + 1]) { flag = false; break; } } if (flag) { num += child->num_entries; continue; } // else then the internal node intersect with _mbr for (i = 0; i < child->num_entries; i++) { // pruning all the entries that do not intersect with our range if (MbrMINDIST(child->entries[i].bounces, _mbr, dimension) > FLOATZERO) continue; // pruning the global skyline itself if (child->level == 0) { bool is_center = true; for (j = 0; j < dimension; j++) { if ((child->entries[i].bounces[2 * j] - _gpt[j]) > FLOATZERO || (_gpt[j] - child->entries[i].bounces[2 * j]) > FLOATZERO) { is_center = false; break; } } if (is_center) continue; } he->dim = dimension; he->son1 = child->entries[i].son; he->level = child->level; he->key = 0; // it dosen't matter for (j = 0; j < 2 * dimension; j++) he->bounces[j] = child->entries[i].bounces[j]; _hp->insert(he); } } } delete he; return num; } void RTree::bbrs_ranked(Heap *_hp, float *_rslt, int &_rsltcnt, float* _qry_pt, int _k, float(*_mindist)(int, float*, float*)) { int i, j; _rsltcnt = 0; Heap *brq_hp = new Heap(); // heap for bool range query brq_hp->init(dimension, 1000); float *global_skyline_pts = new float[MAX_SKYLINE_RESULT]; // set of global skyline points int global_skyline_cnt = 0; // number of global skyline points // insert all entries of the root in the Heap _hp sorted by distance from query point _hp->used = 0; HeapEntry *he = new HeapEntry(); he->dim = dimension; he->son1 = root; he->key = 0; he->level = 1; // not important, but make sure it's greater than 0 he->bounces = new float[2 * dimension]; for (i = 0; i < 2 * dimension; i++) he->bounces[i] = 0.0; _hp->insert(he); while (_hp->used > 0) { // remove top entry _hp->remove(he); int son = he->son1; int level = he->level; // if the top entry is globally dominated by some global skyline points found yet // then we discard it. if (global_dom(dimension, global_skyline_pts, global_skyline_cnt, he->bounces, _qry_pt)) continue; if (level == 0) { // a new global skyline point is found // (1) insert it into global skyline list float *gpt = new float[dimension]; // the new global skyline point for (i = 0; i < dimension; i++) gpt[i] = he->bounces[2 * i]; memcpy(&global_skyline_pts[dimension*global_skyline_cnt], gpt, sizeof(float)*dimension); global_skyline_cnt++; // (2) execute a window query based on gpt and the query point _qry_pt float *range = new float[2 * dimension]; for (i = 0; i < dimension; i++) { if (gpt[i] < _qry_pt[i]) { range[2 * i] = _qry_pt[i] + 2 * (gpt[i] - _qry_pt[i]); range[2 * i + 1] = _qry_pt[i]; } else { range[2 * i] = _qry_pt[i]; range[2 * i + 1] = _qry_pt[i] + 2 * (gpt[i] - _qry_pt[i]); } } brq_hp->used = 0; if (!bool_range_query(brq_hp, range, gpt)) // if bool range query return false { // a new reverse skyline point is found memcpy(&_rslt[dimension*_rsltcnt], gpt, sizeof(float)*dimension); _rsltcnt++; } delete[] range; delete[] gpt; } else { RTNode *child = new RTNode(this, son); for (i = 0; i < child->num_entries; i++) { if (!global_dom(dimension, global_skyline_pts, global_skyline_cnt , child->entries[i].bounces, _qry_pt)) { he->dim = dimension; he->son1 = child->entries[i].son; he->level = child->level; he->key = _mindist(dimension, child->entries[i].bounces, _qry_pt); memcpy(he->bounces, child->entries[i].bounces, sizeof(float) * 2 * dimension); _hp->insert(he); } } delete child; } } delete brq_hp; delete he; delete[] global_skyline_pts; } void RTree::rssa_ranked(Heap *_hp, float *_rslt, int &_rsltcnt, float* _qry_pt, int _k, float(*_mindist)(int, float*, float*)) { // TODO... } bool RTree::global_dom_skyband(int _dim, float *_skyline, int _skylinecnt, float *_mbr, float *_qry_pt, int _k) { int i, j; bool ret = true; int num = 0; for (i = 0; i < _skylinecnt; i++) { bool flag = true; for (j = 0; j < _dim; j++) { if ((_skyline[i*_dim + j] - _qry_pt[j])*(_mbr[2 * j] - _qry_pt[j]) < 0 || (_skyline[i*_dim + j] - _qry_pt[j])*(_mbr[2 * j + 1] - _qry_pt[j]) < 0) { flag = false; break; } } if (flag) { // this point, with its coordinates transformed, is to be checked if it is globally dominated float *pt = new float[_dim]; for (j = 0; j < _dim; j++) { if ((_mbr[2 * j] - _qry_pt[j]) < (_mbr[2 * j + 1] - _qry_pt[j])) pt[j] = _mbr[2 * j] - _qry_pt[j]; else pt[j] = _mbr[2 * j + 1] - _qry_pt[j]; if (pt[j] < 0) pt[j] = (-1)*pt[j]; // make sure it's positive } // the global skyline point whose coordinates are transformed float *gpt = new float[_dim]; for (j = 0; j < _dim; j++) { gpt[j] = _skyline[i*_dim + j] - _qry_pt[j]; if (gpt[j] < 0) gpt[j] = (-1)*gpt[j]; // make sure it's positive } if (dominate(_dim, gpt, pt)) { num++; if (num > _k) { ret = false; break; } } delete[] gpt; delete[] pt; } } return ret; } void RTree::bbrs_skyband(Heap *_hp, float *_rslt, int &_rsltcnt, float* _qry_pt, int _k) { int i, j; _rsltcnt = 0; Heap *brq_hp = new Heap(); // heap for bool range query brq_hp->init(dimension, 1000); float *global_skyline_pts = new float[MAX_SKYLINE_RESULT]; // set of global skyline points int global_skyline_cnt = 0; // number of global skyline points // insert all entries of the root in the Heap _hp sorted by distance from query point _hp->used = 0; HeapEntry *he = new HeapEntry(); he->dim = dimension; he->son1 = root; he->key = 0; he->level = 1; // not important, but make sure it's greater than 0 he->bounces = new float[2 * dimension]; for (i = 0; i < 2 * dimension; i++) he->bounces[i] = 0.0; _hp->insert(he); while (_hp->used > 0) { // remove top entry _hp->remove(he); int son = he->son1; int level = he->level; // if the top entry is globally dominated by some global skyline points found yet // then we discard it. if (global_dom_skyband(dimension, global_skyline_pts, global_skyline_cnt, he->bounces, _qry_pt, _k)) continue; if (level == 0) { // a new global skyline point is found // (1) insert it into global skyline list float *gpt = new float[dimension]; // the new global skyline point for (i = 0; i < dimension; i++) gpt[i] = he->bounces[2 * i]; memcpy(&global_skyline_pts[dimension*global_skyline_cnt], gpt, sizeof(float)*dimension); global_skyline_cnt++; // (2) execute a window query based on gpt and the query point _qry_pt float *range = new float[2 * dimension]; for (i = 0; i < dimension; i++) { if (gpt[i] < _qry_pt[i]) { range[2 * i] = _qry_pt[i] + 2 * (gpt[i] - _qry_pt[i]); range[2 * i + 1] = _qry_pt[i]; } else { range[2 * i] = _qry_pt[i]; range[2 * i + 1] = _qry_pt[i] + 2 * (gpt[i] - _qry_pt[i]); } } brq_hp->used = 0; // gpt is pruned only if a windows query for this point returns more than _k points. if (enum_range_query(brq_hp, range, gpt) <= _k) { // a new reverse skyline point is found memcpy(&_rslt[dimension*_rsltcnt], gpt, sizeof(float)*dimension); _rsltcnt++; } delete[] range; delete[] gpt; } else { RTNode *child = new RTNode(this, son); for (i = 0; i < child->num_entries; i++) { if (!global_dom_skyband(dimension, global_skyline_pts, global_skyline_cnt , child->entries[i].bounces, _qry_pt, _k)) { he->dim = dimension; he->son1 = child->entries[i].son; he->level = child->level; he->key = MINDIST(_qry_pt, child->entries[i].bounces, dimension); memcpy(he->bounces, child->entries[i].bounces, sizeof(float) * 2 * dimension); _hp->insert(he); } } delete child; } } delete brq_hp; delete he; delete[] global_skyline_pts; } void RTree::rssa_skyband(Heap *_hp, float *_rslt, int &_rsltcnt, float* _qry_pt, int _k) { // TODO... } void RTree::modifyWandK_approximate_reuse(Heap *_hp, float *modifyweight, int &modifyk, float &penalty, float* _qry_pt, float* weightset, int &weightnum, int k, float quality_of_answer, float probability_guarantee, float& pruning) {//modifyweight, modifyk存放结果, int bedomnum, i, j, incomnum; //incomnum是incomparable点的个数,bedomnum是dominate查询点q的点的个数, float *incomparable = new float[3000000]; incomparable_points_reuse(_hp, incomparable, incomnum, _qry_pt, bedomnum); //求incomparable点的集合,放在数组incomparable中,并求出incomnum和 bedomnum的值 ofstream outfile("result_reuse1.txt", ios::app); outfile << "查询点: " << _qry_pt[0] << "\t" << incomnum << "\t" << bedomnum << endl; for (int cnt = 0; cnt < incomnum; cnt++) { for (int dim = 0; dim < dimension; dim++) outfile << " " << incomparable[cnt * dimension + dim]; outfile << endl; } int qminrank; qminrank = bedomnum + 1; //qmaxrank = incomnum + bedomnum + 1; //求出查询点q可能的排序的范围 long samplesize = (long)(log(1 - probability_guarantee) / log(1 - quality_of_answer / 100)) + 1; //样本大小 float *sampleweight = new float[samplesize * dimension]; if (incomnum != 0) SampleWeights(samplesize, sampleweight, incomparable, incomnum, _qry_pt); //( quality_of_answer, probability_guarantee, sampleweight); //取样,放在数组sampleweight中; else SampleWeights(sampleweight, dimension, samplesize, true); //( quality_of_answer, probability_guarantee, sampleweight); //取样,放在数组sampleweight中; int *rankofq = new int[samplesize]; //用来记录查询点q在每个样本权重下的排序位置 float *currentweight = new float[dimension]; int ranking; for (i = 0; i<samplesize; i++) //对于每个样本向量下查询点q的排序 { //------------------------------------------------------------- memcpy(currentweight, &sampleweight[i * dimension], dimension * sizeof(float)); /*for (j = 0; j < dimension; j ++) { currentweight[j] = sampleweight[ i * dimension + j]; }*/ //-------------------------------------------------------------- bbs_ranking_querypoint(incomparable, incomnum, _qry_pt, currentweight, ranking); rankofq[i] = ranking + bedomnum + 1; } int qmaxrank_real = 0; /*ofstream outfile(".\\parax.txt", ios::app);*/ for (i = 0; i<weightnum; i++) //对于每个why-not向量下查询点q的排序 { //------------------------------------------------------- memcpy(currentweight, &weightset[i * dimension], sizeof(float) * dimension); /* for (j = 0; j < dimension; j ++) { currentweight[j] = weightset[ i * dimension + j]; }*/ //------------------------------------------------------- bbs_ranking_querypoint(incomparable, incomnum, _qry_pt, currentweight, ranking); /*outfile<<"_qry_pt "<<endl; for( int dd = 0; dd < dimension; dd++ ) outfile<<_qry_pt[dd]<<" ";*/ //outfile<<endl; //outfile<<"currentweight"<<currentweight[0]<<endl; //outfile<<"ranking+bedomnum+1 "<<ranking+bedomnum+1<<endl; if (qmaxrank_real<ranking + bedomnum + 1) qmaxrank_real = ranking + bedomnum + 1; } float parameter_k, parameter_w = 0, ww = 0; parameter_k = 0.5 / (qmaxrank_real - k);//penalty中修正k的参数 for (i = 0; i<weightnum; i++) { ww = 0; for (j = 0; j < dimension; j++) ww += weightset[i * dimension + j] * weightset[i * dimension + j]; ww += 1; ww = sqrt(ww); parameter_w += ww; } parameter_w = 0.5 / parameter_w;//penalty中修正w的参数 /*outfile<<"parameter_w "<<parameter_w<<endl;*/ int minrank, id, x; float *temptweight = new float[samplesize * dimension]; int *temptrankofq = new int[samplesize]; //根据查询点q在样本权重下排序的位置对样本进行排序,从小到大,排序后的权重放在temptweight,对应的q的排序放在temptrankofq;看看是否可以优化 for (i = 0; i<samplesize; i++) { minrank = 100000; id = 0; for (j = 0; j < samplesize; j++) { if (rankofq[j] != 0 && rankofq[j] < minrank) { id = j; minrank = rankofq[j]; } } //-------------------------------------------------------------- memcpy(&temptweight[i * dimension], &sampleweight[id * dimension], sizeof(float) * dimension); //for (x = 0; x < dimension; x ++) //{ // temptweight[i * dimension + x] = sampleweight[ id * dimension + x]; //} //-------------------------------------------------------------- temptrankofq[i] = minrank; rankofq[id] = 0; //cout << temptrankofq[i] << ", "; } //float *modifyweight = new float[1000]; float *mindeltaweight = new float[weightnum * dimension]; //用来存放k小于等于某个值时,每个why-not向量delta值最小所对应的样本向量 float *mindelta = new float[weightnum]; //用来存放k小于等于某个值时,每个why-not向量最小的delta值 //int modifyk; float deltaw, currentpenalty; bool tag; penalty = 0; //----------------------------------- memset(mindelta, 0, sizeof(float) * weightnum); /*for(i = 0; i < weightnum; i ++) { mindelta[i] = 0; }*/ //----------------------------------- // 以 why -not 向量初始化 penalty modifyk = qmaxrank_real; if (modifyk > k) penalty = (modifyk - k) * parameter_k; //=================================== memcpy(modifyweight, weightset, sizeof(float) * dimension * weightnum); for (int mindeltaNum = 0; mindeltaNum < weightnum; mindeltaNum++) mindelta[mindeltaNum] = 5.0; //if(modifyk>k) // penalty += (modifyk - k) * parameter_k; //计算penalty //cout << "penalty: " << penalty << endl; //for(int wnum = 0; wnum < weightnum; wnum ++) //用temptrankofq最小的那个向量来初始化modifyweight,modifyk, mindeltaweight和mindelta //{ // //------------------------------------------------------ // //memcpy( &modifyweight [wnum * dimension], temptweight, sizeof( float ) * dimension ); // //memcpy( &mindeltaweight[wnum * dimension], temptweight, sizeof( float ) * dimension ); // //------------------------------------------------------ // for(x = 0; x < dimension; x ++) // { // //------------------------------------------------------------------ // //modify0 // //minde1ltaweight[i * dimension + x] = temptweight[ x ]; // //------------------------------------------------------------------- // mindelta[wnum] = mindelta[wnum] + (temptweight[wnum * dimension + x] - weightset[wnum * dimension + x])*(temptweight[wnum * dimension + x] - weightset[wnum * dimension + x]); // //cout << modifyweight[i * dimension + x] << ", "; // } //} for (i = 0; i<samplesize; i++) //找delta最小的W和k { if (temptrankofq[i] > qmaxrank_real) //提前终止 { //outfile<<"samplesize - i"<<samplesize - i<<endl; pruning = (samplesize - i) / (float)samplesize; break; } tag = false; for (j = 0; j < weightnum; j++)//更新mindeltaweight { deltaw = 0; for (x = 0; x < dimension; x++) { deltaw = deltaw + (temptweight[i * dimension + x] - weightset[j * dimension + x]) * (temptweight[i * dimension + x] - weightset[j * dimension + x]); } deltaw = sqrt(deltaw); //更新mindeltaweight if (deltaw < mindelta[j]) { tag = true; mindelta[j] = deltaw; //--------------------------------------------------------- memcpy(&mindeltaweight[j * dimension], &temptweight[i * dimension], sizeof(float) * dimension); /*for(x = 0; x < dimension; x ++) { mindeltaweight[j * dimension + x] = temptweight[ i * dimension + x ]; }*/ //--------------------------------------------------------- } } if (tag == false) continue; deltaw = 0; for (j = 0; j < weightnum; j++) //如果更新后mindeltaweight包含k等于某个值时对应的向量,需计算penalty,验证其是否是解 deltaw = deltaw + mindelta[j]; float pp; if (temptrankofq[i] > k) pp = deltaw * parameter_w + (temptrankofq[i] - k) * parameter_k; else pp = deltaw * parameter_w; if (penalty > pp) { //------------------------------------------------------- memcpy(modifyweight, mindeltaweight, sizeof(float) * dimension * weightnum); //for(j = 0; j < weightnum; j ++) //{ // for(x = 0; x < dimension; x ++) // { // modifyweight[j * dimension + x] = mindeltaweight[j * dimension + x]; // //cout << modifyweight[j * dimension + x] << ", "; // } // // //cout << endl; //} //------------------------------------------ modifyk = temptrankofq[i]; penalty = pp; //cout << "penalty" <<penalty<< endl; } } delete incomparable; delete sampleweight; delete rankofq; delete currentweight; delete temptweight; delete temptrankofq; delete mindeltaweight; delete mindelta; } void RTree::modify_k_W_Q_reuse(Heap *_hp, float* _qry_pt, float* _qry_pt1, float* weightset, int &weightnum, int k, float *qpmodified, float* modifyweight, int &modifyk, float quality_of_answer, float probability_guarantee, float &penalty, float& pruning) { penalty = 100000.0; long samplesize = (long)(log(1 - probability_guarantee) / log(1 - quality_of_answer / 100)) + 1; //样本大小 float *samplepoint = new float[samplesize * dimension]; //SampleWeights( quality_of_answer, probability_guarantee, samplepoint); //取样,放在数组samplepoint中; SampleWeightsbyq(quality_of_answer, probability_guarantee, samplepoint, _qry_pt1, _qry_pt); //cout << "zaipao1" << " "; cout << "samplesize=" << samplesize << endl; float *tempmodifyweight = new float[weightnum * dimension]; int tempmodifyk; float temppenalty; float *tempt_qry_pt = new float[dimension]; float pruning_tmp = 0.0; float qqmodify = 0.0; float qqmin = 0.0; //cout << "zaipao2" << endl; for (int i = 0; i<samplesize; i++) { //------------------------------------------------------------------------- memcpy(tempt_qry_pt, &samplepoint[i*dimension], dimension * sizeof(float)); //for(j=0;j <dimension; j ++) //{ // tempt_qry_pt[j]=samplepoint[i*dimension+j]; //} //----------------------------------------------------------------------------- cout << "当前跑到第" << i << "个抽样" << endl; //cout << "zaipao3" << endl; modifyWandK_approximate_reuse(_hp, tempmodifyweight, tempmodifyk, temppenalty, tempt_qry_pt, weightset, weightnum, k, quality_of_answer, probability_guarantee, pruning); pruning_tmp += pruning; //cout << "zaipao4" << endl; for (int q_pos = 0; q_pos < dimension; q_pos++) { qqmodify += (_qry_pt[q_pos] - tempt_qry_pt[q_pos]) * (_qry_pt[q_pos] - tempt_qry_pt[q_pos]); qqmin += (_qry_pt[q_pos] - _qry_pt1[q_pos]) * (_qry_pt[q_pos] - _qry_pt1[q_pos]); } qqmodify = sqrt(qqmodify); qqmin = sqrt(qqmin); temppenalty = temppenalty * 0.5; temppenalty += 0.5 * qqmodify / qqmin; if (temppenalty < penalty) { modifyk = tempmodifyk; penalty = temppenalty; //------------------------------------------------------------------------------------------------- memcpy(modifyweight, tempmodifyweight, sizeof(float) * dimension*weightnum); memcpy(qpmodified, tempt_qry_pt, sizeof(float) * dimension); } } delete samplepoint; delete tempmodifyweight; delete tempt_qry_pt; pruning = pruning_tmp / samplesize; } void RTree::incomparable_points_reuse(Heap *_hp, float *_rslt, int &_rsltcnt, float* _qry_pt, int &bedominatnum) { int i, j; _rsltcnt = 0; bedominatnum = 0; HeapEntry *he = new HeapEntry(); he->bounces = new float[2 * dimension]; //first time, insert the root into the heap------------------------- if (_hp->used == 0) { he->dim = dimension; he->son1 = root; he->key = 0; he->level = 1; //this is not important but make sure it is greather than 0 //------------------------------------------------ memset(he->bounces, 0.0, 2 * dimension * sizeof(float)); _hp->insert(he); } //the reuse heap which store the visired nodes ------------------------- Heap *hp_reuse = new Heap(); hp_reuse->init(dimension); while (_hp->used > 0) { //remove the top heap------------------------------------- _hp->remove(he); int son = he->son1; int level = he->level; float *bounces_left = new float[dimension]; float *bounces_right = new float[dimension]; for (i = 0; i < dimension; i++) { bounces_left[i] = he->bounces[i * 2]; bounces_right[i] = he->bounces[i * 2 + 1]; } if (level == 0) { if (dominate(dimension, bounces_right, _qry_pt))//if (!dominate(dimension, bounces_right, _qry_pt)&&!dominate(dimension,_qry_pt , bounces_left)) { bedominatnum++; /*for(int i=0;i<dimension;i++) cout<<_qry_pt[i]<<" "; cout<<"的主导点:"; for (int i = 0; i < dimension; i++) { cout << bounces_right[i] << " "; } cout << endl;*/ } else if (!dominate(dimension, _qry_pt, bounces_left)) { memcpy(&_rslt[dimension * _rsltcnt], bounces_left, sizeof(float) * dimension); _rsltcnt++; } hp_reuse->insert(he); } else { if (!dominate(dimension, _qry_pt, bounces_left)) { RTNode *child = new RTNode(this, son); float *left = new float[dimension]; for (i = 0; i < child->num_entries; i++) { he->dim = dimension; he->son1 = child->entries[i].son; he->level = child->level; memcpy(he->bounces, child->entries[i].bounces, 2 * sizeof(float)* dimension); he->key = MINDIST(_qry_pt, child->entries[i].bounces, dimension); _hp->insert(he); } delete child; delete[] left; } else hp_reuse->insert(he); } delete[] bounces_left; delete[] bounces_right; } while (hp_reuse->used > 0) { hp_reuse->remove(he); _hp->insert(he); } delete hp_reuse; delete he; }
9ca9e8fbfd3e3788e4ed96da1f1a0c07bf784fe5
188cbf5dd41d87c17632ff568cf08bd49eb07fec
/Probability_theory/main.cpp
1dbdb76f8ba0c773bc01c6eec3d485a1d3867101
[]
no_license
whekin/Probability_theory_exp
cc15010f153546fb7bc5a842fe0979ddc5281a18
4c68b2302cc42338a3f405e132815609c825c175
refs/heads/master
2020-04-06T12:38:02.630486
2018-12-09T12:06:35
2018-12-09T12:06:35
157,463,437
0
0
null
null
null
null
UTF-8
C++
false
false
5,856
cpp
main.cpp
#include <iostream> #include <vector> #include "ins.h" #include "experiment.h" #include "experiment_handler.h" #include "to_interval.h" #include "mathAnalytically.h" #include <SFML/Graphics.hpp> #include <SFML/OpenGL.hpp> #include "table/TextTable.h" #include "Poligon.h"; #include <cmath> using namespace std; int main(int args, char** argv) { int depth = 1; int iteration_count = 100; bool updated; sf::Font roboto; roboto.loadFromFile("Roboto-Medium.ttf"); vector<vector<int>> mathData; sf::Color backColor(38, 50, 56); sf::ContextSettings settings; settings.antialiasingLevel = 8; sf::RenderWindow window(sf::VideoMode(1200, 800), "Probability theory", sf::Style::Default, settings); glLineWidth(2.f); vector<int> sumArray; vector<vector<int>> data; Poligon poligon(window, roboto); Poligon math_poligon(window, roboto); math_poligon.setMainParams(mathData, 1, 2); math_poligon.setBackColor(backColor); math_poligon.showLabels = false; math_poligon.lineColor = sf::Color::Color(33, 150, 243); math_poligon.update(); sf::Text calculating("Calculating...", roboto); calculating.setPosition(window.getSize().x / 2, window.getSize().y / 2); calculating.setCharacterSize(25); calculating.setOrigin(calculating.getGlobalBounds().width / 2, 0); calculating.setFillColor(sf::Color::Color(33, 150, 243)); sf::Text depth_text("Depth = " + to_string(depth), roboto); depth_text.setPosition(10, 10); depth_text.setCharacterSize(18); sf::Text iteration_count_text("Iter count = " + to_string(iteration_count), roboto); iteration_count_text.setCharacterSize(18); iteration_count_text.setPosition(10, 35); sf::Clock clock; sf::Thread thread( [ &mathData, &clock, &depth_text, &iteration_count_text, &updated, &backColor, &poligon, &math_poligon, &iteration_count, &depth, &data, &sumArray ]() mutable { updated = false; cout << "Calculating..." << endl; clock.restart(); // if depth didn't change mathData = calcDataAnalytically(depth); sumArray = doExperiment(depth, iteration_count); data = experiment_handler(sumArray); system("cls"); sf::Time calculatingTime = clock.restart(); cout << "Depth: " << depth << endl; cout << "Iteration count: " << iteration_count << endl; cout << "Time of calculating: " << calculatingTime.asMilliseconds() << endl; vector<double> interval_data; vector<vector<int>> idata; vector<vector<int>> current_data; if (depth > 4) { poligon.isInterval = true; vector<int> d(data.size()); for (int i = 0; i < data.size(); i++) d[i] = data[i][1]; interval_data = to_interval(d, 20); for (int i = 0; i < interval_data.size(); i++) { vector<int> idata_item(2); idata_item[0] = i; idata_item[1] = round(interval_data[i]); idata.push_back(idata_item); } current_data = idata; } else { if (poligon.isInterval == true) poligon.isInterval = false; current_data = data; } float max = 0; float min = numeric_limits<float>::max(); for (auto& num : data) { if (num[1] > max) max = num[1]; if (num[1] < min) min = num[1]; } float mathMax = 0; for (auto& num : mathData) { if (num[1] > mathMax) mathMax = num[1]; } math_poligon.setMainParams(mathData, 1, mathMax); math_poligon.update(); poligon.setMainParams(current_data, iteration_count, max); poligon.setBackColor(backColor); poligon.update(); updated = true; // console output cout << "The maximum: " << round((max * 100.f / iteration_count) * 100.f) / 100 << "%" << " or " << max << endl; cout << "The minimum: " << round((min * 100.f / iteration_count) * 100.f) / 100 << "%" << " or " << min << endl; TextTable t('-', '|', '+'); t.add("Sum"); t.add("Freq %"); t.add("Math %"); t.endOfRow(); for (int i = 0; i < current_data.size(); i++) { float n = round((current_data[i][1] * 100.f / iteration_count) * 100.f) / 100.f; float n2; if (depth <= 2) n2 = mathData[i][1] * 100.f / calcCountBranches(depth); else n2 = 0; t.add(to_string(current_data[i][0])); t.add(toString(n, 2) + "%"); t.add(toString(n2, 2)); t.endOfRow(); } cout << t; cout << "The interval: " << data.back()[0] - data.front()[0] + 1 << endl; }); thread.launch(); while (window.isOpen()) { sf::Event event; while (window.pollEvent(event)) { switch (event.type) { case sf::Event::Closed: window.close(); break; case sf::Event::Resized: window.setView(sf::View(sf::FloatRect(0, 0, event.size.width, event.size.height))); poligon.update(); math_poligon.update(); break; case sf::Event::KeyPressed: switch (event.key.code) { case sf::Keyboard::Space: case sf::Keyboard::Enter: thread.launch(); break; case sf::Keyboard::Up: depth++; break; case sf::Keyboard::Down: if (depth > 1) depth--; break; case sf::Keyboard::Right: iteration_count += pow(10, digit_of_num(iteration_count) - 1); break; case sf::Keyboard::Left: if (iteration_count > 100) { iteration_count -= pow(10, digit_of_num(iteration_count - 1) - 1); } break; } depth_text.setString("Depth = " + to_string(depth)); iteration_count_text.setString("Iter count = " + to_string(iteration_count)); break; } } calculating.setString("Calculating... (" + to_string(clock.getElapsedTime().asMilliseconds()) + ")"); calculating.setOrigin(calculating.getGlobalBounds().width / 2, 0); window.clear(backColor); window.pushGLStates(); if (depth <= 2) math_poligon.render(); if (updated) poligon.render(); else window.draw(calculating); window.draw(depth_text); window.draw(iteration_count_text); window.display(); window.popGLStates(); } return EXIT_SUCCESS; }
801f5403d7b0116031bb1e755225a9b3a159688d
4019f3d4f76a1d9cfe6099c9c9780cd69d4a187e
/Compilers/src/main.cxx
5a7b45c192425aa27cf163c6160779ec0bfd92b9
[]
no_license
electricFeel/Ant-Runner
4f431539feeb69529f24358e6141e2bf8aef6780
b68ea4e357db29a96accf8152415cfb21f3dd7ef
refs/heads/master
2022-02-05T07:20:44.499885
2009-07-05T21:06:20
2009-07-05T21:06:20
244,880
0
1
null
2022-01-27T16:18:36
2009-07-07T02:21:49
Java
UTF-8
C++
false
false
4,145
cxx
main.cxx
/******************************************************************************/ /* IAP In-System Application Programming Demo */ /******************************************************************************/ /* This file is part of the uVision/ARM development tools. */ /* Copyright (c) 2005-2006 Keil Software. All rights reserved. */ /* This software may only be used under the terms of a valid, current, */ /* end user licence from KEIL for a compatible version of KEIL software */ /* development tools. Nothing else gives you the right to use this software. */ /******************************************************************************/ #include <stdio.h> /* standard I/O .h-file */ #include <LPC23xx.H> /* LPC23xx definitions */ #include <math.h> #include <stdlib.h> #include <stdint.h> #include "Serial.h" #include "sbl_iap.h" #include "fio.h" #define LED_FIOPIN FIO2PIN #define LED_FIOSET FIO2SET #define LED_FIOCLR FIO2CLR #define LED_GREEN_MASK (1UL<<0) #define LED_RED_MASK (1UL<<1) #define LED_BLUE_MASK (1UL<<2) #define LED_NORTH_MASK (1UL<<3) #define LED_SOUTH_MASK (1UL<<4) #define LED_WEST_MASK (1UL<<5) #define LED_EAST_MASK (1UL<<26) #define kMCUId "lpc2368" #define kApplicationStartAddr 0x00004000 #define kApplicationEndAddr 0x0007BFFF #define kSPM_PAGE_SIZE 512 #define kUSART_RX_BUFFER_SIZE kSPM_PAGE_SIZE #define kSoftwareIdentifier "AVRBOOT" #define kSoftwareVersionHigh '0' #define kSoftwareVersionLow '7' #define kDevType 0x74 //mega645 #define kSignatureByte3 0x1E //mega2560 #define kSignatureByte2 0x98 //mega2560 #define kSignatureByte1 0x01 //mega2560 extern void sysInit(void); extern int getCurrent(uint8_t portNum); void butterflyService(void); char BufferLoad(unsigned int size, unsigned char memType); void BlockRead(unsigned int size, unsigned char memType); unsigned int gAddress=0; // butterfly address unsigned int gAddressPgm=kApplicationStartAddr; //address to program unsigned char gBuffer[kUSART_RX_BUFFER_SIZE]; //RAM buffer for unsigned char gDevice; unsigned char gDevType; volatile unsigned int purge; unsigned int num=0; static void time_waste( DWORD dv ); //unsigned int datax[80000] __attribute__((section(".text"))); void ledSpin() { for (purge=0;purge<600000; purge++) { ; } num++; if (num==4) { num=0; } switch (num) { case 0: FIO2CLR |= LED_NORTH_MASK; FIO2SET |= LED_SOUTH_MASK; FIO2SET |= LED_WEST_MASK; FIO1SET |= LED_EAST_MASK; break; case 1: FIO2SET |= LED_NORTH_MASK; FIO2CLR |= LED_SOUTH_MASK; FIO2SET |= LED_WEST_MASK; FIO1SET |= LED_EAST_MASK; break; case 2: FIO2SET |= LED_NORTH_MASK; FIO2SET |= LED_SOUTH_MASK; FIO2CLR |= LED_WEST_MASK; FIO1SET |= LED_EAST_MASK; break; case 3: FIO2SET |= LED_NORTH_MASK; FIO2SET |= LED_SOUTH_MASK; FIO2SET |= LED_WEST_MASK; FIO1CLR |= LED_EAST_MASK; break; } } int main (void) { sysInit(); GPIOInit( 2, FAST_PORT, DIR_OUT, LED_RED_MASK ); GPIOInit( 2, FAST_PORT, DIR_OUT, LED_GREEN_MASK ); GPIOInit( 2, FAST_PORT, DIR_OUT, LED_BLUE_MASK ); GPIOInit( 2, FAST_PORT, DIR_OUT, LED_NORTH_MASK ); GPIOInit( 2, FAST_PORT, DIR_OUT, LED_SOUTH_MASK ); GPIOInit( 2, FAST_PORT, DIR_OUT, LED_WEST_MASK ); GPIOInit( 1, FAST_PORT, DIR_OUT, LED_EAST_MASK ); FIO2PIN |= LED_RED_MASK; FIO2PIN |= LED_GREEN_MASK; FIO2PIN |= LED_BLUE_MASK; FIO2PIN |= LED_NORTH_MASK; FIO2PIN |= LED_SOUTH_MASK; FIO2PIN |= LED_WEST_MASK; FIO1PIN |= LED_EAST_MASK; setup(); while(1) { ledSpin(); loop(); } }
cbdcb7ff3ead8bf4b3af459f0bb482b6eeacee61
2421c7328589b9392c68ef0a1e99f7523e6b6dfa
/KiwiWidgets/KiwiGuiButton.cpp
603741879657f406738f00b7b0a5486eec207fb8
[]
no_license
KiwiMusic/KiwiGui
58beedacdfa1ce9f5e4f4bf5ef74ce35890eda27
073f04fda1c415bc5bab533ecb126e733b7b9b61
refs/heads/master
2021-01-17T11:19:11.852080
2015-06-13T14:38:24
2015-06-13T14:38:24
29,305,724
1
1
null
null
null
null
UTF-8
C++
false
false
3,646
cpp
KiwiGuiButton.cpp
/* ============================================================================== This file is part of the KIWI library. Copyright (c) 2014 Pierre Guillot & Eliott Paris. Permission is granted to use this software under the terms of either: a) the GPL v2 (or any later version) b) the Affero GPL v3 Details of these licenses can be found at: www.gnu.org/licenses KIWI is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. ------------------------------------------------------------------------------ To release a closed-source product which uses KIWI, contact : guillotpierre6@gmail.com ============================================================================== */ #include "KiwiGuiButton.h" #include "KiwiGuiDevice.h" namespace Kiwi { // ================================================================================ // // GUI BUTTON // // ================================================================================ // GuiButton::GuiButton(sGuiContext context, Color const& color) noexcept : GuiModel(context), m_background_color(color) { ; } void GuiButton::setBackgroundColor(Color const& color) noexcept { if(color != m_background_color) { m_background_color = color; redraw(); } } void GuiButton::draw(sController ctrl, Sketch& sketch) const { const Rectangle bounds = ctrl->getBounds().withZeroOrigin(); sketch.setColor(m_background_color.darker(0.1)); sketch.setLineWidth(1.); sketch.drawRectangle(bounds); sketch.setColor(m_background_color); sketch.fillRectangle(bounds.reduced(0.5)); } bool GuiButton::receive(sController ctrl, MouseEvent const& event) { return event.isUp() && ctrl->contains(event.getPosition() + ctrl->getPosition()); } sGuiController GuiButton::createController() { return make_shared<Controller>(static_pointer_cast<GuiButton>(shared_from_this())); } // ================================================================================ // // GUI BUTTON CONTROLLER // // ================================================================================ // GuiButton::Controller::Controller(sGuiButton button) noexcept : GuiController(button), m_button(button) { setBounds(Rectangle(0.,0., 20., 20.)); shouldReceiveMouse(true); shouldReceiveKeyboard(false); shouldReceiveActions(false); } bool GuiButton::Controller::receive(sGuiView view, MouseEvent const& event) { sGuiButton button(getButton()); if(button) { if(button->receive(static_pointer_cast<Controller>(shared_from_this()), event)) { vector<sListener> listeners(getListeners()); for(auto it : listeners) { it->buttonPressed(button); } return true; } } return false; } void GuiButton::Controller::draw(sGuiView view, Sketch& sketch) { sGuiButton button(getButton()); if(button) { button->draw(static_pointer_cast<Controller>(shared_from_this()), sketch); } } }
d99debdb6ab7b8b64d9e72d9dbdc17166429f211
e582e4332a2f1fb7703b60787ff1e5adf162aae7
/cpp/39_combinationSum.cpp
4c0de3a7458e3c045158b90ca6f4238b301e9695
[]
no_license
loversmile/leetcode
eb0b8f275361b52b5441ea456be508b0ea75103e
5c752fecc28d6032692816ca3468fbf3fad8a29f
refs/heads/master
2022-12-17T20:13:42.151534
2020-09-14T03:47:31
2020-09-14T03:47:31
294,271,271
0
0
null
null
null
null
UTF-8
C++
false
false
1,164
cpp
39_combinationSum.cpp
#include <iostream> #include <vector> using namespace std; class Solution { public: void dfs(vector<int>& candidates, int target, vector<vector<int>>& res, vector<int>& combine, int idx) { if (idx == candidates.size()) return; if (target == 0) { res.emplace_back(combine); return; } dfs(candidates, target, res, combine, idx + 1); if (target - candidates[idx] >= 0) { combine.emplace_back(candidates[idx]); dfs(candidates, target - candidates[idx], res, combine, idx); combine.pop_back(); } } vector<vector<int>> combinationSum(vector<int>& candidates, int target) { vector<vector<int>> res; vector<int> combine; dfs(candidates, target, res, combine, 0); return res; } }; int main() { Solution S; vector<int> candidates = {2,3,5,7}; int target = 8; vector<vector<int>> res; res = S.combinationSum(candidates, target); for (auto a : res) { for (auto r: a) { cout << r << " "; } cout << endl; } return 0; }
11139c3b4ce7c67848ca0423a70b8f82192caece
3172e1455ae3d40289c122f1e39da054c3137f40
/Ishrakk_Tawsif-ac/CodeForces/25D/13924326_AC_60ms_3760kB.cpp
f325181fa2f56b786b60ffc8a46d051cc48704a2
[]
no_license
Ishrak-Tawsif/Accepted-Codes
959d2e1b444e3a7727ad78945f0590f62819ba31
24254c00e4b1c5a0b5ffc8eb2a01ee1d53f9a467
refs/heads/master
2020-12-26T19:36:15.048621
2020-02-01T13:27:56
2020-02-01T13:27:56
237,616,661
0
0
null
null
null
null
UTF-8
C++
false
false
3,186
cpp
13924326_AC_60ms_3760kB.cpp
#include <bits/stdc++.h> using namespace std; int dx[8]={0,0,1,-1,1,1,-1,-1}; int dy[8]={1,-1,0,0,1,-1,1,-1}; /*#pragma comment(linker,"/stack:200000000") #pragma GCC optimize("Ofast") #pragma GCC target("sse,sse2,sse3,ssse3,sse4,popcnt,abm,mmx,avx,tune=native")*/ #define sf(nn) scanf ("%d", &nn) #define sfll(nn) scanf ("%lld", &nn) #define pf printf #define casepf(nn) printf ("Case %d: ",nn) #define out(nn) cout <<nn <<endl #define loop(var,start,till) for(int var=start; var<till; var++) #define loop1(var,start,till) for(int var=start; var<=till; var++) #define pb push_back #define mem(a,b) memset(a,b,sizeof(a)) #define mp make_pair #define ll long long int #define inf 2e9 #define llinf 2e18 #define READ(f) freopen(f,"r",stdin) #define WRITE(f) freopen(f,"w",stdout) #define all(a) (a.begin(),a.end()) #define Unique_(a) sort(all(a));a.erase(unique(all(a)),a.end()) #define mx 100005 #define mod 1000000007 #define left(n) (n<<1) #define right(n) ((n<<1) + 1) #define fast ios_base :: sync_with_stdio(false); cin.tie(NULL); cout.tie(NULL); #define PI acos(-1) #define ull unsigned long long template <typename T> inline T BigMod(T A,T B){T ret = 1;while(B){if(B & 1) ret = (ret * A)%mod;A = (A * A)%mod;B = B >> 1;}return ret;} template <typename T> inline T InvMod (T A,T M = mod){return BigMod(A,M-2);} string tostring(ll res){string curstr="";while(res!=0){ll temp=(res%10);curstr+=((char)temp+'0');res/=10;}reverse(curstr.begin(),curstr.end());return curstr;} ll toint(string ss){ll inss = 0;for(int i=0;i<ss.size();i++){inss=(inss * 10)+((int)(ss[i]-'0'));}return inss;} /* ...........................................................................................................*/ vector <pair<int,int> > graph,extra; vector <int> ans; int par[1005]; int find_par(int p) { if(par[p] == p) return p; else return par[p] = find_par(par[p]); } int main() { int n,m,u,v; scanf("%d", &n); for(int i=1; i<=n; i++) par[i] = i; for(int i=0; i<n-1; i++) { scanf("%d %d", &u,&v); graph.pb({u,v}); } for(int i=0; i<graph.size(); i++) { u = graph[i].first; v = graph[i].second; int paru = find_par(u); int parv = find_par(v); if(paru != parv) { par[paru] = parv; } else extra.pb({u,v}); } for(int i=1; i<=n; i++) { if(par[i] == i) { ans.pb(i); } } if(ans.size() == 1) { pf("0\n"); return 0; } pf("%d\n",ans.size()-1); int ind = 0; for(int i=0; i<ans.size(); i++) { if(i>0) { cout<<extra[ind++].first<<" "<<extra[ind].second<<" "<<ans[i-1]<<" "<<ans[i]<<endl; } } return 0; }
b9aa14f0c94d77c92c496d34205f35b1bf5894a2
ed54435352f5c9a55eb01c579535265f1a734ba0
/common/src/World.cpp
b4b49d1248346f6f299392fc43cd0af35f50e0a1
[]
no_license
LoganBarnes/LogiBearPlayground
cd9ab5f0b3c4dfb8aafa4ba560fac2f2d637e394
718ed2cfef9ba615741be33f6b1da8745b8937c2
refs/heads/master
2020-04-06T06:36:38.998038
2016-10-09T08:58:37
2016-10-09T08:58:37
70,309,496
0
0
null
null
null
null
UTF-8
C++
false
false
684
cpp
World.cpp
#include "World.hpp" namespace lbc { ///////////////////////////////////////////// /// \brief World::World /// /// \author LogiBear ///////////////////////////////////////////// World::World( ) {} ///////////////////////////////////////////// /// \brief World::~World /// /// \author LogiBear ///////////////////////////////////////////// World::~World( ) {} ///////////////////////////////////////////// /// \brief World::update /// /// \author LogiBear ///////////////////////////////////////////// void World::update( const double, ///< update to this time const double ///< interval since last update ) {} } // namespace lbp
faa55d9bfc2ac81848332a89317fa316a77d6523
f35339490b06ad09f6537da693ca577fa1ae0f18
/Employee.h
aab323c7fcbaf3045d46b3c97957b6fb2101788f
[]
no_license
athfemoiur/companyProject
53fcc70f1b6eed0592f5dc25e6351414fa2fa92c
81e83d5f27f221d26055463b1113eef786e3aef1
refs/heads/master
2023-05-29T10:03:59.356870
2021-06-14T04:58:49
2021-06-14T04:58:49
376,317,050
3
0
null
null
null
null
UTF-8
C++
false
false
1,014
h
Employee.h
#ifndef COMPANY_PROJECT_EMPLOYEE_H #define COMPANY_PROJECT_EMPLOYEE_H #include <ostream> #include "istream" #include "Person.h" class Employee : public Person { protected: int hourWork; int salaryPerHour; int workToDo; int workDone; public: Employee(const string &, const string &, const Address &, int, int, int, int); Employee() = default; Employee(const Employee &); bool validate(string string1); friend ostream &operator<<(ostream &os, const Employee &employee); friend istream &operator>>(istream &os, Employee &employee); int getHourWork() const; void setHourWork(int hourWork); int getSalaryPerHour() const; void setSalaryPerHour(int salaryPerHour); int getWorkToDo() const; void setWorkToDo(int workToDo); int getWorkDone() const; void setWorkDone(int workDone); Employee& operator=(const Employee &); double calculateSalary() const; double efficiency() const; }; #endif //COMPANY_PROJECT_EMPLOYEE_H
ab31573c838e671571cba58da5dac4f5cca46a71
69dd4bd4268e1c361d8b8d95f56b5b3f5264cc96
/GPU Pro5/06_Compute/Object-order Ray Tracing for Fully Dynamic Scenes/Application/RayTracing/header/RayTracing/LightEffectDriver.h
d4038b84af830cbcc830961caef5103e55cdb021
[ "MIT", "BSD-3-Clause" ]
permissive
AnabaenaQing/Source-Code_ShaderX_GPU-Pro_GPU-Zen
65c16710d1abb9207fd7e1116290336a64ddfc86
f442622273c6c18da36b61906ec9acff3366a790
refs/heads/master
2022-12-15T00:40:42.931271
2020-09-07T16:48:25
2020-09-07T16:48:25
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,083
h
LightEffectDriver.h
#pragma once #include "Tracing.h" #include <beScene/beLightEffectDriver.h> #include "TracingEffectBinder.h" namespace app { namespace tracing { class TracingEffectBinderPool; /// Light effect driver. class LightEffectDriver : public besc::LightEffectDriver { protected: TracingEffectBinder m_tracingBinder; ///< Tracing effect binder. public: /// Constructor. LightEffectDriver(const beGraphics::Technique &technique, besc::RenderingPipeline *pipeline, besc::PerspectiveEffectBinderPool *perspectivePool, TracingEffectBinderPool *tracingPool, uint4 flags = 0); /// Destructor. ~LightEffectDriver(); /// Draws the given pass. void Render(const besc::QueuedPass *pPass, const besc::LightEffectData *pLightData, const besc::Perspective &perspective, lean::vcallable<DrawJobSignature> &drawJob, beGraphics::StateManager &stateManager, const beGraphics::DeviceContext &context) const LEAN_OVERRIDE; /// Gets the tracing effect binder. LEAN_INLINE const TracingEffectBinder& GetTracingBinder() const { return m_tracingBinder; } }; } // namespace } // namespace
a8e68059794148f6c0e01c44e73f6eeb12928874
a1e9fbed8e3fdca91aeb30424b4e49164fd8bed0
/samurai/arduino_5/arduino_5.ino
b5c8940383c85259752a4003c70f4cf6ec6943ab
[]
no_license
tmildemberger/micro_asm
4c8a7c920f0f88a03627064c123219bb9c2fa289
55ff3c5f592f1d8c71f288632a6097a8f7fdca44
refs/heads/master
2020-03-08T15:29:24.890570
2018-05-24T18:30:32
2018-05-24T18:30:32
128,213,346
0
0
null
null
null
null
UTF-8
C++
false
false
2,091
ino
arduino_5.ino
/** * Aluno: Thiago de Mendonça Mildemberger. Data: 24/05/2018 */ /** * O sketch usa 584 bytes (1%) de espaço de armazenamento para programas. O máximo são 32.256 bytes. * Variáveis globais usam 9 bytes (0%) de memória dinâmica, deixando 2.039 bytes para variáveis locais. O máximo são 2.048 bytes. */ void setup(){ asm("sbi 0x04, 5"); asm("cbi 0x0A, 2"); asm("cbi 0x0A, 3"); } void loop(){ asm("start:"); asm("sbic 0x09, 3"); asm("rjmp pino_3_em_um"); asm("rjmp pino_3_em_zero"); asm("pino_3_em_zero:"); asm("sbic 0x09, 2"); asm("rjmp zero_um"); asm("rjmp zero_zero"); asm("pino_3_em_um:"); asm("sbic 0x09, 2"); asm("rjmp um_um"); asm("rjmp um_zero"); asm("zero_zero:"); asm("sbi 0x05, 5"); asm("rcall atraso_15ms"); asm("rcall atraso_5ms"); asm("cbi 0x05, 5"); asm("rcall atraso_15ms"); asm("rcall atraso_15ms"); asm("rcall atraso_5ms"); asm("rjmp start"); asm("zero_um:"); asm("sbi 0x05, 5"); asm("rcall atraso_15ms"); asm("rcall atraso_5ms"); asm("rcall atraso_15ms"); asm("rcall atraso_5ms"); asm("cbi 0x05, 5"); asm("rcall atraso_15ms"); asm("rcall atraso_15ms"); asm("rcall atraso_15ms"); asm("rjmp start"); asm("um_zero:"); asm("sbi 0x05, 5"); asm("rcall atraso_15ms"); asm("rcall atraso_5ms"); asm("cbi 0x05, 5"); asm("rcall atraso_15ms"); asm("rcall atraso_5ms"); asm("rjmp start"); asm("um_um:"); asm("sbi 0x05, 5"); asm("rcall atraso_15ms"); asm("rcall atraso_5ms"); asm("rcall atraso_15ms"); asm("rcall atraso_5ms"); asm("cbi 0x05, 5"); asm("rcall atraso_15ms"); asm("rcall atraso_5ms"); asm("rcall atraso_15ms"); asm("rcall atraso_5ms"); asm("rjmp start"); asm("atraso_15ms:"); asm("ldi r18, 0x4c"); asm("ldi r21, 0x29"); asm("rjmp loop1"); asm("atraso_5ms:"); asm("ldi r18, 0x34"); asm("ldi r21, 0x1c"); asm(" "); asm("loop1:"); asm("mov r19, r18"); asm("loop2:"); asm("mov r20, r19"); asm("loop3:"); asm("dec r20"); asm("brne loop3"); asm("dec r19"); asm("brne loop2"); asm("dec r18"); asm("brne loop1"); asm("loop4:"); asm("mov r22, r21"); asm("loop5:"); asm("dec r22"); asm("brne loop5"); asm("dec r21"); asm("brne loop4"); asm("ret"); }
bf6ce1f8d0b4a400026f8d321d42ad5a9bf50708
98f90b3b495d3ae98bf007ff3d5383cc8aeb8adc
/feynman.cpp
c4591b50b8d78b3ae6ccd5b0077472994363210f
[]
no_license
AYRtonMeD/contest-training
f8740de903f61cf2ded62ab1bb5cedc315d51caa
703658b1b29ed8203527a487372ae7d400e46aab
refs/heads/master
2021-07-01T13:53:53.459677
2020-10-03T23:33:56
2020-10-03T23:33:56
179,202,441
0
0
null
null
null
null
UTF-8
C++
false
false
269
cpp
feynman.cpp
#include <iostream> using namespace std; int main(){ int p; int total; while (cin >> p && p != 0){ total = 0; for (int i = 0; i < p; i++){ total += p*p/(i+1)*(i+1); } cout << total << endl; } return 0; }
c4d1fa7cc2d2b45ef0d5417cd38376e8dfd553e9
a4d742ef60ae720a8b8ee842400d61981a7399db
/src/widgets/ldapclientsearch.cpp
2cd3286b1451934b06bee5509dad82b4c9af1319
[ "CC0-1.0", "BSD-3-Clause" ]
permissive
KDE/kldap
84e5bed06cd160504ad4fb741a5d55a811a25944
d32defc69c9aa45a83776fd05e6dec5fc3cd68d3
refs/heads/master
2023-07-31T13:46:41.617870
2023-07-31T02:15:37
2023-07-31T02:15:37
42,736,302
10
5
null
null
null
null
UTF-8
C++
false
false
12,842
cpp
ldapclientsearch.cpp
/* kldapclient.cpp - LDAP access * SPDX-FileCopyrightText: 2002 Klarälvdalens Datakonsult AB * SPDX-FileContributor: Steffen Hansen <hansen@kde.org> * * Ported to KABC by Daniel Molkentin <molkentin@kde.org> * * SPDX-FileCopyrightText: 2013-2023 Laurent Montel <montel@kde.org> * * SPDX-License-Identifier: LGPL-2.0-or-later */ #include "ldapclientsearch.h" #include "ldapclient_debug.h" #include "ldapclientsearchconfig.h" #include "ldapsearchclientreadconfigserverjob.h" #include "ldapclient.h" #include <kldap/ldapserver.h> #include <kldap/ldapurl.h> #include <kldap/ldif.h> #include <KConfig> #include <KConfigGroup> #include <KDirWatch> #include <KProtocolInfo> #if QT_VERSION < QT_VERSION_CHECK(6, 0, 0) #include <Kdelibs4ConfigMigrator> #endif #include <KIO/Job> #include <QStandardPaths> #include <QTimer> using namespace KLDAP; class Q_DECL_HIDDEN LdapClientSearch::LdapClientSearchPrivate { public: LdapClientSearchPrivate(LdapClientSearch *qq) : q(qq) { } ~LdapClientSearchPrivate() = default; void readWeighForClient(LdapClient *client, const KConfigGroup &config, int clientNumber); void readConfig(); void finish(); void makeSearchData(QStringList &ret, LdapResult::List &resList); void slotLDAPResult(const KLDAP::LdapClient &client, const KLDAP::LdapObject &); void slotLDAPError(const QString &); void slotLDAPDone(); void slotDataTimer(); void slotFileChanged(const QString &); void init(const QStringList &attributes); LdapClientSearch *const q; QList<LdapClient *> mClients; QStringList mAttributes; QString mSearchText; QString mFilter; QTimer mDataTimer; int mActiveClients = 0; bool mNoLDAPLookup = false; LdapResultObject::List mResults; QString mConfigFile; }; LdapClientSearch::LdapClientSearch(QObject *parent) : QObject(parent) , d(new LdapClientSearchPrivate(this)) { d->init(LdapClientSearch::defaultAttributes()); } LdapClientSearch::LdapClientSearch(const QStringList &attr, QObject *parent) : QObject(parent) , d(new LdapClientSearchPrivate(this)) { d->init(attr); } LdapClientSearch::~LdapClientSearch() = default; void LdapClientSearch::LdapClientSearchPrivate::init(const QStringList &attributes) { #if QT_VERSION < QT_VERSION_CHECK(6, 0, 0) Kdelibs4ConfigMigrator migrate(QStringLiteral("ldapsettings")); migrate.setConfigFiles(QStringList() << QStringLiteral("kabldaprc")); migrate.migrate(); #endif if (!KProtocolInfo::isKnownProtocol(QUrl(QStringLiteral("ldap://localhost")))) { mNoLDAPLookup = true; return; } mAttributes = attributes; // Set the filter, to make sure old usage (before 4.14) of this object still works. mFilter = QStringLiteral( "&(|(objectclass=person)(objectclass=groupOfNames)(mail=*))" "(|(cn=%1*)(mail=%1*)(givenName=%1*)(sn=%1*))"); readConfig(); q->connect(KDirWatch::self(), &KDirWatch::dirty, q, [this](const QString &filename) { slotFileChanged(filename); }); } void LdapClientSearch::LdapClientSearchPrivate::readWeighForClient(LdapClient *client, const KConfigGroup &config, int clientNumber) { const int completionWeight = config.readEntry(QStringLiteral("SelectedCompletionWeight%1").arg(clientNumber), -1); if (completionWeight != -1) { client->setCompletionWeight(completionWeight); } } void LdapClientSearch::updateCompletionWeights() { KConfigGroup config(KLDAP::LdapClientSearchConfig::config(), "LDAP"); for (int i = 0, total = d->mClients.size(); i < total; ++i) { d->readWeighForClient(d->mClients[i], config, i); } } QList<LdapClient *> LdapClientSearch::clients() const { return d->mClients; } QString LdapClientSearch::filter() const { return d->mFilter; } void LdapClientSearch::setFilter(const QString &filter) { d->mFilter = filter; } QStringList LdapClientSearch::attributes() const { return d->mAttributes; } void LdapClientSearch::setAttributes(const QStringList &attrs) { if (attrs != d->mAttributes) { d->mAttributes = attrs; d->readConfig(); } } QStringList LdapClientSearch::defaultAttributes() { const QStringList attr{QStringLiteral("cn"), QStringLiteral("mail"), QStringLiteral("givenname"), QStringLiteral("sn")}; return attr; } void LdapClientSearch::LdapClientSearchPrivate::readConfig() { q->cancelSearch(); qDeleteAll(mClients); mClients.clear(); // stolen from KAddressBook KConfigGroup config(KLDAP::LdapClientSearchConfig::config(), "LDAP"); const int numHosts = config.readEntry("NumSelectedHosts", 0); if (!numHosts) { mNoLDAPLookup = true; } else { for (int j = 0; j < numHosts; ++j) { auto ldapClient = new LdapClient(j, q); auto job = new LdapSearchClientReadConfigServerJob; job->setCurrentIndex(j); job->setActive(true); job->setConfig(config); job->setLdapClient(ldapClient); job->start(); mNoLDAPLookup = false; readWeighForClient(ldapClient, config, j); ldapClient->setAttributes(mAttributes); q->connect(ldapClient, &LdapClient::result, q, [this](const LdapClient &client, const KLDAP::LdapObject &obj) { slotLDAPResult(client, obj); }); q->connect(ldapClient, &LdapClient::done, q, [this]() { slotLDAPDone(); }); q->connect(ldapClient, qOverload<const QString &>(&LdapClient::error), q, [this](const QString &str) { slotLDAPError(str); }); mClients.append(ldapClient); } q->connect(&mDataTimer, &QTimer::timeout, q, [this]() { slotDataTimer(); }); } mConfigFile = QStandardPaths::writableLocation(QStandardPaths::ConfigLocation) + QStringLiteral("/kabldaprc"); KDirWatch::self()->addFile(mConfigFile); } void LdapClientSearch::LdapClientSearchPrivate::slotFileChanged(const QString &file) { if (file == mConfigFile) { readConfig(); } } void LdapClientSearch::startSearch(const QString &txt) { if (d->mNoLDAPLookup) { QMetaObject::invokeMethod(this, &LdapClientSearch::searchDone, Qt::QueuedConnection); return; } cancelSearch(); int pos = txt.indexOf(QLatin1Char('\"')); if (pos >= 0) { ++pos; const int pos2 = txt.indexOf(QLatin1Char('\"'), pos); if (pos2 >= 0) { d->mSearchText = txt.mid(pos, pos2 - pos); } else { d->mSearchText = txt.mid(pos); } } else { d->mSearchText = txt; } const QString filter = d->mFilter.arg(d->mSearchText); QList<LdapClient *>::Iterator it(d->mClients.begin()); const QList<LdapClient *>::Iterator end(d->mClients.end()); for (; it != end; ++it) { (*it)->startQuery(filter); qCDebug(LDAPCLIENT_LOG) << "LdapClientSearch::startSearch()" << filter; ++d->mActiveClients; } } void LdapClientSearch::cancelSearch() { QList<LdapClient *>::Iterator it(d->mClients.begin()); const QList<LdapClient *>::Iterator end(d->mClients.end()); for (; it != end; ++it) { (*it)->cancelQuery(); } d->mActiveClients = 0; d->mResults.clear(); } void LdapClientSearch::LdapClientSearchPrivate::slotLDAPResult(const LdapClient &client, const KLDAP::LdapObject &obj) { LdapResultObject result; result.client = &client; result.object = obj; mResults.append(result); if (!mDataTimer.isActive()) { mDataTimer.setSingleShot(true); mDataTimer.start(500); } } void LdapClientSearch::LdapClientSearchPrivate::slotLDAPError(const QString &) { slotLDAPDone(); } void LdapClientSearch::LdapClientSearchPrivate::slotLDAPDone() { if (--mActiveClients > 0) { return; } finish(); } void LdapClientSearch::LdapClientSearchPrivate::slotDataTimer() { QStringList lst; LdapResult::List reslist; Q_EMIT q->searchData(mResults); makeSearchData(lst, reslist); if (!lst.isEmpty()) { Q_EMIT q->searchData(lst); } if (!reslist.isEmpty()) { Q_EMIT q->searchData(reslist); } } void LdapClientSearch::LdapClientSearchPrivate::finish() { mDataTimer.stop(); slotDataTimer(); // Q_EMIT final bunch of data Q_EMIT q->searchDone(); } void LdapClientSearch::LdapClientSearchPrivate::makeSearchData(QStringList &ret, LdapResult::List &resList) { LdapResultObject::List::ConstIterator it1(mResults.constBegin()); const LdapResultObject::List::ConstIterator end1(mResults.constEnd()); for (; it1 != end1; ++it1) { QString name; QString mail; QString givenname; QString sn; QStringList mails; bool isDistributionList = false; bool wasCN = false; bool wasDC = false; // qCDebug(LDAPCLIENT_LOG) <<"\n\nLdapClientSearch::makeSearchData()"; KLDAP::LdapAttrMap::ConstIterator it2; for (it2 = (*it1).object.attributes().constBegin(); it2 != (*it1).object.attributes().constEnd(); ++it2) { QByteArray val = (*it2).first(); int len = val.size(); if (len > 0 && '\0' == val[len - 1]) { --len; } const QString tmp = QString::fromUtf8(val.constData(), len); // qCDebug(LDAPCLIENT_LOG) <<" key: \"" << it2.key() <<"\" value: \"" << tmp <<"\""; if (it2.key() == QLatin1String("cn")) { name = tmp; if (mail.isEmpty()) { mail = tmp; } else { if (wasCN) { mail.prepend(QLatin1Char('.')); } else { mail.prepend(QLatin1Char('@')); } mail.prepend(tmp); } wasCN = true; } else if (it2.key() == QLatin1String("dc")) { if (mail.isEmpty()) { mail = tmp; } else { if (wasDC) { mail.append(QLatin1Char('.')); } else { mail.append(QLatin1Char('@')); } mail.append(tmp); } wasDC = true; } else if (it2.key() == QLatin1String("mail")) { mail = tmp; KLDAP::LdapAttrValue::ConstIterator it3 = it2.value().constBegin(); for (; it3 != it2.value().constEnd(); ++it3) { mails.append(QString::fromUtf8((*it3).data(), (*it3).size())); } } else if (it2.key() == QLatin1String("givenName")) { givenname = tmp; } else if (it2.key() == QLatin1String("sn")) { sn = tmp; } else if (it2.key() == QLatin1String("objectClass") && (tmp == QLatin1String("groupOfNames") || tmp == QLatin1String("kolabGroupOfNames"))) { isDistributionList = true; } } if (mails.isEmpty()) { if (!mail.isEmpty()) { mails.append(mail); } if (isDistributionList) { // qCDebug(LDAPCLIENT_LOG) <<"\n\nLdapClientSearch::makeSearchData() found a list:" << name; ret.append(name); // following lines commented out for bugfixing kolab issue #177: // // Unlike we thought previously we may NOT append the server name here. // // The right server is found by the SMTP server instead: Kolab users // must use the correct SMTP server, by definition. // // mail = (*it1).client->base().simplified(); // mail.replace( ",dc=", ".", false ); // if( mail.startsWith("dc=", false) ) // mail.remove(0, 3); // mail.prepend( '@' ); // mail.prepend( name ); // mail = name; } else { continue; // nothing, bad entry } } else if (name.isEmpty()) { ret.append(mail); } else { ret.append(QStringLiteral("%1 <%2>").arg(name, mail)); } LdapResult sr; sr.dn = (*it1).object.dn(); sr.clientNumber = (*it1).client->clientNumber(); sr.completionWeight = (*it1).client->completionWeight(); sr.name = name; sr.email = mails; resList.append(sr); } mResults.clear(); } bool LdapClientSearch::isAvailable() const { return !d->mNoLDAPLookup; } #include "moc_ldapclientsearch.cpp"
41ffb9f66f5254afd92e885091089634fe83f339
d50b3cf185f19206cc04657efb39e441f8e5ac59
/GameTemplate/myEngine/ksEngine/graphics/Bloom.cpp
a7121a5c8789f56e0b3d2e0ce387dc2689079ace
[]
no_license
kaito1111/GameTemplete
bf908fe837c7777dd8e6b34dc9a2399f8e044646
b752228adae4913c831c32270a9a700e72b597fd
refs/heads/master
2023-08-24T21:10:48.896577
2021-10-14T05:21:51
2021-10-14T05:21:51
278,224,007
0
0
null
null
null
null
SHIFT_JIS
C++
false
false
5,779
cpp
Bloom.cpp
#include "stdafx.h" #include "Bloom.h" #include "PostEffect.h" Bloom::Bloom() { } Bloom::~Bloom() { if (m_disableBlendState != nullptr) { m_disableBlendState->Release(); } //if (m_blurParamCB != nullptr) { // m_blurParamCB->Release(); //} //if (m_samplerState != nullptr) { // m_samplerState->Release(); //} if (m_finalBlendState != nullptr) { m_finalBlendState->Release(); } } void Bloom::Init() { InitRenderTarget(); InitShader(); InitAlphaBlendState(); //InitConstantBuffer(); InitSamplerState(); //輝度テクスチャをぼかすためのガウシアンブラーを初期化する。 ID3D11ShaderResourceView* srcBlurTexture = m_luminanceRT.GetRenderTargetSRV(); for (int i = 0; i < NUM_DOWN_SAMPLE; i++) { m_gaussianBlur[i].Init(srcBlurTexture, 25.0f); //次のガウスブラーで使用するソーステクスチャを設定する。 srcBlurTexture = m_gaussianBlur[i].GetResultTextureSRV(); } } void Bloom::InitAlphaBlendState() { CD3D11_DEFAULT defaultSettings; //デフォルトセッティングで初期化する。 CD3D11_BLEND_DESC blendDesc(defaultSettings); auto device = g_graphicsEngine->GetD3DDevice(); device->CreateBlendState(&blendDesc, &m_disableBlendState); //最終合成用のブレンドステートを作成する。 //最終合成は加算合成。 blendDesc.RenderTarget[0].BlendEnable = true; blendDesc.RenderTarget[0].SrcBlend = D3D11_BLEND_ONE; blendDesc.RenderTarget[0].DestBlend = D3D11_BLEND_ONE; device->CreateBlendState(&blendDesc, &m_finalBlendState); } //void Bloom::InitConstantBuffer() //{ // D3D11_BUFFER_DESC desc; // // ZeroMemory(&desc, sizeof(desc)); // desc.Usage = D3D11_USAGE_DEFAULT; // desc.ByteWidth = (((sizeof(SBlurParam) - 1) / 16) + 1) * 16; //16バイトアライメントに切りあげる。 // desc.BindFlags = D3D11_BIND_CONSTANT_BUFFER; // desc.CPUAccessFlags = 0; // g_graphicsEngine->GetD3DDevice()->CreateBuffer(&desc, NULL, &m_blurParamCB); //} void Bloom::InitShader() { m_vs.Load("Assets/shader/bloom.fx", "VSMain", ksEngine::Shader::EnType::VS); m_psLuminance.Load("Assets/shader/bloom.fx", "PSSamplingLuminance", ksEngine::Shader::EnType::PS); //m_vsXBlur.Load("Assets/shader/bloom.fx", "VSXBlur", ksEngine::Shader::EnType::VS); //m_vsYBlur.Load("Assets/shader/bloom.fx", "VSYBlur", ksEngine::Shader::EnType::VS); //m_psBlur.Load("Assets/shader/bloom.fx", "PSBlur", ksEngine::Shader::EnType::PS); m_psFinal.Load("Assets/shader/bloom.fx", "PSFinal", ksEngine::Shader::EnType::PS); } void Bloom::InitRenderTarget() { //輝度抽出用のレンダリングターゲットを作成する。 m_luminanceRT.Create( FRAME_BUFFER_W, FRAME_BUFFER_H, DXGI_FORMAT_R16G16B16A16_FLOAT ); ////ブラーをかけるためのダウンサンプリング用のレンダリングターゲットを作成。 ////横ブラー用。 //m_downSamplingRT[0].Create( // FRAME_BUFFER_W * 0.5f, //横の解像度をフレームバッファの半分にする。 // FRAME_BUFFER_H, // DXGI_FORMAT_R16G16B16A16_FLOAT //); ////縦ブラー用。 //m_downSamplingRT[1].Create( // FRAME_BUFFER_W * 0.5f, //横の解像度をフレームバッファの半分にする。 // FRAME_BUFFER_H * 0.5f, //縦の解像度をフレームバッファの半分にする。 // DXGI_FORMAT_R16G16B16A16_FLOAT //); } void Bloom::InitSamplerState() { D3D11_SAMPLER_DESC desc; ZeroMemory(&desc, sizeof(desc)); desc.AddressU = D3D11_TEXTURE_ADDRESS_CLAMP; desc.AddressV = D3D11_TEXTURE_ADDRESS_CLAMP; desc.AddressW = D3D11_TEXTURE_ADDRESS_CLAMP; desc.Filter = D3D11_FILTER_MIN_MAG_MIP_LINEAR; g_graphicsEngine->GetD3DDevice()->CreateSamplerState(&desc, &m_samplerState); } void Bloom::Draw(PostEffect & postEffect) { auto deviceContext = g_graphicsEngine->GetD3DDeviceContext(); deviceContext->PSSetSamplers(0, 1, &m_samplerState); //まずは輝度を抽出する。 { //αブレンドを無効にする。 float blendFactor[] = { 0.0f, 0.0f, 0.0f, 0.0f }; deviceContext->OMSetBlendState(m_disableBlendState, blendFactor, 0xffffffff); //輝度抽出用のレンダリングターゲットに変更する。 ChangeRenderTarget( m_luminanceRT.GetRenderTargetView(), m_luminanceRT.GetDepthStensilView(), m_luminanceRT.GetViewport() ); //レンダリングターゲットのクリア。 float clearColor[] = { 0.0f, 0.0f, 0.0f, 1.0f }; m_luminanceRT.ClearRenderTarget(clearColor); //シーンをテクスチャとする。 auto mainRTTexSRV = postEffect.GetMainRenderTarget()->GetRenderTargetSRV(); deviceContext->PSSetShaderResources(0, 1, &mainRTTexSRV); //フルスクリーン描画。 postEffect.DrawFullScreenQuadPrimitive(m_vs, m_psLuminance); } for (int i = 0; i < NUM_DOWN_SAMPLE; i++) { m_gaussianBlur[i].Execute(postEffect); } //最後にぼかした絵を加算合成でメインレンダリングターゲットに合成して終わり。 { auto MainrenderTarget = postEffect.GetMainRenderTarget(); ChangeRenderTarget( MainrenderTarget->GetRenderTargetView(), MainrenderTarget->GetDepthStensilView(), MainrenderTarget->GetViewport(), false ); for (int registerNo = 0; registerNo < NUM_DOWN_SAMPLE; registerNo++) { auto srv = m_gaussianBlur[registerNo].GetResultTextureSRV(); deviceContext->PSSetShaderResources(registerNo, 1, &srv); } //加算合成用のブレンディングステートを設定する。 float blendFactor[] = { 0.0f, 0.0f, 0.0f, 0.0f }; deviceContext->OMSetBlendState(m_finalBlendState, blendFactor, 0xffffffff); //フルスクリーン描画。 postEffect.DrawFullScreenQuadPrimitive(m_vs, m_psFinal); //ブレンディングステートを戻す。 deviceContext->OMSetBlendState(m_disableBlendState, blendFactor, 0xffffffff); } }
e210f800fdfd6425362ce1d11cda5f4d7c11eb77
e0898eaa79845e16ba38d1397976fe55b57604f7
/prm_planner/prm_planner/src/planners/prm/heuristic.cpp
c080425a8161ae8e63f2e7f946dbf551c4e4d919
[]
no_license
hitersyw/prm_planner
ef34b2fd55def2d63549233af3b3223cfb04ab79
c53d33a6882dcee4110958649ae0ca72d34839e3
refs/heads/master
2021-09-10T12:38:31.680684
2018-03-26T11:59:16
2018-03-26T11:59:16
299,898,310
1
0
null
2020-09-30T11:33:35
2020-09-30T11:33:34
null
UTF-8
C++
false
false
1,071
cpp
heuristic.cpp
/* * Copyright (c) 2016 Daniel Kuhner <kuhnerd@informatik.uni-freiburg.de>. * All rights reserved. * * Created on: Jun 21, 2016 * Author: Daniel Kuhner <kuhnerd@informatik.uni-freiburg.de> * Filename: heuristic.cpp */ #include <prm_planner/planners/prm/heuristic.h> #include <Eigen/Core> namespace prm_planner { Heuristic::Heuristic() { } Heuristic::~Heuristic() { } double Heuristic::euclideanDistEndEffector(const PRMNode* n1, const PRMNode* n2) { return (n1->getPosition() - n2->getPosition()).norm(); } double Heuristic::frameDistEndEffector(const PRMNode* n1, const PRMNode* n2) { const Eigen::Matrix3d& r1 = n1->getPose().linear(); const Eigen::Matrix3d& r2 = n2->getPose().linear(); const Eigen::Vector3d& p1 = n1->getPosition(); const Eigen::Vector3d& p2 = n2->getPosition(); double dx = ((r1.col(0) + p1) - (r2.col(0) + p2)).norm(); double dy = ((r1.col(1) + p1) - (r2.col(1) + p2)).norm(); double dz = ((r1.col(2) + p1) - (r2.col(2) + p2)).norm(); return sqrt(dx * dx + dy * dy + dz * dz); } } /* namespace prm_planner */
2115073170901d744bb2d273d1bc2f7b8bec6a01
33668d1b4d081758b05cd4a22e8628ede7f37208
/core/source/buffer/vertexBuffer.cpp
c402b7583eb37ad491a9ebdeab110f3cb6a541a6
[]
no_license
snaildex/ogele
8612c8e0fd4ad7b6b3ff6dd89cb82d5095a534fd
35502cc3d92665e8c56001bb336ae822fc2f2388
refs/heads/master
2021-07-05T09:19:48.845488
2020-08-02T22:10:34
2020-08-02T22:10:34
140,880,517
0
0
null
null
null
null
UTF-8
C++
false
false
1,082
cpp
vertexBuffer.cpp
#include <stdafx.h> #include <ogele.h> namespace ogele { BufferBase::BufferBase(BufferDataType dataType, size_t structSize, int size) { switch (dataType) { case BufferDataType::Byte: m_elemSize = sizeof(signed char); break; case BufferDataType::Short: m_elemSize = sizeof(signed short); break; case BufferDataType::Int: m_elemSize = sizeof(signed int); break; case BufferDataType::UnsignedByte: m_elemSize = sizeof(unsigned char); break; case BufferDataType::UnsignedShort: m_elemSize = sizeof(unsigned short); break; case BufferDataType::UnsignedInt: m_elemSize = sizeof(unsigned int); break; case BufferDataType::Float: m_elemSize = sizeof(float); break; case BufferDataType::Double: m_elemSize = sizeof(double); break; default: throw std::runtime_error("Unsupported vertex buffer data type"); } m_size = size; m_dataType = dataType; m_structSize = structSize; m_handle = 0; glGenBuffers(1, &m_handle); GLErr(); } BufferBase::~BufferBase() { glDeleteBuffers(1, &m_handle); GLErr(); } }
66063f9a8e3da4acb92a48db7eb7497609cdd0d8
c8b39acfd4a857dc15ed3375e0d93e75fa3f1f64
/Engine/Source/Runtime/AIModule/Private/BehaviorTree/Decorators/BTDecorator_BlackboardBase.cpp
8df75ecdf586c66676392aa2333ee4fa03671d11
[ "MIT", "LicenseRef-scancode-proprietary-license" ]
permissive
windystrife/UnrealEngine_NVIDIAGameWorks
c3c7863083653caf1bc67d3ef104fb4b9f302e2a
b50e6338a7c5b26374d66306ebc7807541ff815e
refs/heads/4.18-GameWorks
2023-03-11T02:50:08.471040
2022-01-13T20:50:29
2022-01-13T20:50:29
124,100,479
262
179
MIT
2022-12-16T05:36:38
2018-03-06T15:44:09
C++
UTF-8
C++
false
false
2,369
cpp
BTDecorator_BlackboardBase.cpp
// Copyright 1998-2017 Epic Games, Inc. All Rights Reserved. #include "BehaviorTree/Decorators/BTDecorator_BlackboardBase.h" #include "BehaviorTree/BlackboardComponent.h" UBTDecorator_BlackboardBase::UBTDecorator_BlackboardBase(const FObjectInitializer& ObjectInitializer) : Super(ObjectInitializer) { NodeName = "BlackboardBase"; bNotifyBecomeRelevant = true; bNotifyCeaseRelevant = true; // empty KeySelector = allow everything } void UBTDecorator_BlackboardBase::InitializeFromAsset(UBehaviorTree& Asset) { Super::InitializeFromAsset(Asset); UBlackboardData* BBAsset = GetBlackboardAsset(); if (BBAsset) { BlackboardKey.ResolveSelectedKey(*BBAsset); } else { UE_LOG(LogBehaviorTree, Warning, TEXT("Can't initialize %s due to missing blackboard data."), *GetName()); BlackboardKey.InvalidateResolvedKey(); } } void UBTDecorator_BlackboardBase::OnBecomeRelevant(UBehaviorTreeComponent& OwnerComp, uint8* NodeMemory) { UBlackboardComponent* BlackboardComp = OwnerComp.GetBlackboardComponent(); if (BlackboardComp) { auto KeyID = BlackboardKey.GetSelectedKeyID(); BlackboardComp->RegisterObserver(KeyID, this, FOnBlackboardChangeNotification::CreateUObject(this, &UBTDecorator_BlackboardBase::OnBlackboardKeyValueChange)); } } void UBTDecorator_BlackboardBase::OnCeaseRelevant(UBehaviorTreeComponent& OwnerComp, uint8* NodeMemory) { UBlackboardComponent* BlackboardComp = OwnerComp.GetBlackboardComponent(); if (BlackboardComp) { BlackboardComp->UnregisterObserversFrom(this); } } EBlackboardNotificationResult UBTDecorator_BlackboardBase::OnBlackboardKeyValueChange(const UBlackboardComponent& Blackboard, FBlackboard::FKey ChangedKeyID) { UBehaviorTreeComponent* BehaviorComp = (UBehaviorTreeComponent*)Blackboard.GetBrainComponent(); if (BehaviorComp == nullptr) { return EBlackboardNotificationResult::RemoveObserver; } if (BlackboardKey.GetSelectedKeyID() == ChangedKeyID) { BehaviorComp->RequestExecution(this); } return EBlackboardNotificationResult::ContinueObserving; } #if WITH_EDITOR FName UBTDecorator_BlackboardBase::GetNodeIconName() const { return FName("BTEditor.Graph.BTNode.Decorator.Blackboard.Icon"); } #endif // WITH_EDITOR //----------------------------------------------------------------------// // DEPRECATED //----------------------------------------------------------------------//
032b290b7e876337b299dad5e1972d2f993e935d
f83ef53177180ebfeb5a3e230aa29794f52ce1fc
/ACE/ACE_wrappers/apps/JAWS2/JAWS/Cache_Hash_T.cpp
022553c65ba90c1bdcb40319933fe576103673a4
[ "Apache-2.0" ]
permissive
msrLi/portingSources
fe7528b3fd08eed4a1b41383c88ee5c09c2294ef
57d561730ab27804a3172b33807f2bffbc9e52ae
refs/heads/master
2021-07-08T01:22:29.604203
2019-07-10T13:07:06
2019-07-10T13:07:06
196,183,165
2
1
Apache-2.0
2020-10-13T14:30:53
2019-07-10T10:16:46
null
UTF-8
C++
false
false
6,440
cpp
Cache_Hash_T.cpp
#ifndef JAWS_CACHE_HASH_T_CPP #define JAWS_CACHE_HASH_T_CPP #include "JAWS/Cache_Hash_T.h" #include "JAWS/Hash_Bucket_T.h" template <class EXT_ID, class HASH_FUNC, class EQ_FUNC> unsigned long JAWS_Cache_Hash<EXT_ID,HASH_FUNC,EQ_FUNC>::hash (const EXT_ID &ext_id) const { return HASH_FUNC (ext_id) % this->size_; } template <class EXT_ID, class HASH_FUNC, class EQ_FUNC> bool JAWS_Cache_Hash<EXT_ID,HASH_FUNC,EQ_FUNC>::isprime (size_t number) const { size_t d = 3; if (number <= 2) return (number == 2); if (number % 2 == 0) return 0; while (d <= number/d) { if (number % d == 0) return 0; d += 2; } return 1; } template <class EXT_ID, class HASH_FUNC, class EQ_FUNC> int JAWS_Cache_Hash<EXT_ID,HASH_FUNC,EQ_FUNC>::new_cachebucket (size_t hash_idx) { if (this->hashtable_[hash_idx] == 0) { size_t alloc_size = sizeof (CACHE_BUCKET_MANAGER); ACE_NEW_MALLOC_RETURN (this->hashtable_[hash_idx], (CACHE_BUCKET_MANAGER *) this->allocator_->malloc (alloc_size), CACHE_BUCKET_MANAGER (this->allocator_), -1); } return 0; } template <class EXT_ID, class HASH_FUNC, class EQ_FUNC> JAWS_Cache_Hash<EXT_ID,HASH_FUNC,EQ_FUNC>::JAWS_Cache_Hash (ACE_Allocator *alloc, size_t size) : allocator_ (alloc), hashtable_ (0) { while (!this->isprime (size)) size++; this->size_ = size; if (this->allocator_ == 0) this->allocator_ = ACE_Allocator::instance (); size_t memsize = this->size_ * sizeof (CACHE_BUCKET_MANAGER *); this->hashtable_ = (CACHE_BUCKET_MANAGER **) this->allocator_->malloc (memsize); if (this->hashtable_) { for (size_t i = 0; i < this->size_; i++) this->hashtable_[i] = 0; } else { this->size_ = 0; // should indicate something is wrong to the user. } } template <class EXT_ID, class HASH_FUNC, class EQ_FUNC> JAWS_Cache_Hash<EXT_ID,HASH_FUNC,EQ_FUNC>::~JAWS_Cache_Hash (void) { if (this->hashtable_) { for (size_t i = 0; i < this->size_; i++) { if (this->hashtable_[i]) { ACE_DES_FREE_TEMPLATE3(this->hashtable_[i], this->allocator_->free, JAWS_Hash_Bucket_Manager, EXT_ID, JAWS_Cache_Object *, EQ_FUNC); this->hashtable_[i] = 0; } } this->allocator_->free (this->hashtable_); this->hashtable_ = 0; } this->allocator_ = 0; } template <class EXT_ID, class HASH_FUNC, class EQ_FUNC> int JAWS_Cache_Hash<EXT_ID,HASH_FUNC,EQ_FUNC>::find (const EXT_ID &ext_id) const { unsigned long hash_idx = this->hash (ext_id); if (this->hashtable_[hash_idx] == 0) return -1; return this->hashtable_[hash_idx]->find (ext_id); } template <class EXT_ID, class HASH_FUNC, class EQ_FUNC> int JAWS_Cache_Hash<EXT_ID,HASH_FUNC,EQ_FUNC>::find (const EXT_ID &ext_id, JAWS_Cache_Object *&int_id) const { unsigned long hash_idx = this->hash (ext_id); if (this->hashtable_[hash_idx] == 0) return -1; return this->hashtable_[hash_idx]->find (ext_id, int_id); } template <class EXT_ID, class HASH_FUNC, class EQ_FUNC> int JAWS_Cache_Hash<EXT_ID,HASH_FUNC,EQ_FUNC>::bind (const EXT_ID &ext_id, JAWS_Cache_Object *const &int_id) { int result; unsigned long hash_idx = this->hash (ext_id); if (this->hashtable_[hash_idx] == 0) { ACE_GUARD_RETURN (ACE_SYNCH_MUTEX, g, this->lock_, -1); if (this->new_cachebucket (hash_idx) == -1) return -1; result = this->hashtable_[hash_idx]->bind (ext_id, int_id); } else result = this->hashtable_[hash_idx]->bind (ext_id, int_id); return result; } template <class EXT_ID, class HASH_FUNC, class EQ_FUNC> int JAWS_Cache_Hash<EXT_ID,HASH_FUNC,EQ_FUNC>::trybind (const EXT_ID &ext_id, JAWS_Cache_Object *&int_id) { int result; unsigned long hash_idx = this->hash (ext_id); if (this->hashtable_[hash_idx] == 0) { ACE_GUARD_RETURN (ACE_SYNCH_MUTEX, g, this->lock_, -1); if (this->new_cachebucket (hash_idx) == -1) return -1; result = this->hashtable_[hash_idx]->trybind (ext_id, int_id); } else result = this->hashtable_[hash_idx]->trybind (ext_id, int_id); return result; } template <class EXT_ID, class HASH_FUNC, class EQ_FUNC> int JAWS_Cache_Hash<EXT_ID,HASH_FUNC,EQ_FUNC>::rebind (const EXT_ID &ext_id, JAWS_Cache_Object *const &int_id, EXT_ID &old_ext_id, JAWS_Cache_Object *&old_int_id) { int result; unsigned long hash_idx = this->hash (ext_id); if (this->hashtable_[hash_idx] == 0) { ACE_GUARD_RETURN (ACE_SYNCH_MUTEX, g, this->lock_, -1); if (this->new_cachebucket (hash_idx) == -1) return -1; result = this->hashtable_[hash_idx]->rebind (ext_id, int_id, old_ext_id, old_int_id); } else result = this->hashtable_[hash_idx]->rebind (ext_id, int_id, old_ext_id, old_int_id); return result; } template <class EXT_ID, class HASH_FUNC, class EQ_FUNC> int JAWS_Cache_Hash<EXT_ID,HASH_FUNC,EQ_FUNC>::unbind (const EXT_ID &ext_id) { unsigned long hash_idx = this->hash (ext_id); if (this->hashtable_[hash_idx] == 0) return -1; return this->hashtable_[hash_idx]->unbind (ext_id); } template <class EXT_ID, class HASH_FUNC, class EQ_FUNC> int JAWS_Cache_Hash<EXT_ID,HASH_FUNC,EQ_FUNC>::unbind (const EXT_ID &ext_id, JAWS_Cache_Object *&int_id) { unsigned long hash_idx = this->hash (ext_id); if (this->hashtable_[hash_idx] == 0) return -1; return this->hashtable_[hash_idx]->unbind (ext_id, int_id); } template <class EXT_ID, class HASH_FUNC, class EQ_FUNC> size_t JAWS_Cache_Hash<EXT_ID,HASH_FUNC,EQ_FUNC>::size (void) const { return this->size_; } #endif /* JAWS_CACHEHASH_T_CPP */
4d6b77f0288de0cff20ae53f76d9093946ade8b6
32b934cb3ef99474b7295da510420ca4a03d6017
/GamosPhysics/PhysicsList/src/GmAcollinearEplusAnnihilation.cc
95af013ee70439a35912239280df8310ec60f364
[]
no_license
ethanlarochelle/GamosCore
450fc0eeb4a5a6666da7fdb75bcf5ee23a026238
70612e9a2e45b3b1381713503eb0f405530d44f0
refs/heads/master
2022-03-24T16:03:39.569576
2018-01-20T12:43:43
2018-01-20T12:43:43
116,504,426
2
0
null
null
null
null
UTF-8
C++
false
false
7,829
cc
GmAcollinearEplusAnnihilation.cc
// // ******************************************************************** // * License and Disclaimer * // * * // * The GAMOS software is copyright of the Copyright Holders of * // * the GAMOS Collaboration. It is provided under the terms and * // * conditions of the GAMOS Software License, included in the file * // * LICENSE and available at http://fismed.ciemat.es/GAMOS/license .* // * These include a list of copyright holders. * // * * // * Neither the authors of this software system, nor their employing * // * institutes,nor the agencies providing financial support for this * // * work make any representation or warranty, express or implied, * // * regarding this software system or assume any liability for its * // * use. Please see the license in the file LICENSE and URL above * // * for the full disclaimer and the limitation of liability. * // * * // * This code implementation is the result of the scientific and * // * technical work of the GAMOS collaboration. * // * By using, copying, modifying or distributing the software (or * // * any work based on the software) you agree to acknowledge its * // * use in resulting scientific publications, and indicate your * // * acceptance of all terms of the GAMOS Software license. * // ******************************************************************** // #include "GmAcollinearEplusAnnihilation.hh" #include "G4PhysicalConstants.hh" #include "G4MaterialCutsCouple.hh" #include "G4Gamma.hh" #include "G4PhysicsVector.hh" #include "G4PhysicsLogVector.hh" #include "G4eeToTwoGammaModel.hh" //....oooOO0OOooo........oooOO0OOooo........oooOO0OOooo........oooOO0OOooo.... using namespace std; GmAcollinearEplusAnnihilation::GmAcollinearEplusAnnihilation(const G4String& name) : G4VEmProcess(name), isInitialised(false) { theGamma = G4Gamma::Gamma(); SetIntegral(true); SetBuildTableFlag(false); SetStartFromNullFlag(false); SetSecondaryParticle(theGamma); SetProcessSubType(fAnnihilation); enableAtRestDoIt = true; } //....oooOO0OOooo........oooOO0OOooo........oooOO0OOooo........oooOO0OOooo.... GmAcollinearEplusAnnihilation::~GmAcollinearEplusAnnihilation() {} //....oooOO0OOooo........oooOO0OOooo........oooOO0OOooo........oooOO0OOooo.... G4bool GmAcollinearEplusAnnihilation::IsApplicable(const G4ParticleDefinition& p) { return (&p == G4Positron::Positron()); } //....oooOO0OOooo........oooOO0OOooo........oooOO0OOooo........oooOO0OOooo.... G4double GmAcollinearEplusAnnihilation::AtRestGetPhysicalInteractionLength( const G4Track&, G4ForceCondition* condition) { *condition = NotForced; return 0.0; } //....oooOO0OOooo........oooOO0OOooo........oooOO0OOooo........oooOO0OOooo.... void GmAcollinearEplusAnnihilation::InitialiseProcess(const G4ParticleDefinition*) { if(!isInitialised) { isInitialised = true; if(!EmModel(1)) { SetEmModel(new G4eeToTwoGammaModel(),1); } EmModel(1)->SetLowEnergyLimit(MinKinEnergy()); EmModel(1)->SetHighEnergyLimit(MaxKinEnergy()); AddEmModel(1, EmModel(1)); } } //....oooOO0OOooo........oooOO0OOooo........oooOO0OOooo........oooOO0OOooo.... void GmAcollinearEplusAnnihilation::PrintInfo() {} //....oooOO0OOooo........oooOO0OOooo........oooOO0OOooo........oooOO0OOooo.... G4VParticleChange* GmAcollinearEplusAnnihilation::AtRestDoIt(const G4Track& aTrack, const G4Step& ) // // Performs the e+ e- annihilation when both particles are assumed at rest. // It generates two photons with energy = electron_mass and with an angular difference // between their directions following the distribution as measured by Colombino et al. (1965). // The angular distribution is isotropic. // GEANT4 internal units // // Note : Effects due to binding of atomic electrons are negliged. { fParticleChange.InitializeForPostStep(aTrack); G4DynamicParticle *aGammaDP1, *aGammaDP2; G4double epsil = 0.5; //this variable can be used in the future to change the //portion of the total energy going to the two photons according to the residual //center of mass momentum of the ee system at the time of annihilation //and the direction of the two photons in the lab system. G4double TotalAvailableEnergy = 2.0*electron_mass_c2; //this should be modified in case //one wants to take into account the residual center of mass momentum of the ee system at the time of annihilation G4double Phot1Energy = epsil*TotalAvailableEnergy; G4double cosTeta = 2.*G4UniformRand()-1.; G4double sinTeta = sqrt((1.-cosTeta)*(1.0 + cosTeta)); G4double phi = twopi * G4UniformRand(); G4ThreeVector dir(sinTeta*cos(phi), sinTeta*sin(phi), cosTeta); G4ThreeVector normal_dir(-sinTeta*sin(phi), sinTeta*cos(phi), 0); //needed as rotation axis // G4double theta = pi * G4UniformRand(); // G4double phi = twopi * G4UniformRand(); // G4ThreeVector dir(sin(theta)*cos(phi), sin(theta)*sin(phi), cos(theta)); // G4ThreeVector normal_dir(-sin(theta)*sin(phi), sin(theta)*cos(phi), 0); //needed as rotation axis if(sinTeta == 0) { G4ThreeVector x_dir(1,0,0); normal_dir = x_dir; //correct the rotation axis in case the previous gives a null vector } // e+ parameters G4double weight = aTrack.GetWeight(); G4double time = aTrack.GetGlobalTime(); fParticleChange.SetNumberOfSecondaries(2); //first photon direction and polarization G4ThreeVector Phot1Direction = dir.unit(); aGammaDP1 = new G4DynamicParticle (theGamma,Phot1Direction.unit(), Phot1Energy); phi = twopi * G4UniformRand(); G4ThreeVector pol1(cos(phi), sin(phi), 0.0); //not clear to me how the polarization works. copied from the G4eeToTwoGammaModel. pol1.rotateUz(Phot1Direction.unit()); aGammaDP1->SetPolarization(pol1.x(),pol1.y(),pol1.z()); G4Track* track = new G4Track(aGammaDP1, time, aTrack.GetPosition()); track->SetTouchableHandle(aTrack.GetTouchableHandle()); track->SetWeight(weight); pParticleChange->AddSecondary(track); //get the random angular difference between the two gamma directions according to the empirical formula //for B(theta) distribution for room temperature water in the article from Colombino et al, //Nuovo Cimento, vol.38 num.2, 16 July 1965 bool good_delta_theta = false; G4double delta_theta = 0; while(!good_delta_theta) { delta_theta = 0.023*(2*G4UniformRand()-1); //limit between -23 and 23 mRad for 0.001 accuracy G4double draw = G4UniformRand(); G4double prob = (346.5*pow(pow(0.124*delta_theta*1000,2)+1,2)+5330*(pow(0.124*delta_theta*1000,2)+1)-4264)/pow(pow(0.124*delta_theta*1000,2)+1,5)/(346.5+5330-4264); if(draw<prob) { good_delta_theta = true; } } //second photon direction and polarization G4double Phot2Energy =(1.-epsil)*TotalAvailableEnergy; G4ThreeVector Phot2Direction = Phot1Direction; Phot2Direction.rotate(pi+delta_theta,normal_dir.unit()); G4double rotation = pi*G4UniformRand(); Phot2Direction.rotate(rotation,Phot1Direction); aGammaDP2 = new G4DynamicParticle (theGamma,Phot2Direction.unit(), Phot2Energy); aGammaDP2->SetPolarization(-pol1.x(),-pol1.y(),-pol1.z()); track = new G4Track(aGammaDP2, time, aTrack.GetPosition()); track->SetTouchableHandle(aTrack.GetTouchableHandle()); track->SetWeight(weight); pParticleChange->AddSecondary(track); // Kill the incident positron // fParticleChange.ProposeTrackStatus(fStopAndKill); return &fParticleChange; } //....oooOO0OOooo........oooOO0OOooo........oooOO0OOooo........oooOO0OOooo....
2b2d9bec30ffe07da883c66f7f1334248f8b7340
a9e308c81c27a80c53c899ce806d6d7b4a9bbbf3
/SDK/include/WildMagic4/SDK/Include/Wm4IntrBox3Sphere3.h
b64f6902868de43bf7c83013c707922528e682e7
[ "BSL-1.0" ]
permissive
NikitaNikson/xray-2_0
00d8e78112d7b3d5ec1cb790c90f614dc732f633
82b049d2d177aac15e1317cbe281e8c167b8f8d1
refs/heads/master
2023-06-25T16:51:26.243019
2020-09-29T15:49:23
2020-09-29T15:49:23
390,966,305
1
0
null
null
null
null
UTF-8
C++
false
false
2,680
h
Wm4IntrBox3Sphere3.h
// Geometric Tools, LLC // Copyright (c) 1998-2010 // Distributed under the Boost Software License, Version 1.0. // http://www.boost.org/LICENSE_1_0.txt // http://www.geometrictools.com/License/Boost/LICENSE_1_0.txt // // File Version: 4.10.0 (2009/11/18) #ifndef WM4INTRBOX3SPHERE3_H #define WM4INTRBOX3SPHERE3_H #include "Wm4FoundationLIB.h" #include "Wm4Intersector.h" #include "Wm4Box3.h" #include "Wm4Sphere3.h" namespace Wm4 { template <class Real> class WM4_FOUNDATION_ITEM IntrBox3Sphere3 : public Intersector<Real,Vector3<Real> > { public: IntrBox3Sphere3 (const Box3<Real>& rkBox, const Sphere3<Real>& rkSphere); // object access const Box3<Real>& GetBox () const; const Sphere3<Real>& GetSphere () const; // test-intersection query virtual bool Test (); // find-intersection query virtual bool Find (Real fTMax, const Vector3<Real>& rkVelocity0, const Vector3<Real>& rkVelocity1); // intersection set for dynamic find-intersection query const Vector3<Real>& GetContactPoint () const; private: using Intersector<Real,Vector3<Real> >::IT_EMPTY; using Intersector<Real,Vector3<Real> >::IT_POINT; using Intersector<Real,Vector3<Real> >::IT_OTHER; using Intersector<Real,Vector3<Real> >::m_iIntersectionType; using Intersector<Real,Vector3<Real> >::m_fContactTime; // supporting functions for dynamic Find function static Real GetVertexIntersection (Real fDx, Real fDy, Real fDz, Real fVx, Real fVy, Real fVz, Real fRSqr); static Real GetEdgeIntersection (Real fDx, Real fDz, Real fVx, Real fVz, Real fVSqr, Real fRSqr); int FindFaceRegionIntersection (Real fEx, Real fEy, Real fEz, Real fCx, Real fCy, Real fCz, Real fVx, Real fVy, Real fVz, Real& rfIx, Real& rfIy, Real& rfIz, bool bAboveFace); int FindJustEdgeIntersection (Real fCy, Real fEx, Real fEy, Real fEz, Real fDx, Real fDz, Real fVx, Real fVy, Real fVz, Real& rfIx, Real& rfIy, Real& rfIz); int FindEdgeRegionIntersection (Real fEx, Real fEy, Real fEz, Real fCx, Real fCy, Real fCz, Real fVx, Real fVy, Real fVz, Real& rfIx, Real& rfIy, Real& rfIz, bool bAboveEdge); int FindVertexRegionIntersection (Real fEx, Real fEy, Real fEz, Real fCx, Real fCy, Real fCz, Real fVx, Real fVy, Real fVz, Real& rfIx, Real& rfIy, Real& rfIz); // the objects to intersect const Box3<Real>* m_pkBox; const Sphere3<Real>* m_pkSphere; // point of intersection Vector3<Real> m_kContactPoint; }; typedef IntrBox3Sphere3<float> IntrBox3Sphere3f; typedef IntrBox3Sphere3<double> IntrBox3Sphere3d; } #endif
0cf0479a58de8a8666ca6666687d8b8066d0a0a8
70e30b2e3a578f509b66f1ee1049b23c5fcceaf0
/3268/main.cpp
6be484e29525c2d4c414325a1c5c579e0910822c
[]
no_license
xyzwj/POJ
283d20a646eb71e42f0b68a4fea56d78c2145769
ec9389bc57cf6ec4a2c02ad2e8ae28c4130b7d85
refs/heads/master
2021-01-17T12:47:14.180223
2012-06-14T23:03:19
2012-06-14T23:03:19
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,932
cpp
main.cpp
// Limit: 65536K 2000MS // Used : 988K 94MS #include <iostream> #include <iomanip> #include <sstream> #include <vector> #include <map> #include <set> #include <queue> #include <stack> #include <algorithm> #include <cstdio> #include <cmath> #include <cstring> using namespace std; typedef vector<int> VI; typedef vector<VI> VVI; typedef vector<string> VS; typedef pair<int, int> PII; typedef long long LL; #define ALL(a) (a).begin(),(a).end() #define REP(i,n) for(int i=0;i<(n);++i) const double EPS = 1e-10; const double PI = acos(-1.0); #define dump(x) cerr << " (L" << __LINE__ << ") " << #x << " = " << (x) << endl; #define dumpv(x) cerr << " (L" << __LINE__ << ") " << #x << " = "; REP(q,(x).size()) cerr << (x)[q] << " "; cerr << endl; template<typename T1, typename T2> ostream& operator<<(ostream& s, const pair<T1, T2>& d) {return s << "(" << d.first << "," << d.second << ")";} struct edge { int to, cost; edge(int t, int c): to(t), cost(c) {} }; const int INF = 1e9; vector<int> dijkstra(int N, int X, vector<vector<edge> >& G) { vector<int> dist(N, INF); priority_queue<PII, vector<PII>, greater<PII> > que; que.push(PII(0, X-1)); while (!que.empty()) { PII p = que.top(); que.pop(); int d = p.first; int v = p.second; if (dist[v] == INF) { dist[v] = d; REP(i, G[v].size()) { edge& e = G[v][i]; if (dist[e.to] == INF) { que.push(PII(dist[v] + e.cost, e.to)); } } } } return dist; } int main() { cin.tie(0); ios::sync_with_stdio(false); int N, M, X; cin >> N >> M >> X; vector<vector<edge> > G1(N), G2(N); REP(i, M) { int A, B, T; cin >> A >> B >> T; G1[A-1].push_back(edge(B-1, T)); G2[B-1].push_back(edge(A-1, T)); } vector<int> dist1 = dijkstra(N, X, G1); vector<int> dist2 = dijkstra(N, X, G2); int ans = 0; REP(i, N) ans = max(ans, dist1[i] + dist2[i]); cout << ans << endl; }
122c040620ea5da469f5926a20293cfddaf1c8ea
10e6c6416f768d9ce74e70fe900ad475facf41a3
/src/media/ffmpeg.h
2869cd57fea301bcb220fd0caa50041ca85ef173
[ "MIT" ]
permissive
longlonghands/fps-challenge
eddfb809c90d95b0efa5d344ed658064aef672a0
020c133a782285364d52b1c98e9661c9aedfd96d
refs/heads/main
2022-12-27T07:29:56.210284
2020-10-13T09:00:48
2020-10-13T09:00:48
302,957,861
0
0
null
null
null
null
UTF-8
C++
false
false
1,295
h
ffmpeg.h
#pragma once #include <string> #include <memory> #include <inttypes.h> #define __STDC_CONSTANT_MACROS extern "C" { #include <libavutil/opt.h> #include <libavcodec/avcodec.h> #include <libavformat/avformat.h> #include <libswscale/swscale.h> #include <libavutil/log.h> #include <libavutil/base64.h> #include <libavdevice/avdevice.h> #include <libavutil/imgutils.h> } #include <sstream> namespace challenge { namespace media { class FFmpegInitializer { static std::unique_ptr<FFmpegInitializer> instance; FFmpegInitializer(); public: ~FFmpegInitializer(); static void Init(); }; class FFmpegException: public std::exception { public: FFmpegException(int error, std::string message = "") { size_t bufferSize = 100; char buffer[bufferSize]; memset(buffer, 0, bufferSize); av_strerror(error, buffer, bufferSize); std::stringstream strBuilder; strBuilder << message << "(error: '" << buffer << "')"; msg = strBuilder.str(); } FFmpegException(std::string message) { msg = message; } virtual const char* what() const noexcept override { return msg.c_str(); } private: std::string msg; }; }} // namespace challenge::media
13912499dd87817a42e21b76a2ada80f810345d9
851a98a0428854bb0e928d42e546e7fa25943003
/src/objects/tex_string.cpp
051ff1d2e44fe0ce0aca23a696ee16a7d02f69bf
[ "MIT" ]
permissive
algorithm-archivists/GathVL
18aeea5756d1453c947fdcf8d4c7331d50305596
0e5c682d8ba0e63129384f7ba102203ce801f4d8
refs/heads/master
2021-12-24T12:25:02.555141
2021-12-16T15:46:41
2021-12-16T15:46:41
126,804,528
12
4
MIT
2021-12-16T15:46:41
2018-03-26T09:21:43
C
UTF-8
C++
false
false
5,514
cpp
tex_string.cpp
#include "../../include/objects/tex_string.h" #include "../../include/stb_image.h" #include "../../include/stb_image_resize.h" #include "../../include/systems/system.h" #include <cstdio> #include <iostream> #include <fstream> #include <random> #include <vector> static const char tex_template[] = "\\documentclass[preview]{standalone}\n" "\\usepackage{amsmath}\n" "\\usepackage{amssymb}\n\n" "\\begin{document}\n"; static std::string string_generator() { std::random_device rd; std::mt19937 gen(rd()); std::uniform_int_distribution<> dis(97, 122); int loop_len = (int)dis(gen) % 10 + 5; std::string ret("tex_string_file_"); for (int i = 0; i < loop_len; ++i) { ret.push_back((char)dis(gen)); } ret += "_."; return ret; } static int tex_to_png(const std::string& str, const std::string& url) { std::ofstream tex_file(url + "tex", std::ios_base::out); tex_file.write(tex_template, sizeof(tex_template) - 1); tex_file.write(str.c_str(), str.size()); tex_file.write("\n\\end{document}", 15); tex_file.close(); std::vector<std::string> latex_args = {"latex", url + "tex"}; if (subprocess("/usr/bin/latex", latex_args)) { return 1; } std::vector<std::string> png_args = {"dvipng", url + "dvi", "-D", "2000", "-bg", "transparent","-o", url + "png"}; return subprocess("/usr/bin/dvipng", png_args); } static inline void format_converter(unsigned char *in, unsigned char *out, int width, int height) { for (int i = 0; i < height; ++i) { for (int j = 0; j < width * 4; j += 4) { out[j + 2] = in[j]; out[j + 1] = in[j + 1]; out[j] = in[j + 2]; out[j + 3] = in[j + 3]; } out += width * 4; in += width * 4; } } void tex_string::draw(cairo_t *ctx) const { if (image_data) { int stride = 0; unsigned char *data = nullptr; cairo_surface_t *surface; if (size.x <= 0 || size.y <= 0 || (size.x == width && size.y == height)) { stride = cairo_format_stride_for_width(CAIRO_FORMAT_ARGB32, width); data = new unsigned char[stride * height]; if (!data) { std::cout << "Malloc failed in tex_string." << std::endl; return; } format_converter(image_data, data, width, height); surface = cairo_image_surface_create_for_data(data, CAIRO_FORMAT_ARGB32, width, height, stride); } else { stride = cairo_format_stride_for_width(CAIRO_FORMAT_ARGB32, (int)size.x); data = new unsigned char[stride * (int)size.y]; if (!data) { std::cout << "Malloc for data failed in tex_string." << std::endl; return; } unsigned char *tmp = new unsigned char[(int)(size.x * size.y * 4)]; if (!tmp) { std::cout << "Malloc failed in tex_string." << std::endl; delete[] data; return; } stbir_resize_uint8(image_data, width, height, 0, tmp, size.x, size.y, 0, 4); format_converter(tmp, data, (int)size.x, (int)size.y); surface = cairo_image_surface_create_for_data(data, CAIRO_FORMAT_ARGB32, (int)size.x, (int)size.y, stride); delete[] tmp; } cairo_save(ctx); cairo_translate(ctx, location.x, location.y); cairo_rotate(ctx, rotation); cairo_set_source_rgba(ctx, clr.r, clr.g, clr.b, clr.a); cairo_mask_surface(ctx, surface, 0, 0); cairo_fill(ctx); cairo_restore(ctx); cairo_surface_destroy(surface); delete[] data; } } tex_string::tex_string(const std::string& str, vec location, vec size, double rotation, color clr) : location(location), size(size), rotation(rotation), clr(clr) { texfile = string_generator(); if (tex_to_png(str, texfile)) { std::cout << "Failed to make Latex png file." << std::endl; return; } std::string tmp = texfile + "png"; image_data = stbi_load(tmp.c_str(), &width, &height, NULL, 4); if (!image_data) { std::cout << "The image " << tmp << " can't be opened." << std::endl; } } tex_string::~tex_string() { std::string tmp = texfile + "tex"; if (std::remove(tmp.c_str()) != 0) { std::cout << "The file " << tmp << " hasn't been removed" << std::endl; } tmp = texfile + "dvi"; if (std::remove(tmp.c_str()) != 0) { std::cout << "The file " << tmp << " hasn't been removed" << std::endl; } tmp = texfile + "log"; if (std::remove(tmp.c_str()) != 0) { std::cout << "The file " << tmp << " hasn't been removed" << std::endl; } tmp = texfile + "aux"; if (std::remove(tmp.c_str()) != 0) { std::cout << "The file " << tmp << " hasn't been removed" << std::endl; } tmp = texfile + "png"; if (std::remove(tmp.c_str()) != 0) { std::cout << "The file " << tmp << " hasn't been removed" << std::endl; } stbi_image_free(image_data); }
f1820a0e278f6d9bf8e69ba47733b8a6311c0e92
ba77bae271c17c794b7cf6e05862a85f6e21b283
/Source/Lift_Off_Laetus/PowerUps/HarvestSource.h
7a64b75edfd1b088334cb6c8dbba5b77d58d283b
[ "MIT" ]
permissive
Used-Unicycle-Usurpers/Lift_Off_Laetus
0dc2fe48a1621ad6d52639415df1634bf0670ea5
de72f3cf9b8edec6e884a0970fc4c0507a8cbc7c
refs/heads/main
2023-04-23T13:05:17.509567
2021-05-13T19:49:56
2021-05-13T19:49:56
356,085,470
0
1
MIT
2021-05-13T19:49:57
2021-04-09T00:27:54
C++
UTF-8
C++
false
false
1,207
h
HarvestSource.h
// Fill out your copyright notice in the Description page of Project Settings. #pragma once #include "CoreMinimal.h" #include "GameFramework/Actor.h" #include "PowerUpActor.h" #include "../GameManagement/GameEnums.h" #include "HarvestSource.generated.h" UCLASS() class LIFT_OFF_LAETUS_API AHarvestSource : public AActor { GENERATED_BODY() public: // Sets default values for this actor's properties AHarvestSource(); // Called every frame virtual void Tick(float DeltaTime) override; //Getter for the HarvestSourceType of this AHarvestSouce. HarvestSourceType getHarvestSourceType(); /** * TODO: * Harvest the corresponding material from this space */ virtual APowerUpActor* harvest(); UPROPERTY(EditAnywhere) class UStaticMeshComponent* mesh; UPROPERTY(EditAnywhere) class UPowerUpEffectData* effectToGive; protected: // Called when the game starts or when spawned virtual void BeginPlay() override; //Sets the HarvestSourceType of this AHarvestSource. Only child classes should //be able to set their type. void setHarvestSourceType(HarvestSourceType newType); private: //The type fo AHarvestSource this is (SlimeTree, Rock, or Shrub) HarvestSourceType type; };
f6e271e56ac87e05d97343ce8f752476854e8311
38a0aa9160d74ac7470a97830b13aee81a510a63
/tests/Blast/FileExistenceCheckerTest.cpp
239ce5ce5c9afbf57a98cc31e533d6555a595855
[]
no_license
MarkOates/blast
9339d70dcb8dc4dac2f0b7ff6f28e06640fd6201
bd0d6d49706e88673c2187506cfa6eb0ca9d5cf5
refs/heads/master
2023-08-20T05:54:29.438877
2023-08-17T01:02:42
2023-08-17T01:02:42
116,609,192
0
0
null
2022-08-31T01:35:49
2018-01-08T00:07:51
C++
UTF-8
C++
false
false
1,143
cpp
FileExistenceCheckerTest.cpp
#include <gtest/gtest.h> #include <Blast/FileExistenceChecker.hpp> #ifdef _WIN32 #define TEST_FIXTURES_PATH "/msys64/home/Mark/Repos/blast/tests/fixtures/" #else #define TEST_FIXTURES_PATH "/Users/markoates/Repos/blast/tests/fixtures/" #endif TEST(Blast_FileExistenceCheckerTest, can_be_created_without_blowing_up) { Blast::FileExistenceChecker file_existence_checker; } TEST(Blast_FileExistenceCheckerTest, exists__returns_true_for_regular_files) { std::string test_fixtures_path = TEST_FIXTURES_PATH; std::string expected_file_to_exist = test_fixtures_path + "file_that_exists.txt"; Blast::FileExistenceChecker file_existence_checker(expected_file_to_exist); EXPECT_EQ(true, file_existence_checker.exists()); } TEST(Blast_FileExistenceCheckerTest, exists__returns_false_for_files_that_are_missing) { Blast::FileExistenceChecker file_existence_checker("file_that_does_not_exist.txt"); EXPECT_EQ(false, file_existence_checker.exists()); } TEST(DISABLED_Blast_FileExistenceCheckerTest, exists__returns_false_for_directories) { } TEST(DISABLED_Blast_FileExistenceCheckerTest, exists__returns_true_for_symlinks) { }
d78aec32505a9a6ef487821eabe75bfd37d6e18d
e7f9d01e7fac9d9f2cb7fc8f4cc09d91f4c0d0ed
/Game/unittests_gpp/unittests.cpp
4665e3f7c95522e37742fdb7c70c5e4810855773
[ "MIT" ]
permissive
pampersrocker/risky-epsilon
912a14d92ac53230e305bb7b7cbd2a64c359df2a
28f85a00f9d98c287e83cfca6542c9d78b1ab529
refs/heads/master
2021-01-22T11:37:37.648880
2014-07-31T22:43:39
2014-07-31T22:43:39
null
0
0
null
null
null
null
UTF-8
C++
false
false
941
cpp
unittests.cpp
#include "stdafx.h" #include "gep/unittest/UnittestManager.h" // implement new/delete #include "gep/memory/newdelete.inl" int main(int argc, const char* argv[]) { bool doDebugBreaks = false; bool pause = true; for(int i=1; i<argc; i++) { if(!strcmp(argv[i], "-debugbreak")) doDebugBreaks = true; else if(!strcmp(argv[i], "-nopause")) pause = false; else { printf("Unkown command line option %s\n", argv[i]); return -1; } } if(argc > 1 && !strcmp(argv[1], "-debugbreak")) { doDebugBreaks = true; } gep::UnittestManager::instance().setDoDebugBreaks(doDebugBreaks); int numFailedTests = gep::UnittestManager::instance().runAllTests(); gep::UnittestManager::instance().destoryGlobalInstance(); if(pause) system("pause"); return numFailedTests; }
43517eef1e0f2994be76ae017b8bd479a5902a58
e6d37821568e951670ad4efdf6ceb28ae6fd3bca
/Src/SDE/SimulateNavigate/SpatialIndex/StaticRTree/StaticRTree.cpp
9bca0649cc98ed22315123a184f4dd3476e40d80
[]
no_license
xzrunner/sde
8e927f1cad72182935053ffcb89b16cbeb07406e
ad1b5a2252e84bd8351205f9b2386358dc5c9c3b
refs/heads/master
2020-03-22T18:57:04.442857
2018-07-10T22:28:19
2018-07-10T22:28:19
140,493,562
0
0
null
null
null
null
UTF-8
C++
false
false
17,844
cpp
StaticRTree.cpp
#include "StaticRTree.h" #include "../../../NVDataPublish/Features/BulkLoader.h" #include "../../../NVDataPublish/Features/Data.h" #include "../../../NVDataPublish/Features/Strategy.h" using namespace IS_SDE; using namespace IS_SDE::SimulateNavigate::SpatialIndex::StaticRTree; ISpatialIndex* SimulateNavigate::SpatialIndex::StaticRTree::returnStaticRTree(IStorageManager& sm, Tools::PropertySet& ps) { ISpatialIndex* si = new SimulateNavigate::SpatialIndex::StaticRTree::StaticRTree(sm, ps); return si; } ISpatialIndex* SimulateNavigate::SpatialIndex::StaticRTree::createNewStaticRTree( IStorageManager& sm, id_type& indexIdentifier, size_t condenseStrategy ) { Tools::Variant var; Tools::PropertySet ps; var.m_varType = Tools::VT_LONG; var.m_val.lVal = condenseStrategy; ps.setProperty("CondenseStrategy", var); ISpatialIndex* ret = returnStaticRTree(sm, ps); var = ps.getProperty("IndexIdentifier"); indexIdentifier = var.m_val.lVal; return ret; } ISpatialIndex* SimulateNavigate::SpatialIndex::StaticRTree::createAndBulkLoadNewStaticRTree( BulkLoadMethod m, IDataStream& stream, IStorageManager& sm, NVDataPublish::Features::CondenseData& cd, id_type& indexIdentifier, size_t condenseStrategy ) { ISpatialIndex* tree = createNewStaticRTree(sm, indexIdentifier, condenseStrategy); NVDataPublish::Features::LayerBulkLoader lbl; switch (m) { case BLM_STR: //FIXME: find available memory here. lbl.bulkLoadUsingSTR(static_cast<StaticRTree*>(tree), stream, cd, 200000); break; default: throw Tools::IllegalArgumentException("createAndBulkLoadNewStaticRTree: Unknown bulk load method."); break; } return tree; } ISpatialIndex* SimulateNavigate::SpatialIndex::StaticRTree::loadStaticRTree(IStorageManager& sm, id_type indexIdentifier) { Tools::Variant var; Tools::PropertySet ps; var.m_varType = Tools::VT_LONG; var.m_val.lVal = static_cast<int32_t>(indexIdentifier); ps.setProperty("IndexIdentifier", var); return returnStaticRTree(sm, ps); } SimulateNavigate::SpatialIndex::StaticRTree::StaticRTree:: StaticRTree(IStorageManager& sm, Tools::PropertySet& ps) : m_pStorageManager(&sm), m_rootID(0), m_headerID(StorageManager::NewPage), m_maxDisplayCount(200), m_rectPool(1000), m_nodePool(100), m_condenseStrategy(NULL) { #ifdef PTHREADS pthread_rwlock_init(&m_rwLock, NULL); #else m_rwLock = false; #endif Tools::Variant var = ps.getProperty("IndexIdentifier"); if (var.m_varType != Tools::VT_EMPTY) { if (var.m_varType != Tools::VT_LONG) throw Tools::IllegalArgumentException( "StaticRTree: Property IndexIdentifier must be Tools::VT_LONG" ); m_headerID = var.m_val.lVal; initOld(ps); } else { initNew(ps); var.m_varType = Tools::VT_LONG; var.m_val.lVal = static_cast<int32_t>(m_headerID); ps.setProperty("IndexIdentifier", var); } } SimulateNavigate::SpatialIndex::StaticRTree::StaticRTree:: ~StaticRTree() { #ifdef PTHREADS pthread_rwlock_destroy(&m_rwLock); #endif setFirstDisplayScope(); storeHeader(); } // // ISpatialIndex interface // void SimulateNavigate::SpatialIndex::StaticRTree::StaticRTree:: insertData(size_t len, const byte* pData, const IShape& shape, id_type objID, id_type* nodeID) { throw Tools::NotSupportedException("Should never be called. "); } bool SimulateNavigate::SpatialIndex::StaticRTree::StaticRTree:: deleteData(const IShape& shape, id_type shapeIdentifier) { throw Tools::NotSupportedException("Should never be called. "); } void SimulateNavigate::SpatialIndex::StaticRTree::StaticRTree:: containsWhatQuery(const IShape& query, IVisitor& v, bool isFine) { throw Tools::NotSupportedException("Should never be called. "); } void SimulateNavigate::SpatialIndex::StaticRTree::StaticRTree:: intersectsWithQuery(const IShape& query, IVisitor& v, bool isFine) { rangeQuery(IntersectionQuery, query, v, isFine); } void SimulateNavigate::SpatialIndex::StaticRTree::StaticRTree:: pointLocationQuery(const Point& query, IVisitor& v, bool isFine) { throw Tools::NotSupportedException("Should never be called. "); } void SimulateNavigate::SpatialIndex::StaticRTree::StaticRTree:: nearestNeighborQuery(uint32_t k, const IShape& query, IVisitor& v, INearestNeighborComparator& nnc) { throw Tools::NotSupportedException("Should never be called. "); } void SimulateNavigate::SpatialIndex::StaticRTree::StaticRTree:: nearestNeighborQuery(uint32_t k, const IShape& query, IVisitor& v) { throw Tools::NotSupportedException("Should never be called. "); } void SimulateNavigate::SpatialIndex::StaticRTree::StaticRTree:: selfJoinQuery(const IShape& s, IVisitor& v) { throw Tools::NotSupportedException("Should never be called. "); } void SimulateNavigate::SpatialIndex::StaticRTree::StaticRTree:: queryStrategy(IQueryStrategy& qs) { #ifdef PTHREADS Tools::SharedLock lock(&m_rwLock); #else if (m_rwLock == false) m_rwLock = true; else throw Tools::ResourceLockedException("queryStrategy: cannot acquire a shared lock"); #endif id_type next = m_rootID; bool hasNext = true; try { while (hasNext) { NodePtr n = readNode(next); qs.getNextEntry(*n, next, hasNext); if (qs.shouldStoreEntry()) writeNode(n.get()); } #ifndef PTHREADS m_rwLock = false; #endif } catch (...) { #ifndef PTHREADS m_rwLock = false; #endif throw; } } bool SimulateNavigate::SpatialIndex::StaticRTree::StaticRTree:: countIntersectsQuery(const IShape& query, ICountVisitor& v) { std::stack<NodePtr> st; NodePtr root = readNode(m_rootID); if (root->m_children > 0 && query.intersectsShape(root->m_nodeMBR)) st.push(root); while (! st.empty()) { NodePtr n = st.top(); st.pop(); if (n->isLeaf()) { IShape* nodeMBR; n->getShape(&nodeMBR); bool bNodeIn = query.containsShape(*nodeMBR); delete nodeMBR; if (bNodeIn) { v.countNode(*n.get()); if (v.overUpperLimit()) return true; } else { for (size_t cChild = 0; cChild < n->m_children; cChild++) { if (query.intersectsShape(*(n->m_ptrMBR[cChild]))) { v.countData(*n.get(), cChild, query); if (v.overUpperLimit()) return true; } } } } else { for (size_t cChild = 0; cChild < n->m_children; cChild++) { if (query.intersectsShape(*(n->m_ptrMBR[cChild]))) st.push(readNode(n->m_pIdentifier[cChild])); } } } return false; } void SimulateNavigate::SpatialIndex::StaticRTree::StaticRTree:: getIndexProperties(Tools::PropertySet& out) const { throw Tools::NotSupportedException("Should never be called. "); } void SimulateNavigate::SpatialIndex::StaticRTree::StaticRTree:: addCommand(ICommand* in, CommandType ct) { throw Tools::NotSupportedException("Should never be called. "); } bool SimulateNavigate::SpatialIndex::StaticRTree::StaticRTree:: isIndexValid() { throw Tools::NotSupportedException("Should never be called. "); } void SimulateNavigate::SpatialIndex::StaticRTree::StaticRTree:: getStatistics(IStatistics** out) const { throw Tools::NotSupportedException("Should never be called. "); } void SimulateNavigate::SpatialIndex::StaticRTree::StaticRTree:: readData(id_type nodeID, id_type objID, IShape** out) { throw Tools::NotSupportedException("Should never be called. "); } id_type SimulateNavigate::SpatialIndex::StaticRTree::StaticRTree:: nextObjID() { throw Tools::NotSupportedException("Should never be called. "); } void SimulateNavigate::SpatialIndex::StaticRTree::StaticRTree:: setDisplayRegion(const Rect& scope) { m_firstDisplayScope = scope; } const Rect& SimulateNavigate::SpatialIndex::StaticRTree::StaticRTree:: getDisplayRegion() { return m_firstDisplayScope; } void SimulateNavigate::SpatialIndex::StaticRTree::StaticRTree:: readDataByAddress(id_type nodeID, size_t offset, IShape** s) const { size_t dataLength; byte* buffer; try { m_pStorageManager->loadByteArray(nodeID, dataLength, &buffer); } catch (Tools::InvalidPageException& e) { std::cerr << e.what() << std::endl; //std::cerr << *this << std::endl; throw Tools::IllegalStateException("readTopoEdge: failed with Tools::InvalidPageException"); } byte* ptr = buffer + offset; ptr += Node::MBR_SIZE + Node::EDGE_ID_SIZE; size_t len = 0; memcpy(&len, ptr, Node::EACH_CHILD_SIZE_SIZE); ptr += Node::EACH_CHILD_SIZE_SIZE; m_condenseStrategy->loadFromByteArray(s, ptr, len); delete[] buffer; } void SimulateNavigate::SpatialIndex::StaticRTree::StaticRTree:: initNew(Tools::PropertySet& ps) { Tools::Variant var; // node pool capacity var = ps.getProperty("NodePoolCapacity"); if (var.m_varType != Tools::VT_EMPTY) { if (var.m_varType != Tools::VT_LONG) throw Tools::IllegalArgumentException("initNew: Property IndexPoolCapacity must be Tools::VT_LONG"); m_nodePool.setCapacity(var.m_val.lVal); } // rect pool capacity var = ps.getProperty("RectPoolCapacity"); if (var.m_varType != Tools::VT_EMPTY) { if (var.m_varType != Tools::VT_LONG) throw Tools::IllegalArgumentException("initNew: Property RectPoolCapacity must be Tools::VT_LONG"); m_rectPool.setCapacity(var.m_val.lVal); } var = ps.getProperty("CondenseStrategy"); if (var.m_varType != Tools::VT_EMPTY) { if (var.m_varType != Tools::VT_LONG) throw Tools::IllegalArgumentException("initNew: Property CondenseStrategy must be Tools::VT_LONG"); NVDataPublish::CondenseStrategyType cs = static_cast<NVDataPublish::CondenseStrategyType>(var.m_val.lVal); switch (cs) { case NVDataPublish::CondenseStrategyType::CS_NO_OFFSET: m_condenseStrategy = new NVDataPublish::Features::NoOffsetCondenseStrategy; break; default: throw Tools::IllegalArgumentException("Unknown bulk condense strategy."); break; } } m_infiniteRect.makeInfinite(); Node root(this, -1); m_rootID = writeNode(&root); storeHeader(); } void SimulateNavigate::SpatialIndex::StaticRTree::StaticRTree:: initOld(Tools::PropertySet& ps) { loadHeader(); // only some of the properties may be changed. // the rest are just ignored. Tools::Variant var; // index pool capacity var = ps.getProperty("NodePoolCapacity"); if (var.m_varType != Tools::VT_EMPTY) { if (var.m_varType != Tools::VT_LONG) throw Tools::IllegalArgumentException("initOld: Property IndexPoolCapacity must be Tools::VT_LONG"); m_nodePool.setCapacity(var.m_val.lVal); } // rect pool capacity var = ps.getProperty("RectPoolCapacity"); if (var.m_varType != Tools::VT_EMPTY) { if (var.m_varType != Tools::VT_LONG) throw Tools::IllegalArgumentException("initOld: Property RectPoolCapacity must be Tools::VT_LONG"); m_rectPool.setCapacity(var.m_val.lVal); } m_infiniteRect.makeInfinite(); } void SimulateNavigate::SpatialIndex::StaticRTree::StaticRTree:: storeHeader() { const size_t headerSize = sizeof(id_type) + // m_rootID sizeof(Rect) + // m_firstDisplayScope sizeof(size_t); // m_condenseStrategy byte* header = new byte[headerSize]; byte* ptr = header; memcpy(ptr, &m_rootID, sizeof(id_type)); ptr += sizeof(id_type); size_t lenRect = m_firstDisplayScope.getByteArraySize(); if (m_firstDisplayScope.isEmpty()) { memset(ptr, 0, lenRect); } else { byte* pRect; size_t lenRect; m_firstDisplayScope.storeToByteArray(&pRect, lenRect); memcpy(ptr, pRect, lenRect); delete[] pRect; } ptr += lenRect; size_t type = m_condenseStrategy->getType(); memcpy(ptr, &type, sizeof(size_t)); ptr += sizeof(size_t); m_pStorageManager->storeByteArray(m_headerID, headerSize, header); delete[] header; } void SimulateNavigate::SpatialIndex::StaticRTree::StaticRTree:: loadHeader() { size_t headerSize; byte* header = 0; m_pStorageManager->loadByteArray(m_headerID, headerSize, &header); byte* ptr = header; memcpy(&m_rootID, ptr, sizeof(id_type)); ptr += sizeof(id_type); size_t rectSize = m_firstDisplayScope.getByteArraySize(); byte* pRect = new byte[rectSize]; memcpy(pRect, ptr, rectSize); m_firstDisplayScope.loadFromByteArray(pRect); delete pRect; ptr += rectSize; size_t type; memcpy(&type, ptr, sizeof(size_t)); ptr += sizeof(size_t); NVDataPublish::CondenseStrategyType cs = static_cast<NVDataPublish::CondenseStrategyType>(type); switch (cs) { case NVDataPublish::CondenseStrategyType::CS_NO_OFFSET: m_condenseStrategy = new NVDataPublish::Features::NoOffsetCondenseStrategy; break; default: throw Tools::IllegalArgumentException("Unknown bulk condense strategy."); break; } delete[] header; } void SimulateNavigate::SpatialIndex::StaticRTree::StaticRTree:: rangeQuery(RangeQueryType type, const IShape& query, IVisitor& v, bool isFine) { #ifdef PTHREADS Tools::SharedLock lock(&m_rwLock); #else if (m_rwLock == false) m_rwLock = true; else throw Tools::ResourceLockedException("rangeQuery: cannot acquire a shared lock"); #endif try { std::stack<NodePtr> st; NodePtr root = readNode(m_rootID); if (root->m_children > 0 && query.intersectsShape(root->m_nodeMBR)) st.push(root); while (! st.empty()) { NodePtr n = st.top(); st.pop(); if (n->isLeaf()) { v.visitNode(*n); IShape* nodeMBR; n->getShape(&nodeMBR); bool bNodeIn = dynamic_cast<Rect*>(const_cast<IShape*>(&query)) && query.containsShape(*nodeMBR); delete nodeMBR; if (bNodeIn) { v.visitData(*n); if (v.shouldCheckEachData()) { for (size_t cChild = 0; cChild < n->m_children; cChild++) { NVDataPublish::Features::Data data = NVDataPublish::Features::Data(n->m_pDataLength[cChild], n->m_pData[cChild], *(n->m_ptrMBR[cChild]), n->m_pIdentifier[cChild], m_condenseStrategy); v.visitData(data, cChild); } } } else { for (size_t cChild = 0; cChild < n->m_children; cChild++) { bool b; if (bNodeIn) { b = true; } else { if (type == ContainmentQuery) { b = query.containsShape(*(n->m_ptrMBR[cChild])); if (isFine && !b) { IShape* pS; NVDataPublish::Features::Data(n->m_pDataLength[cChild], n->m_pData[cChild], *(n->m_ptrMBR[cChild]), n->m_pIdentifier[cChild], m_condenseStrategy).getShape(&pS); b = query.containsShape(*pS); delete pS; } } else { b = query.intersectsShape(*(n->m_ptrMBR[cChild])); if (isFine && b) { IShape* pS; NVDataPublish::Features::Data(n->m_pDataLength[cChild], n->m_pData[cChild], *(n->m_ptrMBR[cChild]), n->m_pIdentifier[cChild], m_condenseStrategy).getShape(&pS); b = query.intersectsShape(*pS); delete pS; } } } if (b) { NVDataPublish::Features::Data data = NVDataPublish::Features::Data(n->m_pDataLength[cChild], n->m_pData[cChild], *(n->m_ptrMBR[cChild]), n->m_pIdentifier[cChild], m_condenseStrategy); v.visitData(data, cChild); } } } } else { v.visitNode(*n); for (size_t cChild = 0; cChild < n->m_children; cChild++) { if (query.intersectsShape(*(n->m_ptrMBR[cChild]))) st.push(readNode(n->m_pIdentifier[cChild])); } } } #ifndef PTHREADS m_rwLock = false; #endif } catch (...) { #ifndef PTHREADS m_rwLock = false; #endif throw; } } id_type SimulateNavigate::SpatialIndex::StaticRTree::StaticRTree:: writeNode(Node* n) { byte* buffer; size_t dataLength; n->storeToByteArray(&buffer, dataLength); id_type page; if (n->m_identifier < 0) page = StorageManager::NewPage; else page = n->m_identifier; try { m_pStorageManager->storeByteArray(page, dataLength, buffer); delete[] buffer; } catch (Tools::InvalidPageException& e) { delete[] buffer; std::cerr << e.what() << std::endl; //std::cerr << *this << std::endl; throw Tools::IllegalStateException("writeNode: failed with Tools::InvalidPageException"); } if (n->m_identifier < 0) n->m_identifier = page; return page; } NodePtr SimulateNavigate::SpatialIndex::StaticRTree::StaticRTree:: readNode(id_type id) { size_t dataLength; byte* buffer; try { m_pStorageManager->loadByteArray(id, dataLength, &buffer); } catch (Tools::InvalidPageException& e) { std::cerr << e.what() << std::endl; //std::cerr << *this << std::endl; throw Tools::IllegalStateException("readNode: failed with Tools::InvalidPageException"); } try { NodePtr n = m_nodePool.acquire(); if (n.get() == 0) n = NodePtr(new Node(this, -1), &m_nodePool); n->m_tree = this; n->m_identifier = id; n->m_bLeaf = false; n->loadFromByteArray(buffer); delete[] buffer; return n; } catch (...) { delete[] buffer; throw; } } void SimulateNavigate::SpatialIndex::StaticRTree::StaticRTree:: deleteNode(Node* n) { try { m_pStorageManager->deleteByteArray(n->m_identifier); } catch (Tools::InvalidPageException& e) { std::cerr << e.what() << std::endl; //std::cerr << *this << std::endl; throw Tools::IllegalStateException("deleteNode: failed with Tools::InvalidPageException"); } } void SimulateNavigate::SpatialIndex::StaticRTree::StaticRTree:: setFirstDisplayScope() { if (m_firstDisplayScope.isEmpty()) m_firstDisplayScope = readNode(m_rootID)->m_nodeMBR; while (true) { CountRoadVisitor vis(m_maxDisplayCount); if (countIntersectsQuery(m_firstDisplayScope, vis)) m_firstDisplayScope.changeSize(0.5); else break; } } // // class StaticRTree::CountRoadVisitor // void SimulateNavigate::SpatialIndex::StaticRTree::StaticRTree:: CountRoadVisitor::countNode(const INode& node) { m_count += node.getChildrenCount(); } void SimulateNavigate::SpatialIndex::StaticRTree::StaticRTree:: CountRoadVisitor::countData(const INode& node, size_t iData, const IShape& query) { ++m_count; } bool SimulateNavigate::SpatialIndex::StaticRTree::StaticRTree:: CountRoadVisitor::overUpperLimit() const { return m_count > m_upperLimit; }
73b8aade87be24e2f6034dcee54749b8d488a506
85ca284d9c99c841818bf8390f3dc8593eeedb65
/Lesson8/Activity18/travel_itinerary.cpp
76d71a1c227c970d7d91bf11ad4bb8228f1f3c37
[ "MIT" ]
permissive
sunkyoo/CPP-Data-Structures-and-Algorithms
51d28f080fd96fffd8b53df8d296925263b5c7bb
38d68057891f6be998e8d4f169d1e29245d68a96
refs/heads/main
2023-02-28T04:16:30.303510
2021-02-09T02:35:24
2021-02-09T02:35:24
326,623,052
11
2
null
null
null
null
UTF-8
C++
false
false
1,560
cpp
travel_itinerary.cpp
#include <vector> #include <algorithm> #include <iostream> using namespace std; typedef long long LL; const LL MOD = 1000000007; LL TravelItinerary(int n, vector<int> distance) { reverse(distance.begin(), distance.end()); vector<LL> DP(n + 1, 0); vector<LL> sums(n + 2, 0); DP[0] = sums[1] = 1; for (int i = 1; i <= n; i++) { int dist = distance[i - 1]; LL sum = sums[i] - sums[i - dist]; DP[i] = (DP[i] + sum) % MOD; sums[i + 1] = (sums[i] + DP[i]) % MOD; } return (DP[n] < 0) ? DP[n] + MOD : DP[n]; } vector<int> Generate(int n) { vector<int> distance(n); LL val = 1; for (int i = 0; i < n; i++) { val = (val * 1103515245 + 12345) / 65536; val %= 32768; distance[i] = ((val % 10000) % (n - i)) + 1; } return distance; } int main() { int n; cin >> n; vector<int> distance(n); if (n == 1e7) { distance = Generate(n); } else { for (int i = 0; i < n; i++) { cin >> distance[i]; } cout << endl; } LL result = TravelItinerary(n, distance); cout << result << endl; } /* 3 1 1 1 = 1 6 1 2 3 2 2 1 = 9 15 1 2 5 3 4 2 1 3 6 1 2 1 2 2 1 = 789 40 8 5 9 9 11 3 10 9 9 5 1 6 13 3 13 9 8 5 11 8 4 5 10 3 11 4 10 4 12 11 8 9 3 7 6 4 4 3 2 1 = 47382972 100 39 79 34 76 12 28 51 60 53 7 30 48 45 61 66 24 50 64 18 47 7 19 16 72 8 55 72 26 43 57 45 26 68 23 52 28 35 54 2 57 29 59 6 57 8 47 6 44 43 35 50 41 45 4 43 39 44 43 42 26 40 39 32 37 31 20 9 33 30 27 30 29 28 27 26 25 24 23 22 15 20 19 18 17 1 15 14 2 12 11 1 6 8 7 6 5 4 3 2 1 = 790903754 10000000 = 318948158 */
dcdd7b7e48cc058d185707955a6a3635ee556c5c
38616fa53a78f61d866ad4f2d3251ef471366229
/3rdparty/GPSTk/ext/lib/Vdraw/PSImage.cpp
b71197f430145cbc8797f6b49c0bc977853adc2e
[ "GPL-3.0-only", "LGPL-2.0-or-later", "LGPL-3.0-only", "LGPL-2.1-or-later", "GPL-1.0-or-later", "MIT" ]
permissive
wuyou33/Enabling-Robust-State-Estimation-through-Measurement-Error-Covariance-Adaptation
3b467fa6d3f34cabbd5ee59596ac1950aabf2522
2f1ff054b7c5059da80bb3b2f80c05861a02cc36
refs/heads/master
2020-06-08T12:42:31.977541
2019-06-10T15:04:33
2019-06-10T15:04:33
193,229,646
1
0
MIT
2019-06-22T12:07:29
2019-06-22T12:07:29
null
UTF-8
C++
false
false
3,417
cpp
PSImage.cpp
//============================================================================ // // This file is part of GPSTk, the GPS Toolkit. // // The GPSTk 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.0 of the License, or // any later version. // // The GPSTk 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 GPSTk; if not, write to the Free Software Foundation, // Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110, USA // // Copyright 2004, The University of Texas at Austin // //============================================================================ //============================================================================ // //This software developed by Applied Research Laboratories at the University of //Texas at Austin, under contract to an agency or agencies within the U.S. //Department of Defense. The U.S. Government retains all rights to use, //duplicate, distribute, disclose, or release this software. // //Pursuant to DoD Directive 523024 // // DISTRIBUTION STATEMENT A: This software has been approved for public // release, distribution is unlimited. // //============================================================================= ///@file PSImage.cpp Vector plotting in the Postscript format. Class definitions #include <iostream> #include "PSImage.hpp" namespace vdraw { static char VIEWER_ENV_VAR_NAME[]="VDRAW_PS_VIEWER"; /** * Constructors/Destructors */ PSImage::PSImage(std::ostream& stream, double width, double height, ORIGIN_LOCATION iloc): PSImageBase(stream, width,height,iloc), viewerManager(VIEWER_ENV_VAR_NAME) { outputHeader(); } PSImage::PSImage(const char* fname, double width, double height, ORIGIN_LOCATION iloc): PSImageBase(fname, width, height,iloc), viewerManager(VIEWER_ENV_VAR_NAME) { outputHeader(); } PSImage::~PSImage(void) { if (!footerHasBeenWritten) outputFooter(); } /** * Methods */ void PSImage::outputHeader(void) { using namespace std; ostr << "%!" << endl; ostr << "%% Created by vdraw" << endl; ostr << "%%" << endl; } void PSImage::outputFooter(void) { using namespace std; ostr << "showpage" << endl; footerHasBeenWritten = true; } /** * This function closes the output stream and launches a browser. */ void PSImage::view(void) throw (VDrawException) { // close up the file's contents outputFooter(); // First flush the file stream. ostr.flush(); // Register viewers in case they haven't been registered. viewerManager.registerViewer("ggv"); viewerManager.registerViewer("ghostview"); viewerManager.registerViewer("evince"); viewerManager.registerViewer("kghostview"); viewerManager.registerViewer("gv"); // Use the viewerManager viewerManager.view(filename); return; } } // namespace vdraw
10a59167c8c1836140be6db05dde3743d8c6ebfe
774b8fcea7c8b57b7494cc7f48c6593f5e3e0517
/extras/ESP8266WiFi_nossl_noleak/src/ESP8266WiFiAP.h
74e885026c248b9640678f2208acc9fef6eecfe0
[ "MIT" ]
permissive
Mixiaoxiao/Arduino-HomeKit-ESP8266
a180603fe20db0374d00ce2266827249151e76af
8a8e1a065005e9252d728b24f96f6d0b29993f67
refs/heads/master
2023-08-03T12:49:47.785503
2022-07-21T18:02:27
2022-07-21T18:02:27
240,946,290
1,385
274
MIT
2023-07-19T12:21:00
2020-02-16T18:50:03
C
UTF-8
C++
false
false
2,103
h
ESP8266WiFiAP.h
/* ESP8266WiFiAP.h - esp8266 Wifi support. Based on WiFi.h from Arduino WiFi shield library. Copyright (c) 2011-2014 Arduino. All right reserved. Modified by Ivan Grokhotkov, December 2014 Reworked by Markus Sattler, December 2015 This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef ESP8266WIFIAP_H_ #define ESP8266WIFIAP_H_ #include "ESP8266WiFiType.h" #include "ESP8266WiFiGeneric.h" class ESP8266WiFiAPClass { // ---------------------------------------------------------------------------------------------- // ----------------------------------------- AP function ---------------------------------------- // ---------------------------------------------------------------------------------------------- public: bool softAP(const char* ssid, const char* passphrase = NULL, int channel = 1, int ssid_hidden = 0, int max_connection = 4); bool softAP(const String& ssid,const String& passphrase = emptyString,int channel = 1,int ssid_hidden = 0,int max_connection = 4); bool softAPConfig(IPAddress local_ip, IPAddress gateway, IPAddress subnet); bool softAPdisconnect(bool wifioff = false); uint8_t softAPgetStationNum(); IPAddress softAPIP(); uint8_t* softAPmacAddress(uint8_t* mac); String softAPmacAddress(void); String softAPSSID() const; String softAPPSK() const; protected: }; #endif /* ESP8266WIFIAP_H_*/
037dfd362648e61b6c02d100ff6c45b6145ef2dd
7d0de46d1e9e8eb84cd1061fa146dcf06ab8b0a3
/DEMO/DEMO/Pista.cpp
92030e0806b1d8863e845bf90874b09b99892ba1
[]
no_license
fundDEMO/DEMOProject
118f079d225a424563290b89660b92942a46dc23
644724011e36f2e4d9135dbe3d320983c8a5e0bf
refs/heads/master
2021-01-10T18:59:49.441109
2015-01-16T20:22:27
2015-01-16T20:22:27
28,597,057
0
0
null
null
null
null
WINDOWS-1250
C++
false
false
775
cpp
Pista.cpp
// Pista.cpp: implementación de la clase Pista #include "Pista.h" #include <vector> #include <string> Pista::Pista() // Constructor default. { pistaId = ""; audio = ""; clipEn0 = new ClockTime(0, 0, 0, 0); efectosAplicados = new std::vector<Efecto*>; masterVolume = 0.0f; looped = false; activa = true; modificable = true; seleccionada = false; vacia = true; historial = false; numEf = 0; } Pista::Pista(std::string& au) // Constructor con valores default y referencia a un clip de audio. { Pista(); audio = &au; } Pista::Pista(const std::string& id, std::string& au, const ClockTime& en0, const std::vector<Segmento*>& segs, const std::vector<Efecto*>& efcts, float mstrVol, bool loop, bool act, bool mod, bool vac) { Pista(au); }
4c6def7941509992ce873b716d2bbc534560f0fa
1990124c36c0417193293380473de3d86ee85e8c
/test/core/src/opcodes/extended/cpufirmware_sla.cpp
1423eb29a19a5dff702caca20293d910f517b021
[]
no_license
ien646/sleepy
d60ae1b160eab265f342c34495e69c6efbca7e75
73c5cb7a2591fb1e886998dd51a9f10c652927e9
refs/heads/master
2020-04-25T06:08:40.682867
2020-01-06T22:01:53
2020-01-06T22:01:53
null
0
0
null
null
null
null
UTF-8
C++
false
false
6,512
cpp
cpufirmware_sla.cpp
#include <catch2/catch.hpp> #include "../../cpufw_test_init.hpp" namespace sleepy { TEST_CASE("CpuFirmware_SLA") { SECTION("CpuFirmware_SLA_Registers_Flags") { CPUFW_SLEEPY_TESTINIT(); auto& sla_b = inst_map[opcode(0xCB, 0x20)]; auto& sla_c = inst_map[opcode(0xCB, 0x21)]; auto& sla_d = inst_map[opcode(0xCB, 0x22)]; auto& sla_e = inst_map[opcode(0xCB, 0x23)]; auto& sla_h = inst_map[opcode(0xCB, 0x24)]; auto& sla_l = inst_map[opcode(0xCB, 0x25)]; auto& sla_a = inst_map[opcode(0xCB, 0x27)]; auto test_zero_flag = [&](const vcpu_instruction& inst, u8& reg) { regs.reset_flags(); reg = 0x00; inst.call(nullptr); REQUIRE(regs.read_flag(registers::flag::ZERO)); regs.reset_flags(); reg = 0x01; inst.call(nullptr); REQUIRE(!regs.read_flag(registers::flag::ZERO)); regs.reset_flags(); reg = 0x80; inst.call(nullptr); REQUIRE(regs.read_flag(registers::flag::ZERO)); regs.reset_flags(); reg = 0x81; inst.call(nullptr); REQUIRE(!regs.read_flag(registers::flag::ZERO)); }; test_zero_flag(sla_b, regs.b); test_zero_flag(sla_c, regs.c); test_zero_flag(sla_d, regs.d); test_zero_flag(sla_e, regs.e); test_zero_flag(sla_h, regs.h); test_zero_flag(sla_l, regs.l); test_zero_flag(sla_a, regs.a); auto test_carry_flag = [&](const vcpu_instruction& inst, u8& reg) { regs.reset_flags(); reg = 0x00; inst.call(nullptr); REQUIRE(!regs.read_flag(registers::flag::CARRY)); regs.reset_flags(); reg = 0x7F; inst.call(nullptr); REQUIRE(!regs.read_flag(registers::flag::CARRY)); regs.reset_flags(); reg = 0x80; inst.call(nullptr); REQUIRE(regs.read_flag(registers::flag::CARRY)); regs.reset_flags(); reg = 0x40; inst.call(nullptr); inst.call(nullptr); REQUIRE(regs.read_flag(registers::flag::CARRY)); }; test_carry_flag(sla_b, regs.b); test_carry_flag(sla_c, regs.c); test_carry_flag(sla_d, regs.d); test_carry_flag(sla_e, regs.e); test_carry_flag(sla_h, regs.h); test_carry_flag(sla_l, regs.l); test_carry_flag(sla_a, regs.a); } SECTION("CpuFirmware_SLA_Registers_Operation") { CPUFW_SLEEPY_TESTINIT(); auto& sla_b = inst_map[opcode(0xCB, 0x20)]; auto& sla_c = inst_map[opcode(0xCB, 0x21)]; auto& sla_d = inst_map[opcode(0xCB, 0x22)]; auto& sla_e = inst_map[opcode(0xCB, 0x23)]; auto& sla_h = inst_map[opcode(0xCB, 0x24)]; auto& sla_l = inst_map[opcode(0xCB, 0x25)]; auto& sla_a = inst_map[opcode(0xCB, 0x27)]; auto test_value = [&](const vcpu_instruction& inst, u8& reg) { regs.reset_flags(); reg = 0x00; inst.call(nullptr); REQUIRE(reg == 0x00); regs.reset_flags(); regs.set_flag(registers::flag::CARRY); reg = 0x00; inst.call(nullptr); REQUIRE(reg == 0x00); regs.reset_flags(); reg = 0x01; inst.call(nullptr); REQUIRE(reg == 0x02); regs.reset_flags(); reg = 0x02; inst.call(nullptr); REQUIRE(reg == 0x04); regs.reset_flags(); reg = 0x10; inst.call(nullptr); REQUIRE(reg == 0x20); regs.reset_flags(); reg = 0x80; inst.call(nullptr); REQUIRE(reg == 0x00); regs.reset_flags(); reg = 0xFF; inst.call(nullptr); REQUIRE(reg == 0xFE); }; test_value(sla_b, regs.b); test_value(sla_c, regs.c); test_value(sla_d, regs.d); test_value(sla_e, regs.e); test_value(sla_h, regs.h); test_value(sla_l, regs.l); test_value(sla_a, regs.a); } SECTION("CpuFirmware_SLA_PHL") { CPUFW_SLEEPY_TESTINIT(); auto& sla_phl = inst_map[opcode(0xCB, 0x26)]; u16 addr = 0xF122; u8 val = 0x00; regs.hl(addr); mem.write_byte(addr, val); sla_phl.call(nullptr); REQUIRE(mem.read_byte(addr) == val); REQUIRE(regs.read_flag(registers::flag::ZERO)); REQUIRE(!regs.read_flag(registers::flag::CARRY)); addr = 0xF122; val = 0x01; regs.hl(addr); mem.write_byte(addr, val); sla_phl.call(nullptr); REQUIRE(mem.read_byte(addr) == 0x02); REQUIRE(!regs.read_flag(registers::flag::ZERO)); REQUIRE(!regs.read_flag(registers::flag::CARRY)); addr = 0xF122; val = 0x02; regs.hl(addr); mem.write_byte(addr, val); sla_phl.call(nullptr); REQUIRE(mem.read_byte(addr) == 0x04); REQUIRE(!regs.read_flag(registers::flag::ZERO)); REQUIRE(!regs.read_flag(registers::flag::CARRY)); addr = 0xF122; val = 0x80; regs.hl(addr); mem.write_byte(addr, val); sla_phl.call(nullptr); REQUIRE(mem.read_byte(addr) == 0x00); REQUIRE(regs.read_flag(registers::flag::ZERO)); REQUIRE(regs.read_flag(registers::flag::CARRY)); addr = 0xF122; val = 0xFF; regs.hl(addr); mem.write_byte(addr, val); sla_phl.call(nullptr); REQUIRE(mem.read_byte(addr) == 0xFE); REQUIRE(!regs.read_flag(registers::flag::ZERO)); REQUIRE(regs.read_flag(registers::flag::CARRY)); } } }
cd24a1fdc9b50f97f9f6a99b514cb462b80b3b2b
3e482a2e67038a9739d1cd2c8238837e32d18305
/Engine/cDebugRenderer.cpp
55591d035cbb79e36bca9c3bfc74beec2427bd63
[]
no_license
araujojr82/Graphics2_Midterm
e94568165fd5875b71a5310a2528034f2d89e2e6
9b52c4020ca5b85080ef4b5671734b752569505a
refs/heads/master
2021-04-12T04:32:23.925142
2018-05-07T19:15:36
2018-05-07T19:15:36
125,884,835
0
0
null
null
null
null
UTF-8
C++
false
false
24,594
cpp
cDebugRenderer.cpp
#include "cDebugRenderer.h" #include "globalOpenGL_GLFW.h" #include "cShaderManager.h" #include <glm/mat4x4.hpp> // glm::mat4 #include <glm/gtc/matrix_transform.hpp> // glm::translate, glm::rotate, glm::scale, glm::perspective #include <glm/gtc/type_ptr.hpp> // glm::value_ptr #include <sstream> #include <fstream> /*static*/ const std::string cDebugRenderer::DEFALUT_VERT_SHADER_SOURCE = "\ #version 420 \n \ \n \ uniform mat4 mModel; \n \ uniform mat4 mView; \n \ uniform mat4 mProjection; \n \ \n \ in vec4 vPosition; \n \ in vec4 vColour; \n \ \n \ out vec4 vertColour; \n \ \n \ void main() \n \ { \n \ mat4 MVP = mProjection * mView * mModel; \n \ gl_Position = MVP * vPosition; \n \ \n \ vertColour = vColour; \n \ }\n"; /*static*/ const std::string cDebugRenderer::DEFAULT_FRAG_SHADER_SOURCE = "\ #version 420 \n \ \n \ in vec4 vertColour; \n \ \n \ void main() \n \ { \n \ gl_FragColor.rgb = vertColour.rgb; \n \ gl_FragColor.a = vertColour.a; \n \ }\n "; class cDebugRenderer::cShaderProgramInfo { public: cShaderProgramInfo() : shaderProgramID(0), matProjectionUniformLoc(-1), matViewUniformLoc(-1), matModelUniformLoc(-1) {}; cShaderManager::cShader vertShader; cShaderManager::cShader fragShader; unsigned int shaderProgramID; // Uniforms in the shader int matProjectionUniformLoc; int matViewUniformLoc; int matModelUniformLoc; }; bool cDebugRenderer::initialize(std::string &error) { cShaderManager shaderManager; this->m_pShaderProg->vertShader.parseStringIntoMultiLine(this->m_vertexShaderSource); this->m_pShaderProg->fragShader.parseStringIntoMultiLine(this->m_fragmentShaderSource); if ( ! shaderManager.createProgramFromSource( "debugShader", this->m_pShaderProg->vertShader, this->m_pShaderProg->fragShader ) ) { error = "Could not create the debug shader program.\n" + shaderManager.getLastError(); return false; } // The shader was compiled, so get the shader program number this->m_pShaderProg->shaderProgramID = shaderManager.getIDFromFriendlyName("debugShader"); // Get the uniform variable locations glUseProgram(this->m_pShaderProg->shaderProgramID); this->m_pShaderProg->matModelUniformLoc = glGetUniformLocation(this->m_pShaderProg->shaderProgramID, "mModel"); this->m_pShaderProg->matViewUniformLoc = glGetUniformLocation(this->m_pShaderProg->shaderProgramID, "mView"); this->m_pShaderProg->matProjectionUniformLoc = glGetUniformLocation(this->m_pShaderProg->shaderProgramID, "mProjection"); glUseProgram(0); // Set up the VBOs... if ( ! this->resizeBufferForTriangles(cDebugRenderer::DEFAULTNUMBEROFTRIANGLES) ) { return false; } if ( ! this->resizeBufferForLines(cDebugRenderer::DEFAULTNUMBEROFLINES) ) { return false; } if ( ! this->resizeBufferForPoints(cDebugRenderer::DEFAULTNUMBEROFPOINTS) ) { return false; } return true; } bool cDebugRenderer::resizeBufferForPoints(unsigned int newNumberOfPoints) { //TODO return true; } bool cDebugRenderer::resizeBufferForLines(unsigned int newNumberOfLines) { //TODO // Erase any exisiting buffers if( this->m_VAOBufferInfoLines.bIsValid ) { // Assume it exists, so delete it delete[] this->m_VAOBufferInfoLines.pLocalVertexArray; glDeleteBuffers( 1, &( this->m_VAOBufferInfoLines.vertex_buffer_ID ) ); glDeleteVertexArrays( 1, &( this->m_VAOBufferInfoLines.VAO_ID ) ); }//if... // Add a buffer of 10% to the size, because I'm a pessimist... // (Written this way to avoid a type conversion warning) newNumberOfLines = ( unsigned int )( newNumberOfLines * 1.1 ); this->m_VAOBufferInfoLines.bufferSizeObjects = newNumberOfLines; this->m_VAOBufferInfoLines.bufferSizeVertices = newNumberOfLines * 2; this->m_VAOBufferInfoLines.bufferSizeBytes = 0; this->m_VAOBufferInfoLines.numberOfObjectsToDraw = 0; this->m_VAOBufferInfoLines.numberOfVerticesToDraw = 0; this->m_VAOBufferInfoLines.shaderID = this->m_pShaderProg->shaderProgramID; return this->m_InitBuffer( this->m_VAOBufferInfoLines ); return true; } bool cDebugRenderer::resizeBufferForTriangles(unsigned int newNumberOfTriangles) { // Erase any exisiting buffers if ( this->m_VAOBufferInfoTriangles.bIsValid ) { // Assume it exists, so delete it delete [] this->m_VAOBufferInfoTriangles.pLocalVertexArray; glDeleteBuffers(1, &(this->m_VAOBufferInfoTriangles.vertex_buffer_ID) ); glDeleteVertexArrays( 1, &(this->m_VAOBufferInfoTriangles.VAO_ID) ); }//if... // Add a buffer of 10% to the size, because I'm a pessimist... // (Written this way to avoid a type conversion warning) newNumberOfTriangles = (unsigned int)(newNumberOfTriangles * 1.1); this->m_VAOBufferInfoTriangles.bufferSizeObjects = newNumberOfTriangles; this->m_VAOBufferInfoTriangles.bufferSizeVertices = newNumberOfTriangles * 3; this->m_VAOBufferInfoTriangles.bufferSizeBytes = 0; this->m_VAOBufferInfoTriangles.numberOfObjectsToDraw = 0; this->m_VAOBufferInfoTriangles.numberOfVerticesToDraw = 0; this->m_VAOBufferInfoTriangles.shaderID = this->m_pShaderProg->shaderProgramID; return this->m_InitBuffer(this->m_VAOBufferInfoTriangles); } bool cDebugRenderer::m_InitBuffer(sVAOInfoDebug &VAOInfo) { glUseProgram(this->m_pShaderProg->shaderProgramID); // Create a Vertex Array Object (VAO) glGenVertexArrays( 1, &(VAOInfo.VAO_ID) ); glBindVertexArray( VAOInfo.VAO_ID ); glGenBuffers(1, &(VAOInfo.vertex_buffer_ID) ); glBindBuffer(GL_ARRAY_BUFFER, VAOInfo.vertex_buffer_ID); VAOInfo.pLocalVertexArray = new sVertex_xyzw_rgba[VAOInfo.bufferSizeVertices]; // Clear buffer VAOInfo.bufferSizeBytes = sizeof(sVertex_xyzw_rgba) * VAOInfo.bufferSizeVertices; memset(VAOInfo.pLocalVertexArray, 0, VAOInfo.bufferSizeBytes); // Copy the local vertex array into the GPUs memory glBufferData(GL_ARRAY_BUFFER, VAOInfo.bufferSizeBytes, VAOInfo.pLocalVertexArray, GL_DYNAMIC_DRAW); // **DON'T** Get rid of local vertex array! // (We will need to copy the debug objects into this later!!) //delete [] pVertices; // Now set up the vertex layout (for this shader): // // in vec4 vPosition; // in vec4 vColour; // GLuint vpos_location = glGetAttribLocation(VAOInfo.shaderID, "vPosition"); // program, "vPos"); // 6 GLuint vcol_location = glGetAttribLocation(VAOInfo.shaderID, "vColour"); // program, "vCol"); // 13 // Size of the vertex we are using in the array. // This is called the "stride" of the vertices in the vertex buffer const unsigned int VERTEX_SIZE_OR_STRIDE_IN_BYTES = sizeof(sVertex_xyzw_rgba); glEnableVertexAttribArray(vpos_location); const unsigned int OFFSET_TO_X_IN_CVERTEX = offsetof(sVertex_xyzw_rgba, x ); glVertexAttribPointer(vpos_location, 4, // in vec4 vPosition; GL_FLOAT, GL_FALSE, VERTEX_SIZE_OR_STRIDE_IN_BYTES, reinterpret_cast<void*>(static_cast<uintptr_t>(OFFSET_TO_X_IN_CVERTEX)) ); // 64-bit glEnableVertexAttribArray(vcol_location); const unsigned int OFFSET_TO_R_IN_CVERTEX = offsetof(sVertex_xyzw_rgba, r ); glVertexAttribPointer(vcol_location, 4, // in vec4 vColour; GL_FLOAT, GL_FALSE, VERTEX_SIZE_OR_STRIDE_IN_BYTES, reinterpret_cast<void*>(static_cast<uintptr_t>(OFFSET_TO_R_IN_CVERTEX)) ); // 64-bit // ******************************************************************* VAOInfo.bIsValid = true; // CRITICAL // Unbind the VAO first!!!! glBindVertexArray( 0 ); // // Unbind (release) everything glBindBuffer( GL_ARRAY_BUFFER, 0 ); // glBindBuffer( GL_ELEMENT_ARRAY_BUFFER, 0 ); glDisableVertexAttribArray(vcol_location); glDisableVertexAttribArray(vpos_location); glUseProgram(0); return true; } bool cDebugRenderer::IsOK(void) { //TODO return true; } cDebugRenderer::cDebugRenderer() { this->m_vertexShaderSource = cDebugRenderer::DEFALUT_VERT_SHADER_SOURCE; this->m_fragmentShaderSource = cDebugRenderer::DEFAULT_FRAG_SHADER_SOURCE; this->m_pShaderProg = new cShaderProgramInfo(); return; } cDebugRenderer::~cDebugRenderer() { if (this->m_pShaderProg) { delete this->m_pShaderProg; } return; } void cDebugRenderer::RenderDebugObjects(glm::mat4 matCameraView, glm::mat4 matProjection ) { this->m_copyTrianglesIntoRenderBuffer(); this->m_copyLinesIntoRenderBuffer(); //this->m_copyPointsIntoRenderBuffer(); // Start rendering glUseProgram(this->m_pShaderProg->shaderProgramID); glUniformMatrix4fv( this->m_pShaderProg->matViewUniformLoc, 1, GL_FALSE, (const GLfloat*) glm::value_ptr(matCameraView) ); glUniformMatrix4fv( this->m_pShaderProg->matProjectionUniformLoc, 1, GL_FALSE, (const GLfloat*) glm::value_ptr(matProjection) ); // Model matrix is just set to identity. // In other words, the values in the buffers are in WORLD coordinates (untransformed) glUniformMatrix4fv( this->m_pShaderProg->matModelUniformLoc, 1, GL_FALSE, (const GLfloat*) glm::value_ptr(glm::mat4(1.0f)) ); //TODO: Right now, the objects are drawn WITHOUT the depth buffer // To be added is the ability to draw objects with and without depth // (like some objects are draw "in the scene" and others are drawn // "on top of" the scene) glPolygonMode( GL_FRONT_AND_BACK, GL_LINE ); // Default glDisable(GL_CULL_FACE); glDisable(GL_DEPTH_TEST); // Test for z and store in z buffer //glEnable(GL_PROGRAM_POINT_SIZE); //glPointSize(50.0f); // Draw triangles glBindVertexArray( this->m_VAOBufferInfoTriangles.VAO_ID ); glDrawArrays( GL_TRIANGLES, 0, // 1st vertex this->m_VAOBufferInfoTriangles.numberOfVerticesToDraw ); glBindVertexArray( 0 ); // Draw lines glBindVertexArray( this->m_VAOBufferInfoLines.VAO_ID ); glDrawArrays( GL_LINES, 0, // 1st vertex this->m_VAOBufferInfoLines.numberOfVerticesToDraw ); glBindVertexArray( 0 ); // Draw points glUseProgram(0); // Put everything back as it was glPolygonMode( GL_FRONT_AND_BACK, GL_FILL ); // Default glEnable(GL_CULL_FACE); glCullFace(GL_BACK); glEnable(GL_DEPTH_TEST); return; } void cDebugRenderer::m_copyTrianglesIntoRenderBuffer(void) { // Used to keep the "persistent" ones... std::vector<drTri> vecTriTemp; this->m_VAOBufferInfoTriangles.numberOfObjectsToDraw = (unsigned int)this->m_vecTriangles.size(); // Is the draw buffer big enough? if ( this->m_VAOBufferInfoTriangles.bufferSizeObjects < this->m_VAOBufferInfoTriangles.numberOfObjectsToDraw ) { // Resize the buffer this->resizeBufferForTriangles( this->m_VAOBufferInfoTriangles.numberOfObjectsToDraw ); } this->m_VAOBufferInfoTriangles.numberOfVerticesToDraw = this->m_VAOBufferInfoTriangles.numberOfObjectsToDraw * 3; // Triangles unsigned int vertexIndex = 0; // index of the vertex buffer to copy into unsigned int triIndex = 0; // index of the triangle buffer for (; triIndex != this->m_VAOBufferInfoTriangles.numberOfObjectsToDraw; triIndex++, vertexIndex++) { drTri& curTri = this->m_vecTriangles[triIndex]; this->m_VAOBufferInfoTriangles.pLocalVertexArray[vertexIndex+0].x = curTri.v[0].x; this->m_VAOBufferInfoTriangles.pLocalVertexArray[vertexIndex+0].y = curTri.v[0].y; this->m_VAOBufferInfoTriangles.pLocalVertexArray[vertexIndex+0].z = curTri.v[0].z; this->m_VAOBufferInfoTriangles.pLocalVertexArray[vertexIndex+0].w = 1.0f; this->m_VAOBufferInfoTriangles.pLocalVertexArray[vertexIndex+0].r = curTri.colour.r; this->m_VAOBufferInfoTriangles.pLocalVertexArray[vertexIndex+0].g = curTri.colour.g; this->m_VAOBufferInfoTriangles.pLocalVertexArray[vertexIndex+0].b = curTri.colour.b; this->m_VAOBufferInfoTriangles.pLocalVertexArray[vertexIndex+0].a = 1.0f; this->m_VAOBufferInfoTriangles.pLocalVertexArray[vertexIndex+1].x = curTri.v[1].x; this->m_VAOBufferInfoTriangles.pLocalVertexArray[vertexIndex+1].y = curTri.v[1].y; this->m_VAOBufferInfoTriangles.pLocalVertexArray[vertexIndex+1].z = curTri.v[1].z; this->m_VAOBufferInfoTriangles.pLocalVertexArray[vertexIndex+1].w = 1.0f; this->m_VAOBufferInfoTriangles.pLocalVertexArray[vertexIndex+1].r = curTri.colour.r; this->m_VAOBufferInfoTriangles.pLocalVertexArray[vertexIndex+1].g = curTri.colour.g; this->m_VAOBufferInfoTriangles.pLocalVertexArray[vertexIndex+1].b = curTri.colour.b; this->m_VAOBufferInfoTriangles.pLocalVertexArray[vertexIndex+1].a = 1.0f; this->m_VAOBufferInfoTriangles.pLocalVertexArray[vertexIndex+2].x = curTri.v[2].x; this->m_VAOBufferInfoTriangles.pLocalVertexArray[vertexIndex+2].y = curTri.v[2].y; this->m_VAOBufferInfoTriangles.pLocalVertexArray[vertexIndex+2].z = curTri.v[2].z; this->m_VAOBufferInfoTriangles.pLocalVertexArray[vertexIndex+2].w = 1.0f; this->m_VAOBufferInfoTriangles.pLocalVertexArray[vertexIndex+2].r = curTri.colour.r; this->m_VAOBufferInfoTriangles.pLocalVertexArray[vertexIndex+2].g = curTri.colour.g; this->m_VAOBufferInfoTriangles.pLocalVertexArray[vertexIndex+2].b = curTri.colour.b; this->m_VAOBufferInfoTriangles.pLocalVertexArray[vertexIndex+2].a = 1.0f; // Keep this one? (i.e. is persistent?) if (curTri.bPersist) { vecTriTemp.push_back(curTri); } }//for (; // Clear the triangle list and push back the persistent ones this->m_vecTriangles.clear(); for (std::vector<drTri>::iterator itTri = vecTriTemp.begin(); itTri != vecTriTemp.end(); itTri++) { this->m_vecTriangles.push_back(*itTri); } // Copy the new vertex information to the vertex buffer // Copy the local vertex array into the GPUs memory unsigned int numberOfBytesToCopy = this->m_VAOBufferInfoTriangles.numberOfVerticesToDraw * sizeof(sVertex_xyzw_rgba); GLenum err = glGetError(); glBindBuffer(GL_ARRAY_BUFFER, this->m_VAOBufferInfoTriangles.vertex_buffer_ID); glBufferData(GL_ARRAY_BUFFER, numberOfBytesToCopy, this->m_VAOBufferInfoTriangles.pLocalVertexArray, GL_DYNAMIC_DRAW); glBindBuffer(GL_ARRAY_BUFFER, 0); err = glGetError(); std::string error; std::string errDetails; if (err != GL_NO_ERROR) { //error = decodeGLErrorFromEnum(err, errDetails); error = COpenGLError::TranslateErrorEnum( err ); } // numberOfBytesToCopy, // this->m_VAOBufferInfoTriangles.pLocalVertexArray, // GL_DYNAMIC_DRAW); // void* pGPUBuff = glMapBuffer( this->m_VAOBufferInfoTriangles.vertex_buffer_ID, // GL_COPY_WRITE_BUFFER); //memcpy( // this->m_VAOBufferInfoTriangles.pLocalVertexArray, // pGPUBuff, // numberOfBytesToCopy); // glUnmapBuffer(this->m_VAOBufferInfoTriangles.vertex_buffer_ID); return; } iDebugRenderer::sDebugTri::sDebugTri() { this->v[0] = glm::vec3(0.0f); this->v[1] = glm::vec3(0.0f); this->v[2] = glm::vec3(0.0f); this->colour = glm::vec3(1.0f); // white this->bPersist = false; this->bIgnorDepthBuffer = false; return; } iDebugRenderer::sDebugTri::sDebugTri(glm::vec3 v1, glm::vec3 v2, glm::vec3 v3, glm::vec3 colour, bool bPersist/*=false*/) { this->v[0] = v1; this->v[1] = v2; this->v[2] = v3; this->colour = colour; this->bPersist = bPersist; this->bIgnorDepthBuffer = false; return; } iDebugRenderer::sDebugTri::sDebugTri(glm::vec3 v[3], glm::vec3 colour, bool bPersist /*=false*/) { this->v[0] = v[0]; this->v[1] = v[1]; this->v[2] = v[2]; this->colour = colour; this->bPersist = bPersist; this->bIgnorDepthBuffer = false; return; } iDebugRenderer::sDebugLine::sDebugLine() { this->points[0] = glm::vec3(0.0f); this->points[0] = glm::vec3(0.0f); this->colour = glm::vec3(1.0f); // white this->bPersist = false; this->bIgnorDepthBuffer = false; return; } iDebugRenderer::sDebugLine::sDebugLine(glm::vec3 start, glm::vec3 end, glm::vec3 colour, bool bPersist /*=false*/) { this->points[0] = start; this->points[1] = end; this->colour = colour; this->bPersist = bPersist; this->bIgnorDepthBuffer = false; return; } iDebugRenderer::sDebugLine::sDebugLine(glm::vec3 points[2], glm::vec3 colour, bool bPersist /*=false*/) { this->points[0] = points[0]; this->points[1] = points[1]; this->colour = colour; this->bPersist = bPersist; this->bIgnorDepthBuffer = false; return; } /*static*/ const float cDebugRendererDEFAULT_POINT_SIZE = 1.0f; iDebugRenderer::sDebugPoint::sDebugPoint() { this->xyz = glm::vec3(0.0f); this->colour = glm::vec3(1.0f); // white this->bPersist = false; this->pointSize = cDebugRendererDEFAULT_POINT_SIZE; this->bIgnorDepthBuffer = false; return; } iDebugRenderer::sDebugPoint::sDebugPoint(glm::vec3 xyz, glm::vec3 colour, bool bPersist/*=false*/) { this->xyz = xyz; this->colour = colour; this->bPersist = bPersist; this->pointSize = cDebugRendererDEFAULT_POINT_SIZE; this->bIgnorDepthBuffer = false; return; } iDebugRenderer::sDebugPoint::sDebugPoint(glm::vec3 xyz, glm::vec3 colour, float pointSize, bool bPersist/*=false*/) { this->xyz = xyz; this->colour = colour; this->pointSize = pointSize; this->bPersist = bPersist; this->bIgnorDepthBuffer = false; return; } void cDebugRenderer::addTriangle(glm::vec3 v1XYZ, glm::vec3 v2XYZ, glm::vec3 v3XYZ, glm::vec3 colour, bool bPersist /*=false*/) { drTri tempTri(v1XYZ, v2XYZ, v3XYZ, colour, bPersist); this->addTriangle(tempTri); return; } void cDebugRenderer::addTriangle(drTri &tri) { this->m_vecTriangles.push_back(tri); return; } void cDebugRenderer::addCircle( glm::vec3 position, float range, glm::vec3 color ) { glm::vec3 point0 = glm::vec3( position.x, 0.0f, position.z + range ); glm::vec3 point3 = glm::vec3( position.x + range, 0.0f, position.z ); glm::vec3 point6 = glm::vec3( position.x, 0.0f, position.z - range ); glm::vec3 point9 = glm::vec3( position.x - range, 0.0f, position.z ); float x30 = glm::cos( glm::radians( 30.0f ) ) * range; float z30 = glm::sin( glm::radians( 30.0f ) ) * range; float x60 = glm::cos( glm::radians( 60.0f ) ) * range; float z60 = glm::sin( glm::radians( 60.0f ) ) * range; glm::vec3 point1 = glm::vec3( position.x + x60, 0.0f, position.z + z60 ); glm::vec3 point2 = glm::vec3( position.x + x30, 0.0f, position.z + z30 ); glm::vec3 point4 = glm::vec3( position.x + x30, 0.0f, position.z - z30 ); glm::vec3 point5 = glm::vec3( position.x + x60, 0.0f, position.z - z60 ); glm::vec3 point7 = glm::vec3( position.x - x60, 0.0f, position.z - z60 ); glm::vec3 point8 = glm::vec3( position.x - x30, 0.0f, position.z - z30 ); glm::vec3 point10 = glm::vec3( position.x - x30, 0.0f, position.z + z30 ); glm::vec3 point11 = glm::vec3( position.x - x60, 0.0f, position.z + z60 ); this->addLine( point0, point1, color, false ); this->addLine( point1, point2, color, false ); this->addLine( point2, point3, color, false ); this->addLine( point3, point4, color, false ); this->addLine( point4, point5, color, false ); this->addLine( point5, point6, color, false ); this->addLine( point6, point7, color, false ); this->addLine( point7, point8, color, false ); this->addLine( point8, point9, color, false ); this->addLine( point9, point10, color, false ); this->addLine( point10, point11, color, false ); this->addLine( point11, point0, color, false ); return; } void cDebugRenderer::addLine(glm::vec3 startXYZ, glm::vec3 endXYZ, glm::vec3 colour, bool bPersist /*=false*/) { drLine tempLine(startXYZ, endXYZ, colour, bPersist); this->addLine(tempLine); return; } void cDebugRenderer::addLine(drLine &line) { this->m_vecLines.push_back(line); return; } void cDebugRenderer::addPoint(glm::vec3 xyz, glm::vec3 colour, bool bPersist /*=false*/) { drPoint tempPoint(xyz, colour, bPersist); this->addPoint(tempPoint); return; } void cDebugRenderer::addPoint(drPoint &point) { this->m_vecPoints.push_back(point); return; } void cDebugRenderer::addPoint(glm::vec3 xyz, glm::vec3 colour, float pointSize, bool bPersist /*=false*/) { drPoint tempPoint(xyz, colour, pointSize, bPersist); this->addPoint(tempPoint); return; } void cDebugRenderer::m_copyLinesIntoRenderBuffer( void ) { // Used to keep the "persistent" ones... std::vector<drLine> vecLineTemp; this->m_VAOBufferInfoLines.numberOfObjectsToDraw = ( unsigned int )this->m_vecLines.size(); // Is the draw buffer big enough? if( this->m_VAOBufferInfoLines.bufferSizeObjects < this->m_VAOBufferInfoLines.numberOfObjectsToDraw ) { // Resize the buffer this->resizeBufferForLines( this->m_VAOBufferInfoLines.numberOfObjectsToDraw ); } this->m_VAOBufferInfoLines.numberOfVerticesToDraw = this->m_VAOBufferInfoLines.numberOfObjectsToDraw * 2; // Lines unsigned int vertexIndex = 0; // index of the vertex buffer to copy into unsigned int lineIndex = 0; // index of the line buffer for( ; lineIndex != this->m_VAOBufferInfoLines.numberOfObjectsToDraw; lineIndex++, vertexIndex++ ) { drLine& curLine = this->m_vecLines[lineIndex]; this->m_VAOBufferInfoLines.pLocalVertexArray[vertexIndex + 0].x = curLine.points[0].x; //curLine.points->x; this->m_VAOBufferInfoLines.pLocalVertexArray[vertexIndex + 0].y = curLine.points[0].y; this->m_VAOBufferInfoLines.pLocalVertexArray[vertexIndex + 0].z = curLine.points[0].z; this->m_VAOBufferInfoLines.pLocalVertexArray[vertexIndex + 0].w = 1.0f; this->m_VAOBufferInfoLines.pLocalVertexArray[vertexIndex + 0].r = curLine.colour.r; this->m_VAOBufferInfoLines.pLocalVertexArray[vertexIndex + 0].g = curLine.colour.g; this->m_VAOBufferInfoLines.pLocalVertexArray[vertexIndex + 0].b = curLine.colour.b; this->m_VAOBufferInfoLines.pLocalVertexArray[vertexIndex + 0].a = 1.0f; this->m_VAOBufferInfoLines.pLocalVertexArray[vertexIndex + 1].x = curLine.points[1].x; this->m_VAOBufferInfoLines.pLocalVertexArray[vertexIndex + 1].y = curLine.points[1].y; this->m_VAOBufferInfoLines.pLocalVertexArray[vertexIndex + 1].z = curLine.points[1].z; this->m_VAOBufferInfoLines.pLocalVertexArray[vertexIndex + 1].w = 1.0f; this->m_VAOBufferInfoLines.pLocalVertexArray[vertexIndex + 1].r = curLine.colour.r; this->m_VAOBufferInfoLines.pLocalVertexArray[vertexIndex + 1].g = curLine.colour.g; this->m_VAOBufferInfoLines.pLocalVertexArray[vertexIndex + 1].b = curLine.colour.b; this->m_VAOBufferInfoLines.pLocalVertexArray[vertexIndex + 1].a = 1.0f; vertexIndex++; // Keep this one? (i.e. is persistent?) if( curLine.bPersist ) { vecLineTemp.push_back( curLine ); } }//for (; // Clear the lines list and push back the persistent ones this->m_vecLines.clear(); for( std::vector<drLine>::iterator itLine = vecLineTemp.begin(); itLine != vecLineTemp.end(); itLine++ ) { this->m_vecLines.push_back( *itLine ); } // Copy the new vertex information to the vertex buffer // Copy the local vertex array into the GPUs memory unsigned int numberOfBytesToCopy = this->m_VAOBufferInfoLines.numberOfVerticesToDraw * sizeof( sVertex_xyzw_rgba ); GLenum err = glGetError(); glBindBuffer( GL_ARRAY_BUFFER, this->m_VAOBufferInfoLines.vertex_buffer_ID ); glBufferData( GL_ARRAY_BUFFER, numberOfBytesToCopy, this->m_VAOBufferInfoLines.pLocalVertexArray, GL_DYNAMIC_DRAW ); glBindBuffer( GL_ARRAY_BUFFER, 0 ); err = glGetError(); std::string error; std::string errDetails; if( err != GL_NO_ERROR ) { //error = decodeGLErrorFromEnum( err, errDetails ); error = COpenGLError::TranslateErrorEnum( err ); } // numberOfBytesToCopy, // this->m_VAOBufferInfoLines.pLocalVertexArray, // GL_DYNAMIC_DRAW); // void* pGPUBuff = glMapBuffer( this->m_VAOBufferInfoLines.vertex_buffer_ID, // GL_COPY_WRITE_BUFFER); //memcpy( // this->m_VAOBufferInfoLines.pLocalVertexArray, // pGPUBuff, // numberOfBytesToCopy); // glUnmapBuffer(this->m_VAOBufferInfoLines.vertex_buffer_ID); return; }
05e6b93d0ecd234df2a0a9502275d148be4a06a2
36136944e4e0e334660e95fdadca3a0e62f8d2a6
/Engine/Source/ZeronPlatform/Platform/API/Shared/GLFW/WindowGLFW.cpp
291ee67be5c8f3956c5f626a544e13eb72c2a6ce
[ "MIT" ]
permissive
ekokturk/ZeronEngine
0abf914549d6f68a3ec00cee53f0c6ca2a92173a
bdedeb3de5dbb98b1f570a901a095ac23af92275
refs/heads/main
2023-04-29T16:48:38.177272
2023-04-22T23:37:30
2023-04-22T23:37:30
241,022,858
0
0
null
null
null
null
UTF-8
C++
false
false
6,978
cpp
WindowGLFW.cpp
// Copyright (C) Eser Kokturk. All Rights Reserved. #if ZE_WINDOW_GLFW # include <Platform/API/Shared/GLFW/WindowGLFW.h> # include <GLFW/glfw3.h> # include <Platform/API/Shared/GLFW/GLFWHelpers.h> namespace Zeron { int WindowGLFW::mWindowGLFWCount = 0; WindowGLFW::WindowGLFW(const WindowConfig& config, void* userData) : Window(config, WindowAPI::GLFW) , mWindowGLFW(nullptr) , mMonitorGLFW(nullptr) , mCursorGLFW(nullptr) , mIsCursorClipped(false) { glfwSetErrorCallback([](int errorCode, const char* errorMessage) { ZE_LOGE("GLFW ERROR {}: {}", errorCode, errorMessage); }); if (mWindowGLFWCount == 0) { if (glfwInit() == GLFW_FALSE) { ZE_FAIL("GLFW was not initialized!"); } int vMajor, vMinor, vPatch; glfwGetVersion(&vMajor, &vMinor, &vPatch); ZE_LOGI("GLFW v{}.{}.{} initialized...", vMajor, vMinor, vPatch); } // const int initRefreshRate = videoMode ? videoMode->refreshRate : mRefreshRate; // glfwWindowHint(GLFW_REFRESH_RATE, initRefreshRate); glfwWindowHint(GLFW_CLIENT_API, GLFW_NO_API); mWindowGLFW = glfwCreateWindow(mSize.X, mSize.Y, mName.c_str(), mMonitorGLFW, nullptr); if (!mWindowGLFW) { ZE_FAIL("GLFW window was not created!"); } glfwSetWindowUserPointer(mWindowGLFW, userData); // We need to initialize cached postion glfwGetWindowPos(mWindowGLFW, &mPos.X, &mPos.Y); mPosPrev = mPos; mWindowGLFWCount++; } WindowGLFW::~WindowGLFW() { if (mWindowGLFW) { glfwDestroyWindow(mWindowGLFW); mWindowGLFWCount--; ZE_ASSERT(mWindowGLFWCount >= 0, "Invalid GLFW window count!"); } if (mWindowGLFWCount == 0) { glfwTerminate(); } } void WindowGLFW::Update() { // ClearEventQueue(); if (glfwWindowShouldClose(mWindowGLFW)) { return; } if (mIsCursorClipped) { // OPTIMIZE: This is not ideal, find a better way double mouseX, mouseY; glfwGetCursorPos(mWindowGLFW, &mouseX, &mouseY); const int newMouseX = std::clamp<int>(static_cast<int>(mouseX), mPos.X, mPos.X + mSize.X); const int newMouseY = std::clamp<int>(static_cast<int>(mouseY), mPos.Y, mPos.Y + mSize.Y); if (newMouseX != static_cast<int>(mouseX) || newMouseY != static_cast<int>(mouseY)) { glfwSetCursorPos(mWindowGLFW, newMouseX, newMouseY); } } // Queue blocked until resizing is over so we send the final size with the event if (mIsResizing) { OnSystemEvent({ SystemEvent::WindowResized{ mSize.X, mSize.Y } }); mIsResizing = false; } } void WindowGLFW::SetVisible() { glfwShowWindow(mWindowGLFW); mIsHidden = false; } void WindowGLFW::SetHidden() { glfwHideWindow(mWindowGLFW); mIsHidden = true; } void WindowGLFW::SetName(const std::string& name) { mName = name; glfwSetWindowTitle(mWindowGLFW, mName.c_str()); } void WindowGLFW::SetAspectRatio(int numerator, int denominator) { if (!IsFullScreen()) { glfwSetWindowAspectRatio(mWindowGLFW, numerator, denominator); } } void WindowGLFW::SetSize(int width, int height) { if (!IsFullScreen()) { glfwSetWindowSize(mWindowGLFW, width, height); } } void WindowGLFW::SetSizeLimits(int minWidth, int maxWidth, int minHeight, int maxHeight) { glfwSetWindowSizeLimits(mWindowGLFW, minWidth, minHeight, maxWidth, maxHeight); } void WindowGLFW::SetScreenPosition(int posX, int posY) { if (!IsFullScreen()) { glfwSetWindowPos(mWindowGLFW, posX, posY); } } void WindowGLFW::SetClipCursor(bool shouldClip) { mIsCursorClipped = shouldClip; } void WindowGLFW::_onFullScreenChangedBorderless() { if (mIsFullScreen) { GLFWmonitor* monitor = FindCurrentMonitor(); const GLFWvidmode* mode = glfwGetVideoMode(monitor); const int width = mode->width; const int height = mode->height; int xPos, yPos; glfwGetMonitorPos(monitor, &xPos, &yPos); glfwSetWindowAttrib(mWindowGLFW, GLFW_RESIZABLE, GLFW_FALSE); glfwSetWindowAttrib(mWindowGLFW, GLFW_DECORATED, GLFW_FALSE); glfwSetWindowAttrib(mWindowGLFW, GLFW_RESIZABLE, GLFW_TRUE); glfwSetWindowMonitor(mWindowGLFW, nullptr, xPos, yPos, width, height, mode->refreshRate); } else { GLFWmonitor* monitor = FindCurrentMonitor(); const GLFWvidmode* mode = glfwGetVideoMode(monitor); glfwSetWindowAttrib(mWindowGLFW, GLFW_RESIZABLE, GLFW_FALSE); glfwSetWindowAttrib(mWindowGLFW, GLFW_DECORATED, GLFW_TRUE); glfwSetWindowAttrib(mWindowGLFW, GLFW_RESIZABLE, GLFW_TRUE); glfwSetWindowMonitor(mWindowGLFW, nullptr, mPosPrev.X, mPosPrev.Y, mSizePrev.X, mSizePrev.Y, mode->refreshRate); } } void WindowGLFW::_onFullScreenChangedMonitor() { if (mIsFullScreen) { GLFWmonitor* monitor = FindCurrentMonitor(); const GLFWvidmode* mode = glfwGetVideoMode(monitor); glfwSetWindowAttrib(mWindowGLFW, GLFW_RESIZABLE, GLFW_FALSE); glfwSetWindowAttrib(mWindowGLFW, GLFW_DECORATED, GLFW_FALSE); glfwSetWindowAttrib(mWindowGLFW, GLFW_RESIZABLE, GLFW_TRUE); glfwSetWindowMonitor(mWindowGLFW, monitor, 0, 0, mSize.X, mSize.Y, mode->refreshRate); } else { GLFWmonitor* monitor = FindCurrentMonitor(); glfwSetWindowAttrib(mWindowGLFW, GLFW_RESIZABLE, GLFW_TRUE); const GLFWvidmode* mode = glfwGetVideoMode(monitor); glfwSetWindowMonitor(mWindowGLFW, nullptr, mPosPrev.X, mPosPrev.Y, mSizePrev.X, mSizePrev.Y, mode->refreshRate); glfwSetWindowAttrib(mWindowGLFW, GLFW_RESIZABLE, GLFW_FALSE); glfwSetWindowAttrib(mWindowGLFW, GLFW_DECORATED, GLFW_TRUE); glfwSetWindowAttrib(mWindowGLFW, GLFW_RESIZABLE, GLFW_TRUE); } } void* WindowGLFW::GetApiHandle() const { return mWindowGLFW; } SystemHandle WindowGLFW::GetSystemHandle() const { return GLFWHelpers::GetPlatformWindowHandle(mWindowGLFW); } void WindowGLFW::SetMinimized() { glfwIconifyWindow(mWindowGLFW); } void WindowGLFW::SetMaximized() { glfwMaximizeWindow(mWindowGLFW); } void WindowGLFW::SetRestored() { glfwRestoreWindow(mWindowGLFW); } void WindowGLFW::SetFocused() { glfwFocusWindow(mWindowGLFW); } void WindowGLFW::SetAttention() { glfwRequestWindowAttention(mWindowGLFW); } GLFWmonitor* WindowGLFW::FindCurrentMonitor() const { GLFWmonitor* result; long areaSize = 0; int monitorCount = 0; GLFWmonitor** monitorList = glfwGetMonitors(&monitorCount); for (int i = 0; i < monitorCount; i++) { GLFWmonitor* monitor = monitorList[i]; int xPos, yPos; glfwGetMonitorPos(monitor, &xPos, &yPos); const GLFWvidmode* mode = glfwGetVideoMode(monitor); const int width = mode->width; const int height = mode->height; // Get the monitor with the largest intersection area const int aX = std::max<int>(xPos, mPos.X); const int aY = std::max<int>(yPos, mPos.Y); const int bX = std::min<int>(xPos + width, mPos.X + mSize.X); const int bY = std::min<int>(yPos + height, mPos.Y + mSize.Y); if (aX > bX || aY > bY) { continue; } const long calcArea = std::abs((bY - aY) * (bX - aX)); if (calcArea > areaSize) { result = monitor; } } return result; } } #endif
198bc219bbd719cdac206b24243738bd1248ca8c
b53575b4f1da8246e9abbb2bf4d297fd0af75ebb
/UVa/10900/10926.how-many-dependences.cpp
560b295c34d4cbe17fd40629fa8206b7f2147d0f
[]
no_license
mauriciopoppe/competitive-programming
217272aa3ee1c3158ca2412652f5ccd6596eb799
32b558582402e25c9ffcdd8840d78543bebd2245
refs/heads/master
2023-04-09T11:56:07.487804
2023-03-19T20:45:00
2023-03-19T20:45:00
120,259,279
8
1
null
null
null
null
UTF-8
C++
false
false
1,373
cpp
10926.how-many-dependences.cpp
#include<iostream> #include<string> #include<cmath> #include<cctype> #include<algorithm> #include<bitset> #include<vector> #include<queue> #include<map> #define M 101 using namespace std; vector<vector<int> > g; int mx,best,temp; bitset<M> d; void dfs(int u) { d[u]=1; for(int i=0;i<g[u].size();i++) { int v=g[u][i]; if(!d[v])dfs(v); } } void print(int t) { for(int i=1;i<=t;i++) { printf("Node %d,%d:",i,g[i].size()); for(int j=0;j<g[i].size();j++) printf(" %d",g[i][j]); printf("\n"); } } int main() { int t,con,node; while(scanf("%d",&t) && t) { g.clear(); g.resize(t+1); for(int i=1;i<=t;i++) { scanf("%d",&con); for(int j=0;j<con;j++) { scanf("%d",&node); g[i].push_back(node); } } //print(t); mx=0,best=-1; for(int i=1;i<=t;i++) { d.reset(); dfs(i); temp=d.count(); //printf("%d [%d]\n",i,temp); if(temp>mx){mx=temp;best=i;} } printf("%d\n",best); } return 0; }
04895faa9652e7285e3c0afacdd10be479e8d5ae
32118aee792fb9a9a29ca5ce533dd1e88c771ead
/ООП лаба БГУиР/main.cpp
37a1c6a96e25a11f4d1c39b90ca87386fd0f589d
[]
no_license
vakden/cpp
bff2c1dd4d8552645b59dc796c918ba90fa531b8
343d50d3ffe99d5846dd011c8501824bf8f20ed6
refs/heads/main
2023-04-03T12:04:29.599629
2021-04-14T19:54:47
2021-04-14T19:54:47
357,787,663
1
0
null
null
null
null
ISO-8859-6
C++
false
false
780
cpp
main.cpp
#include <iostream> #include "Header.h" using namespace std; int main() { try { setlocale(LC_ALL, ".1251"); List L; L.ListPrint(); L.InsertFirst('w'); L.ListPrint(); L.InsertLast('a'); L.ListPrint(); L.InsertFirst('b'); L.ListPrint(); L.InsertLast('c'); L.ListPrint(); L.InsertLast('d'); L.ListPrint(); List M(L); M.ListPrint(); M.Erase(); M.ListPrint(); M = L; M.ListPrint(); L.FindSr('b'); L.FindSr('d'); L.FindSr('c'); L.Insert('k', 'a'); L.ListPrint(); L.FindSr('s'); L.Iz('1'); L.ListPrint(); L.FindDel('1'); L.DeleteFirst(); L.DeleteLast(); L.Erase(); L.ListPrint(); system("pause"); return 0; } catch (char*) { cout << "دسرزخ!!!" << endl; } }
251e1633cf93ec3261435b1ab0d3a6591a41ad90
883887c3c84bd3ac4a11ac76414129137a1b643b
/Voip/VoipManServer/include/PipeProtocol/KickedOut.h
f2a86c763410f7f6fbccc11a6c3cdc0f6d4646eb
[]
no_license
15831944/vAcademia
4dbb36d9d772041e2716506602a602d516e77c1f
447f9a93defb493ab3b6f6c83cbceb623a770c5c
refs/heads/master
2022-03-01T05:28:24.639195
2016-08-18T12:32:22
2016-08-18T12:32:22
null
0
0
null
null
null
null
UTF-8
C++
false
false
129
h
KickedOut.h
#pragma once #include "CommonPipePacketOut.h" class CKickedOut : public CCommonPipePacketOut { public: CKickedOut(byte aID); };
f7173fa4db059388d268fc493a2e111ccceeac0d
5cbe1a50ac812d5954918a1f6bcdbbb696793bed
/MVMFirmwareUnitTests/simulated_i2c_device.h
885f0ccdc8ca8309ef5960254d15cc3b4dfba686
[ "Apache-2.0" ]
permissive
vpesudo/mvm-firmware
e03415d04ee58769b058694c11199d6041130a9c
869c867cc2440f236d1e649a5d0fbc1398528a14
refs/heads/master
2022-06-27T08:03:10.946548
2020-05-08T16:57:15
2020-05-08T16:57:15
null
0
0
null
null
null
null
UTF-8
C++
false
false
4,391
h
simulated_i2c_device.h
// // File: simulated_i2c_device.h // // Author: Francesco Prelz (Francesco.Prelz@mi.infn.it) // // Revision history: // 23-Apr-2020 Initial version. // // Description: // Base class to describe simulated I2C devices. // #ifndef _I2C_DEVICE_SIMUL_H #define _I2C_DEVICE_SIMUL_H #include <functional> #include <sstream> #include <string> #include <map> #include <stdint.h> // <cstdint> is C++11. const int I2C_DEVICE_SIMUL_NOT_FOUND=-1; const int I2C_DEVICE_SIMUL_NO_CMD=-2; const int I2C_DEVICE_SIMUL_UNKNOWN_CMD=-3; const int I2C_DEVICE_SIMUL_DEAD=-4; const int I2C_DEVICE_INSUFFICIENT_READ_BUFFER=-5; const int I2C_DEVICE_NOT_ACTIVE=-6; const int I2C_DEVICE_NOT_ENABLED=-7; const int I2C_DEVICE_BUSY=-8; const std::string I2C_DEVICE_module_name("I2C SIMULATION"); #include "DebugIface.h" #include "mvm_fw_unit_test_config.h" struct sim_i2c_devaddr { sim_i2c_devaddr() {} sim_i2c_devaddr(uint8_t i_address, int8_t i_muxport): address(i_address), muxport(i_muxport) {} uint8_t address; int8_t muxport; //-1 indicates ANY bool operator< (const sim_i2c_devaddr &other) const { if (this->muxport == other.muxport) return (this->address < other.address); else return (this->muxport < other.muxport); } }; class simulated_i2c_device { public: typedef std::function<int (uint8_t* a1, int a2, uint8_t* a3, int a4)> simulated_i2c_cmd_handler_t; typedef std::map<uint8_t, simulated_i2c_cmd_handler_t> simulated_i2c_cmd_handler_container_t; simulated_i2c_device(const std::string &name, DebugIfaceClass &dbg) : m_dbg(dbg), m_name(name) {} simulated_i2c_device(const char *name, DebugIfaceClass &dbg) : m_dbg(dbg), m_name(name) {} virtual ~simulated_i2c_device() {} void set_alive_attr(const std::string &attr) { m_alive_attr = attr; } // The device name will be used as a prefix for retrieving timeline // attributes unless the following is set: void set_timeline_prefix(const std::string &prefix) { m_timeline_prefix = prefix; } int exchange_message(uint8_t* wbuffer, int wlength, uint8_t *rbuffer, int rlength, bool stop) { if (!alive()) return I2C_DEVICE_SIMUL_DEAD; if ((wbuffer != NULL) && (wlength < 1)) { std::ostringstream err; err << I2C_DEVICE_module_name << ": Missing command for device '" << m_name << "'."; m_dbg.DbgPrint(DBG_CODE, DBG_INFO, err.str().c_str()); return I2C_DEVICE_SIMUL_NO_CMD; } uint8_t cmd = 0; if (wbuffer != NULL) { cmd = wbuffer[0]; ++wbuffer; } return handle_command(cmd, wbuffer, wlength-1, rbuffer, rlength); } void add_command_handler(uint8_t cmd, simulated_i2c_cmd_handler_t hnd) { simulated_i2c_cmd_handler_container_t::iterator cmdp; cmdp = m_cmd_handlers.find(cmd); if (cmdp != m_cmd_handlers.end()) { cmdp->second = hnd; } else { m_cmd_handlers.insert(std::make_pair(cmd, hnd)); } } virtual int handle_command(uint8_t cmd, uint8_t *wbuffer, int wlength, uint8_t *rbuffer, int rlength) { simulated_i2c_cmd_handler_container_t::iterator cmdp; cmdp = m_cmd_handlers.find(cmd); if (cmdp != m_cmd_handlers.end()) { return cmdp->second(wbuffer, wlength, rbuffer, rlength); } else { std::ostringstream err; err << I2C_DEVICE_module_name << ": No handler in device '" << m_name << "' for command " << std::hex << std::showbase << static_cast<int>(cmd) << "."; m_dbg.DbgPrint(DBG_CODE, DBG_INFO, err.str().c_str()); return I2C_DEVICE_SIMUL_UNKNOWN_CMD; } } const std::string &get_name() const { return m_name; } DebugIfaceClass &get_dbg() const { return m_dbg; } bool alive() { if (m_alive_attr.length() <= 0) return true; if (FW_TEST_qtl_double.value(m_alive_attr,FW_TEST_ms)) return true; return false; } protected: DebugIfaceClass &m_dbg; simulated_i2c_cmd_handler_container_t m_cmd_handlers; std::string m_name; std::string m_alive_attr; std::string m_timeline_prefix; }; typedef std::map<sim_i2c_devaddr, simulated_i2c_device *> simulated_i2c_devices_t; #endif /* defined _I2C_DEVICE_SIMUL_H */
755ec99c569edb8bb96c4d5e0789209ff8f2d3ce
21dfcc44840cb94058bcd014946f2a38fbf30c54
/src/regal/RegalPpa.h
55bbf8bd8b9263b8afa4a5d64fb2544037459f96
[ "SGI-B-2.0", "MIT", "Libpng", "BSD-3-Clause", "LicenseRef-scancode-glut", "Zlib", "LicenseRef-scancode-public-domain", "BSD-2-Clause", "Unlicense" ]
permissive
nigels-com/regal
819a74deeeac00860bcb6f21c3e59ccad1b78448
3f1a06d5c098339d30221c9e999640e4c5437a0b
refs/heads/master
2020-12-14T16:19:29.701418
2015-10-18T08:57:48
2015-10-18T08:58:56
9,986,650
2
3
null
2014-07-12T07:28:49
2013-05-10T17:35:20
C++
UTF-8
C++
false
false
78,490
h
RegalPpa.h
/* Copyright (c) 2011-2013 NVIDIA Corporation Copyright (c) 2011-2012 Cass Everitt Copyright (c) 2012 Scott Nations Copyright (c) 2012 Mathias Schott Copyright (c) 2012 Nigel Stewart All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ /* Regal push / pop attrib Nigel Stewart, Scott Nations */ #ifndef __REGAL_PPA_H__ #define __REGAL_PPA_H__ #include "RegalUtil.h" #if REGAL_EMULATION REGAL_GLOBAL_BEGIN #include <vector> #include <GL/Regal.h> #include "RegalState.h" #include "RegalEmu.h" #include "RegalEmuInfo.h" #include "RegalLog.h" #include "RegalToken.h" #include "RegalContext.h" #include "RegalContextInfo.h" REGAL_GLOBAL_END REGAL_NAMESPACE_BEGIN namespace Emu { // Work in progress... struct Ppa : public State::Stencil, State::Depth, State::Polygon, State::Transform, State::Hint, State::Enable, State::List, State::AccumBuffer, State::Scissor, State::Viewport, State::Line, State::Multisample, State::Eval, State::Fog, State::Point, State::PolygonStipple, State::ColorBuffer, State::PixelMode, State::Lighting { void Init(RegalContext &ctx) { activeTextureUnit = 0; // update emu info with the limits that this layer supports RegalAssert(ctx.emuInfo); ctx.emuInfo->gl_max_attrib_stack_depth = REGAL_EMU_MAX_ATTRIB_STACK_DEPTH; ctx.emuInfo->gl_max_draw_buffers = REGAL_EMU_MAX_DRAW_BUFFERS; ctx.emuInfo->gl_max_texture_units = REGAL_EMU_MAX_TEXTURE_UNITS; ctx.emuInfo->gl_max_viewports = REGAL_EMU_MAX_VIEWPORTS; } void Cleanup(RegalContext &ctx) { UNUSED_PARAMETER(ctx); } void PushAttrib(RegalContext *ctx, GLbitfield mask) { // from glspec44.compatibility.withchanges.pdf Sec. 21.6, p. 643 // // A STACK_OVERFLOW error is generated if PushAttrib is called // and the attribute stack depth is equal to the value of // MAX_ATTRIB_STACK_DEPTH. // // TODO: set correct GL error here RegalAssert(ctx); RegalAssert(ctx->emuInfo); if (maskStack.size() >= ctx->emuInfo->gl_max_attrib_stack_depth) return; maskStack.push_back(mask); if (mask&GL_DEPTH_BUFFER_BIT) { Internal("Regal::Ppa::PushAttrib GL_DEPTH_BUFFER_BIT ",State::Depth::toString()); depthStack.push_back(State::Depth()); depthStack.back() = *this; mask &= ~GL_DEPTH_BUFFER_BIT; } if (mask&GL_STENCIL_BUFFER_BIT) { Internal("Regal::Ppa::PushAttrib GL_STENCIL_BUFFER_BIT ",State::Stencil::toString()); stencilStack.push_back(State::Stencil()); stencilStack.back() = *this; mask &= ~GL_STENCIL_BUFFER_BIT; } if (mask&GL_POLYGON_BIT) { Internal("Regal::Ppa::PushAttrib GL_POLYGON_BIT ",State::Polygon::toString()); polygonStack.push_back(State::Polygon()); polygonStack.back() = *this; mask &= ~GL_POLYGON_BIT; } if (mask&GL_TRANSFORM_BIT) { Internal("Regal::Ppa::PushAttrib GL_TRANSFORM_BIT ",State::Transform::toString()); transformStack.push_back(State::Transform()); transformStack.back() = *this; mask &= ~GL_TRANSFORM_BIT; } if (mask&GL_HINT_BIT) { Internal("Regal::Ppa::PushAttrib GL_HINT_BIT ",State::Hint::toString()); hintStack.push_back(State::Hint()); hintStack.back() = *this; mask &= ~GL_HINT_BIT; } if (mask&GL_ENABLE_BIT) { Internal("Regal::Ppa::PushAttrib GL_ENABLE_BIT ",State::Enable::toString()); enableStack.push_back(State::Enable()); enableStack.back() = *this; mask &= ~GL_ENABLE_BIT; } if (mask&GL_LIST_BIT) { Internal("Regal::Ppa::PushAttrib GL_LIST_BIT ",State::List::toString()); listStack.push_back(State::List()); listStack.back() = *this; mask &= ~GL_LIST_BIT; } if (mask&GL_ACCUM_BUFFER_BIT) { Internal("Regal::Ppa::PushAttrib GL_ACCUM_BUFFER_BIT ",State::AccumBuffer::toString()); accumBufferStack.push_back(State::AccumBuffer()); accumBufferStack.back() = *this; mask &= ~GL_ACCUM_BUFFER_BIT; } if (mask&GL_SCISSOR_BIT) { Internal("Regal::Ppa::PushAttrib GL_SCISSOR_BIT ",State::Scissor::toString()); if (!State::Scissor::fullyDefined()) State::Scissor::getUndefined(ctx->dispatcher.emulation); scissorStack.push_back(State::Scissor()); scissorStack.back() = *this; mask &= ~GL_SCISSOR_BIT; } if (mask&GL_VIEWPORT_BIT) { Internal("Regal::Ppa::PushAttrib GL_VIEWPORT_BIT ",State::Viewport::toString()); if (!State::Viewport::fullyDefined()) State::Viewport::getUndefined(ctx->dispatcher.emulation); viewportStack.push_back(State::Viewport()); viewportStack.back() = *this; mask &= ~GL_VIEWPORT_BIT; } if (mask&GL_LINE_BIT) { Internal("Regal::Ppa::PushAttrib GL_LINE_BIT ",State::Line::toString()); lineStack.push_back(State::Line()); lineStack.back() = *this; mask &= ~GL_LINE_BIT; } if (mask&GL_MULTISAMPLE_BIT) { Internal("Regal::Ppa::PushAttrib GL_MULTISAMPLE_BIT ",State::Multisample::toString()); multisampleStack.push_back(State::Multisample()); multisampleStack.back() = *this; mask &= ~GL_MULTISAMPLE_BIT; } if (mask&GL_EVAL_BIT) { Internal("Regal::Ppa::PushAttrib GL_EVAL_BIT ",State::Eval::toString()); evalStack.push_back(State::Eval()); evalStack.back() = *this; mask &= ~GL_EVAL_BIT; } if (mask&GL_FOG_BIT) { Internal("Regal::Ppa::PushAttrib GL_FOG_BIT ",State::Fog::toString()); fogStack.push_back(State::Fog()); fogStack.back() = *this; mask &= ~GL_FOG_BIT; } if (mask&GL_POINT_BIT) { Internal("Regal::Ppa::PushAttrib GL_POINT_BIT ",State::Point::toString()); if (!State::Point::fullyDefined()) State::Point::getUndefined(ctx->dispatcher.emulation); pointStack.push_back(State::Point()); pointStack.back() = *this; mask &= ~GL_POINT_BIT; } if (mask&GL_POLYGON_STIPPLE_BIT) { Internal("Regal::Ppa::PushAttrib GL_POLYGON_STIPPLE_BIT ",State::PolygonStipple::toString()); polygonStippleStack.push_back(State::PolygonStipple()); polygonStippleStack.back() = *this; mask &= ~GL_POLYGON_STIPPLE_BIT; } if (mask&GL_COLOR_BUFFER_BIT) { Internal("Regal::Ppa::PushAttrib GL_COLOR_BUFFER_BIT ",State::ColorBuffer::toString()); if (!State::ColorBuffer::fullyDefined()) State::ColorBuffer::getUndefined(ctx->dispatcher.emulation); colorBufferStack.push_back(State::ColorBuffer()); colorBufferStack.back() = *this; mask &= ~GL_COLOR_BUFFER_BIT; } if (mask&GL_PIXEL_MODE_BIT) { Internal("Regal::Ppa::PushAttrib GL_PIXEL_MODE_BIT ",State::PixelMode::toString()); if (!State::PixelMode::fullyDefined()) State::PixelMode::getUndefined(ctx->dispatcher.emulation); pixelModeStack.push_back(State::PixelMode()); pixelModeStack.back() = *this; mask &= ~GL_PIXEL_MODE_BIT; } if (mask&GL_LIGHTING_BIT) { Internal("Regal::Ppa::PushAttrib GL_LIGHTING_BIT ",State::Lighting::toString()); lightingStack.push_back(State::Lighting()); lightingStack.back() = *this; mask &= ~GL_LIGHTING_BIT; } // Pass the rest through, for now RegalAssert(ctx); if (ctx->info->core || ctx->info->es1 || ctx->info->es2) return; if (mask) ctx->dispatcher.emulation.glPushAttrib(mask); } void PopAttrib(RegalContext *ctx) { RegalAssert(ctx); RegalAssert(maskStack.size()); if (maskStack.size()) { GLbitfield mask = maskStack.back(); maskStack.pop_back(); if (mask&GL_DEPTH_BUFFER_BIT) { RegalAssert(depthStack.size()); State::Depth::swap(depthStack.back()); depthStack.pop_back(); Internal("Regal::Ppa::PopAttrib GL_DEPTH_BUFFER_BIT ",State::Depth::toString()); // Ideally we'd only set the state that has changed // since the glPushAttrib() - revisit State::Depth::set(ctx->dispatcher.emulation); mask &= ~GL_DEPTH_BUFFER_BIT; } if (mask&GL_STENCIL_BUFFER_BIT) { RegalAssert(stencilStack.size()); State::Stencil::swap(stencilStack.back()); stencilStack.pop_back(); Internal("Regal::Ppa::PopAttrib GL_STENCIL_BUFFER_BIT ",State::Stencil::toString()); // Ideally we'd only set the state that has changed // since the glPushAttrib() - revisit State::Stencil::set(ctx->dispatcher.emulation); mask &= ~GL_STENCIL_BUFFER_BIT; } if (mask&GL_POLYGON_BIT) { RegalAssert(polygonStack.size()); State::Polygon::swap(polygonStack.back()); polygonStack.pop_back(); Internal("Regal::Ppa::PopAttrib GL_POLYGON_BIT ",State::Polygon::toString()); // Ideally we'd only set the state that has changed // since the glPushAttrib() - revisit State::Polygon::set(ctx->dispatcher.emulation); mask &= ~GL_POLYGON_BIT; } if (mask&GL_TRANSFORM_BIT) { RegalAssert(transformStack.size()); State::Transform::swap(transformStack.back()); Internal("Regal::Ppa::PopAttrib GL_TRANSFORM_BIT ",State::Transform::toString()); State::Transform::transition(ctx->dispatcher.emulation, transformStack.back()); transformStack.pop_back(); mask &= ~GL_TRANSFORM_BIT; } if (mask&GL_HINT_BIT) { RegalAssert(hintStack.size()); State::Hint::swap(hintStack.back()); hintStack.pop_back(); Internal("Regal::Ppa::PopAttrib GL_HINT_BIT ",State::Hint::toString()); // Ideally we'd only set the state that has changed // since the glPushAttrib() - revisit State::Hint::set(ctx->dispatcher.emulation); mask &= ~GL_HINT_BIT; } if (mask&GL_ENABLE_BIT) { RegalAssert(enableStack.size()); State::Enable::swap(enableStack.back()); enableStack.pop_back(); Internal("Regal::Ppa::PopAttrib GL_ENABLE_BIT ",State::Enable::toString()); // Ideally we'd only set the state that has changed // since the glPushAttrib() - revisit State::Enable::set(*ctx); mask &= ~GL_ENABLE_BIT; } if (mask&GL_LIST_BIT) { RegalAssert(listStack.size()); State::List::swap(listStack.back()); listStack.pop_back(); Internal("Regal::Ppa::PopAttrib GL_LIST_BIT ",State::List::toString()); // Ideally we'd only set the state that has changed // since the glPushAttrib() - revisit State::List::set(ctx->dispatcher.emulation); mask &= ~GL_LIST_BIT; } if (mask&GL_ACCUM_BUFFER_BIT) { RegalAssert(accumBufferStack.size()); State::AccumBuffer::swap(accumBufferStack.back()); accumBufferStack.pop_back(); Internal("Regal::Ppa::PopAttrib GL_ACCUM_BUFFER_BIT ",State::AccumBuffer::toString()); // Ideally we'd only set the state that has changed // since the glPushAttrib() - revisit State::AccumBuffer::set(ctx->dispatcher.emulation); mask &= ~GL_ACCUM_BUFFER_BIT; } if (mask&GL_SCISSOR_BIT) { RegalAssert(scissorStack.size()); State::Scissor::swap(scissorStack.back()); scissorStack.pop_back(); Internal("Regal::Ppa::PopAttrib GL_SCISSOR_BIT ",State::Scissor::toString()); // Ideally we'd only set the state that has changed // since the glPushAttrib() - revisit if (!State::Scissor::fullyDefined()) State::Scissor::getUndefined(ctx->dispatcher.emulation); State::Scissor::set(ctx->dispatcher.emulation); mask &= ~GL_SCISSOR_BIT; } if (mask&GL_VIEWPORT_BIT) { RegalAssert(viewportStack.size()); State::Viewport::swap(viewportStack.back()); viewportStack.pop_back(); Internal("Regal::Ppa::PopAttrib GL_VIEWPORT_BIT ",State::Viewport::toString()); // Ideally we'd only set the state that has changed // since the glPushAttrib() - revisit if (!State::Viewport::fullyDefined()) State::Viewport::getUndefined(ctx->dispatcher.emulation); State::Viewport::set(ctx->dispatcher.emulation); mask &= ~GL_VIEWPORT_BIT; } if (mask&GL_LINE_BIT) { RegalAssert(lineStack.size()); State::Line::swap(lineStack.back()); lineStack.pop_back(); Internal("Regal::Ppa::PopAttrib GL_LINE_BIT ",State::Line::toString()); // Ideally we'd only set the state that has changed // since the glPushAttrib() - revisit State::Line::set(ctx->dispatcher.emulation); mask &= ~GL_LINE_BIT; } if (mask&GL_MULTISAMPLE_BIT) { RegalAssert(multisampleStack.size()); State::Multisample::swap(multisampleStack.back()); multisampleStack.pop_back(); Internal("Regal::Ppa::PopAttrib GL_MULTISAMPLE_BIT ",State::Multisample::toString()); // Ideally we'd only set the state that has changed // since the glPushAttrib() - revisit State::Multisample::set(*ctx); mask &= ~GL_MULTISAMPLE_BIT; } if (mask&GL_EVAL_BIT) { RegalAssert(evalStack.size()); State::Eval::swap(evalStack.back()); evalStack.pop_back(); Internal("Regal::Ppa::PopAttrib GL_EVAL_BIT ",State::Eval::toString()); // Ideally we'd only set the state that has changed // since the glPushAttrib() - revisit State::Eval::set(ctx->dispatcher.emulation); mask &= ~GL_EVAL_BIT; } if (mask&GL_FOG_BIT) { RegalAssert(fogStack.size()); State::Fog::swap(fogStack.back()); fogStack.pop_back(); Internal("Regal::Ppa::PopAttrib GL_FOG_BIT ",State::Fog::toString()); // Ideally we'd only set the state that has changed // since the glPushAttrib() - revisit State::Fog::set(ctx->dispatcher.emulation); mask &= ~GL_FOG_BIT; } if (mask&GL_POINT_BIT) { RegalAssert(pointStack.size()); State::Point::swap(pointStack.back()); pointStack.pop_back(); Internal("Regal::Ppa::PopAttrib GL_POINT_BIT ",State::Point::toString()); // Ideally we'd only set the state that has changed // since the glPushAttrib() - revisit if (!State::Point::fullyDefined()) State::Point::getUndefined(ctx->dispatcher.emulation); State::Point::set(ctx->dispatcher.emulation); mask &= ~GL_POINT_BIT; } if (mask&GL_POLYGON_STIPPLE_BIT) { RegalAssert(polygonStippleStack.size()); State::PolygonStipple::swap(polygonStippleStack.back()); polygonStippleStack.pop_back(); Internal("Regal::Ppa::PopAttrib GL_POLYGON_STIPPLE_BIT ",State::PolygonStipple::toString()); // Ideally we'd only set the state that has changed // since the glPushAttrib() - revisit State::PolygonStipple::set(ctx->dispatcher.emulation); mask &= ~GL_POLYGON_STIPPLE_BIT; } if (mask&GL_COLOR_BUFFER_BIT) { RegalAssert(colorBufferStack.size()); State::ColorBuffer::swap(colorBufferStack.back()); colorBufferStack.pop_back(); Internal("Regal::Ppa::PopAttrib GL_COLOR_BUFFER_BIT ",State::ColorBuffer::toString()); // Ideally we'd only set the state that has changed // since the glPushAttrib() - revisit if (!State::ColorBuffer::fullyDefined()) State::ColorBuffer::getUndefined(ctx->dispatcher.emulation); State::ColorBuffer::set(ctx->dispatcher.emulation); mask &= ~GL_COLOR_BUFFER_BIT; } if (mask&GL_PIXEL_MODE_BIT) { RegalAssert(pixelModeStack.size()); State::PixelMode::swap(pixelModeStack.back()); pixelModeStack.pop_back(); Internal("Regal::Ppa::PopAttrib GL_PIXEL_MODE_BIT ",State::PixelMode::toString()); // Ideally we'd only set the state that has changed // since the glPushAttrib() - revisit if (!State::PixelMode::fullyDefined()) State::PixelMode::getUndefined(ctx->dispatcher.emulation); State::PixelMode::set(ctx->dispatcher.emulation); mask &= ~GL_PIXEL_MODE_BIT; } if (mask&GL_LIGHTING_BIT) { RegalAssert(lightingStack.size()); State::Lighting::swap(lightingStack.back()); lightingStack.pop_back(); Internal("Regal::Ppa::PopAttrib GL_LIGHTING_BIT ",State::Lighting::toString()); // Ideally we'd only set the state that has changed // since the glPushAttrib() - revisit State::Lighting::set(ctx->dispatcher.emulation); mask &= ~GL_LIGHTING_BIT; } // Pass the rest through, for now if (ctx->info->core || ctx->info->es1 || ctx->info->es2) return; if (mask) ctx->dispatcher.emulation.glPopAttrib(); } } template <typename T> bool glGetv(RegalContext *ctx, GLenum pname, T *params) { RegalAssert(ctx); RegalAssert(ctx->info); if (ctx->info->core || ctx->info->es1 || ctx->info->es2) { switch (pname) { case GL_ACCUM_RED_BITS: case GL_ACCUM_GREEN_BITS: case GL_ACCUM_BLUE_BITS: case GL_ACCUM_ALPHA_BITS: if (params) params[0] = 32; break; case GL_RED_BITS: case GL_GREEN_BITS: case GL_BLUE_BITS: case GL_ALPHA_BITS: case GL_INDEX_BITS: case GL_STENCIL_BITS: if (params) params[0] = 8; break; case GL_DEPTH_BITS: if (params) params[0] = 24; break; case GL_AUX_BUFFERS: case GL_LINE_STIPPLE: case GL_MAX_PIXEL_MAP_TABLE: case GL_MAX_NAME_STACK_DEPTH: case GL_MAX_LIST_NESTING: case GL_MAX_EVAL_ORDER: if (params) params[0] = 0; break; case GL_ATTRIB_STACK_DEPTH: if (params) params[0] = static_cast<T>(maskStack.size()); break; case GL_MAX_ATTRIB_STACK_DEPTH: if (params) { RegalAssert(ctx->emuInfo); params[0] = static_cast<T>(ctx->emuInfo->gl_max_attrib_stack_depth); } break; default: return false; } return true; } switch (pname) { case GL_ACCUM_CLEAR_VALUE: params[0] = static_cast<T>(State::AccumBuffer::clear[0]); params[1] = static_cast<T>(State::AccumBuffer::clear[1]); params[2] = static_cast<T>(State::AccumBuffer::clear[2]); params[3] = static_cast<T>(State::AccumBuffer::clear[3]); break; case GL_ALPHA_BIAS: params[0] = static_cast<T>(State::PixelMode::alphaBias); break; case GL_ALPHA_SCALE: params[0] = static_cast<T>(State::PixelMode::alphaScale); break; case GL_ALPHA_TEST_FUNC: params[0] = static_cast<T>(State::ColorBuffer::alphaTestFunc); break; case GL_ALPHA_TEST_REF: params[0] = static_cast<T>(State::ColorBuffer::alphaTestRef); break; case GL_BLEND_COLOR: params[0] = static_cast<T>(State::ColorBuffer::blendColor[0]); params[1] = static_cast<T>(State::ColorBuffer::blendColor[1]); params[2] = static_cast<T>(State::ColorBuffer::blendColor[2]); params[3] = static_cast<T>(State::ColorBuffer::blendColor[3]); break; case GL_BLUE_BIAS: params[0] = static_cast<T>(State::PixelMode::blueBias); break; case GL_BLUE_SCALE: params[0] = static_cast<T>(State::PixelMode::blueScale); break; case GL_CLAMP_FRAGMENT_COLOR: params[0] = static_cast<T>(State::Enable::clampFragmentColor); break; case GL_CLAMP_READ_COLOR: params[0] = static_cast<T>(State::Enable::clampReadColor); break; case GL_CLAMP_VERTEX_COLOR: params[0] = static_cast<T>(State::Enable::clampVertexColor); break; case GL_COLOR_CLEAR_VALUE: params[0] = static_cast<T>(State::ColorBuffer::colorClearValue[0]); params[1] = static_cast<T>(State::ColorBuffer::colorClearValue[1]); params[2] = static_cast<T>(State::ColorBuffer::colorClearValue[2]); params[3] = static_cast<T>(State::ColorBuffer::colorClearValue[3]); break; case GL_COLOR_MATERIAL_FACE: params[0] = static_cast<T>(State::Lighting::colorMaterialFace); break; case GL_COLOR_MATERIAL_PARAMETER: params[0] = static_cast<T>(State::Lighting::colorMaterialParameter); break; case GL_CULL_FACE_MODE: params[0] = static_cast<T>(State::Polygon::cullFaceMode); break; case GL_DEPTH_CLEAR_VALUE: params[0] = static_cast<T>(State::Depth::clear); break; case GL_DEPTH_FUNC: params[0] = static_cast<T>(State::Depth::func); break; case GL_DEPTH_WRITEMASK: params[0] = static_cast<T>(State::Depth::mask); break; case GL_DRAW_BUFFER0: case GL_DRAW_BUFFER1: case GL_DRAW_BUFFER2: case GL_DRAW_BUFFER3: case GL_DRAW_BUFFER4: case GL_DRAW_BUFFER5: case GL_DRAW_BUFFER6: case GL_DRAW_BUFFER7: case GL_DRAW_BUFFER8: case GL_DRAW_BUFFER9: case GL_DRAW_BUFFER10: case GL_DRAW_BUFFER11: case GL_DRAW_BUFFER12: case GL_DRAW_BUFFER13: case GL_DRAW_BUFFER14: case GL_DRAW_BUFFER15: { GLuint index = static_cast<GLuint>(pname - GL_DRAW_BUFFER0); if ( index < array_size( State::ColorBuffer::drawBuffers )) { if (!State::ColorBuffer::fullyDefined()) State::ColorBuffer::getUndefined(ctx->dispatcher.emulation); RegalAssertArrayIndex( State::ColorBuffer::drawBuffers, index ); params[0] = static_cast<T>(State::ColorBuffer::drawBuffers[index]); } } break; case GL_FOG_COLOR: params[0] = static_cast<T>(State::Fog::color[0]); params[1] = static_cast<T>(State::Fog::color[1]); params[2] = static_cast<T>(State::Fog::color[2]); params[3] = static_cast<T>(State::Fog::color[3]); break; case GL_FOG_COORD_SRC: params[0] = static_cast<T>(State::Fog::coordSrc); break; case GL_FOG_DENSITY: params[0] = static_cast<T>(State::Fog::density); break; case GL_FOG_END: params[0] = static_cast<T>(State::Fog::end); break; case GL_FOG_HINT: params[0] = static_cast<T>(State::Hint::fog); break; case GL_FOG_INDEX: params[0] = static_cast<T>(State::Fog::index); break; case GL_FOG_MODE: params[0] = static_cast<T>(State::Fog::mode); break; case GL_FOG_START: params[0] = static_cast<T>(State::Fog::start); break; case GL_FRAGMENT_SHADER_DERIVATIVE_HINT: params[0] = static_cast<T>(State::Hint::fragmentShaderDerivative); break; case GL_FRONT_FACE: params[0] = static_cast<T>(State::Polygon::frontFace); break; case GL_GENERATE_MIPMAP_HINT: params[0] = static_cast<T>(State::Hint::generateMipmap); break; case GL_GREEN_BIAS: params[0] = static_cast<T>(State::PixelMode::greenBias); break; case GL_GREEN_SCALE: params[0] = static_cast<T>(State::PixelMode::greenScale); break; case GL_INDEX_CLEAR_VALUE: params[0] = static_cast<T>(State::ColorBuffer::indexClearValue); break; case GL_INDEX_OFFSET: params[0] = static_cast<T>(State::PixelMode::indexOffset); break; case GL_INDEX_SHIFT: params[0] = static_cast<T>(State::PixelMode::indexShift); break; case GL_INDEX_WRITEMASK: params[0] = static_cast<T>(State::ColorBuffer::indexWritemask); break; case GL_LIGHT_MODEL_AMBIENT: params[0] = static_cast<T>(State::Lighting::lightModelAmbient[0]); params[1] = static_cast<T>(State::Lighting::lightModelAmbient[1]); params[2] = static_cast<T>(State::Lighting::lightModelAmbient[2]); params[3] = static_cast<T>(State::Lighting::lightModelAmbient[3]); break; case GL_LIGHT_MODEL_COLOR_CONTROL: params[0] = static_cast<T>(State::Lighting::lightModelColorControl); break; case GL_LIGHT_MODEL_LOCAL_VIEWER: params[0] = static_cast<T>(State::Lighting::lightModelLocalViewer); break; case GL_LIGHT_MODEL_TWO_SIDE: params[0] = static_cast<T>(State::Lighting::lightModelTwoSide); break; case GL_LINE_SMOOTH_HINT: params[0] = static_cast<T>(State::Hint::lineSmooth); break; case GL_LINE_STIPPLE_PATTERN: params[0] = static_cast<T>(State::Line::stipplePattern); break; case GL_LINE_STIPPLE_REPEAT: params[0] = static_cast<T>(State::Line::stippleRepeat); break; case GL_LINE_WIDTH: params[0] = static_cast<T>(State::Line::width); break; case GL_LIST_BASE: params[0] = static_cast<T>(State::List::base); break; case GL_LOGIC_OP_MODE: params[0] = static_cast<T>(State::ColorBuffer::logicOpMode); break; case GL_MAP1_GRID_DOMAIN: params[0] = static_cast<T>(State::Eval::map1GridDomain[0]); params[1] = static_cast<T>(State::Eval::map1GridDomain[1]); break; case GL_MAP1_GRID_SEGMENTS: params[0] = static_cast<T>(State::Eval::map1GridSegments); break; case GL_MAP2_GRID_DOMAIN: params[0] = static_cast<T>(State::Eval::map2GridDomain[0]); params[1] = static_cast<T>(State::Eval::map2GridDomain[1]); params[2] = static_cast<T>(State::Eval::map2GridDomain[2]); params[3] = static_cast<T>(State::Eval::map2GridDomain[3]); break; case GL_MAP2_GRID_SEGMENTS: params[0] = static_cast<T>(State::Eval::map2GridSegments[0]); params[1] = static_cast<T>(State::Eval::map2GridSegments[1]); break; case GL_MAP_COLOR: params[0] = static_cast<T>(State::PixelMode::mapColor); break; case GL_ATTRIB_STACK_DEPTH: params[0] = static_cast<T>(maskStack.size()); break; case GL_MAX_ATTRIB_STACK_DEPTH: RegalAssert(ctx->emuInfo); params[0] = static_cast<T>(ctx->emuInfo->gl_max_attrib_stack_depth); break; case GL_MAX_TEXTURE_UNITS: RegalAssert(ctx->emuInfo); params[0] = static_cast<T>(ctx->emuInfo->gl_max_texture_units); break; case GL_MAX_VIEWPORTS: RegalAssert(ctx->emuInfo); params[0] = static_cast<T>(ctx->emuInfo->gl_max_viewports); break; case GL_MAP_STENCIL: params[0] = static_cast<T>(State::PixelMode::mapStencil); break; case GL_MIN_SAMPLE_SHADING_VALUE: params[0] = static_cast<T>(State::Multisample::minSampleShadingValue); break; case GL_PERSPECTIVE_CORRECTION_HINT: params[0] = static_cast<T>(State::Hint::perspectiveCorrection); break; case GL_POINT_DISTANCE_ATTENUATION: params[0] = static_cast<T>(State::Point::distanceAttenuation[0]); params[1] = static_cast<T>(State::Point::distanceAttenuation[1]); params[2] = static_cast<T>(State::Point::distanceAttenuation[2]); break; case GL_POINT_FADE_THRESHOLD_SIZE: params[0] = static_cast<T>(State::Point::fadeThresholdSize); break; case GL_POINT_SIZE_MAX: params[0] = static_cast<T>(State::Point::sizeMax); break; case GL_POINT_SIZE_MIN: params[0] = static_cast<T>(State::Point::sizeMin); break; case GL_POINT_SIZE: params[0] = static_cast<T>(State::Point::size); break; case GL_POINT_SMOOTH_HINT: params[0] = static_cast<T>(State::Hint::pointSmooth); break; case GL_POINT_SPRITE_COORD_ORIGIN: params[0] = static_cast<T>(State::Point::spriteCoordOrigin); break; case GL_POLYGON_MODE: params[0] = static_cast<T>(State::Polygon::mode[0]); params[1] = static_cast<T>(State::Polygon::mode[1]); break; case GL_POLYGON_OFFSET_FACTOR: params[0] = static_cast<T>(State::Polygon::factor); break; case GL_POLYGON_OFFSET_UNITS: params[0] = static_cast<T>(State::Polygon::units); break; case GL_POLYGON_SMOOTH_HINT: params[0] = static_cast<T>(State::Hint::polygonSmooth); break; case GL_POST_COLOR_MATRIX_ALPHA_BIAS: params[0] = static_cast<T>(State::PixelMode::postColorMatrixAlphaBias); break; case GL_POST_COLOR_MATRIX_ALPHA_SCALE: params[0] = static_cast<T>(State::PixelMode::postColorMatrixAlphaScale); break; case GL_POST_COLOR_MATRIX_BLUE_BIAS: params[0] = static_cast<T>(State::PixelMode::postColorMatrixBlueBias); break; case GL_POST_COLOR_MATRIX_BLUE_SCALE: params[0] = static_cast<T>(State::PixelMode::postColorMatrixBlueScale); break; case GL_POST_COLOR_MATRIX_GREEN_BIAS: params[0] = static_cast<T>(State::PixelMode::postColorMatrixGreenBias); break; case GL_POST_COLOR_MATRIX_GREEN_SCALE: params[0] = static_cast<T>(State::PixelMode::postColorMatrixGreenScale); break; case GL_POST_COLOR_MATRIX_RED_BIAS: params[0] = static_cast<T>(State::PixelMode::postColorMatrixRedBias); break; case GL_POST_COLOR_MATRIX_RED_SCALE: params[0] = static_cast<T>(State::PixelMode::postColorMatrixRedScale); break; case GL_POST_CONVOLUTION_ALPHA_BIAS: params[0] = static_cast<T>(State::PixelMode::postConvolutionAlphaBias); break; case GL_POST_CONVOLUTION_ALPHA_SCALE: params[0] = static_cast<T>(State::PixelMode::postConvolutionAlphaScale); break; case GL_POST_CONVOLUTION_BLUE_BIAS: params[0] = static_cast<T>(State::PixelMode::postConvolutionBlueBias); break; case GL_POST_CONVOLUTION_BLUE_SCALE: params[0] = static_cast<T>(State::PixelMode::postConvolutionBlueScale); break; case GL_POST_CONVOLUTION_GREEN_BIAS: params[0] = static_cast<T>(State::PixelMode::postConvolutionGreenBias); break; case GL_POST_CONVOLUTION_GREEN_SCALE: params[0] = static_cast<T>(State::PixelMode::postConvolutionGreenScale); break; case GL_POST_CONVOLUTION_RED_BIAS: params[0] = static_cast<T>(State::PixelMode::postConvolutionRedBias); break; case GL_POST_CONVOLUTION_RED_SCALE: params[0] = static_cast<T>(State::PixelMode::postConvolutionRedScale); break; case GL_PROVOKING_VERTEX: params[0] = static_cast<T>(State::Lighting::provokingVertex); break; case GL_READ_BUFFER: { if (!State::PixelMode::fullyDefined()) State::PixelMode::getUndefined(ctx->dispatcher.emulation); params[0] = static_cast<T>(State::PixelMode::readBuffer); } break; case GL_RED_BIAS: params[0] = static_cast<T>(State::PixelMode::redBias); break; case GL_RED_SCALE: params[0] = static_cast<T>(State::PixelMode::redScale); break; case GL_SAMPLE_COVERAGE_INVERT: params[0] = static_cast<T>(State::Multisample::sampleCoverageInvert); break; case GL_SAMPLE_COVERAGE_VALUE: params[0] = static_cast<T>(State::Multisample::sampleCoverageValue); break; case GL_SHADE_MODEL: params[0] = static_cast<T>(State::Lighting::shadeModel); break; case GL_STENCIL_BACK_FAIL: params[0] = static_cast<T>(State::Stencil::back.fail); break; case GL_STENCIL_BACK_FUNC: params[0] = static_cast<T>(State::Stencil::back.func); break; case GL_STENCIL_BACK_PASS_DEPTH_FAIL: params[0] = static_cast<T>(State::Stencil::back.zfail); break; case GL_STENCIL_BACK_PASS_DEPTH_PASS: params[0] = static_cast<T>(State::Stencil::back.zpass); break; case GL_STENCIL_BACK_REF: params[0] = static_cast<T>(State::Stencil::back.ref); break; case GL_STENCIL_BACK_VALUE_MASK: params[0] = static_cast<T>(State::Stencil::back.valueMask); break; case GL_STENCIL_BACK_WRITEMASK: params[0] = static_cast<T>(State::Stencil::back.writeMask); break; case GL_STENCIL_CLEAR_VALUE: params[0] = static_cast<T>(State::Stencil::clear); break; case GL_STENCIL_FAIL: params[0] = static_cast<T>(State::Stencil::front.fail); break; case GL_STENCIL_FUNC: params[0] = static_cast<T>(State::Stencil::front.func); break; case GL_STENCIL_PASS_DEPTH_FAIL: params[0] = static_cast<T>(State::Stencil::front.zfail); break; case GL_STENCIL_PASS_DEPTH_PASS: params[0] = static_cast<T>(State::Stencil::front.zpass); break; case GL_STENCIL_REF: params[0] = static_cast<T>(State::Stencil::front.ref); break; case GL_STENCIL_VALUE_MASK: params[0] = static_cast<T>(State::Stencil::front.valueMask); break; case GL_STENCIL_WRITEMASK: params[0] = static_cast<T>(State::Stencil::front.writeMask); break; case GL_TEXTURE_COMPRESSION_HINT: params[0] = static_cast<T>(State::Hint::textureCompression); break; case GL_ZOOM_X: params[0] = static_cast<T>(State::PixelMode::zoomX); break; case GL_ZOOM_Y: params[0] = static_cast<T>(State::PixelMode::zoomY); break; default: return false; } return true; } template <typename T> bool glGeti_v(RegalContext *ctx, GLenum pname, GLuint index, T *params) { UNUSED_PARAMETER(ctx); switch (pname) { case GL_BLEND_DST_ALPHA: if (index < array_size( State::ColorBuffer::blendDstAlpha )) { RegalAssertArrayIndex( State::ColorBuffer::blendDstAlpha, index ); params[0] = static_cast<T>(State::ColorBuffer::blendDstAlpha[index]); } break; case GL_BLEND_DST_RGB: if (index < array_size( State::ColorBuffer::blendDstRgb )) { RegalAssertArrayIndex( State::ColorBuffer::blendDstRgb, index ); params[0] = static_cast<T>(State::ColorBuffer::blendDstRgb[index]); } break; case GL_BLEND_EQUATION_ALPHA: if (index < array_size( State::ColorBuffer::blendEquationAlpha )) { RegalAssertArrayIndex( State::ColorBuffer::blendEquationAlpha, index ); params[0] = static_cast<T>(State::ColorBuffer::blendEquationAlpha[index]); } break; case GL_BLEND_EQUATION_RGB: if (index < array_size( State::ColorBuffer::blendEquationRgb )) { RegalAssertArrayIndex( State::ColorBuffer::blendEquationRgb, index ); params[0] = static_cast<T>(State::ColorBuffer::blendEquationRgb[index]); } break; case GL_BLEND_SRC_ALPHA: if (index < array_size( State::ColorBuffer::blendSrcAlpha )) { RegalAssertArrayIndex( State::ColorBuffer::blendSrcAlpha, index ); params[0] = static_cast<T>(State::ColorBuffer::blendSrcAlpha[index]); } break; case GL_BLEND_SRC_RGB: if (index < array_size( State::ColorBuffer::blendSrcRgb )) { RegalAssertArrayIndex( State::ColorBuffer::blendSrcRgb, index ); params[0] = static_cast<T>(State::ColorBuffer::blendSrcRgb[index]); } break; case GL_COLOR_WRITEMASK: RegalAssert(ctx->emuInfo); if (index < ctx->emuInfo->gl_max_draw_buffers) { params[0] = static_cast<T>(State::ColorBuffer::colorWritemask[index][0]); params[1] = static_cast<T>(State::ColorBuffer::colorWritemask[index][1]); params[2] = static_cast<T>(State::ColorBuffer::colorWritemask[index][2]); params[3] = static_cast<T>(State::ColorBuffer::colorWritemask[index][3]); } break; case GL_DEPTH_RANGE: RegalAssert(ctx->emuInfo); if (index < ctx->emuInfo->gl_max_viewports) { params[0] = static_cast<T>(State::Viewport::depthRange[index][0]); params[1] = static_cast<T>(State::Viewport::depthRange[index][1]); } break; case GL_MAX_VIEWPORTS: RegalAssert(ctx->emuInfo); params[0] = static_cast<T>(ctx->emuInfo->gl_max_viewports); break; case GL_SCISSOR_BOX: RegalAssert(ctx->emuInfo); if (index < ctx->emuInfo->gl_max_viewports) { if (!State::Scissor::fullyDefined()) State::Scissor::getUndefined(ctx->dispatcher.emulation); params[0] = static_cast<T>(State::Scissor::scissorBox[index][0]); params[1] = static_cast<T>(State::Scissor::scissorBox[index][1]); params[2] = static_cast<T>(State::Scissor::scissorBox[index][2]); params[3] = static_cast<T>(State::Scissor::scissorBox[index][3]); } break; case GL_VIEWPORT: RegalAssert(ctx->emuInfo); if (index < ctx->emuInfo->gl_max_viewports) { if (!State::Viewport::fullyDefined()) State::Viewport::getUndefined(ctx->dispatcher.emulation); params[0] = static_cast<T>(State::Viewport::viewport[index][0]); params[1] = static_cast<T>(State::Viewport::viewport[index][1]); params[2] = static_cast<T>(State::Viewport::viewport[index][2]); params[3] = static_cast<T>(State::Viewport::viewport[index][3]); } break; default: return false; } return true; } bool glGetPolygonStipple(RegalContext *ctx, GLubyte *pattern) { UNUSED_PARAMETER(ctx); // If a non-zero named buffer object is bound to the GL_PIXEL_PACK_BUFFER target // (see glBindBuffer) while a polygon stipple pattern is requested, pattern is // treated as a byte offset into the buffer object's data store. // // TODO: need to handle this case, dammit. but for now just... memcpy(pattern, State::PolygonStipple::pattern, (32*4)*sizeof(GLubyte)); return true; } template <typename T> bool glGetColorTableParameterv(RegalContext *ctx, GLenum target, GLenum pname, T *params) { UNUSED_PARAMETER(ctx); GLuint index = 0; switch (pname) { case GL_COLOR_TABLE: index = 0; break; case GL_POST_CONVOLUTION_COLOR_TABLE: index = 1; break; case GL_POST_COLOR_MATRIX_COLOR_TABLE: index = 2; break; default: return false; } GLfloat *p = NULL; switch (target) { case GL_COLOR_TABLE_SCALE: p = &State::PixelMode::colorTableScale[index][0]; break; case GL_COLOR_TABLE_BIAS: p = &State::PixelMode::colorTableBias[index][0]; break; default: return false; } params[0] = static_cast<T>(p[0]); params[1] = static_cast<T>(p[1]); params[2] = static_cast<T>(p[2]); params[3] = static_cast<T>(p[3]); return true; } template <typename T> bool glGetConvolutionParameterv(RegalContext *ctx, GLenum target, GLenum pname, T *params) { UNUSED_PARAMETER(ctx); GLuint index = 0; switch (pname) { case GL_CONVOLUTION_1D: index = 0; break; case GL_CONVOLUTION_2D: index = 1; break; case GL_SEPARABLE_2D: index = 2; break; default: return false; } if (target == GL_CONVOLUTION_BORDER_MODE) { params[0] = static_cast<T>(State::PixelMode::convolutionBorderMode[index]); return true; } GLfloat *p = NULL; switch (target) { case GL_CONVOLUTION_BORDER_COLOR: p = &State::PixelMode::convolutionBorderColor[index][0]; break; case GL_CONVOLUTION_FILTER_SCALE: p = &State::PixelMode::convolutionFilterScale[index][0]; break; case GL_CONVOLUTION_FILTER_BIAS: p = &State::PixelMode::convolutionFilterBias[index][0]; break; default: return false; } params[0] = static_cast<T>(p[0]); params[1] = static_cast<T>(p[1]); params[2] = static_cast<T>(p[2]); params[3] = static_cast<T>(p[3]); return true; } template <typename T> bool glGetLightv(RegalContext *ctx, GLenum light, GLenum pname, T *params) { UNUSED_PARAMETER(ctx); GLint ii = light - GL_LIGHT0; if (ii < 0 || static_cast<size_t>(ii) >= array_size( State::Lighting::lights )) return false; RegalAssertArrayIndex( State::Lighting::lights, ii ); State::LightingLight l = State::Lighting::lights[ii]; GLuint num = 0; GLfloat *p = NULL; switch (pname) { case GL_AMBIENT: num = 4; p = &l.ambient[0]; break; case GL_DIFFUSE: num = 4; p = &l.diffuse[0]; break; case GL_SPECULAR: num = 4; p = &l.specular[0]; break; case GL_POSITION: num = 4; p = &l.position[0]; break; case GL_CONSTANT_ATTENUATION: num = 1; p = &l.constantAttenuation; break; case GL_LINEAR_ATTENUATION: num = 1; p = &l.linearAttenuation; break; case GL_QUADRATIC_ATTENUATION: num = 1; p = &l.quadraticAttenuation; break; case GL_SPOT_DIRECTION: num = 3; p = &l.spotDirection[0]; break; case GL_SPOT_EXPONENT: num = 1; p = &l.spotExponent; break; case GL_SPOT_CUTOFF: num = 1; p = &l.spotCutoff; break; default: return false; } for (size_t ii = 0; ii < num; ii++) params[ii] = static_cast<T>(p[ii]); return true; } template <typename T> bool glGetMaterialv(RegalContext *ctx, GLenum face, GLenum pname, T *params) { UNUSED_PARAMETER(ctx); if (face != GL_FRONT && face != GL_BACK) return false; State::LightingFace &f = (face == GL_FRONT) ? State::Lighting::front : State::Lighting::back; GLuint num = 0; GLfloat *p = NULL; switch (pname) { case GL_AMBIENT: num = 4; p = &f.ambient[0]; break; case GL_DIFFUSE: num = 4; p = &f.diffuse[0]; break; case GL_SPECULAR: num = 4; p = &f.specular[0]; break; case GL_EMISSION: num = 4; p = &f.emission[0]; break; case GL_SHININESS: num = 1; p = &f.shininess; break; case GL_COLOR_INDEXES: num = 3; p = &f.colorIndexes[0]; break; default: return false; } for (size_t ii = 0; ii < num; ii++) params[ii] = static_cast<T>(p[ii]); return true; } template <typename T> bool glGetMultiTexEnvv(RegalContext *ctx, GLenum texunit, GLenum target, GLenum pname, T *params) { UNUSED_PARAMETER(ctx); if (target != GL_POINT_SPRITE || pname != GL_COORD_REPLACE) return false; GLint ii = texunit - GL_TEXTURE0; if (ii < 0 || static_cast<size_t>(ii) >= array_size( State::Point::coordReplace )) return false; RegalAssertArrayIndex( State::Point::coordReplace, ii ); *params = static_cast<T>(State::Point::coordReplace[ii]); return true; } template <typename T> bool glGetTexEnvv(RegalContext *ctx, GLenum target, GLenum pname, T *params) { return glGetMultiTexEnvv(ctx, GL_TEXTURE0+activeTextureUnit, target, pname, params); } template <typename T> bool glGetTexParameter( RegalContext *ctx, GLenum target, GLenum pname, T * params ) { UNUSED_PARAMETER(target); switch( pname ) { case GL_DEPTH_STENCIL_TEXTURE_MODE: if( ctx->info->es2 || ! ctx->info->gl_arb_stencil_texturing ) { params[0] = GL_DEPTH_COMPONENT; return true; } break; case GL_TEXTURE_SWIZZLE_R: if( ctx->info->es2 || ! ctx->info->gl_ext_texture_swizzle ) { params[0] = GL_RED; return true; } break; case GL_TEXTURE_SWIZZLE_G: if( ctx->info->es2 || ! ctx->info->gl_ext_texture_swizzle ) { params[0] = GL_GREEN; return true; } break; case GL_TEXTURE_SWIZZLE_B: if( ctx->info->es2 || ! ctx->info->gl_ext_texture_swizzle ) { params[0] = GL_BLUE; return true; } break; case GL_TEXTURE_SWIZZLE_A: if( ctx->info->es2 || ! ctx->info->gl_ext_texture_swizzle ) { params[0] = GL_ALPHA; return true; } break; case GL_TEXTURE_SWIZZLE_RGBA: if( ctx->info->es2 || ! ctx->info->gl_ext_texture_swizzle ) { params[0] = GL_RED; params[1] = GL_GREEN; params[2] = GL_BLUE; params[3] = GL_ALPHA; return true; } break; default: break; } return false; } template <typename T> bool glGetTextureParameter( RegalContext *ctx, GLuint texture, GLenum target, GLenum pname, T * params ) { UNUSED_PARAMETER(texture); return glGetTexParameter( ctx, target, pname, params ); } template <typename T> bool glGetTexLevelParameter( RegalContext *ctx, GLenum target, GLint level, GLenum pname, T * params ) { //<> why is this function empty? UNUSED_PARAMETER(ctx); UNUSED_PARAMETER(target); UNUSED_PARAMETER(level); UNUSED_PARAMETER(pname); UNUSED_PARAMETER(params); return false; } template <typename T> bool glGetTextureLevelParameter( RegalContext *ctx, GLuint texture, GLenum target, GLint level, GLenum pname, T * params ) { UNUSED_PARAMETER(texture); return glGetTexLevelParameter( ctx, target, level, pname, params ); } bool glIsEnabled(RegalContext *ctx, GLboolean &enabled, GLenum pname) { UNUSED_PARAMETER(ctx); switch (pname) { case GL_ALPHA_TEST: enabled = State::Enable::alphaTest; break; case GL_BLEND: enabled = State::Enable::blend[0]; break; case GL_AUTO_NORMAL: enabled = State::Enable::autoNormal; break; case GL_CLIP_DISTANCE0: case GL_CLIP_DISTANCE1: case GL_CLIP_DISTANCE2: case GL_CLIP_DISTANCE3: case GL_CLIP_DISTANCE4: case GL_CLIP_DISTANCE5: case GL_CLIP_DISTANCE6: case GL_CLIP_DISTANCE7: if (pname-GL_CLIP_DISTANCE0 < array_size( State::Enable::clipDistance )) { RegalAssertArrayIndex( State::Enable::clipDistance, pname-GL_CLIP_DISTANCE0 ); enabled = State::Enable::clipDistance[pname-GL_CLIP_DISTANCE0]; } break; case GL_COLOR_LOGIC_OP: enabled = State::Enable::colorLogicOp; break; case GL_COLOR_MATERIAL: enabled = State::Enable::colorMaterial; break; case GL_COLOR_SUM: enabled = State::Enable::colorSum; break; case GL_COLOR_TABLE: enabled = State::Enable::colorTable; break; case GL_CONVOLUTION_1D: enabled = State::Enable::convolution1d; break; case GL_CONVOLUTION_2D: enabled = State::Enable::convolution2d; break; case GL_CULL_FACE: enabled = State::Enable::cullFace; break; case GL_DEPTH_CLAMP: enabled = State::Enable::depthClamp; break; case GL_DEPTH_TEST: enabled = State::Enable::depthTest; break; case GL_DITHER: enabled = State::Enable::dither; break; case GL_FOG: enabled = State::Enable::fog; break; case GL_FRAMEBUFFER_SRGB: enabled = State::Enable::framebufferSRGB; break; case GL_HISTOGRAM: enabled = State::Enable::histogram; break; case GL_INDEX_LOGIC_OP: enabled = State::Enable::indexLogicOp; break; case GL_LIGHT0: case GL_LIGHT1: case GL_LIGHT2: case GL_LIGHT3: case GL_LIGHT4: case GL_LIGHT5: case GL_LIGHT6: case GL_LIGHT7: if (pname-GL_LIGHT0 < array_size( State::Enable::light )) { RegalAssertArrayIndex( State::Enable::light, pname-GL_LIGHT0 ); enabled = State::Enable::light[pname-GL_LIGHT0]; } break; case GL_LIGHTING: enabled = State::Enable::lighting; break; case GL_LINE_SMOOTH: enabled = State::Enable::lineSmooth; break; case GL_LINE_STIPPLE: enabled = State::Enable::lineStipple; break; case GL_MAP1_COLOR_4: enabled = State::Enable::map1Color4; break; case GL_MAP1_INDEX: enabled = State::Enable::map1Index; break; case GL_MAP1_NORMAL: enabled = State::Enable::map1Normal; break; case GL_MAP1_TEXTURE_COORD_1: enabled = State::Enable::map1TextureCoord1; break; case GL_MAP1_TEXTURE_COORD_2: enabled = State::Enable::map1TextureCoord2; break; case GL_MAP1_TEXTURE_COORD_3: enabled = State::Enable::map1TextureCoord3; break; case GL_MAP1_TEXTURE_COORD_4: enabled = State::Enable::map1TextureCoord4; break; case GL_MAP1_VERTEX_3: enabled = State::Enable::map1Vertex3; break; case GL_MAP1_VERTEX_4: enabled = State::Enable::map1Vertex4; break; case GL_MAP2_COLOR_4: enabled = State::Enable::map2Color4; break; case GL_MAP2_INDEX: enabled = State::Enable::map2Index; break; case GL_MAP2_NORMAL: enabled = State::Enable::map2Normal; break; case GL_MAP2_TEXTURE_COORD_1: enabled = State::Enable::map2TextureCoord1; break; case GL_MAP2_TEXTURE_COORD_2: enabled = State::Enable::map2TextureCoord2; break; case GL_MAP2_TEXTURE_COORD_3: enabled = State::Enable::map2TextureCoord3; break; case GL_MAP2_TEXTURE_COORD_4: enabled = State::Enable::map2TextureCoord4; break; case GL_MAP2_VERTEX_3: enabled = State::Enable::map2Vertex3; break; case GL_MAP2_VERTEX_4: enabled = State::Enable::map2Vertex4; break; case GL_MINMAX: enabled = State::Enable::minmax; break; case GL_MULTISAMPLE: enabled = State::Enable::multisample; break; case GL_NORMALIZE: enabled = State::Enable::normalize; break; case GL_POINT_SMOOTH: enabled = State::Enable::pointSmooth; break; case GL_POINT_SPRITE: enabled = State::Enable::pointSprite; break; case GL_POLYGON_OFFSET_FILL: enabled = State::Enable::polygonOffsetFill; break; case GL_POLYGON_OFFSET_LINE: enabled = State::Enable::polygonOffsetLine; break; case GL_POLYGON_OFFSET_POINT: enabled = State::Enable::polygonOffsetPoint; break; case GL_POLYGON_SMOOTH: enabled = State::Enable::polygonSmooth; break; case GL_POLYGON_STIPPLE: enabled = State::Enable::polygonStipple; break; case GL_POST_COLOR_MATRIX_COLOR_TABLE: enabled = State::Enable::postColorMatrixColorTable; break; case GL_POST_CONVOLUTION_COLOR_TABLE: enabled = State::Enable::postConvolutionColorTable; break; case GL_PROGRAM_POINT_SIZE: enabled = State::Enable::programPointSize; break; case GL_RESCALE_NORMAL: enabled = State::Enable::rescaleNormal; break; case GL_SAMPLE_ALPHA_TO_COVERAGE: enabled = State::Enable::sampleAlphaToCoverage; break; case GL_SAMPLE_ALPHA_TO_ONE: enabled = State::Enable::sampleAlphaToOne; break; case GL_SAMPLE_COVERAGE: enabled = State::Enable::sampleCoverage; break; case GL_SAMPLE_SHADING: enabled = State::Enable::sampleShading; break; case GL_SCISSOR_TEST: enabled = State::Enable::scissorTest[0]; break; case GL_SEPARABLE_2D: enabled = State::Enable::separable2d; break; case GL_STENCIL_TEST: enabled = State::Enable::stencilTest; break; case GL_TEXTURE_1D: if (static_cast<size_t>(activeTextureUnit) < array_size(State::Enable::texture1d)) { RegalAssertArrayIndex( State::Enable::texture1d, activeTextureUnit ); enabled = State::Enable::texture1d[activeTextureUnit]; } break; case GL_TEXTURE_2D: if (static_cast<size_t>(activeTextureUnit) < array_size(State::Enable::texture2d)) { RegalAssertArrayIndex( State::Enable::texture2d, activeTextureUnit ); enabled = State::Enable::texture2d[activeTextureUnit]; } break; case GL_TEXTURE_3D: if (static_cast<size_t>(activeTextureUnit) < array_size(State::Enable::texture3d)) { RegalAssertArrayIndex( State::Enable::texture3d, activeTextureUnit ); enabled = State::Enable::texture3d[activeTextureUnit]; } break; case GL_TEXTURE_CUBE_MAP: if (static_cast<size_t>(activeTextureUnit) < array_size(State::Enable::textureCubeMap)) { RegalAssertArrayIndex( State::Enable::textureCubeMap, activeTextureUnit ); enabled = State::Enable::textureCubeMap[activeTextureUnit]; } break; case GL_TEXTURE_RECTANGLE: if (static_cast<size_t>(activeTextureUnit) < array_size(State::Enable::textureRectangle)) { RegalAssertArrayIndex( State::Enable::textureRectangle, activeTextureUnit ); enabled = State::Enable::textureRectangle[activeTextureUnit]; } break; case GL_TEXTURE_GEN_S: if (static_cast<size_t>(activeTextureUnit) < array_size(State::Enable::textureGenS)) { RegalAssertArrayIndex( State::Enable::textureGenS, activeTextureUnit ); enabled = State::Enable::textureGenS[activeTextureUnit]; } else enabled = GL_FALSE; break; case GL_TEXTURE_GEN_T: if (static_cast<size_t>(activeTextureUnit) < array_size(State::Enable::textureGenT)) { RegalAssertArrayIndex( State::Enable::textureGenT, activeTextureUnit ); enabled = State::Enable::textureGenT[activeTextureUnit]; } else enabled = GL_FALSE; break; case GL_TEXTURE_GEN_R: if (static_cast<size_t>(activeTextureUnit) < array_size(State::Enable::textureGenR)) { RegalAssertArrayIndex( State::Enable::textureGenR, activeTextureUnit ); enabled = State::Enable::textureGenR[activeTextureUnit]; } else enabled = GL_FALSE; break; case GL_TEXTURE_GEN_Q: if (static_cast<size_t>(activeTextureUnit) < array_size(State::Enable::textureGenQ)) { RegalAssertArrayIndex( State::Enable::textureGenQ, activeTextureUnit ); enabled = State::Enable::textureGenQ[activeTextureUnit]; } else enabled = GL_FALSE; break; case GL_VERTEX_PROGRAM_TWO_SIDE: enabled = State::Enable::vertexProgramTwoSide; break; default: return false; } return true; } bool glIsEnabledi(RegalContext *ctx, GLboolean &enabled, GLenum pname, GLuint index) { UNUSED_PARAMETER(ctx); switch (pname) { case GL_BLEND: if (index >= array_size( State::Enable::blend )) return false; RegalAssertArrayIndex( State::Enable::blend, index ); enabled = State::Enable::blend[index]; break; case GL_SCISSOR_TEST: if (index >= array_size( State::Enable::scissorTest )) return false; RegalAssertArrayIndex( State::Enable::scissorTest, index ); enabled = State::Enable::scissorTest[index]; break; default: return false; } return true; } bool SetEnable(RegalContext *ctx, GLenum cap, GLboolean enabled) { switch (cap) { case GL_ALPHA_TEST: State::Enable::alphaTest = State::ColorBuffer::alphaTest = enabled; break; case GL_BLEND: { size_t n = array_size( State::Enable::blend ); RegalAssert( array_size( State::ColorBuffer::blend ) == n ); for (size_t ii=0; ii<n; ii++) { RegalAssertArrayIndex( State::Enable::blend, ii ); RegalAssertArrayIndex( State::ColorBuffer::blend, ii ); State::Enable::blend[ii] = State::ColorBuffer::blend[ii] = enabled; } } break; case GL_AUTO_NORMAL: State::Enable::autoNormal = State::Eval::autoNormal = enabled; break; case GL_CLIP_DISTANCE0: case GL_CLIP_DISTANCE1: case GL_CLIP_DISTANCE2: case GL_CLIP_DISTANCE3: case GL_CLIP_DISTANCE4: case GL_CLIP_DISTANCE5: case GL_CLIP_DISTANCE6: case GL_CLIP_DISTANCE7: if ((cap-GL_CLIP_DISTANCE0 < array_size( State::Enable::clipDistance )) && (cap-GL_CLIP_DISTANCE0 < array_size( State::Transform::clipPlane ))) { RegalAssertArrayIndex( State::Enable::clipDistance, cap-GL_CLIP_DISTANCE0 ); RegalAssertArrayIndex( State::Transform::clipPlane, cap-GL_CLIP_DISTANCE0 ); State::Enable::clipDistance[cap-GL_CLIP_DISTANCE0] = State::Transform::clipPlane[cap-GL_CLIP_DISTANCE0].enabled = enabled; } break; case GL_COLOR_LOGIC_OP: State::Enable::colorLogicOp = State::ColorBuffer::colorLogicOp = enabled; break; case GL_COLOR_MATERIAL: State::Enable::colorMaterial = State::Lighting::colorMaterial = enabled; break; case GL_COLOR_SUM: State::Enable::colorSum = State::Fog::colorSum = enabled; break; case GL_COLOR_TABLE: State::Enable::colorTable = State::PixelMode::colorTable = enabled; break; case GL_CONVOLUTION_1D: State::Enable::convolution1d = State::PixelMode::convolution1d = enabled; break; case GL_CONVOLUTION_2D: State::Enable::convolution2d = State::PixelMode::convolution2d = enabled; break; case GL_CULL_FACE: State::Enable::cullFace = State::Polygon::cullEnable = enabled; break; case GL_DEPTH_CLAMP: State::Enable::depthClamp = State::Transform::depthClamp = enabled; break; case GL_DEPTH_TEST: State::Enable::depthTest = State::Depth::enable = enabled; break; case GL_DITHER: State::Enable::dither = State::ColorBuffer::dither = enabled; break; case GL_FOG: State::Enable::fog = State::Fog::enable = enabled; break; case GL_FRAMEBUFFER_SRGB: State::Enable::framebufferSRGB = State::ColorBuffer::framebufferSRGB = enabled; break; case GL_HISTOGRAM: State::Enable::histogram = State::PixelMode::histogram = enabled; break; case GL_INDEX_LOGIC_OP: State::Enable::indexLogicOp = State::ColorBuffer::indexLogicOp = enabled; break; case GL_LIGHT0: case GL_LIGHT1: case GL_LIGHT2: case GL_LIGHT3: case GL_LIGHT4: case GL_LIGHT5: case GL_LIGHT6: case GL_LIGHT7: if ((cap-GL_LIGHT0 < array_size( State::Enable::light )) && (cap-GL_LIGHT0 < array_size( State::Lighting::lights ))) { RegalAssertArrayIndex( State::Enable::light, cap-GL_LIGHT0 ); RegalAssertArrayIndex( State::Lighting::lights, cap-GL_LIGHT0 ); State::Enable::light[cap-GL_LIGHT0] = State::Lighting::lights[cap-GL_LIGHT0].enabled = enabled; } break; case GL_LIGHTING: State::Enable::lighting = State::Lighting::lighting = enabled; break; case GL_LINE_SMOOTH: State::Enable::lineSmooth = State::Line::smooth = enabled; break; case GL_LINE_STIPPLE: State::Enable::lineStipple = State::Line::stipple = enabled; break; case GL_MAP1_COLOR_4: if (cap-GL_MAP1_COLOR_4 < array_size( State::Eval::map1dEnables)) { RegalAssertArrayIndex( State::Eval::map1dEnables, cap-GL_MAP1_COLOR_4 ); State::Enable::map1Color4 = State::Eval::map1dEnables[cap-GL_MAP1_COLOR_4] = enabled; } break; case GL_MAP1_INDEX: if (cap-GL_MAP1_COLOR_4 < array_size( State::Eval::map1dEnables )) { RegalAssertArrayIndex( State::Eval::map1dEnables, cap-GL_MAP1_COLOR_4 ); State::Enable::map1Index = State::Eval::map1dEnables[cap-GL_MAP1_COLOR_4] = enabled; } break; case GL_MAP1_NORMAL: if (cap-GL_MAP1_COLOR_4 < array_size( State::Eval::map1dEnables )) { RegalAssertArrayIndex( State::Eval::map1dEnables, cap-GL_MAP1_COLOR_4 ); State::Enable::map1Normal = State::Eval::map1dEnables[cap-GL_MAP1_COLOR_4] = enabled; } break; case GL_MAP1_TEXTURE_COORD_1: if (cap-GL_MAP1_COLOR_4 < array_size( State::Eval::map1dEnables )) { RegalAssertArrayIndex( State::Eval::map1dEnables, cap-GL_MAP1_COLOR_4 ); State::Enable::map1TextureCoord1 = State::Eval::map1dEnables[cap-GL_MAP1_COLOR_4] = enabled; } break; case GL_MAP1_TEXTURE_COORD_2: if (cap-GL_MAP1_COLOR_4 < array_size( State::Eval::map1dEnables )) { RegalAssertArrayIndex( State::Eval::map1dEnables, cap-GL_MAP1_COLOR_4 ); State::Enable::map1TextureCoord2 = State::Eval::map1dEnables[cap-GL_MAP1_COLOR_4] = enabled; } break; case GL_MAP1_TEXTURE_COORD_3: if (cap-GL_MAP1_COLOR_4 < array_size( State::Eval::map1dEnables )) { RegalAssertArrayIndex( State::Eval::map1dEnables, cap-GL_MAP1_COLOR_4 ); State::Enable::map1TextureCoord3 = State::Eval::map1dEnables[cap-GL_MAP1_COLOR_4] = enabled; } break; case GL_MAP1_TEXTURE_COORD_4: if (cap-GL_MAP1_COLOR_4 < array_size( State::Eval::map1dEnables )) { RegalAssertArrayIndex( State::Eval::map1dEnables, cap-GL_MAP1_COLOR_4 ); State::Enable::map1TextureCoord4 = State::Eval::map1dEnables[cap-GL_MAP1_COLOR_4] = enabled; } break; case GL_MAP1_VERTEX_3: if (cap-GL_MAP1_COLOR_4 < array_size( State::Eval::map1dEnables )) { RegalAssertArrayIndex( State::Eval::map1dEnables, cap-GL_MAP1_COLOR_4 ); State::Enable::map1Vertex3 = State::Eval::map1dEnables[cap-GL_MAP1_COLOR_4] = enabled; } break; case GL_MAP1_VERTEX_4: if (cap-GL_MAP1_COLOR_4 < array_size( State::Eval::map1dEnables )) { RegalAssertArrayIndex( State::Eval::map1dEnables, cap-GL_MAP1_COLOR_4 ); State::Enable::map1Vertex4 = State::Eval::map1dEnables[cap-GL_MAP1_COLOR_4] = enabled; } break; case GL_MAP2_COLOR_4: if (cap-GL_MAP2_COLOR_4 < array_size( State::Eval::map2dEnables )) { RegalAssertArrayIndex( State::Eval::map2dEnables, cap-GL_MAP2_COLOR_4 ); State::Enable::map2Color4 = State::Eval::map2dEnables[cap-GL_MAP2_COLOR_4] = enabled; } break; case GL_MAP2_INDEX: if (cap-GL_MAP2_COLOR_4 < array_size( State::Eval::map2dEnables )) { RegalAssertArrayIndex( State::Eval::map2dEnables, cap-GL_MAP2_COLOR_4 ); State::Enable::map2Index = State::Eval::map2dEnables[cap-GL_MAP2_COLOR_4] = enabled; } break; case GL_MAP2_NORMAL: if (cap-GL_MAP2_COLOR_4 < array_size( State::Eval::map2dEnables )) { RegalAssertArrayIndex( State::Eval::map2dEnables, cap-GL_MAP2_COLOR_4 ); State::Enable::map2Normal = State::Eval::map2dEnables[cap-GL_MAP2_COLOR_4] = enabled; } break; case GL_MAP2_TEXTURE_COORD_1: if (cap-GL_MAP2_COLOR_4 < array_size( State::Eval::map2dEnables )) { RegalAssertArrayIndex( State::Eval::map2dEnables, cap-GL_MAP2_COLOR_4 ); State::Enable::map2TextureCoord1 = State::Eval::map2dEnables[cap-GL_MAP2_COLOR_4] = enabled; } break; case GL_MAP2_TEXTURE_COORD_2: if (cap-GL_MAP2_COLOR_4 < array_size( State::Eval::map2dEnables )) { RegalAssertArrayIndex( State::Eval::map2dEnables, cap-GL_MAP2_COLOR_4 ); State::Enable::map2TextureCoord2 = State::Eval::map2dEnables[cap-GL_MAP2_COLOR_4] = enabled; } break; case GL_MAP2_TEXTURE_COORD_3: if (cap-GL_MAP2_COLOR_4 < array_size( State::Eval::map2dEnables )) { RegalAssertArrayIndex( State::Eval::map2dEnables, cap-GL_MAP2_COLOR_4 ); State::Enable::map2TextureCoord3 = State::Eval::map2dEnables[cap-GL_MAP2_COLOR_4] = enabled; } break; case GL_MAP2_TEXTURE_COORD_4: if (cap-GL_MAP2_COLOR_4 < array_size( State::Eval::map2dEnables )) { RegalAssertArrayIndex( State::Eval::map2dEnables, cap-GL_MAP2_COLOR_4 ); State::Enable::map2TextureCoord4 = State::Eval::map2dEnables[cap-GL_MAP2_COLOR_4] = enabled; } break; case GL_MAP2_VERTEX_3: if (cap-GL_MAP2_COLOR_4 < array_size( State::Eval::map2dEnables )) { RegalAssertArrayIndex( State::Eval::map2dEnables, cap-GL_MAP2_COLOR_4 ); State::Enable::map2Vertex3 = State::Eval::map2dEnables[cap-GL_MAP2_COLOR_4] = enabled; } break; case GL_MAP2_VERTEX_4: if (cap-GL_MAP2_COLOR_4 < array_size( State::Eval::map2dEnables )) { RegalAssertArrayIndex( State::Eval::map2dEnables, cap-GL_MAP2_COLOR_4 ); State::Enable::map2Vertex4 = State::Eval::map2dEnables[cap-GL_MAP2_COLOR_4] = enabled; } break; case GL_MINMAX: State::Enable::minmax = State::PixelMode::minmax = enabled; break; case GL_MULTISAMPLE: State::Enable::multisample = State::Multisample::multisample = enabled; break; case GL_NORMALIZE: State::Enable::normalize = State::Transform::normalize = enabled; break; case GL_POINT_SMOOTH: State::Enable::pointSmooth = State::Point::smooth = enabled; break; case GL_POINT_SPRITE: State::Enable::pointSprite = State::Point::sprite = enabled; break; case GL_POLYGON_OFFSET_FILL: State::Enable::polygonOffsetFill = State::Polygon::offsetFill = enabled; break; case GL_POLYGON_OFFSET_LINE: State::Enable::polygonOffsetLine = State::Polygon::offsetLine = enabled; break; case GL_POLYGON_OFFSET_POINT: State::Enable::polygonOffsetPoint = State::Polygon::offsetPoint = enabled; break; case GL_POLYGON_SMOOTH: State::Enable::polygonSmooth = State::Polygon::smoothEnable = enabled; break; case GL_POLYGON_STIPPLE: State::Enable::polygonStipple = State::Polygon::stippleEnable = enabled; break; case GL_POST_COLOR_MATRIX_COLOR_TABLE: State::Enable::postColorMatrixColorTable = State::PixelMode::postColorMatrixColorTable = enabled; break; case GL_POST_CONVOLUTION_COLOR_TABLE: State::Enable::postConvolutionColorTable = State::PixelMode::postConvolutionColorTable = enabled; break; case GL_PROGRAM_POINT_SIZE: State::Enable::programPointSize = enabled; break; case GL_RESCALE_NORMAL: State::Enable::rescaleNormal = State::Transform::rescaleNormal = enabled; break; case GL_SAMPLE_ALPHA_TO_COVERAGE: State::Enable::sampleAlphaToCoverage = State::Multisample::sampleAlphaToCoverage = enabled; break; case GL_SAMPLE_ALPHA_TO_ONE: State::Enable::sampleAlphaToOne = State::Multisample::sampleAlphaToOne = enabled; break; case GL_SAMPLE_COVERAGE: State::Enable::sampleCoverage = State::Multisample::sampleCoverage = enabled; break; case GL_SAMPLE_SHADING: State::Enable::sampleShading = State::Multisample::sampleShading = enabled; break; case GL_SCISSOR_TEST: { size_t n = array_size( State::Enable::scissorTest ); RegalAssert( array_size( State::Scissor::scissorTest ) == n ); for (size_t ii=0; ii<n; ii++) { if ((ii < array_size( State::Enable::scissorTest )) && (ii < array_size( State::Scissor::scissorTest ))) { RegalAssertArrayIndex( State::Enable::scissorTest, ii ); RegalAssertArrayIndex( State::Scissor::scissorTest, ii ); State::Enable::scissorTest[ii] = State::Scissor::scissorTest[ii] = enabled; } } } break; case GL_SEPARABLE_2D: State::Enable::separable2d = State::PixelMode::separable2d = enabled; break; case GL_STENCIL_TEST: State::Enable::stencilTest = State::Stencil::enable = enabled; break; case GL_TEXTURE_1D: if (static_cast<size_t>(activeTextureUnit) < array_size(State::Enable::texture1d)) { RegalAssertArrayIndex( State::Enable::texture1d, activeTextureUnit ); State::Enable::texture1d[activeTextureUnit] = enabled; } break; case GL_TEXTURE_2D: if (static_cast<size_t>(activeTextureUnit) < array_size(State::Enable::texture2d)) { RegalAssertArrayIndex( State::Enable::texture2d, activeTextureUnit ); State::Enable::texture2d[activeTextureUnit] = enabled; } break; case GL_TEXTURE_3D: if (static_cast<size_t>(activeTextureUnit) < array_size(State::Enable::texture3d)) { RegalAssertArrayIndex( State::Enable::texture3d, activeTextureUnit ); State::Enable::texture3d[activeTextureUnit] = enabled; } break; case GL_TEXTURE_CUBE_MAP: if (static_cast<size_t>(activeTextureUnit) < array_size(State::Enable::textureCubeMap)) { RegalAssertArrayIndex( State::Enable::textureCubeMap, activeTextureUnit ); State::Enable::textureCubeMap[activeTextureUnit] = enabled; } break; case GL_TEXTURE_RECTANGLE: if (static_cast<size_t>(activeTextureUnit) < array_size(State::Enable::textureRectangle)) { RegalAssertArrayIndex( State::Enable::textureRectangle, activeTextureUnit ); State::Enable::textureRectangle[activeTextureUnit] = enabled; } break; case GL_TEXTURE_GEN_S: if (static_cast<size_t>(activeTextureUnit) < array_size(State::Enable::textureGenS)) { RegalAssertArrayIndex( State::Enable::textureGenS, activeTextureUnit ); State::Enable::textureGenS[activeTextureUnit] = enabled; } break; case GL_TEXTURE_GEN_T: if (static_cast<size_t>(activeTextureUnit) < array_size(State::Enable::textureGenT)) { RegalAssertArrayIndex( State::Enable::textureGenT, activeTextureUnit ); State::Enable::textureGenT[activeTextureUnit] = enabled; } break; case GL_TEXTURE_GEN_R: if (static_cast<size_t>(activeTextureUnit) < array_size(State::Enable::textureGenR)) { RegalAssertArrayIndex( State::Enable::textureGenR, activeTextureUnit ); State::Enable::textureGenR[activeTextureUnit] = enabled; } break; case GL_TEXTURE_GEN_Q: if (static_cast<size_t>(activeTextureUnit) < array_size(State::Enable::textureGenQ)) { RegalAssertArrayIndex( State::Enable::textureGenQ, activeTextureUnit ); State::Enable::textureGenQ[activeTextureUnit] = enabled; } break; case GL_VERTEX_PROGRAM_TWO_SIDE: State::Enable::vertexProgramTwoSide = enabled; break; default: break; } if (ctx->info->core || ctx->info->es1 || ctx->info->es2) { switch( cap ) { case GL_POINT_SMOOTH: case GL_LINE_STIPPLE: return true; default: break; } } return false; } bool SetEnablei(RegalContext *ctx, GLenum cap, GLuint index, GLboolean enabled) { UNUSED_PARAMETER(ctx); switch (cap) { case GL_BLEND: { size_t n = array_size( State::Enable::blend ); RegalAssert( array_size( State::ColorBuffer::blend ) == n ); if (index < n) { RegalAssertArrayIndex( State::Enable::blend, index ); RegalAssertArrayIndex( State::ColorBuffer::blend, index ); State::Enable::blend[index] = State::ColorBuffer::blend[index] = enabled; } } break; case GL_SCISSOR_TEST: { size_t n = array_size( State::Enable::scissorTest ); RegalAssert( array_size( State::Scissor::scissorTest ) == n ); if (index < n) { RegalAssertArrayIndex( State::Enable::scissorTest, index ); RegalAssertArrayIndex( State::Scissor::scissorTest, index ); State::Enable::scissorTest[index] = State::Scissor::scissorTest[index] = enabled; } } break; default: return false; } return true; } bool Enable(RegalContext *ctx, GLenum cap) { Internal("Regal::Ppa::Enable ",Token::toString(cap)); return SetEnable(ctx, cap, GL_TRUE); } bool Disable(RegalContext *ctx, GLenum cap) { Internal("Regal::Ppa::Disable ",Token::toString(cap)); return SetEnable(ctx, cap, GL_FALSE); } bool Enablei(RegalContext *ctx, GLenum cap, GLuint index) { Internal("Regal::Ppa::Enablei ",Token::toString(cap),index); return SetEnablei(ctx, cap, index, GL_TRUE); } bool Disablei(RegalContext *ctx, GLenum cap, GLuint index) { Internal("Regal::Ppa::Disablei ",Token::toString(cap),index); return SetEnablei(ctx, cap, index, GL_FALSE); } void glActiveTexture( GLenum texture ) { if (validTextureEnum(texture)) activeTextureUnit = texture - GL_TEXTURE0; } inline void glClampColor( GLenum target, GLenum clamp ) { switch (target) { case GL_CLAMP_FRAGMENT_COLOR: State::Enable::clampFragmentColor = State::ColorBuffer::clampFragmentColor = clamp; break; case GL_CLAMP_READ_COLOR: State::Enable::clampReadColor = State::ColorBuffer::clampReadColor = clamp; break; case GL_CLAMP_VERTEX_COLOR: State::Enable::clampVertexColor = State::Lighting::clampVertexColor = clamp; break; default: break; } } template <typename T> void glTexEnv(GLenum target, GLenum pname, T param) { if ((target == GL_POINT_SPRITE) && (pname == GL_COORD_REPLACE)) glMultiTexEnv(static_cast<GLenum>(GL_TEXTURE0+activeTextureUnit),target,pname,param); } template <typename T> void glTexEnvv(GLenum target, GLenum pname, const T *params) { if ((target == GL_POINT_SPRITE) && (pname == GL_COORD_REPLACE)) glMultiTexEnvv(static_cast<GLenum>(GL_TEXTURE0+activeTextureUnit),target,pname,params); } std::vector<GLbitfield> maskStack; std::vector<State::Depth> depthStack; std::vector<State::Stencil> stencilStack; std::vector<State::Polygon> polygonStack; std::vector<State::Transform> transformStack; std::vector<State::Hint> hintStack; std::vector<State::Enable> enableStack; std::vector<State::List> listStack; std::vector<State::AccumBuffer> accumBufferStack; std::vector<State::Scissor> scissorStack; std::vector<State::Viewport> viewportStack; std::vector<State::Line> lineStack; std::vector<State::Multisample> multisampleStack; std::vector<State::Eval> evalStack; std::vector<State::Fog> fogStack; std::vector<State::Point> pointStack; std::vector<State::PolygonStipple> polygonStippleStack; std::vector<State::ColorBuffer> colorBufferStack; std::vector<State::PixelMode> pixelModeStack; std::vector<State::Lighting> lightingStack; GLuint activeTextureUnit; }; } REGAL_NAMESPACE_END #endif // REGAL_EMULATION #endif // ! __REGAL_PPA_H__
0dfc66ad9a624104d162a95fd0d1159cd73109c5
b01195f7a4d6559c7483419cbf479aab290f4154
/Chapter_08_Inheritance_Code.cpp
939dbf3ed337ed5466d32f2f80e2cfbd68cba28c
[]
no_license
huanfeiwang/PIC10B-Projects
7d9461305082867b727cfcb521b4cda333ea36d3
328ca464c25c19b2e3d8af031ccffa7e92ed228b
refs/heads/master
2022-02-27T19:03:54.556430
2019-10-29T08:10:27
2019-10-29T08:10:27
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,948
cpp
Chapter_08_Inheritance_Code.cpp
#include <vector> #include <iostream> #include <cstring> #include <string> #include <iomanip> using namespace std; class Point2D { public: Point2D() {} Point2D(double a, double b) { x = a; y = b; } void setx(double a) { x = a; } void sety(double b) { x = b; } double getx() const { return x; } double gety() const { return y; } virtual void print() const { std::cout << "(" << getx() << "," << gety() << ")"; } private: double x; double y; }; class Point3D : public Point2D { public: Point3D() {} Point3D(double a, double b, double c) :Point2D(a, b), z(c) {} double getz() const { return z; } virtual void print() const { std::cout << "(" << getx() << "," << gety() << "," << getz() << ")"; } private: double z; }; class ColorPoint2D : public Point2D { public: ColorPoint2D() {} ColorPoint2D(double a, double b, string input_color):Point2D(a, b), color(input_color) {} virtual void print() const { cout << color << ", "; std::cout << "(" << getx() << "," << gety() << ")"; } private: string color; }; // Abstract container class class BaseIntContainer { public: typedef unsigned int size_type; // alias for the size type BaseIntContainer() : num(0), p(NULL) { tmp = new int[10]; } // tmp is some temporary storage of size 10 size_type get_size() const { return num; } int* get_p() const { return p; } // abstract methods that do not require implementation virtual void print() const = 0; virtual void memalloc() = 0; // When an object is destroyed then the destructor // of the base class is executed first, then that of derived one. // Thus: To employ polymorphism one has to have the destructor in the base class to be virtual. // do not forget to delete memory virtual ~BaseIntContainer() { delete tmp; cout << "Base Destructor: The destructor of the base class is executed!\n"; } protected: int* p; size_type num; int* tmp; // some temporary storage of size 10 }; // class IntContainer : public BaseIntContainer { public: IntContainer() : BaseIntContainer() {}; IntContainer(size_type n) { num = n; memalloc(); }; virtual void print() const { for (size_type i = 0; i < get_size(); i++) cout << get_p()[i]; } virtual void memalloc() { if (p == NULL) p = new int[get_size()]; } // do not forget to delete memory // but only the memory allocated in the derived class! do not delete tmp here! ~IntContainer() { delete p; cout << "Derived Destructor: Memory is reclaimed!\n"; /* Do not delete tmp; ERROR!*/ } private: }; //BaseIntContainer(size_type n) { num = n; if (num != 0) p = new double[num]; }; int main() { // Example 1: Polymorphism in action: vector<Point2D*> p(3); p[0] = new Point2D(1, 2); p[1] = new ColorPoint2D(1, 2, "blue"); p[2] = new Point3D(1, 2, 3); // using polymorphic features for (int i = 0; i < 3; i++) { p[i]->print(); cout << endl; } // using polymorphic features for (int i = 0; i < 3; i++) { delete p[i]; } // Example 2: // BaseIntContainer* bc = new BaseIntContainer; //This will be an error! BaseIntContainer* p1; IntContainer* p2; p1 = new IntContainer(5); // allowed due to polymorphism p2 = new IntContainer(5); // When an object is destroyed then the destructor // of the base class is executed first, then that of derived one. // Thus: To employ polymorphism one has to have the destructor in the base class to be virtual // Look at the comments for the destructor delete p1; delete p2; // Observe that p1 will reclaim the memory return 0; }
bcb4d90f28650713ac9bf42cd99cd189c120c3a8
eef2c88186610a5ff4b56fac5c3c53773a0bcce1
/prova2/c.cpp
50586a400c9cb4e2c293145aad013c8c9f46eacd
[]
no_license
heronsousa/PPC
c9933b877989430f9c6735027e0ce1362030dea5
5e2c11c2b2a148778c57a7eac7818c2ccb91c477
refs/heads/master
2020-07-03T13:51:26.373175
2019-08-12T12:25:12
2019-08-12T12:25:12
201,925,116
0
0
null
null
null
null
UTF-8
C++
false
false
550
cpp
c.cpp
#include <bits/stdc++.h> using namespace std; using ll = long long; int main(){ ll m, n, v; vector<ll> val; val.push_back(0); cin >> m >> n; ll sum=0; while(n--){ cin >> v; val.push_back(v); } ll ans = 0; for(ll i=0; i<val.size(); i++){ if(val[i] > 0) ans+=val[i]; else if(val[i]<0 && val[i]+ans<0){ sum+=val[i]+ans; ans=0; if(sum*-1>m) break; } else if(val[i]<0 && val[i]+ans>=0) ans+=val[i]; } if(sum*-1<=m) cout << sum*-1 << endl; else cout << "-1" << endl; return 0; }
3900a32a31f1094ac50ed2b236bf836a295513ae
675e55b07deb42ad99dddbe8746899e051127701
/26_Rm_Duplicates_from_Sorted_Array/26.cpp
d89b4d0c11de013a17d5029ccf97a85d70a805e7
[]
no_license
wyc25013/leetcode
3bbef070b72a16666a1cdf0d4710d3558c30f4be
5358f3c2cc7a5999d134b77bc87c8764dad2ddc2
refs/heads/master
2021-01-18T15:17:05.658334
2015-10-14T02:14:39
2015-10-14T02:14:39
37,750,911
0
0
null
null
null
null
UTF-8
C++
false
false
583
cpp
26.cpp
#include <iostream> using namespace std; class Solution { public: int removeDuplicates(int A[], int n) { if(!n) return 0; int *head = A; int *tail = A; int count = 1; int i = 0; while (i < n - 1) { tail++; if(*tail == *head) { head++; } else { head++; A[count] = *tail; count++; } i++; } return count; } }; int main(){ Solution soln; int a[] = {1,1,2}; cout << soln.removeDuplicates(a,3) <<endl; return 0; }
6e994da8c7c62cf4043fd347e5e60ba984cfb63f
c35f3fdc158d100e328b901827f07fc485e31c0a
/src/host/ut_host/CommandNumberPopupTests.cpp
8c4460ec8a0e0bfc0278f01f8c707f553b99b470
[ "MIT", "LicenseRef-scancode-object-form-exception-to-mit", "BSD-3-Clause", "BSD-2-Clause", "Unlicense", "LGPL-2.1-or-later" ]
permissive
cinnamon-msft/terminal
dee3e60459994f39fa035e2f17b7b7478eacee6b
4deee64b0fce46827ce2fdda5c91917297e1c9d2
refs/heads/main
2023-05-12T15:24:51.369560
2023-04-17T15:53:18
2023-04-17T15:53:18
282,002,283
16
0
MIT
2023-04-17T18:55:48
2020-07-23T16:27:47
C++
UTF-8
C++
false
false
11,972
cpp
CommandNumberPopupTests.cpp
// Copyright (c) Microsoft Corporation. // Licensed under the MIT license. #include "precomp.h" #include "WexTestClass.h" #include "../../inc/consoletaeftemplates.hpp" #include "CommonState.hpp" #include "PopupTestHelper.hpp" #include "../../interactivity/inc/ServiceLocator.hpp" #include "../CommandNumberPopup.hpp" #include "../CommandListPopup.hpp" using namespace WEX::Common; using namespace WEX::Logging; using namespace WEX::TestExecution; using Microsoft::Console::Interactivity::ServiceLocator; static constexpr size_t BUFFER_SIZE = 256; class CommandNumberPopupTests { TEST_CLASS(CommandNumberPopupTests); std::unique_ptr<CommonState> m_state; CommandHistory* m_pHistory; TEST_CLASS_SETUP(ClassSetup) { m_state = std::make_unique<CommonState>(); m_state->PrepareGlobalFont(); return true; } TEST_CLASS_CLEANUP(ClassCleanup) { m_state->CleanupGlobalFont(); return true; } TEST_METHOD_SETUP(MethodSetup) { m_state->PrepareGlobalInputBuffer(); m_state->PrepareGlobalScreenBuffer(); m_state->PrepareReadHandle(); m_pHistory = CommandHistory::s_Allocate(L"cmd.exe", nullptr); if (!m_pHistory) { return false; } // History must be prepared before COOKED_READ (as it uses s_Find to get at it) m_state->PrepareCookedReadData(); return true; } TEST_METHOD_CLEANUP(MethodCleanup) { CommandHistory::s_Free(nullptr); m_pHistory = nullptr; m_state->CleanupCookedReadData(); m_state->CleanupReadHandle(); m_state->CleanupGlobalInputBuffer(); m_state->CleanupGlobalScreenBuffer(); return true; } TEST_METHOD(CanDismiss) { // function to simulate user pressing escape key Popup::UserInputFunction fn = [](COOKED_READ_DATA& /*cookedReadData*/, bool& popupKey, DWORD& modifiers, wchar_t& wch) { popupKey = true; wch = VK_ESCAPE; modifiers = 0; return STATUS_SUCCESS; }; auto& gci = ServiceLocator::LocateGlobals().getConsoleInformation(); // prepare popup CommandNumberPopup popup{ gci.GetActiveOutputBuffer() }; popup.SetUserInputFunction(fn); // prepare cookedReadData const std::wstring testString = L"hello world"; wchar_t buffer[BUFFER_SIZE]; std::fill(std::begin(buffer), std::end(buffer), UNICODE_SPACE); std::copy(testString.begin(), testString.end(), std::begin(buffer)); auto& cookedReadData = gci.CookedReadData(); PopupTestHelper::InitReadData(cookedReadData, buffer, ARRAYSIZE(buffer), testString.size()); PopupTestHelper::InitHistory(*m_pHistory); cookedReadData._commandHistory = m_pHistory; VERIFY_ARE_EQUAL(popup.Process(cookedReadData), static_cast<NTSTATUS>(CONSOLE_STATUS_WAIT_NO_BLOCK)); // the buffer should not be changed const std::wstring resultString(buffer, buffer + testString.size()); VERIFY_ARE_EQUAL(testString, resultString); VERIFY_ARE_EQUAL(cookedReadData._bytesRead, testString.size() * sizeof(wchar_t)); // popup has been dismissed VERIFY_IS_FALSE(CommandLine::Instance().HasPopup()); } TEST_METHOD(CanDismissAllPopups) { Log::Comment(L"that that all popups are dismissed when CommandNumberPopup is dismissed"); // CommandNumberPopup is the only popup that can act as a 2nd popup. make sure that it dismisses all // popups when exiting // function to simulate user pressing escape key Popup::UserInputFunction fn = [](COOKED_READ_DATA& /*cookedReadData*/, bool& popupKey, DWORD& modifiers, wchar_t& wch) { popupKey = true; wch = VK_ESCAPE; modifiers = 0; return STATUS_SUCCESS; }; auto& gci = ServiceLocator::LocateGlobals().getConsoleInformation(); // add popups to CommandLine auto& commandLine = CommandLine::Instance(); commandLine._popups.emplace_front(std::make_unique<CommandListPopup>(gci.GetActiveOutputBuffer(), *m_pHistory)); commandLine._popups.emplace_front(std::make_unique<CommandNumberPopup>(gci.GetActiveOutputBuffer())); auto& numberPopup = *commandLine._popups.front(); numberPopup.SetUserInputFunction(fn); VERIFY_ARE_EQUAL(commandLine._popups.size(), 2u); // prepare cookedReadData const std::wstring testString = L"hello world"; wchar_t buffer[BUFFER_SIZE]; std::fill(std::begin(buffer), std::end(buffer), UNICODE_SPACE); std::copy(testString.begin(), testString.end(), std::begin(buffer)); auto& cookedReadData = gci.CookedReadData(); PopupTestHelper::InitReadData(cookedReadData, buffer, ARRAYSIZE(buffer), testString.size()); PopupTestHelper::InitHistory(*m_pHistory); cookedReadData._commandHistory = m_pHistory; VERIFY_ARE_EQUAL(numberPopup.Process(cookedReadData), static_cast<NTSTATUS>(CONSOLE_STATUS_WAIT_NO_BLOCK)); VERIFY_IS_FALSE(commandLine.HasPopup()); } TEST_METHOD(EmptyInputCountsAsOldestHistory) { Log::Comment(L"hitting enter with no input should grab the oldest history item"); Popup::UserInputFunction fn = [](COOKED_READ_DATA& /*cookedReadData*/, bool& popupKey, DWORD& modifiers, wchar_t& wch) { popupKey = false; wch = UNICODE_CARRIAGERETURN; modifiers = 0; return STATUS_SUCCESS; }; auto& gci = ServiceLocator::LocateGlobals().getConsoleInformation(); // prepare popup CommandNumberPopup popup{ gci.GetActiveOutputBuffer() }; popup.SetUserInputFunction(fn); // prepare cookedReadData wchar_t buffer[BUFFER_SIZE]; std::fill(std::begin(buffer), std::end(buffer), UNICODE_SPACE); auto& cookedReadData = gci.CookedReadData(); PopupTestHelper::InitReadData(cookedReadData, buffer, ARRAYSIZE(buffer), 0); PopupTestHelper::InitHistory(*m_pHistory); cookedReadData._commandHistory = m_pHistory; VERIFY_ARE_EQUAL(popup.Process(cookedReadData), static_cast<NTSTATUS>(CONSOLE_STATUS_WAIT_NO_BLOCK)); // the buffer should contain the least recent history item const auto expected = m_pHistory->GetLastCommand(); const std::wstring resultString(buffer, buffer + expected.size()); VERIFY_ARE_EQUAL(expected, resultString); } TEST_METHOD(CanSelectHistoryItem) { PopupTestHelper::InitHistory(*m_pHistory); for (unsigned int historyIndex = 0; historyIndex < m_pHistory->GetNumberOfCommands(); ++historyIndex) { Popup::UserInputFunction fn = [historyIndex](COOKED_READ_DATA& /*cookedReadData*/, bool& popupKey, DWORD& modifiers, wchar_t& wch) { static auto needReturn = false; popupKey = false; modifiers = 0; if (!needReturn) { const auto str = std::to_string(historyIndex); wch = str.at(0); needReturn = true; } else { wch = UNICODE_CARRIAGERETURN; needReturn = false; } return STATUS_SUCCESS; }; auto& gci = ServiceLocator::LocateGlobals().getConsoleInformation(); // prepare popup CommandNumberPopup popup{ gci.GetActiveOutputBuffer() }; popup.SetUserInputFunction(fn); // prepare cookedReadData wchar_t buffer[BUFFER_SIZE]; std::fill(std::begin(buffer), std::end(buffer), UNICODE_SPACE); auto& cookedReadData = gci.CookedReadData(); PopupTestHelper::InitReadData(cookedReadData, buffer, ARRAYSIZE(buffer), 0); cookedReadData._commandHistory = m_pHistory; VERIFY_ARE_EQUAL(popup.Process(cookedReadData), static_cast<NTSTATUS>(CONSOLE_STATUS_WAIT_NO_BLOCK)); // the buffer should contain the correct nth history item const auto expected = m_pHistory->GetNth(gsl::narrow<short>(historyIndex)); const std::wstring resultString(buffer, buffer + expected.size()); VERIFY_ARE_EQUAL(expected, resultString); } } TEST_METHOD(LargeNumberGrabsNewestHistoryItem) { Log::Comment(L"entering a number larger than the number of history items should grab the most recent history item"); // simulates user pressing 1, 2, 3, 4, 5, enter Popup::UserInputFunction fn = [](COOKED_READ_DATA& /*cookedReadData*/, bool& popupKey, DWORD& modifiers, wchar_t& wch) { static auto num = 1; popupKey = false; modifiers = 0; if (num <= 5) { const auto str = std::to_string(num); wch = str.at(0); ++num; } else { wch = UNICODE_CARRIAGERETURN; } return STATUS_SUCCESS; }; auto& gci = ServiceLocator::LocateGlobals().getConsoleInformation(); // prepare popup CommandNumberPopup popup{ gci.GetActiveOutputBuffer() }; popup.SetUserInputFunction(fn); // prepare cookedReadData wchar_t buffer[BUFFER_SIZE]; std::fill(std::begin(buffer), std::end(buffer), UNICODE_SPACE); auto& cookedReadData = gci.CookedReadData(); PopupTestHelper::InitReadData(cookedReadData, buffer, ARRAYSIZE(buffer), 0); PopupTestHelper::InitHistory(*m_pHistory); cookedReadData._commandHistory = m_pHistory; VERIFY_ARE_EQUAL(popup.Process(cookedReadData), static_cast<NTSTATUS>(CONSOLE_STATUS_WAIT_NO_BLOCK)); // the buffer should contain the most recent history item const auto expected = m_pHistory->GetLastCommand(); const std::wstring resultString(buffer, buffer + expected.size()); VERIFY_ARE_EQUAL(expected, resultString); } TEST_METHOD(InputIsLimited) { auto& gci = ServiceLocator::LocateGlobals().getConsoleInformation(); CommandNumberPopup popup{ gci.GetActiveOutputBuffer() }; // input can't delete past zero number input popup._pop(); VERIFY_ARE_EQUAL(popup._parse(), 0); // input can only be numbers VERIFY_THROWS_SPECIFIC(popup._push(L'$'), wil::ResultException, [](wil::ResultException& e) { return e.GetErrorCode() == E_INVALIDARG; }); VERIFY_THROWS_SPECIFIC(popup._push(L'A'), wil::ResultException, [](wil::ResultException& e) { return e.GetErrorCode() == E_INVALIDARG; }); // input can't be more than 5 numbers popup._push(L'1'); VERIFY_ARE_EQUAL(popup._parse(), 1); popup._push(L'2'); VERIFY_ARE_EQUAL(popup._parse(), 12); popup._push(L'3'); VERIFY_ARE_EQUAL(popup._parse(), 123); popup._push(L'4'); VERIFY_ARE_EQUAL(popup._parse(), 1234); popup._push(L'5'); VERIFY_ARE_EQUAL(popup._parse(), 12345); // this shouldn't affect the parsed number popup._push(L'6'); VERIFY_ARE_EQUAL(popup._parse(), 12345); // make sure we can delete input correctly popup._pop(); VERIFY_ARE_EQUAL(popup._parse(), 1234); } };
b8ab4778259207e90f4c0fc7b323321ce7052738
58a0ba5ee99ec7a0bba36748ba96a557eb798023
/CodeForces/Complete/400-499/426B-SerejaAndMirroring.cpp
5666697c652b9056565727c9e4c8732aa050031b
[ "MIT" ]
permissive
adityanjr/code-DS-ALGO
5bdd503fb5f70d459c8e9b8e58690f9da159dd53
1c104c33d2f56fe671d586b702528a559925f875
refs/heads/master
2022-10-22T21:22:09.640237
2022-10-18T15:38:46
2022-10-18T15:38:46
217,567,198
40
54
MIT
2022-10-18T15:38:47
2019-10-25T15:50:28
C++
UTF-8
C++
false
false
495
cpp
426B-SerejaAndMirroring.cpp
#include <cstdio> #include <iostream> #include <vector> int main(){ int n(0), m(0); scanf("%d %d\n", &n, &m); int output = n; std::vector<std::string> rows(n, " "); for(int k = 0; k < n; k++){getline(std::cin, rows[k]);} bool stop = 0; while(output % 2 == 0){ for(int k = 0; k < output / 2; k++){if(rows[k] != rows[output - 1 - k]){stop = 1; break;}} if(!stop){output /= 2;} else{break;} } std::cout << output << std::endl; return 0; }
4a5e267ae8e5de15db82dd4e73cc4a46b4c60ae1
e5503be4f2e97e90fb5a078711b5d79b17dc5c6c
/map/seychia_room_db.cpp
37e086994fa3a3300803f67c9dca383c0407b068
[]
no_license
Michal-Atlas/TextAdventure-Experiments
aa0f7c8eb92d4d49f3ccb776e7374164a0b16f15
8edbc60a3f084385f886bf6448ed3db9741c5056
refs/heads/master
2022-12-03T04:33:29.569615
2020-08-10T12:07:58
2020-08-10T12:07:58
null
0
0
null
null
null
null
UTF-8
C++
false
false
340
cpp
seychia_room_db.cpp
#include <map> #include "map.h" namespace DawnStorm { std::map<std::string, Room> Room::DB = { {"dungeon_0", Room{ "The Lone Wild", { { "rock" } } }} }; }
78aef4593c44510d39a91edbc75156fdc7b70e6b
613de79e1134485ce750cfbcdd2d2293831ca7f8
/CP_Platform_Bucket/CodeChef/chefcake.cpp
74ccba78ddc548a9041320a08ca2ee4875ff9093
[]
no_license
arkch99/CodeBucket
a668ad69bd759a2545ec402652c0c3fadfa6e489
2a4959114e3d9a501211afeb2341dc729f4042c2
refs/heads/master
2023-01-08T11:23:56.765635
2020-10-30T07:03:55
2020-10-30T07:03:55
303,733,044
0
0
null
null
null
null
UTF-8
C++
false
false
365
cpp
chefcake.cpp
#include<bits/stdc++.h> using namespace std; int fact(int n) { if(n==0||n==1) return 1; else return n*fact(n-1); } int main() { int t; cin>>t; while(t--) { int n; cin>>n; long long int i,j,a[n],sum=0; for(i=0;i<n;i++) cin>>a[i]; for(i=0;i<n;i++) for(j=1;j<pow(10,n);j*=10) sum+=j*a[i]*(fact(n)/n); cout<<sum<<endl; } return 0; }
a41d74dc8520f2f04b82a272511a496f6ce80a5f
753777cd3722ad731f848908e94adc7630c8cf4f
/CSE 461 - Advance Operating Systems/Lab7/Table.cpp
f356da13ba1b4ed9bc99da80e64e1b10a62c0aa1
[]
no_license
MikeSmith14/School-Work
cf6bac0b791689f302844ecc1c16ecea55f8e7aa
eb31894356463bd65e73a17a2d3a1fd7d1a6da45
refs/heads/master
2020-04-15T08:21:58.108962
2019-01-08T01:24:30
2019-01-08T01:24:30
164,520,007
1
0
null
null
null
null
UTF-8
C++
false
false
1,472
cpp
Table.cpp
#include <fstream> #include <sstream> #include <iostream> #include <string> #include <iomanip> #include "Filesys.h" #include "Table.h" using namespace std; Table::Table(string diskname, int blocksize, int numberofblocks, string flatfile, string indexfile) :Filesys(diskname, numberofblocks, blocksize), flatfile(flatfile), indexfile(indexfile) { newfile(flatfile); newfile(indexfile); } int Table::Build_Table(string input_file) { string rec, key; ostringstream ostream; int blockid; ifstream infile; getline(infile, rec); while (infile.good()) { key = rec.substr(0, 3); vector<string> blocks = block(rec, getblocksize()); blockid = addblock(flatfile, blocks[0]); ostream << key << " " << blockid << " "; getline(infile, rec); } string buffer1 = ostream.str(); vector<string> blocks = block(buffer1, getblocksize()); for (int i = 0; i < getblocksize(); i++) { addblock(indexfile, blocks[i]); } return 1; } int Table::Search(string value) { return IndexSearch(value); } int Table::IndexSearch(string value) { int fblock = getfirstblock(indexfile); if (fblock == -1) return 0; int block_num, index; string buffer1, buffer2; while (fblock > 0) { readblock(indexfile, fblock, buffer1); buffer2 += buffer1; fblock = nextblock(indexfile, fblock); } istringstream temp(buffer2); while (temp.good()) { temp >> index >> block_num; if (stoi(value) == index) return block_num; } return 0; //if nothing is found, error check }
bcd7ee742198a02bedcb5cead72a6f4774c01bb1
a9e4c398451c8b0d1711d3dffb3fc19ab4a6eb8c
/C++/include/ParameterData.h
bb7f80f2593d91f300cb0b5bf319b100b3daac19
[ "LicenseRef-scancode-us-govt-public-domain" ]
permissive
supriyantomaftuh/icarous
df0ef8c5571672f65e3baadb3b6ec1d50d919876
b0d2262a89f5783bcad5664991d80b73be316b64
refs/heads/master
2017-12-07T15:16:49.563140
2017-03-10T04:37:26
2017-03-10T04:37:26
69,625,426
0
1
null
null
null
null
UTF-8
C++
false
false
10,297
h
ParameterData.h
/* * Copyright (c) 2014-2016 United States Government as represented by * the National Aeronautics and Space Administration. No copyright * is claimed in the United States under Title 17, U.S.Code. All Other * Rights Reserved. */ #ifndef PARAMETERDATA_H_ #define PARAMETERDATA_H_ #include "Units.h" #include "ErrorLog.h" #include "ErrorReporter.h" #include "format.h" #include "Quad.h" #include "string_util.h" #include <string> #include <iostream> #include <fstream> #include <sstream> #include <vector> #include <map> #include <stdexcept> #include <algorithm> namespace larcfm { struct stringCaseInsensitive { bool operator() (const std::string& lhs, const std::string& rhs) const {return toLowerCase(lhs)<toLowerCase(rhs);} }; /** * This class stores a database of parameters. In addition, it performs various * operations parameter strings, including parsing some more complicated * parameter strings into various data structures. */ class ParameterData { public: static const std::string parenPattern; static const std::string defaultEntrySeparator; ParameterData(); bool isCaseSensitive(); void setCaseSensitive(bool v); bool isPreserveUnits(); void setPreserveUnits(bool v); bool isUnitCompatibility(); void setUnitCompatibility(bool v); int size(); /** * Returns an array of parameter strings encountered. */ std::vector<std::string> getList() const; /** * Returns an array of parameter strings encountered. */ std::vector<std::string> getListFull() const; /** * Removes all stored parameters. */ void clear(); /** * Returns true if the parameter key was defined. */ bool contains(const std::string& key) const; std::vector<std::string> matchList(const std::string& key) const; ParameterData copyWithPrefix(const std::string& prefix) const; ParameterData extractPrefix(const std::string& prefix) const; /** * Returns the string value of the given parameter key. This may be a * space-delimited list. If the key is not present, return the empty string. * Parameter keys may be case-sensitive. */ std::string getString(const std::string& key) const; /** * Returns the double-precision value of the given parameter key in internal * units. If the key is not present or if the value is not a numeral, then * return 0. Parameter keys may be case-sensitive. * * * * * * * Returns the double-precision value of the given parameter key. If units * were specified in the file, this value has been converted into internal * units. If no units were specified, then the value in the file is * returned. If the key is not present or if the value is not a numeral, * then return 0. Parameter keys may be case-sensitive. */ double getValue(const std::string& key) const; /** * Returns the double-precision value of the given parameter key in internal * units. Only in the case when units were not specified in the file, will * the defaultUnit parameter be used. If the key is not present or if the * value is not a numeral, then return 0. Parameter keys may be * case-sensitive. * * * * Returns the double-precision value of the given parameter key in internal * units. If no units were specified in the file, then the defaultUnit * parameter is used. If units were specified in the file, then the * defaultUnit parameter is ignored. If the key is not present or if the * value is not a numeral, then return 0. Parameter keys may be * case-sensitive. */ double getValue(const std::string& key, const std::string& defaultUnit) const; /** * Returns the string representation of the specified unit of the given * parameter key. If the key is not present or no unit was specified, return * "unspecified". Parameter keys may be case-sensitive. */ std::string getUnit(const std::string& key) const; /** * Returns the Boolean value of the given parameter key. If the key is not * present, or not representation of "true", return the empty string. * Parameter keys may be case-sensitive. */ bool getBool(const std::string& key) const; /** * Returns the integer value of the given parameter key in internal units. * If no units were specified in the file, then the defaultUnit parameter is used. * If the key is not present or if the * value is not a numeral, then return 0. This value is an integer version of the * double value (see the related getParameterValue() method). If the double value is * larger than an integer, behavior is undefined. * Parameter keys may be case-sensitive. */ int getInt(const std::string& key) const; /** * Returns the long value of the given parameter key in internal units. * If no units were specified in the file, then the defaultUnit parameter is used. * If the key is not present or if the * value is not a numeral, then return 0. This value is an integer version of the * double value (see the related getParameterValue() method). If the double value is * larger than an long, behavior is undefined. * Parameter keys may be case-sensitive. */ long getLong(const std::string& key) const; /** * Parses the given string as a parameter assignment. If successful, returns * a true value and adds the parameter. Otherwise returns a false value and * makes no change to the parameter database.<p> * * Examples of valid strings include: * <ul> * <li> a = true * <li> b = hello everyone! * <li> c = 10 [NM] * </ul> */ bool set(const std::string& s); /** * Associates a parameter key with a value (both represented as strings). * The value field may include a units descriptor in addition to the actual * value, usually in a format similar to "10 [NM]", representing 10 nautical * miles. */ bool set(const std::string& key, const std::string& value); bool set(const std::string& key, char* value); bool set(const std::string& key, const char* value); /** Associates a bool value with a parameter key. */ bool setTrue(const std::string& key); bool setFalse(const std::string& key); bool setBool(const std::string& key, bool val); // WARNING: DO NOT add this method to C++, bool's in C++ are integers and will // capture some calls to .set with integer (and some pointer) parameters. For // the case with integer parameters, the desired behavior is to go to the set(string,double,string) version. //void set(const std::string& key, bool value); /** Associates a value (in the given units) with a parameter key. */ bool set(const std::string& key, double value, const std::string& unit); /** Associates a value (in internal units) with a parameter key. The default units of * this value are provided by the units string. */ bool setInternal(const std::string& key, double value, const std::string& units); bool setInternal(const std::string& key, double value, const std::string& units, int prec); /** Associates a value (in the given units) with a parameter key. * If the parameter was already defined with a specified unit than * the original unit is retained as the default unit for this parameter. If not, then the * unit provided through this method becomes the default unit for * this parameter. * * @param key * @param value * @param units */ void setPreserveUnit(const std::string& key, double value, const std::string& units); /** Associates a value (in internal units) with a parameter key. * If the parameter was already defined with a specified unit than * the original unit is retained as the default unit for this parameter. If not, then the * unit provided through this method becomes the default unit for * this parameter. * * @param key * @param value * @param units */ void setInternalPreserveUnit(const std::string& key, double value, const std::string& units); // bool setValueOnly(const std::string& key, double value); // bool setDefaultUnit(const std::string& key, const std::string& unit); /** * Checks the parameters against the supplied list, and returns a list of * unrecognized parameters that have been read, possible empty */ std::vector<std::string> unrecognizedParameters(std::vector<std::string> c) const; /** * Checks the parameters against the supplied list, and returns a list * of unrecognized parameters. */ std::vector<std::string> validateParameters(std::vector<std::string> c); void copy(ParameterData p, bool overwrite); /** * Remove this key from the database, if it exsts. */ void remove(const std::string& key); /** * Remove all keys in the list from this database, if they exist. */ void removeAll(const std::vector<std::string>& key); std::string toParameterList(const std::string& separator) const; bool parseParameterList(const std::string& separator, std::string line); std::string toString() const; bool equals(const ParameterData& pd) const; std::vector<int> getListInteger(const std::string& key) const; std::vector<double> getListDouble(const std::string& key) const; std::vector<std::string> getListString(const std::string& key) const; std::vector<bool> getListBool(const std::string& key) const; bool set(const std::string& key, const std::vector<int>& list); bool set(const std::string& key, const std::vector<double>& list); bool set(const std::string& key, const std::vector<std::string>& list); bool setListBool(const std::string& key, const std::vector<bool>& list); private: bool parse_parameter_string(const std::string& str); bool putParam(const std::string& key, const std::pair<bool, Quad<std::string, double, std::string, bool> >& entry); std::pair<bool, Quad<std::string, double, std::string, bool> > parse_parameter_value(const std::string& value); static std::vector<std::string> stringList(const std::string& instring); static std::vector<int> intList(const std::string& instring); static std::vector<double> doubleList(const std::string& instring); static std::vector<bool> boolList(const std::string& instring); bool caseSensitive; bool preserveUnits; bool unitCompatibility; std::string patternStr; typedef std::map<std::string, Quad<std::string,double,std::string,bool>, stringCaseInsensitive > paramtype; paramtype parameters; }; } #endif
f8d3b5f87fdaf535198bb7d2b2b44b3127003725
ca3ad5bd204721d5f9e3df39d8030816fd14ea08
/ch01/ex1_15.cpp
1bbecc19cd024662b2d356b78343513505d1d578
[]
no_license
sealingShing/cpp_Primer
2dffb9a533666cb1aa33e0690324e12cd358bef3
e4d1e37ad4bde04358fc380017b146fb3560161b
refs/heads/main
2023-07-19T05:09:11.323236
2021-09-14T11:21:56
2021-09-14T11:21:56
394,485,621
0
0
null
null
null
null
UTF-8
C++
false
false
302
cpp
ex1_15.cpp
// // Created by wfs on 2021/8/10. // #include "iostream" using namespace std; int main(){ cout << "Read each file." << endl; cout << "Update master." << endl; cout << "Write new master." << endl; int v1 = 0, v2 = 0; cin >> v1 >> v2; cout << v1 + v2 << endl; return 0; }
00199226e83775e86600d36ca70a1ab7a3f90ee2
0dda8cef707f38f5058c3503666cbe3bf6ce8c57
/CODEFORCES/1307B_Cow_and_Friend.cpp
c622f15017e82ff12aa10593c0b168f449fd82b9
[]
no_license
Yuessiah/Destiny_Record
4b1ea05be13fa8e78b55bc95f8ee9a1b682108f2
69beb5486d2048e43fb5943c96c093f77e7133af
refs/heads/master
2022-10-09T07:05:04.820318
2022-10-07T01:50:58
2022-10-07T01:50:58
44,083,491
0
1
null
2017-05-04T12:50:35
2015-10-12T04:08:17
C++
UTF-8
C++
false
false
432
cpp
1307B_Cow_and_Friend.cpp
#include<bits/stdc++.h> using namespace std; int const maxn = 1e5 + 10; int t, n, x, a; int main() { scanf("%d", &t); while(t--) { scanf("%d%d", &n, &x); int mx = 0; bool eq = false; for(int i = 0; i < n; i++) { scanf("%d", &a); if(a == x) eq = true; mx = max(mx, a); } if(eq) puts("1"); else if(mx > x) puts("2"); else printf("%d\n", x/mx + !!(x%mx)); } return 0; }
f0e5a242a138be04f9529b9f922bc66571f9473f
65f9576021285bc1f9e52cc21e2d49547ba77376
/LINUX/android/vendor/qcom/proprietary/qcril-hal/modules/qmi/src/UimHttpModemEndPointModule.cpp
cf43152c011b391f917d365f44236348098d9daf
[ "Apache-2.0" ]
permissive
AVCHD/qcs605_root_qcom
183d7a16e2f9fddc9df94df9532cbce661fbf6eb
44af08aa9a60c6ca724c8d7abf04af54d4136ccb
refs/heads/main
2023-03-18T21:54:11.234776
2021-02-26T11:03:59
2021-02-26T11:03:59
null
0
0
null
null
null
null
UTF-8
C++
false
false
40,092
cpp
UimHttpModemEndPointModule.cpp
/****************************************************************************** # @file UimHttpModemEndPointModule.cpp # @brief Registers with QMI UIM HTTP and sends receives messages to and from # modem using QMI UIM interface # # --------------------------------------------------------------------------- # # Copyright (c) 2016-2017 Qualcomm Technologies, Inc. # All Rights Reserved. # Confidential and Proprietary - Qualcomm Technologies, Inc. # --------------------------------------------------------------------------- #******************************************************************************/ /*=========================================================================== INCLUDE FILES ===========================================================================*/ #include <cstring> #include "common_v01.h" #include "user_identity_module_http_v01.h" #include "modules/qmi/QmiServiceUpIndMessage.h" #include "modules/qmi/QmiServiceDownIndMessage.h" #include "modules/qmi/QmiUimHttpSetupRequest.h" #include "modules/lpa/LpaQmiUimHttpIndicationMsg.h" #include "modules/lpa/LpaUimHttpTransactionIndMsg.h" #include "modules/lpa/LpaUimHttpTransactionRspMsg.h" #include "modules/lpa/LpaUimHttpSrvc.h" #include "framework/ModuleLooper.h" #include "UimHttpModemEndPointModule.h" #ifdef QMI_RIL_UTF extern "C"{ #include "ril_utf_qmi_sim.h" } #endif #define TAG "UimHttpModemEndPointModule" #define QCRIL_QMI_UIM_HTTP_FREE_PTR(ptr) \ if (ptr != nullptr) \ { \ delete ptr; \ ptr = nullptr; \ } \ /*========================================================================= FUNCTION: qmiNotifyCb Description : Callback for qmi service notification ===========================================================================*/ static void qmiNotifyCb ( qmi_client_type user_handle, qmi_idl_service_object_type service_obj, qmi_client_notify_event_type service_event, void *notify_cb_data ) { /* Wrapper for member method*/ UimHttpModemEndPointModule *me = (UimHttpModemEndPointModule *)notify_cb_data; me->onQmiNotifyCb(user_handle, service_obj, service_event); } /*========================================================================= FUNCTION: qcril_uim_http_generic_response_callback Description : Callback for two things 1. the error transaction request send to MODEM 2. reset request send to MODEM ===========================================================================*/ static void qcril_uim_http_generic_response_callback ( qmi_client_type user_handle, unsigned int msg_id, void * qmi_http_rsp_ptr, unsigned int qmi_http_rsp_len, void * resp_cb_data_ptr, qmi_client_error_type transp_err ) { (void)user_handle; (void)qmi_http_rsp_len; (void)resp_cb_data_ptr; Log::getInstance().d("qcril_uim_http_generic_response_callback: msg_id = " + std::to_string(msg_id) + "with transp err = " + std::to_string(transp_err)); delete (uim_http_transaction_resp_msg_v01 *)qmi_http_rsp_ptr; qmi_http_rsp_ptr = nullptr; } /* qcril_uim_http_generic_response_callback */ /*========================================================================= FUNCTION: qmiUnsolIndCb Description : Callback for qmi service notification ===========================================================================*/ static void qmiUnsolIndCb ( qmi_client_type user_handle, unsigned long msg_id, unsigned char *ind_buf, int ind_buf_len, void *ind_cb_data ) { if (ind_cb_data == nullptr) { return; } UimHttpModemEndPointModule *me = (UimHttpModemEndPointModule *)ind_cb_data; me->onQmiUnsolIndCb(user_handle, msg_id, ind_buf, ind_buf_len); } /*========================================================================= FUNCTION: qmi_uim_http_request_cb Description : Callback for qmi uim http request ===========================================================================*/ static void qmi_uim_http_request_cb ( qmi_client_type user_handle, unsigned int msg_id, void * qmi_http_rsp_ptr, unsigned int qmi_http_rsp_len, void * resp_cb_data_ptr, qmi_client_error_type transp_err ) { if (resp_cb_data_ptr == nullptr) { if (qmi_http_rsp_ptr != nullptr) { delete (uim_http_reset_resp_msg_v01 *)qmi_http_rsp_ptr; qmi_http_rsp_ptr = nullptr; } return; } /* Wrapper for member method*/ UimHttpModemEndPointModule *me = (UimHttpModemEndPointModule *)resp_cb_data_ptr; me->qcril_uim_http_transaction_completed_callback(user_handle, msg_id, qmi_http_rsp_ptr, qmi_http_rsp_len, transp_err); } /*========================================================================= FUNCTION: UimHttpModemEndPointModule Description : UIM HTTP qmi module constructor ===========================================================================*/ UimHttpModemEndPointModule::UimHttpModemEndPointModule ( string name, ModemEndPoint *owner ) { mName = name; mOwner = owner; mServiceObject = nullptr; mQmiSvcClient = nullptr; http_trasaction_ind_ptr = nullptr; http_transaction_req_ptr = nullptr; mLooper = std::unique_ptr<ModuleLooper>(new ModuleLooper); using std::placeholders::_1; mMessageHandler = { HANDLER(QmiUimHttpSetupRequest, UimHttpModemEndPointModule::handleQmiClientSetup), HANDLER(LpaUimHttpRequestMsg, UimHttpModemEndPointModule::qcril_uim_http_client_transaction_request), HANDLER(LpaUimHttpTransactionIndMsg, UimHttpModemEndPointModule::qcril_uim_http_handle_transaction_ind), HANDLER(LpaUimHttpTransactionRspMsg, UimHttpModemEndPointModule::qcril_uim_http_process_transaction_completed_qmi_callback), HANDLER(QmiServiceUpIndMessage, UimHttpModemEndPointModule::handleQmiServiceUp), HANDLER(QmiServiceDownIndMessage, UimHttpModemEndPointModule::handleQmiServiceDown), }; } /*========================================================================= FUNCTION: UimHttpModemEndPointModule Description : UIM HTTP qmi module destructor ===========================================================================*/ UimHttpModemEndPointModule::~UimHttpModemEndPointModule() { mLooper = nullptr; if (mQmiNotifyHandle != nullptr) { (void)qmi_client_release(mQmiNotifyHandle); mQmiNotifyHandle = nullptr; } if (mQmiSvcClient != nullptr) { (void)qmi_client_release(mQmiSvcClient); mQmiSvcClient = nullptr; } mServiceObject = nullptr; } /*========================================================================= FUNCTION: qcril_uim_http_copy_indication Description : Makes a copy of the indication received from QMI UIM HTTP. ===========================================================================*/ uint8_t * UimHttpModemEndPointModule::qcril_uim_http_copy_indication ( qmi_client_type user_handle_ptr, unsigned int msg_id, unsigned char * qmi_http_ind_ptr, unsigned int qmi_http_ind_len, uint32_t * out_len_ptr ) { uint8_t * decoded_payload_ptr = nullptr; uint32_t decoded_payload_len = 0; qmi_client_error_type qmi_err = QMI_INTERNAL_ERR; if ((user_handle_ptr == nullptr) || (qmi_http_ind_ptr == nullptr) || (out_len_ptr == nullptr)) { return nullptr; } /* First decode the message payload from QCCI */ qmi_idl_get_message_c_struct_len(uim_http_get_service_object_v01(), QMI_IDL_INDICATION, msg_id, &decoded_payload_len); if (decoded_payload_len == 0) { return nullptr; } /* Allocate decoded payload buffer */ decoded_payload_ptr = new uint8_t[decoded_payload_len]; if (decoded_payload_ptr == nullptr) { return nullptr; } memset(decoded_payload_ptr, 0x00, decoded_payload_len); /* Decode the Indication payload */ qmi_err = qmi_client_message_decode(user_handle_ptr, QMI_IDL_INDICATION, msg_id, qmi_http_ind_ptr, qmi_http_ind_len, (void *)decoded_payload_ptr, decoded_payload_len); if (qmi_err != QMI_NO_ERR) { if (decoded_payload_ptr != nullptr) { delete[] decoded_payload_ptr; decoded_payload_ptr = nullptr; } return nullptr; } /* Initialize the payload data & assign the message data pointer */ *out_len_ptr = decoded_payload_len; return decoded_payload_ptr; } /* qcril_uim_http_copy_indication */ /*========================================================================= FUNCTION: onQmiUnsolIndCb Description : UIM HTTP qmi module unsol indication callback ===========================================================================*/ void UimHttpModemEndPointModule::onQmiUnsolIndCb ( qmi_client_type user_handle, unsigned long msg_id, unsigned char *ind_buf_ptr, int ind_buf_len ) { uint8_t *msg_ptr = nullptr; uint32_t msg_len = 0; Log::getInstance().d("[UimHttpModemEndPointModule]: onQmiUnsolIndCb()"); if ((ind_buf_ptr == nullptr) || (ind_buf_len == 0)) { return; } /* Process only the supported IND messages */ switch (msg_id) { case QMI_UIM_HTTP_TRANSACTION_IND_V01: msg_ptr = qcril_uim_http_copy_indication(user_handle, msg_id, ind_buf_ptr, ind_buf_len, &msg_len); break; default: Log::getInstance().d("Unsupported QMI UIM HTTP indication: 0x%x"+ std::to_string(msg_id)); break; } if (msg_ptr != nullptr && msg_len > 0) { this->dispatch( std::shared_ptr<Message>(new LpaUimHttpTransactionIndMsg(msg_len, msg_ptr, msg_id, 0))); delete[] msg_ptr; } } /* UimHttpModemEndPointModule::onQmiUnsolIndCb */ /*========================================================================= FUNCTION: onQmiNotifyCb Description : UIM HTTP qmi module unsol notification callback ===========================================================================*/ void UimHttpModemEndPointModule::onQmiNotifyCb ( qmi_client_type user_handle, qmi_idl_service_object_type service_obj, qmi_client_notify_event_type service_event ) { (void)user_handle; (void)service_obj; Log::getInstance().d("[UimHttpModemEndPointModule]: onQmiNotifyCb()"); switch (service_event) { case QMI_CLIENT_SERVICE_COUNT_INC: Log::getInstance().d( "[UimHttpModemEndPointModule]: qmiNotifyCb() Service up indication"); this->dispatch( std::shared_ptr<Message>(new QmiServiceUpIndMessage(nullptr))); break; case QMI_CLIENT_SERVICE_COUNT_DEC: Log::getInstance().d( "[UimHttpModemEndPointModule]: qmiNotifyCb() Service down indication"); this->dispatch( std::shared_ptr<Message>(new QmiServiceDownIndMessage(QMI_SERVICE_ERR))); break; default: Log::getInstance().d( "[UimHttpModemEndPointModule]: qmiNotifyCb() unsupported service " "event: " + std::to_string(service_event)); break; } return; } /*========================================================================= FUNCTION: handleQmiClientSetup Description : UIM HTTP qmi module client setup ===========================================================================*/ void UimHttpModemEndPointModule::handleQmiClientSetup ( std::shared_ptr<Message> msg ) { (void)msg; Log::getInstance().d("[UimHttpModemEndPointModule]: handleQmiClientSetup()"); if (mServiceObject == nullptr) { mServiceObject = uim_http_get_service_object_v01(); if (mServiceObject == nullptr) { Log::getInstance().d( "[UimHttpModemEndPointModule]:Did not get uim_get_service_object"); return; } else { Log::getInstance().d( "[UimHttpModemEndPointModule]:Got uim_get_service_object"); } qmi_client_error_type rc = qmi_client_notifier_init( mServiceObject, &mNotifierOsParams, &mQmiNotifyHandle); if (rc == QMI_NO_ERR) { mMessageList.push_back(msg); rc = qmi_client_register_notify_cb(mQmiNotifyHandle, qmiNotifyCb, this); if (rc != QMI_NO_ERR) { Log::getInstance().d( "[UimHttpModemEndPointModule]: qmi_client_register_notify_cb " "failed: " + std::to_string(rc)); } mOwner->setState(ModemEndPoint::State::WAITING_SERVICE_UP); } else { Log::getInstance().d( "[UimHttpModemEndPointModule]: qmi_client_notifier_init failed: " + std::to_string(rc)); } return; } else { mMessageList.push_back(msg); return; } } /*========================================================================= FUNCTION: handleQmiServiceUp Description : QMI service up handler ===========================================================================*/ void UimHttpModemEndPointModule::handleQmiServiceUp ( std::shared_ptr<Message> msg_ptr ) { qmi_client_type qmi_svc_client = nullptr; qmi_client_error_type client_err = QMI_NO_ERR; uim_http_reset_req_msg_v01 qmi_http_req; uim_http_reset_resp_msg_v01 * qmi_http_rsp_ptr = nullptr; qmi_txn_handle txn_handle; qmi_service_info info; (void) msg_ptr; Log::getInstance().d("[UimHttpModemEndPointModule]: handleQmiServiceUp()"); if (mQmiSvcClient != nullptr) { QCRIL_LOG_INFO( "Already Registered to service"); return; } memset(&mOsParams, 0x00, sizeof(mOsParams)); client_err = qmi_client_get_any_service(mServiceObject, &info); Log::getInstance().d("[UimHttpModemEndPointModule]: client_info: " + std::to_string(client_err)); client_err = qmi_client_init(&info, mServiceObject, (qmi_client_ind_cb)qmiUnsolIndCb, this, &mOsParams, &qmi_svc_client); mOwner->setState(ModemEndPoint::State::CLIENT_INIT_REQUESTED); Log::getInstance().d("[UimHttpModemEndPointModule]: client_err = " + std::to_string(client_err)); if (client_err != QMI_NO_ERR) { Log::getInstance().d("[UimHttpModemEndPointModule]: Error in client init"); } else { Log::getInstance().d("[UimHttpModemEndPointModule]: No Error in client init"); mQmiSvcClient = qmi_svc_client; mOwner->setState(ModemEndPoint::State::OPERATIONAL); // Notify clients of this end-point that we have qmi client handle. for (auto msg : mMessageList) { std::shared_ptr<QmiUimHttpSetupRequest> shared_msg = std::static_pointer_cast<QmiUimHttpSetupRequest>(msg); Log::getInstance().d("[UimHttpModemEndPointModule]: Notify client = " + msg->dump()); if(shared_msg) { shared_msg->sendResponse(shared_msg, Message::Callback::Status::SUCCESS, nullptr); } } std::shared_ptr<LpaQmiUimHttpIndicationMsg> ind_msg_ptr = std::make_shared<LpaQmiUimHttpIndicationMsg>(QMI_UIM_HTTP_SRVC_UP_IND_MSG, nullptr); if (ind_msg_ptr != nullptr) { ind_msg_ptr->broadcast(); } mMessageList.clear(); /* UTF is not supported for HTTP, don't send event during initalization which will fail bootup test cases */ Log::getInstance().d("QMI UIM HTTP Client init complete, send reset request to MODEM"); qmi_http_rsp_ptr = new uim_http_reset_resp_msg_v01; if (qmi_http_rsp_ptr == nullptr) { Log::getInstance().d("error allocating memory for rsp pointers"); return; } memset(&qmi_http_req, 0x00, sizeof(uim_http_reset_req_msg_v01)); memset(qmi_http_rsp_ptr, 0x00, sizeof(uim_http_reset_resp_msg_v01)); client_err = qmi_client_send_msg_async( mQmiSvcClient, QMI_UIM_HTTP_RESET_REQ_V01, (void *)&qmi_http_req, sizeof(uim_http_reset_req_msg_v01), (void *)qmi_http_rsp_ptr, sizeof(uim_http_reset_resp_msg_v01), qcril_uim_http_generic_response_callback, nullptr, &txn_handle); if (client_err != 0) { Log::getInstance().d("error in sending http reset req"); delete qmi_http_rsp_ptr; qmi_http_rsp_ptr = nullptr; } } } /*========================================================================= FUNCTION: handleQmiServiceDown Description : QMI service down handler ===========================================================================*/ void UimHttpModemEndPointModule::handleQmiServiceDown ( std::shared_ptr<Message> msg ) { (void)msg; if (mQmiSvcClient != NULL) { (void)qmi_client_release(mQmiSvcClient); mQmiSvcClient = nullptr; } QCRIL_LOG_INFO( "handleQmiServiceDown : %d", mOwner->getState()); mOwner->setState(ModemEndPoint::State::NON_OPERATIONAL); std::shared_ptr<LpaQmiUimHttpIndicationMsg> ind_msg_ptr = std::make_shared<LpaQmiUimHttpIndicationMsg>(QMI_UIM_HTTP_SRVC_DOWN_IND_MSG, nullptr); if (ind_msg_ptr != nullptr) { ind_msg_ptr->broadcast(); } } /* UimHttpModemEndPointModule::handleQmiServiceDown */ /*========================================================================= FUNCTION: qcril_uim_http_transaction_completed_callback Description : Callback implementation for the QMI UIM HTTP commands. ===========================================================================*/ void UimHttpModemEndPointModule::qcril_uim_http_transaction_completed_callback ( qmi_client_type user_handle, unsigned int msg_id, void * qmi_http_rsp_ptr, unsigned int qmi_http_rsp_len, qmi_client_error_type transp_err ) { (void) user_handle; if (http_transaction_req_ptr == nullptr) { return; } /* Process only the supported RESP messages */ switch (msg_id) { case QMI_UIM_HTTP_TRANSACTION_RESP_V01: this->dispatch(std::shared_ptr<Message>( new LpaUimHttpTransactionRspMsg(qmi_http_rsp_len, qmi_http_rsp_ptr, msg_id, transp_err))); break; default: break; } } /* qcril_uim_http_transaction_completed_callback */ /*=========================================================================== FUNCTION: qcril_uim_http_send_error_response Description : This function sends response to the Modem for any failure in the transaction indication ===========================================================================*/ void UimHttpModemEndPointModule::qcril_uim_http_send_error_response ( uint32_t token_id ) { int qmi_err_code = 0; uim_http_transaction_req_msg_v01 * qmi_http_req_ptr = nullptr; uim_http_transaction_resp_msg_v01 * qmi_http_rsp_ptr = nullptr; qmi_txn_handle txn_handle; if (token_id == 0) { /* do nothing if the token ID is invalid */ return; } qmi_http_req_ptr = new uim_http_transaction_req_msg_v01; qmi_http_rsp_ptr = new uim_http_transaction_resp_msg_v01; if ((qmi_http_rsp_ptr == nullptr) || (qmi_http_req_ptr == nullptr)) { if (qmi_http_req_ptr != nullptr) { delete qmi_http_req_ptr; qmi_http_req_ptr = nullptr; } if (qmi_http_rsp_ptr != nullptr) { delete qmi_http_rsp_ptr; qmi_http_rsp_ptr = nullptr; } Log::getInstance().d("error allocating memory for req or rsp pointers"); return; } memset(qmi_http_rsp_ptr, 0x00, sizeof(uim_http_transaction_resp_msg_v01)); /* Fill the qmi_http_req_ptr with token ID and result as error */ memset(qmi_http_req_ptr, 0, sizeof(uim_http_transaction_req_msg_v01)); qmi_http_req_ptr->token_id = token_id; qmi_http_req_ptr->result = UIM_HTTP_UNKNOWN_ERROR_V01; qmi_err_code = qmi_client_send_msg_async( mQmiSvcClient, QMI_UIM_HTTP_TRANSACTION_REQ_V01, (void *)qmi_http_req_ptr, sizeof(uim_http_transaction_req_msg_v01), (void *)qmi_http_rsp_ptr, sizeof(uim_http_transaction_resp_msg_v01), qcril_uim_http_generic_response_callback, nullptr, &txn_handle); if (qmi_err_code != 0) { Log::getInstance().d("Failure in sending the error notification to modem"); delete qmi_http_rsp_ptr; qmi_http_rsp_ptr = nullptr; } delete qmi_http_req_ptr; qmi_http_req_ptr = nullptr; } /* qcril_uim_http_send_error_response */ /*=========================================================================== FUNCTION: qcril_uim_http_handle_transaction_ind Description : Handles the HTTP indication ===========================================================================*/ void UimHttpModemEndPointModule::qcril_uim_http_handle_transaction_ind ( std::shared_ptr<Message> msg_ptr ) { uint8_t index = 0; uim_http_transaction_ind_msg_v01 * qmi_http_ind_ptr = nullptr; uint32_t msg_len = 0; uint32_t segment_offset = 0; std::shared_ptr<LpaUimHttpTransactionIndMsg> http_transaction_ind_msg_ptr( std::static_pointer_cast<LpaUimHttpTransactionIndMsg>(msg_ptr)); if (http_transaction_ind_msg_ptr == nullptr) { return; } qmi_http_ind_ptr = (uim_http_transaction_ind_msg_v01 *)http_transaction_ind_msg_ptr->get_message(&msg_len); if (qmi_http_ind_ptr == nullptr) { return; } Log::getInstance().d("token_id: " + std::to_string(qmi_http_ind_ptr->token_id)); /* Token ID should be same for all the chunks of a http command payload */ if (http_trasaction_ind_ptr != nullptr && http_trasaction_ind_ptr->token_id != qmi_http_ind_ptr->token_id) { Log::getInstance().d("Token ID received is different than expected, send error to previous token and process the new indication"); goto report_error_to_modem; } /* http_transaction_ind_ptr will be nullptr for the first chunk of a http request payload from the MODEM */ if (http_trasaction_ind_ptr == nullptr) { http_trasaction_ind_ptr = new uim_http_transaction_ind_msg; if (http_trasaction_ind_ptr == nullptr) { Log::getInstance().d("error allocating memory for http_trasaction_payload_ptr"); goto report_error_to_modem; } memset(http_trasaction_ind_ptr, 0x00, sizeof(uim_http_transaction_msg)); http_trasaction_ind_ptr->token_id = qmi_http_ind_ptr->token_id; if (qmi_http_ind_ptr->payload_body_valid) { uint32_t payload_len = 0; if (qmi_http_ind_ptr->segment_info_valid) { payload_len = qmi_http_ind_ptr->segment_info.total_size; } else { payload_len = qmi_http_ind_ptr->payload_body_len; } http_trasaction_ind_ptr->payload_ptr = new uint8_t[payload_len]{}; if (http_trasaction_ind_ptr->payload_ptr == nullptr) { Log::getInstance().d("error allocating memory for http_trasaction_payload_ptr"); goto report_error_to_modem; } http_trasaction_ind_ptr->payload_len = payload_len; memset(http_trasaction_ind_ptr->payload_ptr, 0x00, sizeof(uint8_t) * http_trasaction_ind_ptr->payload_len); } } /* Copying URL */ if (qmi_http_ind_ptr->url_valid) { http_trasaction_ind_ptr->url_valid = true; strlcpy(http_trasaction_ind_ptr->url, qmi_http_ind_ptr->url, UIM_HTTP_URL_MAX_LEN); http_trasaction_ind_ptr->url[UIM_HTTP_URL_MAX_LEN] = '\0'; } /* Copying headers */ if (qmi_http_ind_ptr->headers_valid) { http_trasaction_ind_ptr->headers_valid = true; strlcpy(http_trasaction_ind_ptr->headers.content_type, qmi_http_ind_ptr->headers.content_type, UIM_HTTP_HEADER_VALUE_MAX_LEN); http_trasaction_ind_ptr->headers.content_type[UIM_HTTP_HEADER_VALUE_MAX_LEN] = '\0'; for(index = 0; index < qmi_http_ind_ptr->headers.custom_header_len && index < UIM_HTTP_CUST_HEADER_MAX_COUNT_V01 && index < UIM_HTTP_CUST_HEADER_MAX_COUNT; index++) { strlcpy(http_trasaction_ind_ptr->headers.custom_header[index].name, qmi_http_ind_ptr->headers.custom_header[index].name, UIM_HTTP_HEADER_NAME_MAX_LEN); http_trasaction_ind_ptr->headers.custom_header[index].name[UIM_HTTP_HEADER_NAME_MAX_LEN] = '\0'; strlcpy(http_trasaction_ind_ptr->headers.custom_header[index].value, qmi_http_ind_ptr->headers.custom_header[index].value, UIM_HTTP_HEADER_VALUE_MAX_LEN); http_trasaction_ind_ptr->headers.custom_header[index].value[UIM_HTTP_HEADER_VALUE_MAX_LEN] = '\0'; } } /* Copying Payload */ if ((qmi_http_ind_ptr->payload_body_valid != 0) && (qmi_http_ind_ptr->payload_body_len > 0) && (http_trasaction_ind_ptr->payload_ptr != nullptr)) { if (qmi_http_ind_ptr->segment_info_valid) { segment_offset = qmi_http_ind_ptr->segment_info.segment_offset; } if(segment_offset + qmi_http_ind_ptr->payload_body_len <= http_trasaction_ind_ptr->payload_len) { memcpy(http_trasaction_ind_ptr->payload_ptr + segment_offset, qmi_http_ind_ptr->payload_body, qmi_http_ind_ptr->payload_body_len); } else { goto report_error_to_modem; } Log::getInstance().d("Received the http transaction request payload. Received bytes: " + std::to_string(qmi_http_ind_ptr->payload_body_len + segment_offset) + "total payload size: " + std::to_string(http_trasaction_ind_ptr->payload_len)); } /* Send the entire http payload to the client after receiving the total payload from multiple chunk indications */ if(segment_offset + qmi_http_ind_ptr->payload_body_len == http_trasaction_ind_ptr->payload_len) { std::shared_ptr<LpaQmiUimHttpIndicationMsg> qcril_uim_http_ind_ptr = std::make_shared<LpaQmiUimHttpIndicationMsg>(QMI_UIM_HTTP_SRVC_TRANSACTION_IND_MSG, http_trasaction_ind_ptr); if (qcril_uim_http_ind_ptr != nullptr) { qcril_uim_http_ind_ptr->broadcast(); } goto cleanup_memory; } return; report_error_to_modem: qcril_uim_http_send_error_response(qmi_http_ind_ptr->token_id); cleanup_memory: if (http_trasaction_ind_ptr != nullptr && http_trasaction_ind_ptr->payload_ptr != nullptr) { delete[] http_trasaction_ind_ptr->payload_ptr; http_trasaction_ind_ptr->payload_ptr = nullptr; } QCRIL_QMI_UIM_HTTP_FREE_PTR(http_trasaction_ind_ptr); http_transaction_ind_msg_ptr = nullptr; } /* qcril_uim_http_handle_transaction_ind */ /*========================================================================= FUNCTION: qcril_uim_http_process_transaction_completed_qmi_callback Description : This function sends the http response payload to the MODEM in chunks ===========================================================================*/ void UimHttpModemEndPointModule::qcril_uim_http_process_transaction_completed_qmi_callback ( std::shared_ptr<Message> msg_ptr ) { qmi_txn_handle txn_handle; int qmi_err_code = 0; uint32_t msg_len = 0; uim_http_transaction_req_msg_v01 * qmi_http_req_ptr = nullptr; uim_http_transaction_resp_msg_v01 * qmi_http_rsp_ptr = nullptr; uim_http_transaction_msg * http_req_ptr = nullptr; std::shared_ptr<LpaUimHttpTransactionRspMsg> http_transaction_rsp_msg_ptr( std::static_pointer_cast<LpaUimHttpTransactionRspMsg>(msg_ptr)); std::shared_ptr<lpa_qmi_uim_http_rsp_data_type> resp_data_ptr = nullptr; if (http_transaction_req_ptr == nullptr || http_transaction_rsp_msg_ptr == nullptr) { return; } http_req_ptr = (uim_http_transaction_msg *)http_transaction_req_ptr->get_message(); if (http_req_ptr == nullptr) { return; } if (http_transaction_rsp_msg_ptr->get_transport_err() != 0) { goto clean_up; } http_req_ptr->offset += UIM_HTTP_PAYLOAD_BODY_CHUNK_MAX_LEN_V01; QCRIL_LOG_INFO("Token: 0x%x, result: %d, payload_len: %d, offset:%d", http_req_ptr->token_id, http_req_ptr->result, http_req_ptr->payload_len, http_req_ptr->offset); /* Check to see if there are still chunks left that needs to be sent to MODEM */ if(http_req_ptr->offset < http_req_ptr->payload_len && http_req_ptr->payload_ptr != nullptr) { /* Allocate memory for the new QMI HTTP transaction request where the next payload chunk will be sent */ qmi_http_req_ptr = new uim_http_transaction_req_msg_v01; if (qmi_http_req_ptr == nullptr) { goto clean_up; } memset(qmi_http_req_ptr, 0, sizeof(uim_http_transaction_req_msg_v01)); qmi_http_req_ptr->token_id = http_req_ptr->token_id; qmi_http_req_ptr->result = (uim_http_result_type_enum_v01)http_req_ptr->result; qmi_http_req_ptr->segment_info_valid = 0x01; qmi_http_req_ptr->payload_body_valid = 0x01; qmi_http_req_ptr->segment_info.total_size = http_req_ptr->payload_len; qmi_http_req_ptr->segment_info.segment_offset = http_req_ptr->offset; if ((http_req_ptr->payload_len - http_req_ptr->offset) > UIM_HTTP_PAYLOAD_BODY_CHUNK_MAX_LEN_V01 ) { qmi_http_req_ptr->payload_body_len = UIM_HTTP_PAYLOAD_BODY_CHUNK_MAX_LEN_V01; } else { qmi_http_req_ptr->payload_body_len = (http_req_ptr->payload_len - http_req_ptr->offset); } memcpy(qmi_http_req_ptr->payload_body, http_req_ptr->payload_ptr + http_req_ptr->offset, qmi_http_req_ptr->payload_body_len); QCRIL_LOG_INFO("payload_len: %d, total: %d, offset: %d", qmi_http_req_ptr->payload_body_len, qmi_http_req_ptr->segment_info.total_size, qmi_http_req_ptr->segment_info.segment_offset); /* Allocate response pointer since it is an async command */ qmi_http_rsp_ptr = new uim_http_transaction_resp_msg_v01; if (qmi_http_rsp_ptr == nullptr) { goto clean_up; } memset(qmi_http_rsp_ptr, 0x00, sizeof(uim_http_transaction_resp_msg_v01)); /* Proceed with transaction request */ qmi_err_code = qmi_client_send_msg_async( mQmiSvcClient, QMI_UIM_HTTP_TRANSACTION_REQ_V01, (void *) qmi_http_req_ptr, sizeof(uim_http_transaction_req_msg_v01), (void *) qmi_http_rsp_ptr, sizeof(uim_http_transaction_resp_msg_v01), qmi_uim_http_request_cb, this, &txn_handle); /* On successful API call, free only the request */ if (qmi_err_code != 0) { goto clean_up; } QCRIL_QMI_UIM_HTTP_FREE_PTR(qmi_http_req_ptr); return; } resp_data_ptr = std::shared_ptr<lpa_qmi_uim_http_rsp_data_type>(new lpa_qmi_uim_http_rsp_data_type{}); if (resp_data_ptr == nullptr) { goto clean_up; } resp_data_ptr->transp_err = -1; resp_data_ptr->qmi_error_code = -1; /* When the entire response payload is sent, the client is notified using qcril_uim_http_transaction_resp */ switch(http_transaction_rsp_msg_ptr->get_msg_id()) { case QMI_UIM_HTTP_TRANSACTION_RESP_V01: qmi_http_rsp_ptr = (uim_http_transaction_resp_msg_v01 *)http_transaction_rsp_msg_ptr->get_message(&msg_len); resp_data_ptr->rsp_id = LPA_QMI_UIM_HTTP_TRANSACTION_RSP; resp_data_ptr->transp_err = http_transaction_rsp_msg_ptr->get_transport_err(); if (qmi_http_rsp_ptr != nullptr) { resp_data_ptr->qmi_error_code = qmi_http_rsp_ptr->resp.error; } break; default: /* This shouldn't happen since we never post for these msg ids */ Log::getInstance().d("Unsupported QMI UIM HTTP response: " + std::to_string(http_transaction_req_ptr->get_msg_id())); break; } clean_up: http_transaction_req_ptr->sendResponse((std::shared_ptr<Message>)http_transaction_req_ptr, Message::Callback::Status::SUCCESS, resp_data_ptr); /* Free memory allocated previously.*/ QCRIL_QMI_UIM_HTTP_FREE_PTR(qmi_http_req_ptr); QCRIL_QMI_UIM_HTTP_FREE_PTR(qmi_http_rsp_ptr); http_transaction_req_ptr = nullptr; } /* qcril_uim_http_process_transaction_completed_qmi_callback */ /*=========================================================================== FUNCTION: qcril_uim_http_client_transaction_request Description : Handles UIM_HTTP_TRANSACTION request from the client. ===========================================================================*/ void UimHttpModemEndPointModule::qcril_uim_http_client_transaction_request ( std::shared_ptr<Message> msg_ptr ) { qmi_txn_handle txn_handle; uint8_t header_index = 0; int qmi_err_code = -1; uim_http_transaction_req_msg_v01 * qmi_http_req_ptr = nullptr; uim_http_transaction_resp_msg_v01 * qmi_http_rsp_ptr = nullptr; uim_http_transaction_msg * http_req_ptr = nullptr; std::shared_ptr<lpa_qmi_uim_http_rsp_data_type> resp_data_ptr = nullptr; std::shared_ptr<LpaUimHttpRequestMsg> http_transaction_req_msg_ptr( std::static_pointer_cast<LpaUimHttpRequestMsg>(msg_ptr)); if (http_transaction_req_msg_ptr == nullptr) { return; } http_req_ptr = (uim_http_transaction_msg *)http_transaction_req_msg_ptr->get_message(); if (http_req_ptr == nullptr) { return; } /* Allocate QMI HTTP transaction request for the first response payload chunk to be sent */ qmi_http_req_ptr = new uim_http_transaction_req_msg_v01; if (qmi_http_req_ptr == nullptr) { goto report_error_to_modem; } if (http_req_ptr->payload_ptr == nullptr && http_req_ptr->payload_len != 0) { goto report_error_to_modem; } Log::getInstance().d("Sending payload of length " + std::to_string(http_req_ptr->payload_len)); /* Filling the qmi_http_req_ptr */ memset(qmi_http_req_ptr, 0, sizeof(uim_http_transaction_req_msg_v01)); QCRIL_LOG_INFO("Token: 0x%x, result: %d, payload_len :%d, offset: %d", http_req_ptr->token_id, http_req_ptr->result, http_req_ptr->payload_len, http_req_ptr->offset); qmi_http_req_ptr->token_id = http_req_ptr->token_id; qmi_http_req_ptr->result = (uim_http_result_type_enum_v01)http_req_ptr->result; if (http_req_ptr->payload_len > 0) { qmi_http_req_ptr->segment_info_valid = 0x01; qmi_http_req_ptr->payload_body_valid = 0x01; qmi_http_req_ptr->segment_info.total_size = http_req_ptr->payload_len; qmi_http_req_ptr->segment_info.segment_offset = http_req_ptr->offset; if (http_req_ptr->payload_len > UIM_HTTP_PAYLOAD_BODY_CHUNK_MAX_LEN_V01 ) { qmi_http_req_ptr->payload_body_len = UIM_HTTP_PAYLOAD_BODY_CHUNK_MAX_LEN_V01; } else { qmi_http_req_ptr->payload_body_len = http_req_ptr->payload_len; } memcpy(qmi_http_req_ptr->payload_body, http_req_ptr->payload_ptr, qmi_http_req_ptr->payload_body_len); } QCRIL_LOG_INFO("payload_len: %d, total: %d, offset: %d", qmi_http_req_ptr->payload_body_len, qmi_http_req_ptr->segment_info.total_size, qmi_http_req_ptr->segment_info.segment_offset); if(http_req_ptr->headers_valid) { qmi_http_req_ptr->headers_valid = true; if (http_req_ptr->headers_len > UIM_HTTP_CUST_HEADER_MAX_COUNT_V01) { qmi_http_req_ptr->headers_len = UIM_HTTP_CUST_HEADER_MAX_COUNT_V01; } else { qmi_http_req_ptr->headers_len = http_req_ptr->headers_len; } for(header_index = 0; header_index < qmi_http_req_ptr->headers_len && header_index < UIM_HTTP_CUST_HEADER_MAX_COUNT; header_index++) { (void)strlcpy(qmi_http_req_ptr->headers[header_index].name, http_req_ptr->headers[header_index].name, UIM_HTTP_HEADER_NAME_MAX_LEN_V01); qmi_http_req_ptr->headers[header_index].name[UIM_HTTP_HEADER_NAME_MAX_LEN_V01] = '\0'; (void)strlcpy(qmi_http_req_ptr->headers[header_index].value, http_req_ptr->headers[header_index].value, UIM_HTTP_HEADER_VALUE_MAX_LEN_V01); qmi_http_req_ptr->headers[header_index].value[UIM_HTTP_HEADER_VALUE_MAX_LEN_V01] = '\0'; } } /* Allocate response pointer since it is an async command */ qmi_http_rsp_ptr = new uim_http_transaction_resp_msg_v01; if (qmi_http_rsp_ptr == nullptr) { goto report_error_to_modem; } memset(qmi_http_rsp_ptr, 0x00, sizeof(uim_http_transaction_resp_msg_v01)); http_transaction_req_ptr = http_transaction_req_msg_ptr; qmi_err_code = qmi_client_send_msg_async( mQmiSvcClient, QMI_UIM_HTTP_TRANSACTION_REQ_V01, (void *) qmi_http_req_ptr, sizeof(uim_http_transaction_req_msg_v01), (void *) qmi_http_rsp_ptr, sizeof(uim_http_transaction_resp_msg_v01), qmi_uim_http_request_cb, (void *)this, &txn_handle); /* On successful API call, free only the request */ if (qmi_err_code != 0) { goto report_error; } QCRIL_QMI_UIM_HTTP_FREE_PTR(qmi_http_req_ptr); return; report_error_to_modem: qcril_uim_http_send_error_response(http_req_ptr->token_id); report_error: resp_data_ptr = std::shared_ptr<lpa_qmi_uim_http_rsp_data_type>(new lpa_qmi_uim_http_rsp_data_type{}); if (resp_data_ptr != nullptr) { resp_data_ptr->qmi_error_code = -1; resp_data_ptr->rsp_id = LPA_QMI_UIM_HTTP_TRANSACTION_RSP; resp_data_ptr->transp_err = -1; } /* In any case of error, check & free all the allocated pointers */ http_transaction_req_msg_ptr->sendResponse((std::shared_ptr<Message>)http_transaction_req_msg_ptr, Message::Callback::Status::SUCCESS, resp_data_ptr); http_transaction_req_ptr = nullptr; QCRIL_QMI_UIM_HTTP_FREE_PTR(qmi_http_req_ptr); QCRIL_QMI_UIM_HTTP_FREE_PTR(qmi_http_rsp_ptr); } /* qcril_uim_http_client_transaction_request */ #ifdef QMI_RIL_UTF void UimHttpModemEndPointModule::cleanUpQmiSvcClient() { if(nullptr != mQmiSvcClient) { qmi_client_release(mQmiSvcClient); mQmiSvcClient = nullptr; mServiceObject = nullptr; } } #endif
7d9683427b74f37b2db3823a3340db0f2e172fd1
1ea17fb9415957a1bedd02f121627a094620ed52
/Session 1/gaonK/3/9461.cpp
8130535f466ce77bf455ea05712cfe8731357d81
[]
no_license
gaonK/AlgorithmStudy
e5dd261537c8ec2bb3058d4c7fd05cda599aafc5
025f09bc7b18f2c84c5db24a66548c06f86f3d0b
refs/heads/master
2021-07-09T12:38:13.777563
2019-03-07T22:29:49
2019-03-07T22:29:49
147,552,885
2
2
null
2019-03-07T22:29:50
2018-09-05T17:09:58
C++
UTF-8
C++
false
false
363
cpp
9461.cpp
#include <iostream> using namespace std; long long p[101]; int main() { p[1] = 1; p[2] = 1; p[3] = 1; p[4] = 2; p[5] = 2; for (int i = 6; i <= 100; i++) { p[i] = p[i - 1] + p[i - 5]; } int T; cin >> T; while (T--) { int N; cin >> N; cout << p[N] << '\n'; } return 0; }
7a0d558a19fc00ad015936adcaa8548047ce1426
a315d8c81c934f778b4f602fdd1cd77717c6e1b0
/src/dtl/filter/blocked_bloomfilter/blocked_bloomfilter_config.hpp
84b132661ae9cda46a092b57fb25cd1de980aaf5
[ "BSD-3-Clause", "BSL-1.0", "Apache-2.0" ]
permissive
diegomestre2/bloomfilter-bsd
ac749c0d452cbd349607872bdf5801a71e4d644f
4c800910acee25b74d946580d9da893a871cc1e1
refs/heads/master
2020-05-16T10:07:59.512210
2019-03-07T15:54:42
2019-03-07T15:54:42
151,229,238
0
0
NOASSERTION
2018-10-02T09:15:29
2018-10-02T09:15:29
null
UTF-8
C++
false
false
1,950
hpp
blocked_bloomfilter_config.hpp
#pragma once #include <sstream> #include <dtl/dtl.hpp> #include "block_addressing_logic.hpp" namespace dtl { //===----------------------------------------------------------------------===// struct blocked_bloomfilter_config { $u32 k = 8; $u32 word_size = 4; // [byte] $u32 word_cnt_per_block = 1; $u32 sector_cnt = 1; dtl::block_addressing addr_mode = dtl::block_addressing::POWER_OF_TWO; $u32 zone_cnt = 1; bool operator<(const blocked_bloomfilter_config& o) const { return k < o.k || (k == o.k && word_size < o.word_size) || (k == o.k && word_size == o.word_size && word_cnt_per_block < o.word_cnt_per_block) || (k == o.k && word_size == o.word_size && word_cnt_per_block == o.word_cnt_per_block && sector_cnt < o.sector_cnt) || (k == o.k && word_size == o.word_size && word_cnt_per_block == o.word_cnt_per_block && sector_cnt == o.sector_cnt && addr_mode < o.addr_mode) || (k == o.k && word_size == o.word_size && word_cnt_per_block == o.word_cnt_per_block && sector_cnt == o.sector_cnt && addr_mode == o.addr_mode && zone_cnt < o.zone_cnt); } bool operator==(const blocked_bloomfilter_config& o) const { return k == o.k && word_size == o.word_size && word_cnt_per_block == o.word_cnt_per_block && sector_cnt == o.sector_cnt && addr_mode == o.addr_mode && zone_cnt == o.zone_cnt; } bool operator!=(const blocked_bloomfilter_config& o) const { return !(*this == o); } void print(std::ostream& os) const { std::stringstream str; str << "bbf" << ",k=" << k << ",word_size=" << word_size << ",word_cnt=" << word_cnt_per_block << ",sector_cnt=" << sector_cnt << ",addr=" << (addr_mode == dtl::block_addressing::POWER_OF_TWO ? "pow2" : "magic") << ",zone_cnt=" << zone_cnt; os << str.str(); } }; //===----------------------------------------------------------------------===// } // namespace dtl
bdeb0e6df5b0f55a0eebe1acd86bdf7f606d6d33
59f00d4f6fccb6b1103c5aa54f43a6e4d4f8bfc5
/src/common-lib/IdentificationTools/Substance.cpp
247b146b68cd668a4d5dd80c7ffe7adcff15f024
[]
no_license
tomas-pluskal/masspp
9c9492443bb796533bcb27fe52a0a60e4ba62160
808bf095215e549e7eb5317c02c04dfb2ceaba15
refs/heads/master
2021-01-01T05:33:44.483127
2015-06-07T12:54:17
2015-06-07T12:54:17
33,917,190
0
1
null
null
null
null
UTF-8
C++
false
false
2,266
cpp
Substance.cpp
/** * @file Substance.cpp // implementation of Substance class * * @author H.Parry * @date 2012.01.25 * * Copyright(C) 2006-2014 Shimadzu Corporation. All rights reserved. */ #include "stdafx.h" #include "Substance.h" #include "Hit.h" #include "SearchResult.h" using namespace kome::ident; #include <crtdbg.h> #ifdef _DEBUG #define new new( _NORMAL_BLOCK, __FILE__, __LINE__ ) #define malloc( s ) _malloc_dbg( s, _NORMAL_BLOCK, __FILE__, __LINE__ ) #endif // _DEBUG // constructor Substance::Substance( SearchResult* pSrchResult, const char * accession, const char* name, const SubstanceType type, Substance* parent ) : m_pSrchResult(pSrchResult), m_accession(accession), m_name(name), m_type(type), m_parent(parent) { m_pSrchResult->addSubstance( this ); } // destructor Substance::~Substance( void ) { m_pSrchResult->removeSubstance( this ); } // get the accession name std::string Substance::getAccession( void ) const { return m_accession; } // get the substance name std::string Substance::getName( void ) const { return m_name; } // get the substance type SubstanceType Substance::getType( void ) const { return m_type; } // get the parent substance (e.g. peptide -> protein) Substance* Substance::getParentSubstance( void ) const { return m_parent; } // set the parent substance (e.g. peptide -> protein) void Substance::setParentSubstance( Substance* parent ) { m_parent = parent; } // get the number of child substances (e.g. protein -> peptides) int Substance::getNumberOfChildSubstances( void ) const { int nChildCount = 0; for (int i = 0; i < m_pSrchResult->getNumberOfSubstances(); i++) { if (m_pSrchResult->getSubstance(i)->getParentSubstance() == this) { nChildCount++; } } return nChildCount; } // get the child substances (e.g. protein -> peptide) void Substance::getChildSubstances( std::vector<Substance*>& substanceList ) const { substanceList.clear(); for (int i = 0; i < m_pSrchResult->getNumberOfSubstances(); i++) { if (m_pSrchResult->getSubstance(i)->getParentSubstance() == this) { substanceList.push_back(m_pSrchResult->getSubstance(i)); } } } // get the substance properties object kome::core::Properties& Substance::getProperties( void ) { return m_properties; }
bea92c16e5ea2562c9b5a95edac6cde463ebec6b
1ffe4a35cf8244cb94e2b8e50ffd026f2e9ecef4
/Tools/ResourceEditor/Classes/Qt/Scene/SceneTabWidget.cpp
95ea459ff1f05e270cd5d8f1dd1c493032da4e71
[]
no_license
jjiezheng/dava.framework
481ff2cff24495feaf0bf24454eedf2c3e7ad4bc
6e961010c23918bb6ae83c0c3bee5e672d18537b
refs/heads/master
2020-12-25T08:42:01.782045
2013-06-12T11:13:05
2013-06-12T11:13:05
null
0
0
null
null
null
null
UTF-8
C++
false
false
726
cpp
SceneTabWidget.cpp
#include "GameCore.h" #include "Scene/SceneTabWidget.h" #include <QVBoxLayout> SceneTabWidget::SceneTabWidget(QWidget *parent) : QWidget(parent) , davaUIScreenID() { // init all DAVA things InitDAVAUI(); // create Qt controls and add them into layout tabBar = new QTabBar(this); davaWidget = new DavaGLWidget(this); davaWidget->setFocusPolicy(Qt::StrongFocus); QVBoxLayout *layout = new QVBoxLayout(); layout->addWidget(tabBar); layout->addWidget(davaWidget); layout->setMargin(1); setLayout(layout); } SceneTabWidget::~SceneTabWidget() { } void SceneTabWidget::InitDAVAUI() { davaUIScreen = new DAVA::UIScreen(); } void SceneTabWidget::setCurrentIndex(int index) { }
01b71dfdfa0ab313606b06783bc71ef8c838abb2
deceac78497921ad4e732c136e32d275f1910cd5
/src/mods/Sample.cpp
3cd9b4397e4169f18aaab97ef361371b4d0e7858
[ "MIT" ]
permissive
muhopensores/dmc4_hook
579447f95bce49e6987cdc5aedd2e1f112f0804f
396838b21ed3c1410c95cfc7c608540405a10ac1
refs/heads/master
2023-07-18T04:21:49.925799
2023-07-12T02:12:58
2023-07-12T02:12:58
225,172,831
16
4
MIT
2022-12-21T08:42:29
2019-12-01T14:14:17
C++
UTF-8
C++
false
false
1,302
cpp
Sample.cpp
// include your mod header file #include "Sample.hpp" #if 0 static uintptr_t jmp_return { NULL }; static bool mod_enabled{ false }; //uintptr_t ModSample::some_shared_ptr{ NULL }; // detour // naked is defined to __declspec(naked) naked void detour() { __asm { } } std::optional<std::string> ModSample::onInitialize() { return Mod::onInitialize(); } // onFrame() // do something each frame example //void ModSample::onFrame(fmilliseconds& dt) {} // onConfigSave // save your data into cfg structure. //void ModSample::onConfigSave(utility::Config& cfg) { cfg.set<variable_type>("config_string",variable_name); }; // onConfigLoad // load data into variables from config structure. //void ModSample::onConfigLoad(const utility::Config& cfg) { //variable_name = cfg.get<variable_type>("config_string").value_or(default_value); }; // onGUIframe() // draw your imgui widgets here, you are inside imgui context. //void ModSample::onGUIframe() { ImGui::Text("ModSample text"); }; // onGamePause() // do something when toggling a gui //void ModName::onGamePause(bool toggle) { }; // onMessage() // handle some window message, return true to pass to the game window // or false to drop it. //bool ModName::onMessage(HWND wnd, UINT message, WPARAM wParam, LPARAM lParam) { return true; }; #endif
0fbc5ab98c25a5ce523271c4301144cf0dd8b6ae
a57f34a696c449c5a091edb5c57e1927a38e6064
/class/deserializador.cpp
a1a9a748850477b5d9633d02e2d623fc46065d4e
[]
no_license
TheMarlboroMan/the-seer
4ad257473c456452f06314b3f21705f6a5dcb2b2
eaee3c4b31d568607553a888b88a2739b04cd552
refs/heads/master
2021-05-15T04:08:59.374274
2021-05-11T11:09:23
2021-05-11T11:09:23
119,861,400
1
0
null
null
null
null
UTF-8
C++
false
false
10,911
cpp
deserializador.cpp
#include "deserializador.h" Deserializador::Deserializador(unsigned int indice_archivo): archivo(Definiciones_serializador_deserializador::construir_ruta_archivo(indice_archivo), std::ios::in), version(0), id_sala(0), id_entrada(0), error(false) { } Deserializador::~Deserializador() { } bool Deserializador::es_fin_seccion(const std::string& linea) { return linea.find(Definiciones_serializador_deserializador::SEPARADOR_SECCION)!=std::string::npos || archivo.eof(); } bool Deserializador::comprobar_inicio_seccion(const std::string& linea, const char codigo, bool marcar) { std::string pieza=linea.substr(0, 3); bool resultado=Definiciones_serializador_deserializador::comprobar_marca(pieza, codigo); if(!marcar) { return resultado; } else { error=!resultado; return resultado; } } std::string Deserializador::extraer_cadena_seccion(const std::string& linea) { std::string resultado(linea.substr(3)); return resultado; } bool Deserializador::es_valido() const { return archivo.is_open(); } void Deserializador::finalizar() { archivo.close(); } void Deserializador::iniciar() { std::string linea=Utilidades_cargadores::obtener_siguiente_linea_archivo(archivo); if(!comprobar_inicio_seccion(linea, Definiciones_serializador_deserializador::M_INICIO)) { return; } int paso=0; while(!es_fin_seccion(linea)) { switch(paso) { case 0: { std::vector<unsigned int> v=Utilidades_cargadores::explotar_linea_a_enteros( extraer_cadena_seccion(linea), Definiciones_serializador_deserializador::SEPARADOR_DATOS ); if(v.size()!=3) { LOG<<"ERROR: Al iniciar deserializacion no hay 3 parametros"; } else { version=v[0]; id_sala=v[1]; id_entrada=v[2]; } } break; case 1: nombre=linea; break; } linea=Utilidades_cargadores::obtener_siguiente_linea_archivo(archivo); ++paso; } } void Deserializador::deserializar(Info_juego& c) { if(es_error()) return; std::string linea=Utilidades_cargadores::obtener_siguiente_linea_archivo(archivo); while(!es_fin_seccion(linea)) { if(!comprobar_inicio_seccion(linea, Definiciones_serializador_deserializador::M_INFO_JUEGO)) { return; } std::vector<unsigned int> v=Utilidades_cargadores::explotar_linea_a_enteros( extraer_cadena_seccion(linea), Definiciones_serializador_deserializador::SEPARADOR_DATOS ); if(v.size()!=3) { LOG<<"ERROR: deserializacion info juego no hay 3 parametros"; } else { c.actualizar_vidas_perdidas(v[0]); c.actualizar_llaves(v[1]); c.actualizar_bonus_tiempo(v[2]); } linea=Utilidades_cargadores::obtener_siguiente_linea_archivo(archivo); } } void Deserializador::deserializar(Tiempo_juego& c) { if(es_error()) return; std::string linea=Utilidades_cargadores::obtener_siguiente_linea_archivo(archivo); while(!es_fin_seccion(linea)) { if(!comprobar_inicio_seccion(linea, Definiciones_serializador_deserializador::M_TIEMPO_JUEGO)) { return; } unsigned int segundos=DLibH::Herramientas::cadena_a_entero(extraer_cadena_seccion(linea)); c.establecer_segundos_restantes(segundos); linea=Utilidades_cargadores::obtener_siguiente_linea_archivo(archivo); } } void Deserializador::deserializar(Control_salas& c) { std::string linea=Utilidades_cargadores::obtener_siguiente_linea_archivo(archivo); unsigned int num_linea=0; while(!es_fin_seccion(linea)) { switch(num_linea) { case 0: { if(!comprobar_inicio_seccion(linea, Definiciones_serializador_deserializador::M_CONTROL_SALAS)) { return; } std::vector<unsigned int> v=Utilidades_cargadores::explotar_linea_a_enteros( extraer_cadena_seccion(linea), Definiciones_serializador_deserializador::SEPARADOR_DATOS); for(unsigned int i : v) c.descubrir_sala(i); } break; case 1: { std::vector<unsigned int> v=Utilidades_cargadores::explotar_linea_a_enteros( linea, Definiciones_serializador_deserializador::SEPARADOR_DATOS); for(unsigned int i : v) c.marcar_gemas(i, true); } break; default: break; } linea=Utilidades_cargadores::obtener_siguiente_linea_archivo(archivo); ++num_linea; /* if(!comprobar_inicio_seccion(linea, Definiciones_serializador_deserializador::M_CONTROL_SALAS)) { return; } std::vector<unsigned int> v=Utilidades_cargadores::explotar_linea_a_enteros( extraer_cadena_seccion(linea), Definiciones_serializador_deserializador::SEPARADOR_DATOS ); for(unsigned int i : v) { c.descubrir_sala(i); } linea=Utilidades_cargadores::obtener_siguiente_linea_archivo(archivo); */ } } void Deserializador::deserializar(Control_objetivos& c) { std::string linea=Utilidades_cargadores::obtener_siguiente_linea_archivo(archivo); while(!es_fin_seccion(linea)) { if(!comprobar_inicio_seccion(linea, Definiciones_serializador_deserializador::M_CONTROL_OBJETIVOS)) { return; } std::vector<unsigned int> v=Utilidades_cargadores::explotar_linea_a_enteros( extraer_cadena_seccion(linea), Definiciones_serializador_deserializador::SEPARADOR_DATOS ); unsigned int i=0; unsigned int indice=0; //Primero los objetivos while(i<Control_objetivos::T_MAX) { unsigned int cuenta=v[indice++]; unsigned int total=v[indice++]; c.contar(i, cuenta); c.sumar_total(i, total); ++i; } //Y luego los mensajes. i=0; while(i<Control_objetivos::M_MAX) { unsigned int val=v[indice++]; if(val) c.marcar_mensaje_mostrado(i); else c.desmarcar_mensaje_mostrado(i); ++i; } //Luego los mensajes... linea=Utilidades_cargadores::obtener_siguiente_linea_archivo(archivo); } } void Deserializador::deserializar(Control_puzzle& c) { std::string linea=Utilidades_cargadores::obtener_siguiente_linea_archivo(archivo); while(!es_fin_seccion(linea)) { if(!comprobar_inicio_seccion(linea, Definiciones_serializador_deserializador::M_CONTROL_PUZZLE)) { return; } linea=extraer_cadena_seccion(linea); if(linea.size()) { std::vector<unsigned int> v=Utilidades_cargadores::explotar_linea_a_enteros( linea, Definiciones_serializador_deserializador::SEPARADOR_DATOS ); LOG<<"Deserializar "<<v.size()<<" piezas "<<std::endl; for(unsigned int i : v) c.recoger_pieza(i); } linea=Utilidades_cargadores::obtener_siguiente_linea_archivo(archivo); } } void Deserializador::deserializar(Control_energia& c) { if(es_error()) return; std::string linea=Utilidades_cargadores::obtener_siguiente_linea_archivo(archivo); while(!es_fin_seccion(linea)) { if(!comprobar_inicio_seccion(linea, Definiciones_serializador_deserializador::M_CONTROL_ENERGIA)) { return; } unsigned int tanques=DLibH::Herramientas::cadena_a_entero(extraer_cadena_seccion(linea)); unsigned int i=0; while(i<tanques) { c.nuevo_tanque(); ++i; } linea=Utilidades_cargadores::obtener_siguiente_linea_archivo(archivo); } } void Deserializador::deserializar(Control_habilidades& c) { std::string linea=Utilidades_cargadores::obtener_siguiente_linea_archivo(archivo); while(!es_fin_seccion(linea)) { if(!comprobar_inicio_seccion(linea, Definiciones_serializador_deserializador::M_CONTROL_HABILIDADES)) { return; } std::vector<unsigned int> v=Utilidades_cargadores::explotar_linea_a_enteros( extraer_cadena_seccion(linea), Definiciones_serializador_deserializador::SEPARADOR_DATOS ); LOG<<"Deserializar "<<v.size()<<" entradas: activas + habilidades. La linea es :"<<linea<<std::endl; bool primero=true; for(unsigned int i : v) { if(primero) { LOG<<"Activar habilidades?"<<i<<std::endl; primero=false; if(i) c.activar_habilidades(); else c.desactivar_habilidades(); } else { LOG<<"Concediendo habilidad "<<i<<std::endl; c.conceder_habilidad(i); } } linea=Utilidades_cargadores::obtener_siguiente_linea_archivo(archivo); } } void Deserializador::deserializar(Controlador_datos_persistentes& c) { std::string linea=Utilidades_cargadores::obtener_siguiente_linea_archivo(archivo); while(!es_fin_seccion(linea)) { if(!comprobar_inicio_seccion(linea, Definiciones_serializador_deserializador::M_CONTROL_DATOS_PERSISTENTES)) { return; } linea=extraer_cadena_seccion(linea); if(linea.size()) { const std::vector<std::string> partes=DLibH::Herramientas::explotar( linea, Definiciones_serializador_deserializador::SEPARADOR_DATOS); for(const std::string& cad : partes) { std::vector<unsigned int> v=Utilidades_cargadores::explotar_linea_a_enteros(cad, Definiciones_serializador_deserializador::SEPARADOR_INTERNO); c.actualizar_valor(v[0], v[1]); } } linea=Utilidades_cargadores::obtener_siguiente_linea_archivo(archivo); } } void Deserializador::deserializar(Control_actores_persistentes& c) { unsigned int id_sala=0; unsigned int total_sala=0; unsigned int indice=0; std::string linea=Utilidades_cargadores::obtener_siguiente_linea_archivo(archivo); if(!comprobar_inicio_seccion(linea, Definiciones_serializador_deserializador::M_CONTROL_ACTORES_PERSISTENTES)) { return; } else { linea=extraer_cadena_seccion(linea); } //No hay propiedad de los actores: se servirán al controlador, que //se adueñará de ellos. std::vector<Actor *> actores; while(!es_fin_seccion(linea)) { LOG<<"Deserializando linea "<<linea<<std::endl; if(indice==total_sala) { if(id_sala) { LOG<<"Insertando "<<actores.size()<<" actores en sala "<<id_sala<<std::endl; c.insertar_actores(id_sala, actores); } std::vector<unsigned int> v=Utilidades_cargadores::explotar_linea_a_enteros(linea, Definiciones_serializador_deserializador::SEPARADOR_DATOS); actores.clear(); id_sala=v[0]; total_sala=v[1]; indice=0; LOG<<"Se lee la cabecera de "<<total_sala<<" actores en sala "<<id_sala<<std::endl; } else { std::vector<unsigned int> v=Utilidades_cargadores::explotar_linea_a_enteros(linea, Definiciones_serializador_deserializador::SEPARADOR_DATOS_ACTORES); const unsigned int id_tipo=v[0]; Factoria_actores::Parametros_factoria params(v[1], v[2], v[3]); unsigned int ip=4; while(ip < v.size()) { params.insertar_param(v[ip]); ip++; } actores.push_back(Factoria_actores::fabricar(id_tipo, params)); ++indice; } linea=Utilidades_cargadores::obtener_siguiente_linea_archivo(archivo); } } bool Deserializador::localizar_seccion(const char clave) { //Rebobinar... archivo.seekg(std::ios_base::beg); int pos=archivo.tellg(); std::string linea=Utilidades_cargadores::obtener_siguiente_linea_archivo(archivo); while(!archivo.eof()) { if(comprobar_inicio_seccion(linea, clave, false)) { archivo.seekg(pos); return true; } pos=archivo.tellg(); linea=Utilidades_cargadores::obtener_siguiente_linea_archivo(archivo); } return false; }
9c8ed44be89112b544cf3e5ccf52afaa2bbd21aa
ee3ab94bab428c5774410d196c7bd929207a9290
/include/Menu.hpp
abb93b0fd4f449388f40b73c8e346a395ba1d0d6
[]
no_license
codergopher/Hotdog-Inspector
fc8b29407361f749998e8965233b6139aca3d85d
3b34e8aaaacf1840e6bcbca1d01fdbc1e8c0be8a
refs/heads/master
2023-01-14T12:26:18.760446
2020-08-17T02:52:35
2020-08-17T02:52:35
286,106,695
15
7
null
2020-11-28T09:20:05
2020-08-08T19:27:41
C++
UTF-8
C++
false
false
236
hpp
Menu.hpp
#pragma once #include <map> #include <string> #include "Sprite.hpp" #include "Animation.hpp" class Menu : public Sprite { public: Menu(); Menu(const SpriteCreateInfo& p_info); void update(const float& p_dt) override; private: };
487d36ce5ae9bdf68b75ed67ed0fb17ed7c0adab
32389f46f2abc0822b733fb70c14c17cba4a4c2b
/shaders/raymarching/PixelMetaballShader.cpp
af2a99105bb44ecc08573c66a41a7f49cf35c750
[]
no_license
FamilyAgency/Appart
70975f45aa186593cf713efcd078dca3b9c07a31
b410645d718917a5ef8fb668fb9e7d46a1d388c7
refs/heads/master
2020-03-28T06:30:11.346294
2018-09-07T15:19:53
2018-09-07T15:19:53
147,839,375
0
0
null
null
null
null
UTF-8
C++
false
false
2,127
cpp
PixelMetaballShader.cpp
#include "PixelMetaballShader.h" #include "MathTools.h" using namespace frames; PixelMetaballShader::PixelMetaballShader(float width, float height) : FrameShader(width, height), scale(50.) { name = "Pixel Metaball Shader"; spoutChannelName = "Shader Art"; addParameter(new Parameter3f("u_color", ofVec3f(1.0, 0.0, 0.0))); addParameter(new ParameterF("u_scale", scale)); setupShader(); } PixelMetaballShader::~PixelMetaballShader() { } void PixelMetaballShader::setup() { // setup init values scale = 50.; direction = 1; #ifndef release guiscale = 50.; scale = guiscale; #endif auto color = mathTools().randomColorNormalize(); updateParameter("u_color", color); updateParameter("u_scale", float(scale)); } void PixelMetaballShader::GUISetup() { #ifndef release FrameShader::GUISetup(); gui.add(guiscale.setup("scale", 50., 1., 500.0)); #endif } void PixelMetaballShader::update() { FrameShader::update(); float diff = 0.08; if (scale > 70. && direction == 1) { direction = -1; } else if (scale < 20. && direction == -1) { direction = 1; } diff *= direction; scale += diff; updateParameter("u_scale", float(scale)); } string PixelMetaballShader::getFragSrc() { return GLSL_STRING(120, uniform vec3 u_color; uniform vec2 u_resolution; uniform float u_time; uniform float u_scale; float ellipse(vec2 uv, vec2 o, float r, float n) { float res = pow(abs((uv.x - o.x) / r), n) + pow(abs((uv.y - o.y) / r), n); return res <= 1. ? sqrt(1. - res) : .0; } vec3 setPixel(vec2 uv) { return ellipse(fract(uv), vec2(.5), .5, 3.5)*u_color; } void main(void) { vec2 R = u_resolution.xy; vec2 uv = (2.*gl_FragCoord.xy - R) / R.y*u_scale; vec2 fuv = floor(uv) + .5; vec2 t = vec2(sin(u_time), cos(u_time))*u_scale / 2.4; vec2 o1 = vec2(0, 1.5*t.x); vec2 o2 = vec2(2.7*t.x, 0); vec2 o3 = 1.8*t.yx; vec3 l = vec3(distance(o1, fuv), distance(o2, fuv), distance(o3, fuv)) * .8; vec3 g = u_scale*vec3(.5 / (l.x*l.x), 1. / (l.y*l.y), .75 / (l.z*l.z)); gl_FragColor = g.x + g.y + g.z > 20. / u_scale ? vec4(setPixel(uv), 1.) : vec4(0., 0., 0., 1.); } ); }
7406a5767e2bc9f43584aced4f3b898ce2593e96
805f02059eb5d374fb4b72995c8acbda1f379941
/ch1/hello.cpp
df3e0ec4c825d1b120f8fd4f992d8f2665ae8cfa
[]
no_license
axesurvey/opencv_python_examples
a6f4cc3af301c725f1f84467bd8389fc1d001999
712c3e2831cdf21cb07fa51dd394956e3ed2e37e
refs/heads/master
2020-12-02T17:39:31.906456
2016-12-25T02:42:58
2016-12-25T02:42:58
null
0
0
null
null
null
null
UTF-8
C++
false
false
101
cpp
hello.cpp
#include <iostream> #include "hello.h" void sayHello() { std::cout << "Hello OpenCV!\n"; }
806b35fb35966a601040b904787d560b5114cffa
73c900fdb63579fb59b7552813dffc9cc4572a5f
/src/assignment2/SkeletonNode.cpp
47b68d14db611da04b4e4b9e2f984fed63de6e58
[]
no_license
bbartschi14/heirarchical_skinning
5048e1ed2fdf69d3baaa74dd3ffa35424222d0a4
efa830294613971b4c90275c309c60643034448e
refs/heads/main
2022-12-28T11:23:58.717284
2020-10-17T04:50:19
2020-10-17T04:50:19
304,777,270
0
0
null
null
null
null
UTF-8
C++
false
false
15,313
cpp
SkeletonNode.cpp
#include "SkeletonNode.hpp" #include "gloo/utils.hpp" #include "gloo/InputManager.hpp" #include "gloo/MeshLoader.hpp" #include "gloo/debug/PrimitiveFactory.hpp" #include "gloo/components/RenderingComponent.hpp" #include "gloo/components/ShadingComponent.hpp" #include "gloo/components/MaterialComponent.hpp" #include "gloo/shaders/PhongShader.hpp" #include "gloo/shaders/SimpleShader.hpp" #include <fstream> #include <algorithm> namespace GLOO { SkeletonNode::SkeletonNode(const std::string& filename) : SceneNode(), draw_mode_(DrawMode::Skeleton) { LoadAllFiles(filename); DecorateTree(); // Force initial update. OnJointChanged(false); } void SkeletonNode::ToggleDrawMode() { draw_mode_ = draw_mode_ == DrawMode::Skeleton ? DrawMode::SSD : DrawMode::Skeleton; // TODO: implement here toggling between skeleton mode and SSD mode. // The current mode is draw_mode_; // Hint: you may find SceneNode::SetActive convenient here as // inactive nodes will not be picked up by the renderer. if (draw_mode_ == DrawMode::SSD) { for (auto joint : joint_ptrs_) { joint->SetActive(false); } ssd_ptr_->SetActive(true); } else { for (auto joint : joint_ptrs_) { joint->SetActive(true); } ssd_ptr_->SetActive(false); } } std::vector<SceneNode*> SkeletonNode::GetSpherePtrs() { return sphere_nodes_ptrs_; } void SkeletonNode::DecorateTree() { // TODO: set up addtional nodes, add necessary components here. // You should create one set of nodes/components for skeleton mode // (spheres for joints and cylinders for bones), and another set for // SSD mode (you could just use a single node with a RenderingComponent // that is linked to a VertexObject with the mesh information. Then you // only need to update the VertexObject - updating vertex positions and // recalculating the normals, etc.). shader_ = std::make_shared<PhongShader>(); sphere_mesh_ = PrimitiveFactory::CreateSphere(0.025f, 25, 25); cylinder_mesh_ = PrimitiveFactory::CreateCylinder(0.015f, 1, 25); std::vector<glm::vec3> origins; for (int i = 0; i < joint_ptrs_.size(); i++) { int child_count = joint_ptrs_[i]->GetChildrenCount(); bool check_exists = std::find(origins.begin(), origins.end(), joint_ptrs_[i]->GetTransform().GetPosition()) != origins.end(); bool check_zero = joint_ptrs_[i]->GetTransform().GetPosition() != glm::vec3(0.0f); if (!(check_exists) && check_zero) { origins.push_back(joint_ptrs_[i]->GetTransform().GetPosition()); auto sphere_node = make_unique<SceneNode>(); sphere_node->CreateComponent<ShadingComponent>(shader_); sphere_node->CreateComponent<RenderingComponent>(sphere_mesh_); auto sphere_node_ptr = sphere_node.get(); sphere_nodes_ptrs_.push_back(sphere_node_ptr); joint_ptrs_[i]->AddChild(std::move(sphere_node)); std::vector<glm::vec3> offsets; float scale = .075f; offsets.push_back(glm::vec3(1.0f * scale, 0.0f, 0.0f)); offsets.push_back(glm::vec3(0.0f, 1.0f * scale, 0.0f)); offsets.push_back(glm::vec3(0.0f, 0.0f, 1.0f * scale)); std::vector<glm::vec3> color; color.push_back(glm::vec3(1.0f, 0.f, 0.f)); color.push_back(glm::vec3(0.0f, 1.f, 0.f)); color.push_back(glm::vec3(0.0f, 0.f, 1.f)); for (int num = 0; num < 3; num++) { auto small_sphere_node = make_unique<SceneNode>(); small_sphere_node->CreateComponent<ShadingComponent>(shader_); small_sphere_node->CreateComponent<RenderingComponent>(PrimitiveFactory::CreateSphere(0.01f, 25, 25)); small_sphere_node->GetTransform().SetPosition(offsets[num]); auto material = std::make_shared<Material>(color[num], color[num], color[num], 0); small_sphere_node->CreateComponent<MaterialComponent>(material); small_sphere_node->SetActive(false); small_sphere_node->SetGizmoAxis(num); auto line = std::make_shared<VertexObject>(); auto line_shader = std::make_shared<SimpleShader>(); auto indices = IndexArray(); indices.push_back(0); indices.push_back(1); line->UpdateIndices(make_unique<IndexArray>(indices)); auto positions = make_unique<PositionArray>(); float length = .05f; if (num == 0) { positions->push_back(glm::vec3(0.f, -1.f * length, 0.f)); positions->push_back(glm::vec3(0.f, 1.f * length, 0.f)); } else if (num == 1) { positions->push_back(glm::vec3(0.f, 0.f, -1.f * length)); positions->push_back(glm::vec3(0.f, 0.f, 1.f * length)); } else { positions->push_back(glm::vec3(-1.f * length, 0.f, 0.f)); positions->push_back(glm::vec3(1.f * length, 0.f, 0.f)); } line->UpdatePositions(std::move(positions)); auto line_node = make_unique<SceneNode>(); line_node->CreateComponent<ShadingComponent>(line_shader); auto& rc_line = line_node->CreateComponent<RenderingComponent>(line); rc_line.SetDrawMode(GLOO::DrawMode::Lines); auto material_new = std::make_shared<Material>(color[num], color[num], color[num], 0.0f); line_node->CreateComponent<MaterialComponent>(material); small_sphere_node->AddChild(std::move(line_node)); sphere_node_ptr->AddToGizmoPtrs(small_sphere_node.get()); sphere_node_ptr->AddChild(std::move(small_sphere_node)); } } std::vector<glm::vec3> child_origins; for (int j = 0; j < child_count; j++) { bool check_child_exists = std::find(child_origins.begin(), child_origins.end(), joint_ptrs_[i]->GetChild(j).GetTransform().GetPosition()) != child_origins.end(); bool check_child_zero = joint_ptrs_[i]->GetChild(j).GetTransform().GetPosition() != glm::vec3(0.0f); if (!check_child_exists && check_child_zero) { child_origins.push_back(joint_ptrs_[i]->GetChild(j).GetTransform().GetPosition()); auto cylinder_node = make_unique<SceneNode>(); cylinder_node->CreateComponent<ShadingComponent>(shader_); cylinder_node->CreateComponent<RenderingComponent>(cylinder_mesh_); glm::vec3 joint_pos = joint_ptrs_[i]->GetChild(j).GetTransform().GetPosition(); float height = glm::length(joint_pos); cylinder_node->GetTransform().SetScale(glm::vec3(1.0f, height, 1.0f)); glm::vec3 rot_axis = glm::normalize(glm::cross(glm::vec3(0.f, 1.f, 0.f), glm::normalize(joint_pos))); float rot_angle = glm::acos(glm::dot(glm::vec3(0.f, 1.f, 0.f), glm::normalize(joint_pos))); cylinder_node->GetTransform().SetRotation(rot_axis, rot_angle); cylinder_nodes_ptrs_.push_back(cylinder_node.get()); joint_ptrs_[i]->AddChild(std::move(cylinder_node)); } } } auto mesh_node = make_unique<SceneNode>(); mesh_node->CreateComponent<ShadingComponent>(shader_); mesh_node->CreateComponent<RenderingComponent>(bind_pose_mesh_); mesh_node->CreateComponent<MaterialComponent>(std::make_shared<Material>(Material::GetDefault())); glm::vec3 color = glm::vec3(.7f); mesh_node->GetComponentPtr<MaterialComponent>()->GetMaterial().SetAmbientColor(color); mesh_node->GetComponentPtr<MaterialComponent>()->GetMaterial().SetDiffuseColor(color); ssd_ptr_ = mesh_node.get(); AddChild(std::move(mesh_node)); ssd_ptr_->SetActive(false); } void SkeletonNode::Update(double delta_time) { // Prevent multiple toggle. static bool prev_released = true; if (InputManager::GetInstance().IsKeyPressed('S')) { if (prev_released) { ToggleDrawMode(); } prev_released = false; } else if (InputManager::GetInstance().IsKeyReleased('S')) { prev_released = true; } } void SkeletonNode::OnJointChanged(bool from_gizmo) { // TODO: this method is called whenever the values of UI sliders change. // The new Euler angles (represented as EulerAngle struct) can be retrieved // from linked_angles_ (a std::vector of EulerAngle*). // The indices of linked_angles_ align with the order of the joints in .skel // files. For instance, *linked_angles_[0] corresponds to the first line of // the .skel file. if (!from_gizmo) { if (linked_angles_.size() > 0) { for (int i = 0; i < joint_ptrs_.size(); i++) { glm::vec3 rot_vec = glm::vec3(linked_angles_[i]->rx, linked_angles_[i]->ry, linked_angles_[i]->rz); joint_ptrs_[i]->GetTransform().SetRotation(glm::quat(rot_vec)); } } } CalculateTMatrices(); ComputeNewPositions(); CalculateNormals(); } void SkeletonNode::LinkRotationControl(const std::vector<EulerAngle*>& angles) { linked_angles_ = angles; } void SkeletonNode::ComputeNewPositions() { auto new_positions = make_unique<PositionArray>(); for (int i = 0; i < orig_positions_.size(); i++) { glm::vec4 new_pos = glm::vec4(0.0f); for (int j = 0; j < joint_ptrs_.size() - 1; j++) { new_pos += vertex_weights_[i][j]*t_matrices[j]*b_matrices[j]*glm::vec4(orig_positions_[i],1.0f); } new_positions->push_back(glm::vec3(new_pos[0],new_pos[1],new_pos[2])); } bind_pose_mesh_->UpdatePositions(std::move(new_positions)); } void SkeletonNode::FindIncidentTriangles() { auto indices = bind_pose_mesh_->GetIndices(); auto positions = bind_pose_mesh_->GetPositions(); std::vector<std::vector<int>> incident_tris; for (int position_index = 0; position_index < positions.size(); position_index++) { std::vector<int> tris; for (int i = 0; i < indices.size() - 2; i += 3) { if (indices[i] == position_index || indices[i + 1] == position_index || indices[i + 2] == position_index) { tris.push_back(i / 3); } } incident_tris.push_back(tris); } incident_triangles_ = incident_tris; } void SkeletonNode::CalculateTMatrices() { t_matrices.clear(); glm::mat4 mat = joint_ptrs_[1]->GetTransform().GetLocalToWorldMatrix(); //std::cout << "Original Matrix: " << mat[0][0] << " " << mat[0][1] << " " << mat[0][2] << " " << mat[0][3] << " " << mat[1][0] << " " << mat[1][1] << " " << mat[1][2] << " " << mat[1][3] << std::endl; for (int i = 1; i < joint_ptrs_.size(); i++) { t_matrices.push_back(joint_ptrs_[i]->GetTransform().GetLocalToWorldMatrix()); } glm::mat4 mat_new = t_matrices[0]; //std::cout << "New Matrix: " << mat_new[0][0] << " " << mat_new[0][1] << " " << mat_new[0][2] << " " << mat_new[0][3] << " " << mat_new[1][0] << " " << mat_new[1][1] << " " << mat_new[1][2] << " " << mat_new[1][3] << std::endl; } void SkeletonNode::CalculateBMatrices() { for (int i = 1; i < joint_ptrs_.size(); i++) { b_matrices.push_back(glm::inverse(joint_ptrs_[i]->GetTransform().GetLocalToWorldMatrix())); } } void SkeletonNode::CalculateNormals() { auto indices = bind_pose_mesh_->GetIndices(); auto positions = bind_pose_mesh_->GetPositions(); auto new_normals = make_unique<NormalArray>(); for (int position_index = 0; position_index < positions.size(); position_index++) { glm::vec3 vertex_norm = glm::vec3(0.0f); for (int tri : incident_triangles_[position_index]) { glm::vec3 a = positions[indices[(tri * 3)]]; glm::vec3 b = positions[indices[(tri * 3)+1]]; glm::vec3 c = positions[indices[(tri * 3)+2]]; glm::vec3 u = b - a; glm::vec3 v = c - a; glm::vec3 tri_norm = glm::normalize(glm::cross(u, v)); vertex_norm += tri_norm * FindTriArea(a, b, c); } new_normals->push_back(glm::normalize(vertex_norm)); } bind_pose_mesh_->UpdateNormals(std::move(new_normals)); } float SkeletonNode::FindTriArea(glm::vec3 a, glm::vec3 b, glm::vec3 c) { float u_mag = glm::length(glm::cross(b - a, c - a)); return u_mag / 2; } void SkeletonNode::LoadSkeletonFile(const std::string& path) { std::vector<glm::vec3> joint_positions; std::vector<int> joint_parents; std::ifstream infile(path); float x, y, z; int parent_index; while (infile >> x >> y >> z >> parent_index) { //std::cout << x << " " << y << " " << z << " " << parent_index << std::endl; joint_positions.push_back(glm::vec3(x, y, z)); joint_parents.push_back(parent_index); } joint_ptrs_.resize(joint_parents.size()); RecursiveAddJoints(*this, -1, joint_positions, joint_parents); //std::cout << joint_ptrs_[1]->GetChildrenCount() << std::endl; } void SkeletonNode::RecursiveAddJoints(SceneNode& parent, int parent_index, std::vector<glm::vec3> positions, std::vector<int> joint_parents) { int current_child = 0; //std::cout << "Finding " << parent_index << "'s" << std::endl; for (int i = 0; i < joint_parents.size(); i++) { if (joint_parents[i] == parent_index) { //std::cout << "Found " << i << " for " << parent_index << std::endl; auto joint_node = make_unique<SceneNode>(); joint_node->GetTransform().SetPosition(positions[i]); joint_ptrs_[i] = joint_node.get(); parent.AddChild(std::move(joint_node)); auto& new_ptr = parent.GetChild(current_child); current_child++; RecursiveAddJoints(new_ptr, i, positions, joint_parents); } } } void SkeletonNode::LoadMeshFile(const std::string& filename) { std::shared_ptr<VertexObject> vtx_obj = MeshLoader::Import(filename).vertex_obj; bind_pose_mesh_ = vtx_obj; orig_positions_ = bind_pose_mesh_->GetPositions(); FindIncidentTriangles(); CalculateNormals(); CalculateBMatrices(); } void SkeletonNode::LoadAttachmentWeights(const std::string& path) { std::vector<std::vector<float>> weights; std::ifstream infile(path); float single_weight; std::vector<float> single_line; while (infile >> single_weight) { single_line.push_back(single_weight); //std::cout << single_weight << " "; if (single_line.size() == joint_ptrs_.size() - 1) { //std::cout << single_line.size() << std::endl; weights.push_back(single_line); single_line.clear(); } } //std::cout << weights.size() << std::endl; vertex_weights_ = weights; } void SkeletonNode::LoadAllFiles(const std::string& prefix) { std::string prefix_full = GetAssetDir() + prefix; LoadSkeletonFile(prefix_full + ".skel"); LoadMeshFile(prefix + ".obj"); LoadAttachmentWeights(prefix_full + ".attach"); } } // namespace GLOO
4736010a9ab9ebd0e7536ae453ef5469b217e6ac
717e50a345d596dee57feefa798a50c4fa76daa6
/TungstenOsmosis/TungstenWPFInterop.cpp
1fae822bcb93fc1ca68d9fd30c56591531292b05
[]
no_license
daniel-stanciu/Tungsten2
933bc30cc98f73201582a6619b5fd7b653095b5a
0e3b3dc02f92d419ec954b99042912281dee3813
refs/heads/master
2022-11-23T04:48:40.432958
2020-07-11T15:40:27
2020-07-11T15:40:27
84,127,255
0
0
null
null
null
null
UTF-8
C++
false
false
3,241
cpp
TungstenWPFInterop.cpp
// This is the main DLL file. #include "pch.h" #include "TungstenWPFInterop.h" #include "Tungsten/PlatformTools.h" #include "Tungsten/ConfigManager.h" #include <vcclr.h> #include "Tungsten\D3DRenderer.h" #include "TungstenWPFWindowRenderer.h" #include "Tungsten/ServiceLocator.h" #include "Tungsten/TungstenMath.h" #include "TungstenWPFImageRenderer.h" using namespace System::IO; using namespace Tungsten; using namespace System::Windows; using namespace System::Runtime::InteropServices; void TungstenOsmosis::TungstenWPFInterop::InitialiseRendererFromWindow(Window^ window) { auto wih = gcnew WindowInteropHelper(window); IntPtr hwnd = wih->Handle; _graphics = new TungstenWPFWindowRenderer((HWND)hwnd.ToInt64(),window->Width,window->Height); Services.SetGraphics(_graphics); /*_sprite = new SpriteImmediateEffect(); sp = new Sprite(); sp->Position = { { 300_px,300_px },{ 300_px,500_px } }; sp->Texture = TextureLoader::Get(L"Data\\Textures\\null.png"); Tungsten::Rectangle<Pixels> ret = { { 0.0f,0.0f },{ 256.0f,256.0f } }; sp->TextureSample = Tungsten::Rectangle<Pixels>::FromTopLeftSize(Tungsten::Point<Pixels>(0_px, 0_px), Tungsten::Point<Pixels>(256_px, 256_px));*/ } void TungstenOsmosis::TungstenWPFInterop::InitialiseRendererFromHwnd(IntPtr hwnd,int width,int height) { _graphics = new TungstenWPFWindowRenderer((HWND)hwnd.ToInt64(),width,height); Services.SetGraphics(_graphics); /*_sprite = new SpriteImmediateEffect(); sp = new Sprite(); sp->Position = { { 300_px,300_px },{ 600_px,600_px } }; sp->Texture = TextureLoader::Get(L"Data\\Textures\\null.png"); Tungsten::Rectangle<Pixels> ret = { { 0.0f,0.0f },{ 256.0f,256.0f } }; sp->TextureSample = Tungsten::Rectangle<Pixels>::FromTopLeftSize(Tungsten::Point<Pixels>(0_px, 0_px), Tungsten::Point<Pixels>(256_px, 256_px));*/ } void TungstenOsmosis::TungstenWPFInterop::InitialiseRendererFromImage(Image^ image) { _graphics = new TungstenWPFImageRenderer(image); Services.SetGraphics(_graphics); /*_sprite = new SpriteImmediateEffect(); sp = new Sprite(); sp->Position = { { 300_px,300_px },{ 300_px,500_px } }; sp->Texture = TextureLoader::Get(L"Data\\Textures\\null.png"); Tungsten::Rectangle<Pixels> ret = { { 0.0f,0.0f },{ 256.0f,256.0f } }; sp->TextureSample = Tungsten::Rectangle<Pixels>::FromTopLeftSize(Tungsten::Point<Pixels>(0_px, 0_px), Tungsten::Point<Pixels>(256_px, 256_px)); */ } TungstenOsmosis::TungstenWPFInterop::TungstenWPFInterop() { } void TungstenOsmosis::TungstenWPFInterop::RenderOnImage(Image ^ image) { _graphics->Present(); auto imageRender = (TungstenWPFImageRenderer*)_graphics; imageRender->Project(image); } void TungstenOsmosis::TungstenWPFInterop::RenderOnWindow() { //static float x = 0; //x = x + 0.3f; //if (x > 1) // x -= 1; //sp->Position.Center.x += 2.0f; //if (sp->Position.Center.x > 500) //{ // sp->Position.Center.y += 5; // sp->Position.Center.x = 0; // if (sp->Position.Center.y > 500) // { // sp->Position.Center.y = 0; // } //} //_graphics->Clear({ 0.0f,0.0f,1.0f,1.0f }); //_sprite->DrawSprite(*sp); ////sp->Position _graphics->Present(); } void TungstenOsmosis::TungstenWPFInterop::Clear() { _graphics->Clear({ 0.0f,0.0f,0.0f,1.0f }); }
013f97ef05261cc55c2abbe4e9c038a552cb98cf
4ba129e0121fda723e7fb292495ad1da1fd7a640
/Ozcan_vs_Nebulus_and_the_Towergoround/code/Game/CHUD.h
36c53680de559de31ce76339fa26a989ca3c3147
[]
no_license
nickben99/Ozcan
64f13069fa61f1bb790ec7e0093d19f7a71e3ed0
07ecc94e8587600ed9f0b5d6d2803741ca52c7fa
refs/heads/master
2020-05-21T16:42:27.590241
2018-01-11T04:59:49
2018-01-11T04:59:49
61,513,500
0
0
null
null
null
null
UTF-8
C++
false
false
4,373
h
CHUD.h
//CHUD.h - header for the Head Up Display (HUD) class // system includes ---------- #include <stdio.h> // header file for standard input/output #include "Rendering/OpenGLInclude.h" // -------------------------- #ifndef _CHUD_h_ #define _CHUD_h_ //header files------------------- #include "FileReading/texture.h" // for loading textures #include "CNebulus.h" #include "CHUDFader.h" #ifdef USE_SHADERS #include "Rendering/MeshBuffer.h" #include "Rendering/Text.h" #endif //------------------------------- class CVector4; // defines ---------------------- enum hudState // the different states the HUD can be in { INTRO_SCREEN, RESTART_SCREEN, MAIN_GAME, REPLAY, END_GAME }; // ------------------------------ class CHUD { private: //-----private variables----------- #ifdef USE_SHADERS Text* font; Text* largeFont; #else int fontBase, // the hud fonts display list largeFontBase; #endif int introScreenBackground; int letterHeight; // height of HUD font #ifdef USE_SHADERS MeshBuffer introScreenBuffer, loadingBarBackgroundBuffer, loadingBarForegroundBuffer, powerUpBarBackgroundBuffer, powerUpBarForegroundBuffer, restartScreenBackgroundBuffer, endGameScreenBackgroundBuffer; #endif float screenWidth, screenHeight; // record window dimensions //--------------------------------- //-----private methods-------------------- CHUD( void); // Constructor // run the intro screen drawing code void introScreenDraw( void); // run the main game drawing code void mainGameDraw(); void ReplayDraw(); #ifndef USE_SHADERS // draw a bar chart void drawBarChart( float leftSide, float rightSide, float top, float bottom, float perCent, unsigned char *backColour, unsigned char *frontColour, float &quadTwoRightSide ); #else // draw a bar chart void DrawBarChartWithShaders(MeshBuffer& background, MeshBuffer& foreground, float leftSide, float rightSide, float top, float bottom, float percent, float &quadTwoRightSide); #endif void GetLoadingBarDimensionsAndColor(float& left, float& right, float& top, float& bottom, CVector4& background, CVector4& foreground); void GetPowerUpBarDimensionsAndColor(float& left, float& right, float& top, float& bottom, CVector4& background, CVector4& foreground); // print a string #ifndef USE_SHADERS void printString(int charactersRequired, char * string, ...); #endif //---------------------------------------- public: //----public variables------------- char introScreenText[256], // text for the introscreen restartScreenText[256], // text for the restart screen restartScreenSubText[256], endScreenText[256], // text for the end game screen endScreenSubText[256]; // sub text for the restart screen hudState currentHUDState; // the hud state (from hudStates enum above) CNebulus *theNebulus; // pointer to singleton nebulus int *levelTimer; // referance to the CLevel levelTimer float powerUpPerCentRemaining, // perCent of timed power up remaining endScreenTextXScreenPerCent, // the x positioning of the end screen text endScreenSubTextXScreenPerCent, // the x positioning of the end screen sub text restartScreenTextXScreenPerCent, restartScreenSubTextXScreenPerCent; CHUDFader fader; //--------------------------------- //----public methods---------------------------------------- static CHUD* instance(); // get the singleton CHUD instance ~CHUD(); // destructor int loadHUDGraphicsAndFont(float width, float height); // load the huds graphics and font void update(float delta); // update any quantities displayed on the HUD void draw( void); // draw the HUD to the screen // draw the loading bar for the intro screen void drawIntroScreenLoadingBar( float floadPerCentComplete_ ); // print out the message when the game restarts after Nebulus dies void drawReStartScreen(); // reinitialise the HUD void reinitialiseHUD( void); // set back to starting state // delete the HUD display lists and graphics void deleteHUD( void); // draw the end game screen void drawEndGameScreen( void); inline float GetScreenWidth() { return screenWidth; } inline float GetScreenHeight() { return screenHeight; } //----------------------------------------------------------- }; // end class CHUD #endif // ifndef _CHUD_h_
5ff667498f2cd7de319d526ac8f93465cce66c4d
9ab0f33e9fa020fd0ef1a9da21c47969ba6c642c
/Biye/timer.h
6de7f5480531809e4436f3c2f37ba1fdf3375fc8
[]
no_license
YuriHehe/BiyeSheji
c25c3af59e3fc88ae1847bb0b76b1ec7b95d7224
4298be00329ec92bd5a2340802f0b8c11ccbbe27
refs/heads/master
2020-05-25T10:07:46.885643
2019-05-28T02:16:20
2019-05-28T02:16:20
187,754,082
0
0
null
null
null
null
UTF-8
C++
false
false
260
h
timer.h
#include "predefine.h" #include "util.h" namespace timer { class Timer { public: Timer() : start_(util::get_timestamp_ms()) {}; int64_t get_elapsed_us() { return util::get_timestamp_ms() - start_; } private: const int64_t start_; }; }
0917cecb9f00d4cd216e8c1e73fa26c0217773e8
e15bae789aaf7d1020929df50206649ac027b2a6
/Source/TextReader.h
8682d3a2b0a5e789f9a2afa2bacaf5269b8a44fb
[]
no_license
fredrikhanses/GraphicsGLFW
4bfb332535b71d5c0cff6737c88e78615ffcc9e1
d17b1ec65262baaff2d7ff10addc417af6bbbf0f
refs/heads/main
2023-03-12T02:32:05.516234
2021-02-27T11:49:06
2021-02-27T11:49:06
337,235,395
0
0
null
null
null
null
UTF-8
C++
false
false
142
h
TextReader.h
#pragma once #include <string> class TextReader { public: TextReader(); ~TextReader(); std::string ReadText(std::string Path); private: };
4bf91fed11574b6a71711963a1a90042fac735b7
6e3b592de89cb3e7d594993c784e7059bdb2a9ae
/Source/AllProjects/CQCAdmin/CQCAdmin_ImgViewTab.cpp
96c3f8e7443f99270afde8f72aed3a4fd2e902bd
[ "MIT" ]
permissive
jjzhang166/CQC
9aae1b5ffeddde2c87fafc3bb4bd6e3c7a98a1c2
8933efb5d51b3c0cb43afe1220cdc86187389f93
refs/heads/master
2023-08-28T04:13:32.013199
2021-04-16T14:41:21
2021-04-16T14:41:21
null
0
0
null
null
null
null
UTF-8
C++
false
false
4,716
cpp
CQCAdmin_ImgViewTab.cpp
// // FILE NAME: CQCAdmin_ImgViewTab.cpp // // AUTHOR: Dean Roddey // // CREATED: 08/09/2015 // // COPYRIGHT: Charmed Quark Systems, Ltd @ 2020 // // This software is copyrighted by 'Charmed Quark Systems, Ltd' and // the author (Dean Roddey.) It is licensed under the MIT Open Source // license: // // https://opensource.org/licenses/MIT // // DESCRIPTION: // // This file implements a tab for read only viewing of text based content. // // CAVEATS/GOTCHAS: // // LOG: // // --------------------------------------------------------------------------- // Includes // --------------------------------------------------------------------------- #include "CQCAdmin.hpp" #include "CQCAdmin_ImgViewTab.hpp" // --------------------------------------------------------------------------- // Do our RTTI macros // --------------------------------------------------------------------------- RTTIDecls(TImgViewTab, TContentTab) // --------------------------------------------------------------------------- // CLASS: TImgViewTab // PREFIX: wnd // --------------------------------------------------------------------------- // --------------------------------------------------------------------------- // TImgViewTab: Constructors and destructor // --------------------------------------------------------------------------- TImgViewTab::TImgViewTab(const TString& strPath, const TString& strRelPath) : TContentTab(strPath, strRelPath, L"Image", kCIDLib::False) , m_pwndScroll(nullptr) , m_pwndImage(nullptr) { } TImgViewTab::~TImgViewTab() { } // --------------------------------------------------------------------------- // TImgViewTab: Public, non-virtual methods // --------------------------------------------------------------------------- tCIDLib::TVoid TImgViewTab::CreateTab( TTabbedWnd& wndParent , const TString& strTabText , const TBitmap& bmpToDisplay) { wndParent.c4CreateTab(this, strTabText, 0, kCIDLib::True); // // Set the image on the image window and size it up to fit, via the scroll // windwo so it knows and will adjust its scroll bars. // m_pwndImage->SetBitmap(bmpToDisplay); m_pwndScroll->SetChildSize(bmpToDisplay.szBitmap()); // Now we can show the image window m_pwndImage->SetVisibility(kCIDLib::True); } // --------------------------------------------------------------------------- // TImgViewTab: Protected, inherited methods // --------------------------------------------------------------------------- tCIDLib::TVoid TImgViewTab::AreaChanged(const TArea& areaPrev , const TArea& areaNew , const tCIDCtrls::EPosStates ePosState , const tCIDLib::TBoolean bOrgChanged , const tCIDLib::TBoolean bSizeChanged , const tCIDLib::TBoolean bStateChanged) { // Call our parent first TTabWindow::AreaChanged(areaPrev, areaNew, ePosState, bOrgChanged, bSizeChanged, bStateChanged); // Keep our list sized to fit if ((ePosState != tCIDCtrls::EPosStates::Minimized) && bSizeChanged && m_pwndScroll) m_pwndScroll->SetSize(areaClient().szArea(), kCIDLib::True); } tCIDLib::TBoolean TImgViewTab::bCreated() { TParent::bCreated(); // Create the scroller window m_pwndScroll = new TScrollArea(); m_pwndScroll->Create ( *this , kCIDCtrls::widFirstCtrl , areaClient() , tCIDCtrls::EWndStyles::ClippingVisChild , tCIDCtrls::EScrAStyles::None ); m_pwndScroll->c4Margin(8); // Create the image window m_pwndImage = new TStaticImg(); m_pwndImage->CreateStaticImg ( *m_pwndScroll , kCIDCtrls::widFirstCtrl + 1 , TArea(0, 0, 8, 8) , tCIDGraphDev::EPlacement::UpperLeft , tCIDCtrls::EWndStyles::VisChild ); // Tell the scroll area to treat our image window as it's scrollable child m_pwndScroll->SetChild(m_pwndImage); // Set them both to the standard window background m_pwndScroll->SetBgnColor(facCIDCtrls().rgbSysClr(tCIDCtrls::ESysColors::Window)); m_pwndImage->SetBgnColor(facCIDCtrls().rgbSysClr(tCIDCtrls::ESysColors::Window)); return kCIDLib::True; } tCIDLib::TVoid TImgViewTab::Destroyed() { // // Delete the scroll window if we created it. It will destroy the image // window. // if (m_pwndScroll) { if (m_pwndScroll->bIsValid()) m_pwndScroll->Destroy(); delete m_pwndScroll; m_pwndScroll= nullptr; } TParent::Destroyed(); }
c55aadfac0b8b619b3eff09d17669bf9d50421b2
c909ae1cbb7f73632b0f1d363e18eaf892aec1b7
/build/px4_sitl_default/build_gazebo/Odometry.pb.cc
e444afb75b419065723e65c0933050601edce6e2
[ "BSD-3-Clause" ]
permissive
amilearning/PX4_Firmware_rw
8e4454db2cc98530ffce9484f3e1a5367dae551a
8babdc71169f2632ec23173530eb871d475aada1
refs/heads/master
2023-06-20T13:36:22.333503
2021-07-20T02:46:38
2021-07-20T02:46:38
387,507,315
1
1
null
null
null
null
UTF-8
C++
false
true
34,697
cc
Odometry.pb.cc
// Generated by the protocol buffer compiler. DO NOT EDIT! // source: Odometry.proto #define INTERNAL_SUPPRESS_PROTOBUF_FIELD_DEPRECATION #include "Odometry.pb.h" #include <algorithm> #include <google/protobuf/stubs/common.h> #include <google/protobuf/stubs/port.h> #include <google/protobuf/stubs/once.h> #include <google/protobuf/io/coded_stream.h> #include <google/protobuf/wire_format_lite_inl.h> #include <google/protobuf/descriptor.h> #include <google/protobuf/generated_message_reflection.h> #include <google/protobuf/reflection_ops.h> #include <google/protobuf/wire_format.h> // @@protoc_insertion_point(includes) namespace nav_msgs { namespace msgs { namespace { const ::google::protobuf::Descriptor* Odometry_descriptor_ = NULL; const ::google::protobuf::internal::GeneratedMessageReflection* Odometry_reflection_ = NULL; } // namespace void protobuf_AssignDesc_Odometry_2eproto() GOOGLE_ATTRIBUTE_COLD; void protobuf_AssignDesc_Odometry_2eproto() { protobuf_AddDesc_Odometry_2eproto(); const ::google::protobuf::FileDescriptor* file = ::google::protobuf::DescriptorPool::generated_pool()->FindFileByName( "Odometry.proto"); GOOGLE_CHECK(file != NULL); Odometry_descriptor_ = file->message_type(0); static const int Odometry_offsets_[7] = { GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(Odometry, time_usec_), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(Odometry, position_), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(Odometry, orientation_), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(Odometry, linear_velocity_), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(Odometry, angular_velocity_), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(Odometry, pose_covariance_), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(Odometry, velocity_covariance_), }; Odometry_reflection_ = ::google::protobuf::internal::GeneratedMessageReflection::NewGeneratedMessageReflection( Odometry_descriptor_, Odometry::default_instance_, Odometry_offsets_, GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(Odometry, _has_bits_[0]), -1, -1, sizeof(Odometry), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(Odometry, _internal_metadata_), -1); } namespace { GOOGLE_PROTOBUF_DECLARE_ONCE(protobuf_AssignDescriptors_once_); inline void protobuf_AssignDescriptorsOnce() { ::google::protobuf::GoogleOnceInit(&protobuf_AssignDescriptors_once_, &protobuf_AssignDesc_Odometry_2eproto); } void protobuf_RegisterTypes(const ::std::string&) GOOGLE_ATTRIBUTE_COLD; void protobuf_RegisterTypes(const ::std::string&) { protobuf_AssignDescriptorsOnce(); ::google::protobuf::MessageFactory::InternalRegisterGeneratedMessage( Odometry_descriptor_, &Odometry::default_instance()); } } // namespace void protobuf_ShutdownFile_Odometry_2eproto() { delete Odometry::default_instance_; delete Odometry_reflection_; } void protobuf_AddDesc_Odometry_2eproto() GOOGLE_ATTRIBUTE_COLD; void protobuf_AddDesc_Odometry_2eproto() { static bool already_here = false; if (already_here) return; already_here = true; GOOGLE_PROTOBUF_VERIFY_VERSION; ::gazebo::msgs::protobuf_AddDesc_quaternion_2eproto(); ::gazebo::msgs::protobuf_AddDesc_vector3d_2eproto(); ::google::protobuf::DescriptorPool::InternalAddGeneratedFile( "\n\016Odometry.proto\022\rnav_msgs.msgs\032\020quatern" "ion.proto\032\016vector3d.proto\"\223\002\n\010Odometry\022\021" "\n\ttime_usec\030\001 \002(\003\022\'\n\010position\030\002 \002(\0132\025.ga" "zebo.msgs.Vector3d\022,\n\013orientation\030\003 \002(\0132" "\027.gazebo.msgs.Quaternion\022.\n\017linear_veloc" "ity\030\004 \002(\0132\025.gazebo.msgs.Vector3d\022/\n\020angu" "lar_velocity\030\005 \002(\0132\025.gazebo.msgs.Vector3" "d\022\033\n\017pose_covariance\030\006 \003(\002B\002\020\001\022\037\n\023veloci" "ty_covariance\030\007 \003(\002B\002\020\001", 343); ::google::protobuf::MessageFactory::InternalRegisterGeneratedFile( "Odometry.proto", &protobuf_RegisterTypes); Odometry::default_instance_ = new Odometry(); Odometry::default_instance_->InitAsDefaultInstance(); ::google::protobuf::internal::OnShutdown(&protobuf_ShutdownFile_Odometry_2eproto); } // Force AddDescriptors() to be called at static initialization time. struct StaticDescriptorInitializer_Odometry_2eproto { StaticDescriptorInitializer_Odometry_2eproto() { protobuf_AddDesc_Odometry_2eproto(); } } static_descriptor_initializer_Odometry_2eproto_; // =================================================================== #if !defined(_MSC_VER) || _MSC_VER >= 1900 const int Odometry::kTimeUsecFieldNumber; const int Odometry::kPositionFieldNumber; const int Odometry::kOrientationFieldNumber; const int Odometry::kLinearVelocityFieldNumber; const int Odometry::kAngularVelocityFieldNumber; const int Odometry::kPoseCovarianceFieldNumber; const int Odometry::kVelocityCovarianceFieldNumber; #endif // !defined(_MSC_VER) || _MSC_VER >= 1900 Odometry::Odometry() : ::google::protobuf::Message(), _internal_metadata_(NULL) { SharedCtor(); // @@protoc_insertion_point(constructor:nav_msgs.msgs.Odometry) } void Odometry::InitAsDefaultInstance() { position_ = const_cast< ::gazebo::msgs::Vector3d*>(&::gazebo::msgs::Vector3d::default_instance()); orientation_ = const_cast< ::gazebo::msgs::Quaternion*>(&::gazebo::msgs::Quaternion::default_instance()); linear_velocity_ = const_cast< ::gazebo::msgs::Vector3d*>(&::gazebo::msgs::Vector3d::default_instance()); angular_velocity_ = const_cast< ::gazebo::msgs::Vector3d*>(&::gazebo::msgs::Vector3d::default_instance()); } Odometry::Odometry(const Odometry& from) : ::google::protobuf::Message(), _internal_metadata_(NULL) { SharedCtor(); MergeFrom(from); // @@protoc_insertion_point(copy_constructor:nav_msgs.msgs.Odometry) } void Odometry::SharedCtor() { _cached_size_ = 0; time_usec_ = GOOGLE_LONGLONG(0); position_ = NULL; orientation_ = NULL; linear_velocity_ = NULL; angular_velocity_ = NULL; ::memset(_has_bits_, 0, sizeof(_has_bits_)); } Odometry::~Odometry() { // @@protoc_insertion_point(destructor:nav_msgs.msgs.Odometry) SharedDtor(); } void Odometry::SharedDtor() { if (this != default_instance_) { delete position_; delete orientation_; delete linear_velocity_; delete angular_velocity_; } } void Odometry::SetCachedSize(int size) const { GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); _cached_size_ = size; GOOGLE_SAFE_CONCURRENT_WRITES_END(); } const ::google::protobuf::Descriptor* Odometry::descriptor() { protobuf_AssignDescriptorsOnce(); return Odometry_descriptor_; } const Odometry& Odometry::default_instance() { if (default_instance_ == NULL) protobuf_AddDesc_Odometry_2eproto(); return *default_instance_; } Odometry* Odometry::default_instance_ = NULL; Odometry* Odometry::New(::google::protobuf::Arena* arena) const { Odometry* n = new Odometry; if (arena != NULL) { arena->Own(n); } return n; } void Odometry::Clear() { // @@protoc_insertion_point(message_clear_start:nav_msgs.msgs.Odometry) if (_has_bits_[0 / 32] & 31u) { time_usec_ = GOOGLE_LONGLONG(0); if (has_position()) { if (position_ != NULL) position_->::gazebo::msgs::Vector3d::Clear(); } if (has_orientation()) { if (orientation_ != NULL) orientation_->::gazebo::msgs::Quaternion::Clear(); } if (has_linear_velocity()) { if (linear_velocity_ != NULL) linear_velocity_->::gazebo::msgs::Vector3d::Clear(); } if (has_angular_velocity()) { if (angular_velocity_ != NULL) angular_velocity_->::gazebo::msgs::Vector3d::Clear(); } } pose_covariance_.Clear(); velocity_covariance_.Clear(); ::memset(_has_bits_, 0, sizeof(_has_bits_)); if (_internal_metadata_.have_unknown_fields()) { mutable_unknown_fields()->Clear(); } } bool Odometry::MergePartialFromCodedStream( ::google::protobuf::io::CodedInputStream* input) { #define DO_(EXPRESSION) if (!GOOGLE_PREDICT_TRUE(EXPRESSION)) goto failure ::google::protobuf::uint32 tag; // @@protoc_insertion_point(parse_start:nav_msgs.msgs.Odometry) for (;;) { ::std::pair< ::google::protobuf::uint32, bool> p = input->ReadTagWithCutoff(127); tag = p.first; if (!p.second) goto handle_unusual; switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) { // required int64 time_usec = 1; case 1: { if (tag == 8) { DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive< ::google::protobuf::int64, ::google::protobuf::internal::WireFormatLite::TYPE_INT64>( input, &time_usec_))); set_has_time_usec(); } else { goto handle_unusual; } if (input->ExpectTag(18)) goto parse_position; break; } // required .gazebo.msgs.Vector3d position = 2; case 2: { if (tag == 18) { parse_position: DO_(::google::protobuf::internal::WireFormatLite::ReadMessageNoVirtual( input, mutable_position())); } else { goto handle_unusual; } if (input->ExpectTag(26)) goto parse_orientation; break; } // required .gazebo.msgs.Quaternion orientation = 3; case 3: { if (tag == 26) { parse_orientation: DO_(::google::protobuf::internal::WireFormatLite::ReadMessageNoVirtual( input, mutable_orientation())); } else { goto handle_unusual; } if (input->ExpectTag(34)) goto parse_linear_velocity; break; } // required .gazebo.msgs.Vector3d linear_velocity = 4; case 4: { if (tag == 34) { parse_linear_velocity: DO_(::google::protobuf::internal::WireFormatLite::ReadMessageNoVirtual( input, mutable_linear_velocity())); } else { goto handle_unusual; } if (input->ExpectTag(42)) goto parse_angular_velocity; break; } // required .gazebo.msgs.Vector3d angular_velocity = 5; case 5: { if (tag == 42) { parse_angular_velocity: DO_(::google::protobuf::internal::WireFormatLite::ReadMessageNoVirtual( input, mutable_angular_velocity())); } else { goto handle_unusual; } if (input->ExpectTag(50)) goto parse_pose_covariance; break; } // repeated float pose_covariance = 6 [packed = true]; case 6: { if (tag == 50) { parse_pose_covariance: DO_((::google::protobuf::internal::WireFormatLite::ReadPackedPrimitive< float, ::google::protobuf::internal::WireFormatLite::TYPE_FLOAT>( input, this->mutable_pose_covariance()))); } else if (tag == 53) { DO_((::google::protobuf::internal::WireFormatLite::ReadRepeatedPrimitiveNoInline< float, ::google::protobuf::internal::WireFormatLite::TYPE_FLOAT>( 1, 50, input, this->mutable_pose_covariance()))); } else { goto handle_unusual; } if (input->ExpectTag(58)) goto parse_velocity_covariance; break; } // repeated float velocity_covariance = 7 [packed = true]; case 7: { if (tag == 58) { parse_velocity_covariance: DO_((::google::protobuf::internal::WireFormatLite::ReadPackedPrimitive< float, ::google::protobuf::internal::WireFormatLite::TYPE_FLOAT>( input, this->mutable_velocity_covariance()))); } else if (tag == 61) { DO_((::google::protobuf::internal::WireFormatLite::ReadRepeatedPrimitiveNoInline< float, ::google::protobuf::internal::WireFormatLite::TYPE_FLOAT>( 1, 58, input, this->mutable_velocity_covariance()))); } else { goto handle_unusual; } if (input->ExpectAtEnd()) goto success; break; } default: { handle_unusual: if (tag == 0 || ::google::protobuf::internal::WireFormatLite::GetTagWireType(tag) == ::google::protobuf::internal::WireFormatLite::WIRETYPE_END_GROUP) { goto success; } DO_(::google::protobuf::internal::WireFormat::SkipField( input, tag, mutable_unknown_fields())); break; } } } success: // @@protoc_insertion_point(parse_success:nav_msgs.msgs.Odometry) return true; failure: // @@protoc_insertion_point(parse_failure:nav_msgs.msgs.Odometry) return false; #undef DO_ } void Odometry::SerializeWithCachedSizes( ::google::protobuf::io::CodedOutputStream* output) const { // @@protoc_insertion_point(serialize_start:nav_msgs.msgs.Odometry) // required int64 time_usec = 1; if (has_time_usec()) { ::google::protobuf::internal::WireFormatLite::WriteInt64(1, this->time_usec(), output); } // required .gazebo.msgs.Vector3d position = 2; if (has_position()) { ::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray( 2, *this->position_, output); } // required .gazebo.msgs.Quaternion orientation = 3; if (has_orientation()) { ::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray( 3, *this->orientation_, output); } // required .gazebo.msgs.Vector3d linear_velocity = 4; if (has_linear_velocity()) { ::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray( 4, *this->linear_velocity_, output); } // required .gazebo.msgs.Vector3d angular_velocity = 5; if (has_angular_velocity()) { ::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray( 5, *this->angular_velocity_, output); } // repeated float pose_covariance = 6 [packed = true]; if (this->pose_covariance_size() > 0) { ::google::protobuf::internal::WireFormatLite::WriteTag(6, ::google::protobuf::internal::WireFormatLite::WIRETYPE_LENGTH_DELIMITED, output); output->WriteVarint32(_pose_covariance_cached_byte_size_); } for (int i = 0; i < this->pose_covariance_size(); i++) { ::google::protobuf::internal::WireFormatLite::WriteFloatNoTag( this->pose_covariance(i), output); } // repeated float velocity_covariance = 7 [packed = true]; if (this->velocity_covariance_size() > 0) { ::google::protobuf::internal::WireFormatLite::WriteTag(7, ::google::protobuf::internal::WireFormatLite::WIRETYPE_LENGTH_DELIMITED, output); output->WriteVarint32(_velocity_covariance_cached_byte_size_); } for (int i = 0; i < this->velocity_covariance_size(); i++) { ::google::protobuf::internal::WireFormatLite::WriteFloatNoTag( this->velocity_covariance(i), output); } if (_internal_metadata_.have_unknown_fields()) { ::google::protobuf::internal::WireFormat::SerializeUnknownFields( unknown_fields(), output); } // @@protoc_insertion_point(serialize_end:nav_msgs.msgs.Odometry) } ::google::protobuf::uint8* Odometry::InternalSerializeWithCachedSizesToArray( bool deterministic, ::google::protobuf::uint8* target) const { // @@protoc_insertion_point(serialize_to_array_start:nav_msgs.msgs.Odometry) // required int64 time_usec = 1; if (has_time_usec()) { target = ::google::protobuf::internal::WireFormatLite::WriteInt64ToArray(1, this->time_usec(), target); } // required .gazebo.msgs.Vector3d position = 2; if (has_position()) { target = ::google::protobuf::internal::WireFormatLite:: InternalWriteMessageNoVirtualToArray( 2, *this->position_, false, target); } // required .gazebo.msgs.Quaternion orientation = 3; if (has_orientation()) { target = ::google::protobuf::internal::WireFormatLite:: InternalWriteMessageNoVirtualToArray( 3, *this->orientation_, false, target); } // required .gazebo.msgs.Vector3d linear_velocity = 4; if (has_linear_velocity()) { target = ::google::protobuf::internal::WireFormatLite:: InternalWriteMessageNoVirtualToArray( 4, *this->linear_velocity_, false, target); } // required .gazebo.msgs.Vector3d angular_velocity = 5; if (has_angular_velocity()) { target = ::google::protobuf::internal::WireFormatLite:: InternalWriteMessageNoVirtualToArray( 5, *this->angular_velocity_, false, target); } // repeated float pose_covariance = 6 [packed = true]; if (this->pose_covariance_size() > 0) { target = ::google::protobuf::internal::WireFormatLite::WriteTagToArray( 6, ::google::protobuf::internal::WireFormatLite::WIRETYPE_LENGTH_DELIMITED, target); target = ::google::protobuf::io::CodedOutputStream::WriteVarint32ToArray( _pose_covariance_cached_byte_size_, target); } for (int i = 0; i < this->pose_covariance_size(); i++) { target = ::google::protobuf::internal::WireFormatLite:: WriteFloatNoTagToArray(this->pose_covariance(i), target); } // repeated float velocity_covariance = 7 [packed = true]; if (this->velocity_covariance_size() > 0) { target = ::google::protobuf::internal::WireFormatLite::WriteTagToArray( 7, ::google::protobuf::internal::WireFormatLite::WIRETYPE_LENGTH_DELIMITED, target); target = ::google::protobuf::io::CodedOutputStream::WriteVarint32ToArray( _velocity_covariance_cached_byte_size_, target); } for (int i = 0; i < this->velocity_covariance_size(); i++) { target = ::google::protobuf::internal::WireFormatLite:: WriteFloatNoTagToArray(this->velocity_covariance(i), target); } if (_internal_metadata_.have_unknown_fields()) { target = ::google::protobuf::internal::WireFormat::SerializeUnknownFieldsToArray( unknown_fields(), target); } // @@protoc_insertion_point(serialize_to_array_end:nav_msgs.msgs.Odometry) return target; } int Odometry::RequiredFieldsByteSizeFallback() const { // @@protoc_insertion_point(required_fields_byte_size_fallback_start:nav_msgs.msgs.Odometry) int total_size = 0; if (has_time_usec()) { // required int64 time_usec = 1; total_size += 1 + ::google::protobuf::internal::WireFormatLite::Int64Size( this->time_usec()); } if (has_position()) { // required .gazebo.msgs.Vector3d position = 2; total_size += 1 + ::google::protobuf::internal::WireFormatLite::MessageSizeNoVirtual( *this->position_); } if (has_orientation()) { // required .gazebo.msgs.Quaternion orientation = 3; total_size += 1 + ::google::protobuf::internal::WireFormatLite::MessageSizeNoVirtual( *this->orientation_); } if (has_linear_velocity()) { // required .gazebo.msgs.Vector3d linear_velocity = 4; total_size += 1 + ::google::protobuf::internal::WireFormatLite::MessageSizeNoVirtual( *this->linear_velocity_); } if (has_angular_velocity()) { // required .gazebo.msgs.Vector3d angular_velocity = 5; total_size += 1 + ::google::protobuf::internal::WireFormatLite::MessageSizeNoVirtual( *this->angular_velocity_); } return total_size; } int Odometry::ByteSize() const { // @@protoc_insertion_point(message_byte_size_start:nav_msgs.msgs.Odometry) int total_size = 0; if (((_has_bits_[0] & 0x0000001f) ^ 0x0000001f) == 0) { // All required fields are present. // required int64 time_usec = 1; total_size += 1 + ::google::protobuf::internal::WireFormatLite::Int64Size( this->time_usec()); // required .gazebo.msgs.Vector3d position = 2; total_size += 1 + ::google::protobuf::internal::WireFormatLite::MessageSizeNoVirtual( *this->position_); // required .gazebo.msgs.Quaternion orientation = 3; total_size += 1 + ::google::protobuf::internal::WireFormatLite::MessageSizeNoVirtual( *this->orientation_); // required .gazebo.msgs.Vector3d linear_velocity = 4; total_size += 1 + ::google::protobuf::internal::WireFormatLite::MessageSizeNoVirtual( *this->linear_velocity_); // required .gazebo.msgs.Vector3d angular_velocity = 5; total_size += 1 + ::google::protobuf::internal::WireFormatLite::MessageSizeNoVirtual( *this->angular_velocity_); } else { total_size += RequiredFieldsByteSizeFallback(); } // repeated float pose_covariance = 6 [packed = true]; { int data_size = 0; data_size = 4 * this->pose_covariance_size(); if (data_size > 0) { total_size += 1 + ::google::protobuf::internal::WireFormatLite::Int32Size(data_size); } GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); _pose_covariance_cached_byte_size_ = data_size; GOOGLE_SAFE_CONCURRENT_WRITES_END(); total_size += data_size; } // repeated float velocity_covariance = 7 [packed = true]; { int data_size = 0; data_size = 4 * this->velocity_covariance_size(); if (data_size > 0) { total_size += 1 + ::google::protobuf::internal::WireFormatLite::Int32Size(data_size); } GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); _velocity_covariance_cached_byte_size_ = data_size; GOOGLE_SAFE_CONCURRENT_WRITES_END(); total_size += data_size; } if (_internal_metadata_.have_unknown_fields()) { total_size += ::google::protobuf::internal::WireFormat::ComputeUnknownFieldsSize( unknown_fields()); } GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); _cached_size_ = total_size; GOOGLE_SAFE_CONCURRENT_WRITES_END(); return total_size; } void Odometry::MergeFrom(const ::google::protobuf::Message& from) { // @@protoc_insertion_point(generalized_merge_from_start:nav_msgs.msgs.Odometry) if (GOOGLE_PREDICT_FALSE(&from == this)) { ::google::protobuf::internal::MergeFromFail(__FILE__, __LINE__); } const Odometry* source = ::google::protobuf::internal::DynamicCastToGenerated<const Odometry>( &from); if (source == NULL) { // @@protoc_insertion_point(generalized_merge_from_cast_fail:nav_msgs.msgs.Odometry) ::google::protobuf::internal::ReflectionOps::Merge(from, this); } else { // @@protoc_insertion_point(generalized_merge_from_cast_success:nav_msgs.msgs.Odometry) MergeFrom(*source); } } void Odometry::MergeFrom(const Odometry& from) { // @@protoc_insertion_point(class_specific_merge_from_start:nav_msgs.msgs.Odometry) if (GOOGLE_PREDICT_FALSE(&from == this)) { ::google::protobuf::internal::MergeFromFail(__FILE__, __LINE__); } pose_covariance_.MergeFrom(from.pose_covariance_); velocity_covariance_.MergeFrom(from.velocity_covariance_); if (from._has_bits_[0 / 32] & (0xffu << (0 % 32))) { if (from.has_time_usec()) { set_time_usec(from.time_usec()); } if (from.has_position()) { mutable_position()->::gazebo::msgs::Vector3d::MergeFrom(from.position()); } if (from.has_orientation()) { mutable_orientation()->::gazebo::msgs::Quaternion::MergeFrom(from.orientation()); } if (from.has_linear_velocity()) { mutable_linear_velocity()->::gazebo::msgs::Vector3d::MergeFrom(from.linear_velocity()); } if (from.has_angular_velocity()) { mutable_angular_velocity()->::gazebo::msgs::Vector3d::MergeFrom(from.angular_velocity()); } } if (from._internal_metadata_.have_unknown_fields()) { mutable_unknown_fields()->MergeFrom(from.unknown_fields()); } } void Odometry::CopyFrom(const ::google::protobuf::Message& from) { // @@protoc_insertion_point(generalized_copy_from_start:nav_msgs.msgs.Odometry) if (&from == this) return; Clear(); MergeFrom(from); } void Odometry::CopyFrom(const Odometry& from) { // @@protoc_insertion_point(class_specific_copy_from_start:nav_msgs.msgs.Odometry) if (&from == this) return; Clear(); MergeFrom(from); } bool Odometry::IsInitialized() const { if ((_has_bits_[0] & 0x0000001f) != 0x0000001f) return false; if (has_position()) { if (!this->position_->IsInitialized()) return false; } if (has_orientation()) { if (!this->orientation_->IsInitialized()) return false; } if (has_linear_velocity()) { if (!this->linear_velocity_->IsInitialized()) return false; } if (has_angular_velocity()) { if (!this->angular_velocity_->IsInitialized()) return false; } return true; } void Odometry::Swap(Odometry* other) { if (other == this) return; InternalSwap(other); } void Odometry::InternalSwap(Odometry* other) { std::swap(time_usec_, other->time_usec_); std::swap(position_, other->position_); std::swap(orientation_, other->orientation_); std::swap(linear_velocity_, other->linear_velocity_); std::swap(angular_velocity_, other->angular_velocity_); pose_covariance_.UnsafeArenaSwap(&other->pose_covariance_); velocity_covariance_.UnsafeArenaSwap(&other->velocity_covariance_); std::swap(_has_bits_[0], other->_has_bits_[0]); _internal_metadata_.Swap(&other->_internal_metadata_); std::swap(_cached_size_, other->_cached_size_); } ::google::protobuf::Metadata Odometry::GetMetadata() const { protobuf_AssignDescriptorsOnce(); ::google::protobuf::Metadata metadata; metadata.descriptor = Odometry_descriptor_; metadata.reflection = Odometry_reflection_; return metadata; } #if PROTOBUF_INLINE_NOT_IN_HEADERS // Odometry // required int64 time_usec = 1; bool Odometry::has_time_usec() const { return (_has_bits_[0] & 0x00000001u) != 0; } void Odometry::set_has_time_usec() { _has_bits_[0] |= 0x00000001u; } void Odometry::clear_has_time_usec() { _has_bits_[0] &= ~0x00000001u; } void Odometry::clear_time_usec() { time_usec_ = GOOGLE_LONGLONG(0); clear_has_time_usec(); } ::google::protobuf::int64 Odometry::time_usec() const { // @@protoc_insertion_point(field_get:nav_msgs.msgs.Odometry.time_usec) return time_usec_; } void Odometry::set_time_usec(::google::protobuf::int64 value) { set_has_time_usec(); time_usec_ = value; // @@protoc_insertion_point(field_set:nav_msgs.msgs.Odometry.time_usec) } // required .gazebo.msgs.Vector3d position = 2; bool Odometry::has_position() const { return (_has_bits_[0] & 0x00000002u) != 0; } void Odometry::set_has_position() { _has_bits_[0] |= 0x00000002u; } void Odometry::clear_has_position() { _has_bits_[0] &= ~0x00000002u; } void Odometry::clear_position() { if (position_ != NULL) position_->::gazebo::msgs::Vector3d::Clear(); clear_has_position(); } const ::gazebo::msgs::Vector3d& Odometry::position() const { // @@protoc_insertion_point(field_get:nav_msgs.msgs.Odometry.position) return position_ != NULL ? *position_ : *default_instance_->position_; } ::gazebo::msgs::Vector3d* Odometry::mutable_position() { set_has_position(); if (position_ == NULL) { position_ = new ::gazebo::msgs::Vector3d; } // @@protoc_insertion_point(field_mutable:nav_msgs.msgs.Odometry.position) return position_; } ::gazebo::msgs::Vector3d* Odometry::release_position() { // @@protoc_insertion_point(field_release:nav_msgs.msgs.Odometry.position) clear_has_position(); ::gazebo::msgs::Vector3d* temp = position_; position_ = NULL; return temp; } void Odometry::set_allocated_position(::gazebo::msgs::Vector3d* position) { delete position_; position_ = position; if (position) { set_has_position(); } else { clear_has_position(); } // @@protoc_insertion_point(field_set_allocated:nav_msgs.msgs.Odometry.position) } // required .gazebo.msgs.Quaternion orientation = 3; bool Odometry::has_orientation() const { return (_has_bits_[0] & 0x00000004u) != 0; } void Odometry::set_has_orientation() { _has_bits_[0] |= 0x00000004u; } void Odometry::clear_has_orientation() { _has_bits_[0] &= ~0x00000004u; } void Odometry::clear_orientation() { if (orientation_ != NULL) orientation_->::gazebo::msgs::Quaternion::Clear(); clear_has_orientation(); } const ::gazebo::msgs::Quaternion& Odometry::orientation() const { // @@protoc_insertion_point(field_get:nav_msgs.msgs.Odometry.orientation) return orientation_ != NULL ? *orientation_ : *default_instance_->orientation_; } ::gazebo::msgs::Quaternion* Odometry::mutable_orientation() { set_has_orientation(); if (orientation_ == NULL) { orientation_ = new ::gazebo::msgs::Quaternion; } // @@protoc_insertion_point(field_mutable:nav_msgs.msgs.Odometry.orientation) return orientation_; } ::gazebo::msgs::Quaternion* Odometry::release_orientation() { // @@protoc_insertion_point(field_release:nav_msgs.msgs.Odometry.orientation) clear_has_orientation(); ::gazebo::msgs::Quaternion* temp = orientation_; orientation_ = NULL; return temp; } void Odometry::set_allocated_orientation(::gazebo::msgs::Quaternion* orientation) { delete orientation_; orientation_ = orientation; if (orientation) { set_has_orientation(); } else { clear_has_orientation(); } // @@protoc_insertion_point(field_set_allocated:nav_msgs.msgs.Odometry.orientation) } // required .gazebo.msgs.Vector3d linear_velocity = 4; bool Odometry::has_linear_velocity() const { return (_has_bits_[0] & 0x00000008u) != 0; } void Odometry::set_has_linear_velocity() { _has_bits_[0] |= 0x00000008u; } void Odometry::clear_has_linear_velocity() { _has_bits_[0] &= ~0x00000008u; } void Odometry::clear_linear_velocity() { if (linear_velocity_ != NULL) linear_velocity_->::gazebo::msgs::Vector3d::Clear(); clear_has_linear_velocity(); } const ::gazebo::msgs::Vector3d& Odometry::linear_velocity() const { // @@protoc_insertion_point(field_get:nav_msgs.msgs.Odometry.linear_velocity) return linear_velocity_ != NULL ? *linear_velocity_ : *default_instance_->linear_velocity_; } ::gazebo::msgs::Vector3d* Odometry::mutable_linear_velocity() { set_has_linear_velocity(); if (linear_velocity_ == NULL) { linear_velocity_ = new ::gazebo::msgs::Vector3d; } // @@protoc_insertion_point(field_mutable:nav_msgs.msgs.Odometry.linear_velocity) return linear_velocity_; } ::gazebo::msgs::Vector3d* Odometry::release_linear_velocity() { // @@protoc_insertion_point(field_release:nav_msgs.msgs.Odometry.linear_velocity) clear_has_linear_velocity(); ::gazebo::msgs::Vector3d* temp = linear_velocity_; linear_velocity_ = NULL; return temp; } void Odometry::set_allocated_linear_velocity(::gazebo::msgs::Vector3d* linear_velocity) { delete linear_velocity_; linear_velocity_ = linear_velocity; if (linear_velocity) { set_has_linear_velocity(); } else { clear_has_linear_velocity(); } // @@protoc_insertion_point(field_set_allocated:nav_msgs.msgs.Odometry.linear_velocity) } // required .gazebo.msgs.Vector3d angular_velocity = 5; bool Odometry::has_angular_velocity() const { return (_has_bits_[0] & 0x00000010u) != 0; } void Odometry::set_has_angular_velocity() { _has_bits_[0] |= 0x00000010u; } void Odometry::clear_has_angular_velocity() { _has_bits_[0] &= ~0x00000010u; } void Odometry::clear_angular_velocity() { if (angular_velocity_ != NULL) angular_velocity_->::gazebo::msgs::Vector3d::Clear(); clear_has_angular_velocity(); } const ::gazebo::msgs::Vector3d& Odometry::angular_velocity() const { // @@protoc_insertion_point(field_get:nav_msgs.msgs.Odometry.angular_velocity) return angular_velocity_ != NULL ? *angular_velocity_ : *default_instance_->angular_velocity_; } ::gazebo::msgs::Vector3d* Odometry::mutable_angular_velocity() { set_has_angular_velocity(); if (angular_velocity_ == NULL) { angular_velocity_ = new ::gazebo::msgs::Vector3d; } // @@protoc_insertion_point(field_mutable:nav_msgs.msgs.Odometry.angular_velocity) return angular_velocity_; } ::gazebo::msgs::Vector3d* Odometry::release_angular_velocity() { // @@protoc_insertion_point(field_release:nav_msgs.msgs.Odometry.angular_velocity) clear_has_angular_velocity(); ::gazebo::msgs::Vector3d* temp = angular_velocity_; angular_velocity_ = NULL; return temp; } void Odometry::set_allocated_angular_velocity(::gazebo::msgs::Vector3d* angular_velocity) { delete angular_velocity_; angular_velocity_ = angular_velocity; if (angular_velocity) { set_has_angular_velocity(); } else { clear_has_angular_velocity(); } // @@protoc_insertion_point(field_set_allocated:nav_msgs.msgs.Odometry.angular_velocity) } // repeated float pose_covariance = 6 [packed = true]; int Odometry::pose_covariance_size() const { return pose_covariance_.size(); } void Odometry::clear_pose_covariance() { pose_covariance_.Clear(); } float Odometry::pose_covariance(int index) const { // @@protoc_insertion_point(field_get:nav_msgs.msgs.Odometry.pose_covariance) return pose_covariance_.Get(index); } void Odometry::set_pose_covariance(int index, float value) { pose_covariance_.Set(index, value); // @@protoc_insertion_point(field_set:nav_msgs.msgs.Odometry.pose_covariance) } void Odometry::add_pose_covariance(float value) { pose_covariance_.Add(value); // @@protoc_insertion_point(field_add:nav_msgs.msgs.Odometry.pose_covariance) } const ::google::protobuf::RepeatedField< float >& Odometry::pose_covariance() const { // @@protoc_insertion_point(field_list:nav_msgs.msgs.Odometry.pose_covariance) return pose_covariance_; } ::google::protobuf::RepeatedField< float >* Odometry::mutable_pose_covariance() { // @@protoc_insertion_point(field_mutable_list:nav_msgs.msgs.Odometry.pose_covariance) return &pose_covariance_; } // repeated float velocity_covariance = 7 [packed = true]; int Odometry::velocity_covariance_size() const { return velocity_covariance_.size(); } void Odometry::clear_velocity_covariance() { velocity_covariance_.Clear(); } float Odometry::velocity_covariance(int index) const { // @@protoc_insertion_point(field_get:nav_msgs.msgs.Odometry.velocity_covariance) return velocity_covariance_.Get(index); } void Odometry::set_velocity_covariance(int index, float value) { velocity_covariance_.Set(index, value); // @@protoc_insertion_point(field_set:nav_msgs.msgs.Odometry.velocity_covariance) } void Odometry::add_velocity_covariance(float value) { velocity_covariance_.Add(value); // @@protoc_insertion_point(field_add:nav_msgs.msgs.Odometry.velocity_covariance) } const ::google::protobuf::RepeatedField< float >& Odometry::velocity_covariance() const { // @@protoc_insertion_point(field_list:nav_msgs.msgs.Odometry.velocity_covariance) return velocity_covariance_; } ::google::protobuf::RepeatedField< float >* Odometry::mutable_velocity_covariance() { // @@protoc_insertion_point(field_mutable_list:nav_msgs.msgs.Odometry.velocity_covariance) return &velocity_covariance_; } #endif // PROTOBUF_INLINE_NOT_IN_HEADERS // @@protoc_insertion_point(namespace_scope) } // namespace msgs } // namespace nav_msgs // @@protoc_insertion_point(global_scope)
d9c4f32284957b469122014f5a073ff3554b2621
25f97b71289d7839b70650ff4a154ee2fbdf7011
/170522/03_sfinae/02_lower_bound_b.cpp
51f097e86070d56a3e0559bab0d2a3e1a27747cb
[ "MIT" ]
permissive
yeputons/spring-2017-cpp
3d1f6be5d8f5d1d3c81c56d369b823cbac3becee
f590dcf031be6f2920cae5fc9fe147fcac414d3f
refs/heads/master
2021-01-17T16:00:18.158210
2017-06-08T13:15:58
2017-06-08T13:15:58
84,119,719
0
0
null
null
null
null
UTF-8
C++
false
false
1,658
cpp
02_lower_bound_b.cpp
#include <algorithm> #include <iostream> #include <set> #include <vector> #include <type_traits> // https://stackoverflow.com/questions/257288 template<typename Container, typename Arg> struct has_lower_bound { private: template<typename T> static auto foo(int) -> decltype( std::declval<T>().lower_bound(std::declval<Arg>()) // Пробуем вызвать метод , std::true_type() ); template<typename> static std::false_type foo(...); // Приоритет при выборе перегрузки у ... минимален public: using type = decltype(foo<Container>(0)); // typedef decltype(foo<Container>(0)) type; // То же самое static const bool value = type::value; }; template<typename T, typename V> typename std::enable_if<!has_lower_bound<T, V>::value, typename T::const_iterator>::type my_lower_bound(const T &container, const V &value) { std::cout << "Calling global lower_bound\n"; return std::lower_bound(container.begin(), container.end(), value); } template<typename T, typename V> typename std::enable_if<has_lower_bound<T, V>::value, typename T::const_iterator>::type my_lower_bound(const T &container, const V &value) { std::cout << "Calling lower_bound method\n"; return container.lower_bound(value); } int main() { std::set<int> a = { 1, 2, 3, 5, 6, 7 }; std::vector<int> b = { 1, 2, 3, 5, 6, 7 }; std::cout << "set: " << has_lower_bound<std::set<int>, int>::value << "\n"; std::cout << *my_lower_bound(a, 4) << "\n"; std::cout << "vector: " << has_lower_bound<std::vector<int>, int>::value << "\n"; std::cout << *my_lower_bound(b, 4) << "\n"; return 0; }
10ee08724a0b91527df8b1c74faea5ff9b9d79bd
4135cd460b4e62af63679281c400e1d4077f071b
/Test/PngTest.cc
44d22dd8cdb2f605a437fbe668e247518d7a6bc8
[]
no_license
duane/render
ce9ea5bc676edca13bd9b9963cd9c15f7121076e
06390929fa8094e8f70b9c469cc9925cdeb779ad
refs/heads/master
2016-09-06T08:16:29.169505
2013-10-17T18:37:05
2013-10-17T18:37:21
null
0
0
null
null
null
null
UTF-8
C++
false
false
593
cc
PngTest.cc
#include <Raster/Image.h> #include <Raster/PNGDriver.h> #include <stdint.h> #include <stdio.h> #include <stdlib.h> #include <string.h> int main(int argc, char **argv) { const size_t width = 100; const size_t height = 100; const size_t size = width * height * 3; uint8_t *data = (uint8_t*)malloc(size); for (size_t i = 0; i < size; i++) { data[i] = (uint8_t*)rand(); } render::Image image = render::Image(render::RGB, data, width, height); render::PNGDriver driver = render::PNGDriver(); driver.WriteImage(image, "output.png"); return 0; }
7c2400f2a9156643a45fd6b2fc63a66babf6eba0
62e9e89f941b7f70d3c532a063248dfb8d48ae3a
/load_image.cpp
c8a86ace31a7a755fd030ac55f7d2e721ad24bec
[]
no_license
ryanmcmahon1/opencv
f28caa2cda1602fa7bdce318e76b14df5f68de1b
3c9cb7d869e1668d69b7f2cfefa9690cd591d3cd
refs/heads/master
2021-04-03T13:17:22.059795
2020-03-19T15:15:50
2020-03-19T15:15:50
248,357,838
0
0
null
null
null
null
UTF-8
C++
false
false
417
cpp
load_image.cpp
#include <opencv2/core/core.hpp> #include <opencv2/highgui/highgui.hpp> #include <iostream> using namespace cv; using namespace std; int main() { Mat image = imread("beach.jpg", CV_LOAD_IMAGE_COLOR); if (!image.data) { cout << "image can't be loaded" << endl; return -1; } namedWindow("window", CV_WINDOW_AUTOSIZE); imshow("beach", image); imwrite("write_image.jpg", image); waitKey(0); return 0; }
a1bd00270454e7f3c4fecb2beb136da6428d9686
720d5e92b631cbcca07c7c074ebf9ec832765af7
/aos/common/actions/action_test.cc
21da2c7a6f6598adb1d34c0b9db7a21edffed737
[ "BSD-2-Clause" ]
permissive
comran/miranda-dashboard
e1d3dd1ca3c4738b0ed92224bc60cdac4f160f47
54079cb276ef4ee149e931d618b445a618c7c1c0
refs/heads/master
2021-01-12T04:06:24.676407
2017-01-06T01:41:36
2017-01-06T01:41:36
77,504,455
1
0
null
null
null
null
UTF-8
C++
false
false
15,539
cc
action_test.cc
#include <unistd.h> #include <memory> #include <thread> #include "gtest/gtest.h" #include "aos/common/queue.h" #include "aos/common/actions/actor.h" #include "aos/common/actions/actions.h" #include "aos/common/actions/actions.q.h" #include "aos/common/actions/test_action.q.h" #include "aos/common/event.h" #include "aos/testing/test_shm.h" using ::aos::time::Time; namespace aos { namespace common { namespace actions { namespace testing { class TestActorIndex : public aos::common::actions::ActorBase<actions::TestActionQueueGroup> { public: explicit TestActorIndex(actions::TestActionQueueGroup *s) : aos::common::actions::ActorBase<actions::TestActionQueueGroup>(s) {} bool RunAction(const uint32_t &new_index) override { index = new_index; return true; } uint32_t index = 0; }; ::std::unique_ptr< aos::common::actions::TypedAction<actions::TestActionQueueGroup>> MakeTestActionIndex(uint32_t index) { return ::std::unique_ptr< aos::common::actions::TypedAction<actions::TestActionQueueGroup>>( new aos::common::actions::TypedAction<actions::TestActionQueueGroup>( &actions::test_action, index)); } class TestActorNOP : public aos::common::actions::ActorBase<actions::TestActionQueueGroup> { public: explicit TestActorNOP(actions::TestActionQueueGroup *s) : actions::ActorBase<actions::TestActionQueueGroup>(s) {} bool RunAction(const uint32_t &) override { return true; } }; ::std::unique_ptr< aos::common::actions::TypedAction<actions::TestActionQueueGroup>> MakeTestActionNOP() { return MakeTestActionIndex(0); } class TestActorShouldCancel : public aos::common::actions::ActorBase<actions::TestActionQueueGroup> { public: explicit TestActorShouldCancel(actions::TestActionQueueGroup *s) : aos::common::actions::ActorBase<actions::TestActionQueueGroup>(s) {} bool RunAction(const uint32_t &) override { while (!ShouldCancel()) { LOG(FATAL, "NOT CANCELED!!\n"); } return true; } }; ::std::unique_ptr< aos::common::actions::TypedAction<actions::TestActionQueueGroup>> MakeTestActionShouldCancel() { return MakeTestActionIndex(0); } class TestActor2Nop : public aos::common::actions::ActorBase<actions::TestAction2QueueGroup> { public: explicit TestActor2Nop(actions::TestAction2QueueGroup *s) : actions::ActorBase<actions::TestAction2QueueGroup>(s) {} bool RunAction(const actions::MyParams &) { return true; } }; ::std::unique_ptr< aos::common::actions::TypedAction<actions::TestAction2QueueGroup>> MakeTestAction2NOP(const actions::MyParams &params) { return ::std::unique_ptr< aos::common::actions::TypedAction<actions::TestAction2QueueGroup>>( new aos::common::actions::TypedAction<actions::TestAction2QueueGroup>( &actions::test_action2, params)); } class ActionTest : public ::testing::Test { protected: ActionTest() { actions::test_action.goal.Clear(); actions::test_action.status.Clear(); actions::test_action2.goal.Clear(); actions::test_action2.status.Clear(); } virtual ~ActionTest() { actions::test_action.goal.Clear(); actions::test_action.status.Clear(); actions::test_action2.goal.Clear(); actions::test_action2.status.Clear(); } // Bring up and down Core. ::aos::testing::TestSharedMemory my_shm_; ::aos::common::actions::ActionQueue action_queue_; }; // Tests that the the actions exist in a safe state at startup. TEST_F(ActionTest, DoesNothing) { // Tick an empty queue and make sure it was not running. EXPECT_FALSE(action_queue_.Running()); action_queue_.Tick(); EXPECT_FALSE(action_queue_.Running()); } // Tests that starting with an old run message in the goal queue actually works. // This used to result in the client hanging, waiting for a response to its // cancel message. TEST_F(ActionTest, StartWithOldGoal) { ASSERT_TRUE(actions::test_action.goal.MakeWithBuilder().run(971).Send()); TestActorNOP nop_act(&actions::test_action); ASSERT_FALSE(actions::test_action.status.FetchLatest()); ::std::thread init_thread([&nop_act]() { nop_act.Initialize(); }); ::aos::time::SleepFor(::aos::time::Time::InSeconds(0.1)); ASSERT_TRUE(actions::test_action.goal.MakeWithBuilder().run(1).Send()); init_thread.join(); ASSERT_TRUE(actions::test_action.status.FetchLatest()); EXPECT_EQ(0u, actions::test_action.status->running); EXPECT_EQ(0u, actions::test_action.status->last_running); action_queue_.EnqueueAction(MakeTestActionNOP()); nop_act.WaitForActionRequest(); // We started an action and it should be running. EXPECT_TRUE(action_queue_.Running()); action_queue_.CancelAllActions(); action_queue_.Tick(); EXPECT_TRUE(action_queue_.Running()); // Run the action so it can signal completion. nop_act.RunIteration(); action_queue_.Tick(); // Make sure it stopped. EXPECT_FALSE(action_queue_.Running()); } // Tests that the queues are properly configured for testing. Tests that queues // work exactly as used in the tests. TEST_F(ActionTest, QueueCheck) { actions::TestActionQueueGroup *send_side = &actions::test_action; actions::TestActionQueueGroup *recv_side = &actions::test_action; send_side->goal.MakeWithBuilder().run(1).Send(); EXPECT_TRUE(recv_side->goal.FetchLatest()); EXPECT_TRUE(recv_side->goal->run); send_side->goal.MakeWithBuilder().run(0).Send(); EXPECT_TRUE(recv_side->goal.FetchLatest()); EXPECT_FALSE(recv_side->goal->run); send_side->status.MakeWithBuilder().running(5).last_running(6).Send(); EXPECT_TRUE(recv_side->status.FetchLatest()); EXPECT_EQ(5, static_cast<int>(recv_side->status->running)); EXPECT_EQ(6, static_cast<int>(recv_side->status->last_running)); } // Tests that an action starts and stops. TEST_F(ActionTest, ActionQueueWasRunning) { TestActorNOP nop_act(&actions::test_action); // Tick an empty queue and make sure it was not running. action_queue_.Tick(); EXPECT_FALSE(action_queue_.Running()); action_queue_.EnqueueAction(MakeTestActionNOP()); nop_act.WaitForActionRequest(); // We started an action and it should be running. EXPECT_TRUE(action_queue_.Running()); // Tick it and make sure it is still running. action_queue_.Tick(); EXPECT_TRUE(action_queue_.Running()); // Run the action so it can signal completion. nop_act.RunIteration(); action_queue_.Tick(); // Make sure it stopped. EXPECT_FALSE(action_queue_.Running()); } // Tests that we can cancel two actions and have them both stop. TEST_F(ActionTest, ActionQueueCancelAll) { TestActorNOP nop_act(&actions::test_action); // Tick an empty queue and make sure it was not running. action_queue_.Tick(); EXPECT_FALSE(action_queue_.Running()); // Enqueue two actions to test both cancel. We can have an action and a next // action so we want to test that. action_queue_.EnqueueAction(MakeTestActionNOP()); action_queue_.EnqueueAction(MakeTestActionNOP()); nop_act.WaitForActionRequest(); action_queue_.Tick(); // Check that current and next exist. EXPECT_TRUE(action_queue_.GetCurrentActionState(nullptr, nullptr, nullptr, nullptr, nullptr, nullptr)); EXPECT_TRUE(action_queue_.GetNextActionState(nullptr, nullptr, nullptr, nullptr, nullptr, nullptr)); action_queue_.CancelAllActions(); action_queue_.Tick(); // It should still be running as the actor could not have signaled. EXPECT_TRUE(action_queue_.Running()); bool sent_started, sent_cancel, interrupted; EXPECT_TRUE(action_queue_.GetCurrentActionState( nullptr, &sent_started, &sent_cancel, &interrupted, nullptr, nullptr)); EXPECT_TRUE(sent_started); EXPECT_TRUE(sent_cancel); EXPECT_FALSE(interrupted); EXPECT_FALSE(action_queue_.GetNextActionState(nullptr, nullptr, nullptr, nullptr, nullptr, nullptr)); // Run the action so it can signal completion. nop_act.RunIteration(); action_queue_.Tick(); // Make sure it stopped. EXPECT_FALSE(action_queue_.Running()); } // Tests that an action that would block forever stops when canceled. TEST_F(ActionTest, ActionQueueCancelOne) { TestActorShouldCancel cancel_act(&actions::test_action); // Enqueue blocking action. action_queue_.EnqueueAction(MakeTestActionShouldCancel()); cancel_act.WaitForActionRequest(); action_queue_.Tick(); EXPECT_TRUE(action_queue_.Running()); // Tell action to cancel. action_queue_.CancelCurrentAction(); action_queue_.Tick(); // This will block forever on failure. // TODO(ben): prolly a bad way to fail cancel_act.RunIteration(); action_queue_.Tick(); // It should still be running as the actor could not have signalled. EXPECT_FALSE(action_queue_.Running()); } // Tests that an action starts and stops. TEST_F(ActionTest, ActionQueueTwoActions) { TestActorNOP nop_act(&actions::test_action); // Tick an empty queue and make sure it was not running. action_queue_.Tick(); EXPECT_FALSE(action_queue_.Running()); // Enqueue action to be canceled. action_queue_.EnqueueAction(MakeTestActionNOP()); nop_act.WaitForActionRequest(); action_queue_.Tick(); // Should still be running as the actor could not have signalled. EXPECT_TRUE(action_queue_.Running()); // id for the first time run. uint32_t nop_act_id = 0; // Check the internal state and write down id for later use. bool sent_started, sent_cancel, interrupted; EXPECT_TRUE(action_queue_.GetCurrentActionState(nullptr, &sent_started, &sent_cancel, &interrupted, &nop_act_id, nullptr)); EXPECT_TRUE(sent_started); EXPECT_FALSE(sent_cancel); EXPECT_FALSE(interrupted); ASSERT_NE(0u, nop_act_id); // Add the next action which should ensure the first stopped. action_queue_.EnqueueAction(MakeTestActionNOP()); // id for the second run. uint32_t nop_act2_id = 0; // Check the internal state and write down id for later use. EXPECT_TRUE(action_queue_.GetNextActionState(nullptr, &sent_started, &sent_cancel, &interrupted, &nop_act2_id, nullptr)); EXPECT_NE(nop_act_id, nop_act2_id); EXPECT_FALSE(sent_started); EXPECT_FALSE(sent_cancel); EXPECT_FALSE(interrupted); ASSERT_NE(0u, nop_act2_id); action_queue_.Tick(); // Run the action so it can signal completion. nop_act.RunIteration(); action_queue_.Tick(); // Wait for the first id to finish, needed for the correct number of fetches. nop_act.WaitForStop(nop_act_id); // Start the next action on the actor side. nop_act.WaitForActionRequest(); // Check the new action is the right one. uint32_t test_id = 0; EXPECT_TRUE(action_queue_.GetCurrentActionState( nullptr, &sent_started, &sent_cancel, &interrupted, &test_id, nullptr)); EXPECT_TRUE(sent_started); EXPECT_FALSE(sent_cancel); EXPECT_FALSE(interrupted); EXPECT_EQ(nop_act2_id, test_id); // Make sure it is still going. EXPECT_TRUE(action_queue_.Running()); // Run the next action so it can accomplish signal completion. nop_act.RunIteration(); action_queue_.Tick(); nop_act.WaitForStop(nop_act_id); // Make sure it stopped. EXPECT_FALSE(action_queue_.Running()); } // Tests that we do get an index with our goal TEST_F(ActionTest, ActionIndex) { TestActorIndex idx_act(&actions::test_action); // Tick an empty queue and make sure it was not running. action_queue_.Tick(); EXPECT_FALSE(action_queue_.Running()); // Enqueue action to post index. action_queue_.EnqueueAction(MakeTestActionIndex(5)); EXPECT_TRUE(actions::test_action.goal.FetchLatest()); EXPECT_EQ(5u, actions::test_action.goal->params); EXPECT_EQ(0u, idx_act.index); idx_act.WaitForActionRequest(); action_queue_.Tick(); // Check the new action is the right one. uint32_t test_id = 0; EXPECT_TRUE(action_queue_.GetCurrentActionState(nullptr, nullptr, nullptr, nullptr, &test_id, nullptr)); // Run the next action so it can accomplish signal completion. idx_act.RunIteration(); action_queue_.Tick(); idx_act.WaitForStop(test_id); EXPECT_EQ(5u, idx_act.index); // Enqueue action to post index. action_queue_.EnqueueAction(MakeTestActionIndex(3)); EXPECT_TRUE(actions::test_action.goal.FetchLatest()); EXPECT_EQ(3u, actions::test_action.goal->params); // Run the next action so it can accomplish signal completion. idx_act.RunIteration(); action_queue_.Tick(); idx_act.WaitForStop(test_id); EXPECT_EQ(3u, idx_act.index); } // Tests that an action with a structure params works. TEST_F(ActionTest, StructParamType) { TestActor2Nop nop_act(&actions::test_action2); // Tick an empty queue and make sure it was not running. action_queue_.Tick(); EXPECT_FALSE(action_queue_.Running()); actions::MyParams p; p.param1 = 5.0; p.param2 = 7; action_queue_.EnqueueAction(MakeTestAction2NOP(p)); nop_act.WaitForActionRequest(); // We started an action and it should be running. EXPECT_TRUE(action_queue_.Running()); // Tick it and make sure it is still running. action_queue_.Tick(); EXPECT_TRUE(action_queue_.Running()); // Run the action so it can signal completion. nop_act.RunIteration(); action_queue_.Tick(); // Make sure it stopped. EXPECT_FALSE(action_queue_.Running()); } // Tests that cancelling an action before the message confirming it started is // received works. // Situations like this used to lock the action queue up waiting for an action // to report that it successfully cancelled. // This situation is kind of a race condition, but it happens very consistently // when hitting buttons while the robot is in teleop-disabled. To hit the race // condition consistently in the test, there are a couple of Events inserted in // between various things running. TEST_F(ActionTest, CancelBeforeStart) { Event thread_ready, ready_to_start, ready_to_stop; ::std::thread action_thread( [this, &thread_ready, &ready_to_start, &ready_to_stop]() { TestActorNOP nop_act(&actions::test_action); nop_act.Initialize(); thread_ready.Set(); ready_to_start.Wait(); nop_act.WaitForActionRequest(); LOG(DEBUG, "got a request to run\n"); const uint32_t running_id = nop_act.RunIteration(); LOG(DEBUG, "waiting for %" PRIx32 " to be stopped\n", running_id); ready_to_stop.Set(); nop_act.WaitForStop(running_id); }); action_queue_.CancelAllActions(); EXPECT_FALSE(action_queue_.Running()); thread_ready.Wait(); LOG(DEBUG, "starting action\n"); action_queue_.EnqueueAction(MakeTestActionNOP()); action_queue_.Tick(); action_queue_.CancelAllActions(); ready_to_start.Set(); LOG(DEBUG, "started action\n"); EXPECT_TRUE(action_queue_.Running()); ready_to_stop.Wait(); EXPECT_TRUE(action_queue_.Running()); LOG(DEBUG, "action is ready to stop\n"); action_queue_.Tick(); action_queue_.CancelAllActions(); EXPECT_FALSE(action_queue_.Running()); action_queue_.Tick(); action_queue_.CancelAllActions(); ASSERT_FALSE(action_queue_.Running()); action_thread.join(); action_queue_.Tick(); action_queue_.CancelAllActions(); ASSERT_FALSE(action_queue_.Running()); } } // namespace testing } // namespace actions } // namespace common } // namespace aos
9ab4f9adf5f11aad01dc397a302371862a47eeb4
e4833fb04f56ac806d91debc0571804e88512d4e
/2021/01/11/robot.cpp
3c86518daeb5ed0d5efac5020c56441ea98c91d9
[]
no_license
Papillon6814/tracker
f7cca3b2f19c1c63b4bed226abdd7a66f550a1dd
1cd1012865f317b85670da7b3e41364270cf7f2a
refs/heads/main
2023-06-26T18:28:45.089288
2021-07-10T13:26:03
2021-07-10T13:26:03
303,100,401
0
0
null
null
null
null
UTF-8
C++
false
false
663
cpp
robot.cpp
#include <bits/stdc++.h> using namespace std; typedef pair<int, int> pii; int main() { int N; cin >> N; // それぞれ座標と腕の長さを表す vector<int> x(N), l(N); for(int i=0; i<N; i++) { cin >> x[i] >> l[i]; } // robotの始点と終点 vector<pii> p(N); for(int i=0; i<N; i++) { p[i].first = x[i] + l[i]; p[i].second = x[i] - l[i]; } sort(p.begin(), p.end()); int ans = 1; int tail = p[0].first; for(int i=1; i<N; i++) { if(tail <= p[i].second) { ans++; tail = p[i].first; } } cout << ans << endl; return 0; }
13c5f96447c8097385b28aa8d97b973dd5e7bd72
b34d78655cb6bcb96872d8ddfdce837cc184158d
/basics/math2.cpp
d612f57978211e2027d656b8f896a00442791b83
[]
no_license
gabefgonc/learning-cpp
5c050221f1811bc2ca70ff0e6c4edaac709f156f
b08090585843339c2d07e3a5c1a8a914579cc96c
refs/heads/master
2022-12-04T22:38:00.250868
2020-08-18T15:23:44
2020-08-18T15:23:44
284,142,585
0
0
null
null
null
null
UTF-8
C++
false
false
310
cpp
math2.cpp
#include <iostream> using namespace std; int main(){ int n1, n2; n1 = 0; n2 = 10; cout << "n1" << endl; cout << n1 << endl; W n1 += 5; cout << n1 << endl; n1++; cout << n1 << endl; cout << "n2" << endl; cout << n2 << endl; n2 -= 5; cout << n2 << endl; n2--; cout << n2 << endl; }
fa24cc93875702ad073fbfbf1bc66e09cd09d627
ceaf222cb0e08eb2253ae9a83a04fe73b08718f3
/functions.cpp
bb9e4a62b1aeb9223e68bfd3033156a8e2755a9f
[]
no_license
herocodemaster/Image-labeling-tool
bba0c0d8d431a167cf0b1fb7b75f9adf6e90c41f
780d0566ab494adb4ac11a646d67a0cd248acbab
refs/heads/master
2021-01-11T04:16:07.322638
2011-12-15T15:30:32
2011-12-15T15:30:32
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,700
cpp
functions.cpp
/* * functions.cpp * * Created on: Oct 6, 2011 * Author: Gapchich Vladislav */ #include "functions.h" #include <QString> #include <QChar> #include <QDomDocument> #include <QDomNode> #include <QDomText> #include <QPoint> #include <QLine> #include <qmath.h> #include <QDebug> //! Gets number from a string which is located between aFirstStr and aSecondStr /*! * \param[in] aString pointer to the source string containing the number we need * \param[in] aFirstStr a string which is located to the left side of the number * \param[in] aSecondStr a string which is located to the right side of the number * \param[in,out] anOkFlag a pointer to the bool flag indicating the conversation errors * * example: aString contains "0: Poly #0; LabelID: 1; points:..." * aFirstStr "LabelID: " * aSecondStr ";" * function returns 1 */ int getNumFromString( QString *aString, const QString &aFirstStr, const QString &aSecondStr, bool *anOkFlag ) { int numPos = aString->indexOf(aFirstStr) + aFirstStr.size(); if (numPos < 0) { *anOkFlag = 0; return -1; /* NOTREACHED */ } int numLength = -1; for (int i = numPos; i < aString->size(); i++) { if (aSecondStr == aString->at(i)) { numLength = i - numPos; break; } } if (numLength <= 0) { *anOkFlag = 0; return -1; /* NOTREACHED */ } QString numString = aString->mid(numPos, numLength); if (numString.isEmpty()) { *anOkFlag = 0; return -1; /* NOTREACHED */ } bool ok = 0; int num = numString.toInt(&ok, 10); if (!ok) { *anOkFlag = 0; return -1; /* NOTREACHED */ } *anOkFlag = 1; return num; } //! Adds given suffix to the file name /* * example: /home/user/file.dot -> /home/user/file_altered.dot */ QString alterFileName(const QString &aFilename, const QString &aSuffix) { /* altering the name of a new file */ QString newFileName = aFilename; int dotPos = newFileName.lastIndexOf('.'); if (-1 == dotPos) dotPos = newFileName.size(); else newFileName.remove(dotPos, newFileName.size() - dotPos); newFileName.insert(dotPos, aSuffix); return newFileName; } //! Removes the path from filename /*! * example: /home/user/file -> file */ QString removePath(const QString &aFilename) { QString newFileName = aFilename; int slashPos = newFileName.lastIndexOf('/'); newFileName.remove(0, slashPos + 1); return newFileName; } //! Gets path from filename /*! * example: /home/user/file.dot -> /home/user */ QString getPathFromFilename(const QString &aFilename) { QString path = aFilename; int slashPos = path.lastIndexOf('/'); path = path.mid(0, slashPos + 1); return path; } //! Calculates coefficients a,b,c (ax + by + c = 0) for the straight line /*! * \see ImageHolder::posInPolygon(QPoint *aPos,QPolygon *aPoly) * \param[in] p1 first point defining the line * \param[in] p2 second point defining the line * \param[out] a pointer to the coefficient * \param[out] b pointer to the coefficient * \param[out] c pointer to the coefficient */ void calcLineCoeff( const QPoint &p1, const QPoint &p2, int *a, int *b, int *c ) { *a = p1.y() - p2.y(); *b = p2.x() - p1.x(); *c = (p1.x() * p2.y()) - (p2.x() * p1.y()); } //! Returns the distance between point and a line /*! * \see calcLineCoeff( const QPoint &p1, const QPoint &p2, int *a, int *b, int *c ) \see ImageHolder::posInPolygon(QPoint *aPos,QPolygon *aPoly) * \param[in] aLine line * \param[in] aPoint point */ int pointToLineDistance( const QLine &aLine, const QPoint &aPoint ) { int a, b, c; int distance = 0; calcLineCoeff( aLine.p1(), aLine.p2(), &a, &b, &c ); distance = qAbs((a * aPoint.x()) + (b * aPoint.y()) + c); return distance; } /* * */
57c03857b5ae71e8ef55d6441538ee9adbe1ea16
93307b0361c5abb72bfa4059bd3aac9c28d6be6f
/destinationimage.cpp
a2193f475ff2cd6daa4d0a5bfead9acdc2d16b94
[]
no_license
MinjieTao/PoissonImage
3e54850a86d4a9cb4b4dbea97bee324c2c5659a9
458450521ef6effb8896fc1c1a653c15b6881ae2
refs/heads/master
2021-01-02T22:51:51.795097
2012-06-01T06:39:25
2012-06-01T06:39:25
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,125
cpp
destinationimage.cpp
#include "destinationimage.h" DestinationImage::DestinationImage(QWidget *parent) : QWidget(parent) { } void DestinationImage::paintEvent(QPaintEvent *event) { QPainter painter(this); if(!destinationImage.isNull()) painter.drawImage(0,0,destinationImage); if(!subImage.isNull()) painter.drawImage(maskPosition,subImage); } void DestinationImage::loadImage() { QString fileName = QFileDialog::getOpenFileName(this, tr("select source")); if(!fileName.isEmpty()) { destinationImage.load(fileName); } } void DestinationImage::mouseMoveEvent(QMouseEvent *event) { if(event->buttons()&Qt::LeftButton) { QPoint halfMask(subImage.width()/2,subImage.height()/2); maskPosition=event->pos(); maskPosition-=halfMask; } this->update(); } void DestinationImage::mousePressEvent(QMouseEvent *event) { if(event->button()==Qt::LeftButton) { QPoint halfMask(subImage.width()/2,subImage.height()/2); maskPosition=event->pos(); maskPosition-=halfMask; } qDebug()<<maskPosition; this->update(); }
35eabbfc8af3b585d64bee1011df8273e802f50e
c6c8ebb6647556273411c0f9db8cf5fb2a80c618
/Day127.cpp
f689341bb4078336937593df78f362dd769dac89
[]
no_license
dhanendraverma/Daily-Coding-Problem
3d254591880439c48a3963045298c965790ae5be
4bec6bc4fa72d7ab7a21332bdef78a544a9cb3df
refs/heads/master
2023-01-19T15:26:18.508292
2023-01-14T07:27:12
2023-01-14T07:27:12
189,551,929
35
12
null
null
null
null
UTF-8
C++
false
false
2,011
cpp
Day127.cpp
/************************************************************************************************************************************* Good morning! Here's your coding interview problem for today. This problem was asked by Microsoft. Let's represent an integer in a linked list format by having each node represent a digit in the number. The nodes make up the number in reversed order. For example, the following linked list: 1 -> 2 -> 3 -> 4 -> 5 is the number 54321. Given two linked lists in this format, return their sum in the same linked list format. For example, given 9 -> 9 5 -> 2 return 124 (99 + 25) as: 4 -> 2 -> 1 **************************************************************************************************************************************/ #include <iostream> using namespace std; class Node{ public: int data; Node* next; Node(int data){ this->data = data; this->next = NULL; } }; class LinkedList{ public: Node* head; LinkedList(){ this->head = NULL; } void insert(int data){ if(!head) head = new Node(data); else{ Node* temp = new Node(data); temp->next = head; head = temp; } } void printList(){ Node* temp = head; while(temp){ cout<<temp->data<<" "; temp = temp->next; } cout<<endl; } void findSum(Node* a, Node* b){ LinkedList ansList; if(!a) ansList.head = b; else if(!b) ansList.head = a; else{ int s,carry=0; Node *prev=NULL, *temp; while(a || b){ s = carry+(a?a->data:0)+(b?b->data:0); carry = (s>=10)?1:0; s = s%10; temp = new Node(s); if(!prev) ansList.head = temp; else prev->next = temp; prev = temp; if(a) a = a->next; if(b) b = b->next; } if(carry){ temp->next = new Node(carry); } ansList.printList(); } } }; int main() { LinkedList ll1, ll2; ll1.insert(9); ll1.insert(9); ll1.insert(1); ll1.printList(); ll2.insert(2); ll2.insert(5); ll2.insert(9); ll2.printList(); ll1.findSum(ll1.head, ll2.head); return 0; }
710363829f5b7c9c42527520a833204d26fd5129
e5edc6c16ed134b48293668ed07cf5d8d768b386
/Ray.hpp
fc89c56c2f4afd23c8bc6ef25bccbc24963105fa
[ "LicenseRef-scancode-public-domain", "LicenseRef-scancode-warranty-disclaimer" ]
permissive
fcccode/XnaMathWrapper
e7d6f6247c03ce63fdf6d893c9160d0ea2113465
ab846169d78fbf935e873a5fc8401cef85623bff
refs/heads/master
2020-04-09T18:40:42.479336
2015-04-13T22:06:03
2015-04-13T22:06:03
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,495
hpp
Ray.hpp
#pragma once #ifndef __MATHS_RAY_HPP__ #define __MATHS_RAY_HPP__ #include "Vector3.hpp" namespace Math { class Ray { private: // The values are private because we want to keep the direction vector normalised Vector3 mOrigin; Vector3 mDirection; public: Ray() : mDirection(Vector3::UNIT_Z) { } Ray(const Vector3& origin, const Vector3& direction) : mOrigin(origin), mDirection(direction) { mDirection.normalise(); } Ray(const Ray& ray) : mOrigin(ray.mOrigin), mDirection(ray.mDirection) { } Ray& operator = (const Ray& ray) { mOrigin = ray.mOrigin; mDirection = ray.mDirection; return *this; } bool operator == (const Ray& ray) const { return mOrigin == ray.mOrigin && mDirection == ray.mDirection; } bool operator != (const Ray& ray) const { return mOrigin != ray.mOrigin || mDirection != ray.mDirection; } Vector3 point_at(float t) const { return mOrigin + mDirection * t; } Vector3 operator * (float t) const { return mOrigin + mDirection * t; } friend Vector3 operator * (float t, const Ray& ray) { return ray.mOrigin + ray.mDirection * t; } void origin(const Vector3& o) { mOrigin = o; } const Vector3& origin() const { return mOrigin; } void direction(const Vector3& d) { mDirection = d; mDirection.normalise(); } const Vector3& direction() const { return mDirection; } }; } // namespace Math #endif // __MATHS_RAY_HPP__
b20f52ebfd39cd7df870dd6aee5a26a7e5c94989
0015079f91ab1e823cca7244d9e7338914609f6b
/rnn.cpp
c92f8c96b0c60707a41ee0c3da7663d18d19eacf
[]
no_license
dongzwhitsz/hls-demo
a23aa518986693726dd07058bf4b9d819f8909ae
60e0e4f0c57a2063d0516d40286f755f47b128f9
refs/heads/master
2020-06-20T05:51:55.925172
2019-09-03T11:19:57
2019-09-03T11:19:57
197,015,437
0
0
null
null
null
null
UTF-8
C++
false
false
9,742
cpp
rnn.cpp
//#include <iostream> //#include <cmath> //using namespace std; #include "./weight/dense_bias.h" #include "./weight/dense_kernel.h" #include "./weight/lstm_kernel_o.h" #include "./weight/lstm_kernel_c.h" #include "./weight/lstm_kernel_f.h" #include "./weight/lstm_kernel_i.h" #include "./weight/lstm_bias_c.h" #include "./weight/lstm_bias_f.h" #include "./weight/lstm_bias_i.h" #include "./weight/lstm_bias_o.h" #include "./weight/lstm_recurrent_kernel_c.h" #include "./weight/lstm_recurrent_kernel_f.h" #include "./weight/lstm_recurrent_kernel_i.h" #include "./weight/lstm_recurrent_kernel_o.h" #include "./weight/softmax_bias.h" #include "./weight/softmax_kernel.h" #include "./img/0_5.h" #include "./img/1_0.h" #include "./img/2_4.h" #include "./img/0_5.h" #include "./img/1_0.h" #include "./img/3_1.h" #include "./img/4_9.h" #include "./img/5_2.h" #include "./img/6_1.h" #include "./img/7_3.h" #include "./img/8_1.h" #include "./img/9_4.h" typedef float data_t; #define IMG_S 28 #define NUM_UNITS 256 #define DENSE_UNITS 256 // 暴力枚举网络各处参数 /************* LSTM params ****************/ data_t c[NUM_UNITS] = {0}; data_t h[NUM_UNITS] = {0}; data_t lstm_bias_c[NUM_UNITS] = LSTM_BIAS_C; data_t lstm_bias_f[NUM_UNITS] = LSTM_BIAS_F; data_t lstm_bias_i[NUM_UNITS] = LSTM_BIAS_I; data_t lstm_bias_o[NUM_UNITS] = LSTM_BIAS_O; data_t lstm_kernel_c[IMG_S][NUM_UNITS] = W_LSTM_KERNEL_C; data_t lstm_kernel_f[IMG_S][NUM_UNITS] = W_LSTM_KERNEL_F; data_t lstm_kernel_i[IMG_S][NUM_UNITS] = W_LSTM_KERNEL_I; data_t lstm_kernel_o[IMG_S][NUM_UNITS] = W_LSTM_KERNEL_O; data_t lstm_recurrent_kernel_c[NUM_UNITS][NUM_UNITS] = W_LSTM_RECURRENT_KERNEL_C; data_t lstm_recurrent_kernel_f[NUM_UNITS][NUM_UNITS] = W_LSTM_RECURRENT_KERNEL_F; data_t lstm_recurrent_kernel_i[NUM_UNITS][NUM_UNITS] = W_LSTM_RECURRENT_KERNEL_I; data_t lstm_recurrent_kernel_o[NUM_UNITS][NUM_UNITS] = W_LSTM_RECURRENT_KERNEL_O; /************* dense params ****************/ data_t dense_bias[DENSE_UNITS] = W_DENSE_BIAS; data_t dense_kernel[NUM_UNITS][DENSE_UNITS] = W_DENSE_KERNEL; // data_t dense_input[DENSE_UNITS] = {0}; data_t dense_output[DENSE_UNITS] = {0}; /************* softmax params ****************/ data_t softmax_bias[10] = W_SOFTMAX_BIAS; data_t softmax_kernel[NUM_UNITS][10] = W_SOFTMAX_KERNEL; // data_t softmax_input[10] = {0}; data_t softmax_output[10] = {0}; /******************** function prototype declare *********************************** */ void img_preprocess(data_t img[IMG_S][IMG_S]); void lstm_forward(data_t img[IMG_S][IMG_S]); void lstm_forward_once(data_t img_line[IMG_S]); void dense_forward(data_t h[NUM_UNITS]); void softmax_forward(data_t dense_output[DENSE_UNITS]); /*********************** function realizaton ************************************* */ void top(data_t img[IMG_S][IMG_S], data_t output[10]) { // 首先预处理图片 img_preprocess(img); lstm_forward(img); dense_forward(h); softmax_forward(dense_output); // output the result of the network; for(int i = 0; i < 10; ++i) { output[i] = softmax_output[i]; } } //int main() //{ // // test bench for the top function in g++; // // data_t arr[28][28] = IMG_0_5; // // data_t arr[28][28] = IMG_1_0; // // data_t arr[28][28] = IMG_2_4; // // data_t arr[28][28] = IMG_3_1; // // data_t arr[28][28] = IMG_4_9; // data_t arr[28][28] = IMG_5_2; // // data_t arr[28][28] = IMG_6_1; // // data_t arr[28][28] = IMG_7_3; // // data_t arr[28][28] = IMG_8_1; // // data_t arr[28][28] = IMG_9_4; // data_t output[10] = {0}; // top(arr, output); // // for(int i = 0; i < 10; i ++) // { // cout << i << ": " << output[i] << endl; // } // cout << endl; // return 0; //} void img_preprocess(data_t img[IMG_S][IMG_S]) { for(int i = 0; i < IMG_S; i++) { for(int j = 0; j < IMG_S; j++) { img[i][j] = img[i][j] / 128.0 - 1; } } } void lstm_forward(data_t img[IMG_S][IMG_S]) { for(int i = 0; i < NUM_UNITS; ++i) { c[i] = 0; h[i] = 0; } for(int i = 0; i < IMG_S; ++i) { lstm_forward_once(img[i]); } } void lstm_forward_once(data_t img_line[IMG_S]) { /************** forget gate *************** */ data_t arr1[NUM_UNITS] = {0}; // img_line 与 权重作用 for(int i = 0; i < NUM_UNITS; ++i) { for(int j = 0; j < IMG_S; ++j) { arr1[i] += img_line[j] * lstm_kernel_f[j][i]; } } data_t arr2[NUM_UNITS] = {0}; // h matmul with weights for(int i = 0; i < NUM_UNITS; ++i) { for(int j = 0; j < NUM_UNITS; ++j) { arr2[i] += h[j] * lstm_recurrent_kernel_f[j][i]; } } data_t arr3[NUM_UNITS] = {0}; // store the hard sigmoid result in the arr3 for(int i = 0; i < NUM_UNITS; ++i) { arr3[i] = arr1[i] + arr2[i]+ lstm_bias_f[i]; // arr3 add the bias arr3[i] = 0.2 * arr3[i] + 0.5; if (arr3[i] >2.5) arr3[i] = 1; else if (arr3[i] < -2.5) arr3[i] = 0; } /************** input gate *************** */ data_t arr4[NUM_UNITS] = {0}; // img_line 与 权重作用 for(int i = 0; i < NUM_UNITS; ++i) { for(int j = 0; j < IMG_S; ++j) { arr4[i] += img_line[j] * lstm_kernel_i[j][i]; } } data_t arr5[NUM_UNITS] = {0}; // h matmul with weights for(int i = 0; i < NUM_UNITS; ++i) { for(int j = 0; j < NUM_UNITS; ++j) { arr5[i] += h[j] * lstm_recurrent_kernel_i[j][i]; } } data_t arr6[NUM_UNITS] = {0}; // store the hard sigmoid result in the arr6 for(int i = 0; i < NUM_UNITS; ++i) { // add the bias to the arr6 arr6[i] = arr4[i] + arr5[i] + lstm_bias_i[i]; arr6[i] = 0.2 * arr6[i] + 0.5; if (arr6[i] > 2.5) arr6[i] = 1; else if (arr6[i] < -2.5) arr6[i] = 0; } /************** candidate gate *************** */ data_t arr7[NUM_UNITS] = {0}; // img_line 与 权重作用 for(int i = 0; i < NUM_UNITS; ++i) { for(int j = 0; j < IMG_S; ++j) { arr7[i] += img_line[j] * lstm_kernel_c[j][i]; } } data_t arr8[NUM_UNITS] = {0}; // h matmul with weights for(int i = 0; i < NUM_UNITS; ++i) { for(int j = 0; j < NUM_UNITS; ++j) { arr8[i] += h[j] * lstm_recurrent_kernel_c[j][i]; } } data_t arr9[NUM_UNITS] = {0}; // store the hard sigmoid result in the arr9 for(int i = 0; i < NUM_UNITS; ++i) { // add the bias to the arr9 arr9[i] = arr7[i] + arr8[i] + lstm_bias_c[i]; // arr9[i] = tanh(arr9[i]); arr9[i] = 0.8 * arr9[i]; if (arr9[i] > 1) arr9[i] = 1; else if (arr9[i] < -1) arr9[i] = -1; } /************** output gate *************** */ data_t arr10[NUM_UNITS] = {0}; // img_line 与 权重作用 for(int i = 0; i < NUM_UNITS; ++i) { for(int j = 0; j < IMG_S; ++j) { arr10[i] += img_line[j] * lstm_kernel_o[j][i]; } } data_t arr11[NUM_UNITS] = {0}; // h matmul with weights for(int i = 0; i < NUM_UNITS; ++i) { for(int j = 0; j < NUM_UNITS; ++j) { arr11[i] += h[j] * lstm_recurrent_kernel_o[j][i]; } } data_t arr12[NUM_UNITS] = {0}; // store the hard sigmoid result in the arr12 for(int i = 0; i < NUM_UNITS; ++i) { arr12[i] = arr10[i] + arr11[i] + lstm_bias_o[i]; // add the bias to the arr12 arr12[i] = arr12[i] * 0.2 + 0.5; if ( arr12[i] > 2.5) { arr12[i] = 1; }else if( arr12[i] < -2.5) { arr12[i] = 0; } // arr12[i] = 0.8 * arr12[i]; // if (arr12[i] > 1) // arr12[i] = 1; // else if (arr12[i] < -1) // arr12[i] = -1; } // get the c and h for(int i = 0; i < NUM_UNITS; ++i) { c[i] = c[i] * arr3[i]; } for(int i = 0; i < NUM_UNITS; ++i) { c[i] = c[i] + arr6[i] * arr9[i]; } data_t arr13[NUM_UNITS] = {0}; for(int i = 0; i < NUM_UNITS; ++i) { // arr13[i] = tanh(c[i]); arr13[i] = c[i] * 0.8; if(arr13[i] > 1) { arr13[i] = 1; }else if(arr13[i] < -1) { arr13[i] = -1; } } for(int i = 0; i < NUM_UNITS; ++i) { h[i] = arr13[i] * arr12[i]; } } void dense_forward(data_t h[NUM_UNITS]) { for(int i = 0; i < DENSE_UNITS; ++i) { dense_output[i] = 0; for(int j = 0; j < NUM_UNITS; ++j) dense_output[i] += dense_kernel[j][i] * h[j]; } // add bias for(int i = 0; i < DENSE_UNITS; ++i) { dense_output[i] += dense_bias[i]; // relu if(dense_output[i] < 0) { dense_output[i] = 0; } } } void softmax_forward(data_t dense_output[DENSE_UNITS]) { for(int i = 0; i < 10; ++i) { softmax_output[i] = 0; for(int j = 0; j < DENSE_UNITS; ++j) softmax_output[i] += softmax_kernel[j][i] * dense_output[j]; } // add bias for(int i = 0; i < 10; ++i) { softmax_output[i] += softmax_bias[i]; } // don't need to do the exp in forward step; // data_t s = 0; // for(int i = 0 ; i < 10; i ++) // { // softmax_output[i] = exp(softmax_output[i]); // s += softmax_output[i]; // } // for(int i = 0; i < 10; i ++) // { // softmax_output[i] = softmax_output[i] / s; // } }
01e22c9aeb76ba9be9d8d38bc8256014a212ae9f
91dd40450b8f251e96b70da424e3c5b82d3493ba
/decode_the_mad_man.cpp
865f5ff2d84c175f4b3ba94db265280c371c9b9e
[]
no_license
danielecappuccio/UVa-online-judge
3cfa2cdafeb5deec9048483964dbe7969b719650
b3a6c65a56aad98cd5e86325cd1f29082892b86f
refs/heads/master
2021-07-06T09:56:05.257214
2017-10-01T11:51:28
2017-10-01T11:51:28
85,356,118
1
1
null
null
null
null
UTF-8
C++
false
false
1,138
cpp
decode_the_mad_man.cpp
/* * Competitive Programming * * @author Daniele Cappuccio * @link (https://github.com/daniele-cappuccio/UVa-online-judge) * @license MIT License (https://opensource.org/licenses/MIT) */ #include <iostream> #include <string> using namespace std; int main(){ ios::sync_with_stdio(false); int i, j; char keyboard[] = {'q', 'w', 'e', 'r', 't', 'y', 'u', 'i', 'o', 'p', '[', ']', 92, 'a', 's', 'd', 'f', 'g', 'h', 'j', 'k', 'l', ';', 39, 'z', 'x', 'c', 'v', 'b', 'n', 'm', ',', '.', '/', '`', '1', '2', '3', '4', '5', '6', '7', '8', '9', '0', '-', '='} ; string str; while (getline(cin, str)){ for (i = 0; i < str.size(); ++i){ if (str[i] == ' ' || str[i] == '\n') cout << str[i]; else { for (j = 2; j < 47; ++j){ if (tolower(str[i]) == keyboard[j]){ cout << keyboard[j - 2]; break; } } } } cout << endl; } return 0; }
11f78f37e6d927d15aeb8c2aa9d6fa8534ea17bb
a3d6556180e74af7b555f8d47d3fea55b94bcbda
/chrome/browser/ash/app_list/chrome_app_list_item_browsertest.cc
6e2c297891d9627a5f800c08629c22fd50d7d369
[ "BSD-3-Clause" ]
permissive
chromium/chromium
aaa9eda10115b50b0616d2f1aed5ef35d1d779d6
a401d6cf4f7bf0e2d2e964c512ebb923c3d8832c
refs/heads/main
2023-08-24T00:35:12.585945
2023-08-23T22:01:11
2023-08-23T22:01:11
120,360,765
17,408
7,102
BSD-3-Clause
2023-09-10T23:44:27
2018-02-05T20:55:32
null
UTF-8
C++
false
false
6,070
cc
chrome_app_list_item_browsertest.cc
// Copyright 2021 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/ash/app_list/chrome_app_list_item.h" #include <vector> #include "ash/constants/ash_features.h" #include "ash/public/cpp/accelerators.h" #include "ash/public/cpp/test/app_list_test_api.h" #include "base/memory/raw_ptr.h" #include "base/strings/stringprintf.h" #include "chrome/browser/ash/app_list/app_list_client_impl.h" #include "chrome/browser/ash/app_list/app_list_model_updater.h" #include "chrome/browser/ash/app_list/test/chrome_app_list_test_support.h" #include "chrome/browser/profiles/profile_manager.h" #include "chrome/test/base/in_process_browser_test.h" #include "content/public/test/browser_test.h" #include "ui/gfx/image/image_skia.h" namespace { // An ImageSkiaSource that counts the number of times it is asked for image // representations. class TestChromeAppListItem : public ChromeAppListItem { public: TestChromeAppListItem(Profile* profile, const std::string& app_id, AppListModelUpdater* model_updater) : ChromeAppListItem(profile, app_id, model_updater) {} ~TestChromeAppListItem() override = default; // ChromeAppListItem: void LoadIcon() override { ++count_; } int GetLoadIconCountAndReset() { int current_count = count_; count_ = 0; return current_count; } private: int count_ = 0; }; } // namespace class ChromeAppListItemTest : public InProcessBrowserTest { public: ChromeAppListItemTest() = default; ~ChromeAppListItemTest() override = default; // InProcessBrowserTest void SetUpOnMainThread() override { InProcessBrowserTest::SetUpOnMainThread(); client_ = AppListClientImpl::GetInstance(); ASSERT_TRUE(client_); client_->UpdateProfile(); model_updater_ = test::GetModelUpdater(client_); } void ShowLauncherAppsGrid() { EXPECT_FALSE(client_->GetAppListWindow()); ash::AcceleratorController::Get()->PerformActionIfEnabled( ash::AcceleratorAction::kToggleAppList, {}); ash::AppListTestApi().WaitForBubbleWindow( /*wait_for_opening_animation=*/false); EXPECT_TRUE(client_->GetAppListWindow()); } Profile* profile() { return ProfileManager::GetActiveUserProfile(); } protected: raw_ptr<AppListClientImpl, DanglingUntriaged | ExperimentalAsh> client_ = nullptr; raw_ptr<AppListModelUpdater, DanglingUntriaged | ExperimentalAsh> model_updater_ = nullptr; }; // Tests that app icon load is deferred until UI is shown. IN_PROC_BROWSER_TEST_F(ChromeAppListItemTest, IconLoadAfterShowingUI) { constexpr char kAppId[] = "FakeAppId"; constexpr char kAppName[] = "FakeApp"; auto app_item_ptr = std::make_unique<TestChromeAppListItem>(profile(), kAppId, model_updater_); TestChromeAppListItem* app_item = app_item_ptr.get(); model_updater_->AddItem(std::move(app_item_ptr)); model_updater_->SetItemName(app_item->id(), kAppName); // No icon loading on creating an app item without UI. EXPECT_EQ(0, app_item->GetLoadIconCountAndReset()); ShowLauncherAppsGrid(); // Icon loading is triggered after showing the launcher. EXPECT_GT(app_item->GetLoadIconCountAndReset(), 0); } // Tests that icon loading is synchronous when UI is visible. IN_PROC_BROWSER_TEST_F(ChromeAppListItemTest, IconLoadWithUI) { ShowLauncherAppsGrid(); constexpr char kAppId[] = "FakeAppId"; constexpr char kAppName[] = "FakeApp"; auto app_item_ptr = std::make_unique<TestChromeAppListItem>(profile(), kAppId, model_updater_); TestChromeAppListItem* app_item = app_item_ptr.get(); model_updater_->AddItem(std::move(app_item_ptr)); model_updater_->SetItemName(app_item->id(), kAppName); // Icon load happens synchronously when UI is visible. EXPECT_GT(app_item->GetLoadIconCountAndReset(), 0); } // Combination of IconLoadAfterShowingUI and IconLoadWithUI but for apps inside // a folder. IN_PROC_BROWSER_TEST_F(ChromeAppListItemTest, FolderIconLoad) { std::vector<TestChromeAppListItem*> apps; // A folder should exist before adding children. constexpr char kFakeFolderId[] = "FakeFolder"; auto folder_item_ptr = std::make_unique<TestChromeAppListItem>( profile(), kFakeFolderId, model_updater_); folder_item_ptr->SetChromeIsFolder(true); folder_item_ptr->SetChromePosition( syncer::StringOrdinal::CreateInitialOrdinal()); model_updater_->AddItem(std::move(folder_item_ptr)); for (int i = 0; i < 2; ++i) { std::string app_id = base::StringPrintf("FakeAppId_%d", i); std::string app_name = base::StringPrintf("FakeApp_%d", i); auto app_item_ptr = std::make_unique<TestChromeAppListItem>( profile(), app_id, model_updater_); TestChromeAppListItem* app_item = app_item_ptr.get(); apps.push_back(app_item); model_updater_->AddAppItemToFolder(std::move(app_item_ptr), kFakeFolderId, /*add_from_local=*/true); model_updater_->SetItemName(app_item->id(), app_name); // No icon loading on creating an app item. EXPECT_EQ(0, app_item->GetLoadIconCountAndReset()); } ShowLauncherAppsGrid(); // Icon loading is triggered after showing the launcher. for (auto* app_item : apps) { SCOPED_TRACE(testing::Message() << "app_id=" << app_item->id()); EXPECT_GT(app_item->GetLoadIconCountAndReset(), 0); } // Adds a new item to folder while UI is visible. auto app_item_ptr = std::make_unique<TestChromeAppListItem>( profile(), "AnotherAppId", model_updater_); TestChromeAppListItem* app_item = app_item_ptr.get(); model_updater_->AddAppItemToFolder(std::move(app_item_ptr), kFakeFolderId, /*add_from_local=*/true); model_updater_->SetItemName(app_item->id(), "AnotherApp"); // Icon load happens synchronously when UI is visible. EXPECT_GT(app_item->GetLoadIconCountAndReset(), 0); }
fc2609a1ebad302741e647b557c104e60a2944ed
355af27bc0929e1f433f3db53c25962e10a60d84
/step/math/CountStep.h
1442ef270773f6d391c577cd3f9e1657874a584a
[ "Apache-2.0" ]
permissive
bgamer50/Gremlin-
698d22fb81e6a07c81cda5d2f0406eb0b2252674
9c917b8a3baac13865fdb932ece082533e70082b
refs/heads/main
2023-08-15T23:21:59.379924
2022-10-12T02:55:49
2022-10-12T02:55:49
173,864,939
23
3
Apache-2.0
2022-06-12T02:37:00
2019-03-05T03:19:15
C++
UTF-8
C++
false
false
523
h
CountStep.h
#ifndef COUNT_STEP_H #define COUNT_STEP_H #define COUNT_STEP 0x61 #include "step/TraversalStep.h" #include <functional> class CountStep : public TraversalStep { public: CountStep() : TraversalStep(true, MAP, COUNT_STEP) { // empty constructor } virtual void apply(GraphTraversal* traversal, TraverserSet& traversers) { size_t size = traversers.size(); traversers.clear(); traversers.push_back(Traverser(size)); } }; #endif
6f1bff4abb5683474ecb5903569fedb0c8a27999
8d5359051852e8f191fa0e71fed62e8fc8f06f5e
/Programs/Copy of testing copy v6/SimuBoundaryTable.cpp
d3f1a0ceeca6d31e492526495d53684f8c33b77f
[]
no_license
practisedaybyday/MSc-Thesis
0289a279048a7501c512a51b4ec1d92e198c7923
f9ca80b6c64e6c7cfa12f4ce5866c4e94bd569c2
refs/heads/master
2020-04-16T23:49:21.413706
2017-10-12T16:47:22
2017-10-12T16:47:22
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,352
cpp
SimuBoundaryTable.cpp
// SimuBoundaryTable.cpp: implementation of the CSimuBoundaryTable class. // ////////////////////////////////////////////////////////////////////// #include "stdafx.h" #include "SimuFlexApp.h" #include "SimuBoundaryTable.h" #ifdef _DEBUG #undef THIS_FILE static char THIS_FILE[]=__FILE__; #define new DEBUG_NEW #endif ////////////////////////////////////////////////////////////////////// // Construction/Destruction ////////////////////////////////////////////////////////////////////// CSimuBoundaryTable::CSimuBoundaryTable() { m_bdryType = TABLE; } CSimuBoundaryTable::CSimuBoundaryTable(CVector3D* tblCenter, SimuValue tblSideLen) { m_bdryType = TABLE; if (tblCenter != NULL) m_tblCenter.SetValue(tblCenter); else m_tblCenter.SetValue((SimuValue)0); m_tblSideLen = tblSideLen; ComputeTableVariables(); } CSimuBoundaryTable::~CSimuBoundaryTable() { } void CSimuBoundaryTable::DrawBoundary() { glPushAttrib(GL_ALL_ATTRIB_BITS); SimuColor3v(m_bdryColor->v); glBegin(GL_QUADS); SimuNormal3d(0, 1, 0); SimuVertex3d(m_tblMinX, m_tblCenter[Y], m_tblMinZ); SimuVertex3d(m_tblMinX, m_tblCenter[Y], m_tblMaxZ); SimuVertex3d(m_tblMaxX, m_tblCenter[Y], m_tblMaxZ); SimuVertex3d(m_tblMaxX, m_tblCenter[Y], m_tblMinZ); glEnd(); glPopAttrib(); } void CSimuBoundaryTable::ExportBoundaryData(FILE* fp) { fprintf(fp, "#declare m_tblSideLen = %f;\n", m_tblSideLen); fprintf(fp, "#declare m_tblCenter_Level = %f;\n", m_tblCenter[Y]); } void CSimuBoundaryTable::ImportBoundaryData(FILE* fp) { float tmpFloat; fscanf(fp, "#declare m_tblSideLen = %f;\n", &tmpFloat); m_tblSideLen = tmpFloat; fscanf(fp, "#declare m_tblCenter_Level = %f;\n", &tmpFloat); m_tblCenter[Y] = tmpFloat; ComputeTableVariables(); } bool CSimuBoundaryTable::EnforceBoundaryConstraint(CVirtualPrtl* pPrtl, SimuValue timeStep) { CVector3D* pos = pPrtl->m_vpPos; // prevent from penetrating table SimuValue tmpDist = pos->v[Y] - m_tblCenter[Y]; if (tmpDist < 0) { SimuValue tmpX = pos->v[X] - m_tblCenter[X]; if (tmpX < m_tblMinX) return false; if (tmpX > m_tblMaxX) return false; SimuValue tmpZ = pos->v[Z] - m_tblCenter[Z]; if (tmpZ < m_tblMinZ) return false; if (tmpZ > m_tblMaxZ) return false; if (fabs(tmpDist) > m_tblThickness) return false; pos->v[Y] += -tmpDist*(1+m_bdryDistDumpingRate); if (pPrtl->m_vpVel->v[Y] < 0) pPrtl->m_vpVel->v[Y] *= -m_bdryEnergyDumpingRate; pPrtl->m_vpVel->v[X] *= m_bdryFrictionRate; pPrtl->m_vpVel->v[Z] *= m_bdryFrictionRate; return true; } return false; } bool CSimuBoundaryTable::PosBreakBoundary(CVector3D* pPos) { // check if particle is under the table SimuValue tmpDist = pPos->v[Y] - m_tblCenter[Y]; if (tmpDist < 0) { if (pPos->v[X] < m_tblMinX) return true; if (pPos->v[X] > m_tblMaxX) return true; if (pPos->v[Z] < m_tblMinZ) return true; if (pPos->v[Z] > m_tblMaxZ) return true; return false; } return true; } void CSimuBoundaryTable::ComputeTableVariables() { m_tblHalfSideLen = m_tblSideLen/2; m_tblThickness = CSimuManager::m_prtlDistance*2; m_tblMinX = m_tblCenter[X] - m_tblHalfSideLen; m_tblMaxX = m_tblCenter[X] + m_tblHalfSideLen; m_tblMinZ = m_tblCenter[Z] - m_tblHalfSideLen; m_tblMaxZ = m_tblCenter[Z] + m_tblHalfSideLen; }
9d295bce6bc085708af04cfd14c0533ce385a69d
244769435c3954c1f37efdccca3ed0d714f80091
/Fraction/FractionClass.cpp
6ab2705634c10129b19309c01ecaaee6ae5961bf
[]
no_license
Annerley/FractionExam
2ef8f5566b59fa651156cf8eed732b325bf71a71
2793eec2f47b78c9c7a0e49547bd71f6765b7452
refs/heads/main
2023-02-05T02:27:50.448457
2020-12-28T08:21:05
2020-12-28T08:21:05
324,936,224
0
0
null
null
null
null
UTF-8
C++
false
false
27
cpp
FractionClass.cpp
#include "FractionClass.h"
aa8567b4079b8f1feb4522c990b2a6bccad45f4d
33f77c32fb16283501d950b6fc6b43a07914f32e
/autopilot/Autopilot/hw/gps/GpsTime.hpp
434c13ef90d107d8e9ad451ffbfde8ae2a3f56dc
[]
no_license
CLUBMODELISMECEADSTOULOUSE/autopilot
26b79d6a2a632f08989a5528e82f553616617646
a6ffae2f8a86fbc79e636ddd5173af104e1af9cd
refs/heads/master
2021-01-21T00:59:06.271128
2015-10-25T09:31:54
2015-10-25T09:31:54
34,409,237
1
0
null
null
null
null
ISO-8859-2
C++
false
false
250
hpp
GpsTime.hpp
/* * GpsTime.hpp * * Created on: 24 déc. 2013 * Author: Robotique */ #ifndef GPSTIME_HPP_ #define GPSTIME_HPP_ namespace hw { class GpsTime { public: GpsTime(); virtual ~GpsTime(); }; } /* namespace hw */ #endif /* GPSTIME_HPP_ */
c66e59af4b448caeda0bf1e4bb4aa747385d7d91
09461b035c15d1a01af2429ce4ef23895c44828a
/ripples/src/ofApp.cpp
178450e225d11381a488bb81e96868212c5f855f
[ "MIT" ]
permissive
graham-riches/sketches
7d5ca86b2bc21c4c59106683294028096162512e
026be227193e84859aedcd350e7fcfc4b87e43d2
refs/heads/main
2023-08-25T13:50:45.020875
2021-10-30T18:52:45
2021-10-30T18:52:45
337,732,865
0
0
null
null
null
null
UTF-8
C++
false
false
3,881
cpp
ofApp.cpp
/** * \file ofApp.cpp * \author Graham Riches (graham.riches@live.com) * \brief * \version 0.1 * \date 2021-02-16 * * @copyright Copyright (c) 2021 * */ /********************************** Includes *******************************************/ #include "ofApp.h" #include "ripple.hpp" #include <filesystem> #include <cmath> #include <cstdlib> /********************************** Function Definitions *******************************************/ /** * \brief generic function to turn calculate the radius of a cartesian point * * \tparam T type of the points x and y * \param x coordinate * \param y coordinate * \retval return type deduced based on arguments */ template <typename T> auto calculate_radius(T&& x, T&& y) { return std::sqrt(std::pow(x, 2.0) + std::pow(y, 2.0)); } /** * \brief Construct a new application::application object * * \param width width of the wireframe in grid tiles * \param height height of the wireframe in grid tiles */ application::application(int width, int height) : _width(width) , _height(height) { _x_origin = width / 2; _y_origin = height / 2; _image.allocate(height, width, OF_IMAGE_GRAYSCALE); _plane.set(1200, 900, width, height, OF_PRIMITIVE_TRIANGLES); _plane.mapTexCoordsFromTexture(_image.getTexture()); } /** * \brief setup function to load shaders and other objects */ void application::setup() { auto path = std::filesystem::current_path(); auto parent_path = path.parent_path(); std::filesystem::path shader_path = parent_path / std::filesystem::path{"shaders"}; _displacement_shader.load(shader_path / std::filesystem::path{"shadersGL3/shader"}); } /** * \brief update method to draw a new frame */ void application::update() { auto time = ofGetElapsedTimef(); ofPixels& pixels = _image.getPixels(); const auto width = _image.getWidth(); const auto height = _image.getHeight(); ripple wave{255, 1, 0.1}; for ( uint64_t row = 0; row < height; row++ ) { for ( uint64_t column = 0; column < width; column++ ) { uint64_t x = std::llabs(column - _x_origin); uint64_t y = std::llabs(row - _y_origin); auto r = calculate_radius(x, y); pixels[row * static_cast<int>(width) + column] = ofClamp(wave.get_value(r, time), 0, 255); } } _image.update(); } /** * \brief renders the image to the screen */ void application::draw() { //!< bind the texture to the shader _image.getTexture().bind(); //!< start the shader _displacement_shader.begin(); _displacement_shader.setUniform1f("u_scale", 200); //!< push the current local coordinate system to move to a new relative one ofPushMatrix(); //!< translate the plane into the center of the screen auto center_x = ofGetWidth() / 2.0; auto center_y = ofGetHeight() / 2.0; ofTranslate(center_x, center_y); //!< rotate it to a more isometric view auto rotation = ofMap(0.30, 0, 1, -60, 60, true) + 60; ofRotateDeg(rotation, 1, 0, 0); //!< draw the wireframe _plane.drawWireframe(); ofPopMatrix(); _displacement_shader.end(); } /********************************** Unused Openframeworks API Functions *******************************************/ void application::keyPressed(int key) { } void application::keyReleased(int key) { } void application::mouseMoved(int x, int y) { } void application::mouseDragged(int x, int y, int button) { } void application::mousePressed(int x, int y, int button) { } void application::mouseReleased(int x, int y, int button) { } void application::mouseEntered(int x, int y) { } void application::mouseExited(int x, int y) { } void application::windowResized(int w, int h) { } void application::gotMessage(ofMessage msg) { } void application::dragEvent(ofDragInfo dragInfo) { }
2b00cc475bca58bad48ff35bdf03081e02a2f350
859b30c6a1aef258b296da0c4ed2ef162eae1d0a
/KAVI/include/PlanAction.h
2f8b76cc01bf6b6e8b2ebac92b6b11ebbf8f2baf
[]
no_license
xuanjianwu/KAVI
e809d8d14ea4c8626050690025e673d2ef3bb6f9
063e05b4777951aef0c2d6d55a3bc21b2afed203
refs/heads/master
2018-07-20T22:36:55.293729
2018-06-26T12:03:56
2018-06-26T12:03:56
117,961,570
1
0
null
null
null
null
UTF-8
C++
false
false
3,239
h
PlanAction.h
/* * @author: liYc * @date : 2018/3/4 * @brief : This class implements an action from plan. Save the action's preconditions, effects and so on. */ #ifndef PLANACTION_H #define PLANACTION_H #include "KAVIBase.h" class PlanAction{ public: /* * construct function * @params: N/A * @return: N/A */ PlanAction(); QString getFormula() const; void setFormula(const QString &value); double getTime() const; void setTime(double value); int getId() const; void setId(int value); QSet<QString> getPositiveEffects() const; void setPositiveEffects(const QSet<QString> &value); QSet<QString> getNegativeEffects() const; void setNegativeEffects(const QSet<QString> &value); QSet<QString> getPositivePreconditions() const; void setPositivePreconditions(const QSet<QString> &value); QSet<QString> getNegativePreconditions() const; void setNegativePreconditions(const QSet<QString> &value); QMap<QString, bool> getRepairAdvice() const; void setRepairAdvice(const QMap<QString, bool> &value); /* * add repair advice to the action * @params: * precondition - the target precondition * advice - the bool advice for the precondition * @return: N/A */ void addRepairAdvice(const QString precondition, const bool advice); int getRepairAdviceSize() const; QMap<int, QSet<QString> > getPositivePreconditionsDependers() const; void setPositivePreconditionsDependers(const QMap<int, QSet<QString> > &value); QMap<int, QSet<QString> > getNegativePreconditionsDependers() const; void setNegativePreconditionsDependers(const QMap<int, QSet<QString> > &value); QMap<int, QSet<QString> > getPositiveEffectsDependers() const; void setPositiveEffectsDependers(const QMap<int, QSet<QString> > &value); QMap<int, QSet<QString> > getNegativeEffectsDependers() const; void setNegativeEffectsDependers(const QMap<int, QSet<QString> > &value); QString getActioName() const; void setActioName(const QString &value); QMap<QString, QString> getArgumentTypePair() const; void setArgumentTypePair(const QMap<QString, QString> &value); private: // the formula of the action QString formula; // the time of the action double time; // action's id int id; // action's name QString actioName; // action's [argument, type] pairs QMap<QString, QString> argumentTypePair; // positive preconditions QSet<QString> positivePreconditions; // negative preconditions QSet<QString> negativePreconditions; // positive effects QSet<QString> positiveEffects; // negative effects QSet<QString> negativeEffects; // repair advice against the action QMap<QString, bool> repairAdvice; // positive preconditions dependers QMap<int, QSet<QString> > positivePreconditionsDependers; // negative preconditions dependers QMap<int, QSet<QString> > negativePreconditionsDependers; // positive effects dependers QMap<int, QSet<QString> > positiveEffectsDependers; // negative effects dependers QMap<int, QSet<QString> > negativeEffectsDependers; }; #endif // PLANACTION_H
11aaccdf4c388998b4e49fdea4f0fb90370a91e5
19e225d0c580574f5432b3dcfebc096c20b9ad8c
/notebook2015/Graphs/Bellman-Ford (Shortest Path with Negative Weights).cpp
8bb2d4bcac31629d552bf27cc1fbab92feda82a3
[]
no_license
rhaps0dy/UPF-SWERC
4dd68d12433a0bfcf43207acc038eacca6de5480
28a9e61093a22e1672c0a7f26b763fd9a94e8261
refs/heads/master
2020-04-04T00:55:25.589289
2015-12-01T00:03:52
2015-12-01T00:03:52
25,181,782
3
0
null
null
null
null
UTF-8
C++
false
false
1,040
cpp
Bellman-Ford (Shortest Path with Negative Weights).cpp
// Complexity: E * V - Input: directed graph typedef pair<pair<int,int>,int> P; // par de nodos + coste int N; // numero de nodos vector<P> v; // representacion aristas int bellmanford(int a, int b) { vector<int> d(N, 1000000000); d[a] = 0; for (int i = 1; i < N; i++) for (int j = 0; j < (int)v.SZ; j++) if (d[v[j].X.X] < 1000000000 && d[v[j].X.X] + v[j].Y < d[v[j].X.Y]) d[v[j].X.Y] = d[v[j].X.X] + v[j].Y; for (int j = 0; j < (int)v.SZ; j++) if (d[v[j].X.X] < 1000000000 && d[v[j].X.X] + v[j].Y < d[v[j].X.Y]) return -1000000000; // existe ciclo negativo return d[b]; } int main(){ N=8; v.PB(MP(MP(0, 1), +2)); v.PB(MP(MP(1, 2), -1)); v.PB(MP(MP(1, 3), +1)); v.PB(MP(MP(2, 3), +1)); v.PB(MP(MP(6, 4), -1)); v.PB(MP(MP(4, 5), -1)); v.PB(MP(MP(5, 6), -1)); // min distance, negative cycle, unreachable cout << bellmanford(0, 3) << " " << bellmanford(4, 6) << " " << bellmanford(0, 7) << endl; }
eddc5798b3ada02204f1258c77098206b46c4c64
a5f3b0001cdb692aeffc444a16f79a0c4422b9d0
/main/svx/source/sidebar/area/AreaTransparencyGradientControl.cxx
51adddd8d005c2c732bda790f76ff59069ad248d
[ "Apache-2.0", "CPL-1.0", "bzip2-1.0.6", "LicenseRef-scancode-other-permissive", "Zlib", "LZMA-exception", "LGPL-2.0-or-later", "LicenseRef-scancode-free-unknown", "LicenseRef-scancode-philippe-de-muyter", "OFL-1.1", "LGPL-2.1-only", "MPL-1.1", "X11", "LGPL-2.1-or-later", "GPL-2.0-only", "OpenSSL", "LicenseRef-scancode-cpl-0.5", "GPL-1.0-or-later", "NPL-1.1", "MIT", "MPL-2.0", "LicenseRef-scancode-other-copyleft", "LicenseRef-scancode-unknown-license-reference", "MPL-1.0", "LicenseRef-scancode-openssl", "LicenseRef-scancode-ssleay-windows", "BSL-1.0", "LicenseRef-scancode-docbook", "LicenseRef-scancode-mit-old-style", "Python-2.0", "BSD-3-Clause", "IJG", "LicenseRef-scancode-warranty-disclaimer", "GPL-2.0-or-later", "LGPL-2.0-only", "LicenseRef-scancode-public-domain", "LicenseRef-scancode-unknown", "BSD-2-Clause", "Autoconf-exception-generic", "PSF-2.0", "NTP", "LicenseRef-scancode-python-cwi", "Afmparse", "W3C", "W3C-19980720", "curl", "LicenseRef-scancode-x11-xconsortium-veillard", "Bitstream-Vera", "HPND-sell-variant", "ICU" ]
permissive
apache/openoffice
b9518e36d784898c6c2ea3ebd44458a5e47825bb
681286523c50f34f13f05f7b87ce0c70e28295de
refs/heads/trunk
2023-08-30T15:25:48.357535
2023-08-28T19:50:26
2023-08-28T19:50:26
14,357,669
907
379
Apache-2.0
2023-08-16T20:49:37
2013-11-13T08:00:13
C++
UTF-8
C++
false
false
13,811
cxx
AreaTransparencyGradientControl.cxx
/************************************************************** * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * *************************************************************/ #include "AreaTransparencyGradientControl.hxx" #include "AreaPropertyPanel.hxx" #include "AreaPropertyPanel.hrc" #include <svx/dialogs.hrc> #include <svx/dialmgr.hxx> #include <svx/xflftrit.hxx> #include <sfx2/sidebar/ResourceDefinitions.hrc> #include <sfx2/bindings.hxx> #include <sfx2/dispatch.hxx> namespace svx { namespace sidebar { // positioning helpers #define APOS1_1 Point(LogicToPixel(Point(POPUPPANEL_MARGIN_HORIZONTAL,POPUPPANEL_MARGIN_VERTICAL), MAP_APPFONT)) #define APOS2_1 Point(LogicToPixel(Point(POPUPPANEL_MARGIN_HORIZONTAL,POPUPPANEL_MARGIN_VERTICAL + FIXED_TEXT_HEIGHT + TEXT_CONTROL_SPACING_VERTICAL), MAP_APPFONT)) #define APOS1_2 Point(LogicToPixel(Point(POPUPPANEL_MARGIN_HORIZONTAL+CONTROL_WIDTH+CONTROL_SPACING_HORIZONTAL,POPUPPANEL_MARGIN_VERTICAL), MAP_APPFONT)) #define APOS2_2 Point(LogicToPixel(Point(POPUPPANEL_MARGIN_HORIZONTAL+CONTROL_WIDTH+CONTROL_SPACING_HORIZONTAL,POPUPPANEL_MARGIN_VERTICAL + FIXED_TEXT_HEIGHT + TEXT_CONTROL_SPACING_VERTICAL), MAP_APPFONT)) #define APOS1_3 Point(LogicToPixel(Point(POPUPPANEL_MARGIN_HORIZONTAL,POPUPPANEL_MARGIN_VERTICAL + FIXED_TEXT_HEIGHT + TEXT_CONTROL_SPACING_VERTICAL+MBOX_HEIGHT+CONTROL_SPACING_VERTICAL), MAP_APPFONT)) #define APOS1_4 Point(LogicToPixel(Point(POPUPPANEL_MARGIN_HORIZONTAL,POPUPPANEL_MARGIN_VERTICAL + 2*(FIXED_TEXT_HEIGHT + TEXT_CONTROL_SPACING_VERTICAL)+MBOX_HEIGHT+CONTROL_SPACING_VERTICAL), MAP_APPFONT)) #define APOS2_3 Point(LogicToPixel(Point(POPUPPANEL_MARGIN_HORIZONTAL+CONTROL_WIDTH+CONTROL_SPACING_HORIZONTAL,POPUPPANEL_MARGIN_VERTICAL + FIXED_TEXT_HEIGHT + TEXT_CONTROL_SPACING_VERTICAL+MBOX_HEIGHT+CONTROL_SPACING_VERTICAL), MAP_APPFONT)) #define APOS2_4 Point(LogicToPixel(Point(POPUPPANEL_MARGIN_HORIZONTAL+CONTROL_WIDTH+CONTROL_SPACING_HORIZONTAL,POPUPPANEL_MARGIN_VERTICAL + 2*(FIXED_TEXT_HEIGHT + TEXT_CONTROL_SPACING_VERTICAL)+MBOX_HEIGHT+CONTROL_SPACING_VERTICAL), MAP_APPFONT)) #define APOS1_5 Point(LogicToPixel(Point(POPUPPANEL_MARGIN_HORIZONTAL,POPUPPANEL_MARGIN_VERTICAL + 2*(FIXED_TEXT_HEIGHT + TEXT_CONTROL_SPACING_VERTICAL+MBOX_HEIGHT+CONTROL_SPACING_VERTICAL)), MAP_APPFONT)) #define APOS1_6 Point(LogicToPixel(Point(POPUPPANEL_MARGIN_HORIZONTAL,POPUPPANEL_MARGIN_VERTICAL + 3*(FIXED_TEXT_HEIGHT + TEXT_CONTROL_SPACING_VERTICAL)+2*(MBOX_HEIGHT+CONTROL_SPACING_VERTICAL)), MAP_APPFONT)) #define APOS2_5 Point(LogicToPixel(Point(POPUPPANEL_MARGIN_HORIZONTAL+CONTROL_WIDTH+CONTROL_SPACING_HORIZONTAL,POPUPPANEL_MARGIN_VERTICAL + 2*(FIXED_TEXT_HEIGHT + TEXT_CONTROL_SPACING_VERTICAL+MBOX_HEIGHT+CONTROL_SPACING_VERTICAL)), MAP_APPFONT)) #define APOS2_6 Point(LogicToPixel(Point(POPUPPANEL_MARGIN_HORIZONTAL+CONTROL_WIDTH+CONTROL_SPACING_HORIZONTAL,POPUPPANEL_MARGIN_VERTICAL + 3*(FIXED_TEXT_HEIGHT + TEXT_CONTROL_SPACING_VERTICAL)+2*(MBOX_HEIGHT+CONTROL_SPACING_VERTICAL)), MAP_APPFONT)) #define APOS1_7 Point(LogicToPixel(Point(POPUPPANEL_MARGIN_HORIZONTAL,POPUPPANEL_MARGIN_VERTICAL + 3*(FIXED_TEXT_HEIGHT + TEXT_CONTROL_SPACING_VERTICAL+MBOX_HEIGHT+CONTROL_SPACING_VERTICAL)), MAP_APPFONT)) #define APOS1_8 Point(LogicToPixel(Point(POPUPPANEL_MARGIN_HORIZONTAL,POPUPPANEL_MARGIN_VERTICAL + 4*(FIXED_TEXT_HEIGHT + TEXT_CONTROL_SPACING_VERTICAL)+3*(MBOX_HEIGHT+CONTROL_SPACING_VERTICAL)), MAP_APPFONT)) #define APOS_Left_Right_1 Point(LogicToPixel(Point(LEFT_RIGHT_X1,LEFT_RIGHT_Y1), MAP_APPFONT)) #define APOS_Left_Right_2 Point(LogicToPixel(Point(LEFT_RIGHT_X2,LEFT_RIGHT_Y1), MAP_APPFONT)) #define APOS_Left_Right_3 Point(LogicToPixel(Point(LEFT_RIGHT_X1,LEFT_RIGHT_Y2), MAP_APPFONT)) #define APOS_Left_Right_4 Point(LogicToPixel(Point(LEFT_RIGHT_X2,LEFT_RIGHT_Y2), MAP_APPFONT)) AreaTransparencyGradientControl::AreaTransparencyGradientControl ( Window* pParent, AreaPropertyPanel& rPanel) : PopupControl( pParent,SVX_RES(RID_POPUPPANEL_AREAPAGE_TRGR)), maFtTrgrCenterX(this, SVX_RES(FT_TRGR_CENTER_X)), maMtrTrgrCenterX(this, SVX_RES(MTR_TRGR_CENTER_X)), maFtTrgrCenterY(this, SVX_RES(FT_TRGR_CENTER_Y)), maMtrTrgrCenterY(this, SVX_RES(MTR_TRGR_CENTER_Y)), maFtTrgrAngle(this, SVX_RES(FT_TRGR_ANGLE)), maMtrTrgrAngle(this, SVX_RES(MTR_TRGR_ANGLE)), maBtnLeft45(this, SVX_RES(BTN_LEFT_SECOND)), maBtnRight45(this, SVX_RES(BTN_RIGHT_FIRST)), maFtTrgrStartValue(this, SVX_RES(FT_TRGR_START_VALUE)), maMtrTrgrStartValue(this, SVX_RES(MTR_TRGR_START_VALUE)), maFtTrgrEndValue(this, SVX_RES(FT_TRGR_END_VALUE)), maMtrTrgrEndValue(this, SVX_RES(MTR_TRGR_END_VALUE)), maFtTrgrBorder(this, SVX_RES(FT_TRGR_BORDER)), maMtrTrgrBorder(this, SVX_RES(MTR_TRGR_BORDER)), maRotLeft( SVX_RES(IMG_ROT_LEFT)), maRotRight( SVX_RES(IMG_ROT_RIGHT)), mrAreaPropertyPanel(rPanel), mpBindings(NULL) { Link aLink = LINK( this, AreaTransparencyGradientControl, ModifiedTrgrHdl_Impl); maMtrTrgrCenterX.SetModifyHdl( aLink ); maMtrTrgrCenterY.SetModifyHdl( aLink ); maMtrTrgrAngle.SetModifyHdl( aLink ); maMtrTrgrBorder.SetModifyHdl( aLink ); maMtrTrgrStartValue.SetModifyHdl( aLink ); maMtrTrgrEndValue.SetModifyHdl( aLink ); aLink = LINK( this, AreaTransparencyGradientControl, Left_Click45_Impl); maBtnLeft45.SetSelectHdl( aLink ); aLink = LINK( this, AreaTransparencyGradientControl, Right_Click45_Impl); maBtnRight45.SetSelectHdl( aLink ); maBtnLeft45.SetItemImage(1,maRotLeft); Size aTbxSize = maBtnLeft45.CalcWindowSizePixel(); maBtnLeft45.SetOutputSizePixel( aTbxSize ); maBtnLeft45.SetQuickHelpText(1, String(SVX_RES(STR_HELP_LEFT))); // acc wj maBtnRight45.SetItemImage(1,maRotRight); aTbxSize = maBtnRight45.CalcWindowSizePixel(); maBtnRight45.SetOutputSizePixel( aTbxSize ); maBtnRight45.SetQuickHelpText(1, String(SVX_RES(STR_HELP_RIGHT))); // acc wj maBtnLeft45.SetBackground(Wallpaper()); maBtnLeft45.SetPaintTransparent(true); maBtnRight45.SetBackground(Wallpaper()); maBtnRight45.SetPaintTransparent(true); FreeResource(); mpBindings = mrAreaPropertyPanel.GetBindings(); } AreaTransparencyGradientControl::~AreaTransparencyGradientControl (void) { } void AreaTransparencyGradientControl::ToGetFocus() { if(maMtrTrgrCenterX.IsVisible()) maMtrTrgrCenterX.GrabFocus(); else maMtrTrgrAngle.GrabFocus(); } void AreaTransparencyGradientControl::Rearrange(XFillFloatTransparenceItem* pGradientItem) { InitStatus(pGradientItem); const XGradient& rGradient = pGradientItem->GetGradientValue(); XGradientStyle eXGS(rGradient.GetGradientStyle()); Size aSize(POP_WIDTH,POP_HEIGHT); aSize = LogicToPixel( aSize, MapMode(MAP_APPFONT) ); Size aSize2(POP_WIDTH,POP_HEIGHT2); aSize2 = LogicToPixel( aSize2, MapMode(MAP_APPFONT) ); long aPosY = 0; Point aPointAngle; Size aSizeAngle = maMtrTrgrAngle.GetSizePixel(); Size aTbxSize = maBtnLeft45.CalcWindowSizePixel(); switch(eXGS) { case XGRAD_LINEAR: case XGRAD_AXIAL: maFtTrgrCenterX.Hide(); maMtrTrgrCenterX.Hide(); maFtTrgrCenterY.Hide(); maMtrTrgrCenterY.Hide(); maFtTrgrAngle.Show(); maFtTrgrAngle.SetPosPixel(APOS1_1); maMtrTrgrAngle.Show(); maMtrTrgrAngle.SetPosPixel(APOS2_1); maFtTrgrStartValue.SetPosPixel(APOS1_3); maMtrTrgrStartValue.SetPosPixel(APOS1_4); maFtTrgrEndValue.SetPosPixel(APOS2_3); maMtrTrgrEndValue.SetPosPixel(APOS2_4); maFtTrgrBorder.SetPosPixel(APOS1_5); maMtrTrgrBorder.SetPosPixel(APOS1_6); maBtnLeft45.Show(); maBtnRight45.Show(); aPointAngle = maMtrTrgrAngle.GetPosPixel(); aPosY = aPointAngle.getY() + aSizeAngle.getHeight() - aTbxSize.getHeight(); maBtnLeft45.SetPosPixel(Point(APOS_Left_Right_1.getX(), aPosY)); maBtnRight45.SetPosPixel(Point(APOS_Left_Right_2.getX(), aPosY)); SetSizePixel(aSize2); break; case XGRAD_RADIAL: maFtTrgrCenterX.Show(); maFtTrgrCenterX.SetPosPixel(APOS1_1); maMtrTrgrCenterX.Show(); maMtrTrgrCenterX.SetPosPixel(APOS2_1); maFtTrgrCenterY.Show(); maFtTrgrCenterY.SetPosPixel(APOS1_2); maMtrTrgrCenterY.Show(); maMtrTrgrCenterY.SetPosPixel(APOS2_2); maFtTrgrAngle.Hide(); maMtrTrgrAngle.Hide(); maFtTrgrStartValue.SetPosPixel(APOS1_3); maMtrTrgrStartValue.SetPosPixel(APOS1_4); maFtTrgrEndValue.SetPosPixel(APOS2_3); maMtrTrgrEndValue.SetPosPixel(APOS2_4); maFtTrgrBorder.SetPosPixel(APOS1_5); maMtrTrgrBorder.SetPosPixel(APOS1_6); maBtnLeft45.Hide(); maBtnRight45.Hide(); SetSizePixel(aSize2); break; case XGRAD_ELLIPTICAL: case XGRAD_SQUARE: case XGRAD_RECT: maFtTrgrCenterX.Show(); maFtTrgrCenterX.SetPosPixel(APOS1_1); maMtrTrgrCenterX.Show(); maMtrTrgrCenterX.SetPosPixel(APOS2_1); maFtTrgrCenterY.Show(); maFtTrgrCenterY.SetPosPixel(APOS1_2); maMtrTrgrCenterY.Show(); maMtrTrgrCenterY.SetPosPixel(APOS2_2); maFtTrgrAngle.Show(); maFtTrgrAngle.SetPosPixel(APOS1_3); maMtrTrgrAngle.Show(); maMtrTrgrAngle.SetPosPixel(APOS1_4); maFtTrgrStartValue.SetPosPixel(APOS1_5); maMtrTrgrStartValue.SetPosPixel(APOS1_6); maFtTrgrEndValue.SetPosPixel(APOS2_5); maMtrTrgrEndValue.SetPosPixel(APOS2_6); maFtTrgrBorder.SetPosPixel(APOS1_7); maMtrTrgrBorder.SetPosPixel(APOS1_8); maBtnLeft45.Show(); maBtnRight45.Show(); aPointAngle = maMtrTrgrAngle.GetPosPixel(); aPosY = aPointAngle.getY() + aSizeAngle.getHeight() - aTbxSize.getHeight(); maBtnLeft45.SetPosPixel(Point(APOS_Left_Right_3.getX(), aPosY)); maBtnRight45.SetPosPixel(Point(APOS_Left_Right_4.getX(), aPosY)); SetSizePixel(aSize); break; } } void AreaTransparencyGradientControl::InitStatus(XFillFloatTransparenceItem* pGradientItem) { const XGradient& rGradient = pGradientItem->GetGradientValue(); XGradient aGradient; if (rGradient.GetXOffset() == AreaPropertyPanel::DEFAULT_CENTERX && rGradient.GetYOffset() == AreaPropertyPanel::DEFAULT_CENTERY && (rGradient.GetAngle() / 10) == AreaPropertyPanel::DEFAULT_ANGLE && ((sal_uInt16)((((sal_uInt16)rGradient.GetStartColor().GetRed() + 1) * 100) / 255)) == AreaPropertyPanel::DEFAULT_STARTVALUE && ((sal_uInt16)((((sal_uInt16)rGradient.GetEndColor().GetRed() + 1) * 100) / 255)) == AreaPropertyPanel::DEFAULT_ENDVALUE && rGradient.GetBorder() == AreaPropertyPanel::DEFAULT_BORDER) { aGradient = mrAreaPropertyPanel.GetGradient(rGradient.GetGradientStyle()); } else { aGradient = rGradient; } maMtrTrgrCenterX.SetValue(aGradient.GetXOffset()); maMtrTrgrCenterY.SetValue(aGradient.GetYOffset()); maMtrTrgrAngle.SetValue(aGradient.GetAngle() / 10); maMtrTrgrStartValue.SetValue((sal_uInt16)((((sal_uInt16)aGradient.GetStartColor().GetRed() + 1) * 100) / 255)); maMtrTrgrEndValue.SetValue((sal_uInt16)((((sal_uInt16)aGradient.GetEndColor().GetRed() + 1) * 100) / 255)); maMtrTrgrBorder.SetValue(aGradient.GetBorder()); } void AreaTransparencyGradientControl::ExecuteValueModify( sal_uInt8 nStartCol, sal_uInt8 nEndCol ) { // Added sal_Int16 aMtrValue = (sal_Int16)maMtrTrgrAngle.GetValue(); while(aMtrValue<0) aMtrValue += 360; sal_uInt16 nVal = aMtrValue/360; nVal = aMtrValue - nVal*360; maMtrTrgrAngle.SetValue(nVal); // End of new code XGradient aTmpGradient( Color(nStartCol, nStartCol, nStartCol), Color(nEndCol, nEndCol, nEndCol), (XGradientStyle)(mrAreaPropertyPanel.GetSelectedTransparencyTypeIndex()-2), (sal_uInt16)maMtrTrgrAngle.GetValue() * 10, (sal_uInt16)maMtrTrgrCenterX.GetValue(), (sal_uInt16)maMtrTrgrCenterY.GetValue(), (sal_uInt16)maMtrTrgrBorder.GetValue(), 100, 100); mrAreaPropertyPanel.SetGradient(aTmpGradient); SfxItemPool* pPool = NULL; bool bEnable = true; XFillFloatTransparenceItem aGradientItem(pPool,aTmpGradient, bEnable ); mpBindings->GetDispatcher()->Execute( SID_ATTR_FILL_FLOATTRANSPARENCE, SFX_CALLMODE_RECORD, &aGradientItem, 0L ); } IMPL_LINK(AreaTransparencyGradientControl, ModifiedTrgrHdl_Impl, void *, /* pControl */) { sal_uInt8 nStartCol = (sal_uInt8)(((sal_uInt16)maMtrTrgrStartValue.GetValue() * 255) / 100); sal_uInt8 nEndCol = (sal_uInt8)(((sal_uInt16)maMtrTrgrEndValue.GetValue() * 255) / 100); ExecuteValueModify( nStartCol, nEndCol ); return( 0L ); } IMPL_LINK(AreaTransparencyGradientControl, Left_Click45_Impl, void *, /* pControl */) { sal_uInt8 nStartCol = (sal_uInt8)(((sal_uInt16)maMtrTrgrStartValue.GetValue() * 255) / 100); sal_uInt8 nEndCol = (sal_uInt8)(((sal_uInt16)maMtrTrgrEndValue.GetValue() * 255) / 100); sal_uInt16 aTemp = (sal_uInt16)maMtrTrgrAngle.GetValue(); if(aTemp>=315) aTemp -= 360; aTemp += 45; maMtrTrgrAngle.SetValue(aTemp); ExecuteValueModify( nStartCol, nEndCol ); return( 0L ); } IMPL_LINK(AreaTransparencyGradientControl, Right_Click45_Impl, void *, /* pControl */) { sal_uInt8 nStartCol = (sal_uInt8)(((sal_uInt16)maMtrTrgrStartValue.GetValue() * 255) / 100); sal_uInt8 nEndCol = (sal_uInt8)(((sal_uInt16)maMtrTrgrEndValue.GetValue() * 255) / 100); sal_uInt16 aTemp = (sal_uInt16)maMtrTrgrAngle.GetValue(); if(aTemp<45) aTemp += 360; aTemp -= 45; maMtrTrgrAngle.SetValue(aTemp); ExecuteValueModify( nStartCol, nEndCol ); return( 0L ); } } } // end of namespace svx::sidebar // eof
e531193586852e9af1393371112ac64142fc5aa9
2c185af119b337fc4baafde2abb8138a18f8b85b
/src/pf_imgui/layouts/BoxLayout.cpp
5a1bdce1477b75567fc8e534d7bc0600a222099e
[]
no_license
southdy/pf_imgui
705a73417e0eff4ffcac7643e6d6ab3fa6affbb4
ed44abe3deee98757264c17bb5ff67e07ca66883
refs/heads/master
2023-08-25T15:01:14.432258
2021-11-14T11:21:45
2021-11-14T11:21:45
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,457
cpp
BoxLayout.cpp
// // Created by petr on 1/24/21. // #include "BoxLayout.h" #include <imgui.h> #include <numeric> namespace pf::ui::ig { BoxLayout::BoxLayout(const std::string &elementName, LayoutDirection layoutDirection, const Size &size, AllowCollapse allowCollapse, ShowBorder showBorder, Persistent persistent) : ResizableLayout(elementName, size, allowCollapse, showBorder, persistent), layoutDirection(layoutDirection) {} BoxLayout::BoxLayout(const std::string &elementName, LayoutDirection layoutDirection, const Size &size, ShowBorder showBorder, Persistent persistent) : BoxLayout(elementName, layoutDirection, size, AllowCollapse::No, showBorder, persistent) {} BoxLayout::BoxLayout(const std::string &elementName, LayoutDirection layoutDirection, const Size &size, AllowCollapse allowCollapse, Persistent persistent) : BoxLayout(elementName, layoutDirection, size, allowCollapse, ShowBorder::No, persistent) {} LayoutDirection BoxLayout::getLayoutDirection() const { return layoutDirection; } void BoxLayout::setLayoutDirection(LayoutDirection newLayoutDirection) { layoutDirection = newLayoutDirection; } void BoxLayout::renderImpl() { auto colorStyle = setColorStack(); auto style = setStyleStack(); const auto flags = isScrollable() ? ImGuiWindowFlags_{} : ImGuiWindowFlags_NoScrollbar | ImGuiWindowFlags_NoScrollWithMouse; RAII end{[&] { ImGui::EndChild(); }}; if (ImGui::BeginChild(getName().c_str(), getSizeIfCollapsed(), isDrawBorder(), flags)) { if (nextFrameScrollPosition.has_value() && *nextFrameScrollPosition == ScrollPosition::Top) { ImGui::SetScrollHereY(0.0f); nextFrameScrollPosition = std::nullopt; } if (renderCollapseButton()) { switch (layoutDirection) { case LayoutDirection::LeftToRight: renderLeftToRight(); break; case LayoutDirection::TopToBottom: renderTopToBottom(); break; } } if (nextFrameScrollPosition.has_value() && *nextFrameScrollPosition == ScrollPosition::Bottom) { ImGui::SetScrollHereY(1.0f); nextFrameScrollPosition = std::nullopt; } } } void BoxLayout::renderTopToBottom() { std::ranges::for_each(children, [&](auto &child) { child->render(); }); } void BoxLayout::renderLeftToRight() { if (!children.empty()) { const auto childrenSize = children.size(); auto idx = 0u; std::ranges::for_each(children, [&](auto &child) { child->render(); if (idx != childrenSize - 1) { ImGui::SameLine(); } ++idx; }); } } void BoxLayout::pushChild(std::unique_ptr<Element> child) { children.emplace_back(std::move(child)); } void BoxLayout::insertChild(std::unique_ptr<Element> child, std::size_t index) { #ifndef _MSC_VER// TODO: MSVC internal error if (index > children.size()) { throw InvalidArgumentException("Index out of bounds: {}", index); } #endif children.insert(children.begin() + static_cast<long long>(index), std::move(child)); } void BoxLayout::removeChild(const std::string &childName) { if (auto iter = std::ranges::find_if(children, [childName](const auto &child) { return child->getName() == childName; }); iter != children.end()) { children.erase(iter); } } std::vector<Renderable *> BoxLayout::getRenderables() { return children | ranges::views::transform([](auto &child) -> Renderable * { return child.get(); }) | ranges::to_vector; } }// namespace pf::ui::ig
6ba0d9e880be397165618f6fd8df97b58f74cbac
339927d079c0bd8cfb4ac97cbc9f007ccbcaf9c6
/YunDisk/debug/moc_buttongroup.cpp
77117b10fad97fb11722ff381249a40750b0efac
[]
no_license
Jsondp/CloudDisk
9fa565e1f3f6eeb065edf9b9870615edc4333cf4
a121ecb74392d53c3f8bc3ebc707301dfd0f1d57
refs/heads/master
2021-07-25T21:10:12.563577
2020-05-03T11:05:35
2020-05-03T11:05:35
163,037,243
2
0
null
null
null
null
UTF-8
C++
false
false
8,616
cpp
moc_buttongroup.cpp
/**************************************************************************** ** Meta object code from reading C++ file 'buttongroup.h' ** ** Created by: The Qt Meta Object Compiler version 67 (Qt 5.5.0) ** ** WARNING! All changes made in this file will be lost! *****************************************************************************/ #include "../buttongroup.h" #include <QtCore/qbytearray.h> #include <QtCore/qmetatype.h> #if !defined(Q_MOC_OUTPUT_REVISION) #error "The header file 'buttongroup.h' doesn't include <QObject>." #elif Q_MOC_OUTPUT_REVISION != 67 #error "This file was generated using the moc from 5.5.0. It" #error "cannot be used with the include files from this version of Qt." #error "(The moc has changed too much.)" #endif QT_BEGIN_MOC_NAMESPACE struct qt_meta_stringdata_ButtonGroup_t { QByteArrayData data[17]; char stringdata0[163]; }; #define QT_MOC_LITERAL(idx, ofs, len) \ Q_STATIC_BYTE_ARRAY_DATA_HEADER_INITIALIZER_WITH_OFFSET(len, \ qptrdiff(offsetof(qt_meta_stringdata_ButtonGroup_t, stringdata0) + ofs \ - idx * sizeof(QByteArrayData)) \ ) static const qt_meta_stringdata_ButtonGroup_t qt_meta_stringdata_ButtonGroup = { { QT_MOC_LITERAL(0, 0, 11), // "ButtonGroup" QT_MOC_LITERAL(1, 12, 9), // "sigMyFile" QT_MOC_LITERAL(2, 22, 0), // "" QT_MOC_LITERAL(3, 23, 12), // "sigShareList" QT_MOC_LITERAL(4, 36, 11), // "sigDownload" QT_MOC_LITERAL(5, 48, 12), // "sigTransform" QT_MOC_LITERAL(6, 61, 13), // "sigSwitchUser" QT_MOC_LITERAL(7, 75, 11), // "closeWindow" QT_MOC_LITERAL(8, 87, 9), // "minWindow" QT_MOC_LITERAL(9, 97, 9), // "maxWindow" QT_MOC_LITERAL(10, 107, 15), // "slotButtonClick" QT_MOC_LITERAL(11, 123, 4), // "Page" QT_MOC_LITERAL(12, 128, 3), // "cur" QT_MOC_LITERAL(13, 132, 4), // "text" QT_MOC_LITERAL(14, 137, 9), // "setParent" QT_MOC_LITERAL(15, 147, 8), // "QWidget*" QT_MOC_LITERAL(16, 156, 6) // "parent" }, "ButtonGroup\0sigMyFile\0\0sigShareList\0" "sigDownload\0sigTransform\0sigSwitchUser\0" "closeWindow\0minWindow\0maxWindow\0" "slotButtonClick\0Page\0cur\0text\0setParent\0" "QWidget*\0parent" }; #undef QT_MOC_LITERAL static const uint qt_meta_data_ButtonGroup[] = { // content: 7, // revision 0, // classname 0, 0, // classinfo 11, 14, // methods 0, 0, // properties 0, 0, // enums/sets 0, 0, // constructors 0, // flags 8, // signalCount // signals: name, argc, parameters, tag, flags 1, 0, 69, 2, 0x06 /* Public */, 3, 0, 70, 2, 0x06 /* Public */, 4, 0, 71, 2, 0x06 /* Public */, 5, 0, 72, 2, 0x06 /* Public */, 6, 0, 73, 2, 0x06 /* Public */, 7, 0, 74, 2, 0x06 /* Public */, 8, 0, 75, 2, 0x06 /* Public */, 9, 0, 76, 2, 0x06 /* Public */, // slots: name, argc, parameters, tag, flags 10, 1, 77, 2, 0x0a /* Public */, 10, 1, 80, 2, 0x0a /* Public */, 14, 1, 83, 2, 0x0a /* Public */, // signals: parameters QMetaType::Void, QMetaType::Void, QMetaType::Void, QMetaType::Void, QMetaType::Void, QMetaType::Void, QMetaType::Void, QMetaType::Void, // slots: parameters QMetaType::Void, 0x80000000 | 11, 12, QMetaType::Void, QMetaType::QString, 13, QMetaType::Void, 0x80000000 | 15, 16, 0 // eod }; void ButtonGroup::qt_static_metacall(QObject *_o, QMetaObject::Call _c, int _id, void **_a) { if (_c == QMetaObject::InvokeMetaMethod) { ButtonGroup *_t = static_cast<ButtonGroup *>(_o); Q_UNUSED(_t) switch (_id) { case 0: _t->sigMyFile(); break; case 1: _t->sigShareList(); break; case 2: _t->sigDownload(); break; case 3: _t->sigTransform(); break; case 4: _t->sigSwitchUser(); break; case 5: _t->closeWindow(); break; case 6: _t->minWindow(); break; case 7: _t->maxWindow(); break; case 8: _t->slotButtonClick((*reinterpret_cast< Page(*)>(_a[1]))); break; case 9: _t->slotButtonClick((*reinterpret_cast< QString(*)>(_a[1]))); break; case 10: _t->setParent((*reinterpret_cast< QWidget*(*)>(_a[1]))); break; default: ; } } else if (_c == QMetaObject::RegisterMethodArgumentMetaType) { switch (_id) { default: *reinterpret_cast<int*>(_a[0]) = -1; break; case 10: switch (*reinterpret_cast<int*>(_a[1])) { default: *reinterpret_cast<int*>(_a[0]) = -1; break; case 0: *reinterpret_cast<int*>(_a[0]) = qRegisterMetaType< QWidget* >(); break; } break; } } else if (_c == QMetaObject::IndexOfMethod) { int *result = reinterpret_cast<int *>(_a[0]); void **func = reinterpret_cast<void **>(_a[1]); { typedef void (ButtonGroup::*_t)(); if (*reinterpret_cast<_t *>(func) == static_cast<_t>(&ButtonGroup::sigMyFile)) { *result = 0; } } { typedef void (ButtonGroup::*_t)(); if (*reinterpret_cast<_t *>(func) == static_cast<_t>(&ButtonGroup::sigShareList)) { *result = 1; } } { typedef void (ButtonGroup::*_t)(); if (*reinterpret_cast<_t *>(func) == static_cast<_t>(&ButtonGroup::sigDownload)) { *result = 2; } } { typedef void (ButtonGroup::*_t)(); if (*reinterpret_cast<_t *>(func) == static_cast<_t>(&ButtonGroup::sigTransform)) { *result = 3; } } { typedef void (ButtonGroup::*_t)(); if (*reinterpret_cast<_t *>(func) == static_cast<_t>(&ButtonGroup::sigSwitchUser)) { *result = 4; } } { typedef void (ButtonGroup::*_t)(); if (*reinterpret_cast<_t *>(func) == static_cast<_t>(&ButtonGroup::closeWindow)) { *result = 5; } } { typedef void (ButtonGroup::*_t)(); if (*reinterpret_cast<_t *>(func) == static_cast<_t>(&ButtonGroup::minWindow)) { *result = 6; } } { typedef void (ButtonGroup::*_t)(); if (*reinterpret_cast<_t *>(func) == static_cast<_t>(&ButtonGroup::maxWindow)) { *result = 7; } } } } const QMetaObject ButtonGroup::staticMetaObject = { { &QWidget::staticMetaObject, qt_meta_stringdata_ButtonGroup.data, qt_meta_data_ButtonGroup, qt_static_metacall, Q_NULLPTR, Q_NULLPTR} }; const QMetaObject *ButtonGroup::metaObject() const { return QObject::d_ptr->metaObject ? QObject::d_ptr->dynamicMetaObject() : &staticMetaObject; } void *ButtonGroup::qt_metacast(const char *_clname) { if (!_clname) return Q_NULLPTR; if (!strcmp(_clname, qt_meta_stringdata_ButtonGroup.stringdata0)) return static_cast<void*>(const_cast< ButtonGroup*>(this)); return QWidget::qt_metacast(_clname); } int ButtonGroup::qt_metacall(QMetaObject::Call _c, int _id, void **_a) { _id = QWidget::qt_metacall(_c, _id, _a); if (_id < 0) return _id; if (_c == QMetaObject::InvokeMetaMethod) { if (_id < 11) qt_static_metacall(this, _c, _id, _a); _id -= 11; } else if (_c == QMetaObject::RegisterMethodArgumentMetaType) { if (_id < 11) qt_static_metacall(this, _c, _id, _a); _id -= 11; } return _id; } // SIGNAL 0 void ButtonGroup::sigMyFile() { QMetaObject::activate(this, &staticMetaObject, 0, Q_NULLPTR); } // SIGNAL 1 void ButtonGroup::sigShareList() { QMetaObject::activate(this, &staticMetaObject, 1, Q_NULLPTR); } // SIGNAL 2 void ButtonGroup::sigDownload() { QMetaObject::activate(this, &staticMetaObject, 2, Q_NULLPTR); } // SIGNAL 3 void ButtonGroup::sigTransform() { QMetaObject::activate(this, &staticMetaObject, 3, Q_NULLPTR); } // SIGNAL 4 void ButtonGroup::sigSwitchUser() { QMetaObject::activate(this, &staticMetaObject, 4, Q_NULLPTR); } // SIGNAL 5 void ButtonGroup::closeWindow() { QMetaObject::activate(this, &staticMetaObject, 5, Q_NULLPTR); } // SIGNAL 6 void ButtonGroup::minWindow() { QMetaObject::activate(this, &staticMetaObject, 6, Q_NULLPTR); } // SIGNAL 7 void ButtonGroup::maxWindow() { QMetaObject::activate(this, &staticMetaObject, 7, Q_NULLPTR); } QT_END_MOC_NAMESPACE
8599f051ed8cd6daed80c50634da3a3febdcc746
a11985724577486c5fc789e3eca3fda636f030c2
/PlzNumbers/src/old/PyAllUp.cpp
4f3a250eedcc80756a2600366976401764b6bc1f
[ "MIT" ]
permissive
McCoyGroup/RynLib
1ffa703e02f20a2ddb8defcffdecf3b1e61e70ed
8d7e119ebbd3da4c8b0efb49facba9ff1cbaa09d
refs/heads/master
2021-06-24T01:05:53.298531
2021-02-17T14:46:30
2021-02-17T14:46:30
182,337,960
1
1
null
2020-03-05T01:51:56
2019-04-19T23:42:51
Python
UTF-8
C++
false
false
6,792
cpp
PyAllUp.cpp
// // Created by Mark Boyer on 1/30/20. // #include "Python.h" #include "RynTypes.hpp" #if PY_MAJOR_VERSION == 3 const char *_GetPyString( PyObject* s, const char *enc, const char *err, PyObject *pyStr) { pyStr = PyUnicode_AsEncodedString(s, enc, err); if (pyStr == NULL) return NULL; const char *strExcType = PyBytes_AsString(pyStr); // Py_XDECREF(pyStr); return strExcType; } const char *_GetPyString( PyObject* s, PyObject *pyStr) { // unfortunately we need to pass the second pyStr so we can XDECREF it later return _GetPyString( s, "utf-8", "strict", pyStr); // utf-8 is safe since it contains ASCII fully } Py_ssize_t _FromInt( PyObject* int_obj ) { return PyLong_AsSsize_t(int_obj); } bool _FromBool( PyObject* bool_obj ) { return PyObject_IsTrue(bool_obj); } Real_t _FromFloat(PyObject* float_obj) { return PyFloat_AsDouble(float_obj); } #else const char *_GetPyString( PyObject* s ) { return PyString_AsString(s); } const char *_GetPyString( PyObject* s, PyObject *pyStr ) { // just to unify the 2/3 interface return _GetPyString( s ); } Py_ssize_t _FromInt( PyObject* int_obj ) { return PyInt_AsSsize_t(int_obj); } bool _FromBool( PyObject* bool_obj ) { return PyObject_IsTrue(bool_obj); } Real_t _FromFloat(PyObject* float_obj) { return PyFloat_AsDouble(float_obj); } #endif Names _getAtomTypes( PyObject* atoms, Py_ssize_t num_atoms ) { Names mattsAtoms(num_atoms); for (int i = 0; i<num_atoms; i++) { PyObject* atom = PyList_GetItem(atoms, i); PyObject* pyStr = NULL; const char* atomStr = _GetPyString(atom, pyStr); Name atomString = atomStr; mattsAtoms[i] = atomString; // Py_XDECREF(atom); Py_XDECREF(pyStr); } return mattsAtoms; } Py_buffer _GetDataBuffer(PyObject *data) { Py_buffer view; PyObject_GetBuffer(data, &view, PyBUF_CONTIG_RO); return view; } double *_GetDoubleDataBufferArray(Py_buffer *view) { double *c_data; if ( view == NULL ) return NULL; c_data = (double *) view->buf; if (c_data == NULL) { PyBuffer_Release(view); } return c_data; } double *_GetDoubleDataArray(PyObject *data) { Py_buffer view = _GetDataBuffer(data); double *array = _GetDoubleDataBufferArray(&view); PyBuffer_Release(&view); // Py_XDECREF(data); // CHECKNULL(array); return array; } PyObject *_getNumPyZerosMethod() { PyObject *array_module = PyImport_ImportModule("numpy"); if (array_module == NULL) return NULL; PyObject *builder = PyObject_GetAttrString(array_module, "zeros"); Py_XDECREF(array_module); if (builder == NULL) return NULL; return builder; }; PyObject *_getNumPyArray( int n, int m, const char *dtype ) { // Initialize NumPy array of correct size and dtype PyObject *builder = _getNumPyZerosMethod(); if (builder == NULL) return NULL; PyObject *dims = Py_BuildValue("((ii))", n, m); Py_XDECREF(builder); if (dims == NULL) return NULL; PyObject *kw = Py_BuildValue("{s:s}", "dtype", dtype); if (kw == NULL) return NULL; PyObject *pot = PyObject_Call(builder, dims, kw); Py_XDECREF(kw); Py_XDECREF(dims); return pot; } PyObject *_getNumPyArray( int n, int m, int l, const char *dtype ) { // Initialize NumPy array of correct size and dtype PyObject *builder = _getNumPyZerosMethod(); if (builder == NULL) return NULL; PyObject *dims = Py_BuildValue("((iii))", n, m, l); Py_XDECREF(builder); if (dims == NULL) return NULL; PyObject *kw = Py_BuildValue("{s:s}", "dtype", dtype); if (kw == NULL) return NULL; PyObject *pot = PyObject_Call(builder, dims, kw); Py_XDECREF(kw); Py_XDECREF(dims); return pot; } PyObject *_getNumPyArray( int n, int m, int l, int k, const char *dtype ) { // Initialize NumPy array of correct size and dtype PyObject *builder = _getNumPyZerosMethod(); if (builder == NULL) return NULL; PyObject *dims = Py_BuildValue("((iiii))", n, m, l, k); Py_XDECREF(builder); if (dims == NULL) return NULL; PyObject *kw = Py_BuildValue("{s:s}", "dtype", dtype); if (kw == NULL) return NULL; PyObject *pot = PyObject_Call(builder, dims, kw); Py_XDECREF(kw); Py_XDECREF(dims); return pot; } // NumPy Communication Methods PyObject *_fillNumPyArray( const PotentialArray &pot_vals, const int ncalls, const int num_walkers ) { // Initialize NumPy array of correct size and dtype PyObject *pot = _getNumPyArray(ncalls, num_walkers, "float"); if (pot == NULL) return NULL; double *data = _GetDoubleDataArray(pot); for (int i = 0; i < ncalls; i++) { memcpy( // where in the data array memory to start copying to data + num_walkers * i, // where in the potential array to start copying from pot_vals[i].data(), // what sizeof(double) * num_walkers ); }; return pot; } PyObject *_fillNumPyArray( RawPotentialBuffer pot_vals, const int ncalls, const int num_walkers ) { // Initialize NumPy array of correct size and dtype PyObject *pot = _getNumPyArray(ncalls, num_walkers, "float"); if (pot == NULL) return NULL; double *data = _GetDoubleDataArray(pot); memcpy(data, pot_vals, sizeof(double) * num_walkers * num_walkers); return pot; } PyObject *_fillWalkersNumPyArray( const RawWalkerBuffer coords, const int num_walkers, const int natoms ) { // Initialize NumPy array of correct size and dtype PyObject *walkers = _getNumPyArray(num_walkers, natoms, 3, "float"); if (walkers == NULL) return NULL; double *data = _GetDoubleDataArray(walkers); memcpy(data, coords, sizeof(double) * num_walkers * natoms * 3); return walkers; } void _printObject(const char* fmtString, PyObject *obj) { PyObject *str=NULL; PyObject *repr=PyObject_Repr(obj); printf(fmtString, _GetPyString(repr, str)); Py_XDECREF(repr); Py_XDECREF(str); } bool _pyPrintStr(const char* raw_str, const char* end="\n") { // printf("Printing %s", raw_str); PyObject *sys = PyImport_ImportModule("sys"); if (sys == NULL) { return -1; } PyObject *stdout_obj = PyObject_GetAttrString(sys, "stdout"); if (sys == NULL) { Py_XDECREF(sys); return -1; } std::string full_str = raw_str; full_str += end; PyObject* res = PyObject_CallMethod(stdout_obj, "write", "s", full_str.c_str()); bool success = (res != NULL); Py_XDECREF(sys); Py_XDECREF(stdout_obj); Py_XDECREF(res); return success; }
c88d3169f542ee3d4ba56a002e23677919c758ac
2ead9e8c28020494403301ec50f7f052098acf2b
/lexical/RegexConf.h
1b0c61761a6a78aadf16883cb05028e1bed3eb85
[]
no_license
340StarObserver/compiler
dd80fd1ef848a0fde569d12c844b9d379a3fe504
e241627d5decad38be752c457a96225c87d8d108
refs/heads/master
2020-12-24T12:05:36.332498
2017-03-24T08:25:04
2017-03-24T08:25:04
73,075,793
2
1
null
null
null
null
UTF-8
C++
false
false
1,351
h
RegexConf.h
/* Author : Lv Yang Created : 22 November 2016 Modified : 01 December 2016 Version : 1.0 */ #ifndef _REGEXCONF_H #define _REGEXCONF_H #include <vector> using std::vector; #include <string> using std::string; namespace Seven { /* one regex conf item */ struct RegexConfItem { int id; // 该正则的编号( 从1开始 ) int priority; // 该正则的优先级( 越大优先级越高 ) string mean; // 该正则的含义 string infix; // 该正则的中缀表达式 }; /* regex conf */ class RegexConf { public: /* all the regexs' conf items */ static vector<RegexConfItem> Items; /* init from a conf file Tip1 : 由于C++的相对路径的计算是以执行命令所在的路径为参考的, 并不是相对于这份代码文件 例如 : A目录下有a.cpp和b.conf,代码中调用的是"b.conf", 编译链接后生成的a.exe也在A目录下, 我在A目录下执行 ./a.exe 是可以读取配置文件的, 而在A的上级目录下执行 ./A/a.exe 是会报运行时错误的 所以,参数推荐使用绝对路径 Tip2 : 配置文件的格式 每一行定义了一个正规表达式的信息,形如 : 编号 优先级 含义 中缀表达式 Tip3 : 该方法必须在构造NFA,DFA之前就被调用 */ static void init(const char * path); }; } #endif
0dbbec37e37aacb7bc51928b5b44228e7248a149
4f75073754f7efa9f75da00da063ae9cdba6c204
/PE2Shellcode/ProccessData.h
88d6333d042c790e477dea8e3c47088bcaee4d7b
[]
no_license
fadinglr/PE2Shellcode
77dd24d230ed490287892c04a73e798d5960dc99
28c510994a77c7976a64b44877849b8d6e893037
refs/heads/master
2022-04-04T01:07:38.025252
2020-01-09T16:24:04
2020-01-09T16:24:04
null
0
0
null
null
null
null
UTF-8
C++
false
false
624
h
ProccessData.h
#pragma once typedef DWORD(__stdcall *pRtlCompressBuffer)( IN ULONG CompressionFormat, IN PVOID SourceBuffer, IN ULONG SourceBufferLength, OUT PVOID DestinationBuffer, IN ULONG DestinationBufferLength, IN ULONG Unknown, OUT PULONG pDestinationSize, IN PVOID WorkspaceBuffer); typedef DWORD(__stdcall *pRtlGetCompressionWorkSpaceSize)( IN ULONG CompressionFormat, OUT PULONG pNeededBufferSize, OUT PULONG pUnknown); namespace CProcsData { int Rc4Encrypt(char * org, int size, unsigned char * rc4Key, int keySize); int CompressData(char *org, int size, char * retData ,int & retSize); }
fae4406d4115bd9f9353984f3143d61bc088c96e
38db68509b1a7d586e81564d7bcf4066eb2df6fc
/Audrey/Audrey_OF1/src/Ball.hpp
d46d6c8414fa58205d7f8e3c0d45d5e3b7509c52
[]
no_license
huynj316/CCLab-Homework
36200765f2db56b089f5cb5a5f60c0013b95cc3b
1b7a7ba6d65b4009281e9731219e233bd1aa3184
refs/heads/master
2016-09-06T02:44:42.664534
2015-12-22T23:52:50
2015-12-22T23:52:50
42,139,507
1
0
null
2015-09-15T23:34:56
2015-09-08T21:17:38
JavaScript
UTF-8
C++
false
false
324
hpp
Ball.hpp
// // Ball.hpp // mySketch // // Created by Audrey on 11/9/15. // // #pragma once class Ball { public: // Ball(); void setup(); void update(); void draw(); float xPos; float yPos; float xSpeed; float ySpeed; int xDirection; int yDirection; };
11fe1064a42161455231bd0c554bb543848469cf
24f8c1bc84049310ade1ecdea8d041f5aff94bd8
/books/The_C++_Programming_Language/Special_Edition/chapter05/ch05ex13.cpp
fbd5d11eab4430599e1f60b2c2b335389e400bd9
[]
no_license
BartVandewoestyne/Cpp
f10d709aed4bbe03b3cca1778ef8f5b7ec554c54
055d3fc61922a29657f48241defcaba744f43d0f
refs/heads/master
2023-08-22T19:42:32.516681
2023-08-03T21:58:02
2023-08-03T21:58:02
4,518,426
126
17
null
null
null
null
UTF-8
C++
false
false
532
cpp
ch05ex13.cpp
#include <iostream> using namespace std; struct Date { int day; int month; int year; }; Date readDate() { Date d; cin >> d.day; cin >> d.month; cin >> d.year; return d; } void printDate(Date* d) { cout << "day = " << d->day << endl;; cout << "month = " << d->month << endl; cout << "year = " << d->year << endl; } Date initDate(int day, int month, int year) { Date d; d.day = day; d.month = month; d.year = year; return d; } int main() { Date d; d = readDate(); printDate(&d); }