blob_id
stringlengths
40
40
directory_id
stringlengths
40
40
path
stringlengths
3
264
content_id
stringlengths
40
40
detected_licenses
listlengths
0
85
license_type
stringclasses
2 values
repo_name
stringlengths
5
140
snapshot_id
stringlengths
40
40
revision_id
stringlengths
40
40
branch_name
stringclasses
986 values
visit_date
timestamp[us]
revision_date
timestamp[us]
committer_date
timestamp[us]
github_id
int64
3.89k
681M
star_events_count
int64
0
209k
fork_events_count
int64
0
110k
gha_license_id
stringclasses
23 values
gha_event_created_at
timestamp[us]
gha_created_at
timestamp[us]
gha_language
stringclasses
145 values
src_encoding
stringclasses
34 values
language
stringclasses
1 value
is_vendor
bool
1 class
is_generated
bool
2 classes
length_bytes
int64
3
10.4M
extension
stringclasses
122 values
content
stringlengths
3
10.4M
authors
listlengths
1
1
author_id
stringlengths
0
158
6482670efbfc529d3a98447aeef18572d9fe7086
d6ebbcf78baa559cf138d073ca0e6174373a8ee8
/algorithm/1603.design-parking-system.cpp
8411be165191872f09c221ea08a7a193b306a167
[]
no_license
silencelee/leetcode
91bd93704a83a48f9afa86744e871d1b3ef098e5
32d1bca2009635423cfdc0f022fb335c9baf4c7e
refs/heads/master
2021-07-09T15:19:50.735419
2021-03-22T03:26:06
2021-03-22T03:26:06
236,697,573
0
0
null
null
null
null
UTF-8
C++
false
false
2,615
cpp
/* * @lc app=leetcode id=1603 lang=cpp * * [1603] Design Parking System * * https://leetcode.com/problems/design-parking-system/description/ * * algorithms * Easy (86.52%) * Likes: 264 * Dislikes: 110 * Total Accepted: 46.9K * Total Submissions: 54.5K * Testcase Example: '["ParkingSystem","addCar","addCar","addCar","addCar"]\n[[1,1,0],[1],[2],[3],[1]]' * * Design a parking system for a parking lot. The parking lot has three kinds * of parking spaces: big, medium, and small, with a fixed number of slots for * each size. * * Implement the ParkingSystem class: * * * ParkingSystem(int big, int medium, int small) Initializes object of the * ParkingSystem class. The number of slots for each parking space are given as * part of the constructor. * bool addCar(int carType) Checks whether there is a parking space of carType * for the car that wants to get into the parking lot. carType can be of three * kinds: big, medium, or small, which are represented by 1, 2, and 3 * respectively. A car can only park in a parking space of its carType. If * there is no space available, return false, else park the car in that size * space and return true. * * * * Example 1: * * * Input * ["ParkingSystem", "addCar", "addCar", "addCar", "addCar"] * [[1, 1, 0], [1], [2], [3], [1]] * Output * [null, true, true, false, false] * * Explanation * ParkingSystem parkingSystem = new ParkingSystem(1, 1, 0); * parkingSystem.addCar(1); // return true because there is 1 available slot * for a big car * parkingSystem.addCar(2); // return true because there is 1 available slot * for a medium car * parkingSystem.addCar(3); // return false because there is no available slot * for a small car * parkingSystem.addCar(1); // return false because there is no available slot * for a big car. It is already occupied. * * * * Constraints: * * * 0 <= big, medium, small <= 1000 * carType is 1, 2, or 3 * At most 1000 calls will be made to addCar * * */ // @lc code=start class ParkingSystem { public: int limits[4]; ParkingSystem(int big, int medium, int small) { memset(limits, 0, sizeof(limits)); limits[1] = big; limits[2] = medium; limits[3] = small; } bool addCar(int carType) { if (limits[carType] <= 0) return false; --limits[carType]; return true; } }; /** * Your ParkingSystem object will be instantiated and called as such: * ParkingSystem* obj = new ParkingSystem(big, medium, small); * bool param_1 = obj->addCar(carType); */ // @lc code=end
[ "lij311@qq.com" ]
lij311@qq.com
f4fc996f7f388c14e1bcb9aa615af7cbffdc818e
9d6df578516566142cec8fe201ce20e6247c4364
/2006-2007/Alfa/Fyrri Hluti/07.cpp
1c16cc61826670204bd11ec022b2ec6669ff8814
[]
no_license
SuprDewd/Forritunarkeppnin-2
d841c9837e395715f8b6065d030a6d752244d526
c5be01ccb4add0ab2b0ab31bfa2b44d55b5609a4
refs/heads/master
2021-01-17T15:35:54.864513
2012-03-11T19:12:16
2012-03-11T19:12:16
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,048
cpp
#include <vector> #include <map> #include <set> #include <queue> #include <stack> #include <bitset> #include <algorithm> #include <functional> #include <numeric> #include <utility> #include <sstream> #include <iostream> #include <iomanip> #include <cstdio> #include <cmath> #include <cstdlib> #include <ctime> #include <string> #include <cstring> #include <fstream> using namespace std; #define all(o) (o).begin(), (o).end() #define allr(o) (o).rbegin(), (o).rend() #define isOn(S, j) ((S) & 1 << (j)) #define setBit(S, j) (S |= 1 << (j)) #define clearBit(S, j) (S &= ~(1 << (j))) #define toggleBit(S, j) (S ^= 1 << (j)) #define lowBit(S) ((S) & -(S)) #define setAll(S, n) (S = (1 << (n)) - 1) #define INF 2147483647 #define NPOS string::npos template <class T> int size(T x) { return x.size(); } typedef long long ll; typedef pair<int, int> ii; typedef vector<int> vi; typedef vector<ii> vii; int main() { int y; double x; cin >> x >> y; double res = 1; for (int i = 0; i < y; i++) { res *= x; } cout << res << endl; return 0; }
[ "suprdewd@gmail.com" ]
suprdewd@gmail.com
c35f3640e161692525b85c36b9b3500984685bf7
f5eb694dbd4201279109b2a9b66c652ec1b4d650
/C++/SpookyRPG/include/Sprite.h
a641cc8779841f233e29e03e274df45b08e4f6e2
[]
no_license
Krokys9/all-my-work
35a84e770b84eba3d86c161d9209e4dcd3c1aa62
6dc8e9f6044bd4910fc79f126f489f49eca93af9
refs/heads/master
2023-02-27T03:49:10.794094
2021-02-01T21:39:06
2021-02-01T21:39:06
331,379,707
0
0
null
null
null
null
UTF-8
C++
false
false
468
h
#ifndef SPRITE_H_INCLUDED #define SPRITE_H_INCLUDED #include <SDL.h> #include <iostream> #include <vector> #define fps 60 class Sprite { protected: SDL_Surface *image; SDL_Rect rect; int origin_x, origin_y; public: Sprite(Uint32 color, int x, int y, int w , int h); void draw(SDL_Surface *destination); SDL_Surface* get_image() const; bool operator == (const Sprite &other) const; void update(); }; #endif // SPRITE_H_INCLUDED
[ "Krokys9@users.noreply.github.com" ]
Krokys9@users.noreply.github.com
a1c8657a8c765a1576422d67a9d6a10b3aebd04e
85e7114ea63a080c1b9b0579e66c7a2d126cffec
/SDK/SoT_GameplayTags_classes.hpp
b432a9b83e7d5d68ac32832d8d64fbaefeab54a6
[]
no_license
EO-Zanzo/SeaOfThieves-Hack
97094307d943c2b8e2af071ba777a000cf1369c2
d8e2a77b1553154e1d911a3e0c4e68ff1c02ee51
refs/heads/master
2020-04-02T14:18:24.844616
2018-10-24T15:02:43
2018-10-24T15:02:43
154,519,316
0
2
null
null
null
null
UTF-8
C++
false
false
8,909
hpp
#pragma once // Sea of Thieves (1.2.6) SDK #ifdef _MSC_VER #pragma pack(push, 0x8) #endif #include "SoT_GameplayTags_structs.hpp" namespace SDK { //--------------------------------------------------------------------------- //Classes //--------------------------------------------------------------------------- // Class GameplayTags.EditableGameplayTagQuery // 0x0070 (0x0098 - 0x0028) class UEditableGameplayTagQuery : public UObject { public: class FString UserDescription; // 0x0028(0x0010) (Edit, ZeroConstructor, DisableEditOnInstance) unsigned char UnknownData00[0x10]; // 0x0038(0x0010) MISSED OFFSET class UEditableGameplayTagQueryExpression* RootExpression; // 0x0048(0x0008) (Edit, ExportObject, ZeroConstructor, DisableEditOnInstance, InstancedReference, IsPlainOldData) struct FGameplayTagQuery TagQueryExportText_Helper; // 0x0050(0x0048) static UClass* StaticClass() { static auto ptr = UObject::FindObject<UClass>("Class GameplayTags.EditableGameplayTagQuery"); return ptr; } }; // Class GameplayTags.EditableGameplayTagQueryExpression // 0x0000 (0x0028 - 0x0028) class UEditableGameplayTagQueryExpression : public UObject { public: static UClass* StaticClass() { static auto ptr = UObject::FindObject<UClass>("Class GameplayTags.EditableGameplayTagQueryExpression"); return ptr; } }; // Class GameplayTags.EditableGameplayTagQueryExpression_AnyTagsMatch // 0x0028 (0x0050 - 0x0028) class UEditableGameplayTagQueryExpression_AnyTagsMatch : public UEditableGameplayTagQueryExpression { public: struct FGameplayTagContainer Tags; // 0x0028(0x0028) (Edit, DisableEditOnInstance) static UClass* StaticClass() { static auto ptr = UObject::FindObject<UClass>("Class GameplayTags.EditableGameplayTagQueryExpression_AnyTagsMatch"); return ptr; } }; // Class GameplayTags.EditableGameplayTagQueryExpression_AllTagsMatch // 0x0028 (0x0050 - 0x0028) class UEditableGameplayTagQueryExpression_AllTagsMatch : public UEditableGameplayTagQueryExpression { public: struct FGameplayTagContainer Tags; // 0x0028(0x0028) (Edit, DisableEditOnInstance) static UClass* StaticClass() { static auto ptr = UObject::FindObject<UClass>("Class GameplayTags.EditableGameplayTagQueryExpression_AllTagsMatch"); return ptr; } }; // Class GameplayTags.EditableGameplayTagQueryExpression_NoTagsMatch // 0x0028 (0x0050 - 0x0028) class UEditableGameplayTagQueryExpression_NoTagsMatch : public UEditableGameplayTagQueryExpression { public: struct FGameplayTagContainer Tags; // 0x0028(0x0028) (Edit, DisableEditOnInstance) static UClass* StaticClass() { static auto ptr = UObject::FindObject<UClass>("Class GameplayTags.EditableGameplayTagQueryExpression_NoTagsMatch"); return ptr; } }; // Class GameplayTags.EditableGameplayTagQueryExpression_AnyExprMatch // 0x0010 (0x0038 - 0x0028) class UEditableGameplayTagQueryExpression_AnyExprMatch : public UEditableGameplayTagQueryExpression { public: TArray<class UEditableGameplayTagQueryExpression*> Expressions; // 0x0028(0x0010) (Edit, ExportObject, ZeroConstructor) static UClass* StaticClass() { static auto ptr = UObject::FindObject<UClass>("Class GameplayTags.EditableGameplayTagQueryExpression_AnyExprMatch"); return ptr; } }; // Class GameplayTags.EditableGameplayTagQueryExpression_AllExprMatch // 0x0010 (0x0038 - 0x0028) class UEditableGameplayTagQueryExpression_AllExprMatch : public UEditableGameplayTagQueryExpression { public: TArray<class UEditableGameplayTagQueryExpression*> Expressions; // 0x0028(0x0010) (Edit, ExportObject, ZeroConstructor) static UClass* StaticClass() { static auto ptr = UObject::FindObject<UClass>("Class GameplayTags.EditableGameplayTagQueryExpression_AllExprMatch"); return ptr; } }; // Class GameplayTags.EditableGameplayTagQueryExpression_NoExprMatch // 0x0010 (0x0038 - 0x0028) class UEditableGameplayTagQueryExpression_NoExprMatch : public UEditableGameplayTagQueryExpression { public: TArray<class UEditableGameplayTagQueryExpression*> Expressions; // 0x0028(0x0010) (Edit, ExportObject, ZeroConstructor) static UClass* StaticClass() { static auto ptr = UObject::FindObject<UClass>("Class GameplayTags.EditableGameplayTagQueryExpression_NoExprMatch"); return ptr; } }; // Class GameplayTags.GameplayTagAssetInterface // 0x0000 (0x0028 - 0x0028) class UGameplayTagAssetInterface : public UInterface { public: static UClass* StaticClass() { static auto ptr = UObject::FindObject<UClass>("Class GameplayTags.GameplayTagAssetInterface"); return ptr; } bool HasMatchingGameplayTag(const struct FGameplayTag& TagToCheck); bool HasAnyMatchingGameplayTags(const struct FGameplayTagContainer& TagContainer, bool bCountEmptyAsMatch); bool HasAllMatchingGameplayTags(const struct FGameplayTagContainer& TagContainer, bool bCountEmptyAsMatch); void GetOwnedGameplayTags(struct FGameplayTagContainer* TagContainer); }; // Class GameplayTags.BlueprintGameplayTagLibrary // 0x0000 (0x0028 - 0x0028) class UBlueprintGameplayTagLibrary : public UBlueprintFunctionLibrary { public: static UClass* StaticClass() { static auto ptr = UObject::FindObject<UClass>("Class GameplayTags.BlueprintGameplayTagLibrary"); return ptr; } struct FGameplayTag STATIC_MakeLiteralGameplayTag(const struct FGameplayTag& Value); struct FGameplayTagQuery STATIC_MakeGameplayTagQuery(const struct FGameplayTagQuery& TagQuery); bool STATIC_HasAllMatchingGameplayTags(const TScriptInterface<class UGameplayTagAssetInterface>& TagContainerInterface, const struct FGameplayTagContainer& OtherContainer, bool bCountEmptyAsMatch); int STATIC_GetNumGameplayTagsInContainer(const struct FGameplayTagContainer& TagContainer); bool STATIC_DoGameplayTagsMatch(const struct FGameplayTag& TagOne, const struct FGameplayTag& TagTwo, TEnumAsByte<EGameplayTagMatchType> TagOneMatchType, TEnumAsByte<EGameplayTagMatchType> TagTwoMatchType); bool STATIC_DoesTagAssetInterfaceHaveTag(const TScriptInterface<class UGameplayTagAssetInterface>& TagContainerInterface, TEnumAsByte<EGameplayTagMatchType> ContainerTagsMatchType, const struct FGameplayTag& Tag, TEnumAsByte<EGameplayTagMatchType> TagMatchType); bool STATIC_DoesContainerMatchTagQuery(const struct FGameplayTagContainer& TagContainer, const struct FGameplayTagQuery& TagQuery); bool STATIC_DoesContainerMatchAnyTagsInContainer(const struct FGameplayTagContainer& TagContainer, const struct FGameplayTagContainer& OtherContainer, bool bCountEmptyAsMatch); bool STATIC_DoesContainerMatchAllTagsInContainer(const struct FGameplayTagContainer& TagContainer, const struct FGameplayTagContainer& OtherContainer, bool bCountEmptyAsMatch); bool STATIC_DoesContainerHaveTag(const struct FGameplayTagContainer& TagContainer, TEnumAsByte<EGameplayTagMatchType> ContainerTagsMatchType, const struct FGameplayTag& Tag, TEnumAsByte<EGameplayTagMatchType> TagMatchType); bool STATIC_AppendGameplayTagContainers(const struct FGameplayTagContainer& InTagContainer, struct FGameplayTagContainer* InOutTagContainer); }; // Class GameplayTags.GameplayTagsManager // 0x0178 (0x01A0 - 0x0028) class UGameplayTagsManager : public UObject { public: unsigned char UnknownData00[0x118]; // 0x0028(0x0118) MISSED OFFSET TArray<class UDataTable*> GameplayTagTables; // 0x0140(0x0010) (ZeroConstructor) unsigned char UnknownData01[0x50]; // 0x0150(0x0050) MISSED OFFSET static UClass* StaticClass() { static auto ptr = UObject::FindObject<UClass>("Class GameplayTags.GameplayTagsManager"); return ptr; } struct FGameplayTag RequestGameplayTag(const struct FName& TagName, bool ErrorIfNotFound); }; // Class GameplayTags.GameplayTagsSettings // 0x0010 (0x0038 - 0x0028) class UGameplayTagsSettings : public UObject { public: TArray<class FString> GameplayTags; // 0x0028(0x0010) (Edit, ZeroConstructor, Config) static UClass* StaticClass() { static auto ptr = UObject::FindObject<UClass>("Class GameplayTags.GameplayTagsSettings"); return ptr; } }; } #ifdef _MSC_VER #pragma pack(pop) #endif
[ "zp2kshield@gmail.com" ]
zp2kshield@gmail.com
132dc2f91f488336f02e6507613eb245eec4d97d
2fcc9ad89cf0c85d12fa549f969973b6f4c68fdc
/LibMathematics/Meshes/Wm5EdgeKey.h
605663779c2280025257583ac770dcffa78d5d68
[ "BSL-1.0" ]
permissive
nmnghjss/WildMagic
9e111de0a23d736dc5b2eef944f143ca84e58bc0
b1a7cc2140dde23d8d9a4ece52a07bd5ff938239
refs/heads/master
2022-04-22T09:01:12.909379
2013-05-13T21:28:18
2013-05-13T21:28:18
null
0
0
null
null
null
null
UTF-8
C++
false
false
587
h
// Geometric Tools, LLC // Copyright (c) 1998-2012 // 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: 5.0.1 (2010/10/01) #ifndef WM5EDGEKEY_H #define WM5EDGEKEY_H #include "Wm5MathematicsLIB.h" namespace Wm5 { class WM5_MATHEMATICS_ITEM EdgeKey { public: EdgeKey (int v0 = -1, int v1 = -1); bool operator< (const EdgeKey& key) const; operator size_t () const; int V[2]; }; #include "Wm5EdgeKey.inl" } #endif
[ "bazhenovc@bazhenovc-laptop" ]
bazhenovc@bazhenovc-laptop
ae1ee466e9fe6eb99daf18aa84ef7364ddc9d2f9
26ac7837de540d915cdfa7783a65dde9bd311e4b
/Source/TiAALS/ExternalObjects/FFTRelated/IRSpectrogramObject/IRSpectrogram/IRSpectrogram/IRSpectrogramComponent.cpp
3b8c1b813ff5af95f3386e3ee870e17c4cf89ee9
[]
no_license
KeitaroTakahashi/TiAALS_FULL
cfdf98a81f5e95f35fb3c7f36837d35856cdcf88
21cbdd04c5caf7b7de7bcc638056ad5af9ded5b0
refs/heads/master
2023-02-20T17:43:19.929814
2021-01-23T13:57:54
2021-01-23T13:57:54
320,263,467
0
0
null
null
null
null
UTF-8
C++
false
false
1,683
cpp
// // IRSpectrogramComponent.cpp // IRiMaS // // Created by Keitaro on 25/07/2019. // #include "IRSpectrogramComponent.hpp" IRSpectrogramComponent::IRSpectrogramComponent(IRNodeObject* nodeObject, IRStr* str) { this->spectrogram = std::make_shared<IRSpectrogram>(nodeObject, str); addAndMakeVisible(this->spectrogram.get()); } IRSpectrogramComponent::~IRSpectrogramComponent() { } void IRSpectrogramComponent::resized() { std::cout << "IRSpectrogramComponent resized " << getWidth() << std::endl; this->spectrogram->parentSizeChanged(getWidth(), getHeight()); } void IRSpectrogramComponent::paint(Graphics& g) { g.fillAll(Colours::yellow); int w = getWidth(); int h = getHeight(); g.setColour(Colours::lightgrey.brighter().brighter()); int i = 0; Path p; for(i=0;i<=w;i+=50) { p.startNewSubPath(i, 0); p.lineTo(i, h); p.startNewSubPath(0, i); p.lineTo(w, i); } p.closeSubPath(); g.strokePath(p, PathStrokeType(2)); for(i=0;i<=w;i+=10) { p.startNewSubPath(i, 0); p.lineTo(i, h); p.startNewSubPath(0, i); p.lineTo(w, i); } p.closeSubPath(); g.strokePath(p, PathStrokeType(1)); } void IRSpectrogramComponent::setMainComponentBounds(Rectangle<int> area) { this->spectrogram->setBounds(area); } void IRSpectrogramComponent::setVisibleArea(Rectangle<int> area) { //std::cout << "iRSpectrogramComponent : size changed " << getWidth()<< std::endl; this->spectrogram->setVisibleArea(area, juce::Point<int>(getWidth(), getHeight())); repaint(); }
[ "neoterize@mac.com" ]
neoterize@mac.com
d4da5ff9e8453ae84549d45319917abade4f67a1
3dda82c149b6f4db9121d7130d3a1f0736148a35
/PatternGenerator/old_main.cpp
4977e0c6dfcc260a09aeb945c0fa8d40ef9f1154
[]
no_license
teiband/arduino-led-interface-rtdb
edcc6006118f43d6b06a380245a20c2db4ba1afe
643db913c1e34205e429fa325c382cbd83e39c75
refs/heads/master
2021-01-10T02:58:53.427672
2016-03-09T09:46:51
2016-03-09T09:46:51
53,485,871
0
0
null
null
null
null
UTF-8
C++
false
false
1,430
cpp
/* * main.cpp * * Created on: 15 Nov 2015 * Author: Thomas Eiband * * thomas.eiband@tum.de */ #include "PatternGenerator.h" #include <getopt.h> #include <iostream> #include <unistd.h> // for sleep() #include <ArduinoData.h> using namespace std; #include <kogmo_rtdb.hxx> using namespace KogniMobil; static struct option long_options[] = { {"device", required_argument, 0, 'd'}, {"verbose", no_argument, 0, 'v'}, {0,0,0,0} }; int main(int argc, char *argv[]) { cout << "Establishing database connection ..." << endl; RTDBConn DBC("PatternGenerator", 5.0); cout << "done" << endl << endl; ArduinoData rtdb_obj(DBC, "ArduinoData"); PatternGenerator pg(rtdb_obj); cout << "Searching RTDB object \"ArduinoData\"... "; rtdb_obj.RTDBSearchWait("ArduinoData"); cout << "done" << endl; cout << "Entering loop and generating some patterns" << endl; while (1) { // TODO implement pattern here, its directly written into pattern_t pattern given in constructor from rtdb object pg.setColor(0x10, 0x00, 0x00); pg.setFillPattern(); // TODO do not forget!!! pg.update(); cout << "Write to RTDB ..."; rtdb_obj.RTDBWrite(); cout << "done" << endl; sleep(1); // wait until cycle done // (signal for ReadWaitNext() in Arduino main) DBC.CycleDone(); } return 0; }
[ "thomas.eiband@gmail.com" ]
thomas.eiband@gmail.com
9dd7a66c6dbe4843bb7089ac59f1d1fa2444068d
682bdce8f2892af6f1c2cf3c38d8f891247a781d
/GK_Lab4/shader.hpp
74b2fdfa04042477d0899df27d06d6aca8a5038d
[]
no_license
rottensunday/GK_Projekt3D
7431feffc1a3c92a1f569251f67c6b8b2add6af0
8a415f2aeed122959fae9d8cc34fd6781d84b2c0
refs/heads/master
2021-01-02T11:45:43.823687
2020-02-10T20:47:40
2020-02-10T20:47:40
239,608,495
1
0
null
null
null
null
UTF-8
C++
false
false
7,289
hpp
#pragma once #include <stdio.h> #include <string> #include <vector> #include <iostream> #include <fstream> #include <algorithm> #include <sstream> using namespace std; #include <stdlib.h> #include <string.h> #include <glad/glad.h> #include <glm/glm.hpp> // THIS IS HELPER CLASS TO LOAD AND USE SHADER. // IT HOLDS SHADER ID, AND HAS METHODS TO MODIFY // PROGRAM EASILY. // -- THIS CODE WAS TAKEN FROM https://learnopengl.com/ MODEL LOADING TUTORIAL -- // class Shader { public: GLuint ID; Shader(const char* vertexPath, const char* fragmentPath, const char* geometryPath = nullptr) { // 1. retrieve the vertex/fragment source code from filePath std::string vertexCode; std::string fragmentCode; std::string geometryCode; std::ifstream vShaderFile; std::ifstream fShaderFile; std::ifstream gShaderFile; // ensure ifstream objects can throw exceptions: vShaderFile.exceptions(std::ifstream::failbit | std::ifstream::badbit); fShaderFile.exceptions(std::ifstream::failbit | std::ifstream::badbit); gShaderFile.exceptions(std::ifstream::failbit | std::ifstream::badbit); try { // open files vShaderFile.open(vertexPath); fShaderFile.open(fragmentPath); std::stringstream vShaderStream, fShaderStream; // read file's buffer contents into streams vShaderStream << vShaderFile.rdbuf(); fShaderStream << fShaderFile.rdbuf(); // close file handlers vShaderFile.close(); fShaderFile.close(); // convert stream into string vertexCode = vShaderStream.str(); fragmentCode = fShaderStream.str(); // if geometry shader path is present, also load a geometry shader if (geometryPath != nullptr) { gShaderFile.open(geometryPath); std::stringstream gShaderStream; gShaderStream << gShaderFile.rdbuf(); gShaderFile.close(); geometryCode = gShaderStream.str(); } } catch (std::ifstream::failure e) { std::cout << "ERROR::SHADER::FILE_NOT_SUCCESFULLY_READ" << std::endl; } const char* vShaderCode = vertexCode.c_str(); const char* fShaderCode = fragmentCode.c_str(); // 2. compile shaders unsigned int vertex, fragment; // vertex shader vertex = glCreateShader(GL_VERTEX_SHADER); glShaderSource(vertex, 1, &vShaderCode, NULL); glCompileShader(vertex); checkCompileErrors(vertex, "VERTEX"); // fragment Shader fragment = glCreateShader(GL_FRAGMENT_SHADER); glShaderSource(fragment, 1, &fShaderCode, NULL); glCompileShader(fragment); checkCompileErrors(fragment, "FRAGMENT"); // if geometry shader is given, compile geometry shader unsigned int geometry; if (geometryPath != nullptr) { const char* gShaderCode = geometryCode.c_str(); geometry = glCreateShader(GL_GEOMETRY_SHADER); glShaderSource(geometry, 1, &gShaderCode, NULL); glCompileShader(geometry); checkCompileErrors(geometry, "GEOMETRY"); } // shader Program ID = glCreateProgram(); glAttachShader(ID, vertex); glAttachShader(ID, fragment); if (geometryPath != nullptr) glAttachShader(ID, geometry); glLinkProgram(ID); checkCompileErrors(ID, "PROGRAM"); // delete the shaders as they're linked into our program now and no longer necessery glDeleteShader(vertex); glDeleteShader(fragment); if (geometryPath != nullptr) glDeleteShader(geometry); } Shader(){} void use() const { glUseProgram(ID); } // utility uniform functions // ------------------------------------------------------------------------ void setBool(const std::string& name, bool value) const { glUniform1i(glGetUniformLocation(ID, name.c_str()), (int)value); } // ------------------------------------------------------------------------ void setInt(const std::string& name, int value) const { glUniform1i(glGetUniformLocation(ID, name.c_str()), value); } // ------------------------------------------------------------------------ void setFloat(const std::string& name, float value) const { glUniform1f(glGetUniformLocation(ID, name.c_str()), value); } // ------------------------------------------------------------------------ void setVec2(const std::string& name, const glm::vec2& value) const { glUniform2fv(glGetUniformLocation(ID, name.c_str()), 1, &value[0]); } void setVec2(const std::string& name, float x, float y) const { glUniform2f(glGetUniformLocation(ID, name.c_str()), x, y); } // ------------------------------------------------------------------------ void setVec3(const std::string& name, const glm::vec3& value) const { glUniform3fv(glGetUniformLocation(ID, name.c_str()), 1, &value[0]); } void setVec3(const std::string& name, float x, float y, float z) const { glUniform3f(glGetUniformLocation(ID, name.c_str()), x, y, z); } // ------------------------------------------------------------------------ void setVec4(const std::string& name, const glm::vec4& value) const { glUniform4fv(glGetUniformLocation(ID, name.c_str()), 1, &value[0]); } void setVec4(const std::string& name, float x, float y, float z, float w) const { glUniform4f(glGetUniformLocation(ID, name.c_str()), x, y, z, w); } // ------------------------------------------------------------------------ void setMat2(const std::string& name, const glm::mat2& mat) const { glUniformMatrix2fv(glGetUniformLocation(ID, name.c_str()), 1, GL_FALSE, &mat[0][0]); } // ------------------------------------------------------------------------ void setMat3(const std::string& name, const glm::mat3& mat) const { glUniformMatrix3fv(glGetUniformLocation(ID, name.c_str()), 1, GL_FALSE, &mat[0][0]); } // ------------------------------------------------------------------------ void setMat4(const std::string& name, const glm::mat4& mat) const { glUniformMatrix4fv(glGetUniformLocation(ID, name.c_str()), 1, GL_FALSE, &mat[0][0]); } void checkCompileErrors(GLuint shader, std::string type) { GLint success; GLchar infoLog[1024]; if (type != "PROGRAM") { glGetShaderiv(shader, GL_COMPILE_STATUS, &success); if (!success) { glGetShaderInfoLog(shader, 1024, NULL, infoLog); std::cout << "ERROR::SHADER_COMPILATION_ERROR of type: " << type << "\n" << infoLog << "\n -- --------------------------------------------------- -- " << std::endl; } } else { glGetProgramiv(shader, GL_LINK_STATUS, &success); if (!success) { glGetProgramInfoLog(shader, 1024, NULL, infoLog); std::cout << "ERROR::PROGRAM_LINKING_ERROR of type: " << type << "\n" << infoLog << "\n -- --------------------------------------------------- -- " << std::endl; } } } };
[ "39813108+rottensunday@users.noreply.github.com" ]
39813108+rottensunday@users.noreply.github.com
08578490aa6dd909147a0046090bed151f031190
666e2ff7aa1a4bcf3592331062ce774373fe6fa6
/crypto/openssl/tls_socket.h
d0f4fbe403c45bdee5c0918e7f5d28e915deb756
[]
no_license
asyr625/mini_sip
aeffd6e5ea1dafafa817b1137859b41351fe9580
12ea4b9a03585b5c7e5b5faeeed0a5bc6a9c19cc
refs/heads/master
2021-01-20T12:06:33.212419
2015-11-24T02:33:26
2015-11-24T02:33:26
46,761,914
0
1
null
null
null
null
UTF-8
C++
false
false
117
h
#ifndef TLS_SOCKET_H #define TLS_SOCKET_H class Ossl_Socket { public: Ossl_Socket(); }; #endif // TLS_SOCKET_H
[ "619695356@qq.com" ]
619695356@qq.com
73d49197778c92f690447ccb9c3783091ae9f4c1
f867c0f5f582a1b44579413c023fcc8f5cd7a6b2
/MainBoosterCat/dirty.ino
6c41403e927f8acc72f27aab051439428799c202
[]
no_license
Happy-Ferret/BoosterCat
e23dd9cef4ababab8b5d4ff343055f43fc51235e
c6d4cc3d764c95ecb5a5c09beb29bac1271e1053
refs/heads/master
2020-07-08T03:46:06.426608
2017-01-24T15:16:21
2017-01-24T15:16:21
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,760
ino
// BoosterCat Dirty Status Occurance // setups for communicating with I2C accelerometer void WireRequestArray(int address, uint8_t* buffer, uint8_t amount); void WireWriteRegister(int address, uint8_t reg, uint8_t value); void WireWriteByte(int address, uint8_t value); // Needed Register Maps static uint8_t const acc = 0x1D; static uint8_t const Power_Ctl = 0x2d; static uint8_t const Data_Format = 0x31; //set range for data; D1 = 1, D0 = 0 to be 8g/ D1 =0, D0 = 1 to be 4g static uint8_t const Read = 0x32; // x-Axis Data 0 static uint8_t const Thresh_Act = 0x24; // Threshold for detecting activity static uint8_t const Thresh_Inact = 0x25; // Threshold for detecting inactivity static uint8_t const Act_Inact = 0x27; //Activity/Inactivity Control static uint8_t const Event_Set = 0x2E; // Enable interruption static uint8_t const Event_Read = 0x30; // read if interrupted // prompt the player that the Booster Cat is unclean; displaying on the LCD screen void unclean(){ if (counter==0){ OrbitOledClear(); OrbitOledMoveTo(0,10); OrbitOledDrawString("Your BoosterCat"); OrbitOledMoveTo(0,20); OrbitOledDrawString("is dirty."); OrbitOledUpdate(); delay(2000); OrbitOledClear(); OrbitOledMoveTo(0,0); OrbitOledDrawString("Go to Menu"); OrbitOledMoveTo(0,10); OrbitOledDrawString("and clean it"); OrbitOledUpdate(); delay(2000); } counter++; // counter implemented so that there is no continuous prompt about the same occurance } // The player select the clean function; increase cleanliness of the Booster Cat stats clean(stats cat){ unsigned long time_before = millis(); unsigned long time_after = millis(); int before = cat.cleanliness; // Give instruction to the player OrbitOledClear(); OrbitOledMoveTo(0,10); OrbitOledDrawString("Shake screen"); OrbitOledMoveTo(0,20); OrbitOledDrawString("to clean"); OrbitOledUpdate(); // setup accelecerometer settings // set range of data WireWriteRegister(acc, Data_Format, 1); //set the range of measured acc to +/-4g WireWriteRegister(acc, Act_Inact, 0x70); // set to dc-coupled operation WireWriteRegister(acc, Thresh_Act, 65); //if the measured value is greater than the theshold value, then it is active WireWriteRegister(acc, Event_Set, 0x10); size_t const num_bytes = 5; uint8_t shake[num_bytes]={0}; // wake up the accelerometer, then start measuring WireWriteRegister(acc, Power_Ctl, 1 << 3); delay(300); // Accelerometer aquires data while no interrupt signal (for activation) is sent and while three seconds have not passed while(shake[3] == 0 && (time_after-time_before) <= 3000){ time_after = millis(); // Obtain interrupt signal for activation WireWriteByte(acc, 0x30); WireRequestArray(acc, shake, num_bytes); delay(100); } // if an interrupt signal for activation detected, then increase cleanliness if (shake[3]){ if (cat.cleanliness > 70){ cat.cleanliness=100; OrbitOledClear(); OrbitOledMoveTo(0,0); OrbitOledDrawString("Your cat is"); OrbitOledMoveTo(0,10); OrbitOledDrawString("clean."); OrbitOledUpdate(); delay(2000); }else { cat.cleanliness += 30; OrbitOledClear(); OrbitOledMoveTo(0,0); OrbitOledDrawString("Your BoosterCat"); OrbitOledMoveTo(0,10); OrbitOledDrawString("is a bit cleaner."); OrbitOledUpdate(); delay(2000); } }else { // If nothing happened, info user OrbitOledClear(); OrbitOledMoveTo(0,0); OrbitOledDrawString("Try Again"); OrbitOledUpdate(); delay(2000); } turnOff(); counter = 0; // set counter 0 for new prompts menu_init = 0; // return to menu return cat; }
[ "noreply@github.com" ]
Happy-Ferret.noreply@github.com
6b44f4244cd775cd7746885aaafdb30212ec01db
4a0993484a1f9882dd7ec710d6f26713a12f3d27
/codeforce/292E.cpp
3b9d732d3f3966227ccb19d719e01cd38b680d3f
[]
no_license
zhouyuzju/code
fbe6a526260119ba42638d65bffe339063365bb0
8401d6c9eb522abd9cb993818cba9d6587ca13d8
refs/heads/master
2020-05-18T06:34:25.421161
2013-09-06T16:52:55
2013-09-06T16:52:55
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,990
cpp
/** * Typical segment tree problem * 2013/4/18 */ #include <cstdio> #include <iostream> #include <cstring> #define MAX 1 << 20 #define INIT -1000000000 #define MULTI -1000000001 #define PR(x) cout << #x << " = " << x << endl using namespace std; struct node{ int l,r,c; } segtree[MAX]; void init(int l,int r,int n){ segtree[n].l = l; segtree[n].r = r; segtree[n].c = INIT; //printf("%d,%d,%d\n",l,r,n); if(l != r){ int mid = (l + r) / 2; init(l,mid,2 * n); init(mid + 1,r,2 * n + 1); } } void update(int l,int r,int n,int c){ //PR(l);PR(r);PR(n);PR(c); if(segtree[n].l == l && segtree[n].r == r){ segtree[n].c = c; return; } if(segtree[n].c != MULTI){ segtree[2 * n].c = segtree[n].c; segtree[2 * n + 1].c = segtree[n].c; segtree[n].c = MULTI; } int mid = (segtree[n].l + segtree[n].r) / 2; if(mid >= r) update(l,r,2 * n,c); else if(mid < l) update(l,r,2 * n + 1,c); else{ update(l,mid,2 * n,c); update(mid + 1,r,2 * n + 1,c); } } int query(int n,int k){ if(segtree[n].c != MULTI) return segtree[n].c; int mid = (segtree[n].l + segtree[n].r) / 2; if(segtree[n].l <= k && mid >= k) query(2 * n,k); else if(mid < k && k <= segtree[n].r) query(2 * n + 1,k); else if(segtree[n].l == k && k == segtree[n].r){ return segtree[n].c; } } int main(){ int n,m; scanf("%d%d",&n,&m); int a[n + 1],b[n + 1]; for(int i = 1;i <= n;i++) scanf("%d",&a[i]); for(int i = 1;i <= n;i++) scanf("%d",&b[i]); init(1,n,1); for(int i = 0;i < m;i++){ int t; scanf("%d",&t); if(t == 2){ int k; scanf("%d",&k); int move = query(1,k); //for(int s = 1;s < 2 * n;s++) // printf("%d,%d,%d\n",segtree[s].l,segtree[s].r,segtree[s].c); if(move == INIT) printf("%d\n",b[k]); else printf("%d\n",a[k + move]); } else if(t == 1){ int x,y,k; scanf("%d%d%d",&x,&y,&k); update(y,y + k - 1,1,x - y); } } return 0; }
[ "jwjzy1020@gmail.com" ]
jwjzy1020@gmail.com
10265cfb0b373b1b8920f9f5573c1b2051fdbce6
561ef87c682feea936a1622ddfb07e6aa7182807
/bioinf/bioinf.hh
b63c77c38cc6f917cf73fd626718b52179c5529f
[]
no_license
deltadev/dpj
80d5b584a0baa01aee007439f3c29e89d3a892f0
93c879c9a5696b305a1a0b39058093cfd3294d8f
HEAD
2016-09-05T23:10:26.209537
2014-09-29T21:27:01
2014-09-29T21:27:01
null
0
0
null
null
null
null
UTF-8
C++
false
false
4,772
hh
#ifndef DPJ_BIOINF_HH_ #define DPJ_BIOINF_HH_ #include <cmath> #include <string> #include <vector> #include <algorithm> #include <numeric> #include <fstream> #include <iostream> namespace dpj { namespace bioinf { inline void unsignedToNucleotides(unsigned n, std::string& s) { char nucs[] = "ACGT"; size_t l = s.size(); for(unsigned pos = 0; pos < l; ++pos) { unsigned mask = 3 << (2 * pos); char nuc = nucs[(n & mask) >> (2 * pos)]; s[l - pos - 1] = nuc; } } struct NucleotidesToBits { unsigned operator()(unsigned currentBits, char nextSymbol) { currentBits <<= 2; unsigned bits = 0; if (nextSymbol == 'A' || nextSymbol == 'a') bits = 0; else if (nextSymbol == 'C' || nextSymbol == 'c') bits = 1; else if (nextSymbol == 'G' || nextSymbol == 'g') bits = 2; else if (nextSymbol == 'T' || nextSymbol == 't') bits = 3; else { std::cerr << "encountered symbol not in alphabet: " << nextSymbol << '\n'; exit(EXIT_FAILURE); } return currentBits | bits; } }; struct NucleotidesToCompBits { unsigned operator()(unsigned currentBits, char nextSymbol) { currentBits <<= 2; unsigned bits = 0; if (nextSymbol == 'A' || nextSymbol == 'a') bits = 3; else if (nextSymbol == 'C' || nextSymbol == 'c') bits = 2; else if (nextSymbol == 'G' || nextSymbol == 'g') bits = 1; else if (nextSymbol == 'T' || nextSymbol == 't') bits = 0; else exit(EXIT_FAILURE); return currentBits | bits; } }; template<typename It> unsigned nucleotidesToUnsigned(It b, It e) { return std::accumulate(b, e, 0, NucleotidesToBits()); } template<typename It> unsigned nucleotideHash(It b, It e) { unsigned hash = std::accumulate(b, e, 0, NucleotidesToBits()); return hash + 4 * (::pow(4, std::distance(b, e) - 1) - 1) / 3; } template<typename It> unsigned nucleotideRevCompHash(It b, It e) { unsigned hash = std::accumulate(b, e, 0, NucleotidesToCompBits()); // Now we need to rotate the bits... size_t len = std::distance(b, e); unsigned newHash = 0; for (unsigned i = 0; i < len; ++i) { newHash <<= 2; newHash |= hash & 3; hash >>= 2; } return newHash + 4 * (::pow(4, len - 1) - 1) / 3; } inline std::string inverseNucleotideHash(unsigned hash) { unsigned l = 1; unsigned q = 4; hash = 3 * hash + 4; while (hash / q) { q *= 4; l++; } std::string unHash(l - 1, ' '); unsignedToNucleotides((hash - q / 4) / 3, unHash); return unHash; } struct complement { char operator()(char c) { if (c == 'A' || c == 'a') return 'T'; else if (c == 'C' || c == 'c') return 'G'; else if (c == 'G' || c == 'g') return 'C'; else if (c == 'T' || c == 't') return 'A'; else return 'N'; } }; template<typename It> void complementNucleotides(It b, It e) { std::transform(b, e, b, complement()); } template<typename It> void reverseComplementNucleotides(It b, It e) { std::reverse(b, e); std::transform(b, e, b, complement()); } } // // The PWM should have the natural layout: // // col1 col2 ... colN // A m11 m12 ... m1n // C m21 // G m31 // T m41 ... m4n // // or its transpose. // inline std::vector<float> readPWM(std::istream& is, bool rowMajorStorage) { float tok; std::vector<float> tmp; while (is >> tok) { tmp.push_back(tok); } std::vector<float> pwm(tmp); if ( ! rowMajorStorage) { // transpose. unsigned motifLength = (unsigned)tmp.size()/4; unsigned counter = 0; for (auto it = tmp.begin(); it != tmp.end(); ++it) { unsigned row = counter % 4; unsigned col = counter / 4; pwm[row * motifLength + col] = *it; counter++; } } return pwm; } inline std::string readFasta(std::string fileName) { std::string fasta, line; std::ifstream iFile(fileName.c_str()); std::getline(iFile, line); // header unsigned lineCounter = 0; while (iFile >> line) { lineCounter++; fasta += line; } std::cerr << "read " << lineCounter << " lines of fasta.\n"; return fasta; } } #endif /* DPJ_BIOINF_HH_ */
[ "dj@deltadev.co.uk" ]
dj@deltadev.co.uk
4567259402d82f0fc4d572564d2947f8497e0d5e
1e40eb8bb863992749e8986f4f3e2e7a54f7632b
/CustomList/listA.h
73754568f1bf5cf480aa83b0792bf924321de7fc
[]
no_license
MarcusCasey/MultiDemArrays
468b4ff9b4c82803d46002806e9564f56a0b96c5
64e3153e9dd0abc137cddfbde34d2865df03181c
refs/heads/master
2020-11-28T20:34:46.883818
2019-12-25T04:49:04
2019-12-25T04:49:04
229,914,445
0
0
null
null
null
null
UTF-8
C++
false
false
605
h
/** * Marcus Casey * CS202 * Section 1103 */ #include <iostream> using namespace std; class ListA { public: ListA(int); ListA(const ListA&); ~ListA(); bool goToBeginning(); bool goToEnd(); bool goToNext(); bool goToPrior(); bool insertBefore(int); bool insertAfter(int); bool remove(); bool isEmpty() const; bool isFull() const; void clear(); // unused bool get(int&) const; //added get fnc ListA& operator=(const ListA&); friend ostream& operator<<(ostream&, const ListA&); private: int size; int actual; int cursor; int *data; };
[ "marcus.casey@outlook.com" ]
marcus.casey@outlook.com
dd7aef2cec036185374c90a7d7166abd4aeba424
e8874f9119df1bc95970549bb08a93a390aecb01
/Exceptions.cpp
2713bc1583ea35b54d865596ad8c6630c22edc7d
[]
no_license
yesalusn/ucd-csci2312-pa3
2f07c38c251389f14e3ff9c69dacb8109792ad84
7f785f185625849e14a52a01170476ba12ff8bf6
refs/heads/master
2021-01-20T17:21:22.784790
2016-03-31T03:52:20
2016-03-31T03:52:20
54,694,249
0
0
null
2016-03-25T04:20:01
2016-03-25T04:20:00
null
UTF-8
C++
false
false
2,331
cpp
// // Created by Nikki on 3/29/2016. // #include <string> #include <iostream> #include "Exceptions.h" using std::string; using std::ostream; using std::istream; namespace Clustering { OutOfBoundsEx::OutOfBoundsEx(unsigned int c, int r): __current(c), __rhs(r) { this->__name = "OutOfBoundsEx"; } unsigned int OutOfBoundsEx::getCurrent() const { return __current; } int OutOfBoundsEx::getRhs() const { return __rhs; } string OutOfBoundsEx::getName() const { return __name; } ostream &operator<<(ostream &os, const OutOfBoundsEx &ex) { os << ex.getName() << ", " << ex.getCurrent() << ", " << ex.getRhs(); return os; } DimensionalityMismatchEx::DimensionalityMismatchEx(unsigned int c, unsigned int r): __current(c), __rhs(r) { this->__name = "DimensionalityMismatchEx"; } unsigned int DimensionalityMismatchEx::getCurrent() const { return __current; } unsigned int DimensionalityMismatchEx::getRhs() const { return __rhs; } string DimensionalityMismatchEx::getName() const { return __name; } ostream &operator<<(ostream &os, const DimensionalityMismatchEx &ex) { os << ex.getName() << ", " << ex.getCurrent() << ", " << ex.getRhs(); return os; } ZeroClustersEx::ZeroClustersEx() { this->__name = "ZeroClustersEx"; } string ZeroClustersEx::getName() const { return __name; } ostream &operator<<(ostream &os, const ZeroClustersEx &ex) { os << ex.getName(); return os; } DataFileOpenEx::DataFileOpenEx(string filename): __filename(filename) { this->__name = "DataFileOpenEx"; } string DataFileOpenEx::getFilename() const { return __filename; } string DataFileOpenEx::getName() const { return __name; } ostream &operator<<(ostream &os, const DataFileOpenEx &ex) { os << ex.getName() << ", " << ex.getFilename(); return os; } ZeroDimensionsEx::ZeroDimensionsEx() { this->__name = "ZeroDimensionsEx"; } string ZeroDimensionsEx::getName() const { return __name; } ostream &operator<<(ostream &os, const ZeroDimensionsEx &ex) { os << ex.getName(); return os; } EmptyClusterEx::EmptyClusterEx() { this->__name = "EmptyClusterEx"; } string EmptyClusterEx::getName() const { return __name; } ostream &operator<<(ostream &os, const EmptyClusterEx &ex) { os << ex.getName(); return os; } }
[ "nikki.yesalusky@ucdenver.edu" ]
nikki.yesalusky@ucdenver.edu
8d13278682c02fdd9e3c80e87a30d85f38be4e45
fde0eeab2c085cd736105caf987e33854fc6c6f5
/basesim.cpp
c10361b30986d037d5e79183715a2f990b602b92
[]
no_license
JerryZhong/Similarity
d5facf2164c3f36b0e4d59c93189d84a583601a0
c9fa8098ca4c2be6d719bf56b120ed29368034ad
refs/heads/master
2021-01-20T07:47:31.421832
2014-02-12T13:05:19
2014-02-12T13:05:19
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,595
cpp
#include<stdio.h> #include<algorithm> #include"basesim.h" namespace crystal{ using namespace std; basesim::basesim():_min_occur_user(0),_max_occur_user(0),_topn_sims(0X7FFFFFF) { } basesim::~basesim() { } int basesim::postprocess() { map<int,vector<sim_t> > ::iterator iter = _item_sims.begin(),iter_end = _item_sims.end(); for(;iter!=iter_end;iter++) sort(iter->second.begin(),iter->second.end(),larger_sim);//<alogrithm> return 0; } int basesim::dump(const char * outputfile) { FILE *fp = fopen(outputfile,"w"); if(fp==NULL) { fprintf(stderr,"open %f error!",outputfile); exit(1); } map<int, vector<sim_t> >::iterator iter = _item_sims.begin(), iter_end = _item_sims.end(); for(;iter!=iter_end;iter++) { int mid = iter->first; if(iter->second.size()==0) continue; fprintf(fp,"%d ",mid); int num = (int)iter->second.size() > _topn_sims ? _topn_sims : (int)iter->second.size(); for(int i=0;i<num;i++) fprintf(fp,"%d,%f ",iter->second[i]._item, iter->second[i]._sim) ; fprintf(fp,"\n") ; } return 0; } void basesim::set_min_occur_user(int limit) { _min_occur_user=limit; } void basesim::set_max_occur_user(int limit) { _max_occur_user=limit; } void basesim::set_topn_sims(int limit) { _topn_sims=limit; } }
[ "zhongwei19900209@gmail.com" ]
zhongwei19900209@gmail.com
35260450ae252cfde0811e22a40ba55770f7a1ef
37baab470e4d1f55119b8e00447e490ee8eaa93e
/Car.h
3df75dbea3e48179f9e8a4de14b2835e2c2388c5
[]
no_license
muneebGH/simple-car-application-
74538aa55a1e05ca82eb0a227059323f1214c4de
34e7400ed239cebc2155cb1f7356c46e3f7486dd
refs/heads/master
2020-12-01T13:55:50.696007
2019-12-28T18:49:54
2019-12-28T18:49:54
230,650,507
0
0
null
null
null
null
UTF-8
C++
false
false
394
h
#include<iostream> #include"MyOOPString.h" using namespace std; class Car { private: int yearModel; char make[30]; int speed; float maxSpeed; public: Car(); void setYearModel(int YM); void setMake(const char * p); void setSpeed(int s); void setMaxSpeed(float MS); int getYearModel(); const char * getMake(); int getSpeed(); void accelarate(); void brake(); };
[ "muneeb.github@gmail.com" ]
muneeb.github@gmail.com
c27530fcc3f2d21c1308b8e933e9a550070e462c
1bb6a0b3692b5468f7d148788298320ac3ba2a23
/Practice/2022/rock_mtn/b.cpp
c9140eef0359e38e726badbc23f583a90e856bc1
[]
no_license
ablondal/comp-prog
ee6ea5c0b32d7fbe0321a4b9919a9cec23fe85f6
725e369476993307874f9f5d6e2e7299918251a0
refs/heads/master
2022-10-08T05:40:39.206721
2022-09-25T22:29:49
2022-09-25T22:29:49
243,620,860
0
0
null
null
null
null
UTF-8
C++
false
false
489
cpp
#include <bits/stdc++.h> using namespace std; // incomplete #define rep(i, a, b) for(int i = a; i < (b); ++i) #define all(x) begin(x), end(x) #define sz(x) (int)(x).size() typedef long long ll; typedef pair<int, int> pii; typedef vector<int> vi; typedef vector<ll> vll; typedef complex<double> cd; int main() { ios_base::sync_with_stdio(false); cin.tie(NULL); double a; cin >> a; a /= 100; double b = (1-a); a = 1/a; b = 1/b; cout << setprecision(16) << a << endl << b << endl; }
[ "ari.blondal@gmail.com" ]
ari.blondal@gmail.com
4461926bb491fc41f8b977665345bfa4be177fee
013c7539d6fb9ffc30740a33691aac902b11b06e
/practive/PTA/advanced/finished/1006.cpp
bf15f329847c0b6cde83efb115f02c481d013480
[]
no_license
eternity6666/life-in-acm
1cc4ebaa65af62219130d53c9be534ad31b361e2
e279121a28e179d0de33674b9ce10c6763d78d32
refs/heads/master
2023-04-13T07:50:58.231217
2023-04-09T09:23:24
2023-04-09T09:23:24
127,930,873
0
0
null
null
null
null
UTF-8
C++
false
false
841
cpp
#include <iostream> using namespace std; struct node { string name; string in; string out; }; int tLen = 8; bool isEarly(string a, string b) { for (int i = 0; i < tLen; ++i) if (a[i] != b[i]) return a[i] < b[i]; return false; } int main() { int m; cin >> m; string name1, in; string name2, out; for (int i = 0; i < m; i++) { node no; cin >> no.name >> no.in >> no.out; if (i == 0) { name1 = name2 = no.name; in = no.in; out = no.out; } else { if (isEarly(no.in, in)) name1 = no.name, in = no.in; if (isEarly(out, no.out)) name2 = no.name, out = no.out; } } cout << name1 << " " << name2 << endl; return 0; }
[ "yzh@DESKTOP-RLSAM61" ]
yzh@DESKTOP-RLSAM61
fd1e8be12113f05e9822808d838ab4584532c790
41df197fd0458619c7cbba2fd27f2eef9411702b
/include/core/base/bundle.h
052012d76db951cf65eeb3cf430f9f50a78ada81
[ "Apache-2.0" ]
permissive
xwpcom/CoreLooper
80c0883cd10d2997c6a526ea6d7c70cd1a6e6915
b6764cc8eed7a616ff8be0ee84e3fe42968188df
refs/heads/master
2023-08-29T13:46:40.168936
2023-08-24T07:27:30
2023-08-24T07:27:30
138,360,379
41
11
null
null
null
null
UTF-8
C++
false
false
2,434
h
#pragma once #include <map> #include <string> #include <sstream> #include <iostream> namespace Bear { namespace Core { //XiongWanPing 2017.09.23 class Bundle { public: template <class T> void Set(string name, T tmp) { stringstream ss; ss << tmp; Set(name, ss.str()); } void Set(const string& name, const string& value) { mItems[name] = value; } bool IsKeyExists(string name)const { auto iter = mItems.find(name); return iter != mItems.end(); } bool GetBool(const string&name, bool defaultValue = false)const { if (!IsKeyExists(name)) { return defaultValue; } auto v = GetString(name); if (v.empty()) { return defaultValue; } return atoi(v.c_str()) != 0; } int GetInt(const string&name, int defaultValue = 0)const { if (!IsKeyExists(name)) { return defaultValue; } auto v = GetString(name); if (v.empty()) { return defaultValue; } return atoi(v.c_str()); } long GetLong(const string&name, long defaultValue = 0)const { if (!IsKeyExists(name)) { return defaultValue; } auto v = GetString(name); if (v.empty()) { return defaultValue; } return atol(v.c_str()); } double GetDouble(const string&name, double defaultValue = 0)const { if (!IsKeyExists(name)) { return defaultValue; } auto v = GetString(name); if (v.empty()) { return defaultValue; } return atof(v.c_str()); } LONGLONG GetLongLong(const string&name, LONGLONG defaultValue = 0)const { if (!IsKeyExists(name)) { return defaultValue; } auto v = GetString(name); if (v.empty()) { return defaultValue; } return atoll(v.c_str()); } const string GetString(const string&name, const string& defaultValue="")const { auto iter = mItems.find(name); if (iter != mItems.end()) { return iter->second; } return defaultValue; } void clear() { mItems.clear(); } void Remove(const string& name) { auto iter = mItems.find(name); if (iter != mItems.end()) { mItems.erase(iter->first); } } string Pack()const { string items; for (auto iter = mItems.begin(); iter != mItems.end(); ++iter) { items += StringTool::Format("%s=%s\r\n", iter->first.c_str(), iter->second.c_str()); } return items; } public: map<string, string> mItems; }; } }
[ "xwpcom@163.com" ]
xwpcom@163.com
490962cd8a4932b1db676f67564ca86f698f398d
edb593be81d61450212e619f9d461ba7d69b22fc
/include/data_structures/stacks/lcp_stack/lcp_stack_delta_x.hpp
f616b81c617c8c685a384b63a96135ff60a62a45
[ "MIT" ]
permissive
jonas-ellert/xss-real
aa4e5b8080bf15a8268943e4b3b6f16e15641ce0
0a526af5a7f29c42ceb52c2920581e62592373b0
refs/heads/master
2020-06-15T13:10:18.129566
2019-09-04T09:06:18
2019-09-04T09:06:18
195,308,515
4
0
null
null
null
null
UTF-8
C++
false
false
5,370
hpp
// Copyright (c) 2019 Jonas Ellert // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to // deal in the Software without restriction, including without limitation the // rights to use, copy, modify, merge, publish, distribute, sublicense, and/or // sell copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS // IN THE SOFTWARE. #pragma once #include <cmath> #include <data_structures/stacks/bool_stack/bool_stack.hpp> #include <data_structures/stacks/unary_stack/unary_stack.hpp> #include <util/common.hpp> template <stack_strategy strategy, typename ctz_type, typename value_type> class lcp_stack_delta_x { private: constexpr static uint64_t minimum_n = 4096; const uint64_t n_; const uint64_t log2_delta_; const uint64_t delta_; const value_type* text_; telescope_stack<strategy, ctz_type> indices_; unary_stack<strategy, ctz_type> lcps_; uint64_t v_stack_size_; uint64_t top_lcp_; xssr_always_inline bool is_absolute_value(const uint64_t l1, const uint64_t l2) { return (l1 < l2 && delta_ <= l1); } xssr_always_inline bool is_relative_value(const uint64_t l1, const uint64_t l2) { return (l1 >= l2 && delta_ <= (l1 - l2)); } xssr_always_inline bool is_transformable(const uint64_t l1, const uint64_t l2) { return is_absolute_value(l1, l2) || is_relative_value(l1, l2); } public: lcp_stack_delta_x(const uint64_t n, const uint64_t delta, const value_type* text) : n_(n), log2_delta_((uint64_t) std::floor(std::log2(delta))), delta_(1ULL << log2_delta_), text_(text), indices_(n), lcps_((n >= minimum_n) ? ((4ULL * n) >> log2_delta_) : 128 * n), v_stack_size_(0), top_lcp_(0) { static_assert(strategy == STATIC || strategy == DYNAMIC); if (delta == 0) { std::cerr << "Delta cannot be 0." << std::endl; std::abort(); } } xssr_always_inline void push_with_lcp(const uint64_t idx, const uint64_t lcp) { indices_.push(idx); if (is_absolute_value(top_lcp_, lcp)) { lcps_.push(top_lcp_ >> log2_delta_); ++v_stack_size_; } else if (is_relative_value(top_lcp_, lcp)) { lcps_.push((top_lcp_ - lcp) >> log2_delta_); ++v_stack_size_; } top_lcp_ = lcp; } xssr_always_inline void push_without_lcp(const uint64_t idx) { indices_.push(idx); } xssr_always_inline void pop_with_lcp() { indices_.pop(); const uint64_t idx_2 = indices_.top(); if (xssr_unlikely(idx_2 == 0)) { if (v_stack_size_ > 0) { lcps_.pop(); --v_stack_size_; } top_lcp_ = 0; return; } indices_.pop(); const uint64_t idx_1 = indices_.top(); indices_.push(idx_2); const uint64_t transform = (v_stack_size_ > 0) ? (lcps_.top() << log2_delta_) : (top_lcp_ + delta_); uint64_t result = std::numeric_limits<uint64_t>::max(); for (uint64_t i = 0; i < delta_; ++i) { if (text_[idx_1 + i] != text_[idx_2 + i]) { result = i; break; } } if (xssr_likely(idx_2 + top_lcp_ < n_)) for (uint64_t i = 0; i < delta_; ++i) { if (text_[idx_1 + top_lcp_ + i] != text_[idx_2 + top_lcp_ + i]) { result = std::min((top_lcp_ + i), result); break; } } if (xssr_likely(idx_2 + transform < n_)) for (uint64_t i = 0; i < delta_; ++i) { if (text_[idx_1 + transform + i] != text_[idx_2 + transform + i]) { result = std::min((transform + i), result); break; } } if (xssr_likely(idx_2 + top_lcp_ + transform < n_)) for (uint64_t i = 0; i < delta_; ++i) { if (text_[idx_1 + transform + top_lcp_ + i] != text_[idx_2 + transform + top_lcp_ + i]) { result = std::min((transform + top_lcp_ + i), result); break; } } if (is_transformable(result, top_lcp_)) { lcps_.pop(); --v_stack_size_; } top_lcp_ = result; } xssr_always_inline void pop_without_lcp() { indices_.pop(); } xssr_always_inline uint64_t top_idx() const { return indices_.top(); } xssr_always_inline uint64_t top_lcp() const { return top_lcp_; } lcp_stack_delta_x(const lcp_stack_delta_x&) = delete; lcp_stack_delta_x& operator=(const lcp_stack_delta_x&) = delete; };
[ "jonas.ellert@tu-dortmund.de" ]
jonas.ellert@tu-dortmund.de
d623ecc84b538e7279fad80ea35288eda5eb20ef
c95bbe1e2e8119647f740d446523b4c00cfd8c00
/aux.cpp
26cabeec171990516e176b4cfdd17d603c086d87
[]
no_license
Snehabisht/APS-PROJECT
7ee3aeeae7fbc72cf6fd89cb0b971d794c1430e6
b6b469ddfb128618cce2dd8ed844c2dab349553c
refs/heads/master
2020-04-28T00:39:08.238296
2019-05-07T18:18:26
2019-05-07T18:18:26
174,823,781
0
5
null
null
null
null
UTF-8
C++
false
false
1,284
cpp
#include <bits/stdc++.h> #include "dijkshastra.cpp" using namespace std; #define v 10 int main() { //schools bool *check = new bool[10]; memset(check, false, sizeof(check)); int graph[v][v] = { {0, 4, 0, 0, 0, 0, 0, 8, 0}, {4, 0, 8, 0, 0, 0, 0, 11, 0}, {0, 8, 0, 7, 0, 4, 0, 0, 2}, {0, 0, 7, 0, 9, 14, 0, 0, 0}, {0, 0, 0, 9, 0, 10, 0, 0, 0}, {0, 0, 4, 14, 10, 0, 2, 0, 0}, {0, 0, 0, 0, 0, 2, 0, 1, 6}, {8, 11, 0, 0, 0, 0, 1, 0, 7}, {0, 0, 2, 0, 0, 0, 6, 7, 0}, }; /*for(int l=0;l<5;++l) { int i=9; for(int j=0;j<10;++j) cin>>graph[i][j]; int m=9; for(int t=0;t<10;++t) cin>>graph[t][m];*/ for(int i=0;i<3;++i) { vector<pair<int, int>> vect = dijkshastra(graph, 10, i, check); for(int j=0;j<10;++j) { if(vect[j].second==0||vect[j].second==1||vect[j].second==2) continue; else { cout << "For house " << i+1 << " school " << 10-(vect[j].second + 1) << " is at minimum distance of " << vect[j].first << "\n"; break; } } } return 0; }
[ "noreply@github.com" ]
Snehabisht.noreply@github.com
30a1ed6e2cbd3fb77d119063923149a485d93d89
4b14e804ee223e20e8e0ad376715155448b28d80
/template_stack.cc
6c5f8d32b3771e76634acd5e1be6a9bd34c712b2
[ "MIT" ]
permissive
tamsynlin/CaTest
6800188246cadf707b139a9c56688940f4ef30d2
c68e58bdd13aa805ac844d34150187aa26a7fb51
refs/heads/master
2020-03-23T20:50:00.914117
2018-08-26T19:47:49
2018-08-26T19:47:49
142,065,218
0
0
null
null
null
null
UTF-8
C++
false
false
1,520
cc
#include <iostream> #include <vector> #include <cstdlib> #include <string> #include <stdexcept> using namespace std; template <class T> class Stack { private: vector<T> elems; // elements public: void push(T const&); // push element void pop(); // pop element T top() const; // return top element bool empty() const { // return true if empty. return elems.empty(); } }; template <class T> void Stack<T>::push (T const& elem) { // append copy of passed element elems.push_back(elem); } template <class T> void Stack<T>::pop () { if (elems.empty()) { throw out_of_range("Stack<>::pop(): empty stack"); } // remove last element elems.pop_back(); } template <class T> T Stack<T>::top () const { if (elems.empty()) { throw out_of_range("Stack<>::top(): empty stack"); } // return copy of last element return elems.back(); } int main() { try { Stack<int> intStack; // stack of ints Stack<string> stringStack; // stack of strings // manipulate int stack intStack.push(7); cout << intStack.top() <<endl; // manipulate string stack stringStack.push("hello"); cout << stringStack.top() << std::endl; stringStack.pop(); stringStack.pop(); } catch (exception const& ex) { cerr << "Exception: " << ex.what() <<endl; return -1; } }
[ "noreply@github.com" ]
tamsynlin.noreply@github.com
f5a1a1dcac141c083d4f67256fc0810c06be2697
a6b0c0f404c251466542ca167ccf8beec040bfe3
/6heap.h
4a1c1692be0bb244d4cc55f049e72a359b5f5313
[]
no_license
eric54205420/algorithms-5
9d76af885c3e4f43f15023291b380a9dbbe953d6
d824fa1afdfa40bb279505324923cc256caaee26
refs/heads/master
2020-05-04T15:32:20.926052
2015-09-11T07:31:13
2015-09-11T07:31:13
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,898
h
#ifndef TEST_HEAP_H #define TEST_HEAP_H #include "test.h" /* 这里建立的是小根堆,元素存在vector容器中,根从下标为1的元素开始 */ template <typename T> class BinaryHeap { public: explicit BinaryHeap(int capacity = 100) :array(capacity + 1), current_size(0) {} explicit BinaryHeap(const vector<T>& items) :array(items.size() + 10), current_size(items.size()) { int i; for (i = 0; i < items.size(); i++) array[i + 1] = items[i]; BuildHeap(); } bool IsEmpty() const { return current_size == 0; } const T& FindMin() const { if (IsEmpty()) cout << "No items in binary heap" << endl; return array[1]; } /* 堆的插入操作是“上滤”的过程。最坏时间为O(logN),平均时间为O(logN)。 先在堆的下一个空闲位置上建立一个空穴,如果这样不破坏堆的性质,那么插入完成。 否则,将空穴父节点的元素移入空穴,这样空穴上升了一层,到达父节点的位置。 继续该过程,直到插入值可以放入空穴为止。 */ void Insert(const T& value) { if (current_size == array.size() - 1) //空间不够,重分配 array.resize(array.size() * 2); int hole = ++current_size; //在堆的下一个空闲位置建立一个空穴 /* 在空穴没上滤到根部并且插入值小于空穴父节点时, 将父节点移入空穴,空穴位置上升一层 */ for ( ; hole > 1 && value < array[hole / 2]; hole /= 2) array[hole] = array[hole / 2]; array[hole] = value; //将值插入到合适位置 } /* 删除操作最坏时间为O(logN),平均时间为O(logN)。 删除最小值时,根成空穴,且堆要少一个元素, 因此原堆的最后一个元素X将要放到堆的某个位置; 如果X可以放到空穴中则完成;否则要将空穴的儿子中较小的元素放入空穴,空穴 下移,重复该过程直到X可以放入空穴。 */ void DeleteMin(); /*{ if (IsEmpty()) cout << "No items in binary heap" << endl; array[1] = array[current_size--]; PercolateDown(1); }*/ void DeleteMin(T& min_item) { if (IsEmpty()) cout << "No items in binary heap" << endl; min_item = array[1]; array[1] = array[current_size--]; PercolateDown(1); } void MakeEmpty() { current_size = 0; } void PrintItems() { cout << "Items: "; int i = 1; while (i <= current_size) {; cout << array[i++] << " " } cout << endl; } private: int current_size; vector<T> array; /* 建立堆的操作最坏时间为O(NlogN),平均时间为O(N) 建立堆的过程就是堆排序的过程 */ void BuildHeap() { int i; for (i = current_size / 2; i > 0; i--) PercolateDown(i); } /* 该函数完成“下滤”过程。 删除堆的过程就是要下滤的。 而堆排序用到了删除堆的操作,因此,堆排序也是要下滤的。 对任意输入序列建立堆也要下滤。 该函数的做法是将插入值置入沿着从根开始 包含最小儿子的一条路径上的正确位置 */ void PercolateDown(int hole) { int pos_child; T tmp = array[hole]; //当空穴位置没有到达堆的尾部前,循环向下层找空穴位置 for ( ; hole * 2 <= current_size; hole = pos_child) { pos_child = 2 * hole; /* 下边语句是要将较小孩子的下标移入空穴,将空穴移入下一层。 下边的pos_child != current_size条件是控制当堆的节点为偶数时情况, 当堆节点为偶数时,最后一个非叶节点只有一个左孩子,则此时要找的 较小孩子的下标就是左孩子的下标,即不用执行下边第一个if */ if (pos_child != current_size && array[pos_child + 1] < array[pos_child]) pos_child++; if (array[pos_child] < tmp) //如果较小孩子比父节点小,则空穴下移一层 array[hole] = array[pos_child]; else break; } array[hole] = tmp; } }; #endif
[ "977709619@qq.com" ]
977709619@qq.com
a15ab23ad9f6b64cc0991d2f490680190124403f
c95c3d2d646a0790d54eba2ee3684d28fb833b40
/day30/221.cpp
a0852ab210ea4037256bbe376e0376093aaadbbd
[]
no_license
loge1998/100-days-of-cp
a23efc2dd6e99fa4afedc2b685a65dae358da32d
f198702a78f0e83d1fa8914366b449f860ce55f6
refs/heads/master
2021-04-23T21:10:37.466905
2020-05-07T17:04:34
2020-05-07T17:04:34
250,005,422
0
0
null
null
null
null
UTF-8
C++
false
false
1,251
cpp
class Solution { public: int maximalSquare(vector<vector<char>>& matrix) { if(matrix.size()==0) return 0; int n = matrix.size(); int m = matrix[0].size(); vector<vector<int>> dp(n,vector<int>(m,0)); int maxVal = 0; for(int i=0;i<n;i++) { for(int j=0;j<m;j++) { if(i==0 || j==0) dp[i][j] = (matrix[i][j]=='1')?1:0; else { if(matrix[i][j]=='1') { if(dp[i-1][j-1]>0 && dp[i-1][j]>0 && dp[i][j-1]>0) { dp[i][j] = min(dp[i-1][j-1],min(dp[i][j-1],dp[i-1][j])); dp[i][j]++; } else { dp[i][j]=1; } } } maxVal = max(maxVal,dp[i][j]); } } for(int i=0;i<n;i++) { for(int j=0;j<m;j++) cout<<dp[i][j]<<" "; cout<<endl; } return maxVal*maxVal; } };
[ "logeshbalu1998@gmail.com" ]
logeshbalu1998@gmail.com
b9358f45fc7389258c3430fd6438c75b38bdf10e
26d75381b9729abfa8732e6a232f9ae9d503f147
/src/amount.h
f0f618ea0381a8b032f69ba4f1451ece254019bb
[ "MIT" ]
permissive
admecoin/philscurrency
c20f1f81f418325e1704dd44ada639a4d8f47dcb
e1f52af1b8b6038fd650f62637592321f42463aa
refs/heads/master
2020-03-09T03:49:27.954413
2019-10-29T18:15:26
2019-10-29T18:15:26
128,573,511
0
0
null
null
null
null
UTF-8
C++
false
false
2,090
h
// Copyright (c) 2009-2010 Satoshi Nakamoto // Copyright (c) 2009-2014 The Bitcoin developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #ifndef BITCOIN_AMOUNT_H #define BITCOIN_AMOUNT_H #include "serialize.h" #include <stdlib.h> #include <string> typedef int64_t CAmount; static const CAmount COIN = 100000000; static const CAmount CENT = 1000000; /** No amount larger than this (in satoshi) is valid */ static const CAmount MAX_MONEY = 120000000 * COIN; inline bool MoneyRange(const CAmount& nValue) { return (nValue >= 0 && nValue <= MAX_MONEY); } /** Type-safe wrapper class to for fee rates * (how much to pay based on transaction size) */ class CFeeRate { private: CAmount nSatoshisPerK; // unit is satoshis-per-1,000-bytes public: CFeeRate() : nSatoshisPerK(0) { } explicit CFeeRate(const CAmount& _nSatoshisPerK): nSatoshisPerK(_nSatoshisPerK) { } CFeeRate(const CAmount& nFeePaid, size_t nSize); CFeeRate(const CFeeRate& other) { nSatoshisPerK = other.nSatoshisPerK; } CAmount GetFee(size_t size) const; // unit returned is satoshis CAmount GetFeePerK() const { return GetFee(1000); } // satoshis-per-1000-bytes friend bool operator<(const CFeeRate& a, const CFeeRate& b) { return a.nSatoshisPerK < b.nSatoshisPerK; } friend bool operator>(const CFeeRate& a, const CFeeRate& b) { return a.nSatoshisPerK > b.nSatoshisPerK; } friend bool operator==(const CFeeRate& a, const CFeeRate& b) { return a.nSatoshisPerK == b.nSatoshisPerK; } friend bool operator<=(const CFeeRate& a, const CFeeRate& b) { return a.nSatoshisPerK <= b.nSatoshisPerK; } friend bool operator>=(const CFeeRate& a, const CFeeRate& b) { return a.nSatoshisPerK >= b.nSatoshisPerK; } std::string ToString() const; ADD_SERIALIZE_METHODS; template <typename Stream, typename Operation> inline void SerializationOp(Stream& s, Operation ser_action, int nType, int nVersion) { READWRITE(nSatoshisPerK); } }; #endif // BITCOIN_AMOUNT_H
[ "philscurrency@gmail.com" ]
philscurrency@gmail.com
547dcb5e7b26c3d135a3494b79beb384c77ad2a6
4bad19f2b4675fad95d21ae8416ff81cb71d5181
/贪心/55_跳跃游戏.cpp
1b4b8bd42eb24c0665976d2842b97fe8b2be80df
[]
no_license
cachefish/LeetCode
39552f93cc2b1bd7fd1dfbb372178868ddda212d
b0bf78a5e3d1e19d1a0575ce6f0238672779ffcb
refs/heads/master
2022-12-08T04:46:20.283970
2020-08-15T07:18:23
2020-08-15T07:18:23
275,514,689
0
0
null
null
null
null
UTF-8
C++
false
false
957
cpp
/* 55. 跳跃游戏 给定一个非负整数数组,你最初位于数组的第一个位置。 数组中的每个元素代表你在该位置可以跳跃的最大长度。 判断你是否能够到达最后一个位置。 示例 1: 输入: [2,3,1,1,4] 输出: true 解释: 我们可以先跳 1 步,从位置 0 到达 位置 1, 然后再从位置 1 跳 3 步到达最后一个位置。 */ #include<vector> using namespace std; class Solution { public: bool canJump(vector<int>& nums) { vector<int> index; for(int i =0;i<nums.size();i++) { index.push_back(i+nums[i]); } int jump = 0; int maxindex = index[0]; while(jump<index[jump]) { if(maxindex<index[jump]){ maxindex = index[jump]; } jump++; } if(jump==index.size()){ return true; }else{ return false; } } };
[ "780207419@qq.com" ]
780207419@qq.com
2b330db652746e8cdb4b5d4c8da6dc7ce7cf7f4d
29c037f0e5f69d9caf2c72623ecdee4367fcba10
/Dynamic_Programming/Knapsack/test01.cpp
70fc31334f7e7cc7494d64b5d02e972d52b96702
[]
no_license
Thebasic123/algorithms_in_CPP
4b8645df2f275addffc48ec7dac08d4171cf8956
56f1af8cd8d142b48e331a4afc7b12a5bf76907d
refs/heads/master
2023-04-24T18:28:54.222187
2021-05-14T08:43:08
2021-05-14T08:43:08
null
0
0
null
null
null
null
UTF-8
C++
false
false
740
cpp
#include <iostream> #include <vector> #include <utility> int knapsack(int W, std::vector<std::pair<int, int>> vwp){ int n = vwp.size(); std::vector<std::vector<int>> dp( n+1, std::vector<int>(W+1)); for(int i=1; i < n+1; ++i){ for(int j = 1; j < W+1; ++j){ if(j>=vwp[i-1].second){ dp[i][j] = std::max(dp[i-1][j], vwp[i-1].first + dp[i-1][j-vwp[i-1].second]); }else{ dp[i][j] = dp[i-1][j]; } } } return dp[n][W]; } int main(int argc, char *argv[]){ int n; int W; std::cin >> W; std::cin >> n; std::vector<std::pair<int, int>> vwp(n); // value weight pair for(int i=0; i < n; ++i){ int v, w; std::cin >> v >> w; vwp[i] = std::make_pair(v, w); } std::cout << knapsack(W, vwp) << "\n"; return 0; }
[ "hufune@gmail.com" ]
hufune@gmail.com
3f5839dfef96b15ab4dde99903f12f01fa74a177
ebeade2609e56126da910684fd41085b85f981d3
/Src/Chest.h
be0b940306d568abcd78696221ca5a3f662b496b
[]
no_license
patrickjamescarr/DirectX_Engine
3364e3d68dffd9365cc781d1246038f242ad4044
bf98fcb8708658e462eaa00e8e5f5c03a035cf49
refs/heads/main
2023-08-15T17:52:27.860256
2021-10-08T12:18:11
2021-10-08T12:18:11
345,572,176
0
0
null
null
null
null
UTF-8
C++
false
false
963
h
#pragma once #include "Mesh.h" #include "PlayerCamera.h" class Chest : public Mesh { public: Chest( DX::DeviceResources& deviceResources, DirectX::SimpleMath::Matrix scale, DirectX::SimpleMath::Matrix rotation, DirectX::SimpleMath::Vector3 position, const MeshObject& chestModel, const MeshObject& coinsModel, Light * sceneLight, PlayerCamera* playerCamera, SoundEffect* coinSoundFx, float fogDistance ); void Draw(DX::DeviceResources& deviceResources, DirectX::FXMMATRIX accumulatedTransform) const override; void Update() override; private: std::unique_ptr<Mesh> m_chestMesh; std::unique_ptr<Mesh> m_coinsMesh; bool m_coinsCollected = false; float m_fogEnd = 20.0f; DirectX::SimpleMath::Vector3 m_position; PlayerCamera * m_playerCamera; std::unique_ptr<SoundEffectInstance> m_coinFxInstance; SoundEffect* m_coinSoundFx; };
[ "carr.patrickjames@gmail.com" ]
carr.patrickjames@gmail.com
0d3dce9ad9e7600ba9462225d8ee83ff256641f5
93b6722cd2e4f33d31281d0d79d6171d270be81a
/main.cpp
3883a4dce10ba04ec281152e46cc7903b293dd6e
[]
no_license
pengliu916/SimpleFire
aff8c656d980d6a17421e3e30662533ea9b69893
f8cd2017b70b3d70bc0dec6dde048c2233a3ce22
refs/heads/master
2021-01-23T06:45:03.694787
2013-09-20T04:38:59
2013-09-20T04:38:59
38,592,050
1
0
null
null
null
null
UTF-8
C++
false
false
7,899
cpp
#include "DXUT.h" #include "DXUT\Optional\DXUTcamera.h" #include "DXUT\Optional\SDKmisc.h" #include "DXUT\Optional\DXUTgui.h" #include "MultiTexturePresenter.h" #include "SimpleFire.h" #define SUB_TEXTUREWIDTH 1024 #define SUB_TEXTUREHEIGHT 768 //-------------------------------------------------------------------------------------- //Global Variables //-------------------------------------------------------------------------------------- MultiTexturePresenter MultiTexture = MultiTexturePresenter(1,true,SUB_TEXTUREWIDTH,SUB_TEXTUREHEIGHT); SimpleFire FireSimple = SimpleFire( SUB_TEXTUREWIDTH,SUB_TEXTUREHEIGHT); //-------------------------------------------------------------------------------------- //Initialization //-------------------------------------------------------------------------------------- HRESULT Initial() { HRESULT hr = S_OK; V_RETURN( MultiTexture.Initial() ); return hr; } //-------------------------------------------------------------------------------------- // Reject any D3D11 devices that aren't acceptable by returning false //-------------------------------------------------------------------------------------- bool CALLBACK IsD3D11DeviceAcceptable( const CD3D11EnumAdapterInfo *AdapterInfo, UINT Output, const CD3D11EnumDeviceInfo *DeviceInfo, DXGI_FORMAT BackBufferFormat, bool bWindowed, void* pUserContext ) { return true; } //-------------------------------------------------------------------------------------- // Called right before creating a D3D9 or D3D11 device, allowing the app to modify the device settings as needed //-------------------------------------------------------------------------------------- bool CALLBACK ModifyDeviceSettings( DXUTDeviceSettings* pDeviceSettings, void* pUserContext ) { MultiTexture.ModifyDeviceSettings( pDeviceSettings ); return true; } //-------------------------------------------------------------------------------------- // Create any D3D11 resources that aren't dependant on the back buffer //-------------------------------------------------------------------------------------- HRESULT CALLBACK OnD3D11CreateDevice( ID3D11Device* pd3dDevice, const DXGI_SURFACE_DESC* pBackBufferSurfaceDesc, void* pUserContext ) { HRESULT hr = S_OK; V_RETURN( FireSimple.CreateResource( pd3dDevice )); V_RETURN( MultiTexture.CreateResource( pd3dDevice, FireSimple.m_pOutputTextureSRV )); return S_OK; } //-------------------------------------------------------------------------------------- // Create any D3D11 resources that depend on the back buffer //-------------------------------------------------------------------------------------- HRESULT CALLBACK OnD3D11ResizedSwapChain( ID3D11Device* pd3dDevice, IDXGISwapChain* pSwapChain, const DXGI_SURFACE_DESC* pBackBufferSurfaceDesc, void* pUserContext ) { MultiTexture.Resize(); FireSimple.Resize(); return S_OK; } //-------------------------------------------------------------------------------------- // Handle updates to the scene. This is called regardless of which D3D API is used //-------------------------------------------------------------------------------------- void CALLBACK OnFrameMove( double fTime, float fElapsedTime, void* pUserContext ) { FireSimple.Update( fElapsedTime ); } //-------------------------------------------------------------------------------------- // Render the scene using the D3D11 device //-------------------------------------------------------------------------------------- void CALLBACK OnD3D11FrameRender( ID3D11Device* pd3dDevice, ID3D11DeviceContext* pd3dImmediateContext, double fTime, float fElapsedTime, void* pUserContext ) { FireSimple.Render( pd3dImmediateContext, fTime, fElapsedTime ); MultiTexture.Render( pd3dImmediateContext ); } //-------------------------------------------------------------------------------------- // Release D3D11 resources created in OnD3D11ResizedSwapChain //-------------------------------------------------------------------------------------- void CALLBACK OnD3D11ReleasingSwapChain( void* pUserContext ) { } //-------------------------------------------------------------------------------------- // Release D3D11 resources created in OnD3D11CreateDevice //-------------------------------------------------------------------------------------- void CALLBACK OnD3D11DestroyDevice( void* pUserContext ) { MultiTexture.Release(); FireSimple.Release(); } //-------------------------------------------------------------------------------------- // Handle messages to the application //-------------------------------------------------------------------------------------- LRESULT CALLBACK MsgProc( HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam, bool* pbNoFurtherProcessing, void* pUserContext ) { FireSimple.HandleMessages( hWnd, uMsg, wParam, lParam ); return 0; } //-------------------------------------------------------------------------------------- // Handle key presses //-------------------------------------------------------------------------------------- void CALLBACK OnKeyboard( UINT nChar, bool bKeyDown, bool bAltDown, void* pUserContext ) { } //-------------------------------------------------------------------------------------- // Handle mouse button presses //-------------------------------------------------------------------------------------- void CALLBACK OnMouse( bool bLeftButtonDown, bool bRightButtonDown, bool bMiddleButtonDown, bool bSideButton1Down, bool bSideButton2Down, int nMouseWheelDelta, int xPos, int yPos, void* pUserContext ) { } //-------------------------------------------------------------------------------------- // Call if device was removed. Return true to find a new device, false to quit //-------------------------------------------------------------------------------------- bool CALLBACK OnDeviceRemoved( void* pUserContext ) { return true; } //-------------------------------------------------------------------------------------- // Initialize everything and go into a render loop //-------------------------------------------------------------------------------------- int WINAPI wWinMain( HINSTANCE hInstance, HINSTANCE hPrevInstance, LPWSTR lpCmdLine, int nCmdShow ) { // Enable run-time memory check for debug builds. #if defined(DEBUG) | defined(_DEBUG) _CrtSetDbgFlag( _CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF ); #endif // DXUT will create and use the best device (either D3D9 or D3D11) // that is available on the system depending on which D3D callbacks are set below // Set general DXUT callbacks DXUTSetCallbackFrameMove( OnFrameMove ); DXUTSetCallbackKeyboard( OnKeyboard ); DXUTSetCallbackMouse( OnMouse ); DXUTSetCallbackMsgProc( MsgProc ); DXUTSetCallbackDeviceChanging( ModifyDeviceSettings ); DXUTSetCallbackDeviceRemoved( OnDeviceRemoved ); // Set the D3D11 DXUT callbacks. Remove these sets if the app doesn't need to support D3D11 DXUTSetCallbackD3D11DeviceAcceptable( IsD3D11DeviceAcceptable ); DXUTSetCallbackD3D11DeviceCreated( OnD3D11CreateDevice ); DXUTSetCallbackD3D11SwapChainResized( OnD3D11ResizedSwapChain ); DXUTSetCallbackD3D11FrameRender( OnD3D11FrameRender ); DXUTSetCallbackD3D11SwapChainReleasing( OnD3D11ReleasingSwapChain ); DXUTSetCallbackD3D11DeviceDestroyed( OnD3D11DestroyDevice ); // Perform any application-level initialization here DXUTInit( true, true, NULL ); // Parse the command line, show msgboxes on error, no extra command line params DXUTSetCursorSettings( true, true ); // Show the cursor and clip it when in full screen Initial(); DXUTCreateWindow( L"SimpleFire" ); // Only require 10-level hardware DXUTCreateDevice( D3D_FEATURE_LEVEL_11_0, true, 640, 480 ); DXUTMainLoop(); // Enter into the DXUT ren der loop // Perform any application-level cleanup here return DXUTGetExitCode(); }
[ "peng.liu916@gmail.com" ]
peng.liu916@gmail.com
44233a7ec7c8532e777c45848429b3e89a12cf3c
3a4b861cf0085953a6f58df2c63f8dfdfca75f84
/ci/17_mergeSortedList.cc
a0d25f88d3323014337d69975557171b733115f8
[]
no_license
ElvisKwok/code
f490c1acfb4025ff2dbe00e61379304f2526176f
b2d5560e7fc1f7e14ff3a7eb827282f2732d22a3
refs/heads/master
2020-04-15T17:31:37.265803
2016-05-09T13:57:42
2016-05-09T13:57:42
23,882,932
0
0
null
null
null
null
UTF-8
C++
false
false
3,039
cc
#include <iostream> #include "utilities/List.h" using namespace std; // file description: // merge two sorted list // this algorithm is recursive // corner case: // 1. pHead1 == NULL, pHead2 == NULL // 2. both contains one node // 3. some nodes' value are equal. ListNode* merge(ListNode* pHead1, ListNode* pHead2) { if (pHead1 == NULL) return pHead2; else if (pHead2 == NULL) return pHead1; ListNode* pMergedHead = NULL; if (pHead1->m_nValue < pHead2->m_nValue) { pMergedHead = pHead1; pMergedHead->m_pNext = merge(pHead1->m_pNext, pHead2); } else { pMergedHead = pHead2; pMergedHead->m_pNext = merge(pHead1, pHead2->m_pNext); } return pMergedHead; } // =====================Test Code===================== ListNode* test(char* testName, ListNode* pHead1, ListNode* pHead2) { if (testName != NULL) cout << testName << " begins: " << endl; cout << "The first list is: " << endl; printList(pHead1); cout << "The second list is: " << endl; printList(pHead2); cout << "The merged list is: " << endl; ListNode* pMergedHead = merge(pHead1, pHead2); printList(pMergedHead); cout << "\n" << endl; return pMergedHead; } // 1->3->5 // 2->4->6 void test1() { ListNode* pNode1 = createListNode(1); ListNode* pNode3 = createListNode(3); ListNode* pNode5 = createListNode(5); connectListNodes(pNode1, pNode3); connectListNodes(pNode3, pNode5); ListNode* pNode2 = createListNode(2); ListNode* pNode4 = createListNode(4); ListNode* pNode6 = createListNode(6); connectListNodes(pNode2, pNode4); connectListNodes(pNode4, pNode6); ListNode* pMergedHead = test("test1", pNode1, pNode2); destroyList(pMergedHead); } // 1->3->5 // 1->3->5 void test2() { ListNode* pNode1 = createListNode(1); ListNode* pNode3 = createListNode(3); ListNode* pNode5 = createListNode(5); connectListNodes(pNode1, pNode3); connectListNodes(pNode3, pNode5); ListNode* pNode2 = createListNode(1); ListNode* pNode4 = createListNode(3); ListNode* pNode6 = createListNode(5); connectListNodes(pNode2, pNode4); connectListNodes(pNode4, pNode6); ListNode* pMergedHead = test("test2", pNode1, pNode2); destroyList(pMergedHead); } // 1 // 2 void test3() { ListNode* pNode1 = createListNode(1); ListNode* pNode2 = createListNode(2); ListNode* pMergedHead = test("test3", pNode1, pNode2); destroyList(pMergedHead); } // 1->3->5 // NULL void test4() { ListNode* pNode1 = createListNode(1); ListNode* pNode3 = createListNode(3); ListNode* pNode5 = createListNode(5); connectListNodes(pNode1, pNode3); connectListNodes(pNode3, pNode5); ListNode* pMergedHead = test("test4", pNode1, NULL); destroyList(pMergedHead); } // NULL // NULL void test5() { ListNode* pMergeHead = test("test5", NULL, NULL); } int main() { test1(); test2(); test3(); test4(); test5(); return 0; }
[ "359619839@qq.com" ]
359619839@qq.com
0c371e73340255da3c55c5ace018bf4d39ef72ba
e2954063aac14aaf0f7aa2778f6aa8c162fbd919
/inventorychange.cpp
c56b586d0bc2cca3bc687c5ff2fe2052ddad85d3
[]
no_license
RrodGtHb/newGitTest
054b96638c0620b32b3828f7340ec24ca31eaf1b
169d6eca485a41e39b8f834b20b27cec7666e6ac
refs/heads/master
2021-05-04T10:34:18.663259
2016-08-16T18:21:23
2016-08-16T18:21:23
54,262,311
0
0
null
null
null
null
UTF-8
C++
false
false
250
cpp
#include "inventorychange.h" #include "ui_inventorychange.h" InventoryChange::InventoryChange(QWidget *parent) : QDialog(parent), ui(new Ui::InventoryChange) { ui->setupUi(this); } InventoryChange::~InventoryChange() { delete ui; }
[ "reyronald19@hotmail.com" ]
reyronald19@hotmail.com
0686274ea119518953b96cccabc88f385fd51118
28082d0e84ce6fbfc362f4c4266e6c7625322fe7
/src/ljevent.h
7df89863356c7e5ddf1a19ac09c2d2dd15383b38
[ "MIT" ]
permissive
Maledictus/harbour-mnemosy
8ce84104510ec5756ac40d5ff1c6d820780ef4c8
d5fdc5fb3a23e82afede51f0390b77f0459a9d4d
refs/heads/master
2020-04-12T01:20:26.317557
2018-06-09T17:44:12
2018-06-09T17:44:12
62,672,675
2
0
null
null
null
null
UTF-8
C++
false
false
5,113
h
/* The MIT License (MIT) Copyright (c) 2016-2018 Oleg Linkin <maledictusdemagog@gmail.com> Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #pragma once #include <QDateTime> #include <QString> #include <QVariant> #include "ljeventproperties.h" namespace Mnemosy { class LJEvent { //Friends entry quint64 m_UserID; quint64 m_UserPicID; quint64 m_PosterID; QUrl m_PosterUrl; QUrl m_PosterPicUrl; QString m_PosterName; JournalType m_PosterJournalType; quint64 m_JournalID; JournalType m_JournalType; QString m_JournalName; QUrl m_JournalUrl; quint64 m_DItemID; QString m_Subject; QString m_Event; QDateTime m_PostDate; QStringList m_Tags; Access m_Access; LJEntryProperties m_Properties; quint64 m_ReplyCount; QString m_FullEvent; quint64 m_ItemID; bool m_CanComment; QUrl m_Url; quint32 m_AllowMask; bool m_HasArg; bool m_FullHasArg; int m_Anum; QDateTime m_LogTime; quint64 m_RepostDItemId; bool m_IsRepost; QString m_ReposterName; quint64 m_OwnerId; QUrl m_OriginalEntryUrl; QString m_OriginalFullEntry; public: LJEvent(); bool IsValid() const; //Friends entry quint64 GetUserID() const; void SetUserID(quint64 id); quint64 GetUserPicID() const; void SetUserPicID(quint64 id); quint64 GetPosterID() const; void SetPosterID(const quint64 posterID); QUrl GetPosterUrl() const; void SetPosterUrl(const QUrl& url); QUrl GetPosterPicUrl() const; void SetPosterPicUrl(const QUrl& url); bool IsPosterPicUrlEmpty() const; QString GetPosterName() const; void SetPosterName(const QString& name); JournalType GetPosterJournalType() const; void SetPosterJournalType(JournalType journalType); quint64 GetJournalID() const; void SetJournalID(quint64 id); JournalType GetJournalType() const; void SetJournalType(JournalType journalType); QString GetJournalName() const; void SetJournalName(const QString& journalName); QUrl GetJournalUrl() const; void SetJournalUrl(const QUrl& url); quint64 GetDItemID() const; void SetDItemID(quint64 ditemId); QString GetSubject() const; void SetSubject(const QString& subject); QString GetEvent() const; void SetEvent(const QString& event); QDateTime GetPostDate() const; void SetPostDate(const QDateTime& date); QStringList GetTags() const; void SetTags(const QStringList& tags); Access GetAccess() const; void SetAccess(Access acc); LJEntryProperties GetProperties() const; void SetProperties(const LJEntryProperties& properties); quint64 GetReplyCount() const; void SetReplyCount(quint64 replyCount); // User entry QString GetFullEvent() const; void SetFullEvent(const QString& event); quint64 GetItemID() const; void SetItemID(quint64 itemId); quint32 GetAllowMask() const; void SetAllowMask(quint32 mask); QUrl GetUrl() const; void SetUrl(const QUrl& url); bool IsCanComment() const; void SetCanComment(bool can); QByteArray Serialize() const; static bool Deserialize(const QByteArray& data, LJEvent& event); void Merge(const LJEvent& entry); QVariantMap ToMap() const; bool GetHasArg() const; void SetHasArg(bool hasArg); bool GetFullHasArg() const; void SetFullHasArg(bool hasArg); int GetAnum() const; void SetAnum(int anum); QDateTime GetLogTime() const; void SetLogTime(const QDateTime& dt); quint64 GetRepostDItemId() const; void SetRepostDItemId(const quint64& repostDItemId); bool GetIsRepost() const; void SetIsRepost(bool isRepost); QString GetReposterName() const; void SetReposterName(const QString& reposterName); quint64 GetOwnerId() const; void SetOwnerId(const quint64& ownerId); QUrl GetOriginalEntryUrl() const; void SetOriginalEntryUrl(const QUrl& originalEntryUrl); QString GetOriginalFullEntry() const; void SetOriginalFullEntry(const QString& originalFullEntry); }; typedef QList<LJEvent> LJEvents_t; }
[ "MaledictusDeMagog@gmail.com" ]
MaledictusDeMagog@gmail.com
e82e0366a87a8e4a7adce95d1a60c8bc53f01bf0
51f6e63555b4fda6a620fb42952c5c1fa6eac706
/chrome/browser/performance_manager/webui_graph_dump_impl_unittest.cc
e570e5114b0d7476b8c3149f20d0d13b2d8e51f4
[ "BSD-3-Clause" ]
permissive
heanglightman/chromium
6f74026b428317a28cbb1226d20d1116ed54dd2b
f561f3e0174135fcc555aad31f4adb845977b8bd
refs/heads/master
2023-02-25T08:18:13.731198
2019-03-25T16:19:12
2019-03-25T16:19:12
177,623,917
1
0
NOASSERTION
2019-03-25T16:27:22
2019-03-25T16:27:22
null
UTF-8
C++
false
false
2,432
cc
// Copyright 2018 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/performance_manager/webui_graph_dump_impl.h" #include "base/test/bind_test_util.h" #include "base/time/time.h" #include "chrome/browser/performance_manager/graph/graph_test_harness.h" #include "chrome/browser/performance_manager/graph/mock_graphs.h" #include "chrome/browser/performance_manager/graph/page_node_impl.h" #include "chrome/browser/performance_manager/resource_coordinator_clock.h" #include "testing/gtest/include/gtest/gtest.h" namespace performance_manager { class WebUIGraphDumpImplTest : public GraphTestHarness {}; TEST_F(WebUIGraphDumpImplTest, Create) { Graph graph; MockMultiplePagesWithMultipleProcessesGraph mock_graph(&graph); base::TimeTicks now = ResourceCoordinatorClock::NowTicks(); constexpr char kExampleUrl[] = "http://www.example.org"; mock_graph.page->OnMainFrameNavigationCommitted(now, 1, kExampleUrl); mock_graph.other_page->OnMainFrameNavigationCommitted(now, 2, kExampleUrl); WebUIGraphDumpImpl impl(&graph); resource_coordinator::mojom::WebUIGraphPtr returned_graph; WebUIGraphDumpImpl::GetCurrentGraphCallback callback = base::BindLambdaForTesting( [&returned_graph](resource_coordinator::mojom::WebUIGraphPtr graph) { returned_graph = std::move(graph); }); impl.GetCurrentGraph(std::move(callback)); task_env().RunUntilIdle(); ASSERT_NE(nullptr, returned_graph.get()); EXPECT_EQ(2u, returned_graph->pages.size()); for (const auto& page : returned_graph->pages) { EXPECT_NE(0u, page->id); EXPECT_NE(0u, page->main_frame_id); } EXPECT_EQ(3u, returned_graph->frames.size()); // Count the top-level frames as we go. size_t top_level_frames = 0; for (const auto& frame : returned_graph->frames) { if (frame->parent_frame_id == 0) ++top_level_frames; EXPECT_NE(0u, frame->id); EXPECT_NE(0u, frame->process_id); } // Make sure we have one top-level frame per page. EXPECT_EQ(returned_graph->pages.size(), top_level_frames); EXPECT_EQ(2u, returned_graph->processes.size()); for (const auto& page : returned_graph->pages) { EXPECT_NE(0u, page->id); EXPECT_NE(0u, page->main_frame_id); EXPECT_EQ(kExampleUrl, page->main_frame_url); } } } // namespace performance_manager
[ "commit-bot@chromium.org" ]
commit-bot@chromium.org
d30d52bb245fc305547c4a0116f262714125c4ac
14b33f9027689a8422f0642f25e65152823b35a1
/C++ program design/cpp files/exp4-4.cpp
4ea57d5c142d28bbbd5aaae033b7688999173632
[ "MIT" ]
permissive
duskmoon314/THU_homework
f224436ad3b3ed2e8accb22b5d3d0a54993b3f3c
3ebd1f711009770f9803ebce4fa68e399461b685
refs/heads/master
2021-07-13T07:54:43.090423
2020-03-03T15:09:02
2020-03-03T15:09:02
155,978,876
1
1
MIT
2021-07-08T06:42:11
2018-11-03T11:59:14
C++
UTF-8
C++
false
false
641
cpp
#include <iostream> #include <fstream> using namespace std; int main() { int iChicken, iHen, iRooster, max = 1; cout << "所求购买方案为:\n"; for (iRooster = 1; iRooster < 99; iRooster++) { for (iChicken = 1; iChicken < 99; iChicken++) { for (iHen = 97; iHen > 1; iHen--) { if ((iChicken + iHen + iRooster == 100) && (5 * iChicken + 15 * iHen + 10 * iRooster < 1001) && iHen >= max) { max = iHen; cout << "母鸡:" << iHen << "只\n公鸡:" << iRooster << "只\n小鸡:" << iChicken << "只\n剩余金额:" << 1000- (5 * iChicken + 15 * iHen + 10 * iRooster) << "\n\n"; } } } } return 0; }
[ "duskmoon314@users.noreply.github.com" ]
duskmoon314@users.noreply.github.com
820447d3d399facb2cd9fd08830499e540fcff6b
7fd93c3f443ee857518f2cc6f65c8567ef98b184
/src/delta_ik/main.cpp
df996c56070f819388849fa71d6e2ed4a2ef070e
[]
no_license
MonsterMaster007/ros-cga-kinematics
e3182cdc18532a34f16813db17781d86835f4cd9
a8ec45189ca708a92c87ce92826023fd37bc3749
refs/heads/master
2023-01-14T02:17:49.630432
2020-11-04T04:42:44
2020-11-04T04:42:44
null
0
0
null
null
null
null
UTF-8
C++
false
false
4,122
cpp
#include <ros/ros.h> #include <tf2_ros/transform_broadcaster.h> #include <sensor_msgs/JointState.h> #include <geometry_msgs/Vector3.h> #include <geometry_msgs/TransformStamped.h> #include <geometry_msgs/PoseStamped.h> #include <urdf/model.h> #include <algorithm> #include <stack> #include "constraint/constraint.h" #include "constraint/parallel.h" #include "constraint/delta.h" class Node { public: Node(ros::NodeHandle &n) { pose_sub = n.subscribe( "end_effector_pose", 1, &Node::end_effector_pose_callback, this ); joint_state_pub = n.advertise<sensor_msgs::JointState>( "joint_states_out", 1 ); // Parse urdf urdf::Model model; if (!model.initParam("robot_description")) { ROS_ERROR("Failed to parse urdf file"); } // Create joint_values map, and joint_state_msg std::stack<urdf::LinkConstSharedPtr> links; links.push(model.getRoot()); urdf::LinkConstSharedPtr it; while (!links.empty()) { it = links.top(); links.pop(); for (std::size_t joint_i = 0; joint_i < it->child_joints.size(); joint_i++) { if (it->child_joints[joint_i]->type != urdf::Joint::FIXED && it->child_joints[joint_i]->type != urdf::Joint::FLOATING) { joint_state_msg.name.push_back(it->child_joints[joint_i]->name); joint_values[it->child_joints[joint_i]->name] = 0; } links.push(it->child_links[joint_i]); } } joint_state_msg.position.resize(joint_state_msg.name.size()); joint_state_msg.velocity.resize(joint_state_msg.name.size()); joint_state_msg.effort.resize(joint_state_msg.name.size()); // Extract loops parameter std::map<std::string, std::string> loop_joints; XmlRpc::XmlRpcValue loops; if (n.getParam("loops", loops)) { assert(loops.getType() == XmlRpc::XmlRpcValue::TypeArray); for (std::size_t i = 0; i < loops.size(); i++) { std::string class_name(loops[i]["class"]); XmlRpc::XmlRpcValue &joints = loops[i]["joints"]; for (auto it = joints.begin(); it != joints.end(); it++) { loop_joints[it->first] = std::string(it->second); } if (class_name == "delta") { loop_constraints.push_back(std::unique_ptr<loop::Constraint>( new loop::Delta(model, loop_joints) )); } else if (class_name == "parallel") { loop_constraints.push_back(std::unique_ptr<loop::Constraint>( new loop::Parallel(model, loop_joints) )); } else { ROS_INFO("Unknown loop class %s", class_name.c_str()); } loop_joints.clear(); } } else { ROS_INFO("Failed to read loops parameter"); } } void end_effector_pose_callback(geometry_msgs::Pose end_effector_pose) { // Assume first loop is the dominant one, set by ik loop_constraints[0]->apply_ik(end_effector_pose, joint_values); for (auto it = loop_constraints.cbegin(); it != loop_constraints.cend(); it++) { (*it)->apply_fk(joint_values); } for (std::size_t i = 0; i < joint_state_msg.name.size(); i++) { joint_state_msg.position[i] = joint_values[joint_state_msg.name[i]]; } joint_state_msg.header.stamp = ros::Time::now(); joint_state_pub.publish(joint_state_msg); } private: ros::Subscriber pose_sub; std::map<std::string, double> joint_values; sensor_msgs::JointState joint_state_msg; ros::Publisher joint_state_pub; std::vector<std::unique_ptr<loop::Constraint>> loop_constraints; }; int main(int argc, char **argv) { ros::init(argc, argv, "delta_ik"); ros::NodeHandle n; Node node(n); ros::spin(); }
[ "zachalambert@gmail.com" ]
zachalambert@gmail.com
701c113aef40e4f1e06c73d99eba6d61370e25bd
dd19107e9469e48ed00cec0dfb2fd2b84b7ca9ba
/D3D12_ModelAnimation/asdx/include/asdxCommandList.h
cf50a78df410e118d0b42c632d2345f623bbe38e
[ "MIT", "LicenseRef-scancode-unknown-license-reference" ]
permissive
ProjectAsura/D3D12Samples
75a1a3e205078d55d1b1e01177ee931f07f41c12
b2e2803120a8d13c2d1b18c2dc58d935bb0ba127
refs/heads/master
2022-06-03T01:11:23.942399
2022-05-22T08:12:18
2022-05-22T08:12:31
72,711,525
17
16
null
null
null
null
UTF-8
C++
false
false
6,455
h
//------------------------------------------------------------------------------------------------- // File : asdxCommandList.h // Desc : Command List Module. // Copyright(c) Project Asura. All right reserved. //------------------------------------------------------------------------------------------------- #pragma once //------------------------------------------------------------------------------------------------- // Includes //------------------------------------------------------------------------------------------------- #include <d3d12.h> #include <asdxRef.h> namespace asdx { /////////////////////////////////////////////////////////////////////////////////////////////////// // GraphicsCommandList class /////////////////////////////////////////////////////////////////////////////////////////////////// class GraphicsCommandList final { //============================================================================================= // list of friend classes and methods. //============================================================================================= /* NOTHING */ public: //============================================================================================= // public variables. //============================================================================================= /* NOTHING */ //============================================================================================= // public methods. //============================================================================================= //--------------------------------------------------------------------------------------------- //! @brief コンストラクタです. //--------------------------------------------------------------------------------------------- GraphicsCommandList(); //--------------------------------------------------------------------------------------------- //! @brief デストラクタです. //--------------------------------------------------------------------------------------------- ~GraphicsCommandList(); //--------------------------------------------------------------------------------------------- //! @brief 初期化処理を行います. //! //! @param[in] pDevice デバイスです. //! @param[in] type コマンドリストタイプです. //! @retval true 初期化に成功. //! @retval false 初期化に失敗. //--------------------------------------------------------------------------------------------- bool Init( ID3D12Device* pDevice, D3D12_COMMAND_LIST_TYPE type, ID3D12PipelineState* pPipelineState ); //--------------------------------------------------------------------------------------------- //! @brief 終了処理を行います. //--------------------------------------------------------------------------------------------- void Term(); //--------------------------------------------------------------------------------------------- //! @brief コマンドリストをリセットします. //--------------------------------------------------------------------------------------------- void Clear( ID3D12PipelineState* pPipelineState ); //--------------------------------------------------------------------------------------------- //! @brief 遷移によるリソースバリアを設定します. //! //! @param[in] pResource リソース. //! @param[in] before 変更前のリソース状態. //! @param[in] after 変更後のリソース状態. //--------------------------------------------------------------------------------------------- void Transition( ID3D12Resource* pResource, D3D12_RESOURCE_STATES before, D3D12_RESOURCE_STATES after); //--------------------------------------------------------------------------------------------- //! @brief コマンドリストを実行します. //! //! @param[in] pQueue コマンドキューです. //--------------------------------------------------------------------------------------------- void Execute( ID3D12CommandQueue* pQueue ); //--------------------------------------------------------------------------------------------- //! @brief アロケータを取得します. //! //! @return コマンドアロケータを返却します. //--------------------------------------------------------------------------------------------- ID3D12CommandAllocator* GetAllocator() const; //--------------------------------------------------------------------------------------------- //! @brief グラフィックスコマンドリストを取得します. //! //! @return グラフィックスコマンドリストを返却します. //--------------------------------------------------------------------------------------------- ID3D12GraphicsCommandList* GetList() const; //--------------------------------------------------------------------------------------------- //! @brief アロー演算子です. //--------------------------------------------------------------------------------------------- ID3D12GraphicsCommandList* operator -> () const; //--------------------------------------------------------------------------------------------- //! @brief コマンドリストにキャストします. //--------------------------------------------------------------------------------------------- ID3D12CommandList* Cast() const; private: //============================================================================================= // private variables. //============================================================================================= RefPtr<ID3D12CommandAllocator> m_Allocator; //!< アロケータです. RefPtr<ID3D12GraphicsCommandList> m_CmdList; //!< コマンドリストです. //============================================================================================= // private methods. //============================================================================================= /* NOTHING */ }; } // namespace asdx
[ "project.asura@gmail.com" ]
project.asura@gmail.com
e911920e35b6c233a931693042b152abe5b84dca
8318a1144be4872574ac1ceabd854f836e7362c2
/Source/Entity.cpp
54fc2476fca293f31e7102b37d782784ec952711
[]
no_license
ValeryStatinov/Patterns_project
239647f8adf62437acd94e6957f58de9c0173125
be29148e817b8a1fb431174a613ee166fb44f9e1
refs/heads/master
2021-01-25T10:06:28.417815
2018-05-23T01:15:42
2018-05-23T01:15:42
123,339,860
0
0
null
2020-02-16T11:09:14
2018-02-28T20:40:26
C++
UTF-8
C++
false
false
876
cpp
#include "../Headers/Entity.h" Entity::Entity() { dir_ = right; position_.x = 0; position_.y = 0; size_.x = 0; size_.y = 0; velocity_vector_.x = 0; velocity_vector_.y = 0; speed_ = 0; animation_manager_.set_animation("stay"); } void Entity::draw_entity(sf::RenderTexture &render_texture, float time) { animation_manager_.draw_animation(render_texture, position_.x, position_.y); animation_manager_.tick(time); return; } void Entity::add_xml_animation(const std::string& file_name, sf::Texture& texture) { animation_manager_.load_from_xml(file_name, texture); return; } sf::FloatRect Entity::get_rect() { sf::FloatRect rect; rect.left = position_.x; rect.top = position_.y; rect.width = size_.x; rect.height = size_.y; return rect; } void Entity::set_position(float x, float y) { position_.x = x; position_.y = y; return; }
[ "stv1k@stv1k-deb" ]
stv1k@stv1k-deb
d1374849d1101b8687dd1d1b9e5bd253d3d228b7
5cfc51db04e750dd33c0953a72075fdef528834a
/ToonTanks/Source/ToonTanks/Pawns/PawnTurret.h
7c7b709fd5502a4c4cb045661e49dd8c5269bb00
[]
no_license
dgnewsom/Unreal_Engine_C-
4db15d4123eb13cf0503abaaff9d57028d41a079
a3a9cdbae25b32a963263a14ee5b297dcf6c6ddf
refs/heads/main
2023-06-02T18:56:19.875100
2021-06-23T12:58:06
2021-06-23T12:58:06
373,844,783
0
0
null
null
null
null
UTF-8
C++
false
false
1,096
h
// Fill out your copyright notice in the Description page of Project Settings. #pragma once #include "CoreMinimal.h" #include "PawnBase.h" #include "PawnTurret.generated.h" class APawnTank; UCLASS() class TOONTANKS_API APawnTurret : public APawnBase { GENERATED_BODY() private: UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "Debug", meta = (AllowPrivateAccess = "true")) bool ShowAttackRadius = false; UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "Combat", meta = (AllowPrivateAccess = "true")) float FireRate = 2.f; UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "Combat", meta = (AllowPrivateAccess = "true")) float AttackRadius = 100.f; FTimerHandle FireRateTimerHandle; APawnTank* PlayerPawn; void CheckFireCondition(); float ReturnDistanceToPlayer(); public: // Sets default values for this pawn's properties APawnTurret(); // Called every frame virtual void Tick(float DeltaTime) override; virtual void HandleDestruction() override; protected: // Called when the game starts or when spawned virtual void BeginPlay() override; };
[ "danielgnewsom@gmail.com" ]
danielgnewsom@gmail.com
8958f28c0ed1e1f25553e4af7f42f6b78bf3f820
dc81c76a02995eb140d10a62588e3791a8c7de0d
/PTv3/PTStation/HistSlopeTrigger.cpp
df257933dd6974efcb28e7464c35e53b3e0cb50f
[]
no_license
xbotuk/cpp-proto-net
ab971a94899da7749b35d6586202bb4c52991461
d685bee57c8bf0e4ec2db0bfa21d028fa90240fd
refs/heads/master
2023-08-17T00:52:03.883886
2016-08-20T03:40:36
2016-08-20T03:40:36
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,187
cpp
#include "StdAfx.h" #include "HistSlopeTrigger.h" #include "DoubleCompare.h" #include "globalmembers.h" CHistSlopeTrigger::CHistSlopeTrigger(const entity::TriggerItem& triggerItem) : CTrigger(triggerItem) { Apply(triggerItem); } CHistSlopeTrigger::~CHistSlopeTrigger(void) { } void CHistSlopeTrigger::Apply( const entity::TriggerItem& triggerItem ) { m_offset = triggerItem.hs_offset(); m_fastAngleThreshold = triggerItem.hs_fastanglethreshold(); m_slowAngleThreshold = triggerItem.hs_slowanglethreshold(); } bool CHistSlopeOpenTrigger::OnTest( const double vals[], int size ) { if(size == 2) { double fastAngle = fabs(vals[0]); double slowAngle = fabs(vals[1]); if(m_offset == entity::OPEN) { LOG_DEBUG(logger, boost::str(boost::format("HistSlope Testing for OPEN: slowAngle: %.2f >= %.2f ?, fastAngle: %.2f >= %.2f ?") % slowAngle % m_slowAngleThreshold % fastAngle % m_fastAngleThreshold)); if(DoubleGreaterEqual(slowAngle, m_slowAngleThreshold) && DoubleGreaterEqual(fastAngle, m_fastAngleThreshold)) { return true; } } } return false; } bool CHistSlopeCloseTrigger::OnTest( const double vals[], int size ) { if(size == 2 && m_direction > entity::NET) { double fastAngle = fabs(vals[0]); double slowAngle = fabs(vals[1]); if(m_offset == entity::CLOSE) { double fa = vals[0]; double sa = vals[1]; LOG_DEBUG(logger, boost::str(boost::format("HistSlope Testing for CLOSE: slowAngle: %.2f, fastAngle: %.2f") % sa % fa)); bool isSlowAngleGood = m_direction == entity::LONG ? sa > 0 : sa < 0; if(isSlowAngleGood) { if(fa * sa < 0 && // fast and slow have different slope direction DoubleGreaterEqual(fastAngle, m_fastAngleThreshold))// fast Angle different than slow Angle, AND > 45 { LOG_DEBUG(logger, boost::str(boost::format("Fast Angle has become against Slow Angle and greater than %.2f") % m_fastAngleThreshold)); return true; } } else { LOG_DEBUG(logger, boost::str(boost::format("Slow Angle has reversed. (sa:%.2f)") % sa)); return true; } } } return false; }
[ "zxiaoyong@163.com" ]
zxiaoyong@163.com
58079e1d1543bbf96e30cdf2177911ea6958dbd5
d9cfe5dd9bcbd5e168c780c0f4ede892b9e9df63
/pfs-dom/include/pfs/dom/document.hpp
82ea9711ddfd47feaf3dc5c631269def7a05dfb7
[]
no_license
semenovf/archive
c196d326d85524f86ee734adee74b2f090eac6ee
5bc6d21d072292dedc9aa4d7a281bc75a1663441
refs/heads/master
2022-05-30T11:04:17.315475
2022-04-27T03:33:56
2022-04-27T03:33:56
130,155,339
0
0
null
null
null
null
UTF-8
C++
false
false
2,298
hpp
#ifndef __PFS_DOM_DOCUMENT_HPP__ #define __PFS_DOM_DOCUMENT_HPP__ #include <pfs/string.hpp> namespace pfs { namespace dom { class document_impl; class node; class dom_implementation; class doctype; class document_fragment; class element; class text; class comment; class cdatasection; class processing_instruction; class attr; class entityref; class nodelist; class DLL_API document : public node { friend class node; friend class document_impl; protected: document (document_impl *); public: document () : node() {} explicit document (const pfs::string & name); explicit document (const doctype & dt); document (const document & other); document & operator = (const document & other); ~document () {} pfs::dom::doctype doctype () const; dom_implementation implementation () const; element document_element () const; element create_element (const pfs::string & tagname); element create_element_ns (const pfs::string & namespace_uri, const pfs::string & qualified_name); document_fragment create_document_fragment (); text create_text_node (const pfs::string & data); comment create_comment (const pfs::string & data); cdatasection create_cdata_section (const pfs::string & data); processing_instruction create_processing_instruction (const pfs::string & target, const pfs::string & data); attr create_attribute (const pfs::string & name); attr create_attribute_ns (const pfs::string & namespace_uri, const pfs::string & qualified_name); entityref create_entity_reference (const pfs::string & name); node import_node (const node & importedNode, bool deep); nodelist get_elements_by_tagname (const pfs::string & tagname) const; nodelist elements_by_tagname (const pfs::string & tagname) const { return get_elements_by_tagname(tagname); } nodelist get_elements_by_tagname_ns (const pfs::string & namespace_uri, const pfs::string & localname) const; nodelist elements_by_tagname_ns (const pfs::string & namespace_uri, const pfs::string & localname) const { return get_elements_by_tagname_ns(namespace_uri, localname); } element get_element_by_id (const pfs::string & element_id) const; element element_by_id (const pfs::string & element_id) const { return get_element_by_id(element_id); } }; }} // pfs::dom #endif /* __PFS_DOM_DOCUMENT_HPP__ */
[ "fedor.v.semenov@gmail.com" ]
fedor.v.semenov@gmail.com
2b03f54d561b597e9ac4e89760fe5df705e9b17f
519bc1ddeb2128c7393d5e6262c282abe3983249
/HW2_ConwaysLife/world.hpp
2973003b3d225b4cdbf849383d9294da425f0026
[]
no_license
listvin/4finomen
6da45aba957f98de998a01af0c460968e04b31d8
f043fd0bb0be5ab5cf4e8ce7a312fc49c135c183
refs/heads/master
2020-04-26T14:55:52.539208
2015-05-21T06:25:27
2015-05-21T06:25:27
31,102,335
0
0
null
null
null
null
UTF-8
C++
false
false
8,832
hpp
#include <iostream> #include <fstream> #include <cstdio> #include <cassert> #include <vector> #include <algorithm> using namespace std; #define CUU "\u001B[1A" #define CUD "\u001B[1B" #define CUF "\u001B[1C" #define CUB "\u001B[1D" #define RESET "\u001B[0m" #define GREEN "\u001B[32m" #define RED "\u001B[31m" #define BGREEN "\u001B[32;1m" #define BRED "\u001B[31;1m" #define REP(n) for (int i = 0; i < (int)n; ++i) #define DB(a) #a " == " << (a) << "; " enum tstate {_dead = 0, _alive = 1}; enum tdir {_east = 0, _north = 1, _west = 2, _south = 3}; tdir inc(tdir dir, int increment = 1){ int tmp = (int)dir + increment; while (tmp < 0) tmp += 4; return (tdir)(tmp % 4); } tdir dec(tdir dir, int decrement = 1){ return inc(dir, -decrement); } tdir opp(tdir dir){ return inc(dir, 2); } const string marker = "ABCDEFGHIJKLMNOPRSTUVWXYZ0123456789"; struct tcell{ static int n; char id; tstate state[2] = {_dead, _dead}; tcell * neighbour[4] = {NULL, NULL, NULL, NULL}; tcell(){ id = ++n < (int)marker.size() ? marker[n] : '$'; } }; int tcell::n = 0; #define FOR_ALL_CELLS(it) \ for (tcell * row = corner[0]; row != NULL; row = row->neighbour[1])\ for (tcell * it = row; it != NULL; it = it->neighbour[2]) namespace debug{ void print(tcell * it, int t = 0){ fprintf(stderr, "\v\v" CUU CUU); if (!it) { fprintf(stderr, " @ │" CUD CUB CUB CUB CUB "@ @│" CUD CUB CUB CUB CUB " @ │" CUU CUU); return; } char c[4]; REP(4) c[i] = it->neighbour[i] ? it->neighbour[i]->id : '@'; /* colour guide * bold green - living second or more step * just green - recently came alive * bold red - being died for at least two steps * just red - died recently */ string me; if (it->state[t]) //alive now me = it->state[!t] ? BGREEN : GREEN; else me = it->state[!t] ? RED : BRED; me = me + it->id + RESET; //~ fprintf(stderr, " %c " CUD CUB CUB CUB "%c%s%c" CUD CUB CUB CUB " %c " CUU CUU, c[_north], c[_west], me.c_str(), c[_east], c[_south]); fprintf(stderr, " %c │" CUD CUB CUB CUB CUB "%c%s%c│" CUD CUB CUB CUB CUB " %c │" CUU CUU, c[_south], c[_east], me.c_str(), c[_west], c[_north]); ///ACHTUNG! IT'S A BIT INVERTED } } class tworld{ private: int T = 0; //time counter tcell * corner[4]; //corner hooks for cells int bound[4] = {1, 1, 0, 0}; int alive[2] = {0, 0}; //count of living cells int length(tdir dir){ return bound[dir] + bound[opp(dir)];} bool parity(bool current = false){ return (T + !current) & 1;} public: int born, dead; //for statistics only int alive_count(){ return alive[parity(true)];} private: void expand(tdir dir){ //1. init locals tcell * hook = corner[dir]; tcell * cur = NULL; tcell * prev = NULL; //2. create new cells while (hook){ cur = new tcell(); hook->neighbour[dir] = cur; if (prev) prev->neighbour[inc(dir, 1)] = cur; cur->neighbour[inc(dir, 2)] = hook; cur->neighbour[inc(dir, 3)] = prev; prev = cur; hook = hook->neighbour[inc(dir)]; } //3. move corners outwards for (int i = 0 ; i < 2; ++i) corner[inc(dir, i)] = corner[inc(dir, i)]->neighbour[dir]; //4. increase size ++bound[dir]; } void expansion(){ bool pp = parity(false); //number of previous (irrelevant) moment of time in tcell.state[] //~ cerr << "gagagagagagagagagagagagagagagagagagagagagagagagagagagagagagagagagagagagagagagagagagagagagagagagagagagagagagagagagagagagagagagagagagagagagagagagagagagagagagagagagagagagagagagagagagagagagagagagagagagagagagagagagagagaga\n"; REP(4){ tdir dir = (tdir)i; //direction of possible expansion //~ cerr << DB(dir) ":"; for (tcell * it = corner[dir]; it != NULL; it = it->neighbour[inc(dir)]) if (it->state[pp]){ //~ cerr << "+"; expand(dir); //~ int k = 0; //~ cerr << DB(corner[0]->id) DB(corner[1]->id) DB(corner[2]->id) DB(corner[3]->id) << endl; //~ FOR_ALL_CELLS(ga) debug::print(ga, parity(true)), cerr << ((++k)%5 ? "" : "\n\n\n"); //cerr << "\n\n\n"; break; } //~ else cerr << "-"; //~ cerr << endl; } } void reduce(tdir dir){ if (length(dir) == 1) return; //1. init locals tcell * prev = NULL; tcell * cur = corner[dir]; //2. move corners inwards for (int i = 0 ; i < 2; ++i) corner[inc(dir, i)] = corner[inc(dir, i)]->neighbour[opp(dir)]; //3. delete extra cells while (cur){ cur->neighbour[opp(dir)]->neighbour[dir] = NULL; prev = cur; cur = cur->neighbour[inc(dir)]; delete prev; } //4. decrease size --bound[dir]; } void reduction(){ bool cp = parity(true); //number of current (relevant) moment of time in tcell.state[] REP(4){ tdir dir = (tdir)i; //direction of possible expansion bool to_reduce = true; while (length(dir) > 1 && to_reduce){ for (tcell * it = corner[dir]->neighbour[opp(dir)]; it != NULL; it = it->neighbour[inc(dir)]) if (it->state[cp]){ to_reduce = false; break; } if (to_reduce) reduce(dir); } } } tstate det_state(tcell * p){ assert(p); int c = 0; //count of alive cells bool pp = parity(false); //number of previous (irrelevant) moment of time in tcell.state[] for (int i = 0; i < 4; ++i){ tdir dir = (tdir)i; if (p->neighbour[dir]){ c += p->neighbour[dir]->state[pp]; if (p->neighbour[dir]->neighbour[inc(dir)]) c += p->neighbour[dir]->neighbour[inc(dir)]->state[pp]; } } return c == 2 ? p->state[pp] : tstate(c == 3); } public: void step(){ //~ cerr << DB(T) << endl; //~ reset(); scope(0,0); //~ int k = 0; //~ FOR_ALL_CELLS(it) debug::print(it, parity(true)), cerr << ((++k)%3 ? "" : "\n\n\n"); //cerr << "\n\n\n"; //1. step the timer ++T; //2. expand if necessary expansion(); //~ --T; reset(); scope(0,0); ++T; //~ int k = 0; //~ FOR_ALL_CELLS(it) debug::print(it, parity(false)), cerr << ((++k)%5 ? "" : "\n\n\n"); //cerr << "\n\n\n"; //3. renew population int pp = parity(false); int cp = parity(true); FOR_ALL_CELLS(it) it->state[cp] = det_state(it); //4. get stats alive[cp] = born = dead = 0; FOR_ALL_CELLS(it) if (bool(it->state[pp]) ^ bool(it->state[cp])){ if (it->state[cp] == _alive) born += !it->state[pp], ++alive[cp]; else ++dead; } //5. reduce if possible //~ reduction(); } tworld(){ corner[0] = corner[1] = corner[2] = corner[3] = new tcell(); } private: tworld(int W, int H) : tworld(){ assert(W >= 1 && H >= 1); while (bound[_east] < W) expand(_east); while (bound[_north] < H) expand(_north); } public: int width(){ return length(_east);} int height(){ return length(_north);} int minX(){ return -bound[_west];} int minY(){ return -bound[_south];} tworld(int W, int H, int aliveCount) : tworld(W, H){ //1. init locals int N = W*H; assert(N >= aliveCount); //2. generate numbers for alive cells vector <int> a(N); REP(N) a[i] = i+1; REP(N) swap(a[i], a[rand()%(i+1)]); sort(&a[0], &a[aliveCount]); //3. walk around the world int i = 0; FOR_ALL_CELLS(it) if (++i == a[alive[0]]) it->state[0] = _alive, ++alive[0]; } tworld(ifstream * inf){ string s; getline(*inf, s); *this = tworld((int)s.size(), (int)s.size()); for (tcell * row = corner[2]; row != NULL; row = row->neighbour[_south]){ int i = 0; for (tcell * it = row; it != NULL; it = it->neighbour[_east], ++i) alive[0] += it->state[0] = s[i] == '0' || s[i] == ' ' || s[i] == '.' ? _dead : _alive; getline(*inf, s); } } private: tcell * shook = NULL; //in order to make scope() faster int sx = 0, sy = 0, sh = 24; //in order to make scope() faster void print(){ int cp = parity(true); tcell * hook = shook; int lsh = 1; REP(sh-1) if (hook->neighbour[_north]) hook = hook->neighbour[_north], ++lsh; assert(corner[2] == hook); int y = 0; for (tcell * row = hook; row != NULL && y < lsh; row = row->neighbour[_south], ++y){ int x = 0; for (tcell * it = row; it != NULL && x < sh; it = it->neighbour[_east], ++x) //~ putchar(it->id); putchar(it->state[cp] ? '#' : '*'); //~ printf("\tline №%d\n", y); printf("\n"); } } public: void reset(){ shook = corner[3]; sx = minX(); sy = minY(); } bool scope(int dx, int dy){ assert(dx * dy == 0); if (!shook) reset(); if (!dx && !dy){ print(); return true; } if (dx) if (dx > 0) if (shook->neighbour[_east]) shook = shook->neighbour[_east]; else return false; else if (shook->neighbour[_west]) shook = shook->neighbour[_west]; else return false; else if (dy > 0) if (shook->neighbour[_north]) shook = shook->neighbour[_north]; else return false; else if (shook->neighbour[_south]) shook = shook->neighbour[_south]; else return false; print(); return true; } }; #undef REP #undef FOR_ALL_CELLS
[ "fyodor-listvin@ya.ru" ]
fyodor-listvin@ya.ru
bb558d18e758c2d758c50d370495e4e8d483c9dd
b8fb6c802cf4767f582b64aca4e05ab8df9b7cbe
/src/Memory/Arena.h
08038f24a9b2b4229d266007bac099abda96a2ee
[ "MIT" ]
permissive
castly6/rainbow
8bc82bbb6d2b1bae3b095a05c12b10f599267ae8
96d90b5a81e1fda09f5b570f6c972026d1b29f32
refs/heads/master
2020-05-30T11:27:39.773049
2015-12-22T16:21:24
2015-12-22T20:10:15
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,768
h
// Copyright (c) 2010-15 Bifrost Entertainment AS and Tommy Nguyen // Distributed under the MIT License. // (See accompanying file LICENSE or copy at http://opensource.org/licenses/MIT) #ifndef MEMORY_ARENA_H_ #define MEMORY_ARENA_H_ #include <iterator> #include <memory> #include <new> #include "Common/NonCopyable.h" template<typename T> class Arena : private NonCopyable<Arena<T>> { public: Arena() : arena_(nullptr) {} Arena(Arena&& a) : arena_(a.arena_) { a.arena_ = nullptr; } ~Arena() { operator delete(arena_); } /// <summary>Returns the pointer to the arena.</summary> T* get() const { return arena_; } /// <summary>Releases <paramref name="count"/> elements.</summary> void release(size_t count) const { if (!arena_) return; while (count > 0) arena_[--count].~T(); } /// <summary> /// Resizes arena to hold <paramref name="new_count"/> elements and moves /// <paramref name="old_count"/> elements over. /// </summary> /// <param name="old_count">Number of elements to keep.</param> /// <param name="new_count">Number of elements to allocate for.</param> void resize(const size_t old_count, const size_t new_count) { T *new_arena = static_cast<T*>(operator new(new_count * sizeof(T))); if (old_count > 0) { std::uninitialized_copy_n( std::make_move_iterator(arena_), old_count, new_arena); } operator delete(arena_); arena_ = new_arena; } /// <summary>Returns whether this arena is valid.</summary> explicit operator bool() const { return arena_; } T& operator[](const size_t i) const { return arena_[i]; } T* operator->() const { return arena_; } T* operator+(const size_t offset) const { return arena_ + offset; } T& operator*() const { return *arena_; } private: T *arena_; }; #endif
[ "tn0502@gmail.com" ]
tn0502@gmail.com
ac66cfd3ce40aa52d98e7965d489d73dae9fb11e
769a40e65649a3bd049ebad0bb58d57937282eaf
/Scans/ScanUtils/ScanState/IdleScanState.h
9026380a6b50c887139c272d0455aa5d5a796044
[]
no_license
ottocruyt/scan
47d25ea1ee4dc2680f7cb0e2e6cc97d5fa9389c1
543ac0cbdc4c8d06b5339f9c23fd05b01c95049f
refs/heads/master
2023-03-26T12:13:20.560681
2021-03-25T14:06:00
2021-03-25T14:06:00
341,096,967
0
0
null
null
null
null
UTF-8
C++
false
false
323
h
#ifndef IDLESCANSTATE_H #define IDLESCANSTATE_H #include "..\..\..\Globals.h" #include <sstream> #include <iostream> #include <string> #include "ScanState.h" #include "SettingUpScanState.h" class IdleScanState : public ScanState { public: IdleScanState(); ~IdleScanState(); void start(); void stop(); }; #endif
[ "ottocruyt@gmail.com" ]
ottocruyt@gmail.com
322ffd432ada890ae191adc16f359f221ebf5b1e
85d2c76b8a646c4183fb095c2b5a2e2a916d70a8
/solution/prefix_sum/21757/main.cpp
bc34c2db7cb4784482934fb8cbad9aa574fb3e09
[ "MIT" ]
permissive
tony9402/baekjoon
448213dcbdf74b58b6d87191ac54c286bad32f29
71f9bfc1f4ed66b97ffc0aff2d17389a095a7d11
refs/heads/main
2023-08-16T17:54:08.533578
2023-08-16T16:36:36
2023-08-16T16:36:36
200,492,112
4,828
1,230
MIT
2023-06-22T11:49:18
2019-08-04T12:48:59
Python
UTF-8
C++
false
false
835
cpp
// Authored by : tony9402 // Co-authored by : - // Link : http://boj.kr/421ce6bb00ca40709c15dc5df958d5f1 #include<bits/stdc++.h> using namespace std; typedef long long ll; const int MAXN = 100000; ll prefix[MAXN + 5]; ll L[MAXN + 5], R[MAXN + 5]; int main(){ ios::sync_with_stdio(false); cin.tie(0); int N; cin >> N; for(int i=1;i<=N;i++) { cin >> prefix[i]; prefix[i] += prefix[i - 1]; } for(int i = 1; i <= N; i++) { L[i] = L[i - 1]; if(prefix[N] == 4 * prefix[i]) L[i] ++; } for(int i = N - 1; i >= 1; i--) { R[i] = R[i + 1]; if(prefix[N] * 3 == 4 * prefix[i]) R[i] ++; } ll answer = 0; for(int i = 2; i < N - 1; i++) { if(prefix[N] == prefix[i] * 2) answer += L[i - 1] * R[i + 1]; } cout << answer; return 0; }
[ "tony9402@naver.com" ]
tony9402@naver.com
61c601948daefe3e27b3b8e6a15f7033f29b448b
41b4adb10cc86338d85db6636900168f55e7ff18
/aws-cpp-sdk-directconnect/source/model/AllocatePublicVirtualInterfaceResult.cpp
48309ba1082343282d7678debe45d3c833286d45
[ "JSON", "MIT", "Apache-2.0" ]
permissive
totalkyos/AWS
1c9ac30206ef6cf8ca38d2c3d1496fa9c15e5e80
7cb444814e938f3df59530ea4ebe8e19b9418793
refs/heads/master
2021-01-20T20:42:09.978428
2016-07-16T00:03:49
2016-07-16T00:03:49
63,465,708
1
1
null
null
null
null
UTF-8
C++
false
false
3,543
cpp
/* * Copyright 2010-2016 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ #include <aws/directconnect/model/AllocatePublicVirtualInterfaceResult.h> #include <aws/core/utils/json/JsonSerializer.h> #include <aws/core/AmazonWebServiceResult.h> #include <aws/core/utils/UnreferencedParam.h> #include <utility> using namespace Aws::DirectConnect::Model; using namespace Aws::Utils::Json; using namespace Aws::Utils; using namespace Aws; AllocatePublicVirtualInterfaceResult::AllocatePublicVirtualInterfaceResult() : m_vlan(0), m_asn(0) { } AllocatePublicVirtualInterfaceResult::AllocatePublicVirtualInterfaceResult(const AmazonWebServiceResult<JsonValue>& result) : m_vlan(0), m_asn(0) { *this = result; } AllocatePublicVirtualInterfaceResult& AllocatePublicVirtualInterfaceResult::operator =(const AmazonWebServiceResult<JsonValue>& result) { const JsonValue& jsonValue = result.GetPayload(); if(jsonValue.ValueExists("ownerAccount")) { m_ownerAccount = jsonValue.GetString("ownerAccount"); } if(jsonValue.ValueExists("virtualInterfaceId")) { m_virtualInterfaceId = jsonValue.GetString("virtualInterfaceId"); } if(jsonValue.ValueExists("location")) { m_location = jsonValue.GetString("location"); } if(jsonValue.ValueExists("connectionId")) { m_connectionId = jsonValue.GetString("connectionId"); } if(jsonValue.ValueExists("virtualInterfaceType")) { m_virtualInterfaceType = jsonValue.GetString("virtualInterfaceType"); } if(jsonValue.ValueExists("virtualInterfaceName")) { m_virtualInterfaceName = jsonValue.GetString("virtualInterfaceName"); } if(jsonValue.ValueExists("vlan")) { m_vlan = jsonValue.GetInteger("vlan"); } if(jsonValue.ValueExists("asn")) { m_asn = jsonValue.GetInteger("asn"); } if(jsonValue.ValueExists("authKey")) { m_authKey = jsonValue.GetString("authKey"); } if(jsonValue.ValueExists("amazonAddress")) { m_amazonAddress = jsonValue.GetString("amazonAddress"); } if(jsonValue.ValueExists("customerAddress")) { m_customerAddress = jsonValue.GetString("customerAddress"); } if(jsonValue.ValueExists("virtualInterfaceState")) { m_virtualInterfaceState = VirtualInterfaceStateMapper::GetVirtualInterfaceStateForName(jsonValue.GetString("virtualInterfaceState")); } if(jsonValue.ValueExists("customerRouterConfig")) { m_customerRouterConfig = jsonValue.GetString("customerRouterConfig"); } if(jsonValue.ValueExists("virtualGatewayId")) { m_virtualGatewayId = jsonValue.GetString("virtualGatewayId"); } if(jsonValue.ValueExists("routeFilterPrefixes")) { Array<JsonValue> routeFilterPrefixesJsonList = jsonValue.GetArray("routeFilterPrefixes"); for(unsigned routeFilterPrefixesIndex = 0; routeFilterPrefixesIndex < routeFilterPrefixesJsonList.GetLength(); ++routeFilterPrefixesIndex) { m_routeFilterPrefixes.push_back(routeFilterPrefixesJsonList[routeFilterPrefixesIndex].AsObject()); } } return *this; }
[ "henso@amazon.com" ]
henso@amazon.com
fb14d16bf4a01258d8d2b421a17bbb31b732c6c1
c9eb7196339cc3b057877a2f8e057b84e145bb03
/UVa514(Rails).cpp
7393d8463eba2046d64ea71b97b888b8552fe54b
[]
no_license
LGHigh/Algorithm
af12b18284af38ce9cab31a244db9a6f571df95a
097ebff72962028442577cb2a434b788c1ca38c7
refs/heads/master
2021-05-07T23:47:05.903308
2018-03-13T02:15:46
2018-03-13T02:15:46
107,564,946
0
0
null
null
null
null
UTF-8
C++
false
false
809
cpp
#include <iostream> #include <stack> #include <vector> using namespace std; int main() { int n; while (cin >> n && n) { int t; while (cin >> t && t) { stack<int>B, C; B.push(t); for (int i = 1; i < n; i++) { int t; cin >> t; B.push(t); } int ok = 1; for (int i = n; i >= 1; i--) { while (!B.empty()) { if (B.top() != i && (C.empty() || C.top() != i)) { C.push(B.top()); B.pop(); } else if (B.top() == i) break; else break; } if (B.empty()) { if (C.top() == i)C.pop(); else { ok = 0; break; } } else { if (B.top() == i)B.pop(); else if (C.empty() || C.top()!=i) { ok = 0; break; } else C.pop(); } } if (!ok)cout << "No" << endl; else cout << "Yes" << endl; } cout << endl; } return 0; }
[ "1612895@mail.nankai.edu.cn" ]
1612895@mail.nankai.edu.cn
c561571db6574210da2f987f977c431f4a98b91d
1c803d259e1f459426fdd62b5399f4c3a65a5291
/6/list.cpp
fd648d8859359c76fd52453dc5741103d80231a6
[]
no_license
CIS190/spring2020
3c13816718116b333d8ec9744fc19cde3e7661db
3d58cefae7051e0adfa7159f6a83e439fe96bb14
refs/heads/master
2021-08-05T22:10:37.891693
2020-12-18T20:46:53
2020-12-18T20:46:53
230,176,647
7
5
null
null
null
null
UTF-8
C++
false
false
212
cpp
#include <iostream> #include <list> using namespace std; int main() { list<int> l; l.emplace_front(2); l.emplace_back(3); l.emplace_front(1); for (auto i : l) cout << i << "\n"; }
[ "paulhe@seas.upenn.edu" ]
paulhe@seas.upenn.edu
b018af9891c3accffccdbf88cee60d9a7e8e069a
702aa7364289f87d16e0fcbd163d648bd9cc4148
/Languages/C++/hello-hacktober.cpp
e269db3897fdf8e5519b0d55018f93e92c7c3237
[]
permissive
syyam/Hacktoberfest
f41cc5c1bafafb8fc4b577a4c34f58ca24d60e19
d58c6289d27aca2c728a5095078e6bc623937c5e
refs/heads/master
2022-12-30T23:37:52.748817
2020-10-06T09:21:27
2020-10-06T09:21:27
152,482,182
0
0
MIT
2018-10-10T19:59:15
2018-10-10T19:59:14
null
UTF-8
C++
false
false
74
cpp
#include<iostream.h> int main(){ cout<<"Hello Hacktober!"; return 0; }
[ "manbir01@hotmail.com" ]
manbir01@hotmail.com
d0950b14e685d383bb39b7979e0044d42022bf05
b0b710e714a7c973099e05f990a90cdab86a6384
/opencl/test/unit_test/command_stream/command_stream_receiver_hw_2_tests.cpp
d16e35fea1603026be2af3b1c7382f3579c63f21
[ "MIT" ]
permissive
gvvynplaine/compute-runtime
b22bd8952d58ac916a7c2b52c8f52860d18687c3
fd492f28b036f3fa1685ecfbef86e64f8c7e3d8a
refs/heads/master
2023-01-06T20:44:37.674507
2020-10-14T13:40:57
2020-10-15T08:22:30
304,321,890
0
0
MIT
2020-10-30T12:32:37
2020-10-15T12:39:15
null
UTF-8
C++
false
false
67,711
cpp
/* * Copyright (C) 2018-2020 Intel Corporation * * SPDX-License-Identifier: MIT * */ #include "shared/source/command_stream/scratch_space_controller_base.h" #include "shared/test/unit_test/utilities/base_object_utils.h" #include "opencl/source/event/user_event.h" #include "opencl/source/helpers/cl_blit_properties.h" #include "opencl/source/mem_obj/mem_obj_helper.h" #include "opencl/test/unit_test/command_stream/command_stream_receiver_hw_fixture.h" #include "opencl/test/unit_test/fixtures/ult_command_stream_receiver_fixture.h" #include "opencl/test/unit_test/helpers/raii_hw_helper.h" #include "opencl/test/unit_test/mocks/mock_allocation_properties.h" #include "opencl/test/unit_test/mocks/mock_hw_helper.h" #include "opencl/test/unit_test/mocks/mock_internal_allocation_storage.h" #include "opencl/test/unit_test/mocks/mock_kernel.h" #include "opencl/test/unit_test/mocks/mock_memory_manager.h" #include "opencl/test/unit_test/mocks/mock_timestamp_container.h" #include "test.h" using namespace NEO; HWTEST_F(BcsTests, givenBltSizeWhenEstimatingCommandSizeThenAddAllRequiredCommands) { constexpr auto max2DBlitSize = BlitterConstants::maxBlitWidth * BlitterConstants::maxBlitHeight; constexpr auto cmdsSizePerBlit = sizeof(typename FamilyType::XY_COPY_BLT) + sizeof(typename FamilyType::MI_ARB_CHECK); size_t notAlignedBltSize = (3 * max2DBlitSize) + 1; size_t alignedBltSize = (3 * max2DBlitSize); uint32_t alignedNumberOfBlts = 3; uint32_t notAlignedNumberOfBlts = 4; auto expectedAlignedSize = cmdsSizePerBlit * alignedNumberOfBlts; auto expectedNotAlignedSize = cmdsSizePerBlit * notAlignedNumberOfBlts; auto alignedCopySize = Vec3<size_t>{alignedBltSize, 1, 1}; auto notAlignedCopySize = Vec3<size_t>{notAlignedBltSize, 1, 1}; auto alignedEstimatedSize = BlitCommandsHelper<FamilyType>::estimateBlitCommandsSize( alignedCopySize, csrDependencies, false, false, pClDevice->getRootDeviceEnvironment()); auto notAlignedEstimatedSize = BlitCommandsHelper<FamilyType>::estimateBlitCommandsSize( notAlignedCopySize, csrDependencies, false, false, pClDevice->getRootDeviceEnvironment()); EXPECT_EQ(expectedAlignedSize, alignedEstimatedSize); EXPECT_EQ(expectedNotAlignedSize, notAlignedEstimatedSize); EXPECT_FALSE(BlitCommandsHelper<FamilyType>::isCopyRegionPreferred(alignedCopySize, pClDevice->getRootDeviceEnvironment())); EXPECT_FALSE(BlitCommandsHelper<FamilyType>::isCopyRegionPreferred(notAlignedCopySize, pClDevice->getRootDeviceEnvironment())); } HWTEST_F(BcsTests, givenDebugCapabilityWhenEstimatingCommandSizeThenAddAllRequiredCommands) { constexpr auto max2DBlitSize = BlitterConstants::maxBlitWidth * BlitterConstants::maxBlitHeight; constexpr auto cmdsSizePerBlit = sizeof(typename FamilyType::XY_COPY_BLT) + sizeof(typename FamilyType::MI_ARB_CHECK); const size_t debugCommandsSize = (EncodeMiFlushDW<FamilyType>::getMiFlushDwCmdSizeForDataWrite() + EncodeSempahore<FamilyType>::getSizeMiSemaphoreWait()) * 2; constexpr uint32_t numberOfBlts = 3; constexpr size_t bltSize = (numberOfBlts * max2DBlitSize); auto expectedSize = (cmdsSizePerBlit * numberOfBlts) + debugCommandsSize + MemorySynchronizationCommands<FamilyType>::getSizeForAdditonalSynchronization(pDevice->getHardwareInfo()) + EncodeMiFlushDW<FamilyType>::getMiFlushDwCmdSizeForDataWrite() + sizeof(typename FamilyType::MI_BATCH_BUFFER_END); expectedSize = alignUp(expectedSize, MemoryConstants::cacheLineSize); BlitProperties blitProperties; blitProperties.copySize = {bltSize, 1, 1}; BlitPropertiesContainer blitPropertiesContainer; blitPropertiesContainer.push_back(blitProperties); auto estimatedSize = BlitCommandsHelper<FamilyType>::estimateBlitCommandsSize( blitPropertiesContainer, false, true, pClDevice->getRootDeviceEnvironment()); EXPECT_EQ(expectedSize, estimatedSize); EXPECT_FALSE(BlitCommandsHelper<FamilyType>::isCopyRegionPreferred(blitProperties.copySize, pClDevice->getRootDeviceEnvironment())); } HWTEST_F(BcsTests, givenBltSizeWhenEstimatingCommandSizeForReadBufferRectThenAddAllRequiredCommands) { constexpr auto max2DBlitSize = BlitterConstants::maxBlitWidth * BlitterConstants::maxBlitHeight; constexpr auto cmdsSizePerBlit = sizeof(typename FamilyType::XY_COPY_BLT) + sizeof(typename FamilyType::MI_ARB_CHECK); Vec3<size_t> notAlignedBltSize = {(3 * max2DBlitSize) + 1, 4, 2}; Vec3<size_t> alignedBltSize = {(3 * max2DBlitSize), 4, 2}; size_t alignedNumberOfBlts = 3 * alignedBltSize.y * alignedBltSize.z; size_t notAlignedNumberOfBlts = 4 * notAlignedBltSize.y * notAlignedBltSize.z; auto expectedAlignedSize = cmdsSizePerBlit * alignedNumberOfBlts; auto expectedNotAlignedSize = cmdsSizePerBlit * notAlignedNumberOfBlts; auto alignedEstimatedSize = BlitCommandsHelper<FamilyType>::estimateBlitCommandsSize( alignedBltSize, csrDependencies, false, false, pClDevice->getRootDeviceEnvironment()); auto notAlignedEstimatedSize = BlitCommandsHelper<FamilyType>::estimateBlitCommandsSize( notAlignedBltSize, csrDependencies, false, false, pClDevice->getRootDeviceEnvironment()); EXPECT_EQ(expectedAlignedSize, alignedEstimatedSize); EXPECT_EQ(expectedNotAlignedSize, notAlignedEstimatedSize); EXPECT_FALSE(BlitCommandsHelper<FamilyType>::isCopyRegionPreferred(notAlignedBltSize, pClDevice->getRootDeviceEnvironment())); EXPECT_FALSE(BlitCommandsHelper<FamilyType>::isCopyRegionPreferred(alignedBltSize, pClDevice->getRootDeviceEnvironment())); } HWTEST_F(BcsTests, givenBltWithBigCopySizeWhenEstimatingCommandSizeForReadBufferRectThenAddAllRequiredCommands) { auto &rootDeviceEnvironment = pClDevice->getRootDeviceEnvironment(); auto maxWidthToCopy = static_cast<size_t>(BlitCommandsHelper<FamilyType>::getMaxBlitWidth(rootDeviceEnvironment)); auto maxHeightToCopy = static_cast<size_t>(BlitCommandsHelper<FamilyType>::getMaxBlitHeight(rootDeviceEnvironment)); constexpr auto cmdsSizePerBlit = sizeof(typename FamilyType::XY_COPY_BLT) + sizeof(typename FamilyType::MI_ARB_CHECK); Vec3<size_t> alignedBltSize = {(3 * maxWidthToCopy), (4 * maxHeightToCopy), 2}; Vec3<size_t> notAlignedBltSize = {(3 * maxWidthToCopy + 1), (4 * maxHeightToCopy), 2}; EXPECT_TRUE(BlitCommandsHelper<FamilyType>::isCopyRegionPreferred(alignedBltSize, rootDeviceEnvironment)); size_t alignedNumberOfBlts = (3 * 4 * alignedBltSize.z); size_t notAlignedNumberOfBlts = (4 * 4 * notAlignedBltSize.z); auto expectedAlignedSize = cmdsSizePerBlit * alignedNumberOfBlts; auto expectedNotAlignedSize = cmdsSizePerBlit * notAlignedNumberOfBlts; auto alignedEstimatedSize = BlitCommandsHelper<FamilyType>::estimateBlitCommandsSize( alignedBltSize, csrDependencies, false, false, rootDeviceEnvironment); auto notAlignedEstimatedSize = BlitCommandsHelper<FamilyType>::estimateBlitCommandsSize( notAlignedBltSize, csrDependencies, false, false, rootDeviceEnvironment); EXPECT_EQ(expectedAlignedSize, alignedEstimatedSize); EXPECT_EQ(expectedNotAlignedSize, notAlignedEstimatedSize); EXPECT_TRUE(BlitCommandsHelper<FamilyType>::isCopyRegionPreferred(notAlignedBltSize, rootDeviceEnvironment)); EXPECT_TRUE(BlitCommandsHelper<FamilyType>::isCopyRegionPreferred(alignedBltSize, rootDeviceEnvironment)); } HWTEST_F(BcsTests, WhenGetNumberOfBlitsIsCalledThenCorrectValuesAreReturned) { auto &rootDeviceEnvironment = pClDevice->getRootDeviceEnvironment(); auto maxWidthToCopy = static_cast<size_t>(BlitCommandsHelper<FamilyType>::getMaxBlitWidth(rootDeviceEnvironment)); auto maxHeightToCopy = static_cast<size_t>(BlitCommandsHelper<FamilyType>::getMaxBlitHeight(rootDeviceEnvironment)); { Vec3<size_t> copySize = {maxWidthToCopy * maxHeightToCopy, 1, 3}; size_t expectednBlitsCopyRegion = maxHeightToCopy * 3; size_t expectednBlitsCopyPerRow = 3; auto nBlitsCopyRegion = BlitCommandsHelper<FamilyType>::getNumberOfBlitsForCopyRegion(copySize, rootDeviceEnvironment); auto nBlitsCopyPerRow = BlitCommandsHelper<FamilyType>::getNumberOfBlitsForCopyPerRow(copySize, rootDeviceEnvironment); EXPECT_EQ(expectednBlitsCopyPerRow, nBlitsCopyPerRow); EXPECT_EQ(expectednBlitsCopyRegion, nBlitsCopyRegion); EXPECT_FALSE(BlitCommandsHelper<FamilyType>::isCopyRegionPreferred(copySize, rootDeviceEnvironment)); } { Vec3<size_t> copySize = {2 * maxWidthToCopy, 16, 3}; size_t expectednBlitsCopyRegion = 2 * 3; size_t expectednBlitsCopyPerRow = 16 * 3; auto nBlitsCopyRegion = BlitCommandsHelper<FamilyType>::getNumberOfBlitsForCopyRegion(copySize, rootDeviceEnvironment); auto nBlitsCopyPerRow = BlitCommandsHelper<FamilyType>::getNumberOfBlitsForCopyPerRow(copySize, rootDeviceEnvironment); EXPECT_EQ(expectednBlitsCopyPerRow, nBlitsCopyPerRow); EXPECT_EQ(expectednBlitsCopyRegion, nBlitsCopyRegion); EXPECT_TRUE(BlitCommandsHelper<FamilyType>::isCopyRegionPreferred(copySize, rootDeviceEnvironment)); } { Vec3<size_t> copySize = {2 * maxWidthToCopy, 3 * maxHeightToCopy, 4}; size_t expectednBlitsCopyRegion = 2 * 3 * 4; size_t expectednBlitsCopyPerRow = 3 * maxHeightToCopy * 4; auto nBlitsCopyRegion = BlitCommandsHelper<FamilyType>::getNumberOfBlitsForCopyRegion(copySize, rootDeviceEnvironment); auto nBlitsCopyPerRow = BlitCommandsHelper<FamilyType>::getNumberOfBlitsForCopyPerRow(copySize, rootDeviceEnvironment); EXPECT_EQ(expectednBlitsCopyPerRow, nBlitsCopyPerRow); EXPECT_EQ(expectednBlitsCopyRegion, nBlitsCopyRegion); EXPECT_TRUE(BlitCommandsHelper<FamilyType>::isCopyRegionPreferred(copySize, rootDeviceEnvironment)); } } HWTEST_F(BcsTests, givenCsrDependenciesWhenProgrammingCommandStreamThenAddSemaphoreAndAtomic) { auto &csr = pDevice->getUltCommandStreamReceiver<FamilyType>(); cl_int retVal = CL_SUCCESS; auto buffer = clUniquePtr<Buffer>(Buffer::create(context.get(), CL_MEM_READ_WRITE, 1, nullptr, retVal)); void *hostPtr = reinterpret_cast<void *>(0x12340000); uint32_t numberOfDependencyContainers = 2; size_t numberNodesPerContainer = 5; auto graphicsAllocation = buffer->getGraphicsAllocation(pDevice->getRootDeviceIndex()); auto blitProperties = BlitProperties::constructPropertiesForReadWriteBuffer(BlitterConstants::BlitDirection::HostPtrToBuffer, csr, graphicsAllocation, nullptr, hostPtr, graphicsAllocation->getGpuAddress(), 0, 0, 0, {1, 1, 1}, 0, 0, 0, 0); MockTimestampPacketContainer timestamp0(*csr.getTimestampPacketAllocator(), numberNodesPerContainer); MockTimestampPacketContainer timestamp1(*csr.getTimestampPacketAllocator(), numberNodesPerContainer); blitProperties.csrDependencies.push_back(&timestamp0); blitProperties.csrDependencies.push_back(&timestamp1); blitBuffer(&csr, blitProperties, true); HardwareParse hwParser; hwParser.parseCommands<FamilyType>(csr.commandStream); auto &cmdList = hwParser.cmdList; bool xyCopyBltCmdFound = false; bool dependenciesFound = false; for (auto cmdIterator = cmdList.begin(); cmdIterator != cmdList.end(); cmdIterator++) { if (genCmdCast<typename FamilyType::XY_COPY_BLT *>(*cmdIterator)) { xyCopyBltCmdFound = true; continue; } auto miSemaphore = genCmdCast<typename FamilyType::MI_SEMAPHORE_WAIT *>(*cmdIterator); if (miSemaphore) { if (UnitTestHelper<FamilyType>::isAdditionalMiSemaphoreWait(*miSemaphore)) { continue; } dependenciesFound = true; EXPECT_FALSE(xyCopyBltCmdFound); auto miAtomic = genCmdCast<typename FamilyType::MI_ATOMIC *>(*(++cmdIterator)); EXPECT_NE(nullptr, miAtomic); for (uint32_t i = 1; i < numberOfDependencyContainers * numberNodesPerContainer; i++) { EXPECT_NE(nullptr, genCmdCast<typename FamilyType::MI_SEMAPHORE_WAIT *>(*(++cmdIterator))); EXPECT_NE(nullptr, genCmdCast<typename FamilyType::MI_ATOMIC *>(*(++cmdIterator))); } } } EXPECT_TRUE(xyCopyBltCmdFound); EXPECT_TRUE(dependenciesFound); } HWTEST_F(BcsTests, givenMultipleBlitPropertiesWhenDispatchingThenProgramCommandsInCorrectOrder) { auto &csr = pDevice->getUltCommandStreamReceiver<FamilyType>(); cl_int retVal = CL_SUCCESS; auto buffer1 = clUniquePtr<Buffer>(Buffer::create(context.get(), CL_MEM_READ_WRITE, 1, nullptr, retVal)); auto buffer2 = clUniquePtr<Buffer>(Buffer::create(context.get(), CL_MEM_READ_WRITE, 1, nullptr, retVal)); void *hostPtr1 = reinterpret_cast<void *>(0x12340000); void *hostPtr2 = reinterpret_cast<void *>(0x12340000); auto graphicsAllocation1 = buffer1->getGraphicsAllocation(pDevice->getRootDeviceIndex()); auto graphicsAllocation2 = buffer2->getGraphicsAllocation(pDevice->getRootDeviceIndex()); auto blitProperties1 = BlitProperties::constructPropertiesForReadWriteBuffer(BlitterConstants::BlitDirection::HostPtrToBuffer, csr, graphicsAllocation1, nullptr, hostPtr1, graphicsAllocation1->getGpuAddress(), 0, 0, 0, {1, 1, 1}, 0, 0, 0, 0); auto blitProperties2 = BlitProperties::constructPropertiesForReadWriteBuffer(BlitterConstants::BlitDirection::HostPtrToBuffer, csr, graphicsAllocation2, nullptr, hostPtr2, graphicsAllocation2->getGpuAddress(), 0, 0, 0, {1, 1, 1}, 0, 0, 0, 0); MockTimestampPacketContainer timestamp1(*csr.getTimestampPacketAllocator(), 1); MockTimestampPacketContainer timestamp2(*csr.getTimestampPacketAllocator(), 1); blitProperties1.csrDependencies.push_back(&timestamp1); blitProperties2.csrDependencies.push_back(&timestamp2); BlitPropertiesContainer blitPropertiesContainer; blitPropertiesContainer.push_back(blitProperties1); blitPropertiesContainer.push_back(blitProperties2); csr.blitBuffer(blitPropertiesContainer, true, false); HardwareParse hwParser; hwParser.parseCommands<FamilyType>(csr.commandStream); auto &cmdList = hwParser.cmdList; uint32_t xyCopyBltCmdFound = 0; uint32_t dependenciesFound = 0; for (auto cmdIterator = cmdList.begin(); cmdIterator != cmdList.end(); cmdIterator++) { if (genCmdCast<typename FamilyType::XY_COPY_BLT *>(*cmdIterator)) { xyCopyBltCmdFound++; EXPECT_EQ(xyCopyBltCmdFound, dependenciesFound); continue; } auto miSemaphore = genCmdCast<typename FamilyType::MI_SEMAPHORE_WAIT *>(*cmdIterator); if (miSemaphore) { if (UnitTestHelper<FamilyType>::isAdditionalMiSemaphoreWait(*miSemaphore)) { continue; } dependenciesFound++; EXPECT_EQ(xyCopyBltCmdFound, dependenciesFound - 1); } } EXPECT_EQ(2u, xyCopyBltCmdFound); EXPECT_EQ(2u, dependenciesFound); } HWTEST_F(BcsTests, givenProfilingEnabledWhenBlitBufferThenCommandBufferIsConstructedProperly) { auto bcsOsContext = std::unique_ptr<OsContext>(OsContext::create(nullptr, 0, pDevice->getDeviceBitfield(), aub_stream::ENGINE_BCS, PreemptionMode::Disabled, false, false, false)); auto bcsCsr = std::make_unique<UltCommandStreamReceiver<FamilyType>>(*pDevice->getExecutionEnvironment(), pDevice->getRootDeviceIndex()); bcsCsr->setupContext(*bcsOsContext); bcsCsr->initializeTagAllocation(); cl_int retVal = CL_SUCCESS; auto buffer = clUniquePtr<Buffer>(Buffer::create(context.get(), CL_MEM_READ_WRITE, 1, nullptr, retVal)); void *hostPtr = reinterpret_cast<void *>(0x12340000); auto graphicsAllocation = buffer->getGraphicsAllocation(pDevice->getRootDeviceIndex()); auto blitProperties = BlitProperties::constructPropertiesForReadWriteBuffer(BlitterConstants::BlitDirection::HostPtrToBuffer, *bcsCsr, graphicsAllocation, nullptr, hostPtr, graphicsAllocation->getGpuAddress(), 0, 0, 0, {1, 1, 1}, 0, 0, 0, 0); MockTimestampPacketContainer timestamp(*bcsCsr->getTimestampPacketAllocator(), 1u); blitProperties.outputTimestampPacket = timestamp.getNode(0); BlitPropertiesContainer blitPropertiesContainer; blitPropertiesContainer.push_back(blitProperties); bcsCsr->blitBuffer(blitPropertiesContainer, false, true); HardwareParse hwParser; hwParser.parseCommands<FamilyType>(bcsCsr->commandStream); auto &cmdList = hwParser.cmdList; auto cmdIterator = find<typename FamilyType::MI_STORE_REGISTER_MEM *>(cmdList.begin(), cmdList.end()); ASSERT_NE(cmdList.end(), cmdIterator); cmdIterator = find<typename FamilyType::MI_STORE_REGISTER_MEM *>(++cmdIterator, cmdList.end()); ASSERT_NE(cmdList.end(), cmdIterator); cmdIterator = find<typename FamilyType::XY_COPY_BLT *>(++cmdIterator, cmdList.end()); ASSERT_NE(cmdList.end(), cmdIterator); cmdIterator = find<typename FamilyType::MI_STORE_REGISTER_MEM *>(++cmdIterator, cmdList.end()); ASSERT_NE(cmdList.end(), cmdIterator); cmdIterator = find<typename FamilyType::MI_STORE_REGISTER_MEM *>(++cmdIterator, cmdList.end()); ASSERT_NE(cmdList.end(), cmdIterator); } HWTEST_F(BcsTests, givenInputAllocationsWhenBlitDispatchedThenMakeAllAllocationsResident) { auto &csr = pDevice->getUltCommandStreamReceiver<FamilyType>(); csr.storeMakeResidentAllocations = true; cl_int retVal = CL_SUCCESS; auto buffer1 = clUniquePtr<Buffer>(Buffer::create(context.get(), CL_MEM_READ_WRITE, 1, nullptr, retVal)); auto buffer2 = clUniquePtr<Buffer>(Buffer::create(context.get(), CL_MEM_READ_WRITE, 1, nullptr, retVal)); void *hostPtr1 = reinterpret_cast<void *>(0x12340000); void *hostPtr2 = reinterpret_cast<void *>(0x43210000); EXPECT_EQ(0u, csr.makeSurfacePackNonResidentCalled); auto graphicsAllocation1 = buffer1->getGraphicsAllocation(pDevice->getRootDeviceIndex()); auto graphicsAllocation2 = buffer2->getGraphicsAllocation(pDevice->getRootDeviceIndex()); auto blitProperties1 = BlitProperties::constructPropertiesForReadWriteBuffer(BlitterConstants::BlitDirection::HostPtrToBuffer, csr, graphicsAllocation1, nullptr, hostPtr1, graphicsAllocation1->getGpuAddress(), 0, 0, 0, {1, 1, 1}, 0, 0, 0, 0); auto blitProperties2 = BlitProperties::constructPropertiesForReadWriteBuffer(BlitterConstants::BlitDirection::HostPtrToBuffer, csr, graphicsAllocation2, nullptr, hostPtr2, graphicsAllocation2->getGpuAddress(), 0, 0, 0, {1, 1, 1}, 0, 0, 0, 0); BlitPropertiesContainer blitPropertiesContainer; blitPropertiesContainer.push_back(blitProperties1); blitPropertiesContainer.push_back(blitProperties2); csr.blitBuffer(blitPropertiesContainer, false, false); EXPECT_TRUE(csr.isMadeResident(graphicsAllocation1)); EXPECT_TRUE(csr.isMadeResident(graphicsAllocation2)); EXPECT_TRUE(csr.isMadeResident(csr.getTagAllocation())); EXPECT_EQ(1u, csr.makeSurfacePackNonResidentCalled); EXPECT_EQ(csr.globalFenceAllocation ? 6u : 5u, csr.makeResidentAllocations.size()); } HWTEST_F(BcsTests, givenFenceAllocationIsRequiredWhenBlitDispatchedThenMakeAllAllocationsResident) { RAIIHwHelperFactory<MockHwHelperWithFenceAllocation<FamilyType>> hwHelperBackup{pDevice->getHardwareInfo().platform.eRenderCoreFamily}; auto bcsOsContext = std::unique_ptr<OsContext>(OsContext::create(nullptr, 0, pDevice->getDeviceBitfield(), aub_stream::ENGINE_BCS, PreemptionMode::Disabled, false, false, false)); auto bcsCsr = std::make_unique<UltCommandStreamReceiver<FamilyType>>(*pDevice->getExecutionEnvironment(), pDevice->getRootDeviceIndex()); bcsCsr->setupContext(*bcsOsContext); bcsCsr->initializeTagAllocation(); bcsCsr->createGlobalFenceAllocation(); bcsCsr->storeMakeResidentAllocations = true; cl_int retVal = CL_SUCCESS; auto buffer1 = clUniquePtr<Buffer>(Buffer::create(context.get(), CL_MEM_READ_WRITE, 1, nullptr, retVal)); auto buffer2 = clUniquePtr<Buffer>(Buffer::create(context.get(), CL_MEM_READ_WRITE, 1, nullptr, retVal)); void *hostPtr1 = reinterpret_cast<void *>(0x12340000); void *hostPtr2 = reinterpret_cast<void *>(0x43210000); EXPECT_EQ(0u, bcsCsr->makeSurfacePackNonResidentCalled); auto graphicsAllocation1 = buffer1->getGraphicsAllocation(pDevice->getRootDeviceIndex()); auto graphicsAllocation2 = buffer2->getGraphicsAllocation(pDevice->getRootDeviceIndex()); auto blitProperties1 = BlitProperties::constructPropertiesForReadWriteBuffer(BlitterConstants::BlitDirection::HostPtrToBuffer, *bcsCsr, graphicsAllocation1, nullptr, hostPtr1, graphicsAllocation1->getGpuAddress(), 0, 0, 0, {1, 1, 1}, 0, 0, 0, 0); auto blitProperties2 = BlitProperties::constructPropertiesForReadWriteBuffer(BlitterConstants::BlitDirection::HostPtrToBuffer, *bcsCsr, graphicsAllocation2, nullptr, hostPtr2, graphicsAllocation2->getGpuAddress(), 0, 0, 0, {1, 1, 1}, 0, 0, 0, 0); BlitPropertiesContainer blitPropertiesContainer; blitPropertiesContainer.push_back(blitProperties1); blitPropertiesContainer.push_back(blitProperties2); bcsCsr->blitBuffer(blitPropertiesContainer, false, false); EXPECT_TRUE(bcsCsr->isMadeResident(graphicsAllocation1)); EXPECT_TRUE(bcsCsr->isMadeResident(graphicsAllocation2)); EXPECT_TRUE(bcsCsr->isMadeResident(bcsCsr->getTagAllocation())); EXPECT_TRUE(bcsCsr->isMadeResident(bcsCsr->globalFenceAllocation)); EXPECT_EQ(1u, bcsCsr->makeSurfacePackNonResidentCalled); EXPECT_EQ(6u, bcsCsr->makeResidentAllocations.size()); } HWTEST_F(BcsTests, givenBufferWhenBlitCalledThenFlushCommandBuffer) { auto &csr = pDevice->getUltCommandStreamReceiver<FamilyType>(); csr.recordFlusheBatchBuffer = true; cl_int retVal = CL_SUCCESS; auto buffer = clUniquePtr<Buffer>(Buffer::create(context.get(), CL_MEM_READ_WRITE, 1, nullptr, retVal)); void *hostPtr = reinterpret_cast<void *>(0x12340000); auto graphicsAllocation = buffer->getGraphicsAllocation(pDevice->getRootDeviceIndex()); auto &commandStream = csr.getCS(MemoryConstants::pageSize); size_t commandStreamOffset = 4; commandStream.getSpace(commandStreamOffset); uint32_t newTaskCount = 17; csr.taskCount = newTaskCount - 1; auto blitProperties = BlitProperties::constructPropertiesForReadWriteBuffer(BlitterConstants::BlitDirection::HostPtrToBuffer, csr, graphicsAllocation, nullptr, hostPtr, graphicsAllocation->getGpuAddress(), 0, 0, 0, {1, 1, 1}, 0, 0, 0, 0); blitBuffer(&csr, blitProperties, true); EXPECT_EQ(commandStream.getGraphicsAllocation(), csr.latestFlushedBatchBuffer.commandBufferAllocation); EXPECT_EQ(commandStreamOffset, csr.latestFlushedBatchBuffer.startOffset); EXPECT_EQ(0u, csr.latestFlushedBatchBuffer.chainedBatchBufferStartOffset); EXPECT_EQ(nullptr, csr.latestFlushedBatchBuffer.chainedBatchBuffer); EXPECT_FALSE(csr.latestFlushedBatchBuffer.requiresCoherency); EXPECT_FALSE(csr.latestFlushedBatchBuffer.low_priority); EXPECT_EQ(QueueThrottle::MEDIUM, csr.latestFlushedBatchBuffer.throttle); EXPECT_EQ(commandStream.getUsed(), csr.latestFlushedBatchBuffer.usedSize); EXPECT_EQ(&commandStream, csr.latestFlushedBatchBuffer.stream); EXPECT_EQ(newTaskCount, csr.latestWaitForCompletionWithTimeoutTaskCount.load()); } HWTEST_F(BcsTests, whenBlitFromHostPtrCalledThenCallWaitWithKmdFallback) { class MyMockCsr : public UltCommandStreamReceiver<FamilyType> { public: using UltCommandStreamReceiver<FamilyType>::UltCommandStreamReceiver; void waitForTaskCountWithKmdNotifyFallback(uint32_t taskCountToWait, FlushStamp flushStampToWait, bool useQuickKmdSleep, bool forcePowerSavingMode) override { waitForTaskCountWithKmdNotifyFallbackCalled++; taskCountToWaitPassed = taskCountToWait; flushStampToWaitPassed = flushStampToWait; useQuickKmdSleepPassed = useQuickKmdSleep; forcePowerSavingModePassed = forcePowerSavingMode; } uint32_t taskCountToWaitPassed = 0; FlushStamp flushStampToWaitPassed = 0; bool useQuickKmdSleepPassed = false; bool forcePowerSavingModePassed = false; uint32_t waitForTaskCountWithKmdNotifyFallbackCalled = 0; }; auto myMockCsr = std::make_unique<::testing::NiceMock<MyMockCsr>>(*pDevice->getExecutionEnvironment(), pDevice->getRootDeviceIndex()); auto &bcsOsContext = pDevice->getUltCommandStreamReceiver<FamilyType>().getOsContext(); myMockCsr->initializeTagAllocation(); myMockCsr->setupContext(bcsOsContext); cl_int retVal = CL_SUCCESS; auto buffer = clUniquePtr<Buffer>(Buffer::create(context.get(), CL_MEM_READ_WRITE, 1, nullptr, retVal)); void *hostPtr = reinterpret_cast<void *>(0x12340000); auto graphicsAllocation = buffer->getGraphicsAllocation(pDevice->getRootDeviceIndex()); auto blitProperties = BlitProperties::constructPropertiesForReadWriteBuffer(BlitterConstants::BlitDirection::HostPtrToBuffer, *myMockCsr, graphicsAllocation, nullptr, hostPtr, graphicsAllocation->getGpuAddress(), 0, 0, 0, {1, 1, 1}, 0, 0, 0, 0); blitBuffer(myMockCsr.get(), blitProperties, false); EXPECT_EQ(0u, myMockCsr->waitForTaskCountWithKmdNotifyFallbackCalled); blitBuffer(myMockCsr.get(), blitProperties, true); EXPECT_EQ(1u, myMockCsr->waitForTaskCountWithKmdNotifyFallbackCalled); EXPECT_EQ(myMockCsr->taskCount, myMockCsr->taskCountToWaitPassed); EXPECT_EQ(myMockCsr->flushStamp->peekStamp(), myMockCsr->flushStampToWaitPassed); EXPECT_FALSE(myMockCsr->useQuickKmdSleepPassed); EXPECT_FALSE(myMockCsr->forcePowerSavingModePassed); } HWTEST_F(BcsTests, whenBlitFromHostPtrCalledThenCleanTemporaryAllocations) { auto &bcsCsr = pDevice->getUltCommandStreamReceiver<FamilyType>(); auto mockInternalAllocationsStorage = new MockInternalAllocationStorage(bcsCsr); bcsCsr.internalAllocationStorage.reset(mockInternalAllocationsStorage); cl_int retVal = CL_SUCCESS; auto buffer = clUniquePtr<Buffer>(Buffer::create(context.get(), CL_MEM_READ_WRITE, 1, nullptr, retVal)); void *hostPtr = reinterpret_cast<void *>(0x12340000); auto graphicsAllocation = buffer->getGraphicsAllocation(pDevice->getRootDeviceIndex()); bcsCsr.taskCount = 17; EXPECT_EQ(0u, mockInternalAllocationsStorage->cleanAllocationsCalled); auto blitProperties = BlitProperties::constructPropertiesForReadWriteBuffer(BlitterConstants::BlitDirection::HostPtrToBuffer, bcsCsr, graphicsAllocation, nullptr, hostPtr, graphicsAllocation->getGpuAddress(), 0, 0, 0, {1, 1, 1}, 0, 0, 0, 0); blitBuffer(&bcsCsr, blitProperties, false); EXPECT_EQ(0u, mockInternalAllocationsStorage->cleanAllocationsCalled); blitBuffer(&bcsCsr, blitProperties, true); EXPECT_EQ(1u, mockInternalAllocationsStorage->cleanAllocationsCalled); EXPECT_EQ(bcsCsr.taskCount, mockInternalAllocationsStorage->lastCleanAllocationsTaskCount); EXPECT_TRUE(TEMPORARY_ALLOCATION == mockInternalAllocationsStorage->lastCleanAllocationUsage); } HWTEST_F(BcsTests, givenBufferWhenBlitOperationCalledThenProgramCorrectGpuAddresses) { auto &csr = pDevice->getUltCommandStreamReceiver<FamilyType>(); cl_int retVal = CL_SUCCESS; auto buffer1 = clUniquePtr<Buffer>(Buffer::create(context.get(), CL_MEM_READ_WRITE, 100, nullptr, retVal)); auto buffer2 = clUniquePtr<Buffer>(Buffer::create(context.get(), CL_MEM_READ_WRITE, 100, nullptr, retVal)); auto graphicsAllocation1 = buffer1->getGraphicsAllocation(pDevice->getRootDeviceIndex()); auto graphicsAllocation2 = buffer2->getGraphicsAllocation(pDevice->getRootDeviceIndex()); void *hostPtr = reinterpret_cast<void *>(0x12340000); const size_t hostPtrOffset = 0x1234; const size_t subBuffer1Offset = 0x23; cl_buffer_region subBufferRegion1 = {subBuffer1Offset, 1}; auto subBuffer1 = clUniquePtr<Buffer>(buffer1->createSubBuffer(CL_MEM_READ_WRITE, 0, &subBufferRegion1, retVal)); Vec3<size_t> copySizes[2] = {{1, 1, 1}, {1, 2, 1}}; EXPECT_FALSE(BlitCommandsHelper<FamilyType>::isCopyRegionPreferred(copySizes[0], pDevice->getRootDeviceEnvironment())); EXPECT_TRUE(BlitCommandsHelper<FamilyType>::isCopyRegionPreferred(copySizes[1], pDevice->getRootDeviceEnvironment())); for (auto &copySize : copySizes) { { // from hostPtr HardwareParse hwParser; auto blitProperties = BlitProperties::constructPropertiesForReadWriteBuffer(BlitterConstants::BlitDirection::HostPtrToBuffer, csr, graphicsAllocation1, nullptr, hostPtr, graphicsAllocation1->getGpuAddress() + subBuffer1->getOffset(), 0, {hostPtrOffset, 0, 0}, 0, copySize, 0, 0, 0, 0); blitBuffer(&csr, blitProperties, true); hwParser.parseCommands<FamilyType>(csr.commandStream); auto cmdIterator = find<typename FamilyType::XY_COPY_BLT *>(hwParser.cmdList.begin(), hwParser.cmdList.end()); ASSERT_NE(hwParser.cmdList.end(), cmdIterator); auto bltCmd = genCmdCast<typename FamilyType::XY_COPY_BLT *>(*cmdIterator); ASSERT_NE(nullptr, bltCmd); if (pDevice->isFullRangeSvm()) { EXPECT_EQ(reinterpret_cast<uint64_t>(ptrOffset(hostPtr, hostPtrOffset)), bltCmd->getSourceBaseAddress()); } EXPECT_EQ(graphicsAllocation1->getGpuAddress() + subBuffer1Offset, bltCmd->getDestinationBaseAddress()); } { // to hostPtr HardwareParse hwParser; auto offset = csr.commandStream.getUsed(); auto blitProperties = BlitProperties::constructPropertiesForReadWriteBuffer(BlitterConstants::BlitDirection::BufferToHostPtr, csr, graphicsAllocation1, nullptr, hostPtr, graphicsAllocation1->getGpuAddress() + subBuffer1->getOffset(), 0, {hostPtrOffset, 0, 0}, 0, copySize, 0, 0, 0, 0); blitBuffer(&csr, blitProperties, true); hwParser.parseCommands<FamilyType>(csr.commandStream, offset); auto cmdIterator = find<typename FamilyType::XY_COPY_BLT *>(hwParser.cmdList.begin(), hwParser.cmdList.end()); ASSERT_NE(hwParser.cmdList.end(), cmdIterator); auto bltCmd = genCmdCast<typename FamilyType::XY_COPY_BLT *>(*cmdIterator); ASSERT_NE(nullptr, bltCmd); if (pDevice->isFullRangeSvm()) { EXPECT_EQ(reinterpret_cast<uint64_t>(ptrOffset(hostPtr, hostPtrOffset)), bltCmd->getDestinationBaseAddress()); } EXPECT_EQ(graphicsAllocation1->getGpuAddress() + subBuffer1Offset, bltCmd->getSourceBaseAddress()); } { // Buffer to Buffer HardwareParse hwParser; auto offset = csr.commandStream.getUsed(); auto blitProperties = BlitProperties::constructPropertiesForCopyBuffer(graphicsAllocation1, graphicsAllocation2, 0, 0, copySize, 0, 0, 0, 0); blitBuffer(&csr, blitProperties, true); hwParser.parseCommands<FamilyType>(csr.commandStream, offset); auto cmdIterator = find<typename FamilyType::XY_COPY_BLT *>(hwParser.cmdList.begin(), hwParser.cmdList.end()); ASSERT_NE(hwParser.cmdList.end(), cmdIterator); auto bltCmd = genCmdCast<typename FamilyType::XY_COPY_BLT *>(*cmdIterator); ASSERT_NE(nullptr, bltCmd); EXPECT_EQ(graphicsAllocation1->getGpuAddress(), bltCmd->getDestinationBaseAddress()); EXPECT_EQ(graphicsAllocation2->getGpuAddress(), bltCmd->getSourceBaseAddress()); } { // Buffer to Buffer - with object offset const size_t subBuffer2Offset = 0x20; cl_buffer_region subBufferRegion2 = {subBuffer2Offset, 1}; auto subBuffer2 = clUniquePtr<Buffer>(buffer2->createSubBuffer(CL_MEM_READ_WRITE, 0, &subBufferRegion2, retVal)); BuiltinOpParams builtinOpParams = {}; builtinOpParams.dstMemObj = subBuffer2.get(); builtinOpParams.srcMemObj = subBuffer1.get(); builtinOpParams.size.x = copySize.x; builtinOpParams.size.y = copySize.y; auto blitProperties = ClBlitProperties::constructProperties(BlitterConstants::BlitDirection::BufferToBuffer, csr, builtinOpParams); auto offset = csr.commandStream.getUsed(); blitBuffer(&csr, blitProperties, true); HardwareParse hwParser; hwParser.parseCommands<FamilyType>(csr.commandStream, offset); auto cmdIterator = find<typename FamilyType::XY_COPY_BLT *>(hwParser.cmdList.begin(), hwParser.cmdList.end()); ASSERT_NE(hwParser.cmdList.end(), cmdIterator); auto bltCmd = genCmdCast<typename FamilyType::XY_COPY_BLT *>(*cmdIterator); EXPECT_NE(nullptr, bltCmd); EXPECT_EQ(graphicsAllocation2->getGpuAddress() + subBuffer2Offset, bltCmd->getDestinationBaseAddress()); EXPECT_EQ(graphicsAllocation1->getGpuAddress() + subBuffer1Offset, bltCmd->getSourceBaseAddress()); } } } HWTEST_F(BcsTests, givenMapAllocationWhenDispatchReadWriteOperationThenSetValidGpuAddress) { auto &csr = pDevice->getUltCommandStreamReceiver<FamilyType>(); auto memoryManager = csr.getMemoryManager(); AllocationProperties properties{csr.getRootDeviceIndex(), false, 1234, GraphicsAllocation::AllocationType::MAP_ALLOCATION, false, pDevice->getDeviceBitfield()}; GraphicsAllocation *mapAllocation = memoryManager->allocateGraphicsMemoryWithProperties(properties, reinterpret_cast<void *>(0x12340000)); auto mapAllocationOffset = 0x1234; auto mapPtr = reinterpret_cast<void *>(mapAllocation->getGpuAddress() + mapAllocationOffset); cl_int retVal = CL_SUCCESS; auto buffer = clUniquePtr<Buffer>(Buffer::create(context.get(), CL_MEM_READ_WRITE, 100, nullptr, retVal)); auto graphicsAllocation = buffer->getGraphicsAllocation(pDevice->getRootDeviceIndex()); const size_t hostPtrOffset = 0x1234; Vec3<size_t> copySizes[2] = {{4, 1, 1}, {4, 2, 1}}; EXPECT_FALSE(BlitCommandsHelper<FamilyType>::isCopyRegionPreferred(copySizes[0], pDevice->getRootDeviceEnvironment())); EXPECT_TRUE(BlitCommandsHelper<FamilyType>::isCopyRegionPreferred(copySizes[1], pDevice->getRootDeviceEnvironment())); for (auto &copySize : copySizes) { { // from hostPtr HardwareParse hwParser; auto blitProperties = BlitProperties::constructPropertiesForReadWriteBuffer(BlitterConstants::BlitDirection::HostPtrToBuffer, csr, graphicsAllocation, mapAllocation, mapPtr, graphicsAllocation->getGpuAddress(), castToUint64(mapPtr), {hostPtrOffset, 0, 0}, 0, copySize, 0, 0, 0, 0); blitBuffer(&csr, blitProperties, true); hwParser.parseCommands<FamilyType>(csr.commandStream); auto cmdIterator = find<typename FamilyType::XY_COPY_BLT *>(hwParser.cmdList.begin(), hwParser.cmdList.end()); ASSERT_NE(hwParser.cmdList.end(), cmdIterator); auto bltCmd = genCmdCast<typename FamilyType::XY_COPY_BLT *>(*cmdIterator); EXPECT_NE(nullptr, bltCmd); if (pDevice->isFullRangeSvm()) { EXPECT_EQ(reinterpret_cast<uint64_t>(ptrOffset(mapPtr, hostPtrOffset)), bltCmd->getSourceBaseAddress()); } EXPECT_EQ(graphicsAllocation->getGpuAddress(), bltCmd->getDestinationBaseAddress()); } { // to hostPtr HardwareParse hwParser; auto offset = csr.commandStream.getUsed(); auto blitProperties = BlitProperties::constructPropertiesForReadWriteBuffer(BlitterConstants::BlitDirection::BufferToHostPtr, csr, graphicsAllocation, mapAllocation, mapPtr, graphicsAllocation->getGpuAddress(), castToUint64(mapPtr), {hostPtrOffset, 0, 0}, 0, copySize, 0, 0, 0, 0); blitBuffer(&csr, blitProperties, true); hwParser.parseCommands<FamilyType>(csr.commandStream, offset); auto cmdIterator = find<typename FamilyType::XY_COPY_BLT *>(hwParser.cmdList.begin(), hwParser.cmdList.end()); ASSERT_NE(hwParser.cmdList.end(), cmdIterator); auto bltCmd = genCmdCast<typename FamilyType::XY_COPY_BLT *>(*cmdIterator); EXPECT_NE(nullptr, bltCmd); if (pDevice->isFullRangeSvm()) { EXPECT_EQ(reinterpret_cast<uint64_t>(ptrOffset(mapPtr, hostPtrOffset)), bltCmd->getDestinationBaseAddress()); } EXPECT_EQ(graphicsAllocation->getGpuAddress(), bltCmd->getSourceBaseAddress()); } { // bufferRect to hostPtr HardwareParse hwParser; auto offset = csr.commandStream.getUsed(); auto copySize = Vec3<size_t>(4, 2, 1); auto blitProperties = BlitProperties::constructPropertiesForReadWriteBuffer(BlitterConstants::BlitDirection::BufferToHostPtr, csr, graphicsAllocation, mapAllocation, mapPtr, graphicsAllocation->getGpuAddress(), castToUint64(mapPtr), {hostPtrOffset, 0, 0}, 0, copySize, 0, 0, 0, 0); blitBuffer(&csr, blitProperties, true); hwParser.parseCommands<FamilyType>(csr.commandStream, offset); auto cmdIterator = find<typename FamilyType::XY_COPY_BLT *>(hwParser.cmdList.begin(), hwParser.cmdList.end()); ASSERT_NE(hwParser.cmdList.end(), cmdIterator); auto bltCmd = genCmdCast<typename FamilyType::XY_COPY_BLT *>(*cmdIterator); EXPECT_NE(nullptr, bltCmd); if (pDevice->isFullRangeSvm()) { EXPECT_EQ(reinterpret_cast<uint64_t>(ptrOffset(mapPtr, hostPtrOffset)), bltCmd->getDestinationBaseAddress()); } EXPECT_EQ(graphicsAllocation->getGpuAddress(), bltCmd->getSourceBaseAddress()); } { // bufferWrite from hostPtr HardwareParse hwParser; auto blitProperties = BlitProperties::constructPropertiesForReadWriteBuffer(BlitterConstants::BlitDirection::HostPtrToBuffer, csr, graphicsAllocation, mapAllocation, mapPtr, graphicsAllocation->getGpuAddress(), castToUint64(mapPtr), {hostPtrOffset, 0, 0}, 0, copySize, 0, 0, 0, 0); blitBuffer(&csr, blitProperties, true); hwParser.parseCommands<FamilyType>(csr.commandStream); auto cmdIterator = find<typename FamilyType::XY_COPY_BLT *>(hwParser.cmdList.begin(), hwParser.cmdList.end()); ASSERT_NE(hwParser.cmdList.end(), cmdIterator); auto bltCmd = genCmdCast<typename FamilyType::XY_COPY_BLT *>(*cmdIterator); EXPECT_NE(nullptr, bltCmd); if (pDevice->isFullRangeSvm()) { EXPECT_EQ(reinterpret_cast<uint64_t>(ptrOffset(mapPtr, hostPtrOffset)), bltCmd->getSourceBaseAddress()); } EXPECT_EQ(graphicsAllocation->getGpuAddress(), bltCmd->getDestinationBaseAddress()); } } memoryManager->freeGraphicsMemory(mapAllocation); } HWTEST_F(BcsTests, givenMapAllocationInBuiltinOpParamsWhenConstructingThenUseItAsSourceOrDstAllocation) { auto &csr = pDevice->getUltCommandStreamReceiver<FamilyType>(); auto memoryManager = csr.getMemoryManager(); AllocationProperties properties{csr.getRootDeviceIndex(), false, 1234, GraphicsAllocation::AllocationType::MAP_ALLOCATION, false, pDevice->getDeviceBitfield()}; GraphicsAllocation *mapAllocation = memoryManager->allocateGraphicsMemoryWithProperties(properties, reinterpret_cast<void *>(0x12340000)); auto mapAllocationOffset = 0x1234; auto mapPtr = reinterpret_cast<void *>(mapAllocation->getGpuAddress() + mapAllocationOffset); cl_int retVal = CL_SUCCESS; auto buffer = clUniquePtr<Buffer>(Buffer::create(context.get(), CL_MEM_READ_WRITE, 100, nullptr, retVal)); { // from hostPtr BuiltinOpParams builtinOpParams = {}; builtinOpParams.dstMemObj = buffer.get(); builtinOpParams.srcPtr = mapPtr; builtinOpParams.size = {1, 1, 1}; builtinOpParams.transferAllocation = mapAllocation; auto blitProperties = ClBlitProperties::constructProperties(BlitterConstants::BlitDirection::HostPtrToBuffer, csr, builtinOpParams); EXPECT_EQ(mapAllocation, blitProperties.srcAllocation); } { // to hostPtr BuiltinOpParams builtinOpParams = {}; builtinOpParams.srcMemObj = buffer.get(); builtinOpParams.dstPtr = mapPtr; builtinOpParams.size = {1, 1, 1}; builtinOpParams.transferAllocation = mapAllocation; auto blitProperties = ClBlitProperties::constructProperties(BlitterConstants::BlitDirection::BufferToHostPtr, csr, builtinOpParams); EXPECT_EQ(mapAllocation, blitProperties.dstAllocation); } memoryManager->freeGraphicsMemory(mapAllocation); } HWTEST_F(BcsTests, givenNonZeroCopySvmAllocationWhenConstructingBlitPropertiesForReadWriteBufferCallThenSetValidAllocations) { auto &csr = pDevice->getUltCommandStreamReceiver<FamilyType>(); MockMemoryManager mockMemoryManager(true, true); SVMAllocsManager svmAllocsManager(&mockMemoryManager); auto svmAllocationProperties = MemObjHelper::getSvmAllocationProperties(CL_MEM_READ_WRITE); auto svmAlloc = svmAllocsManager.createSVMAlloc(csr.getRootDeviceIndex(), 1, svmAllocationProperties, pDevice->getDeviceBitfield()); auto svmData = svmAllocsManager.getSVMAlloc(svmAlloc); auto gpuAllocation = svmData->gpuAllocations.getGraphicsAllocation(pDevice->getRootDeviceIndex()); EXPECT_NE(nullptr, gpuAllocation); EXPECT_NE(nullptr, svmData->cpuAllocation); EXPECT_NE(gpuAllocation, svmData->cpuAllocation); { // from hostPtr BuiltinOpParams builtinOpParams = {}; builtinOpParams.dstSvmAlloc = gpuAllocation; builtinOpParams.srcSvmAlloc = svmData->cpuAllocation; builtinOpParams.srcPtr = reinterpret_cast<void *>(svmData->cpuAllocation->getGpuAddress()); builtinOpParams.size = {1, 1, 1}; auto blitProperties = ClBlitProperties::constructProperties(BlitterConstants::BlitDirection::HostPtrToBuffer, csr, builtinOpParams); EXPECT_EQ(svmData->cpuAllocation, blitProperties.srcAllocation); EXPECT_EQ(gpuAllocation, blitProperties.dstAllocation); } { // to hostPtr BuiltinOpParams builtinOpParams = {}; builtinOpParams.srcSvmAlloc = gpuAllocation; builtinOpParams.dstSvmAlloc = svmData->cpuAllocation; builtinOpParams.dstPtr = reinterpret_cast<void *>(svmData->cpuAllocation->getGpuAddress()); builtinOpParams.size = {1, 1, 1}; auto blitProperties = ClBlitProperties::constructProperties(BlitterConstants::BlitDirection::BufferToHostPtr, csr, builtinOpParams); EXPECT_EQ(svmData->cpuAllocation, blitProperties.dstAllocation); EXPECT_EQ(gpuAllocation, blitProperties.srcAllocation); } svmAllocsManager.freeSVMAlloc(svmAlloc); } HWTEST_F(BcsTests, givenSvmAllocationWhenBlitCalledThenUsePassedPointers) { auto &csr = pDevice->getUltCommandStreamReceiver<FamilyType>(); MockMemoryManager mockMemoryManager(true, true); SVMAllocsManager svmAllocsManager(&mockMemoryManager); auto svmAllocationProperties = MemObjHelper::getSvmAllocationProperties(CL_MEM_READ_WRITE); auto svmAlloc = svmAllocsManager.createSVMAlloc(csr.getRootDeviceIndex(), 1, svmAllocationProperties, pDevice->getDeviceBitfield()); auto svmData = svmAllocsManager.getSVMAlloc(svmAlloc); auto gpuAllocation = svmData->gpuAllocations.getGraphicsAllocation(pDevice->getRootDeviceIndex()); EXPECT_NE(nullptr, gpuAllocation); EXPECT_NE(nullptr, svmData->cpuAllocation); EXPECT_NE(gpuAllocation, svmData->cpuAllocation); uint64_t srcOffset = 2; uint64_t dstOffset = 3; Vec3<size_t> copySizes[2] = {{1, 1, 1}, {1, 2, 1}}; for (auto &copySize : copySizes) { { // from hostPtr BuiltinOpParams builtinOpParams = {}; builtinOpParams.dstSvmAlloc = svmData->cpuAllocation; builtinOpParams.srcSvmAlloc = gpuAllocation; builtinOpParams.srcPtr = reinterpret_cast<void *>(svmData->cpuAllocation->getGpuAddress() + srcOffset); builtinOpParams.dstPtr = reinterpret_cast<void *>(svmData->cpuAllocation->getGpuAddress() + dstOffset); builtinOpParams.size = copySize; auto blitProperties = ClBlitProperties::constructProperties(BlitterConstants::BlitDirection::HostPtrToBuffer, csr, builtinOpParams); EXPECT_EQ(gpuAllocation, blitProperties.srcAllocation); EXPECT_EQ(svmData->cpuAllocation, blitProperties.dstAllocation); blitBuffer(&csr, blitProperties, true); HardwareParse hwParser; hwParser.parseCommands<FamilyType>(csr.commandStream, 0); auto cmdIterator = find<typename FamilyType::XY_COPY_BLT *>(hwParser.cmdList.begin(), hwParser.cmdList.end()); ASSERT_NE(hwParser.cmdList.end(), cmdIterator); auto bltCmd = genCmdCast<typename FamilyType::XY_COPY_BLT *>(*cmdIterator); EXPECT_EQ(castToUint64(builtinOpParams.dstPtr), bltCmd->getDestinationBaseAddress()); EXPECT_EQ(castToUint64(builtinOpParams.srcPtr), bltCmd->getSourceBaseAddress()); } { // to hostPtr BuiltinOpParams builtinOpParams = {}; builtinOpParams.srcSvmAlloc = gpuAllocation; builtinOpParams.dstSvmAlloc = svmData->cpuAllocation; builtinOpParams.dstPtr = reinterpret_cast<void *>(svmData->cpuAllocation + dstOffset); builtinOpParams.srcPtr = reinterpret_cast<void *>(gpuAllocation + srcOffset); builtinOpParams.size = copySize; auto blitProperties = ClBlitProperties::constructProperties(BlitterConstants::BlitDirection::BufferToHostPtr, csr, builtinOpParams); auto offset = csr.commandStream.getUsed(); blitBuffer(&csr, blitProperties, true); HardwareParse hwParser; hwParser.parseCommands<FamilyType>(csr.commandStream, offset); auto cmdIterator = find<typename FamilyType::XY_COPY_BLT *>(hwParser.cmdList.begin(), hwParser.cmdList.end()); ASSERT_NE(hwParser.cmdList.end(), cmdIterator); auto bltCmd = genCmdCast<typename FamilyType::XY_COPY_BLT *>(*cmdIterator); EXPECT_EQ(castToUint64(builtinOpParams.dstPtr), bltCmd->getDestinationBaseAddress()); EXPECT_EQ(castToUint64(builtinOpParams.srcPtr), bltCmd->getSourceBaseAddress()); } } svmAllocsManager.freeSVMAlloc(svmAlloc); } HWTEST_F(BcsTests, givenBufferWithOffsetWhenBlitOperationCalledThenProgramCorrectGpuAddresses) { auto &csr = pDevice->getUltCommandStreamReceiver<FamilyType>(); cl_int retVal = CL_SUCCESS; auto buffer1 = clUniquePtr<Buffer>(Buffer::create(context.get(), CL_MEM_READ_WRITE, 1, nullptr, retVal)); auto buffer2 = clUniquePtr<Buffer>(Buffer::create(context.get(), CL_MEM_READ_WRITE, 1, nullptr, retVal)); void *hostPtr = reinterpret_cast<void *>(0x12340000); auto graphicsAllocation1 = buffer1->getGraphicsAllocation(pDevice->getRootDeviceIndex()); auto graphicsAllocation2 = buffer2->getGraphicsAllocation(pDevice->getRootDeviceIndex()); size_t addressOffsets[] = {0, 1, 1234}; Vec3<size_t> copySizes[2] = {{1, 1, 1}, {1, 2, 1}}; for (auto &copySize : copySizes) { for (auto buffer1Offset : addressOffsets) { { // from hostPtr HardwareParse hwParser; auto offset = csr.commandStream.getUsed(); auto blitProperties = BlitProperties::constructPropertiesForReadWriteBuffer(BlitterConstants::BlitDirection::HostPtrToBuffer, csr, graphicsAllocation1, nullptr, hostPtr, graphicsAllocation1->getGpuAddress(), 0, 0, {buffer1Offset, 0, 0}, copySize, 0, 0, 0, 0); blitBuffer(&csr, blitProperties, true); hwParser.parseCommands<FamilyType>(csr.commandStream, offset); auto cmdIterator = find<typename FamilyType::XY_COPY_BLT *>(hwParser.cmdList.begin(), hwParser.cmdList.end()); ASSERT_NE(hwParser.cmdList.end(), cmdIterator); auto bltCmd = genCmdCast<typename FamilyType::XY_COPY_BLT *>(*cmdIterator); EXPECT_NE(nullptr, bltCmd); if (pDevice->isFullRangeSvm()) { EXPECT_EQ(reinterpret_cast<uint64_t>(hostPtr), bltCmd->getSourceBaseAddress()); } EXPECT_EQ(ptrOffset(graphicsAllocation1->getGpuAddress(), buffer1Offset), bltCmd->getDestinationBaseAddress()); } { // to hostPtr HardwareParse hwParser; auto offset = csr.commandStream.getUsed(); auto blitProperties = BlitProperties::constructPropertiesForReadWriteBuffer(BlitterConstants::BlitDirection::BufferToHostPtr, csr, graphicsAllocation1, nullptr, hostPtr, graphicsAllocation1->getGpuAddress(), 0, 0, {buffer1Offset, 0, 0}, copySize, 0, 0, 0, 0); blitBuffer(&csr, blitProperties, true); hwParser.parseCommands<FamilyType>(csr.commandStream, offset); auto cmdIterator = find<typename FamilyType::XY_COPY_BLT *>(hwParser.cmdList.begin(), hwParser.cmdList.end()); ASSERT_NE(hwParser.cmdList.end(), cmdIterator); auto bltCmd = genCmdCast<typename FamilyType::XY_COPY_BLT *>(*cmdIterator); EXPECT_NE(nullptr, bltCmd); if (pDevice->isFullRangeSvm()) { EXPECT_EQ(reinterpret_cast<uint64_t>(hostPtr), bltCmd->getDestinationBaseAddress()); } EXPECT_EQ(ptrOffset(graphicsAllocation1->getGpuAddress(), buffer1Offset), bltCmd->getSourceBaseAddress()); } for (auto buffer2Offset : addressOffsets) { // Buffer to Buffer HardwareParse hwParser; auto offset = csr.commandStream.getUsed(); auto blitProperties = BlitProperties::constructPropertiesForCopyBuffer(graphicsAllocation1, graphicsAllocation2, {buffer1Offset, 0, 0}, {buffer2Offset, 0, 0}, copySize, 0, 0, 0, 0); blitBuffer(&csr, blitProperties, true); hwParser.parseCommands<FamilyType>(csr.commandStream, offset); auto cmdIterator = find<typename FamilyType::XY_COPY_BLT *>(hwParser.cmdList.begin(), hwParser.cmdList.end()); ASSERT_NE(hwParser.cmdList.end(), cmdIterator); auto bltCmd = genCmdCast<typename FamilyType::XY_COPY_BLT *>(*cmdIterator); EXPECT_NE(nullptr, bltCmd); EXPECT_EQ(ptrOffset(graphicsAllocation1->getGpuAddress(), buffer1Offset), bltCmd->getDestinationBaseAddress()); EXPECT_EQ(ptrOffset(graphicsAllocation2->getGpuAddress(), buffer2Offset), bltCmd->getSourceBaseAddress()); } } } } HWTEST_F(BcsTests, givenBufferWithBigSizesWhenBlitOperationCalledThenProgramCorrectGpuAddresses) { auto &rootDeviceEnvironment = pDevice->getRootDeviceEnvironment(); auto maxWidthToCopy = static_cast<size_t>(BlitCommandsHelper<FamilyType>::getMaxBlitWidth(rootDeviceEnvironment)); auto maxHeightToCopy = static_cast<size_t>(BlitCommandsHelper<FamilyType>::getMaxBlitHeight(rootDeviceEnvironment)); auto &csr = pDevice->getUltCommandStreamReceiver<FamilyType>(); cl_int retVal = CL_SUCCESS; auto buffer1 = clUniquePtr<Buffer>(Buffer::create(context.get(), CL_MEM_READ_WRITE, 1, nullptr, retVal)); auto buffer2 = clUniquePtr<Buffer>(Buffer::create(context.get(), CL_MEM_READ_WRITE, 1, nullptr, retVal)); void *hostPtr = reinterpret_cast<void *>(0x12340000); auto graphicsAllocation = buffer1->getGraphicsAllocation(pDevice->getRootDeviceIndex()); size_t srcOrigin[] = {1, 2, 0}; size_t dstOrigin[] = {4, 3, 1}; size_t region[] = {maxWidthToCopy + 16, maxHeightToCopy + 16, 2}; size_t srcRowPitch = region[0] + 34; size_t srcSlicePitch = srcRowPitch * region[1] + 36; size_t dstRowPitch = region[0] + 40; size_t dstSlicePitch = dstRowPitch * region[1] + 44; auto srcAddressOffset = srcOrigin[0] + (srcOrigin[1] * srcRowPitch) + (srcOrigin[2] * srcSlicePitch); auto dstAddressOffset = dstOrigin[0] + (dstOrigin[1] * dstRowPitch) + (dstOrigin[2] * dstSlicePitch); EXPECT_TRUE(BlitCommandsHelper<FamilyType>::isCopyRegionPreferred(region, rootDeviceEnvironment)); // from hostPtr HardwareParse hwParser; auto offset = csr.commandStream.getUsed(); auto blitProperties = BlitProperties::constructPropertiesForReadWriteBuffer(BlitterConstants::BlitDirection::HostPtrToBuffer, csr, graphicsAllocation, nullptr, hostPtr, graphicsAllocation->getGpuAddress(), 0, srcOrigin, dstOrigin, region, srcRowPitch, srcSlicePitch, dstRowPitch, dstSlicePitch); blitBuffer(&csr, blitProperties, true); hwParser.parseCommands<FamilyType>(csr.commandStream, offset); //1st rectangle xCopy = maxWidthToCopy, yCopy = maxHeightToCopy, zCopy = 1 auto cmdIterator = find<typename FamilyType::XY_COPY_BLT *>(hwParser.cmdList.begin(), hwParser.cmdList.end()); ASSERT_NE(hwParser.cmdList.end(), cmdIterator); auto bltCmd = genCmdCast<typename FamilyType::XY_COPY_BLT *>(*cmdIterator); EXPECT_NE(nullptr, bltCmd); if (pDevice->isFullRangeSvm()) { EXPECT_EQ(ptrOffset(reinterpret_cast<uint64_t>(hostPtr), srcAddressOffset), bltCmd->getSourceBaseAddress()); } EXPECT_EQ(ptrOffset(graphicsAllocation->getGpuAddress(), dstAddressOffset), bltCmd->getDestinationBaseAddress()); srcAddressOffset += maxWidthToCopy; dstAddressOffset += maxWidthToCopy; // 2nd rectangle xCopy = (region[0] - maxWidthToCopy), yCopy = (region[0] - maxHeightToCopy), zCopy = 1 cmdIterator = find<typename FamilyType::XY_COPY_BLT *>(++cmdIterator, hwParser.cmdList.end()); ASSERT_NE(hwParser.cmdList.end(), cmdIterator); bltCmd = genCmdCast<typename FamilyType::XY_COPY_BLT *>(*cmdIterator); EXPECT_NE(nullptr, bltCmd); if (pDevice->isFullRangeSvm()) { EXPECT_EQ(ptrOffset(reinterpret_cast<uint64_t>(hostPtr), srcAddressOffset), bltCmd->getSourceBaseAddress()); } EXPECT_EQ(ptrOffset(graphicsAllocation->getGpuAddress(), dstAddressOffset), bltCmd->getDestinationBaseAddress()); srcAddressOffset += (region[0] - maxWidthToCopy); srcAddressOffset += (srcRowPitch - region[0]); srcAddressOffset += (srcRowPitch * (maxHeightToCopy - 1)); dstAddressOffset += (region[0] - maxWidthToCopy); dstAddressOffset += (dstRowPitch - region[0]); dstAddressOffset += (dstRowPitch * (maxHeightToCopy - 1)); // 3rd rectangle xCopy = maxWidthToCopy, yCopy = maxHeightToCopy, zCopy = 1 cmdIterator = find<typename FamilyType::XY_COPY_BLT *>(++cmdIterator, hwParser.cmdList.end()); ASSERT_NE(hwParser.cmdList.end(), cmdIterator); bltCmd = genCmdCast<typename FamilyType::XY_COPY_BLT *>(*cmdIterator); EXPECT_NE(nullptr, bltCmd); if (pDevice->isFullRangeSvm()) { EXPECT_EQ(ptrOffset(reinterpret_cast<uint64_t>(hostPtr), srcAddressOffset), bltCmd->getSourceBaseAddress()); } EXPECT_EQ(ptrOffset(graphicsAllocation->getGpuAddress(), dstAddressOffset), bltCmd->getDestinationBaseAddress()); srcAddressOffset += maxWidthToCopy; dstAddressOffset += maxWidthToCopy; //4th rectangle xCopy = (region[0] - maxWidthToCopy), yCopy = (region[0] - maxHeightToCopy), zCopy = 1 cmdIterator = find<typename FamilyType::XY_COPY_BLT *>(++cmdIterator, hwParser.cmdList.end()); ASSERT_NE(hwParser.cmdList.end(), cmdIterator); bltCmd = genCmdCast<typename FamilyType::XY_COPY_BLT *>(*cmdIterator); EXPECT_NE(nullptr, bltCmd); if (pDevice->isFullRangeSvm()) { EXPECT_EQ(ptrOffset(reinterpret_cast<uint64_t>(hostPtr), srcAddressOffset), bltCmd->getSourceBaseAddress()); } EXPECT_EQ(ptrOffset(graphicsAllocation->getGpuAddress(), dstAddressOffset), bltCmd->getDestinationBaseAddress()); srcAddressOffset += (region[0] - maxWidthToCopy); srcAddressOffset += (srcRowPitch - region[0]); srcAddressOffset += (srcRowPitch * (region[1] - maxHeightToCopy - 1)); srcAddressOffset += (srcSlicePitch - (srcRowPitch * region[1])); dstAddressOffset += (region[0] - maxWidthToCopy); dstAddressOffset += (dstRowPitch - region[0]); dstAddressOffset += (dstRowPitch * (region[1] - maxHeightToCopy - 1)); dstAddressOffset += (dstSlicePitch - (dstRowPitch * region[1])); //5th rectangle xCopy = maxWidthToCopy, yCopy = maxHeightToCopy, zCopy = 1 cmdIterator = find<typename FamilyType::XY_COPY_BLT *>(++cmdIterator, hwParser.cmdList.end()); ASSERT_NE(hwParser.cmdList.end(), cmdIterator); bltCmd = genCmdCast<typename FamilyType::XY_COPY_BLT *>(*cmdIterator); EXPECT_NE(nullptr, bltCmd); if (pDevice->isFullRangeSvm()) { EXPECT_EQ(ptrOffset(reinterpret_cast<uint64_t>(hostPtr), srcAddressOffset), bltCmd->getSourceBaseAddress()); } EXPECT_EQ(ptrOffset(graphicsAllocation->getGpuAddress(), dstAddressOffset), bltCmd->getDestinationBaseAddress()); } HWTEST_F(BcsTests, givenAuxTranslationRequestWhenBlitCalledThenProgramCommandCorrectly) { auto &csr = pDevice->getUltCommandStreamReceiver<FamilyType>(); cl_int retVal = CL_SUCCESS; auto buffer = clUniquePtr<Buffer>(Buffer::create(context.get(), CL_MEM_READ_WRITE, 123, nullptr, retVal)); auto graphicsAllocation = buffer->getGraphicsAllocation(pDevice->getRootDeviceIndex()); auto allocationGpuAddress = graphicsAllocation->getGpuAddress(); auto allocationSize = graphicsAllocation->getUnderlyingBufferSize(); AuxTranslationDirection translationDirection[] = {AuxTranslationDirection::AuxToNonAux, AuxTranslationDirection::NonAuxToAux}; for (int i = 0; i < 2; i++) { auto blitProperties = BlitProperties::constructPropertiesForAuxTranslation(translationDirection[i], graphicsAllocation); auto offset = csr.commandStream.getUsed(); blitBuffer(&csr, blitProperties, false); HardwareParse hwParser; hwParser.parseCommands<FamilyType>(csr.commandStream, offset); uint32_t xyCopyBltCmdFound = 0; for (auto &cmd : hwParser.cmdList) { if (auto bltCmd = genCmdCast<typename FamilyType::XY_COPY_BLT *>(cmd)) { xyCopyBltCmdFound++; EXPECT_EQ(static_cast<uint32_t>(allocationSize), bltCmd->getTransferWidth()); EXPECT_EQ(1u, bltCmd->getTransferHeight()); EXPECT_EQ(allocationGpuAddress, bltCmd->getDestinationBaseAddress()); EXPECT_EQ(allocationGpuAddress, bltCmd->getSourceBaseAddress()); } } EXPECT_EQ(1u, xyCopyBltCmdFound); } } HWTEST_F(BcsTests, givenInvalidBlitDirectionWhenConstructPropertiesThenExceptionIsThrow) { auto &csr = pDevice->getUltCommandStreamReceiver<FamilyType>(); EXPECT_THROW(ClBlitProperties::constructProperties(static_cast<BlitterConstants::BlitDirection>(7), csr, {}), std::exception); } struct MockScratchSpaceController : ScratchSpaceControllerBase { using ScratchSpaceControllerBase::privateScratchAllocation; using ScratchSpaceControllerBase::ScratchSpaceControllerBase; }; using ScratchSpaceControllerTest = Test<ClDeviceFixture>; TEST_F(ScratchSpaceControllerTest, whenScratchSpaceControllerIsDestroyedThenItReleasePrivateScratchSpaceAllocation) { MockScratchSpaceController scratchSpaceController(pDevice->getRootDeviceIndex(), *pDevice->getExecutionEnvironment(), *pDevice->getGpgpuCommandStreamReceiver().getInternalAllocationStorage()); scratchSpaceController.privateScratchAllocation = pDevice->getExecutionEnvironment()->memoryManager->allocateGraphicsMemoryInPreferredPool(MockAllocationProperties{pDevice->getRootDeviceIndex(), MemoryConstants::pageSize}, nullptr); EXPECT_NE(nullptr, scratchSpaceController.privateScratchAllocation); //no memory leak is expected } TEST(BcsConstantsTests, givenBlitConstantsThenTheyHaveDesiredValues) { EXPECT_EQ(BlitterConstants::maxBlitWidth, 0x3FC0u); EXPECT_EQ(BlitterConstants::maxBlitHeight, 0x3FC0u); }
[ "ocldev@intel.com" ]
ocldev@intel.com
9caae026035df092fd448e52c8799e18d3df2e79
09a45c64b3226272b2a061fa2191eec28ced99e9
/C++/4.24/MultiWindow/Intermediate/Build/Win64/UE4Editor/Inc/MultiWindow/PCSceneCaptureComponent2D.generated.h
ef8dac86d5a016d11d63af9e0299090672405da1
[]
no_license
serishan/UnrealEngine
d33d2e11da2a65109cc8da71e687b6f5db2b994a
bcd73ecd5993180e55d5b6d49cfd92d0edce448e
refs/heads/master
2022-11-18T00:17:03.673752
2020-06-28T15:25:02
2020-06-28T15:25:02
275,609,999
0
0
null
null
null
null
UTF-8
C++
false
false
5,587
h
// Copyright 1998-2019 Epic Games, Inc. All Rights Reserved. /*=========================================================================== Generated code exported from UnrealHeaderTool. DO NOT modify this manually! Edit the corresponding .h files instead! ===========================================================================*/ #include "UObject/ObjectMacros.h" #include "UObject/ScriptMacros.h" PRAGMA_DISABLE_DEPRECATION_WARNINGS #ifdef MULTIWINDOW_PCSceneCaptureComponent2D_generated_h #error "PCSceneCaptureComponent2D.generated.h already included, missing '#pragma once' in PCSceneCaptureComponent2D.h" #endif #define MULTIWINDOW_PCSceneCaptureComponent2D_generated_h #define HostProject_Plugins_MultiWindow_Source_MultiWindow_Public_PCSceneCaptureComponent2D_h_10_SPARSE_DATA #define HostProject_Plugins_MultiWindow_Source_MultiWindow_Public_PCSceneCaptureComponent2D_h_10_RPC_WRAPPERS #define HostProject_Plugins_MultiWindow_Source_MultiWindow_Public_PCSceneCaptureComponent2D_h_10_RPC_WRAPPERS_NO_PURE_DECLS #define HostProject_Plugins_MultiWindow_Source_MultiWindow_Public_PCSceneCaptureComponent2D_h_10_INCLASS_NO_PURE_DECLS \ private: \ static void StaticRegisterNativesUPCSceneCaptureComponent2D(); \ friend struct Z_Construct_UClass_UPCSceneCaptureComponent2D_Statics; \ public: \ DECLARE_CLASS(UPCSceneCaptureComponent2D, USceneCaptureComponent2D, COMPILED_IN_FLAGS(0 | CLASS_Config), CASTCLASS_None, TEXT("/Script/MultiWindow"), NO_API) \ DECLARE_SERIALIZER(UPCSceneCaptureComponent2D) #define HostProject_Plugins_MultiWindow_Source_MultiWindow_Public_PCSceneCaptureComponent2D_h_10_INCLASS \ private: \ static void StaticRegisterNativesUPCSceneCaptureComponent2D(); \ friend struct Z_Construct_UClass_UPCSceneCaptureComponent2D_Statics; \ public: \ DECLARE_CLASS(UPCSceneCaptureComponent2D, USceneCaptureComponent2D, COMPILED_IN_FLAGS(0 | CLASS_Config), CASTCLASS_None, TEXT("/Script/MultiWindow"), NO_API) \ DECLARE_SERIALIZER(UPCSceneCaptureComponent2D) #define HostProject_Plugins_MultiWindow_Source_MultiWindow_Public_PCSceneCaptureComponent2D_h_10_STANDARD_CONSTRUCTORS \ /** Standard constructor, called after all reflected properties have been initialized */ \ NO_API UPCSceneCaptureComponent2D(const FObjectInitializer& ObjectInitializer = FObjectInitializer::Get()); \ DEFINE_DEFAULT_OBJECT_INITIALIZER_CONSTRUCTOR_CALL(UPCSceneCaptureComponent2D) \ DECLARE_VTABLE_PTR_HELPER_CTOR(NO_API, UPCSceneCaptureComponent2D); \ DEFINE_VTABLE_PTR_HELPER_CTOR_CALLER(UPCSceneCaptureComponent2D); \ private: \ /** Private move- and copy-constructors, should never be used */ \ NO_API UPCSceneCaptureComponent2D(UPCSceneCaptureComponent2D&&); \ NO_API UPCSceneCaptureComponent2D(const UPCSceneCaptureComponent2D&); \ public: #define HostProject_Plugins_MultiWindow_Source_MultiWindow_Public_PCSceneCaptureComponent2D_h_10_ENHANCED_CONSTRUCTORS \ /** Standard constructor, called after all reflected properties have been initialized */ \ NO_API UPCSceneCaptureComponent2D(const FObjectInitializer& ObjectInitializer = FObjectInitializer::Get()) : Super(ObjectInitializer) { }; \ private: \ /** Private move- and copy-constructors, should never be used */ \ NO_API UPCSceneCaptureComponent2D(UPCSceneCaptureComponent2D&&); \ NO_API UPCSceneCaptureComponent2D(const UPCSceneCaptureComponent2D&); \ public: \ DECLARE_VTABLE_PTR_HELPER_CTOR(NO_API, UPCSceneCaptureComponent2D); \ DEFINE_VTABLE_PTR_HELPER_CTOR_CALLER(UPCSceneCaptureComponent2D); \ DEFINE_DEFAULT_OBJECT_INITIALIZER_CONSTRUCTOR_CALL(UPCSceneCaptureComponent2D) #define HostProject_Plugins_MultiWindow_Source_MultiWindow_Public_PCSceneCaptureComponent2D_h_10_PRIVATE_PROPERTY_OFFSET #define HostProject_Plugins_MultiWindow_Source_MultiWindow_Public_PCSceneCaptureComponent2D_h_7_PROLOG #define HostProject_Plugins_MultiWindow_Source_MultiWindow_Public_PCSceneCaptureComponent2D_h_10_GENERATED_BODY_LEGACY \ PRAGMA_DISABLE_DEPRECATION_WARNINGS \ public: \ HostProject_Plugins_MultiWindow_Source_MultiWindow_Public_PCSceneCaptureComponent2D_h_10_PRIVATE_PROPERTY_OFFSET \ HostProject_Plugins_MultiWindow_Source_MultiWindow_Public_PCSceneCaptureComponent2D_h_10_SPARSE_DATA \ HostProject_Plugins_MultiWindow_Source_MultiWindow_Public_PCSceneCaptureComponent2D_h_10_RPC_WRAPPERS \ HostProject_Plugins_MultiWindow_Source_MultiWindow_Public_PCSceneCaptureComponent2D_h_10_INCLASS \ HostProject_Plugins_MultiWindow_Source_MultiWindow_Public_PCSceneCaptureComponent2D_h_10_STANDARD_CONSTRUCTORS \ public: \ PRAGMA_ENABLE_DEPRECATION_WARNINGS #define HostProject_Plugins_MultiWindow_Source_MultiWindow_Public_PCSceneCaptureComponent2D_h_10_GENERATED_BODY \ PRAGMA_DISABLE_DEPRECATION_WARNINGS \ public: \ HostProject_Plugins_MultiWindow_Source_MultiWindow_Public_PCSceneCaptureComponent2D_h_10_PRIVATE_PROPERTY_OFFSET \ HostProject_Plugins_MultiWindow_Source_MultiWindow_Public_PCSceneCaptureComponent2D_h_10_SPARSE_DATA \ HostProject_Plugins_MultiWindow_Source_MultiWindow_Public_PCSceneCaptureComponent2D_h_10_RPC_WRAPPERS_NO_PURE_DECLS \ HostProject_Plugins_MultiWindow_Source_MultiWindow_Public_PCSceneCaptureComponent2D_h_10_INCLASS_NO_PURE_DECLS \ HostProject_Plugins_MultiWindow_Source_MultiWindow_Public_PCSceneCaptureComponent2D_h_10_ENHANCED_CONSTRUCTORS \ private: \ PRAGMA_ENABLE_DEPRECATION_WARNINGS template<> MULTIWINDOW_API UClass* StaticClass<class UPCSceneCaptureComponent2D>(); #undef CURRENT_FILE_ID #define CURRENT_FILE_ID HostProject_Plugins_MultiWindow_Source_MultiWindow_Public_PCSceneCaptureComponent2D_h PRAGMA_ENABLE_DEPRECATION_WARNINGS
[ "qc3067@gmail.com" ]
qc3067@gmail.com
a9f6e0597c829e79d09aa9c76961f8dd2a2d5e38
f941477e317cfbc2e04946379f3d2c48427d5206
/0713/miro.cpp
0a4d7d2c85ad5c64ad2d76e681e364f7f885f124
[]
no_license
SangHyeon/Algoritm-practice
9167b90173dae3d1fd800eb037d0d0021e0022c0
a435805198f20f001a8b3ba17d9f5d0dea84ed53
refs/heads/master
2020-12-29T02:44:39.873014
2017-04-13T13:39:14
2017-04-13T13:39:14
39,385,639
0
0
null
null
null
null
UTF-8
C++
false
false
1,604
cpp
/* VC, GCC에서 사용 */ #include <iostream> using namespace std; char table[20][20]; int load[20][20]={0, }; void find(int n, int m,int N, int M) { if(n+1 < N && (table[n+1][m] != '1')) { if(load[n+1][m] > load[n][m]+1 || (load[n+1][m] == 0) ) { load[n+1][m] = load[n][m]+1; find(n+1, m, N, M); } } if(n-1 > -1 && (table[n-1][m] != '1')) { if(load[n-1][m] > load[n][m]+1 || (load[n-1][m] == 0)) { load[n-1][m] = load[n][m]+1; find(n-1, m, N, M); } } if(m+1 < M && (table[n][m+1] != '1')) { if(load[n][m+1] > load[n][m]+1 || (load[n][m+1] == 0)) { load[n][m+1] = load[n][m]+1; find(n, m+1, N, M); } } if(m-1 > -1 && (table[n][m-1] != '1')) { if(load[n][m-1] > load[n][m]+1 || (load[n][m-1] == 0)) { load[n][m-1] = load[n][m]+1; find(n, m-1, N, M); } } // printf("===========>\n"); return; //} } int main() { int itr; int nCount; /* 문제의 테스트 케이스 */ int N, M, result; //int load; //scanf("%d", &nCount); /* 테스트 케이스 입력 */ cin>>nCount; for(itr=0; itr<nCount; itr++) { printf("#testcase%d\n",itr+1); /* 알고리즘이 들어가는 부분 */ scanf("%d %d", &N, &M); for(int i=0; i<N; i++) { for(int j=0; j<M; j++) { //scanf("%c", &table[i][j]); cin>>table[i][j]; } } /* for(int i=0; i<N; i++) scanf("% */ load[N-1][0] = 1; find(N-1, 0, N, M); result = load[0][M-1]; if(result == 0) cout<<"-1"<<endl;//printf("-1\n"); else cout<<result<<endl;//printf("%d\n", result); } return 0; /* 반드시 return 0으로 해주셔야합니다. */ }
[ "sktkddusrj@naver.com" ]
sktkddusrj@naver.com
457caaa0ef386b655d45a568224bc63a92b9775a
3440f343301c534098b7d292878befe67d8a71a7
/SceneMgr.cpp
087b62c8227f7ec55c351260d285d8343eaa95e7
[]
no_license
porygon3/MOUNT
8ce33a3b7e3f1b1184b48bc770ee8bc2229b7b72
6d868ba8b64d059e86e870a28e80f1b0f1b3d37f
refs/heads/master
2020-04-24T22:13:09.041532
2019-07-05T17:53:31
2019-07-05T17:53:31
172,304,343
0
0
null
null
null
null
SHIFT_JIS
C++
false
false
1,225
cpp
#include "DxLib.h" #include "Select.h" #include "Game.h" #include "Title.h" #include "Jacket.h" #include "Result.h" #include "Unlock.h" #include "SceneMgr.h" SceneMgr::SceneMgr(){ scene = new Title(); Initialize(); } SceneMgr::~SceneMgr() { Finalize(); delete scene; } void SceneMgr::Initialize() { scene->Initialize(); } void SceneMgr::Finalize() { scene->Finalize(); } void SceneMgr::ChangeScene() { //削除 if (scene != nullptr) { Finalize(); delete scene; scene = nullptr; } switch (scene->GetNowScene()) { //今のシーンは何か case eScene::eScene_Title: scene = new Title(); break; case eScene::eScene_Select: scene = new Select(); break; case eScene::eScene_Unlock: scene = new Unlock(); break; case eScene::eScene_Jacket: scene = new Jacket(); break; case eScene::eScene_Game: scene = new Game(); break; case eScene::eScene_Result: scene = new Result(); break; default: assert(0); break; } Initialize(); } void SceneMgr::Update() { if (es != scene->GetNowScene()) { es = scene->GetNowScene(); ChangeScene(); } scene->Update(); } void SceneMgr::Draw() { scene->Draw(); }
[ "noreply@github.com" ]
porygon3.noreply@github.com
4751748b6d1a3d3ab4c46168918af63a52b50199
9861baf0aff68fc9c4e13479b9accbb93dcb5428
/src/effects/imageBeatEffectItem.cpp
c4bf18fa5139712fba6294bf32761eb27e45d4be
[]
no_license
Daandelange/karmaMapper
9b36c0bd7244e6f1cb2feee07968eb11feff0d23
274b694f61d1a09e2e58c219d4232344ffceb49e
refs/heads/master
2022-12-27T11:36:29.204878
2020-10-10T11:51:19
2020-10-10T11:51:19
18,294,275
1
1
null
null
null
null
UTF-8
C++
false
false
3,013
cpp
// // imageBeatEffectItem.cpp // workshopMappingCyril // // Created by Daan de Lange on 14/12/2014. // Copyright (c) 2014 __MyCompanyName__. All rights reserved. // // tmp disabled #ifdef KM_PLEASESKIPME #include "imageBeatEffectItem.h" imageBeatEffectItem::imageBeatEffectItem(basicShape* _shape) { if(_shape==NULL) return; vertexShape* shape =((vertexShape*)_shape); bAlive = true; startTime = ofGetElapsedTimef(); center = shape->getCenterPtr(); position = *center - basicPoint( shape->getBoundingBox().x, _shape->getBoundingBox().y ); // get image from shape ofRectangle size = _shape->getBoundingBox(); if( size.width ==0 && size.height ==0 ){ bAlive=false; return; } image.allocate(size.width, size.height, GL_RGBA, 1); image.loadScreenData(size.x, size.y, size.width, size.height); /* ofPixels tmp; // tmp //image.readToPixels(tmp); // draw shape in an fbo and draw shape mask ofFbo buffer; buffer.allocate(size.width, size.height, GL_RGBA, 1); buffer.begin(); ofClear(0,1); ofClearAlpha(); // draw virtual mask //ofTranslate( *shape->getPositionPtr() * ofVec2f(-1.f,-1.f) +size.width/2); // because shape->render() translates it back ofTranslate(-1*ofVec2f( shape->getBoundingBox().x, _shape->getBoundingBox().y )); shape->render(); ofTranslate(ofVec2f( shape->getBoundingBox().x, _shape->getBoundingBox().y )); buffer.end(); // draw texture with alpha mask glEnable(GL_BLEND); glBlendFunc(GL_DST_ALPHA, GL_ONE_MINUS_SRC_ALPHA); glBlendEquation(GL_FUNC_SUBTRACT); //ofSetColor(255,255); image.draw(-position.x,-position.y); ofDisableAlphaBlending(); buffer.end(); //buffer.readToPixels(tmp); //ofSaveImage(tmp, "lol.png"); // get mask pixels ofPixels maskPixels; buffer.readToPixels( maskPixels ); image.loadData(maskPixels); //image. //*/ //ofPixels tmp; //image.readToPixels(tmp); //ofSaveImage(tmp, "lol.png"); // apply mask opacity to image (3=alpha channel) //for( int i=3; i<maskPixels.size(); i += maskPixels.getNumChannels() ) { //image.getPixelsRef()[i] = maskPixels[i]; //} // tmp to see the image mask for debugging //image.setFromPixels(maskPixels); // finally update our image's pixels //image.update(); //image. } imageBeatEffectItem::~imageBeatEffectItem() { } void imageBeatEffectItem::render(){ //ofScopedLock lock( effectMutex ); if(!bAlive) return; float aliveSince = ofGetElapsedTimef()-startTime; if(aliveSince>LEL_LIFE_SPAN) bAlive=false; else render( aliveSince/LEL_LIFE_SPAN ); return true; } void imageBeatEffectItem::render(float state) { if(!bAlive) return; //float opacity = abs( (state*2)-1 ); float opacity = 1-abs( (state-0.5f)*2 ); ofPushStyle(); float scale = 1-state; basicPoint xy = *center - position*scale; basicPoint wh = basicPoint( image.getWidth(), image.getHeight() )*scale; image.draw( xy.x, xy.y, wh.x, wh.y ); ofPopStyle(); } bool imageBeatEffectItem::isAlive() const{ return bAlive; } // END KM_PLEASESKIPME #endif
[ "idaany@gmail.com" ]
idaany@gmail.com
7180ad106a77dc8bfad2f8ce8fb331367136ee6e
870bb58c90ed1fd80e448d7b5361a6c4233ab96b
/src/scene.hpp
792d773b73840005eae99ac9d44b7d416e5534e6
[]
no_license
LanJian/Raytracer
421e483884e8bb961d2113d2183d7f2c305a72c0
b1a923d33b1b97235ff68aefbcc3d491f0ccd56e
refs/heads/master
2016-09-08T00:27:03.361236
2012-06-06T01:16:28
2012-06-06T01:16:28
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,039
hpp
#ifndef SCENE_HPP #define SCENE_HPP #include <list> #include "algebra.hpp" #include "primitive.hpp" #include "material.hpp" class SceneNode { public: SceneNode(const std::string& name); virtual ~SceneNode(); const Matrix4x4& get_transform() const { return m_trans; } const Matrix4x4& get_inverse() const { return m_invtrans; } void set_transform(const Matrix4x4& m) { m_trans = m; m_invtrans = m.invert(); } void set_transform(const Matrix4x4& m, const Matrix4x4& i) { m_trans = m; m_invtrans = i; } void add_child(SceneNode* child) { m_children.push_back(child); } void remove_child(SceneNode* child) { m_children.remove(child); } // Callbacks to be implemented. // These will be called from Lua. void rotate(char axis, double angle); void scale(const Vector3D& amount); void translate(const Vector3D& amount); // Returns true if and only if this node is a JointNode virtual bool is_joint() const; virtual Intersection* intersect(Ray& ray); protected: // Useful for picking int m_id; std::string m_name; // Transformations Matrix4x4 m_trans; Matrix4x4 m_invtrans; // Hierarchy typedef std::list<SceneNode*> ChildList; ChildList m_children; }; class JointNode : public SceneNode { public: JointNode(const std::string& name); virtual ~JointNode(); virtual bool is_joint() const; void set_joint_x(double min, double init, double max); void set_joint_y(double min, double init, double max); struct JointRange { double min, init, max; }; protected: JointRange m_joint_x, m_joint_y; }; class GeometryNode : public SceneNode { public: GeometryNode(const std::string& name, Primitive* primitive); virtual ~GeometryNode(); const Material* get_material() const; Material* get_material(); void set_material(Material* material) { m_material = material; } virtual Intersection* intersect(Ray& ray); protected: Material* m_material; Primitive* m_primitive; }; #endif
[ "jackhxs@gmail.com" ]
jackhxs@gmail.com
d2f0c748eb7822c0d31e79e601db22ac5756c95b
f1a6cdffb793d41d673a945133907334865f7b62
/Codeforces/div2_A/CF677-D2-A_vanya and his friends.cpp
d06d3ff11015f373680aaac24062ec8e6f84a839
[]
no_license
asrezoun/contest-programming
be4b263314e032e3a524eb4301a7d82229151237
c77c47fa26b7ceb90cc37d248bf0897cc6dbac32
refs/heads/main
2023-04-21T02:01:03.794277
2021-05-06T10:43:05
2021-05-06T10:43:05
363,039,602
0
0
null
null
null
null
UTF-8
C++
false
false
362
cpp
#include<cstdio> #include<vector> using namespace std; int main() { int n,h,width=0; scanf("%d %d",&n,&h); vector<int>a(n); for(int i=0;i<n;i++) { scanf("%d",&a[i]); } for(int i=0;i<n;i++) { if(a[i]>h) width +=2; else ++width; } printf("%d",width); return 0; }
[ "abusaid.rezoun@gmail.com" ]
abusaid.rezoun@gmail.com
87ca32220f060f8cbe407569ced73a8687b90c34
6303ec756d2c99cbcea7472341b90056065fdef5
/ECS/ECS/Entity.h
02ff1b985dabfcca6ddba5277cb50e572b6df2b1
[]
no_license
MichaelBridgette/Games-Engineering-Labs
69f49885e4c9d6f246974c9d2bfcee2117305c28
c30ce632b888f63f27c2f27e8aa1301b7a392430
refs/heads/master
2020-03-29T16:00:41.945242
2019-03-11T12:55:13
2019-03-11T12:55:13
150,092,398
0
0
null
null
null
null
UTF-8
C++
false
false
324
h
#ifndef ENTITY_H #define ENTITY_H #include<vector> #include"Component.h" class Entity { public: int id; Entity() {}; void addComponent(Component * c) { components.push_back(c); }; std::vector<Component *> getComponents() { return components; }; private: std::vector<Component * > components; }; #endif // !ENTITY_H
[ "c00205948@itcarlow.ie" ]
c00205948@itcarlow.ie
8b45532b59e086d66fc59489d34c00f1ea5b0887
89378f005af9b78e850e097cba243b51e7460242
/Data Structures/DS11/Project3/BinartSerachTree2.h
2c32ba773c5869542011a4427861e2265ae42265
[]
no_license
KevenTom/my_study_project
5bf15ea24f20e76c1eb5ab1e3d7f1d607dacc6d6
1b49bcfca75612c68a2a061517fc2fd233e6f91c
refs/heads/master
2023-01-21T08:30:36.813165
2020-12-02T18:13:34
2020-12-02T18:13:34
278,594,851
0
0
null
null
null
null
UTF-8
C++
false
false
3,674
h
#pragma once #include "Binary_Tree.h" #include "AVLRebalance.h" #include<iostream> template<typename T> class BinartSerachTree : public Binary_Tree<T> { public: BinartSerachTree() :Binary_Tree<T>() {} void test() { int get = AVLRebalance<T>::instance().GetHightDiff(); std::cout << get << std::endl; } void MakeSearchTree(T insert, Binary_Tree<T>* tree) { if (tree->getData() == insert) return; if (tree->getData() == NULL) { tree->SetData(insert); return; } if (tree->GetRightSubTree() == NULL && tree->getData() < insert) { Binary_Tree<T>* subtree = new Binary_Tree<T>; tree->MakeRightSubTree(subtree); } else if (tree->GetLeftSubTree() == NULL && tree->getData() > insert) { Binary_Tree<T>* subtree = new Binary_Tree<T>; tree->MakeLeftSubTree(subtree); } if (insert > tree->getData()) MakeSearchTree(insert, tree->GetRightSubTree()); else MakeSearchTree(insert, tree->GetLeftSubTree()); } Binary_Tree<T>* SearchTree(T insert, Binary_Tree<T>* tree) { if (tree == NULL) return NULL; if (tree->getData() == insert) return tree; else if (tree->getData() < insert) SearchTree(insert, tree->GetRightSubTree()); else SearchTree(insert, tree->GetLeftSubTree()); } void DeleteSearchTree(T insert) { Binary_Tree<T>* pVroot = new Binary_Tree<T>; Binary_Tree<T>* rootNode = pVroot; Binary_Tree<T>* subNode = this; Binary_Tree<T>* rootNode2; Binary_Tree<T>* subNode2; pVroot->MakeRightSubTree(subNode); while (subNode != NULL && subNode->getData() != insert) { rootNode = subNode; if (subNode->getData() < insert) subNode = subNode->GetRightSubTree(); else subNode = subNode->GetLeftSubTree(); } if (subNode == NULL) return; if (subNode->GetLeftSubTree() == NULL && subNode->GetRightSubTree() == NULL) { if (rootNode->GetLeftSubTree() == subNode) rootNode->MakeLeftSubTree(NULL); else rootNode->MakeRightSubTree(NULL); } else if (subNode->GetLeftSubTree() == NULL || subNode->GetRightSubTree() == NULL) { if (rootNode->GetLeftSubTree() == subNode) { if (subNode->GetLeftSubTree() == NULL) rootNode->MakeLeftSubTree(subNode->GetRightSubTree()); else rootNode->MakeLeftSubTree(subNode->GetLeftSubTree()); } else { if (subNode->GetLeftSubTree() == NULL) rootNode->MakeRightSubTree(subNode->GetRightSubTree()); else rootNode->MakeRightSubTree(subNode->GetLeftSubTree()); } } else { rootNode2 = subNode; subNode2 = subNode->GetRightSubTree(); while (subNode2->GetLeftSubTree() != NULL) { rootNode2 = subNode2; subNode2 = subNode2->GetLeftSubTree(); } subNode->SetData(subNode2->getData()); if (rootNode2->GetLeftSubTree() == subNode2) rootNode2->MakeLeftSubTree(subNode2->GetRightSubTree()); else rootNode2->MakeRightSubTree(subNode2->GetRightSubTree()); subNode = subNode2; } delete[] subNode; } };
[ "zpqls1648@naver.com" ]
zpqls1648@naver.com
6b78b2edfc7ac358303669082e5450fe6fb30172
cf8ddfc720bf6451c4ef4fa01684327431db1919
/SDK/ARKSurvivalEvolved_PrimalItem_DungeonEntrance_TekCave_Easy_classes.hpp
e0f8f207013885364e8d6c8cf234333906c68ba0
[ "MIT" ]
permissive
git-Charlie/ARK-SDK
75337684b11e7b9f668da1f15e8054052a3b600f
c38ca9925309516b2093ad8c3a70ed9489e1d573
refs/heads/master
2023-06-20T06:30:33.550123
2021-07-11T13:41:45
2021-07-11T13:41:45
null
0
0
null
null
null
null
UTF-8
C++
false
false
936
hpp
#pragma once // ARKSurvivalEvolved (329.9) SDK #ifdef _MSC_VER #pragma pack(push, 0x8) #endif #include "ARKSurvivalEvolved_PrimalItem_DungeonEntrance_TekCave_Easy_structs.hpp" namespace sdk { //--------------------------------------------------------------------------- //Classes //--------------------------------------------------------------------------- // BlueprintGeneratedClass PrimalItem_DungeonEntrance_TekCave_Easy.PrimalItem_DungeonEntrance_TekCave_Easy_C // 0x0000 (0x0AEC - 0x0AEC) class UPrimalItem_DungeonEntrance_TekCave_Easy_C : public UPrimalItem_DungeonEntrance_Base_C { public: static UClass* StaticClass() { static auto ptr = UObject::FindClass("BlueprintGeneratedClass PrimalItem_DungeonEntrance_TekCave_Easy.PrimalItem_DungeonEntrance_TekCave_Easy_C"); return ptr; } void ExecuteUbergraph_PrimalItem_DungeonEntrance_TekCave_Easy(int EntryPoint); }; } #ifdef _MSC_VER #pragma pack(pop) #endif
[ "sergey.2bite@gmail.com" ]
sergey.2bite@gmail.com
bd9e45dc8bd870af997ba0640b736682fa8d6ebb
a47a3506c59d861d1a9e2b6ada12fe4f8bf8a3e4
/TutorialsUsed/ForLoopIteration/ForLoopIteration.ino
baa08fa77fffa70a667093409983c228575a3230
[]
no_license
helloimali/ArduinoThings
540c71c3887b8d8c772dcc4df5e744b767c96265
1c0726f6f69d334f42f0524c8ff8eecede0e1274
refs/heads/master
2021-01-10T10:05:03.898356
2017-02-25T06:21:05
2017-02-25T06:21:05
80,338,452
0
0
null
null
null
null
UTF-8
C++
false
false
1,502
ino
// _ ___ _______ ___ ___ ___ ___ _ _ ___ _____ ___ // / |_ )__ / \ / __|_ _| _ \/ __| | | |_ _|_ _/ __| // | |/ / |_ \ |) | | (__ | || / (__| |_| || | | | \__ \ // |_/___|___/___/ \___|___|_|_\\___|\___/|___| |_| |___/ // // For Loop Iteration // // Made by Becky Stern // License: Public Domain // Downloaded from: https://circuits.io/circuits/2932830-for-loop-iteration /* For Loop Iteration Demonstrates the use of a for() loop. Lights multiple LEDs in sequence, then in reverse. The circuit: * LEDs from pins 3 through 7 to ground created 2006 by David A. Mellis modified 30 Aug 2011 by Tom Igoe This example code is in the public domain. http://www.arduino.cc/en/Tutorial/ForLoop */ int timer = 200; // The higher the number, the slower the timing. void setup() { // use a for loop to initialize each pin as an output: for (int thisPin = 3; thisPin < 8; thisPin++) { pinMode(thisPin, OUTPUT); } } void loop() { // loop from the lowest pin to the highest: for (int thisPin = 3; thisPin < 8; thisPin++) { // turn the pin on: digitalWrite(thisPin, HIGH); delay(timer); // turn the pin off: digitalWrite(thisPin, LOW); } // loop from the highest pin to the lowest: for (int thisPin = 7; thisPin >= 3; thisPin--) { // turn the pin on: digitalWrite(thisPin, HIGH); delay(timer); // turn the pin off: digitalWrite(thisPin, LOW); } }
[ "toalisaeedmalik@gmail.com" ]
toalisaeedmalik@gmail.com
0253a41c00dcdf2b19941024b9e5c0ac7abdf2d5
0b81f139cb54d3b6358a00f1a16efe6a5e754452
/test/main.cc
f62c5d99c58f0c489e7d29d714eb7096374218e8
[]
no_license
cjq/proxy
df3cef795ffc14a3d89ff6c003d0fbfb8db4101b
659de55f7258edd7611b000264594660631528cc
refs/heads/master
2020-03-12T17:02:58.376974
2018-04-15T15:32:16
2018-04-15T15:32:16
null
0
0
null
null
null
null
UTF-8
C++
false
false
189
cc
#include "../util/util.h" int main(int argc, char **argv) { ccflag::init_ccflag(argc, argv); cclog::init_cclog(argv[0]); cctest::init_cctest(argc, argv); cctest::run_tests(); }
[ "1135628277@qq.com" ]
1135628277@qq.com
4b4d3d21cbde2bf15001aec797554a5efdb23b06
ef3a7391b0a5c5d8e276355e97cbe4de621d500c
/venv/Lib/site-packages/torch/include/caffe2/operators/elementwise_ops.h
ab6f0e9988de8e14425b28a6642f95fec4cfceb1
[ "Apache-2.0" ]
permissive
countBMB/BenjiRepo
143f6da5d198ea6f06404b4559e1f4528b71b3eb
79d882263baaf2a11654ca67d2e5593074d36dfa
refs/heads/master
2022-12-11T07:37:04.807143
2019-12-25T11:26:29
2019-12-25T11:26:29
230,090,428
1
1
Apache-2.0
2022-12-08T03:21:09
2019-12-25T11:05:59
Python
UTF-8
C++
false
false
16,724
h
#ifndef CAFFE2_OPERATORS_ELEMENTWISE_OPS_H_ #define CAFFE2_OPERATORS_ELEMENTWISE_OPS_H_ #include <iterator> #include <string> #include <tuple> #include <vector> #include "caffe2/core/common_omp.h" #include "caffe2/core/context.h" #include "caffe2/core/logging.h" #include "caffe2/core/operator.h" #include "caffe2/core/tensor.h" #include "caffe2/operators/elementwise_ops_utils.h" #include "caffe2/utils/eigen_utils.h" #include "caffe2/utils/math.h" namespace caffe2 { using NumericTypes = TensorTypes<int32_t, int64_t, float, double>; using IntTypes = TensorTypes<int32_t, int64_t>; using BoolTypes = TensorTypes<bool>; using IntBoolTypes = TensorTypes<int32_t, int64_t, bool>; // discrete types struct SameTypeAsInput { template <typename T> using type = T; }; template <typename R> struct FixedType { template <typename T> using type = R; }; template < typename InputTypes, class Context, class Functor, class OutputTypeMap = SameTypeAsInput> class UnaryElementwiseWithArgsOp final : public Operator<Context> { public: USE_OPERATOR_CONTEXT_FUNCTIONS; template <class... Args> explicit UnaryElementwiseWithArgsOp(Args&&... args) : Operator<Context>(std::forward<Args>(args)...), functor_(*this) {} bool RunOnDevice() override { return DispatchHelper<InputTypes>::call(this, Input(0)); } template <typename T> bool DoRunWithType() { const auto& X = Input(0); auto* Y = Output( 0, X.sizes(), at::dtype<typename OutputTypeMap::template type<T>>()); return functor_( X.numel(), X.template data<T>(), Y->template mutable_data<typename OutputTypeMap::template type<T>>(), &context_); } private: Functor functor_; }; // UnaryFunctorWithDefaultCtor is a functor that can be used as the functor of // an UnaryElementwiseWithArgsOp. It simply forwards the operator() call into // another functor that doesn't accept arguments in its constructor. template <class Functor> struct UnaryFunctorWithDefaultCtor { explicit UnaryFunctorWithDefaultCtor(OperatorBase& /* op */) {} template <typename TIn, typename TOut, class Context> bool operator()(const int size, const TIn* X, TOut* Y, Context* context) const { return functor(size, X, Y, context); } Functor functor{}; }; // UnaryElementwiseOp is a wrapper around UnaryElementwiseWithArgsOp, with the // difference that it takes a functor with default constructor, e.g. that does // not need to take into consideration any arguments during operator creation. template < typename InputTypes, class Context, class Functor, class OutputTypeMap = SameTypeAsInput> using UnaryElementwiseOp = UnaryElementwiseWithArgsOp< InputTypes, Context, UnaryFunctorWithDefaultCtor<Functor>, OutputTypeMap>; template < typename InputTypes, class Context, class Functor, class OutputTypeMap = SameTypeAsInput> class BinaryElementwiseWithArgsOp final : public Operator<Context> { public: USE_OPERATOR_CONTEXT_FUNCTIONS; template <class... Args> explicit BinaryElementwiseWithArgsOp(Args&&... args) : Operator<Context>(std::forward<Args>(args)...), OP_SINGLE_ARG(bool, "broadcast", legacy_broadcast_, false), OP_SINGLE_ARG(int, "axis", axis_, -1), OP_SINGLE_ARG(string, "axis_str", axis_str_, string("")), OP_SINGLE_ARG(string, "order", order_, "NCHW"), functor_(*this) { if (legacy_broadcast_) { if (axis_ != -1) { // Get axis from an explicit axis argument. CAFFE_ENFORCE_EQ( axis_str_.size(), 0, "Args axis and axis_str cannot be used simultaneously."); } else if (axis_str_.size()) { // Get the axis index semantically. CAFFE_ENFORCE_EQ( axis_str_.size(), 1, "Unsupported axis string", axis_str_); const size_t semantic_axis_ = order_.find(axis_str_); CAFFE_ENFORCE_NE( semantic_axis_, string::npos, "Unrecognizable axis string ", axis_str_, " from order string ", order_); axis_ = semantic_axis_; } else { CAFFE_ENFORCE( axis_ == -1 && axis_str_.empty(), "Do not specify axis or axis_str if broadcast is not enabled."); } } } bool RunOnDevice() override { return DispatchHelper<InputTypes>::call(this, Input(0)); } template <typename T> bool DoRunWithType() { const auto& A = Input(0); const auto& B = Input(1); const T* A_data = A.template data<T>(); const T* B_data = B.template data<T>(); std::vector<int> A_dims; std::vector<int> B_dims; std::vector<int64_t> C_dims; if (legacy_broadcast_) { CAFFE_ENFORCE( !IsInputOutputAlias(1, 0), "In-place is allowed only with the first tensor when " "legacy-broadcasting"); C_dims = A.sizes().vec(); if (B.numel() == 1) { A_dims = {static_cast<int>(A.numel())}; B_dims = {1}; } else { size_t pre, n, post; std::tie(pre, n, post) = elementwise_ops_utils::ComputeLegacyBroadcastSizes(A, B, axis_); A_dims = { static_cast<int>(pre), static_cast<int>(n), static_cast<int>(post)}; B_dims = {static_cast<int>(n), 1}; } } else { std::copy( A.sizes().cbegin(), A.sizes().cend(), std::back_inserter(A_dims)); std::copy( B.sizes().cbegin(), B.sizes().cend(), std::back_inserter(B_dims)); // TODO: change the types to vector<int64_t> auto C_dims_int = elementwise_ops_utils::ComputeBinaryBroadcastForwardDims( A_dims, B_dims); std::copy( C_dims_int.cbegin(), C_dims_int.cend(), std::back_inserter(C_dims)); if (IsInputOutputAlias(0, 0)) { CAFFE_ENFORCE_EQ(C_dims_int, A_dims); } else if (IsInputOutputAlias(1, 0)) { CAFFE_ENFORCE_EQ(C_dims_int, B_dims); } } auto* C = Output( 0, C_dims, at::dtype<typename OutputTypeMap::template type<T>>()); auto* C_data = C->template mutable_data<typename OutputTypeMap::template type<T>>(); return functor_.Forward(A_dims, B_dims, A_data, B_data, C_data, &context_); } private: const bool legacy_broadcast_; int axis_; const std::string axis_str_; const std::string order_; Functor functor_; }; template < typename InputTypes, class Context, class Functor, class OutputTypeMap = SameTypeAsInput, class GradientTypeMap = SameTypeAsInput> class BinaryElementwiseWithArgsGradientOp final : public Operator<Context> { public: USE_OPERATOR_CONTEXT_FUNCTIONS; template <class... Args> explicit BinaryElementwiseWithArgsGradientOp(Args&&... args) : Operator<Context>(std::forward<Args>(args)...), OP_SINGLE_ARG(bool, "broadcast", legacy_broadcast_, false), OP_SINGLE_ARG(int, "axis", axis_, -1), OP_SINGLE_ARG(string, "axis_str", axis_str_, ""), OP_SINGLE_ARG(string, "order", order_, "NCHW"), functor_(*this) { if (legacy_broadcast_) { if (axis_ != -1) { // Get axis from an explicit axis argument. CAFFE_ENFORCE_EQ( axis_str_.size(), 0, "Args axis and axis_str cannot be used simultaneously."); } else if (axis_str_.size()) { // Get the axis index semantically. CAFFE_ENFORCE_EQ( axis_str_.size(), 1, "Unsupported axis string", axis_str_); const size_t semantic_axis_ = order_.find(axis_str_); CAFFE_ENFORCE_NE( semantic_axis_, string::npos, "Unrecognizable axis string ", axis_str_, " from order string ", order_); axis_ = semantic_axis_; } else { CAFFE_ENFORCE( axis_ == -1 && axis_str_.empty(), "Do not specify axis or axis_str if broadcast is not enabled."); } } } bool RunOnDevice() override { return DispatchHelper<InputTypes>::call(this, Input(1)); } template <typename T> bool DoRunWithType() { const auto& dC = Input(0); const auto& A = Input(1); const auto& B = Input(2); vector<int> A_dims; vector<int> B_dims; if (legacy_broadcast_) { if (B.numel() == 1) { A_dims = {static_cast<int>(A.numel())}; B_dims = {1}; } else { size_t pre, n, post; std::tie(pre, n, post) = elementwise_ops_utils::ComputeLegacyBroadcastSizes(A, B, axis_); A_dims = { static_cast<int>(pre), static_cast<int>(n), static_cast<int>(post)}; B_dims = {static_cast<int>(n), 1}; } } else { std::copy( A.sizes().cbegin(), A.sizes().cend(), std::back_inserter(A_dims)); std::copy( B.sizes().cbegin(), B.sizes().cend(), std::back_inserter(B_dims)); } const typename OutputTypeMap::template type<T>* C_data = nullptr; if (InputSize() == 4) { const auto& C = Input(3); C_data = C.template data<typename OutputTypeMap::template type<T>>(); } const auto* dC_data = dC.template data<typename GradientTypeMap::template type<T>>(); const T* A_data = A.template data<T>(); const T* B_data = B.template data<T>(); auto* dA = Output( 0, A.sizes(), at::dtype<typename GradientTypeMap::template type<T>>()); auto* dB = Output( 1, B.sizes(), at::dtype<typename GradientTypeMap::template type<T>>()); auto* dA_data = dA->template mutable_data<typename GradientTypeMap::template type<T>>(); auto* dB_data = dB->template mutable_data<typename GradientTypeMap::template type<T>>(); return functor_.Backward( A_dims, B_dims, dC_data, A_data, B_data, C_data, dA_data, dB_data, &context_); } private: const bool legacy_broadcast_; int axis_; const std::string axis_str_; const std::string order_; Functor functor_; }; template <class Functor> struct BinaryFunctorWithDefaultCtor { explicit BinaryFunctorWithDefaultCtor(OperatorBase& /* op */) {} template <typename TIn, typename TOut, class Context> bool Forward( const std::vector<int>& A_dims, const std::vector<int>& B_dims, const TIn* A_data, const TIn* B_data, TOut* C_data, Context* context) const { return functor.Forward(A_dims, B_dims, A_data, B_data, C_data, context); } template <typename TGrad, typename TIn, typename TOut, class Context> bool Backward( const std::vector<int>& A_dims, const std::vector<int>& B_dims, const TGrad* dC_data, const TIn* A_data, const TIn* B_data, const TOut* C_data, TGrad* dA_data, TGrad* dB_data, Context* context) const { return functor.Backward( A_dims, B_dims, dC_data, A_data, B_data, C_data, dA_data, dB_data, context); } Functor functor{}; }; // BinaryElementwiseOp is a wrapper around BinaryElementwiseWithArgsOp, with the // difference that it takes a functor with default constructor, e.g. that does // not need to take into consideration any arguments during operator creation. template < typename InputTypes, class Context, class Functor, class TypeMap = SameTypeAsInput> using BinaryElementwiseOp = BinaryElementwiseWithArgsOp< InputTypes, Context, BinaryFunctorWithDefaultCtor<Functor>, TypeMap>; // BinaryElementwiseGradientOp is a wrapper around // BinaryElementwiseGradientWithArgsOp, with the difference that it takes a // functor with default constructor, e.g. that does not need to take into // consideration any arguments during operator creation. template < typename InputTypes, class Context, class Functor, class OutputTypeMap = SameTypeAsInput, class GradientTypeMap = SameTypeAsInput> using BinaryElementwiseGradientOp = BinaryElementwiseWithArgsGradientOp< InputTypes, Context, BinaryFunctorWithDefaultCtor<Functor>, OutputTypeMap, GradientTypeMap>; // Forward-only Unary Functors. template <class Context> struct NotFunctor { bool operator()(const int N, const bool* X, bool* Y, Context* context) const { math::Not(N, X, Y, context); return true; } }; template <class Context> struct SignFunctor { template <typename T> bool operator()(const int N, const T* X, T* Y, Context* context) const { math::Sign(N, X, Y, context); return true; } }; // Forward-only Binary Functors. #define C10_DECLARE_FORWARD_ONLY_BINARY_FUNCTOR(FunctorName) \ template <class Context> \ struct FunctorName##Functor { \ template <typename TIn, typename TOut> \ bool Forward( \ const std::vector<int>& A_dims, \ const std::vector<int>& B_dims, \ const TIn* A, \ const TIn* B, \ TOut* C, \ Context* context) const { \ math::FunctorName( \ A_dims.size(), \ A_dims.data(), \ B_dims.size(), \ B_dims.data(), \ A, \ B, \ C, \ context); \ return true; \ } \ }; // Compare functors. C10_DECLARE_FORWARD_ONLY_BINARY_FUNCTOR(EQ); C10_DECLARE_FORWARD_ONLY_BINARY_FUNCTOR(NE); C10_DECLARE_FORWARD_ONLY_BINARY_FUNCTOR(LT); C10_DECLARE_FORWARD_ONLY_BINARY_FUNCTOR(LE); C10_DECLARE_FORWARD_ONLY_BINARY_FUNCTOR(GT); C10_DECLARE_FORWARD_ONLY_BINARY_FUNCTOR(GE); // Logical functors. C10_DECLARE_FORWARD_ONLY_BINARY_FUNCTOR(And); C10_DECLARE_FORWARD_ONLY_BINARY_FUNCTOR(Or); C10_DECLARE_FORWARD_ONLY_BINARY_FUNCTOR(Xor); // Bitwise functors. C10_DECLARE_FORWARD_ONLY_BINARY_FUNCTOR(BitwiseAnd); C10_DECLARE_FORWARD_ONLY_BINARY_FUNCTOR(BitwiseOr); C10_DECLARE_FORWARD_ONLY_BINARY_FUNCTOR(BitwiseXor); #undef C10_DECLARE_FORWARD_ONLY_BINARY_FUNCTOR namespace SRLHelper { template <typename T> void sum2one(const T* a, T* y, size_t n); template <typename T> void RunWithBroadcastFront(const T* a, T* y, size_t pre, size_t n, CPUContext*); template <typename T> void RunWithBroadcastBack(const T* a, T* y, size_t post, size_t n, CPUContext*); template <typename T> void RunWithBroadcast2( const T* a, T* y, size_t pre, size_t n, size_t post, CPUContext*); } // namespace SRLHelper // Sum reduction operator that is used for computing the gradient in cases // where the forward op is in broadcast mode. template <class Context> class SumReduceLikeOp final : public Operator<Context> { public: USE_OPERATOR_CONTEXT_FUNCTIONS; template <class... Args> explicit SumReduceLikeOp(Args&&... args) : Operator<Context>(std::forward<Args>(args)...), OP_SINGLE_ARG(int, "axis", axis_, -1), OP_SINGLE_ARG(string, "axis_str", axis_str_, ""), OP_SINGLE_ARG(string, "order", order_, "NCHW") { if (axis_ != -1) { // Get axis from an explicit axis argument. CAFFE_ENFORCE_EQ( axis_str_.size(), 0, "Args axis and axis_str cannot be used simultaneously."); } else if (axis_str_.size()) { // Get the axis index semantically. CAFFE_ENFORCE_EQ( axis_str_.size(), 1, "Unsupported axis string", axis_str_); size_t semantic_axis = order_.find(axis_str_); CAFFE_ENFORCE_NE( semantic_axis, string::npos, "Unrecognizable axis string ", axis_str_, " from order string ", order_); axis_ = semantic_axis; } } bool RunOnDevice() override { return DispatchHelper<TensorTypes<float, double>>::call(this, Input(0)); } template <typename T> bool DoRunWithType(); private: int axis_; string axis_str_; string order_; Tensor ones_{Context::GetDeviceType()}; Tensor sum_buffer_{Context::GetDeviceType()}; }; } // namespace caffe2 #endif // CAFFE2_OPERATORS_ELEMENTWISE_OPS_H_
[ "bengmen92@gmail.com" ]
bengmen92@gmail.com
b7e7cb9af082bda9c64a5a888192b148e8f09436
0641d87fac176bab11c613e64050330246569e5c
/branches/claireho/timezone/source/i18n/coll.cpp
d35a7d1c47cd328b9ce8e18a82d2169fd694e61b
[ "LicenseRef-scancode-unicode", "ICU" ]
permissive
svn2github/libicu_full
ecf883cedfe024efa5aeda4c8527f227a9dbf100
f1246dcb7fec5a23ebd6d36ff3515ff0395aeb29
refs/heads/master
2021-01-01T17:00:58.555108
2015-01-27T16:59:40
2015-01-27T16:59:40
9,308,333
0
2
null
null
null
null
UTF-8
C++
false
false
27,579
cpp
/* ****************************************************************************** * Copyright (C) 1996-2011, International Business Machines Corporation and * others. All Rights Reserved. ****************************************************************************** */ /** * File coll.cpp * * Created by: Helena Shih * * Modification History: * * Date Name Description * 2/5/97 aliu Modified createDefault to load collation data from * binary files when possible. Added related methods * createCollationFromFile, chopLocale, createPathName. * 2/11/97 aliu Added methods addToCache, findInCache, which implement * a Collation cache. Modified createDefault to look in * cache first, and also to store newly created Collation * objects in the cache. Modified to not use gLocPath. * 2/12/97 aliu Modified to create objects from RuleBasedCollator cache. * Moved cache out of Collation class. * 2/13/97 aliu Moved several methods out of this class and into * RuleBasedCollator, with modifications. Modified * createDefault() to call new RuleBasedCollator(Locale&) * constructor. General clean up and documentation. * 2/20/97 helena Added clone, operator==, operator!=, operator=, and copy * constructor. * 05/06/97 helena Added memory allocation error detection. * 05/08/97 helena Added createInstance(). * 6/20/97 helena Java class name change. * 04/23/99 stephen Removed EDecompositionMode, merged with * Normalizer::EMode * 11/23/9 srl Inlining of some critical functions * 01/29/01 synwee Modified into a C++ wrapper calling C APIs (ucol.h) */ #include "unicode/utypes.h" #if !UCONFIG_NO_COLLATION #include "unicode/coll.h" #include "unicode/tblcoll.h" #include "ucol_imp.h" #include "cstring.h" #include "cmemory.h" #include "umutex.h" #include "servloc.h" #include "ustrenum.h" #include "uresimp.h" #include "ucln_in.h" static U_NAMESPACE_QUALIFIER Locale* availableLocaleList = NULL; static int32_t availableLocaleListCount; static U_NAMESPACE_QUALIFIER ICULocaleService* gService = NULL; /** * Release all static memory held by collator. */ U_CDECL_BEGIN static UBool U_CALLCONV collator_cleanup(void) { #if !UCONFIG_NO_SERVICE if (gService) { delete gService; gService = NULL; } #endif if (availableLocaleList) { delete []availableLocaleList; availableLocaleList = NULL; } availableLocaleListCount = 0; return TRUE; } U_CDECL_END U_NAMESPACE_BEGIN #if !UCONFIG_NO_SERVICE // ------------------------------------------ // // Registration // //------------------------------------------- CollatorFactory::~CollatorFactory() {} //------------------------------------------- UBool CollatorFactory::visible(void) const { return TRUE; } //------------------------------------------- UnicodeString& CollatorFactory::getDisplayName(const Locale& objectLocale, const Locale& displayLocale, UnicodeString& result) { return objectLocale.getDisplayName(displayLocale, result); } // ------------------------------------- class ICUCollatorFactory : public ICUResourceBundleFactory { public: ICUCollatorFactory(): ICUResourceBundleFactory(UnicodeString(U_ICUDATA_COLL, -1, US_INV)) { } protected: virtual UObject* create(const ICUServiceKey& key, const ICUService* service, UErrorCode& status) const; }; UObject* ICUCollatorFactory::create(const ICUServiceKey& key, const ICUService* /* service */, UErrorCode& status) const { if (handlesKey(key, status)) { const LocaleKey& lkey = (const LocaleKey&)key; Locale loc; // make sure the requested locale is correct // default LocaleFactory uses currentLocale since that's the one vetted by handlesKey // but for ICU rb resources we use the actual one since it will fallback again lkey.canonicalLocale(loc); return Collator::makeInstance(loc, status); } return NULL; } // ------------------------------------- class ICUCollatorService : public ICULocaleService { public: ICUCollatorService() : ICULocaleService(UNICODE_STRING_SIMPLE("Collator")) { UErrorCode status = U_ZERO_ERROR; registerFactory(new ICUCollatorFactory(), status); } virtual UObject* cloneInstance(UObject* instance) const { return ((Collator*)instance)->clone(); } virtual UObject* handleDefault(const ICUServiceKey& key, UnicodeString* actualID, UErrorCode& status) const { LocaleKey& lkey = (LocaleKey&)key; if (actualID) { // Ugly Hack Alert! We return an empty actualID to signal // to callers that this is a default object, not a "real" // service-created object. (TODO remove in 3.0) [aliu] actualID->truncate(0); } Locale loc(""); lkey.canonicalLocale(loc); return Collator::makeInstance(loc, status); } virtual UObject* getKey(ICUServiceKey& key, UnicodeString* actualReturn, UErrorCode& status) const { UnicodeString ar; if (actualReturn == NULL) { actualReturn = &ar; } Collator* result = (Collator*)ICULocaleService::getKey(key, actualReturn, status); // Ugly Hack Alert! If the actualReturn length is zero, this // means we got a default object, not a "real" service-created // object. We don't call setLocales() on a default object, // because that will overwrite its correct built-in locale // metadata (valid & actual) with our incorrect data (all we // have is the requested locale). (TODO remove in 3.0) [aliu] if (result && actualReturn->length() > 0) { const LocaleKey& lkey = (const LocaleKey&)key; Locale canonicalLocale(""); Locale currentLocale(""); LocaleUtility::initLocaleFromName(*actualReturn, currentLocale); result->setLocales(lkey.canonicalLocale(canonicalLocale), currentLocale, currentLocale); } return result; } virtual UBool isDefault() const { return countFactories() == 1; } }; // ------------------------------------- static ICULocaleService* getService(void) { UBool needInit; UMTX_CHECK(NULL, (UBool)(gService == NULL), needInit); if(needInit) { ICULocaleService *newservice = new ICUCollatorService(); if(newservice) { umtx_lock(NULL); if(gService == NULL) { gService = newservice; newservice = NULL; } umtx_unlock(NULL); } if(newservice) { delete newservice; } else { ucln_i18n_registerCleanup(UCLN_I18N_COLLATOR, collator_cleanup); } } return gService; } // ------------------------------------- static inline UBool hasService(void) { UBool retVal; UMTX_CHECK(NULL, gService != NULL, retVal); return retVal; } // ------------------------------------- UCollator* Collator::createUCollator(const char *loc, UErrorCode *status) { UCollator *result = 0; if (status && U_SUCCESS(*status) && hasService()) { Locale desiredLocale(loc); Collator *col = (Collator*)gService->get(desiredLocale, *status); RuleBasedCollator *rbc; if (col && (rbc = dynamic_cast<RuleBasedCollator *>(col))) { if (!rbc->dataIsOwned) { result = ucol_safeClone(rbc->ucollator, NULL, NULL, status); } else { result = rbc->ucollator; rbc->ucollator = NULL; // to prevent free on delete } } delete col; } return result; } #endif /* UCONFIG_NO_SERVICE */ static UBool isAvailableLocaleListInitialized(UErrorCode &status) { // for now, there is a hardcoded list, so just walk through that list and set it up. UBool needInit; UMTX_CHECK(NULL, availableLocaleList == NULL, needInit); if (needInit) { UResourceBundle *index = NULL; UResourceBundle installed; Locale * temp; int32_t i = 0; int32_t localeCount; ures_initStackObject(&installed); index = ures_openDirect(U_ICUDATA_COLL, "res_index", &status); ures_getByKey(index, "InstalledLocales", &installed, &status); if(U_SUCCESS(status)) { localeCount = ures_getSize(&installed); temp = new Locale[localeCount]; if (temp != NULL) { ures_resetIterator(&installed); while(ures_hasNext(&installed)) { const char *tempKey = NULL; ures_getNextString(&installed, NULL, &tempKey, &status); temp[i++] = Locale(tempKey); } umtx_lock(NULL); if (availableLocaleList == NULL) { availableLocaleListCount = localeCount; availableLocaleList = temp; temp = NULL; ucln_i18n_registerCleanup(UCLN_I18N_COLLATOR, collator_cleanup); } umtx_unlock(NULL); needInit = FALSE; if (temp) { delete []temp; } } ures_close(&installed); } ures_close(index); } return !needInit; } // Collator public methods ----------------------------------------------- Collator* U_EXPORT2 Collator::createInstance(UErrorCode& success) { return createInstance(Locale::getDefault(), success); } Collator* U_EXPORT2 Collator::createInstance(const Locale& desiredLocale, UErrorCode& status) { if (U_FAILURE(status)) return 0; #if !UCONFIG_NO_SERVICE if (hasService()) { Locale actualLoc; Collator *result = (Collator*)gService->get(desiredLocale, &actualLoc, status); // Ugly Hack Alert! If the returned locale is empty (not root, // but empty -- getName() == "") then that means the service // returned a default object, not a "real" service object. In // that case, the locale metadata (valid & actual) is setup // correctly already, and we don't want to overwrite it. (TODO // remove in 3.0) [aliu] if (*actualLoc.getName() != 0) { result->setLocales(desiredLocale, actualLoc, actualLoc); } return result; } #endif return makeInstance(desiredLocale, status); } Collator* Collator::makeInstance(const Locale& desiredLocale, UErrorCode& status) { // A bit of explanation is required here. Although in the current // implementation // Collator::createInstance() is just turning around and calling // RuleBasedCollator(Locale&), this will not necessarily always be the // case. For example, suppose we modify this code to handle a // non-table-based Collator, such as that for Thai. In this case, // createInstance() will have to be modified to somehow determine this fact // (perhaps a field in the resource bundle). Then it can construct the // non-table-based Collator in some other way, when it sees that it needs // to. // The specific caution is this: RuleBasedCollator(Locale&) will ALWAYS // return a valid collation object, if the system is functioning properly. // The reason is that it will fall back, use the default locale, and even // use the built-in default collation rules. THEREFORE, createInstance() // should in general ONLY CALL RuleBasedCollator(Locale&) IF IT KNOWS IN // ADVANCE that the given locale's collation is properly implemented as a // RuleBasedCollator. // Currently, we don't do this...we always return a RuleBasedCollator, // whether it is strictly correct to do so or not, without checking, because // we currently have no way of checking. RuleBasedCollator* collation = new RuleBasedCollator(desiredLocale, status); /* test for NULL */ if (collation == 0) { status = U_MEMORY_ALLOCATION_ERROR; return 0; } if (U_FAILURE(status)) { delete collation; collation = 0; } return collation; } #ifdef U_USE_COLLATION_OBSOLETE_2_6 // !!! dlf the following is obsolete, ignore registration for this Collator * Collator::createInstance(const Locale &loc, UVersionInfo version, UErrorCode &status) { Collator *collator; UVersionInfo info; collator=new RuleBasedCollator(loc, status); /* test for NULL */ if (collator == 0) { status = U_MEMORY_ALLOCATION_ERROR; return 0; } if(U_SUCCESS(status)) { collator->getVersion(info); if(0!=uprv_memcmp(version, info, sizeof(UVersionInfo))) { delete collator; status=U_MISSING_RESOURCE_ERROR; return 0; } } return collator; } #endif // implement deprecated, previously abstract method Collator::EComparisonResult Collator::compare(const UnicodeString& source, const UnicodeString& target) const { UErrorCode ec = U_ZERO_ERROR; return (Collator::EComparisonResult)compare(source, target, ec); } // implement deprecated, previously abstract method Collator::EComparisonResult Collator::compare(const UnicodeString& source, const UnicodeString& target, int32_t length) const { UErrorCode ec = U_ZERO_ERROR; return (Collator::EComparisonResult)compare(source, target, length, ec); } // implement deprecated, previously abstract method Collator::EComparisonResult Collator::compare(const UChar* source, int32_t sourceLength, const UChar* target, int32_t targetLength) const { UErrorCode ec = U_ZERO_ERROR; return (Collator::EComparisonResult)compare(source, sourceLength, target, targetLength, ec); } UCollationResult Collator::compare(UCharIterator &/*sIter*/, UCharIterator &/*tIter*/, UErrorCode &status) const { if(U_SUCCESS(status)) { // Not implemented in the base class. status = U_UNSUPPORTED_ERROR; } return UCOL_EQUAL; } UCollationResult Collator::compareUTF8(const StringPiece &source, const StringPiece &target, UErrorCode &status) const { if(U_FAILURE(status)) { return UCOL_EQUAL; } UCharIterator sIter, tIter; uiter_setUTF8(&sIter, source.data(), source.length()); uiter_setUTF8(&tIter, target.data(), target.length()); return compare(sIter, tIter, status); } UBool Collator::equals(const UnicodeString& source, const UnicodeString& target) const { UErrorCode ec = U_ZERO_ERROR; return (compare(source, target, ec) == UCOL_EQUAL); } UBool Collator::greaterOrEqual(const UnicodeString& source, const UnicodeString& target) const { UErrorCode ec = U_ZERO_ERROR; return (compare(source, target, ec) != UCOL_LESS); } UBool Collator::greater(const UnicodeString& source, const UnicodeString& target) const { UErrorCode ec = U_ZERO_ERROR; return (compare(source, target, ec) == UCOL_GREATER); } // this API ignores registered collators, since it returns an // array of indefinite lifetime const Locale* U_EXPORT2 Collator::getAvailableLocales(int32_t& count) { UErrorCode status = U_ZERO_ERROR; Locale *result = NULL; count = 0; if (isAvailableLocaleListInitialized(status)) { result = availableLocaleList; count = availableLocaleListCount; } return result; } UnicodeString& U_EXPORT2 Collator::getDisplayName(const Locale& objectLocale, const Locale& displayLocale, UnicodeString& name) { #if !UCONFIG_NO_SERVICE if (hasService()) { UnicodeString locNameStr; LocaleUtility::initNameFromLocale(objectLocale, locNameStr); return gService->getDisplayName(locNameStr, name, displayLocale); } #endif return objectLocale.getDisplayName(displayLocale, name); } UnicodeString& U_EXPORT2 Collator::getDisplayName(const Locale& objectLocale, UnicodeString& name) { return getDisplayName(objectLocale, Locale::getDefault(), name); } /* This is useless information */ /*void Collator::getVersion(UVersionInfo versionInfo) const { if (versionInfo!=NULL) uprv_memcpy(versionInfo, fVersion, U_MAX_VERSION_LENGTH); } */ // UCollator protected constructor destructor ---------------------------- /** * Default constructor. * Constructor is different from the old default Collator constructor. * The task for determing the default collation strength and normalization mode * is left to the child class. */ Collator::Collator() : UObject() { } /** * Constructor. * Empty constructor, does not handle the arguments. * This constructor is done for backward compatibility with 1.7 and 1.8. * The task for handling the argument collation strength and normalization * mode is left to the child class. * @param collationStrength collation strength * @param decompositionMode * @deprecated 2.4 use the default constructor instead */ Collator::Collator(UCollationStrength, UNormalizationMode ) : UObject() { } Collator::~Collator() { } Collator::Collator(const Collator &other) : UObject(other) { } UBool Collator::operator==(const Collator& other) const { return (UBool)(this == &other); } UBool Collator::operator!=(const Collator& other) const { return (UBool)!(*this == other); } int32_t U_EXPORT2 Collator::getBound(const uint8_t *source, int32_t sourceLength, UColBoundMode boundType, uint32_t noOfLevels, uint8_t *result, int32_t resultLength, UErrorCode &status) { return ucol_getBound(source, sourceLength, boundType, noOfLevels, result, resultLength, &status); } void Collator::setLocales(const Locale& /* requestedLocale */, const Locale& /* validLocale */, const Locale& /*actualLocale*/) { } UnicodeSet *Collator::getTailoredSet(UErrorCode &status) const { if(U_FAILURE(status)) { return NULL; } // everything can be changed return new UnicodeSet(0, 0x10FFFF); } // ------------------------------------- #if !UCONFIG_NO_SERVICE URegistryKey U_EXPORT2 Collator::registerInstance(Collator* toAdopt, const Locale& locale, UErrorCode& status) { if (U_SUCCESS(status)) { return getService()->registerInstance(toAdopt, locale, status); } return NULL; } // ------------------------------------- class CFactory : public LocaleKeyFactory { private: CollatorFactory* _delegate; Hashtable* _ids; public: CFactory(CollatorFactory* delegate, UErrorCode& status) : LocaleKeyFactory(delegate->visible() ? VISIBLE : INVISIBLE) , _delegate(delegate) , _ids(NULL) { if (U_SUCCESS(status)) { int32_t count = 0; _ids = new Hashtable(status); if (_ids) { const UnicodeString * idlist = _delegate->getSupportedIDs(count, status); for (int i = 0; i < count; ++i) { _ids->put(idlist[i], (void*)this, status); if (U_FAILURE(status)) { delete _ids; _ids = NULL; return; } } } else { status = U_MEMORY_ALLOCATION_ERROR; } } } virtual ~CFactory() { delete _delegate; delete _ids; } virtual UObject* create(const ICUServiceKey& key, const ICUService* service, UErrorCode& status) const; protected: virtual const Hashtable* getSupportedIDs(UErrorCode& status) const { if (U_SUCCESS(status)) { return _ids; } return NULL; } virtual UnicodeString& getDisplayName(const UnicodeString& id, const Locale& locale, UnicodeString& result) const; }; UObject* CFactory::create(const ICUServiceKey& key, const ICUService* /* service */, UErrorCode& status) const { if (handlesKey(key, status)) { const LocaleKey& lkey = (const LocaleKey&)key; Locale validLoc; lkey.currentLocale(validLoc); return _delegate->createCollator(validLoc); } return NULL; } UnicodeString& CFactory::getDisplayName(const UnicodeString& id, const Locale& locale, UnicodeString& result) const { if ((_coverage & 0x1) == 0) { UErrorCode status = U_ZERO_ERROR; const Hashtable* ids = getSupportedIDs(status); if (ids && (ids->get(id) != NULL)) { Locale loc; LocaleUtility::initLocaleFromName(id, loc); return _delegate->getDisplayName(loc, locale, result); } } result.setToBogus(); return result; } URegistryKey U_EXPORT2 Collator::registerFactory(CollatorFactory* toAdopt, UErrorCode& status) { if (U_SUCCESS(status)) { CFactory* f = new CFactory(toAdopt, status); if (f) { return getService()->registerFactory(f, status); } status = U_MEMORY_ALLOCATION_ERROR; } return NULL; } // ------------------------------------- UBool U_EXPORT2 Collator::unregister(URegistryKey key, UErrorCode& status) { if (U_SUCCESS(status)) { if (hasService()) { return gService->unregister(key, status); } status = U_ILLEGAL_ARGUMENT_ERROR; } return FALSE; } #endif /* UCONFIG_NO_SERVICE */ class CollationLocaleListEnumeration : public StringEnumeration { private: int32_t index; public: static UClassID U_EXPORT2 getStaticClassID(void); virtual UClassID getDynamicClassID(void) const; public: CollationLocaleListEnumeration() : index(0) { // The global variables should already be initialized. //isAvailableLocaleListInitialized(status); } virtual ~CollationLocaleListEnumeration() { } virtual StringEnumeration * clone() const { CollationLocaleListEnumeration *result = new CollationLocaleListEnumeration(); if (result) { result->index = index; } return result; } virtual int32_t count(UErrorCode &/*status*/) const { return availableLocaleListCount; } virtual const char* next(int32_t* resultLength, UErrorCode& /*status*/) { const char* result; if(index < availableLocaleListCount) { result = availableLocaleList[index++].getName(); if(resultLength != NULL) { *resultLength = (int32_t)uprv_strlen(result); } } else { if(resultLength != NULL) { *resultLength = 0; } result = NULL; } return result; } virtual const UnicodeString* snext(UErrorCode& status) { int32_t resultLength = 0; const char *s = next(&resultLength, status); return setChars(s, resultLength, status); } virtual void reset(UErrorCode& /*status*/) { index = 0; } }; UOBJECT_DEFINE_RTTI_IMPLEMENTATION(CollationLocaleListEnumeration) // ------------------------------------- StringEnumeration* U_EXPORT2 Collator::getAvailableLocales(void) { #if !UCONFIG_NO_SERVICE if (hasService()) { return getService()->getAvailableLocales(); } #endif /* UCONFIG_NO_SERVICE */ UErrorCode status = U_ZERO_ERROR; if (isAvailableLocaleListInitialized(status)) { return new CollationLocaleListEnumeration(); } return NULL; } StringEnumeration* U_EXPORT2 Collator::getKeywords(UErrorCode& status) { // This is a wrapper over ucol_getKeywords UEnumeration* uenum = ucol_getKeywords(&status); if (U_FAILURE(status)) { uenum_close(uenum); return NULL; } return new UStringEnumeration(uenum); } StringEnumeration* U_EXPORT2 Collator::getKeywordValues(const char *keyword, UErrorCode& status) { // This is a wrapper over ucol_getKeywordValues UEnumeration* uenum = ucol_getKeywordValues(keyword, &status); if (U_FAILURE(status)) { uenum_close(uenum); return NULL; } return new UStringEnumeration(uenum); } StringEnumeration* U_EXPORT2 Collator::getKeywordValuesForLocale(const char* key, const Locale& locale, UBool commonlyUsed, UErrorCode& status) { // This is a wrapper over ucol_getKeywordValuesForLocale UEnumeration *uenum = ucol_getKeywordValuesForLocale(key, locale.getName(), commonlyUsed, &status); if (U_FAILURE(status)) { uenum_close(uenum); return NULL; } return new UStringEnumeration(uenum); } Locale U_EXPORT2 Collator::getFunctionalEquivalent(const char* keyword, const Locale& locale, UBool& isAvailable, UErrorCode& status) { // This is a wrapper over ucol_getFunctionalEquivalent char loc[ULOC_FULLNAME_CAPACITY]; /*int32_t len =*/ ucol_getFunctionalEquivalent(loc, sizeof(loc), keyword, locale.getName(), &isAvailable, &status); if (U_FAILURE(status)) { *loc = 0; // root } return Locale::createFromName(loc); } int32_t U_EXPORT2 Collator::getReorderCodes(int32_t *dest, int32_t destCapacity, UErrorCode& status) const { if (U_SUCCESS(status)) { status = U_UNSUPPORTED_ERROR; } return 0; } void U_EXPORT2 Collator::setReorderCodes(const int32_t *reorderCodes, int32_t reorderCodesLength, UErrorCode& status) { if (U_SUCCESS(status)) { status = U_UNSUPPORTED_ERROR; } } int32_t U_EXPORT2 Collator::getEquivalentReorderCodes(int32_t reorderCode, int32_t *dest, int32_t destCapacity, UErrorCode& status) { if (U_SUCCESS(status)) { status = U_UNSUPPORTED_ERROR; } return 0; } // UCollator private data members ---------------------------------------- /* This is useless information */ /*const UVersionInfo Collator::fVersion = {1, 1, 0, 0};*/ // ------------------------------------- U_NAMESPACE_END #endif /* #if !UCONFIG_NO_COLLATION */ /* eof */
[ "claireho@251d0590-4201-4cf1-90de-194747b24ca1" ]
claireho@251d0590-4201-4cf1-90de-194747b24ca1
d9409e83ba3cafef5c8b2d98590a2e92a9f254f6
3b0dc93b88bb8043bcab2c7b3f1d7be64a58db25
/sketch_feb08c_pwm/sketch_feb08c_pwm.ino
356b21a153acd10575d6cb358c01d4ed62a75092
[]
no_license
nikparam/arduino_stuff
401e552358cae43fb18f7caf56fe74ad9b22236f
a3e7c73ee55f9adb797088269428408b2fe48f59
refs/heads/master
2021-05-02T09:09:31.265159
2018-02-08T21:07:37
2018-02-08T21:07:37
120,817,890
0
0
null
null
null
null
UTF-8
C++
false
false
285
ino
int LEDpin = 9; void setup() { pinMode( LEDpin, OUTPUT ); } void loop() { for( int i = 0; i <= 255; i++ ) { analogWrite( LEDpin, i); delay(10); } delay(1000); for( int i = 255; i >= 0; i-- ) { analogWrite( LEDpin, i); delay(10); } delay(1000); }
[ "nikparam@yandex.ru" ]
nikparam@yandex.ru
7e335fe1a0f59a6d1d5294f333878d2f019fb083
ee1820f94178fdfa93eceb6dd2cb9b9d9c95b72a
/ITSA/C_OT13.cpp
324ef54a2c5dd18f255fb69d94c3881e882fb558
[]
no_license
asd0012/ITSA
3a2f6c8a829c08d49ac0be951514f1bd2ee47989
05879bf4c13db4c75588b8135942bda8bbcc0456
refs/heads/master
2020-06-07T08:05:21.205082
2019-06-21T02:56:59
2019-06-21T02:56:59
192,969,053
0
0
null
null
null
null
UTF-8
C++
false
false
261
cpp
#include<stdio.h> #include<stdlib.h> #include<iostream> using namespace std; int main() { float x1,x2; float y1,y2; //freopen("input.txt","r",stdin); cin>>x1>>y1; cin>>x2>>y2; cout<<(y1-y2)/(x1-x2)<<endl; return 0; }
[ "noreply@github.com" ]
asd0012.noreply@github.com
9df454f540d88bc174eddad5c6079ec6dfbd4923
b48cc66bf4f5a173338e42ba02245da043e71ce7
/LuoguCodes/CF784F.cpp
f45efa4eb51331917f68773070ab1ab2bea40bea
[ "MIT" ]
permissive
Anguei/OI-Codes
6f79f5c446e87b13c6bffe3cc758c722e8d0d65c
0ef271e9af0619d4c236e314cd6d8708d356536a
refs/heads/master
2020-04-22T22:18:14.531234
2019-02-14T14:24:36
2019-02-14T14:24:36
170,703,285
1
0
null
null
null
null
UTF-8
C++
false
false
458
cpp
//【CF784F】Crunching Numbers Just for You - 洛谷 - Uk #include <chrono> #include <thread> #include <vector> #include <iostream> #include <algorithm> int main() { int n; std::cin >> n; std::vector<int> v; for (int i = 1; i <= n; ++i) { int t; std::cin >> t; v.push_back(t); } std::sort(v.begin(), v.end()); long long start = clock(); while (clock() - start < 1142) ; for (auto i : v) std::cout << i << " "; std::cout << std::endl; }
[ "Anguei@users.noreply.github.com" ]
Anguei@users.noreply.github.com
cebb91591cec78f102b8dd282bb4e64ec7358df9
3cc5872c4c534ccd0349d34e860ff41a8c072e90
/hw_2/main.cpp
f722882a08a2515fe62cf30e0ce367645ffde064
[]
no_license
bear24rw/EECE6086
253f2be5f25f06c9748384ad33936f4ad3608d01
3b25ed6951514fbb91fab47300c5a213fe62f555
refs/heads/master
2021-01-10T19:11:41.214890
2014-04-19T03:43:22
2014-04-19T03:43:22
17,157,280
1
0
null
null
null
null
UTF-8
C++
false
false
7,001
cpp
#include <stdlib.h> #include <stdio.h> #include <errno.h> #include <math.h> #include <string.h> #include <fstream> #include <algorithm> #include <string> #include <ctime> #include "main.h" #include "place.h" #include "route.h" #include "magic.h" #include "svg.h" #include "report.h" int num_nets; int num_cells; std::string filename; clock_t start_time; clock_t place_time; clock_t route_time; clock_t end_time; int main(int argc, char *argv[]) { start_time = std::clock(); // // Get number of cells and nets // if (argc < 2) { dprintf("Usage: ./main inputfile\n"); return EINVAL; } filename = argv[1]; std::ifstream fp(filename); if(fp.fail()) { dprintf("Cannot open file.\n"); return ENOENT; } fp >> num_cells; fp >> num_nets; dprintf("Found %d cells and %d nets\n", num_cells, num_nets); // // Generate all cells // std::vector<cell_t> cells(num_cells); for (int i=0; i<num_cells; i++) { cells[i].number = i; } // // Read all the nets // for (int net, cell_a, term_a, cell_b, term_b; fp >> net >> cell_a >> term_a >> cell_b >> term_b;) { // subtract 1 from all the numbers to 0 index them cell_a--; cell_b--; term_a--; term_b--; // create symetric connection for each net cells[cell_a].terms[term_a].dest_cell = &cells[cell_b]; cells[cell_b].terms[term_b].dest_cell = &cells[cell_a]; cells[cell_a].terms[term_a].dest_term = &cells[cell_b].terms[term_b]; cells[cell_b].terms[term_b].dest_term = &cells[cell_a].terms[term_a]; cells[cell_a].terms[term_a].label = net; cells[cell_b].terms[term_b].label = net; cells[cell_a].num_connections++; cells[cell_b].num_connections++; } // // Place // rows_t rows = place(cells); calculate_x_values(rows); calculate_term_positions(rows); place_time = std::clock(); // // Route // channels_t channels = route(rows); calculate_y_values(rows, channels); calculate_term_positions(rows); calculate_track_positions(channels); route_time = std::clock(); // // Output files and reports // write_magic(rows, channels); write_svg(rows, channels); end_time = std::clock(); write_report(rows, channels); } void calculate_x_values(rows_t& rows) { // update the absolute x position of each cell in each row for (auto &row : rows) { int current_x = 0; for (auto &cell : row) { cell->position.x = current_x; // feed through cells are 3 wide, normal cells are 6 wide // every cell has a seperation of 1 if (cell->feed_through) current_x += 4; else current_x += 7; } } } void calculate_y_values(rows_t& rows, channels_t& channels) { // update the absolute y position of each cell in each row based // on the height of the channel between the rows int current_y = 0; for (unsigned int i=0; i<channels.size()-1; i++) { current_y += channels[i].tracks.size() * (TRACK_WIDTH + TRACK_SPACING); for (auto &cell : rows[i]) { cell->position.y = current_y; } current_y += CELL_HEIGHT + CELL_SPACING; } } void calculate_term_positions(rows_t& rows) { // calculates the absolute xy position of each term within each cell for (auto &row : rows) { for (auto &cell : row) { for (auto &term : cell->terms) { term.position = get_term_position(term); } } } } void calculate_term_positions(cell_t* cell) { // calculates the absolute xy position of each term within each cell for (auto &term : cell->terms) { term.position = get_term_position(term); } } point_t get_term_position(term_t& term) { // // Returns the absolute world position of this terminal // // coordinates of terminals are -1 from what is given in // the pdf since we want to work with 0 based indexing point_t offsets[] = {{1,5}, {4,5}, {1,0}, {4,0}}; point_t offsets_x[] = {{1,0}, {4,0}, {1,5}, {4,5}}; point_t offsets_y[] = {{4,5}, {1,5}, {4,0}, {1,0}}; point_t offsets_xy[] = {{4,0}, {1,0}, {4,5}, {1,5}}; point_t offsets_ft[] = {{1,5}, {1,0}}; point_t term_position = offsets[term.number]; if (term.cell->feed_through) return term.cell->position + offsets_ft[term.number]; if (term.cell->flip_x) { term_position = offsets_x[term.number]; } if (term.cell->flip_y) { term_position = offsets_y[term.number]; } if (term.cell->flip_x && term.cell->flip_y) { term_position = offsets_xy[term.number]; } return term.cell->position + term_position; } void calculate_track_positions(channels_t& channels) { for (auto &channel : channels) { for (auto &term : channel.terms) { int y = term->position.y; if (term->on_top()) { y += 1 + CELL_SPACING + term->track_num * (TRACK_WIDTH + TRACK_SPACING); } else { y -= 1 + CELL_SPACING + (channel.tracks.size()-1 - term->track_num) * (TRACK_WIDTH + TRACK_SPACING); } term->track_y = y; } } } int total_wire_length(channels_t& channels) { int length = 0; for (auto &channel : channels) { for (auto &term : channel.terms) { if (term->dest_cell == nullptr) continue; if (term->track_num == VERTICAL) { length += abs(term->position.y - term->dest_term->position.y); continue; } if (term->on_top() == term->dest_term->on_top()) { length += abs(term->position.x - term->dest_term->position.x)+1; length += abs(term->position.y - term->track_y) * 2; continue; } length += abs(term->position.x - term->dest_term->position.x) + 1; length += abs(term->position.y - term->dest_term->position.y); } } length = length / 2; return length; } point_t bounding_box(rows_t& rows, channels_t* channels) { point_t biggest(0,0); // Y dimension biggest.y = rows.size() * 6; if (channels != nullptr) { for (auto &channel : *channels) { biggest.y += channel.tracks.size() * 2 + 1; } // outer 2 channels don't have the +1 biggest.y -= 2; } // X dimension for (auto &row : rows) { int current_x = 0; for (auto &cell : row) { if (cell == nullptr) { current_x += 6; } else { current_x = cell->position.x; current_x += cell->feed_through ? 3 : 6; } } if (current_x > biggest.x) biggest.x = current_x; } return biggest; }
[ "bear24rw@gmail.com" ]
bear24rw@gmail.com
068148f3a18602bc9e995c4435c3f295a719912e
678fe6c52cf30a7a7881090978f97ef8c89f1ad3
/generator.hpp
dae58c5cb596c9ba6ea993f72468b2b14b6d0bb3
[]
no_license
jm-boley/python_equivs
89d57cf98be7c2820554859dfd9a4012c789d56e
d0439d0d0893f94c6f587fc19c649140d850d155
refs/heads/main
2023-01-13T00:32:04.548032
2020-10-23T20:47:36
2020-10-23T20:47:36
306,742,027
0
0
null
null
null
null
UTF-8
C++
false
false
5,666
hpp
#ifndef PYGEN_H_ #define PYGEN_H_ #pragma once #include <functional> #include <iterator> #include <utility> #include <type_traits> #include <memory> #include <chrono> #include <random> #include <exception> namespace PythonicUtils { template <typename _Rs> class GenIter; template <typename _Rs> class Generator { inline void throw_if_expired() { if (stopped_) throw std::runtime_error("begin() called on expired generator"); } public: using iter = GenIter<_Rs>; // TODO: // Poke through C++ stdlib and figure out how STL container // type traits are handled Generator(std::function<_Rs(bool*)>& func) : func_(func), uid_(0), stopped_(false) { std::mt19937_64 rng(std::chrono::steady_clock::now().time_since_epoch().count()); std::exponential_distribution<double> edistr(3.5); uid_ = edistr(rng); } Generator(const Generator&) = delete; Generator(Generator&& other) : func_(other.func_), uid_(other.uid_), stopped_(other.stopped_) { throw_if_expired(); // !!! Make sure this is a good idea !!! // Is it necessary? begin() throws... other.uid_ = 0; other.stopped_ = true; } GenIter<_Rs> begin() { throw_if_expired(); return GenIter<_Rs>(func_, &uid_, &stopped_); } GenIter<_Rs> end() { return GenIter<_Rs>(&uid_, &stopped_); } void reset() { stopped_ = false; } private: std::function<_Rs(bool*)>& func_; double uid_; bool stopped_; }; template <typename _Rs> class GenIter : public std::iterator<std::forward_iterator_tag, _Rs> { friend class Generator<_Rs>; inline void incr_throw_uid_invalid_stopped() { if (this->uid_ == nullptr || *(this->stop_)) throw std::runtime_error("GenIter: Attempted to increment an invalidated iterator"); } public: // using iterator_category = std::forward_iterator_tag; GenIter(std::function<_Rs(bool*)>& func, double* gid, bool* stop) noexcept : gen_func_(func), result_(func(stop)), uid_(gid), stop_(stop) {} GenIter(const GenIter& other) : gen_func_(other.gen_func_), result_(other.result_), uid_(other.uid_), stop_(other.stop_) { if (other.uid_ == nullptr) throw std::invalid_argument("GenIter: Attempted to copy-construct from an invalidated iterator"); } GenIter(GenIter&& other) : gen_func_(other.gen_func_), result_(other.result_), uid_(other.uid_), stop_(other.stop_) { if (other.uid_ == nullptr) throw std::invalid_argument("GenIter: Attempted to move-construct from an invalidated iterator"); other.uid_ = nullptr; other.stop_ = nullptr; } GenIter& operator=(const GenIter& other) { if (this != &other) { if (other.uid_ == nullptr) throw std::invalid_argument("GenIter: Attempted to copy-assign from an invalidated iterator"); this->gen_func_ = other.gen_func_; this->result_ = other.result_; this->uid_ = other.uid_; this->stop_ = other.stop_; } } GenIter& operator=(GenIter&& other) { if (this != &other) { if (other.uid_ == nullptr) throw std::invalid_argument("GenIter: Attempted to move-assign from an invalidated iterator"); this->gen_func_ = other.gen_func_; this->result_ = other.result_; this->uid_ = other.uid_; this->stop_ = other.stop_; other.uid_ = nullptr; other.stop_ = nullptr; } } GenIter& operator++() { // This is probably bad behavior, look into idiomatic handling of client use of invalidated iterators incr_throw_uid_invalid_stopped(); result_ = gen_func_(stop_); return *this; } GenIter operator++(int) { // This is probably bad behavior, look into idiomatic handling of client use of invalidated iterators incr_throw_uid_invalid_stopped(); auto rval = GenIter(*this); result_ = gen_func_(stop_); return rval; } bool operator!=(const GenIter& other) const { if (other.uid_ == nullptr) return true; return *uid_ != *other.uid_ || !(*stop_); } bool operator!=(const GenIter&& other) const { if (other.uid_ == nullptr) return true; return *uid_ != *other.uid_ || !(*stop_); } _Rs operator*() const { if (this->uid_ == nullptr || *(this->stop_)) throw std::runtime_error("GenIter: Attempted to access an invalidated iterator"); return result_; } private: // Special empty lambda used when Generator class wants to construct an end() iterator static std::function<_Rs(bool*)>& empty_lambda() { static std::function<_Rs(bool*)> rval = [](bool*) { return _Rs(); }; return rval; } // Generator-only constructor, used when end() is called GenIter(double* gid, bool* stop) noexcept : gen_func_(empty_lambda()), result_(_Rs()), uid_(gid), stop_(stop) {} std::function<_Rs(bool*)>& gen_func_; _Rs result_; // This is a problem if copy-construction is expensive double* uid_; bool* stop_; }; template <typename _Rs> Generator<_Rs> make_generator(std::function<_Rs(bool*)>& func) { return Generator<_Rs> {func}; } } # PythonicUtils #endif
[ "noreply@github.com" ]
jm-boley.noreply@github.com
f3648ea5d94db5ee37e52b1e79484b9db3b5e4b5
e0234d89a6f7890a8afd8cca3a87395aafd895bc
/fluid_vis/fluid_vis/BaseException.h
6322de710ff5217a308364ea17864cfb3a1b64f0
[]
no_license
piotrekjanisz/master_thesis
175ef08e09cff6a5bb1ab0b997565ae146d10e55
91e86153f2b096f076042114bd27294be2cc16bb
refs/heads/master
2020-05-17T10:43:49.708325
2011-07-06T12:19:13
2011-07-06T12:19:13
1,629,657
0
0
null
null
null
null
UTF-8
C++
false
false
269
h
#pragma once #include <exception> #include <string> class BaseException : public std::exception { std::string _msg; public: BaseException(const std::string& msg); virtual ~BaseException(void); virtual const char* what() const throw() { return _msg.c_str(); } };
[ "Piotrek@.(none)" ]
Piotrek@.(none)
8eae636bd7dbe1c24aac60e0937c80387f808af9
bb2d45152b6fc2ebe9d1a264175369f75fb5d024
/Arcane/src/Arcane/Vendor/renderdoc-1.x/renderdoc/driver/d3d12/d3d12_debug.cpp
ea9bb677a7e70ca0edb781bac2a199aed6e05028
[ "MIT", "LicenseRef-scancode-unknown-license-reference" ]
permissive
Ershany/Arcane-Engine
b719930e7538dcb99185fa31e0255fd2d2b2383b
94ae49d04359bb79916f61fe7c2130939f88f49d
refs/heads/master
2023-07-27T04:38:23.753293
2023-07-23T22:13:48
2023-07-23T22:13:48
66,559,567
492
42
MIT
2023-07-15T12:33:51
2016-08-25T13:20:39
C++
UTF-8
C++
false
false
83,236
cpp
/****************************************************************************** * The MIT License (MIT) * * Copyright (c) 2019-2022 Baldur Karlsson * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. ******************************************************************************/ #include "d3d12_debug.h" #include "common/shader_cache.h" #include "data/resource.h" #include "driver/dx/official/d3dcompiler.h" #include "driver/dxgi/dxgi_common.h" #include "driver/shaders/dxbc/dxbc_bytecode.h" #include "maths/formatpacking.h" #include "maths/matrix.h" #include "maths/vec.h" #include "strings/string_utils.h" #include "d3d12_command_list.h" #include "d3d12_command_queue.h" #include "d3d12_device.h" #include "d3d12_replay.h" #include "d3d12_shader_cache.h" #include "data/hlsl/hlsl_cbuffers.h" inline static D3D12_ROOT_PARAMETER1 cbvParam(D3D12_SHADER_VISIBILITY vis, UINT space, UINT reg) { D3D12_ROOT_PARAMETER1 ret; ret.ShaderVisibility = vis; ret.ParameterType = D3D12_ROOT_PARAMETER_TYPE_CBV; ret.Descriptor.RegisterSpace = space; ret.Descriptor.ShaderRegister = reg; ret.Descriptor.Flags = D3D12_ROOT_DESCRIPTOR_FLAG_NONE; return ret; } inline static D3D12_ROOT_PARAMETER1 constParam(D3D12_SHADER_VISIBILITY vis, UINT space, UINT reg, UINT num) { D3D12_ROOT_PARAMETER1 ret; ret.ShaderVisibility = vis; ret.ParameterType = D3D12_ROOT_PARAMETER_TYPE_32BIT_CONSTANTS; ret.Constants.RegisterSpace = space; ret.Constants.ShaderRegister = reg; ret.Constants.Num32BitValues = num; return ret; } inline static D3D12_ROOT_PARAMETER1 tableParam(D3D12_SHADER_VISIBILITY vis, D3D12_DESCRIPTOR_RANGE_TYPE type, UINT space, UINT basereg, UINT numreg) { // this is a super hack but avoids the need to be clumsy with allocation of these structs static D3D12_DESCRIPTOR_RANGE1 ranges[32] = {}; static int rangeIdx = 0; D3D12_DESCRIPTOR_RANGE1 &range = ranges[rangeIdx]; rangeIdx = (rangeIdx + 1) % ARRAY_COUNT(ranges); D3D12_ROOT_PARAMETER1 ret; ret.ShaderVisibility = vis; ret.ParameterType = D3D12_ROOT_PARAMETER_TYPE_DESCRIPTOR_TABLE; ret.DescriptorTable.NumDescriptorRanges = 1; ret.DescriptorTable.pDescriptorRanges = &range; RDCEraseEl(range); range.RangeType = type; range.RegisterSpace = space; range.BaseShaderRegister = basereg; range.NumDescriptors = numreg; range.OffsetInDescriptorsFromTableStart = 0; if(type != D3D12_DESCRIPTOR_RANGE_TYPE_SAMPLER) range.Flags = D3D12_DESCRIPTOR_RANGE_FLAG_DATA_VOLATILE | D3D12_DESCRIPTOR_RANGE_FLAG_DESCRIPTORS_VOLATILE; else range.Flags = D3D12_DESCRIPTOR_RANGE_FLAG_DESCRIPTORS_VOLATILE; return ret; } D3D12DebugManager::D3D12DebugManager(WrappedID3D12Device *wrapper) { RenderDoc::Inst().RegisterMemoryRegion(this, sizeof(D3D12DebugManager)); m_pDevice = wrapper; D3D12ResourceManager *rm = wrapper->GetResourceManager(); HRESULT hr = S_OK; D3D12_DESCRIPTOR_HEAP_DESC desc; desc.Flags = D3D12_DESCRIPTOR_HEAP_FLAG_NONE; desc.NodeMask = 1; desc.NumDescriptors = 1024; desc.Type = D3D12_DESCRIPTOR_HEAP_TYPE_RTV; RDCCOMPILE_ASSERT(FIRST_WIN_RTV + 256 < 1024, "Increase size of RTV heap"); hr = m_pDevice->CreateDescriptorHeap(&desc, __uuidof(ID3D12DescriptorHeap), (void **)&rtvHeap); m_pDevice->InternalRef(); if(FAILED(hr)) { RDCERR("Couldn't create RTV descriptor heap! HRESULT: %s", ToStr(hr).c_str()); } rm->SetInternalResource(rtvHeap); desc.NumDescriptors = 64; desc.Type = D3D12_DESCRIPTOR_HEAP_TYPE_DSV; RDCCOMPILE_ASSERT(FIRST_WIN_DSV + 32 < 64, "Increase size of DSV heap"); hr = m_pDevice->CreateDescriptorHeap(&desc, __uuidof(ID3D12DescriptorHeap), (void **)&dsvHeap); m_pDevice->InternalRef(); if(FAILED(hr)) { RDCERR("Couldn't create DSV descriptor heap! HRESULT: %s", ToStr(hr).c_str()); } rm->SetInternalResource(dsvHeap); desc.NumDescriptors = 4096; desc.Type = D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV; RDCCOMPILE_ASSERT(MAX_SRV_SLOT < 4096, "Increase size of CBV/SRV/UAV heap"); hr = m_pDevice->CreateDescriptorHeap(&desc, __uuidof(ID3D12DescriptorHeap), (void **)&uavClearHeap); m_pDevice->InternalRef(); if(FAILED(hr)) { RDCERR("Couldn't create CBV/SRV descriptor heap! HRESULT: %s", ToStr(hr).c_str()); } rm->SetInternalResource(uavClearHeap); desc.Flags = D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE; hr = m_pDevice->CreateDescriptorHeap(&desc, __uuidof(ID3D12DescriptorHeap), (void **)&cbvsrvuavHeap); m_pDevice->InternalRef(); if(FAILED(hr)) { RDCERR("Couldn't create CBV/SRV descriptor heap! HRESULT: %s", ToStr(hr).c_str()); } rm->SetInternalResource(cbvsrvuavHeap); desc.NumDescriptors = 16; desc.Type = D3D12_DESCRIPTOR_HEAP_TYPE_SAMPLER; hr = m_pDevice->CreateDescriptorHeap(&desc, __uuidof(ID3D12DescriptorHeap), (void **)&samplerHeap); m_pDevice->InternalRef(); if(FAILED(hr)) { RDCERR("Couldn't create sampler descriptor heap! HRESULT: %s", ToStr(hr).c_str()); } rm->SetInternalResource(samplerHeap); // create fixed samplers, point and linear D3D12_CPU_DESCRIPTOR_HANDLE samp; samp = samplerHeap->GetCPUDescriptorHandleForHeapStart(); D3D12_SAMPLER_DESC sampDesc; RDCEraseEl(sampDesc); sampDesc.AddressU = sampDesc.AddressV = sampDesc.AddressW = D3D12_TEXTURE_ADDRESS_MODE_CLAMP; sampDesc.Filter = D3D12_FILTER_MIN_MAG_MIP_POINT; sampDesc.MaxAnisotropy = 1; sampDesc.MinLOD = 0; sampDesc.MaxLOD = FLT_MAX; sampDesc.MipLODBias = 0.0f; sampDesc.ComparisonFunc = D3D12_COMPARISON_FUNC_ALWAYS; m_pDevice->CreateSampler(&sampDesc, samp); sampDesc.Filter = D3D12_FILTER_MIN_MAG_LINEAR_MIP_POINT; samp.ptr += sizeof(D3D12Descriptor); m_pDevice->CreateSampler(&sampDesc, samp); static const UINT64 bufsize = 2 * 1024 * 1024; m_RingConstantBuffer = MakeCBuffer(bufsize); m_RingConstantOffset = 0; m_pDevice->InternalRef(); D3D12ShaderCache *shaderCache = m_pDevice->GetShaderCache(); shaderCache->SetCaching(true); { ID3DBlob *root = shaderCache->MakeRootSig({ // cbuffer cbvParam(D3D12_SHADER_VISIBILITY_PIXEL, 0, 0), // normal SRVs (2x, 4x, 8x, 16x, 32x) tableParam(D3D12_SHADER_VISIBILITY_PIXEL, D3D12_DESCRIPTOR_RANGE_TYPE_SRV, 0, 1, 5), // stencil SRVs (2x, 4x, 8x, 16x, 32x) tableParam(D3D12_SHADER_VISIBILITY_PIXEL, D3D12_DESCRIPTOR_RANGE_TYPE_SRV, 0, 11, 5), }); RDCASSERT(root); hr = m_pDevice->CreateRootSignature(0, root->GetBufferPointer(), root->GetBufferSize(), __uuidof(ID3D12RootSignature), (void **)&m_ArrayMSAARootSig); m_pDevice->InternalRef(); SAFE_RELEASE(root); rm->SetInternalResource(m_ArrayMSAARootSig); } { ID3DBlob *root = shaderCache->MakeRootSig( { cbvParam(D3D12_SHADER_VISIBILITY_VERTEX, 0, 0), cbvParam(D3D12_SHADER_VISIBILITY_GEOMETRY, 0, 0), // 'push constant' CBV constParam(D3D12_SHADER_VISIBILITY_PIXEL, 0, 0, 4), }, D3D12_ROOT_SIGNATURE_FLAG_ALLOW_INPUT_ASSEMBLER_INPUT_LAYOUT); RDCASSERT(root); hr = m_pDevice->CreateRootSignature(0, root->GetBufferPointer(), root->GetBufferSize(), __uuidof(ID3D12RootSignature), (void **)&m_MeshRootSig); m_pDevice->InternalRef(); SAFE_RELEASE(root); rm->SetInternalResource(m_MeshRootSig); } if(!CreateMathIntrinsicsResources()) { RDCERR("Failed to create resources for shader debugging math intrinsics"); SAFE_RELEASE(m_MathIntrinsicsRootSig); SAFE_RELEASE(m_MathIntrinsicsPso); SAFE_RELEASE(m_MathIntrinsicsResultBuffer); } { rdcstr meshhlsl = GetEmbeddedResource(mesh_hlsl); shaderCache->GetShaderBlob(meshhlsl.c_str(), "RENDERDOC_MeshVS", D3DCOMPILE_WARNINGS_ARE_ERRORS, {}, "vs_5_0", &m_MeshVS); shaderCache->GetShaderBlob(meshhlsl.c_str(), "RENDERDOC_MeshGS", D3DCOMPILE_WARNINGS_ARE_ERRORS, {}, "gs_5_0", &m_MeshGS); shaderCache->GetShaderBlob(meshhlsl.c_str(), "RENDERDOC_MeshPS", D3DCOMPILE_WARNINGS_ARE_ERRORS, {}, "ps_5_0", &m_MeshPS); } { rdcstr hlsl = GetEmbeddedResource(misc_hlsl); shaderCache->GetShaderBlob(hlsl.c_str(), "RENDERDOC_FullscreenVS", D3DCOMPILE_WARNINGS_ARE_ERRORS, {}, "vs_5_0", &m_FullscreenVS); shaderCache->GetShaderBlob(hlsl.c_str(), "RENDERDOC_DiscardFloatPS", D3DCOMPILE_WARNINGS_ARE_ERRORS, {}, "ps_5_0", &m_DiscardFloatPS); shaderCache->GetShaderBlob(hlsl.c_str(), "RENDERDOC_DiscardIntPS", D3DCOMPILE_WARNINGS_ARE_ERRORS, {}, "ps_5_0", &m_DiscardIntPS); } { rdcstr multisamplehlsl = GetEmbeddedResource(multisample_hlsl); shaderCache->GetShaderBlob(multisamplehlsl.c_str(), "RENDERDOC_CopyMSToArray", D3DCOMPILE_WARNINGS_ARE_ERRORS, {}, "ps_5_0", &m_IntMS2Array); shaderCache->GetShaderBlob(multisamplehlsl.c_str(), "RENDERDOC_FloatCopyMSToArray", D3DCOMPILE_WARNINGS_ARE_ERRORS, {}, "ps_5_0", &m_FloatMS2Array); shaderCache->GetShaderBlob(multisamplehlsl.c_str(), "RENDERDOC_DepthCopyMSToArray", D3DCOMPILE_WARNINGS_ARE_ERRORS, {}, "ps_5_0", &m_DepthMS2Array); shaderCache->GetShaderBlob(multisamplehlsl.c_str(), "RENDERDOC_CopyArrayToMS", D3DCOMPILE_WARNINGS_ARE_ERRORS, {}, "ps_5_0", &m_IntArray2MS); shaderCache->GetShaderBlob(multisamplehlsl.c_str(), "RENDERDOC_FloatCopyArrayToMS", D3DCOMPILE_WARNINGS_ARE_ERRORS, {}, "ps_5_0", &m_FloatArray2MS); shaderCache->GetShaderBlob(multisamplehlsl.c_str(), "RENDERDOC_DepthCopyArrayToMS", D3DCOMPILE_WARNINGS_ARE_ERRORS, {}, "ps_5_0", &m_DepthArray2MS); } shaderCache->SetCaching(false); D3D12_RESOURCE_DESC readbackDesc; readbackDesc.Alignment = 0; readbackDesc.DepthOrArraySize = 1; readbackDesc.Dimension = D3D12_RESOURCE_DIMENSION_BUFFER; readbackDesc.Flags = D3D12_RESOURCE_FLAG_NONE; readbackDesc.Format = DXGI_FORMAT_UNKNOWN; readbackDesc.Height = 1; readbackDesc.Layout = D3D12_TEXTURE_LAYOUT_ROW_MAJOR; readbackDesc.MipLevels = 1; readbackDesc.SampleDesc.Count = 1; readbackDesc.SampleDesc.Quality = 0; readbackDesc.Width = m_ReadbackSize; D3D12_HEAP_PROPERTIES heapProps; heapProps.Type = D3D12_HEAP_TYPE_READBACK; heapProps.CPUPageProperty = D3D12_CPU_PAGE_PROPERTY_UNKNOWN; heapProps.MemoryPoolPreference = D3D12_MEMORY_POOL_UNKNOWN; heapProps.CreationNodeMask = 1; heapProps.VisibleNodeMask = 1; hr = m_pDevice->CreateCommittedResource(&heapProps, D3D12_HEAP_FLAG_NONE, &readbackDesc, D3D12_RESOURCE_STATE_COPY_DEST, NULL, __uuidof(ID3D12Resource), (void **)&m_ReadbackBuffer); m_pDevice->InternalRef(); if(FAILED(hr)) { RDCERR("Failed to create readback buffer, HRESULT: %s", ToStr(hr).c_str()); return; } m_ReadbackBuffer->SetName(L"m_ReadbackBuffer"); rm->SetInternalResource(m_ReadbackBuffer); hr = m_pDevice->CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT, __uuidof(ID3D12CommandAllocator), (void **)&m_DebugAlloc); m_pDevice->InternalRef(); if(FAILED(hr)) { RDCERR("Failed to create readback command allocator, HRESULT: %s", ToStr(hr).c_str()); return; } rm->SetInternalResource(m_DebugAlloc); m_pDevice->CreateFence(0, D3D12_FENCE_FLAG_NONE, __uuidof(ID3D12Fence), (void **)&m_DebugFence); m_pDevice->InternalRef(); rm->SetInternalResource(m_DebugFence); ID3D12GraphicsCommandList *list = NULL; hr = m_pDevice->CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, m_DebugAlloc, NULL, __uuidof(ID3D12GraphicsCommandList), (void **)&list); m_pDevice->InternalRef(); // safe to upcast - this is a wrapped object m_DebugList = (ID3D12GraphicsCommandListX *)list; if(FAILED(hr)) { RDCERR("Failed to create readback command list, HRESULT: %s", ToStr(hr).c_str()); return; } rm->SetInternalResource(m_DebugList); if(m_DebugList) m_DebugList->Close(); { ResourceFormat fmt; fmt.type = ResourceFormatType::Regular; fmt.compType = CompType::Float; fmt.compByteWidth = 4; fmt.compCount = 1; bytebuf pattern = GetDiscardPattern(DiscardType::DiscardCall, fmt); fmt.compType = CompType::UInt; pattern.append(GetDiscardPattern(DiscardType::DiscardCall, fmt)); m_DiscardConstants = MakeCBuffer(pattern.size()); m_pDevice->InternalRef(); FillBuffer(m_DiscardConstants, 0, pattern.data(), pattern.size()); ID3DBlob *root = shaderCache->MakeRootSig({ cbvParam(D3D12_SHADER_VISIBILITY_PIXEL, 0, 0), constParam(D3D12_SHADER_VISIBILITY_PIXEL, 0, 1, 1), }); RDCASSERT(root); hr = m_pDevice->CreateRootSignature(0, root->GetBufferPointer(), root->GetBufferSize(), __uuidof(ID3D12RootSignature), (void **)&m_DiscardRootSig); m_pDevice->InternalRef(); SAFE_RELEASE(root); } } D3D12DebugManager::~D3D12DebugManager() { for(auto it = m_CachedMeshPipelines.begin(); it != m_CachedMeshPipelines.end(); ++it) for(size_t p = 0; p < MeshDisplayPipelines::ePipe_Count; p++) SAFE_RELEASE(it->second.pipes[p]); for(auto it = m_MS2ArrayPSOCache.begin(); it != m_MS2ArrayPSOCache.end(); ++it) { SAFE_RELEASE(it->second.first); SAFE_RELEASE(it->second.second); } SAFE_RELEASE(dsvHeap); SAFE_RELEASE(rtvHeap); SAFE_RELEASE(cbvsrvuavHeap); SAFE_RELEASE(uavClearHeap); SAFE_RELEASE(samplerHeap); SAFE_RELEASE(m_MeshVS); SAFE_RELEASE(m_MeshGS); SAFE_RELEASE(m_MeshPS); SAFE_RELEASE(m_MeshRootSig); SAFE_RELEASE(m_MathIntrinsicsRootSig); SAFE_RELEASE(m_MathIntrinsicsPso); SAFE_RELEASE(m_MathIntrinsicsResultBuffer); SAFE_RELEASE(m_ArrayMSAARootSig); SAFE_RELEASE(m_FullscreenVS); SAFE_RELEASE(m_IntMS2Array); SAFE_RELEASE(m_FloatMS2Array); SAFE_RELEASE(m_DepthMS2Array); SAFE_RELEASE(m_IntArray2MS); SAFE_RELEASE(m_FloatArray2MS); SAFE_RELEASE(m_DepthArray2MS); SAFE_RELEASE(m_ReadbackBuffer); SAFE_RELEASE(m_RingConstantBuffer); SAFE_RELEASE(m_TexResource); SAFE_RELEASE(m_DiscardConstants); SAFE_RELEASE(m_DiscardRootSig); SAFE_RELEASE(m_DiscardFloatPS); SAFE_RELEASE(m_DiscardIntPS); SAFE_RELEASE(m_DebugAlloc); SAFE_RELEASE(m_DebugList); SAFE_RELEASE(m_DebugFence); for(auto it = m_DiscardPipes.begin(); it != m_DiscardPipes.end(); it++) if(it->second) it->second->Release(); for(auto it = m_DiscardPatterns.begin(); it != m_DiscardPatterns.end(); it++) if(it->second) it->second->Release(); for(size_t i = 0; i < m_DiscardBuffers.size(); i++) m_DiscardBuffers[i]->Release(); RenderDoc::Inst().UnregisterMemoryRegion(this); } bool D3D12DebugManager::CreateMathIntrinsicsResources() { rdcstr csProgram = "RWStructuredBuffer<float4> outval : register(u0);\n" "cbuffer srcOper : register(b0) { float4 inval; };\n" "cbuffer srcInstr : register(b1) { uint operation; };\n"; // Assign constants to each supported instruction csProgram += StringFormat::Fmt("static const uint OPCODE_RCP = %u;\n", DXBCBytecode::OPCODE_RCP); csProgram += StringFormat::Fmt("static const uint OPCODE_RSQ = %u;\n", DXBCBytecode::OPCODE_RSQ); csProgram += StringFormat::Fmt("static const uint OPCODE_EXP = %u;\n", DXBCBytecode::OPCODE_EXP); csProgram += StringFormat::Fmt("static const uint OPCODE_LOG = %u;\n", DXBCBytecode::OPCODE_LOG); csProgram += StringFormat::Fmt("static const uint OPCODE_SINCOS = %u;\n", DXBCBytecode::OPCODE_SINCOS); csProgram += "[numthreads(1, 1, 1)]\n" "void main(){\n" " switch(operation){\n" " case OPCODE_RCP: outval[0] = rcp(inval); break;\n" " case OPCODE_RSQ: outval[0] = rsqrt(inval); break;\n" " case OPCODE_EXP: outval[0] = exp2(inval); break;\n" " case OPCODE_LOG: outval[0] = log2(inval); break;\n" " case OPCODE_SINCOS: sincos(inval, outval[0], outval[1]); break;\n" " }\n}\n"; ID3DBlob *csBlob = NULL; UINT flags = D3DCOMPILE_DEBUG | D3DCOMPILE_WARNINGS_ARE_ERRORS; if(m_pDevice->GetShaderCache()->GetShaderBlob(csProgram.c_str(), "main", flags, {}, "cs_5_0", &csBlob) != "") { RDCERR("Failed to create shader to calculate math intrinsic"); return false; } D3D12RootSignature rootSig; // Constants param for the operation inputs D3D12RootSignatureParameter constantParam; constantParam.ParameterType = D3D12_ROOT_PARAMETER_TYPE_32BIT_CONSTANTS; constantParam.ShaderVisibility = D3D12_SHADER_VISIBILITY_ALL; constantParam.Constants.Num32BitValues = 4; // Input is 4 floats constantParam.Constants.ShaderRegister = 0; constantParam.Constants.RegisterSpace = 0; rootSig.Parameters.push_back(constantParam); // Constants param for the opcode constantParam.Constants.Num32BitValues = 1; constantParam.Constants.ShaderRegister = 1; constantParam.Constants.RegisterSpace = 0; rootSig.Parameters.push_back(constantParam); // UAV param for the output D3D12RootSignatureParameter uavParam; uavParam.ParameterType = D3D12_ROOT_PARAMETER_TYPE_UAV; uavParam.ShaderVisibility = D3D12_SHADER_VISIBILITY_ALL; uavParam.Descriptor.ShaderRegister = 0; uavParam.Descriptor.RegisterSpace = 0; uavParam.Descriptor.Flags = D3D12_ROOT_DESCRIPTOR_FLAG_NONE; rootSig.Parameters.push_back(uavParam); ID3DBlob *root = m_pDevice->GetShaderCache()->MakeRootSig(rootSig); if(root == NULL) { RDCERR("Failed to create root signature for shader debugging"); SAFE_RELEASE(csBlob); return false; } HRESULT hr = m_pDevice->CreateRootSignature(0, root->GetBufferPointer(), root->GetBufferSize(), __uuidof(ID3D12RootSignature), (void **)&m_MathIntrinsicsRootSig); m_pDevice->InternalRef(); SAFE_RELEASE(root); if(FAILED(hr)) { RDCERR("Failed to create root signature for shader debugging HRESULT: %s", ToStr(hr).c_str()); SAFE_RELEASE(csBlob); return false; } m_pDevice->GetResourceManager()->SetInternalResource(m_MathIntrinsicsRootSig); D3D12_COMPUTE_PIPELINE_STATE_DESC psoDesc; psoDesc.pRootSignature = m_MathIntrinsicsRootSig; psoDesc.CS.BytecodeLength = csBlob->GetBufferSize(); psoDesc.CS.pShaderBytecode = csBlob->GetBufferPointer(); psoDesc.NodeMask = 0; psoDesc.CachedPSO.pCachedBlob = NULL; psoDesc.CachedPSO.CachedBlobSizeInBytes = 0; psoDesc.Flags = D3D12_PIPELINE_STATE_FLAG_NONE; hr = m_pDevice->CreateComputePipelineState(&psoDesc, __uuidof(ID3D12PipelineState), (void **)&m_MathIntrinsicsPso); m_pDevice->InternalRef(); SAFE_RELEASE(csBlob); if(FAILED(hr)) { RDCERR("Failed to create PSO for shader debugging HRESULT: %s", ToStr(hr).c_str()); SAFE_RELEASE(m_MathIntrinsicsRootSig); return false; } m_pDevice->GetResourceManager()->SetInternalResource(m_MathIntrinsicsPso); // Create buffer to store computed result D3D12_RESOURCE_DESC rdesc; ZeroMemory(&rdesc, sizeof(D3D12_RESOURCE_DESC)); rdesc.Dimension = D3D12_RESOURCE_DIMENSION_BUFFER; rdesc.Width = sizeof(Vec4f) * 2; // Output buffer is 2x float4 rdesc.Height = 1; rdesc.DepthOrArraySize = 1; rdesc.MipLevels = 1; rdesc.Format = DXGI_FORMAT_UNKNOWN; rdesc.Flags = D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS; rdesc.Layout = D3D12_TEXTURE_LAYOUT_ROW_MAJOR; rdesc.SampleDesc.Count = 1; rdesc.SampleDesc.Quality = 0; D3D12_HEAP_PROPERTIES heapProps; heapProps.Type = D3D12_HEAP_TYPE_DEFAULT; heapProps.CPUPageProperty = D3D12_CPU_PAGE_PROPERTY_UNKNOWN; heapProps.MemoryPoolPreference = D3D12_MEMORY_POOL_UNKNOWN; heapProps.CreationNodeMask = 1; heapProps.VisibleNodeMask = 1; hr = m_pDevice->CreateCommittedResource( &heapProps, D3D12_HEAP_FLAG_NONE, &rdesc, D3D12_RESOURCE_STATE_UNORDERED_ACCESS, NULL, __uuidof(ID3D12Resource), (void **)&m_MathIntrinsicsResultBuffer); m_pDevice->InternalRef(); if(FAILED(hr)) { RDCERR("Failed to create buffer for pixel shader debugging HRESULT: %s", ToStr(hr).c_str()); SAFE_RELEASE(m_MathIntrinsicsRootSig); SAFE_RELEASE(m_MathIntrinsicsPso); return false; } m_pDevice->GetResourceManager()->SetInternalResource(m_MathIntrinsicsResultBuffer); return true; } ID3D12Resource *D3D12DebugManager::MakeCBuffer(UINT64 size) { ID3D12Resource *ret; D3D12_HEAP_PROPERTIES heapProps; heapProps.Type = D3D12_HEAP_TYPE_UPLOAD; heapProps.CPUPageProperty = D3D12_CPU_PAGE_PROPERTY_UNKNOWN; heapProps.MemoryPoolPreference = D3D12_MEMORY_POOL_UNKNOWN; heapProps.CreationNodeMask = 1; heapProps.VisibleNodeMask = 1; D3D12_RESOURCE_DESC cbDesc; cbDesc.Alignment = 0; cbDesc.DepthOrArraySize = 1; cbDesc.Dimension = D3D12_RESOURCE_DIMENSION_BUFFER; cbDesc.Flags = D3D12_RESOURCE_FLAG_NONE; cbDesc.Format = DXGI_FORMAT_UNKNOWN; cbDesc.Height = 1; cbDesc.Layout = D3D12_TEXTURE_LAYOUT_ROW_MAJOR; cbDesc.MipLevels = 1; cbDesc.SampleDesc.Count = 1; cbDesc.SampleDesc.Quality = 0; cbDesc.Width = size; HRESULT hr = m_pDevice->CreateCommittedResource(&heapProps, D3D12_HEAP_FLAG_NONE, &cbDesc, D3D12_RESOURCE_STATE_GENERIC_READ, NULL, __uuidof(ID3D12Resource), (void **)&ret); if(FAILED(hr)) { RDCERR("Couldn't create cbuffer size %llu! %s", size, ToStr(hr).c_str()); SAFE_RELEASE(ret); return NULL; } return ret; } void D3D12DebugManager::FillBuffer(ID3D12Resource *buf, size_t offset, const void *data, size_t size) { D3D12_RANGE range = {offset, offset + size}; byte *ptr = NULL; HRESULT hr = buf->Map(0, &range, (void **)&ptr); m_pDevice->CheckHRESULT(hr); if(FAILED(hr)) { RDCERR("Can't fill cbuffer HRESULT: %s", ToStr(hr).c_str()); } else { memcpy(ptr + offset, data, size); buf->Unmap(0, &range); } } D3D12_GPU_VIRTUAL_ADDRESS D3D12DebugManager::UploadConstants(const void *data, size_t size) { D3D12_GPU_VIRTUAL_ADDRESS ret = m_RingConstantBuffer->GetGPUVirtualAddress(); if(m_RingConstantOffset + size > m_RingConstantBuffer->GetDesc().Width) m_RingConstantOffset = 0; ret += m_RingConstantOffset; // passing the unwrapped object here is immaterial as all we do is Map/Unmap, but it means we can // call this function while capturing without worrying about serialising the map or deadlocking. FillBuffer(Unwrap(m_RingConstantBuffer), (size_t)m_RingConstantOffset, data, size); m_RingConstantOffset += size; m_RingConstantOffset = AlignUp(m_RingConstantOffset, (UINT64)D3D12_CONSTANT_BUFFER_DATA_PLACEMENT_ALIGNMENT); return ret; } ID3D12GraphicsCommandListX *D3D12DebugManager::ResetDebugList() { m_DebugList->Reset(m_DebugAlloc, NULL); return m_DebugList; } void D3D12DebugManager::ResetDebugAlloc() { m_DebugAlloc->Reset(); } void D3D12DebugManager::FillWithDiscardPattern(ID3D12GraphicsCommandListX *cmd, const D3D12RenderState &state, DiscardType type, ID3D12Resource *res, const D3D12_DISCARD_REGION *region) { RDCASSERT(type == DiscardType::DiscardCall); D3D12MarkerRegion marker( cmd, StringFormat::Fmt("FillWithDiscardPattern %s", ToStr(GetResID(res)).c_str())); D3D12_RESOURCE_DESC desc = res->GetDesc(); rdcarray<D3D12_RECT> rects; if(region && region->NumRects > 0) rects.assign(region->pRects, region->NumRects); else rects = {{0, 0, (LONG)desc.Width, (LONG)desc.Height}}; if(desc.Dimension == D3D12_RESOURCE_DIMENSION_BUFFER) { // ignore rects, they are only allowed with 2D resources size_t size = (size_t)desc.Width; ID3D12Resource *patternBuf = NULL; // if we have discard buffers, try the last one, it's the biggest we have if(!m_DiscardBuffers.empty()) { patternBuf = m_DiscardBuffers.back(); // if it's not big enough, don't use it if(patternBuf->GetDesc().Width < size) patternBuf = NULL; } // if we don't have a buffer, make one that's big enough and use that if(patternBuf == NULL) { bytebuf pattern; // make at least 1K at a time to prevent too much incremental updates if we encounter buffers // of different sizes pattern.resize(AlignUp<size_t>(size, 1024U)); uint32_t value = 0xD15CAD3D; for(size_t i = 0; i < pattern.size(); i += 4) memcpy(&pattern[i], &value, sizeof(uint32_t)); patternBuf = MakeCBuffer(pattern.size()); m_DiscardBuffers.push_back(patternBuf); FillBuffer(patternBuf, 0, pattern.data(), size); } // fill the destination with a copy from the pattern buffer cmd->CopyBufferRegion(res, 0, patternBuf, 0, size); return; } UINT firstSub = region ? region->FirstSubresource : 0; UINT numSubs = region ? region->NumSubresources : GetNumSubresources(m_pDevice, &desc); if(desc.SampleDesc.Count > 1) { // we can't do discard patterns for MSAA on compute comand lists if(cmd->GetType() == D3D12_COMMAND_LIST_TYPE_COMPUTE) return; bool depth = false; if(desc.Flags & D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL) depth = true; DXGI_FORMAT fmt = desc.Format; if(depth) fmt = GetDepthTypedFormat(fmt); else fmt = GetTypedFormat(fmt, CompType::Float); rdcpair<DXGI_FORMAT, UINT> key = {fmt, desc.SampleDesc.Count}; rdcpair<DXGI_FORMAT, UINT> stencilKey = {DXGI_FORMAT_UNKNOWN, desc.SampleDesc.Count}; ID3D12PipelineState *pipe = m_DiscardPipes[key]; ID3D12PipelineState *stencilpipe = pipe; if(fmt == DXGI_FORMAT_D32_FLOAT_S8X24_UINT) { stencilKey.first = DXGI_FORMAT_R32_FLOAT_X8X24_TYPELESS; stencilpipe = m_DiscardPipes[stencilKey]; } else if(fmt == DXGI_FORMAT_D24_UNORM_S8_UINT) { stencilKey.first = DXGI_FORMAT_R24_UNORM_X8_TYPELESS; stencilpipe = m_DiscardPipes[stencilKey]; } bool intFormat = !depth && (IsIntFormat(fmt) || IsUIntFormat(fmt)); if(pipe == NULL) { D3D12_GRAPHICS_PIPELINE_STATE_DESC pipeDesc = {}; pipeDesc.pRootSignature = m_DiscardRootSig; pipeDesc.VS.BytecodeLength = m_FullscreenVS->GetBufferSize(); pipeDesc.VS.pShaderBytecode = m_FullscreenVS->GetBufferPointer(); pipeDesc.PS.BytecodeLength = intFormat ? m_DiscardIntPS->GetBufferSize() : m_DiscardFloatPS->GetBufferSize(); pipeDesc.PS.pShaderBytecode = intFormat ? m_DiscardIntPS->GetBufferPointer() : m_DiscardFloatPS->GetBufferPointer(); pipeDesc.RasterizerState.FillMode = D3D12_FILL_MODE_SOLID; pipeDesc.RasterizerState.CullMode = D3D12_CULL_MODE_NONE; pipeDesc.SampleMask = 0xFFFFFFFF; pipeDesc.SampleDesc.Count = desc.SampleDesc.Count; pipeDesc.IBStripCutValue = D3D12_INDEX_BUFFER_STRIP_CUT_VALUE_DISABLED; pipeDesc.PrimitiveTopologyType = D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE; pipeDesc.BlendState.RenderTarget[0].BlendEnable = FALSE; pipeDesc.BlendState.RenderTarget[0].SrcBlend = D3D12_BLEND_SRC_ALPHA; pipeDesc.BlendState.RenderTarget[0].DestBlend = D3D12_BLEND_INV_SRC_ALPHA; pipeDesc.BlendState.RenderTarget[0].BlendOp = D3D12_BLEND_OP_ADD; pipeDesc.BlendState.RenderTarget[0].SrcBlendAlpha = D3D12_BLEND_SRC_ALPHA; pipeDesc.BlendState.RenderTarget[0].DestBlendAlpha = D3D12_BLEND_INV_SRC_ALPHA; pipeDesc.BlendState.RenderTarget[0].BlendOpAlpha = D3D12_BLEND_OP_ADD; pipeDesc.BlendState.RenderTarget[0].RenderTargetWriteMask = D3D12_COLOR_WRITE_ENABLE_ALL; pipeDesc.DepthStencilState.DepthFunc = D3D12_COMPARISON_FUNC_ALWAYS; pipeDesc.DepthStencilState.DepthWriteMask = D3D12_DEPTH_WRITE_MASK_ALL; pipeDesc.DepthStencilState.StencilReadMask = 0xFF; pipeDesc.DepthStencilState.StencilWriteMask = 0xFF; pipeDesc.DepthStencilState.FrontFace.StencilFunc = D3D12_COMPARISON_FUNC_ALWAYS; pipeDesc.DepthStencilState.FrontFace.StencilPassOp = D3D12_STENCIL_OP_REPLACE; pipeDesc.DepthStencilState.FrontFace.StencilFailOp = D3D12_STENCIL_OP_REPLACE; pipeDesc.DepthStencilState.FrontFace.StencilDepthFailOp = D3D12_STENCIL_OP_REPLACE; pipeDesc.DepthStencilState.BackFace = pipeDesc.DepthStencilState.FrontFace; pipeDesc.DepthStencilState.DepthEnable = FALSE; pipeDesc.DepthStencilState.StencilEnable = FALSE; if(depth) { pipeDesc.DSVFormat = fmt; pipeDesc.DepthStencilState.DepthEnable = TRUE; } else { pipeDesc.NumRenderTargets = 1; pipeDesc.RTVFormats[0] = fmt; } HRESULT hr = m_pDevice->CreateGraphicsPipelineState(&pipeDesc, __uuidof(ID3D12PipelineState), (void **)&pipe); if(FAILED(hr)) RDCERR("Couldn't create MSAA discard pattern pipe! HRESULT: %s", ToStr(hr).c_str()); m_DiscardPipes[key] = pipe; if(stencilKey.first != DXGI_FORMAT_UNKNOWN) { pipeDesc.DepthStencilState.DepthEnable = FALSE; pipeDesc.DepthStencilState.StencilEnable = TRUE; hr = m_pDevice->CreateGraphicsPipelineState(&pipeDesc, __uuidof(ID3D12PipelineState), (void **)&stencilpipe); if(FAILED(hr)) RDCERR("Couldn't create MSAA discard pattern pipe! HRESULT: %s", ToStr(hr).c_str()); m_DiscardPipes[stencilKey] = stencilpipe; } } if(!pipe) return; cmd->IASetPrimitiveTopology(D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST); cmd->SetPipelineState(pipe); cmd->SetGraphicsRootSignature(m_DiscardRootSig); cmd->SetGraphicsRootConstantBufferView(0, m_DiscardConstants->GetGPUVirtualAddress()); D3D12_VIEWPORT viewport = {0, 0, (float)desc.Width, (float)desc.Height, 0.0f, 1.0f}; cmd->RSSetViewports(1, &viewport); if(m_pDevice->GetOpts3().ViewInstancingTier != D3D12_VIEW_INSTANCING_TIER_NOT_SUPPORTED) cmd->SetViewInstanceMask(0); D3D12_RENDER_TARGET_VIEW_DESC rtvDesc; rtvDesc.ViewDimension = D3D12_RTV_DIMENSION_TEXTURE2DMSARRAY; rtvDesc.Format = fmt; rtvDesc.Texture2DMSArray.ArraySize = 1; D3D12_DEPTH_STENCIL_VIEW_DESC dsvDesc; dsvDesc.Flags = D3D12_DSV_FLAG_NONE; dsvDesc.ViewDimension = D3D12_DSV_DIMENSION_TEXTURE2DMSARRAY; dsvDesc.Format = fmt; dsvDesc.Texture2DMSArray.ArraySize = 1; D3D12_CPU_DESCRIPTOR_HANDLE rtv = GetCPUHandle(MSAA_RTV); D3D12_CPU_DESCRIPTOR_HANDLE dsv = GetCPUHandle(MSAA_DSV); for(UINT sub = 0; sub < numSubs; sub++) { UINT subresource = firstSub + sub; if(depth) { dsvDesc.Texture2DMSArray.FirstArraySlice = GetSliceForSubresource(res, subresource); m_pDevice->CreateDepthStencilView(res, &dsvDesc, dsv); cmd->OMSetRenderTargets(0, NULL, FALSE, &dsv); } else { rtvDesc.Texture2DMSArray.FirstArraySlice = GetSliceForSubresource(res, subresource); m_pDevice->CreateRenderTargetView(res, &rtvDesc, rtv); cmd->OMSetRenderTargets(1, &rtv, FALSE, NULL); } UINT mip = GetMipForSubresource(res, subresource); UINT plane = GetPlaneForSubresource(res, subresource); for(D3D12_RECT r : rects) { r.right = RDCMIN(LONG(RDCMAX(1U, (UINT)desc.Width >> mip)), r.right); r.bottom = RDCMIN(LONG(RDCMAX(1U, (UINT)desc.Height >> mip)), r.bottom); cmd->RSSetScissorRects(1, &r); if(depth) { if(plane == 0) { cmd->SetPipelineState(pipe); cmd->SetGraphicsRoot32BitConstant(1, 0, 0); cmd->DrawInstanced(3, 1, 0, 0); } else { cmd->SetPipelineState(stencilpipe); cmd->SetGraphicsRoot32BitConstant(1, 1, 0); cmd->OMSetStencilRef(0x00); cmd->DrawInstanced(3, 1, 0, 0); cmd->SetGraphicsRoot32BitConstant(1, 2, 0); cmd->OMSetStencilRef(0xff); cmd->DrawInstanced(3, 1, 0, 0); } } else { cmd->SetGraphicsRoot32BitConstant(1, 0, 0); cmd->DrawInstanced(3, 1, 0, 0); } } } state.ApplyState(m_pDevice, cmd); return; } // see if we already have a buffer with texels in the desired format, if not then create it ID3D12Resource *buf = m_DiscardPatterns[desc.Format]; if(buf == NULL) { bytebuf pattern = GetDiscardPattern(type, MakeResourceFormat(desc.Format), 256); buf = MakeCBuffer(pattern.size()); FillBuffer(buf, 0, pattern.data(), pattern.size()); m_DiscardPatterns[desc.Format] = buf; } for(UINT sub = firstSub; sub < firstSub + numSubs; sub++) { D3D12_RESOURCE_BARRIER b = {}; b.Transition.pResource = res; b.Transition.Subresource = sub; // TODO can we do better than an educated guess as to what the previous state was? if(desc.Flags & D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL) b.Transition.StateBefore = D3D12_RESOURCE_STATE_DEPTH_WRITE; else if(desc.Flags & D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET) b.Transition.StateBefore = D3D12_RESOURCE_STATE_RENDER_TARGET; else b.Transition.StateBefore = D3D12_RESOURCE_STATE_COMMON; b.Transition.StateAfter = D3D12_RESOURCE_STATE_COPY_DEST; cmd->ResourceBarrier(1, &b); D3D12_TEXTURE_COPY_LOCATION dst, src; dst.Type = D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX; dst.pResource = res; dst.SubresourceIndex = sub; UINT mip = GetMipForSubresource(res, sub); DXGI_FORMAT fmt = desc.Format; UINT bufOffset = 0; // if this is a depth/stencil format it comes in multiple planes - figure out which format we're // copying and the appropriate buffer offset if(IsDepthAndStencilFormat(fmt)) { UINT planeSlice = GetPlaneForSubresource(res, sub); if(planeSlice == 0) { fmt = DXGI_FORMAT_R32_TYPELESS; } else { fmt = DXGI_FORMAT_R8_TYPELESS; bufOffset += GetByteSize(DiscardPatternWidth, DiscardPatternHeight, 1, DXGI_FORMAT_R32_FLOAT, 0); } } // the user isn't allowed to specify rects for 3D textures, so in that case we'll have our own // default 0,0->64k,64k one. Similarly we also discard all z slices uint32_t depth = desc.Dimension == D3D12_RESOURCE_DIMENSION_TEXTURE3D ? desc.DepthOrArraySize : 1U; for(uint32_t z = 0; z < RDCMAX(1U, depth >> mip); z++) { for(D3D12_RECT r : rects) { int32_t rectWidth = RDCMIN(LONG(RDCMAX(1U, (UINT)desc.Width >> mip)), r.right); int32_t rectHeight = RDCMIN(LONG(RDCMAX(1U, (UINT)desc.Height >> mip)), r.bottom); for(int32_t y = r.top; y < rectHeight; y += DiscardPatternHeight) { for(int32_t x = r.left; x < rectWidth; x += DiscardPatternWidth) { src.Type = D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT; src.pResource = buf; src.PlacedFootprint.Offset = bufOffset; src.PlacedFootprint.Footprint.Format = fmt; src.PlacedFootprint.Footprint.RowPitch = AlignUp(GetRowPitch(DiscardPatternWidth, fmt, 0), 256U); src.PlacedFootprint.Footprint.Width = RDCMIN(DiscardPatternWidth, uint32_t(rectWidth - x)); src.PlacedFootprint.Footprint.Height = RDCMIN(DiscardPatternHeight, uint32_t(rectHeight - y)); src.PlacedFootprint.Footprint.Depth = 1; cmd->CopyTextureRegion(&dst, x, y, z, &src, NULL); } } } } std::swap(b.Transition.StateBefore, b.Transition.StateAfter); cmd->ResourceBarrier(1, &b); } } D3D12_CPU_DESCRIPTOR_HANDLE D3D12DebugManager::GetCPUHandle(CBVUAVSRVSlot slot) { D3D12_CPU_DESCRIPTOR_HANDLE ret = cbvsrvuavHeap->GetCPUDescriptorHandleForHeapStart(); ret.ptr += slot * sizeof(D3D12Descriptor); return ret; } D3D12_CPU_DESCRIPTOR_HANDLE D3D12DebugManager::GetCPUHandle(RTVSlot slot) { D3D12_CPU_DESCRIPTOR_HANDLE ret = rtvHeap->GetCPUDescriptorHandleForHeapStart(); ret.ptr += slot * sizeof(D3D12Descriptor); return ret; } D3D12_CPU_DESCRIPTOR_HANDLE D3D12DebugManager::GetCPUHandle(DSVSlot slot) { D3D12_CPU_DESCRIPTOR_HANDLE ret = dsvHeap->GetCPUDescriptorHandleForHeapStart(); ret.ptr += slot * sizeof(D3D12Descriptor); return ret; } D3D12_GPU_DESCRIPTOR_HANDLE D3D12DebugManager::GetGPUHandle(CBVUAVSRVSlot slot) { D3D12_GPU_DESCRIPTOR_HANDLE ret = cbvsrvuavHeap->GetGPUDescriptorHandleForHeapStart(); ret.ptr += slot * sizeof(D3D12Descriptor); return ret; } D3D12_GPU_DESCRIPTOR_HANDLE D3D12DebugManager::GetGPUHandle(RTVSlot slot) { D3D12_GPU_DESCRIPTOR_HANDLE ret = rtvHeap->GetGPUDescriptorHandleForHeapStart(); ret.ptr += slot * sizeof(D3D12Descriptor); return ret; } D3D12_GPU_DESCRIPTOR_HANDLE D3D12DebugManager::GetGPUHandle(DSVSlot slot) { D3D12_GPU_DESCRIPTOR_HANDLE ret = dsvHeap->GetGPUDescriptorHandleForHeapStart(); ret.ptr += slot * sizeof(D3D12Descriptor); return ret; } D3D12_GPU_DESCRIPTOR_HANDLE D3D12DebugManager::GetGPUHandle(SamplerSlot slot) { D3D12_GPU_DESCRIPTOR_HANDLE ret = samplerHeap->GetGPUDescriptorHandleForHeapStart(); ret.ptr += slot * sizeof(D3D12Descriptor); return ret; } D3D12_CPU_DESCRIPTOR_HANDLE D3D12DebugManager::GetTempDescriptor(const D3D12Descriptor &desc, size_t idx) { D3D12_CPU_DESCRIPTOR_HANDLE ret = {}; ID3D12Resource *res = m_pDevice->GetResourceManager()->GetCurrentAs<ID3D12Resource>(desc.GetResResourceId()); if(desc.GetType() == D3D12DescriptorType::RTV) { ret = GetCPUHandle(FIRST_TMP_RTV); ret.ptr += idx * sizeof(D3D12Descriptor); const D3D12_RENDER_TARGET_VIEW_DESC *rtvdesc = &desc.GetRTV(); if(rtvdesc->ViewDimension == D3D12_RTV_DIMENSION_UNKNOWN) rtvdesc = NULL; if(rtvdesc == NULL || rtvdesc->Format == DXGI_FORMAT_UNKNOWN) { const std::map<ResourceId, DXGI_FORMAT> &bbs = m_pDevice->GetBackbufferFormats(); auto it = bbs.find(GetResID(res)); // fixup for backbuffers if(it != bbs.end()) { D3D12_RENDER_TARGET_VIEW_DESC bbDesc = {}; bbDesc.Format = it->second; bbDesc.ViewDimension = D3D12_RTV_DIMENSION_TEXTURE2D; m_pDevice->CreateRenderTargetView(res, &bbDesc, ret); return ret; } } m_pDevice->CreateRenderTargetView(res, rtvdesc, ret); } else if(desc.GetType() == D3D12DescriptorType::DSV) { ret = GetCPUHandle(TMP_DSV); const D3D12_DEPTH_STENCIL_VIEW_DESC *dsvdesc = &desc.GetDSV(); if(dsvdesc->ViewDimension == D3D12_DSV_DIMENSION_UNKNOWN) dsvdesc = NULL; m_pDevice->CreateDepthStencilView(res, dsvdesc, ret); } else if(desc.GetType() == D3D12DescriptorType::UAV) { // need a non-shader visible heap for this one ret = GetUAVClearHandle(TMP_UAV); ID3D12Resource *counterRes = m_pDevice->GetResourceManager()->GetCurrentAs<ID3D12Resource>(desc.GetCounterResourceId()); D3D12_UNORDERED_ACCESS_VIEW_DESC unpacked = desc.GetUAV(); const D3D12_UNORDERED_ACCESS_VIEW_DESC *uavdesc = &unpacked; if(uavdesc->ViewDimension == D3D12_UAV_DIMENSION_UNKNOWN) uavdesc = NULL; if(uavdesc == NULL || uavdesc->Format == DXGI_FORMAT_UNKNOWN) { const std::map<ResourceId, DXGI_FORMAT> &bbs = m_pDevice->GetBackbufferFormats(); auto it = bbs.find(GetResID(res)); // fixup for backbuffers if(it != bbs.end()) { D3D12_UNORDERED_ACCESS_VIEW_DESC bbDesc = {}; bbDesc.Format = it->second; bbDesc.ViewDimension = D3D12_UAV_DIMENSION_TEXTURE2D; m_pDevice->CreateUnorderedAccessView(res, NULL, &bbDesc, ret); return ret; } } m_pDevice->CreateUnorderedAccessView(res, counterRes, uavdesc, ret); } else { RDCERR("Unexpected descriptor type %s for temp descriptor!", ToStr(desc.GetType()).c_str()); } return ret; } void D3D12DebugManager::SetDescriptorHeaps(ID3D12GraphicsCommandList *list, bool cbvsrvuav, bool samplers) { ID3D12DescriptorHeap *heaps[] = {cbvsrvuavHeap, samplerHeap}; if(cbvsrvuav && samplers) { list->SetDescriptorHeaps(2, heaps); } else if(cbvsrvuav) { list->SetDescriptorHeaps(1, &heaps[0]); } else if(samplers) { list->SetDescriptorHeaps(1, &heaps[1]); } } D3D12_CPU_DESCRIPTOR_HANDLE D3D12DebugManager::GetUAVClearHandle(CBVUAVSRVSlot slot) { D3D12_CPU_DESCRIPTOR_HANDLE ret = uavClearHeap->GetCPUDescriptorHandleForHeapStart(); ret.ptr += slot * sizeof(D3D12Descriptor); return ret; } void D3D12DebugManager::GetBufferData(ID3D12Resource *buffer, uint64_t offset, uint64_t length, bytebuf &ret) { if(buffer == NULL) return; D3D12_RESOURCE_DESC desc = buffer->GetDesc(); D3D12_HEAP_PROPERTIES heapProps = {}; // can't call GetHeapProperties on sparse resources if(!m_pDevice->IsSparseResource(GetResID(buffer))) buffer->GetHeapProperties(&heapProps, NULL); if(offset >= desc.Width) { // can't read past the end of the buffer, return empty return; } if(length == 0 || length > desc.Width) { length = desc.Width - offset; } if(offset + length > desc.Width) { RDCWARN("Attempting to read off the end of the buffer (%llu %llu). Will be clamped (%llu)", offset, length, desc.Width); length = RDCMIN(length, desc.Width - offset); } #if DISABLED(RDOC_X64) if(offset + length > 0xfffffff) { RDCERR("Trying to read back too much data on 32-bit build. Try running on 64-bit."); return; } #endif uint64_t outOffs = 0; ret.resize((size_t)length); // directly CPU mappable (and possibly invalid to transition and copy from), so just memcpy if(heapProps.Type == D3D12_HEAP_TYPE_UPLOAD || heapProps.Type == D3D12_HEAP_TYPE_READBACK) { D3D12_RANGE range = {(size_t)offset, size_t(offset + length)}; byte *data = NULL; HRESULT hr = buffer->Map(0, &range, (void **)&data); m_pDevice->CheckHRESULT(hr); if(FAILED(hr)) { RDCERR("Failed to map buffer directly for readback HRESULT: %s", ToStr(hr).c_str()); return; } memcpy(&ret[0], data + offset, (size_t)length); range.Begin = range.End = 0; buffer->Unmap(0, &range); return; } m_DebugList->Reset(m_DebugAlloc, NULL); D3D12_RESOURCE_BARRIER barrier = {}; barrier.Transition.pResource = buffer; barrier.Transition.StateBefore = m_pDevice->GetSubresourceStates(GetResID(buffer))[0]; barrier.Transition.StateAfter = D3D12_RESOURCE_STATE_COPY_SOURCE; if(barrier.Transition.StateBefore != D3D12_RESOURCE_STATE_COPY_SOURCE) m_DebugList->ResourceBarrier(1, &barrier); while(length > 0) { uint64_t chunkSize = RDCMIN(length, m_ReadbackSize); m_DebugList->CopyBufferRegion(m_ReadbackBuffer, 0, buffer, offset + outOffs, chunkSize); m_DebugList->Close(); ID3D12CommandList *l = m_DebugList; m_pDevice->GetQueue()->ExecuteCommandLists(1, &l); m_pDevice->GPUSync(); m_DebugAlloc->Reset(); D3D12_RANGE range = {0, (size_t)chunkSize}; void *data = NULL; HRESULT hr = m_ReadbackBuffer->Map(0, &range, &data); m_pDevice->CheckHRESULT(hr); if(FAILED(hr)) { RDCERR("Failed to map bufferdata buffer HRESULT: %s", ToStr(hr).c_str()); return; } else { memcpy(&ret[(size_t)outOffs], data, (size_t)chunkSize); range.End = 0; m_ReadbackBuffer->Unmap(0, &range); } outOffs += chunkSize; length -= chunkSize; m_DebugList->Reset(m_DebugAlloc, NULL); } if(barrier.Transition.StateBefore != D3D12_RESOURCE_STATE_COPY_SOURCE) { std::swap(barrier.Transition.StateBefore, barrier.Transition.StateAfter); m_DebugList->ResourceBarrier(1, &barrier); } m_DebugList->Close(); ID3D12CommandList *l = m_DebugList; m_pDevice->GetQueue()->ExecuteCommandLists(1, &l); m_pDevice->GPUSync(); m_DebugAlloc->Reset(); } void D3D12Replay::GeneralMisc::Init(WrappedID3D12Device *device, D3D12DebugManager *debug) { HRESULT hr = S_OK; D3D12ShaderCache *shaderCache = device->GetShaderCache(); shaderCache->SetCaching(true); { D3D12_RESOURCE_DESC readbackDesc; readbackDesc.Alignment = 0; readbackDesc.DepthOrArraySize = 1; readbackDesc.Dimension = D3D12_RESOURCE_DIMENSION_BUFFER; readbackDesc.Flags = D3D12_RESOURCE_FLAG_NONE; readbackDesc.Format = DXGI_FORMAT_UNKNOWN; readbackDesc.Height = 1; readbackDesc.Layout = D3D12_TEXTURE_LAYOUT_ROW_MAJOR; readbackDesc.MipLevels = 1; readbackDesc.SampleDesc.Count = 1; readbackDesc.SampleDesc.Quality = 0; readbackDesc.Width = 4096; D3D12_HEAP_PROPERTIES heapProps; heapProps.Type = D3D12_HEAP_TYPE_READBACK; heapProps.CPUPageProperty = D3D12_CPU_PAGE_PROPERTY_UNKNOWN; heapProps.MemoryPoolPreference = D3D12_MEMORY_POOL_UNKNOWN; heapProps.CreationNodeMask = 1; heapProps.VisibleNodeMask = 1; hr = device->CreateCommittedResource(&heapProps, D3D12_HEAP_FLAG_NONE, &readbackDesc, D3D12_RESOURCE_STATE_COPY_DEST, NULL, __uuidof(ID3D12Resource), (void **)&ResultReadbackBuffer); ResultReadbackBuffer->SetName(L"m_ResultReadbackBuffer"); if(FAILED(hr)) { RDCERR("Failed to create readback buffer, HRESULT: %s", ToStr(hr).c_str()); return; } } { ID3DBlob *root = shaderCache->MakeRootSig({ cbvParam(D3D12_SHADER_VISIBILITY_PIXEL, 0, 0), }); RDCASSERT(root); hr = device->CreateRootSignature(0, root->GetBufferPointer(), root->GetBufferSize(), __uuidof(ID3D12RootSignature), (void **)&CheckerboardRootSig); SAFE_RELEASE(root); } { rdcstr hlsl = GetEmbeddedResource(misc_hlsl); ID3DBlob *FullscreenVS = NULL; ID3DBlob *CheckerboardPS = NULL; shaderCache->GetShaderBlob(hlsl.c_str(), "RENDERDOC_FullscreenVS", D3DCOMPILE_WARNINGS_ARE_ERRORS, {}, "vs_5_0", &FullscreenVS); shaderCache->GetShaderBlob(hlsl.c_str(), "RENDERDOC_CheckerboardPS", D3DCOMPILE_WARNINGS_ARE_ERRORS, {}, "ps_5_0", &CheckerboardPS); RDCASSERT(CheckerboardPS); RDCASSERT(FullscreenVS); D3D12_GRAPHICS_PIPELINE_STATE_DESC pipeDesc = {}; pipeDesc.pRootSignature = CheckerboardRootSig; pipeDesc.VS.BytecodeLength = FullscreenVS->GetBufferSize(); pipeDesc.VS.pShaderBytecode = FullscreenVS->GetBufferPointer(); pipeDesc.PS.BytecodeLength = CheckerboardPS->GetBufferSize(); pipeDesc.PS.pShaderBytecode = CheckerboardPS->GetBufferPointer(); pipeDesc.RasterizerState.FillMode = D3D12_FILL_MODE_SOLID; pipeDesc.RasterizerState.CullMode = D3D12_CULL_MODE_NONE; pipeDesc.SampleMask = 0xFFFFFFFF; pipeDesc.SampleDesc.Count = 1; pipeDesc.IBStripCutValue = D3D12_INDEX_BUFFER_STRIP_CUT_VALUE_DISABLED; pipeDesc.PrimitiveTopologyType = D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE; pipeDesc.NumRenderTargets = 1; pipeDesc.RTVFormats[0] = DXGI_FORMAT_R8G8B8A8_UNORM_SRGB; pipeDesc.DSVFormat = DXGI_FORMAT_UNKNOWN; pipeDesc.BlendState.RenderTarget[0].BlendEnable = FALSE; pipeDesc.BlendState.RenderTarget[0].SrcBlend = D3D12_BLEND_SRC_ALPHA; pipeDesc.BlendState.RenderTarget[0].DestBlend = D3D12_BLEND_INV_SRC_ALPHA; pipeDesc.BlendState.RenderTarget[0].BlendOp = D3D12_BLEND_OP_ADD; pipeDesc.BlendState.RenderTarget[0].SrcBlendAlpha = D3D12_BLEND_SRC_ALPHA; pipeDesc.BlendState.RenderTarget[0].DestBlendAlpha = D3D12_BLEND_INV_SRC_ALPHA; pipeDesc.BlendState.RenderTarget[0].BlendOpAlpha = D3D12_BLEND_OP_ADD; pipeDesc.BlendState.RenderTarget[0].RenderTargetWriteMask = D3D12_COLOR_WRITE_ENABLE_ALL; hr = device->CreateGraphicsPipelineState(&pipeDesc, __uuidof(ID3D12PipelineState), (void **)&CheckerboardPipe); if(FAILED(hr)) { RDCERR("Couldn't create m_CheckerboardPipe! HRESULT: %s", ToStr(hr).c_str()); } pipeDesc.SampleDesc.Count = D3D12_MSAA_SAMPLECOUNT; hr = device->CreateGraphicsPipelineState(&pipeDesc, __uuidof(ID3D12PipelineState), (void **)&CheckerboardMSAAPipe); if(FAILED(hr)) { RDCERR("Couldn't create m_CheckerboardMSAAPipe! HRESULT: %s", ToStr(hr).c_str()); } pipeDesc.RTVFormats[0] = DXGI_FORMAT_R16G16B16A16_FLOAT; pipeDesc.BlendState.RenderTarget[0].BlendEnable = TRUE; for(size_t i = 0; i < ARRAY_COUNT(CheckerboardF16Pipe); i++) { pipeDesc.SampleDesc.Count = UINT(1 << i); D3D12_FEATURE_DATA_MULTISAMPLE_QUALITY_LEVELS check = {}; check.Format = DXGI_FORMAT_R16G16B16A16_FLOAT; check.SampleCount = pipeDesc.SampleDesc.Count; device->CheckFeatureSupport(D3D12_FEATURE_MULTISAMPLE_QUALITY_LEVELS, &check, sizeof(check)); if(check.NumQualityLevels == 0) continue; hr = device->CreateGraphicsPipelineState(&pipeDesc, __uuidof(ID3D12PipelineState), (void **)&CheckerboardF16Pipe[i]); if(FAILED(hr)) { RDCERR("Couldn't create CheckerboardF16Pipe[%zu]! HRESULT: %s", i, ToStr(hr).c_str()); } } SAFE_RELEASE(CheckerboardPS); SAFE_RELEASE(FullscreenVS); } shaderCache->SetCaching(false); } void D3D12Replay::GeneralMisc::Release() { SAFE_RELEASE(ResultReadbackBuffer); SAFE_RELEASE(CheckerboardRootSig); SAFE_RELEASE(CheckerboardPipe); SAFE_RELEASE(CheckerboardMSAAPipe); for(size_t i = 0; i < ARRAY_COUNT(CheckerboardF16Pipe); i++) SAFE_RELEASE(CheckerboardF16Pipe[i]); } void D3D12Replay::TextureRendering::Init(WrappedID3D12Device *device, D3D12DebugManager *debug) { HRESULT hr = S_OK; D3D12ShaderCache *shaderCache = device->GetShaderCache(); shaderCache->SetCaching(true); { ID3DBlob *root = shaderCache->MakeRootSig({ // VS cbuffer cbvParam(D3D12_SHADER_VISIBILITY_VERTEX, 0, 0), // normal FS cbuffer cbvParam(D3D12_SHADER_VISIBILITY_PIXEL, 0, 0), // heatmap cbuffer cbvParam(D3D12_SHADER_VISIBILITY_PIXEL, 0, 1), // display SRVs tableParam(D3D12_SHADER_VISIBILITY_PIXEL, D3D12_DESCRIPTOR_RANGE_TYPE_SRV, 0, 0, 32), // samplers tableParam(D3D12_SHADER_VISIBILITY_PIXEL, D3D12_DESCRIPTOR_RANGE_TYPE_SAMPLER, 0, 0, 2), }); RDCASSERT(root); hr = device->CreateRootSignature(0, root->GetBufferPointer(), root->GetBufferSize(), __uuidof(ID3D12RootSignature), (void **)&RootSig); if(FAILED(hr)) { RDCERR("Couldn't create tex display RootSig! HRESULT: %s", ToStr(hr).c_str()); } SAFE_RELEASE(root); } { rdcstr hlsl = GetEmbeddedResource(texdisplay_hlsl); ID3DBlob *TexDisplayPS = NULL; shaderCache->GetShaderBlob(hlsl.c_str(), "RENDERDOC_TexDisplayVS", D3DCOMPILE_WARNINGS_ARE_ERRORS, {}, "vs_5_0", &VS); RDCASSERT(VS); shaderCache->GetShaderBlob(hlsl.c_str(), "RENDERDOC_TexDisplayPS", D3DCOMPILE_WARNINGS_ARE_ERRORS, {}, "ps_5_0", &TexDisplayPS); RDCASSERT(TexDisplayPS); D3D12_GRAPHICS_PIPELINE_STATE_DESC pipeDesc = {}; pipeDesc.pRootSignature = RootSig; pipeDesc.VS.BytecodeLength = VS->GetBufferSize(); pipeDesc.VS.pShaderBytecode = VS->GetBufferPointer(); pipeDesc.PS.BytecodeLength = TexDisplayPS->GetBufferSize(); pipeDesc.PS.pShaderBytecode = TexDisplayPS->GetBufferPointer(); pipeDesc.RasterizerState.FillMode = D3D12_FILL_MODE_SOLID; pipeDesc.RasterizerState.CullMode = D3D12_CULL_MODE_NONE; pipeDesc.SampleMask = 0xFFFFFFFF; pipeDesc.SampleDesc.Count = 1; pipeDesc.IBStripCutValue = D3D12_INDEX_BUFFER_STRIP_CUT_VALUE_DISABLED; pipeDesc.PrimitiveTopologyType = D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE; pipeDesc.NumRenderTargets = 1; pipeDesc.RTVFormats[0] = DXGI_FORMAT_R8G8B8A8_UNORM_SRGB; pipeDesc.DSVFormat = DXGI_FORMAT_UNKNOWN; pipeDesc.BlendState.RenderTarget[0].BlendEnable = TRUE; pipeDesc.BlendState.RenderTarget[0].SrcBlend = D3D12_BLEND_SRC_ALPHA; pipeDesc.BlendState.RenderTarget[0].DestBlend = D3D12_BLEND_INV_SRC_ALPHA; pipeDesc.BlendState.RenderTarget[0].BlendOp = D3D12_BLEND_OP_ADD; pipeDesc.BlendState.RenderTarget[0].SrcBlendAlpha = D3D12_BLEND_SRC_ALPHA; pipeDesc.BlendState.RenderTarget[0].DestBlendAlpha = D3D12_BLEND_INV_SRC_ALPHA; pipeDesc.BlendState.RenderTarget[0].BlendOpAlpha = D3D12_BLEND_OP_ADD; pipeDesc.BlendState.RenderTarget[0].RenderTargetWriteMask = D3D12_COLOR_WRITE_ENABLE_ALL; hr = device->CreateGraphicsPipelineState(&pipeDesc, __uuidof(ID3D12PipelineState), (void **)&BlendPipe); if(FAILED(hr)) { RDCERR("Couldn't create m_TexDisplayBlendPipe! HRESULT: %s", ToStr(hr).c_str()); } pipeDesc.BlendState.RenderTarget[0].BlendEnable = FALSE; hr = device->CreateGraphicsPipelineState(&pipeDesc, __uuidof(ID3D12PipelineState), (void **)&SRGBPipe); if(FAILED(hr)) { RDCERR("Couldn't create m_TexDisplayPipe! HRESULT: %s", ToStr(hr).c_str()); } pipeDesc.RTVFormats[0] = DXGI_FORMAT_R8G8B8A8_UNORM; hr = device->CreateGraphicsPipelineState(&pipeDesc, __uuidof(ID3D12PipelineState), (void **)&LinearPipe); if(FAILED(hr)) { RDCERR("Couldn't create m_TexDisplayPipe! HRESULT: %s", ToStr(hr).c_str()); } pipeDesc.RTVFormats[0] = DXGI_FORMAT_R32G32B32A32_FLOAT; hr = device->CreateGraphicsPipelineState(&pipeDesc, __uuidof(ID3D12PipelineState), (void **)&F32Pipe); if(FAILED(hr)) { RDCERR("Couldn't create m_TexDisplayF32Pipe! HRESULT: %s", ToStr(hr).c_str()); } pipeDesc.RTVFormats[0] = DXGI_FORMAT_R16G16B16A16_FLOAT; hr = device->CreateGraphicsPipelineState(&pipeDesc, __uuidof(ID3D12PipelineState), (void **)&F16Pipe); if(FAILED(hr)) { RDCERR("Couldn't create m_TexDisplayF16Pipe! HRESULT: %s", ToStr(hr).c_str()); } SAFE_RELEASE(TexDisplayPS); hlsl = GetEmbeddedResource(texremap_hlsl); ID3DBlob *TexRemap[3] = {}; DXGI_FORMAT formats[3] = { DXGI_FORMAT_R8G8B8A8_TYPELESS, DXGI_FORMAT_R16G16B16A16_TYPELESS, DXGI_FORMAT_R32G32B32A32_TYPELESS, }; shaderCache->GetShaderBlob(hlsl.c_str(), "RENDERDOC_TexRemapFloat", D3DCOMPILE_WARNINGS_ARE_ERRORS, {}, "ps_5_0", &TexRemap[0]); RDCASSERT(TexRemap[0]); shaderCache->GetShaderBlob(hlsl.c_str(), "RENDERDOC_TexRemapUInt", D3DCOMPILE_WARNINGS_ARE_ERRORS, {}, "ps_5_0", &TexRemap[1]); RDCASSERT(TexRemap[1]); shaderCache->GetShaderBlob(hlsl.c_str(), "RENDERDOC_TexRemapSInt", D3DCOMPILE_WARNINGS_ARE_ERRORS, {}, "ps_5_0", &TexRemap[2]); RDCASSERT(TexRemap[2]); for(int f = 0; f < 3; f++) { for(int i = 0; i < 3; i++) { pipeDesc.PS.BytecodeLength = TexRemap[i]->GetBufferSize(); pipeDesc.PS.pShaderBytecode = TexRemap[i]->GetBufferPointer(); if(i == 0) pipeDesc.RTVFormats[0] = GetFloatTypedFormat(formats[f]); else if(i == 1) pipeDesc.RTVFormats[0] = GetUIntTypedFormat(formats[f]); else pipeDesc.RTVFormats[0] = GetSIntTypedFormat(formats[f]); hr = device->CreateGraphicsPipelineState(&pipeDesc, __uuidof(ID3D12PipelineState), (void **)&m_TexRemapPipe[f][i]); if(FAILED(hr)) { RDCERR("Couldn't create m_TexRemapPipe for %s! HRESULT: %s", ToStr(pipeDesc.RTVFormats[0]).c_str(), ToStr(hr).c_str()); } } } for(int i = 0; i < 3; i++) SAFE_RELEASE(TexRemap[i]); } shaderCache->SetCaching(false); } void D3D12Replay::TextureRendering::Release() { SAFE_RELEASE(BlendPipe); SAFE_RELEASE(SRGBPipe); SAFE_RELEASE(LinearPipe); SAFE_RELEASE(F16Pipe); SAFE_RELEASE(F32Pipe); SAFE_RELEASE(RootSig); SAFE_RELEASE(VS); for(int f = 0; f < 3; f++) { for(int i = 0; i < 3; i++) { SAFE_RELEASE(m_TexRemapPipe[f][i]); } } } void D3D12Replay::OverlayRendering::Init(WrappedID3D12Device *device, D3D12DebugManager *debug) { HRESULT hr = S_OK; D3D12ShaderCache *shaderCache = device->GetShaderCache(); shaderCache->SetCaching(true); { rdcstr meshhlsl = GetEmbeddedResource(mesh_hlsl); shaderCache->GetShaderBlob(meshhlsl.c_str(), "RENDERDOC_TriangleSizeGS", D3DCOMPILE_WARNINGS_ARE_ERRORS, {}, "gs_5_0", &TriangleSizeGS); shaderCache->GetShaderBlob(meshhlsl.c_str(), "RENDERDOC_TriangleSizePS", D3DCOMPILE_WARNINGS_ARE_ERRORS, {}, "ps_5_0", &TriangleSizePS); shaderCache->GetShaderBlob(meshhlsl.c_str(), "RENDERDOC_MeshVS", D3DCOMPILE_WARNINGS_ARE_ERRORS, {}, "vs_5_0", &MeshVS); rdcstr hlsl = GetEmbeddedResource(quadoverdraw_hlsl); shaderCache->GetShaderBlob(hlsl.c_str(), "RENDERDOC_QuadOverdrawPS", D3DCOMPILE_WARNINGS_ARE_ERRORS, {}, "ps_5_0", &QuadOverdrawWritePS); // only create DXIL shaders if DXIL was used by the application, since dxc/dxcompiler is really // flakey. if(device->UsedDXIL()) { shaderCache->GetShaderBlob(hlsl.c_str(), "RENDERDOC_QuadOverdrawPS", D3DCOMPILE_WARNINGS_ARE_ERRORS, {}, "ps_6_0", &QuadOverdrawWriteDXILPS); if(QuadOverdrawWriteDXILPS == NULL) { RDCWARN( "Couldn't compile DXIL overlay shader at runtime, falling back to baked DXIL shader"); QuadOverdrawWriteDXILPS = shaderCache->GetQuadShaderDXILBlob(); if(!QuadOverdrawWriteDXILPS) { RDCWARN("No fallback DXIL shader available!"); } } } } { ID3DBlob *root = shaderCache->MakeRootSig({ // quad overdraw results SRV tableParam(D3D12_SHADER_VISIBILITY_PIXEL, D3D12_DESCRIPTOR_RANGE_TYPE_SRV, 0, 0, 1), }); RDCASSERT(root); hr = device->CreateRootSignature(0, root->GetBufferPointer(), root->GetBufferSize(), __uuidof(ID3D12RootSignature), (void **)&QuadResolveRootSig); SAFE_RELEASE(root); } { rdcstr hlsl = GetEmbeddedResource(misc_hlsl); ID3DBlob *FullscreenVS = NULL; shaderCache->GetShaderBlob(hlsl.c_str(), "RENDERDOC_FullscreenVS", D3DCOMPILE_WARNINGS_ARE_ERRORS, {}, "vs_5_0", &FullscreenVS); RDCASSERT(FullscreenVS); hlsl = GetEmbeddedResource(quadoverdraw_hlsl); ID3DBlob *QOResolvePS = NULL; shaderCache->GetShaderBlob(hlsl.c_str(), "RENDERDOC_QOResolvePS", D3DCOMPILE_WARNINGS_ARE_ERRORS, {}, "ps_5_0", &QOResolvePS); RDCASSERT(QOResolvePS); D3D12_GRAPHICS_PIPELINE_STATE_DESC pipeDesc = {}; pipeDesc.pRootSignature = QuadResolveRootSig; pipeDesc.VS.BytecodeLength = FullscreenVS->GetBufferSize(); pipeDesc.VS.pShaderBytecode = FullscreenVS->GetBufferPointer(); pipeDesc.PS.BytecodeLength = QOResolvePS->GetBufferSize(); pipeDesc.PS.pShaderBytecode = QOResolvePS->GetBufferPointer(); pipeDesc.RasterizerState.FillMode = D3D12_FILL_MODE_SOLID; pipeDesc.RasterizerState.CullMode = D3D12_CULL_MODE_NONE; pipeDesc.SampleMask = 0xFFFFFFFF; pipeDesc.SampleDesc.Count = 1; pipeDesc.IBStripCutValue = D3D12_INDEX_BUFFER_STRIP_CUT_VALUE_DISABLED; pipeDesc.PrimitiveTopologyType = D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE; pipeDesc.NumRenderTargets = 1; pipeDesc.RTVFormats[0] = DXGI_FORMAT_R16G16B16A16_FLOAT; pipeDesc.DSVFormat = DXGI_FORMAT_UNKNOWN; pipeDesc.BlendState.RenderTarget[0].BlendEnable = FALSE; pipeDesc.BlendState.RenderTarget[0].SrcBlend = D3D12_BLEND_SRC_ALPHA; pipeDesc.BlendState.RenderTarget[0].DestBlend = D3D12_BLEND_INV_SRC_ALPHA; pipeDesc.BlendState.RenderTarget[0].BlendOp = D3D12_BLEND_OP_ADD; pipeDesc.BlendState.RenderTarget[0].SrcBlendAlpha = D3D12_BLEND_SRC_ALPHA; pipeDesc.BlendState.RenderTarget[0].DestBlendAlpha = D3D12_BLEND_INV_SRC_ALPHA; pipeDesc.BlendState.RenderTarget[0].BlendOpAlpha = D3D12_BLEND_OP_ADD; pipeDesc.BlendState.RenderTarget[0].RenderTargetWriteMask = D3D12_COLOR_WRITE_ENABLE_ALL; for(size_t i = 0; i < ARRAY_COUNT(QuadResolvePipe); i++) { pipeDesc.SampleDesc.Count = UINT(1 << i); D3D12_FEATURE_DATA_MULTISAMPLE_QUALITY_LEVELS check = {}; check.Format = DXGI_FORMAT_R16G16B16A16_FLOAT; check.SampleCount = pipeDesc.SampleDesc.Count; device->CheckFeatureSupport(D3D12_FEATURE_MULTISAMPLE_QUALITY_LEVELS, &check, sizeof(check)); if(check.NumQualityLevels == 0) continue; hr = device->CreateGraphicsPipelineState(&pipeDesc, __uuidof(ID3D12PipelineState), (void **)&QuadResolvePipe[i]); if(FAILED(hr)) RDCERR("Couldn't create QuadResolvePipe[%zu]! HRESULT: %s", i, ToStr(hr).c_str()); } SAFE_RELEASE(FullscreenVS); SAFE_RELEASE(QOResolvePS); } shaderCache->SetCaching(false); } void D3D12Replay::OverlayRendering::Release() { SAFE_RELEASE(MeshVS); SAFE_RELEASE(TriangleSizeGS); SAFE_RELEASE(TriangleSizePS); SAFE_RELEASE(QuadOverdrawWritePS); SAFE_RELEASE(QuadOverdrawWriteDXILPS); SAFE_RELEASE(QuadResolveRootSig); for(size_t i = 0; i < ARRAY_COUNT(QuadResolvePipe); i++) SAFE_RELEASE(QuadResolvePipe[i]); SAFE_RELEASE(Texture); } void D3D12Replay::VertexPicking::Init(WrappedID3D12Device *device, D3D12DebugManager *debug) { HRESULT hr = S_OK; D3D12ShaderCache *shaderCache = device->GetShaderCache(); shaderCache->SetCaching(true); VB = NULL; VBSize = 0; { ID3DBlob *root = shaderCache->MakeRootSig({ cbvParam(D3D12_SHADER_VISIBILITY_ALL, 0, 0), tableParam(D3D12_SHADER_VISIBILITY_ALL, D3D12_DESCRIPTOR_RANGE_TYPE_SRV, 0, 0, 2), tableParam(D3D12_SHADER_VISIBILITY_ALL, D3D12_DESCRIPTOR_RANGE_TYPE_UAV, 0, 0, 1), }); RDCASSERT(root); hr = device->CreateRootSignature(0, root->GetBufferPointer(), root->GetBufferSize(), __uuidof(ID3D12RootSignature), (void **)&RootSig); SAFE_RELEASE(root); } { rdcstr meshhlsl = GetEmbeddedResource(mesh_hlsl); ID3DBlob *meshPickCS; shaderCache->GetShaderBlob(meshhlsl.c_str(), "RENDERDOC_MeshPickCS", D3DCOMPILE_WARNINGS_ARE_ERRORS, {}, "cs_5_0", &meshPickCS); RDCASSERT(meshPickCS); D3D12_COMPUTE_PIPELINE_STATE_DESC compPipeDesc = {}; compPipeDesc.pRootSignature = RootSig; compPipeDesc.CS.BytecodeLength = meshPickCS->GetBufferSize(); compPipeDesc.CS.pShaderBytecode = meshPickCS->GetBufferPointer(); hr = device->CreateComputePipelineState(&compPipeDesc, __uuidof(ID3D12PipelineState), (void **)&Pipe); if(FAILED(hr)) { RDCERR("Couldn't create m_MeshPickPipe! HRESULT: %s", ToStr(hr).c_str()); } SAFE_RELEASE(meshPickCS); } { D3D12_RESOURCE_DESC pickResultDesc = {}; pickResultDesc.Alignment = 0; pickResultDesc.DepthOrArraySize = 1; pickResultDesc.Dimension = D3D12_RESOURCE_DIMENSION_BUFFER; pickResultDesc.Flags = D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS; pickResultDesc.Format = DXGI_FORMAT_UNKNOWN; pickResultDesc.Height = 1; pickResultDesc.Layout = D3D12_TEXTURE_LAYOUT_ROW_MAJOR; pickResultDesc.MipLevels = 1; pickResultDesc.SampleDesc.Count = 1; pickResultDesc.SampleDesc.Quality = 0; // add an extra 64 bytes for the counter at the start pickResultDesc.Width = MaxMeshPicks * sizeof(Vec4f) + 64; D3D12_HEAP_PROPERTIES heapProps; heapProps.Type = D3D12_HEAP_TYPE_DEFAULT; heapProps.CPUPageProperty = D3D12_CPU_PAGE_PROPERTY_UNKNOWN; heapProps.MemoryPoolPreference = D3D12_MEMORY_POOL_UNKNOWN; heapProps.CreationNodeMask = 1; heapProps.VisibleNodeMask = 1; hr = device->CreateCommittedResource(&heapProps, D3D12_HEAP_FLAG_NONE, &pickResultDesc, D3D12_RESOURCE_STATE_UNORDERED_ACCESS, NULL, __uuidof(ID3D12Resource), (void **)&ResultBuf); ResultBuf->SetName(L"m_PickResultBuf"); if(FAILED(hr)) { RDCERR("Failed to create tile buffer for min/max, HRESULT: %s", ToStr(hr).c_str()); } D3D12_UNORDERED_ACCESS_VIEW_DESC uavDesc = {}; uavDesc.ViewDimension = D3D12_UAV_DIMENSION_BUFFER; uavDesc.Format = DXGI_FORMAT_UNKNOWN; uavDesc.Buffer.CounterOffsetInBytes = 0; // start with elements after the counter uavDesc.Buffer.FirstElement = 64 / sizeof(Vec4f); uavDesc.Buffer.NumElements = MaxMeshPicks; uavDesc.Buffer.StructureByteStride = sizeof(Vec4f); device->CreateUnorderedAccessView(ResultBuf, ResultBuf, &uavDesc, debug->GetCPUHandle(PICK_RESULT_UAV)); device->CreateUnorderedAccessView(ResultBuf, ResultBuf, &uavDesc, debug->GetUAVClearHandle(PICK_RESULT_UAV)); // this UAV is used for clearing everything back to 0 uavDesc.Format = DXGI_FORMAT_R32G32B32A32_UINT; uavDesc.Buffer.FirstElement = 0; uavDesc.Buffer.NumElements = MaxMeshPicks + 64 / sizeof(Vec4f); uavDesc.Buffer.StructureByteStride = 0; device->CreateUnorderedAccessView(ResultBuf, NULL, &uavDesc, debug->GetCPUHandle(PICK_RESULT_CLEAR_UAV)); device->CreateUnorderedAccessView(ResultBuf, NULL, &uavDesc, debug->GetUAVClearHandle(PICK_RESULT_CLEAR_UAV)); } shaderCache->SetCaching(false); } void D3D12Replay::VertexPicking::Release() { SAFE_RELEASE(IB); SAFE_RELEASE(VB); SAFE_RELEASE(ResultBuf); SAFE_RELEASE(RootSig); SAFE_RELEASE(Pipe); } void D3D12Replay::PixelPicking::Init(WrappedID3D12Device *device, D3D12DebugManager *debug) { HRESULT hr = S_OK; { D3D12_RESOURCE_DESC pickPixelDesc = {}; pickPixelDesc.Alignment = 0; pickPixelDesc.DepthOrArraySize = 1; pickPixelDesc.Dimension = D3D12_RESOURCE_DIMENSION_TEXTURE2D; pickPixelDesc.Flags = D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET; pickPixelDesc.Format = DXGI_FORMAT_R32G32B32A32_FLOAT; pickPixelDesc.Height = 1; pickPixelDesc.Layout = D3D12_TEXTURE_LAYOUT_UNKNOWN; pickPixelDesc.MipLevels = 1; pickPixelDesc.SampleDesc.Count = 1; pickPixelDesc.SampleDesc.Quality = 0; pickPixelDesc.Width = 1; D3D12_HEAP_PROPERTIES heapProps; heapProps.Type = D3D12_HEAP_TYPE_DEFAULT; heapProps.CPUPageProperty = D3D12_CPU_PAGE_PROPERTY_UNKNOWN; heapProps.MemoryPoolPreference = D3D12_MEMORY_POOL_UNKNOWN; heapProps.CreationNodeMask = 1; heapProps.VisibleNodeMask = 1; hr = device->CreateCommittedResource(&heapProps, D3D12_HEAP_FLAG_NONE, &pickPixelDesc, D3D12_RESOURCE_STATE_RENDER_TARGET, NULL, __uuidof(ID3D12Resource), (void **)&Texture); Texture->SetName(L"m_PickPixelTex"); if(FAILED(hr)) { RDCERR("Failed to create rendering texture for pixel picking, HRESULT: %s", ToStr(hr).c_str()); return; } D3D12_CPU_DESCRIPTOR_HANDLE rtv = debug->GetCPUHandle(PICK_PIXEL_RTV); device->CreateRenderTargetView(Texture, NULL, rtv); } } void D3D12Replay::PixelPicking::Release() { SAFE_RELEASE(Texture); } void D3D12Replay::HistogramMinMax::Init(WrappedID3D12Device *device, D3D12DebugManager *debug) { HRESULT hr = S_OK; D3D12ShaderCache *shaderCache = device->GetShaderCache(); shaderCache->SetCaching(true); { ID3DBlob *root = shaderCache->MakeRootSig({ cbvParam(D3D12_SHADER_VISIBILITY_ALL, 0, 0), // texture SRVs tableParam(D3D12_SHADER_VISIBILITY_ALL, D3D12_DESCRIPTOR_RANGE_TYPE_SRV, 0, 0, 32), // samplers tableParam(D3D12_SHADER_VISIBILITY_ALL, D3D12_DESCRIPTOR_RANGE_TYPE_SAMPLER, 0, 0, 2), // UAVs tableParam(D3D12_SHADER_VISIBILITY_ALL, D3D12_DESCRIPTOR_RANGE_TYPE_UAV, 0, 0, 3), }); RDCASSERT(root); hr = device->CreateRootSignature(0, root->GetBufferPointer(), root->GetBufferSize(), __uuidof(ID3D12RootSignature), (void **)&HistogramRootSig); SAFE_RELEASE(root); } { rdcstr histogramhlsl = GetEmbeddedResource(histogram_hlsl); D3D12_COMPUTE_PIPELINE_STATE_DESC compPipeDesc = {}; compPipeDesc.pRootSignature = HistogramRootSig; for(int t = RESTYPE_TEX1D; t <= RESTYPE_TEX2D_MS; t++) { // skip unused cube slot if(t == 8) continue; // float, uint, sint for(int i = 0; i < 3; i++) { ID3DBlob *tile = NULL; ID3DBlob *result = NULL; ID3DBlob *histogram = NULL; rdcstr hlsl = rdcstr("#define SHADER_RESTYPE ") + ToStr(t) + "\n"; hlsl += rdcstr("#define SHADER_BASETYPE ") + ToStr(i) + "\n"; hlsl += histogramhlsl; shaderCache->GetShaderBlob(hlsl.c_str(), "RENDERDOC_TileMinMaxCS", D3DCOMPILE_WARNINGS_ARE_ERRORS, {}, "cs_5_0", &tile); compPipeDesc.CS.BytecodeLength = tile->GetBufferSize(); compPipeDesc.CS.pShaderBytecode = tile->GetBufferPointer(); hr = device->CreateComputePipelineState(&compPipeDesc, __uuidof(ID3D12PipelineState), (void **)&TileMinMaxPipe[t][i]); if(FAILED(hr)) { RDCERR("Couldn't create m_TileMinMaxPipe! HRESULT: %s", ToStr(hr).c_str()); } shaderCache->GetShaderBlob(hlsl.c_str(), "RENDERDOC_HistogramCS", D3DCOMPILE_WARNINGS_ARE_ERRORS, {}, "cs_5_0", &histogram); compPipeDesc.CS.BytecodeLength = histogram->GetBufferSize(); compPipeDesc.CS.pShaderBytecode = histogram->GetBufferPointer(); hr = device->CreateComputePipelineState(&compPipeDesc, __uuidof(ID3D12PipelineState), (void **)&HistogramPipe[t][i]); if(FAILED(hr)) { RDCERR("Couldn't create m_HistogramPipe! HRESULT: %s", ToStr(hr).c_str()); } if(t == 1) { shaderCache->GetShaderBlob(hlsl.c_str(), "RENDERDOC_ResultMinMaxCS", D3DCOMPILE_WARNINGS_ARE_ERRORS, {}, "cs_5_0", &result); compPipeDesc.CS.BytecodeLength = result->GetBufferSize(); compPipeDesc.CS.pShaderBytecode = result->GetBufferPointer(); hr = device->CreateComputePipelineState(&compPipeDesc, __uuidof(ID3D12PipelineState), (void **)&ResultMinMaxPipe[i]); if(FAILED(hr)) { RDCERR("Couldn't create m_HistogramPipe! HRESULT: %s", ToStr(hr).c_str()); } } SAFE_RELEASE(tile); SAFE_RELEASE(histogram); SAFE_RELEASE(result); } } } { const uint64_t maxTexDim = 16384; const uint64_t blockPixSize = HGRAM_PIXELS_PER_TILE * HGRAM_TILES_PER_BLOCK; const uint64_t maxBlocksNeeded = (maxTexDim * maxTexDim) / (blockPixSize * blockPixSize); D3D12_RESOURCE_DESC minmaxDesc = {}; minmaxDesc.Alignment = 0; minmaxDesc.DepthOrArraySize = 1; minmaxDesc.Dimension = D3D12_RESOURCE_DIMENSION_BUFFER; minmaxDesc.Flags = D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS; minmaxDesc.Format = DXGI_FORMAT_UNKNOWN; minmaxDesc.Height = 1; minmaxDesc.Layout = D3D12_TEXTURE_LAYOUT_ROW_MAJOR; minmaxDesc.MipLevels = 1; minmaxDesc.SampleDesc.Count = 1; minmaxDesc.SampleDesc.Quality = 0; minmaxDesc.Width = 2 * sizeof(Vec4f) * HGRAM_TILES_PER_BLOCK * HGRAM_TILES_PER_BLOCK * maxBlocksNeeded; D3D12_HEAP_PROPERTIES heapProps; heapProps.Type = D3D12_HEAP_TYPE_DEFAULT; heapProps.CPUPageProperty = D3D12_CPU_PAGE_PROPERTY_UNKNOWN; heapProps.MemoryPoolPreference = D3D12_MEMORY_POOL_UNKNOWN; heapProps.CreationNodeMask = 1; heapProps.VisibleNodeMask = 1; hr = device->CreateCommittedResource(&heapProps, D3D12_HEAP_FLAG_NONE, &minmaxDesc, D3D12_RESOURCE_STATE_UNORDERED_ACCESS, NULL, __uuidof(ID3D12Resource), (void **)&MinMaxTileBuffer); MinMaxTileBuffer->SetName(L"m_MinMaxTileBuffer"); if(FAILED(hr)) { RDCERR("Failed to create tile buffer for min/max, HRESULT: %s", ToStr(hr).c_str()); return; } D3D12_CPU_DESCRIPTOR_HANDLE uav = debug->GetCPUHandle(MINMAX_TILE_UAVS); D3D12_UNORDERED_ACCESS_VIEW_DESC tileDesc = {}; tileDesc.Format = DXGI_FORMAT_R32G32B32A32_FLOAT; tileDesc.ViewDimension = D3D12_UAV_DIMENSION_BUFFER; tileDesc.Buffer.FirstElement = 0; tileDesc.Buffer.NumElements = UINT(minmaxDesc.Width / sizeof(Vec4f)); device->CreateUnorderedAccessView(MinMaxTileBuffer, NULL, &tileDesc, uav); uav.ptr += sizeof(D3D12Descriptor); tileDesc.Format = DXGI_FORMAT_R32G32B32A32_UINT; device->CreateUnorderedAccessView(MinMaxTileBuffer, NULL, &tileDesc, uav); uav.ptr += sizeof(D3D12Descriptor); tileDesc.Format = DXGI_FORMAT_R32G32B32A32_SINT; device->CreateUnorderedAccessView(MinMaxTileBuffer, NULL, &tileDesc, uav); uav = debug->GetCPUHandle(HISTOGRAM_UAV); // re-use the tile buffer for histogram tileDesc.Format = DXGI_FORMAT_R32_UINT; tileDesc.Buffer.NumElements = HGRAM_NUM_BUCKETS; device->CreateUnorderedAccessView(MinMaxTileBuffer, NULL, &tileDesc, uav); device->CreateUnorderedAccessView(MinMaxTileBuffer, NULL, &tileDesc, debug->GetUAVClearHandle(HISTOGRAM_UAV)); D3D12_SHADER_RESOURCE_VIEW_DESC srvDesc = {}; srvDesc.ViewDimension = D3D12_SRV_DIMENSION_BUFFER; srvDesc.Format = DXGI_FORMAT_R32G32B32A32_FLOAT; srvDesc.Shader4ComponentMapping = D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING; srvDesc.Buffer.FirstElement = 0; srvDesc.Buffer.NumElements = UINT(minmaxDesc.Width / sizeof(Vec4f)); D3D12_CPU_DESCRIPTOR_HANDLE srv = debug->GetCPUHandle(MINMAX_TILE_SRVS); device->CreateShaderResourceView(MinMaxTileBuffer, &srvDesc, srv); srv.ptr += sizeof(D3D12Descriptor); srvDesc.Format = DXGI_FORMAT_R32G32B32A32_UINT; device->CreateShaderResourceView(MinMaxTileBuffer, &srvDesc, srv); srv.ptr += sizeof(D3D12Descriptor); srvDesc.Format = DXGI_FORMAT_R32G32B32A32_SINT; device->CreateShaderResourceView(MinMaxTileBuffer, &srvDesc, srv); minmaxDesc.Width = 2 * sizeof(Vec4f); hr = device->CreateCommittedResource(&heapProps, D3D12_HEAP_FLAG_NONE, &minmaxDesc, D3D12_RESOURCE_STATE_UNORDERED_ACCESS, NULL, __uuidof(ID3D12Resource), (void **)&MinMaxResultBuffer); MinMaxResultBuffer->SetName(L"m_MinMaxResultBuffer"); if(FAILED(hr)) { RDCERR("Failed to create result buffer for min/max, HRESULT: %s", ToStr(hr).c_str()); return; } uav = debug->GetCPUHandle(MINMAX_RESULT_UAVS); tileDesc.Buffer.NumElements = 2; tileDesc.Format = DXGI_FORMAT_R32G32B32A32_FLOAT; device->CreateUnorderedAccessView(MinMaxResultBuffer, NULL, &tileDesc, uav); uav.ptr += sizeof(D3D12Descriptor); tileDesc.Format = DXGI_FORMAT_R32G32B32A32_UINT; device->CreateUnorderedAccessView(MinMaxResultBuffer, NULL, &tileDesc, uav); uav.ptr += sizeof(D3D12Descriptor); tileDesc.Format = DXGI_FORMAT_R32G32B32A32_SINT; device->CreateUnorderedAccessView(MinMaxResultBuffer, NULL, &tileDesc, uav); } shaderCache->SetCaching(false); } void D3D12Replay::HistogramMinMax::Release() { SAFE_RELEASE(HistogramRootSig); for(int t = RESTYPE_TEX1D; t <= RESTYPE_TEX2D_MS; t++) { for(int i = 0; i < 3; i++) { SAFE_RELEASE(TileMinMaxPipe[t][i]); SAFE_RELEASE(HistogramPipe[t][i]); if(t == RESTYPE_TEX1D) SAFE_RELEASE(ResultMinMaxPipe[i]); } } SAFE_RELEASE(MinMaxResultBuffer); SAFE_RELEASE(MinMaxTileBuffer); } void MoveRootSignatureElementsToRegisterSpace(D3D12RootSignature &sig, uint32_t registerSpace, D3D12DescriptorType type, D3D12_SHADER_VISIBILITY visibility) { // This function is used when root signature elements need to be added to a specific register // space, such as for debug overlays. We can't remove elements from the root signature entirely // because then then the root signature indices wouldn't match up as expected. Instead move them // into the specified register space so that another register space (commonly space0) can be used // for other purposes. size_t numParams = sig.Parameters.size(); for(size_t i = 0; i < numParams; i++) { if(sig.Parameters[i].ShaderVisibility == visibility || sig.Parameters[i].ShaderVisibility == D3D12_SHADER_VISIBILITY_ALL) { D3D12_ROOT_PARAMETER_TYPE rootType = sig.Parameters[i].ParameterType; if(rootType == D3D12_ROOT_PARAMETER_TYPE_DESCRIPTOR_TABLE) { size_t numRanges = sig.Parameters[i].ranges.size(); for(size_t r = 0; r < numRanges; r++) { D3D12_DESCRIPTOR_RANGE_TYPE rangeType = sig.Parameters[i].ranges[r].RangeType; if(rangeType == D3D12_DESCRIPTOR_RANGE_TYPE_CBV && type == D3D12DescriptorType::CBV) { sig.Parameters[i].ranges[r].RegisterSpace += registerSpace; } else if(rangeType == D3D12_DESCRIPTOR_RANGE_TYPE_SRV && type == D3D12DescriptorType::SRV) { sig.Parameters[i].ranges[r].RegisterSpace += registerSpace; } else if(rangeType == D3D12_DESCRIPTOR_RANGE_TYPE_UAV && type == D3D12DescriptorType::UAV) { sig.Parameters[i].ranges[r].RegisterSpace += registerSpace; } } } else if(rootType == D3D12_ROOT_PARAMETER_TYPE_CBV && type == D3D12DescriptorType::CBV) { sig.Parameters[i].Descriptor.RegisterSpace += registerSpace; } else if(rootType == D3D12_ROOT_PARAMETER_TYPE_SRV && type == D3D12DescriptorType::SRV) { sig.Parameters[i].Descriptor.RegisterSpace += registerSpace; } else if(rootType == D3D12_ROOT_PARAMETER_TYPE_UAV && type == D3D12DescriptorType::UAV) { sig.Parameters[i].Descriptor.RegisterSpace += registerSpace; } } } } void AddDebugDescriptorsToRenderState(WrappedID3D12Device *pDevice, D3D12RenderState &rs, const rdcarray<PortableHandle> &handles, D3D12_DESCRIPTOR_HEAP_TYPE heapType, uint32_t sigElem, std::set<ResourceId> &copiedHeaps) { if(rs.graphics.sigelems.size() <= sigElem) rs.graphics.sigelems.resize(sigElem + 1); PortableHandle newHandle = handles[0]; // If a CBV_SRV_UAV heap is already set and hasn't had a debug descriptor copied in, // copy the desired descriptor in and add the heap to the set of heaps that have had // a debug descriptor set. If there's no available heapOtherwise we can set our own heap. // It is the responsibility of the caller to keep track of the set of copied heaps to // avoid overwriting another debug descriptor that may be needed. for(size_t i = 0; i < rs.heaps.size(); i++) { WrappedID3D12DescriptorHeap *h = pDevice->GetResourceManager()->GetCurrentAs<WrappedID3D12DescriptorHeap>(rs.heaps[i]); if(h->GetDesc().Type == heapType) { // use the last descriptors D3D12_CPU_DESCRIPTOR_HANDLE dst = h->GetCPUDescriptorHandleForHeapStart(); dst.ptr += (h->GetDesc().NumDescriptors - handles.size()) * sizeof(D3D12Descriptor); newHandle = ToPortableHandle(dst); if(copiedHeaps.find(rs.heaps[i]) == copiedHeaps.end()) { for(size_t j = 0; j < handles.size(); ++j) { WrappedID3D12DescriptorHeap *h2 = pDevice->GetResourceManager()->GetCurrentAs<WrappedID3D12DescriptorHeap>( handles[j].heap); D3D12_CPU_DESCRIPTOR_HANDLE src = h2->GetCPUDescriptorHandleForHeapStart(); src.ptr += handles[j].index * sizeof(D3D12Descriptor); // can't do a copy because the src heap is CPU write-only (shader visible). So instead, // create directly D3D12Descriptor *srcDesc = (D3D12Descriptor *)src.ptr; srcDesc->Create(heapType, pDevice, dst); dst.ptr += sizeof(D3D12Descriptor); } copiedHeaps.insert(rs.heaps[i]); } break; } } if(newHandle.heap == handles[0].heap) rs.heaps.push_back(handles[0].heap); rs.graphics.sigelems[sigElem] = D3D12RenderState::SignatureElement(eRootTable, newHandle.heap, newHandle.index); }
[ "bradyjessup@hotmail.com" ]
bradyjessup@hotmail.com
63e64ab93b2d5c5bf70eabe37cdf79f4ee6b4961
539080b0a026f8888ffab7c43f11223310369395
/src/RcppExports.cpp
b8c27e9e1282b060fae1979bfbfa5e8c3bc51306
[]
no_license
shortyatz/Nlopt-and-Rcpp
b87601d6f4b422f4a29481d2aa6e9e6be0a932f4
fc03d14db42bb306af63c52e97b205962d276eb7
refs/heads/master
2020-03-26T17:45:12.145857
2018-08-18T00:35:52
2018-08-18T00:35:52
145,178,146
0
0
null
null
null
null
UTF-8
C++
false
false
710
cpp
// Generated by using Rcpp::compileAttributes() -> do not edit by hand // Generator token: 10BE3573-1514-4C36-9D1C-5A225CD40393 #include <RcppArmadillo.h> #include <Rcpp.h> using namespace Rcpp; // test double test(); RcppExport SEXP _nloptCppTest_test() { BEGIN_RCPP Rcpp::RObject rcpp_result_gen; Rcpp::RNGScope rcpp_rngScope_gen; rcpp_result_gen = Rcpp::wrap(test()); return rcpp_result_gen; END_RCPP } static const R_CallMethodDef CallEntries[] = { {"_nloptCppTest_test", (DL_FUNC) &_nloptCppTest_test, 0}, {NULL, NULL, 0} }; RcppExport void R_init_nloptCppTest(DllInfo *dll) { R_registerRoutines(dll, NULL, CallEntries, NULL, NULL); R_useDynamicSymbols(dll, FALSE); }
[ "shortykatz@gmail.com" ]
shortykatz@gmail.com
948e53a1357edea8032fade26f9cf01b21ccac41
97a019b52a56cfd16cd7c4dbb730e83c581d2b3e
/Archived/Research/GeneralizedCapturePoint/gcp.h
e69672f6a41072fccea20b365a065ce7fdcaa00a
[]
no_license
nalinraut/high-level-Motion-Planning
f0263dcfa344b914159b0486370bc544552ac360
08cd792124defba63583ba6ae6394b20329d38c0
refs/heads/master
2020-03-09T04:20:12.846801
2018-04-09T06:11:29
2018-04-09T06:11:29
128,585,159
1
1
null
null
null
null
UTF-8
C++
false
false
6,566
h
#ifndef GENERALIZED_CAPTURE_POINT_H #define GENERALIZED_CAPTURE_POINT_H #include <stdlib.h> #include <vector> namespace GCP { typedef double Real; class Vector2 { public: Vector2(); Vector2(Real x,Real y); Real x,y; }; class Segment { public: ///Sorts the endpoints in increasing / decreasing x component void Sort(bool increasing=true); ///Returns the height of the segment at x coordinate x Real HeightOf(Real x) const; ///Returns the point at interpolation coordinate u Vector2 Eval(Real u) const; ///Returns the unit tangent vector of the segment Vector2 Tangent() const; ///Returns the unit normal vector of the segment (points to the "left") Vector2 Normal() const; ///Returns the minimum distance to x Real Distance(const Vector2& x) const; ///Returns the point on the segment with minimum distance to x Vector2 ClosestPoint(const Vector2& x) const; Vector2 a,b; }; class PolygonalTerrain { public: ///Negates all of the terrain's x values and segment a/b orders. ///Useful for setting up problems with negative initial x velocities. void FlipX(); ///Sorts the segments in increasing x component of their start //points void Sort(); ///Returns true if the terrain is sorted in increasing x order bool IsSorted() const; ///Returns true if the terrain has no segments overlapping one another ///in the vertical direction bool IsHeightfield() const; ///Returns true if the terrain forms a simple connected chain with ///increasing x component bool IsSimple() const; ///Evaluates a point on the terrain given u in [0,1] Vector2 Evaluate(Real u) const; ///Returns the index of the segment below the given point. Assumes ///segments are sorted by increasing x component int SegmentBelow(const Vector2& pt) const; ///Returns the point on the terrain below the given point. Assumes ///segments are sorted by increasing x component Vector2 PointBelow(const Vector2& pt) const; ///Retrieves a window of a terrain inside a bounding box void Range(const Vector2& bmin,const Vector2& bmax,PolygonalTerrain& result) const; std::vector<Segment> segments; }; class Problem { public: enum SimulationResult { Capture, Overshoot, Undershoot, Slip, MaxItersReached }; ///initialize empty problem. Gravity assumed to be 9.8m/s^2 Problem(); ///initialize standard CP problem along horizontal COM trajectory ///with height h, x velocity vx0. x position, z velocity are assumed ///to be 0. Gravity assumed to be 9.8m/s^2 Problem(Real h,Real vx0); void SetInitialConditions(const Vector2& x0,const Vector2& v0); void SetGravity(Real g); void SetFriction(Real mu); void SetStancePoint(const Vector2& p); ///Solves for a CP that keeps the robot stable along the quadratic path ///starting at x0,v0 and has second derivative dz^2/d^2x = pathCurvature. ///Sets the pathCurvature and capturePoint attributes. Returns true if ///successful. Returns false if not, and capturePoint is set to the best ///found capture point in terms of maximizing time before overshoot / ///undershoot (Note: if false is returned, it may not be reachable...). bool SolveCPFromCurvature(Real pathCurvature,Real tolerance=1e-5); ///Solves for a path curvature with the given CP, that keeps the robot ///stable along the quadratic path starting at x0,v0 and has second ///derivative dz^2/d^2x = pathCurvature. Sets the pathCurvature and ///capturePoint attributes. Returns true if successful. Returns false ///if not, and pathCurvature is set to the best found path curvature ///in terms of maximizing time before overshoot / undershoot. (Note: if ///false is returned, it may not be reachable...) bool SolveCurvatureFromCP(const Vector2& capturePoint,const Vector2& capturePointNormal,Real tolerance=1e-5); ///Solves for all (path curvature,CP) pairs for which CP forms a capture ///point for the quadratic path starting at x0,v0 and has second derivative ///dz^2/d^2x = pathCurvature. The terrain is discretized to the given ///resolution. (This is faster than just looping through terrain points and ///calling SolveCurvatureFromCP) void SolveAllCurvatureCPs(Real resolution,std::vector<Real>& pathCurvatureList,std::vector<Vector2>& cpList); ///Helper: returns the z for a given x value Real PathHeight(Real x) const; ///Helper: solves for a CP on the given segment bool SolveCPFromCurvature(Real pathCurvature,const Segment& segment,Real tolerance=1e-3); ///Given the initial conditions (x0,v0) and the current values of ///pathCurvature and capturePoint, performs a simulation trace. SimulationResult SimulationTrace(Real dt,int maxSteps,std::vector<Vector2>& xtrace,std::vector<Vector2>& vtrace) const; ///Given the initial conditions (x0,v0) and the current values of ///pathCurvature and capturePoint, calculate the result of simulation SimulationResult Simulate(Real dt,int maxSteps,Vector2& xfinal,Vector2& vfinal,int* numSteps=NULL) const; ///Returns true if the given cm satisfies the reachability requirement of ///the cp bool ReachableTerminalCM(const Vector2& cm,const Vector2& cp) const; ///initial position, initial velocity (x-z plane) Vector2 x0,v0; ///z-direction curvature of COM path Real pathCurvature; ///value of the capture point Vector2 capturePoint; ///upward-facing normal of capture point Vector2 capturePointNormal; ///terrain available for capture points PolygonalTerrain terrain; ///friction coefficient (default inf) Real frictionCoefficient; ///gravity strength (default 9.8) Real g; ///min/maximum G's that the robot can apply on the COM with its legs ///(default 0 and 3) Real minGs,maxGs; ///the integration time step (default 1e-2) Real timeStep; ///minimum and maximum limits of CM height above terrain (default 0 and inf) Real hmin,hmax; ///Leg lengths defining minimum and maximum limits of CM distance to ///capture point and stance point (default 0 and inf) Real Lmin,Lmax; ///if true, this can help limit the search bool hasStancePoint; ///value of the current stance point Vector2 stancePoint; ///Tolerances for CM terminal condition for considering a point ///to be a capture point. Specifically, the ///resulting position of CM must be within cpXTolerance of the CP in the ///x direction, and within cpVTolerance of zero velocity. Larger values ///might make the solver converge faster. (default 1e-3) Real cpXTolerance,cpVTolerance; }; } //namespace GCP #endif
[ "rautnalin@gmail.com" ]
rautnalin@gmail.com
9f7b7b1f0cf7e0939f00932f5e0405dfb4555a8d
597964e09d6d2b6fd58055fb81caa1db08d0832c
/seedwires.h
4ee5e18ea0bcab0b998db57cffe6be325ec554f6
[]
no_license
danilapal/Lr3_Pavlov_Alg
88486b680f9ebfcf5f3fad477f829e57e1f42ecd
de8fdf0b2110f8826440ed484732a37fac5bbedc
refs/heads/master
2021-01-20T00:30:29.419963
2017-04-29T17:49:17
2017-04-29T17:49:17
89,144,309
0
0
null
null
null
null
UTF-8
C++
false
false
2,353
h
#ifndef SEEDWIRES_H #define SEEDWIRES_H #include <iostream> #include <vector> #include <math.h> template <class T> T countS (const std::vector<std::vector<T>> &distance,const std::vector<std::vector<T>> &wires,std::vector<T> place) { // std::cout<<"countSS placeSize"<<place.size()<<std::endl; //for (unsigned i=0;i<place.size();i++) // std::cout<<"i="<<i<<" comp "<<place[i]<<std::endl;; T bS=0; for (unsigned int count1=0;count1<place.size();count1++) { for (unsigned int count2=1;count2+count1<place.size();count2++) { // std::cout<<"count1 "<<count1<<" count1+count2 "<<count1+count2<<std::endl; bS=bS+distance[count1] [count1+count2]*wires[place[count1]][place[count1+count2]]; } } return bS; } template <class T> void spaceComponentsT( T variant,T free,T choose,const std::vector<std::vector<T>> &distance,const std::vector<std::vector<T>> &wires,std::vector<T> options,std::vector<T> place,T &bestS) { //std::cout<<"CHOOSE"<<choose<<std::endl; std::swap(options[0+free-1],options[choose]); // std::cout<<"SWAP"<<std::endl; place.push_back(variant); T S=countS(distance,wires,place); //std::cout<<"S="<<S<<std::endl; if ((S>bestS) && (bestS!=0)) { std::cout<<"S="<<S<<" Best S="<<bestS<<std::endl; return ; } if (place.size()==options.size()) { bestS=S; std::cout<<"Best solution now="<<bestS<<std::endl; for (unsigned int p=0;p<place.size();p++) std::cout<<place[p]<<" "; std::cout<<std::endl; return; } for (unsigned int var=0;var+free<options.size();var++) { // std::cout<<"SS "<<var+free<<" DD "<<options[var+free]<<std::endl; spaceComponentsT(options[var+free],(free+1),(int)(var+free),distance,wires,options,place,bestS); } return ; } template <class T> void spaceComponents(const std::vector<std::vector<T>> &distance,const std::vector<std::vector<T>> &wires,std::vector<T> options,std::vector<T> place,T &bestS) { std::cout<<"START"<<std::endl; for (unsigned int var=0;var<options.size();var++) { //std::cout<<"!"<<var<<std::endl; spaceComponentsT(options[var],1,(int)var,distance,wires,options,place,bestS); } std::cout<<"MINIMUM S="<<bestS<<std::endl; return; } #endif // SEEDWIRES_H
[ "danilapal@mail.ru" ]
danilapal@mail.ru
0b45bfd61a96be74834caf2d8a7518c4cd195b30
073f047d6a2f6648167729dac46a4a970f09d59e
/mainwindow.h
9ca1d87a3f84015a56eac9eefc40345663bbbaa7
[]
no_license
alexliu2360/IndoormapEdit
a9bea563745fac07a7898b894de05afe93fea12c
5c487fce8bdd67f03630309c90786c18d9315795
refs/heads/master
2020-05-04T01:54:16.746993
2019-04-01T09:59:31
2019-04-01T09:59:31
178,916,685
1
0
null
null
null
null
UTF-8
C++
false
false
2,171
h
#ifndef MAINWINDOW_H #define MAINWINDOW_H #include <QMainWindow> #include <QListIterator> namespace Ui { class MainWindow; } class DocumentView; class PropertyView; class Feature; QT_FORWARD_DECLARE_CLASS(QTreeView) QT_FORWARD_DECLARE_CLASS(QPrinter) QT_FORWARD_DECLARE_CLASS(QCloseEvent) QT_FORWARD_DECLARE_CLASS(QListWidgetItem) class MainWindow : public QMainWindow { Q_OBJECT public: MainWindow(QWidget *parent = 0); ~MainWindow(); DocumentView *currentDocument() const; public slots: void newFile(); void openFile(); void openRecentFile(); bool saveFile(); bool saveAsFile(); void autoSave(); void closeFile(); void exportFile(); void printFile(); void printCurrent(); void deleteFeature(); void onAddLayerButtonClicked(); void onDeleteButtonClicked(); void rebuildTreeView(); void updatePropertyView(Feature* mapFeature); void setPolygonTool(); void setPolylineTool(); void setSelectTool(); void setPubPointTool(); void setMergeTool(); void setSplitTool(); void setScaleTool(); void setGraphicsViewFont(); void onFind(); void findAllRepeat(); void outputItemClicked(QListWidgetItem* item); void sortAreas(); protected: void closeEvent(QCloseEvent *event); void dragEnterEvent(QDragEnterEvent *event); void dropEvent(QDropEvent *event); private: bool okToContinue(); void addDocument(DocumentView* doc); void openDocument(const QString & fileName); bool saveDocument(const QString & fileName); void setCurrentFile(const QString & fileName); void readSettings(); void writeSettings(); void updateRecentFileActions(); Ui::MainWindow *ui; QTreeView *m_sceneTreeView; PropertyView *m_propertyView; const int m_maxRecentFiles; QStringList m_recentFiles; std::vector<QAction*> m_recentFileActions; QString m_curFile; QString m_lastFilePath; DocumentView* m_docView; QPrinter *m_printer; QTimer *m_timer; int m_autoSaveTime; QList<Feature *> m_searchResults; QListIterator<Feature *> m_searchResultIter; }; #endif // MAINWINDOW_H
[ "906_100009053356_alexliu2360@git.cloud.tencent.com" ]
906_100009053356_alexliu2360@git.cloud.tencent.com
89add5d13b9da71887be880cda3b253fb0a7087b
974d04d2ea27b1bba1c01015a98112d2afb78fe5
/paddle/fluid/distributed/ps/table/ctr_dymf_accessor.cc
4824ab8946b9d03c922318b95c81a21897f15f94
[ "Apache-2.0" ]
permissive
PaddlePaddle/Paddle
b3d2583119082c8e4b74331dacc4d39ed4d7cff0
22a11a60e0e3d10a3cf610077a3d9942a6f964cb
refs/heads/develop
2023-08-17T21:27:30.568889
2023-08-17T12:38:22
2023-08-17T12:38:22
65,711,522
20,414
5,891
Apache-2.0
2023-09-14T19:20:51
2016-08-15T06:59:08
C++
UTF-8
C++
false
false
12,736
cc
// Copyright (c) 2021 PaddlePaddle Authors. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include "paddle/fluid/distributed/ps/table/ctr_dymf_accessor.h" #include <gflags/gflags.h> #include "glog/logging.h" #include "paddle/fluid/string/string_helper.h" namespace paddle { namespace distributed { int CtrDymfAccessor::Initialize() { auto name = _config.embed_sgd_param().name(); _embed_sgd_rule = CREATE_PSCORE_CLASS(SparseValueSGDRule, name); _embed_sgd_rule->LoadConfig(_config.embed_sgd_param(), 1); name = _config.embedx_sgd_param().name(); _embedx_sgd_rule = CREATE_PSCORE_CLASS(SparseValueSGDRule, name); _embedx_sgd_rule->LoadConfig(_config.embedx_sgd_param(), _config.embedx_dim()); common_feature_value.optimizer_name = name; common_feature_value.embed_sgd_dim = _embed_sgd_rule->Dim(); common_feature_value.embedx_dim = _config.embedx_dim(); common_feature_value.embedx_sgd_dim = _embedx_sgd_rule->Dim(); _show_click_decay_rate = _config.ctr_accessor_param().show_click_decay_rate(); _ssd_unseenday_threshold = _config.ctr_accessor_param().ssd_unseenday_threshold(); if (_config.ctr_accessor_param().show_scale()) { _show_scale = true; } for (int i = 0; i < _config.ctr_accessor_param().load_filter_slots_size(); i++) { _filtered_slots.insert(_config.ctr_accessor_param().load_filter_slots(i)); VLOG(0) << "CtrDymfAccessor::Initialize() load filter slot:" << _config.ctr_accessor_param().load_filter_slots(i); } VLOG(0) << " INTO CtrDymfAccessor::Initialize(); embed_sgd_dim:" << common_feature_value.embed_sgd_dim << " embedx_dim:" << common_feature_value.embedx_dim << " embedx_sgd_dim:" << common_feature_value.embedx_sgd_dim; InitAccessorInfo(); return 0; } void CtrDymfAccessor::InitAccessorInfo() { _accessor_info.dim = common_feature_value.Dim(); _accessor_info.size = common_feature_value.Size(); auto embedx_dim = _config.embedx_dim(); VLOG(0) << "InitAccessorInfo embedx_dim:" << embedx_dim; _accessor_info.select_dim = 4 + embedx_dim; _accessor_info.select_size = _accessor_info.select_dim * sizeof(float); _accessor_info.update_dim = 5 + embedx_dim; _accessor_info.update_size = _accessor_info.update_dim * sizeof(float); _accessor_info.mf_size = (embedx_dim + common_feature_value.embedx_sgd_dim) * sizeof(float); } bool CtrDymfAccessor::Shrink(float* value) { auto delete_after_unseen_days = _config.ctr_accessor_param().delete_after_unseen_days(); auto delete_threshold = _config.ctr_accessor_param().delete_threshold(); // time_decay first common_feature_value.Show(value) *= _show_click_decay_rate; common_feature_value.Click(value) *= _show_click_decay_rate; // shrink after auto score = ShowClickScore(common_feature_value.Show(value), common_feature_value.Click(value)); auto unseen_days = common_feature_value.UnseenDays(value); if (score < delete_threshold || unseen_days > delete_after_unseen_days) { return true; } return false; } bool CtrDymfAccessor::SaveCache(float* value, int param, double global_cache_threshold) { auto base_threshold = _config.ctr_accessor_param().base_threshold(); auto delta_keep_days = _config.ctr_accessor_param().delta_keep_days(); if (ShowClickScore(common_feature_value.Show(value), common_feature_value.Click(value)) >= base_threshold && common_feature_value.UnseenDays(value) <= delta_keep_days) { return common_feature_value.Show(value) > global_cache_threshold; } return false; } bool CtrDymfAccessor::SaveSSD(float* value) { if (common_feature_value.UnseenDays(value) > _ssd_unseenday_threshold) { return true; } return false; } bool CtrDymfAccessor::FilterSlot(float* value) { // 热启时过滤掉_filtered_slots中的feasign if (_filtered_slots.find(common_feature_value.Slot(value)) != _filtered_slots.end()) { return true; } return false; } bool CtrDymfAccessor::Save(float* value, int param) { auto base_threshold = _config.ctr_accessor_param().base_threshold(); auto delta_threshold = _config.ctr_accessor_param().delta_threshold(); auto delta_keep_days = _config.ctr_accessor_param().delta_keep_days(); if (param == 2) { delta_threshold = 0; } switch (param) { // save all case 0: { return true; } // save xbox delta case 1: // save xbox base case 2: { if (ShowClickScore(common_feature_value.Show(value), common_feature_value.Click(value)) >= base_threshold && common_feature_value.DeltaScore(value) >= delta_threshold && common_feature_value.UnseenDays(value) <= delta_keep_days) { // do this after save, because it must not be modified when retry if (param == 2) { common_feature_value.DeltaScore(value) = 0; } return true; } else { return false; } } // already decayed in shrink case 3: { // do this after save, because it must not be modified when retry // common_feature_value.UnseenDays(value)++; return true; } // save revert batch_model case 5: { return true; } default: return true; } } void CtrDymfAccessor::UpdateStatAfterSave(float* value, int param) { auto base_threshold = _config.ctr_accessor_param().base_threshold(); auto delta_threshold = _config.ctr_accessor_param().delta_threshold(); auto delta_keep_days = _config.ctr_accessor_param().delta_keep_days(); if (param == 2) { delta_threshold = 0; } switch (param) { case 1: { if (ShowClickScore(common_feature_value.Show(value), common_feature_value.Click(value)) >= base_threshold && common_feature_value.DeltaScore(value) >= delta_threshold && common_feature_value.UnseenDays(value) <= delta_keep_days) { common_feature_value.DeltaScore(value) = 0; } } return; case 3: { common_feature_value.UnseenDays(value)++; } return; default: return; } } int32_t CtrDymfAccessor::Create(float** values, size_t num) { for (size_t value_item = 0; value_item < num; ++value_item) { float* value = values[value_item]; common_feature_value.UnseenDays(value) = 0; common_feature_value.PassId(value) = 0; value[common_feature_value.DeltaScoreIndex()] = 0; value[common_feature_value.ShowIndex()] = 0; value[common_feature_value.ClickIndex()] = 0; value[common_feature_value.SlotIndex()] = -1; value[common_feature_value.MfDimIndex()] = -1; _embed_sgd_rule->InitValue( value + common_feature_value.EmbedWIndex(), value + common_feature_value.EmbedG2SumIndex(), false); // adam embed init not zero, adagrad embed init zero _embedx_sgd_rule->InitValue(value + common_feature_value.EmbedxWIndex(), value + common_feature_value.EmbedxG2SumIndex(), false); } return 0; } bool CtrDymfAccessor::NeedExtendMF(float* value) { float show = value[common_feature_value.ShowIndex()]; float click = value[common_feature_value.ClickIndex()]; float score = (show - click) * _config.ctr_accessor_param().nonclk_coeff() + click * _config.ctr_accessor_param().click_coeff(); return score >= _config.embedx_threshold(); } bool CtrDymfAccessor::HasMF(int size) { return size > common_feature_value.EmbedxG2SumIndex(); } // from CommonFeatureValue to CtrDymfPullValue int32_t CtrDymfAccessor::Select(float** select_values, const float** values, size_t num) { auto embedx_dim = _config.embedx_dim(); for (size_t value_item = 0; value_item < num; ++value_item) { float* select_value = select_values[value_item]; const float* value = values[value_item]; select_value[CtrDymfPullValue::ShowIndex()] = value[common_feature_value.ShowIndex()]; select_value[CtrDymfPullValue::ClickIndex()] = value[common_feature_value.ClickIndex()]; select_value[CtrDymfPullValue::EmbedWIndex()] = value[common_feature_value.EmbedWIndex()]; memcpy(select_value + CtrDymfPullValue::EmbedxWIndex(), value + common_feature_value.EmbedxWIndex(), embedx_dim * sizeof(float)); } return 0; } // from CtrDymfPushValue to CtrDymfPushValue // first dim: item // second dim: field num int32_t CtrDymfAccessor::Merge(float** update_values, const float** other_update_values, size_t num) { // currently merge in cpu is not supported return 0; } // from CtrDymfPushValue to CommonFeatureValue // first dim: item // second dim: field num int32_t CtrDymfAccessor::Update(float** update_values, const float** push_values, size_t num) { // currently update in cpu is not supported return 0; } bool CtrDymfAccessor::CreateValue(int stage, const float* value) { // stage == 0, pull // stage == 1, push if (stage == 0) { return true; } else if (stage == 1) { // operation auto show = CtrDymfPushValue::Show(const_cast<float*>(value)); auto click = CtrDymfPushValue::Click(const_cast<float*>(value)); auto score = ShowClickScore(show, click); if (score <= 0) { return false; } if (score >= 1) { return true; } return local_uniform_real_distribution<float>()(local_random_engine()) < score; } else { return true; } } float CtrDymfAccessor::ShowClickScore(float show, float click) { auto nonclk_coeff = _config.ctr_accessor_param().nonclk_coeff(); auto click_coeff = _config.ctr_accessor_param().click_coeff(); return (show - click) * nonclk_coeff + click * click_coeff; } std::string CtrDymfAccessor::ParseToString(const float* v, int param) { /* float unseen_days; float delta_score; float show; float click; float embed_w; std::vector<float> embed_g2sum; // float embed_g2sum float slot; float mf_dim; std::<vector>float embedx_g2sum; // float embedx_g2sum std::vector<float> embedx_w; */ thread_local std::ostringstream os; os.clear(); os.str(""); os << common_feature_value.UnseenDays(const_cast<float*>(v)) << " " << v[1] << " " << v[2] << " " << v[3] << " " << v[4]; // << v[5] << " " << v[6]; for (int i = common_feature_value.EmbedG2SumIndex(); i < common_feature_value.EmbedxG2SumIndex(); i++) { os << " " << v[i]; } auto show = common_feature_value.Show(const_cast<float*>(v)); auto click = common_feature_value.Click(const_cast<float*>(v)); auto score = ShowClickScore(show, click); auto mf_dim = static_cast<int>(common_feature_value.MfDim(const_cast<float*>(v))); if (score >= _config.embedx_threshold() && param > common_feature_value.EmbedxG2SumIndex()) { for (auto i = common_feature_value.EmbedxG2SumIndex(); i < common_feature_value.Dim(mf_dim); ++i) { os << " " << v[i]; } } return os.str(); } int CtrDymfAccessor::ParseFromString(const std::string& str, float* value) { auto ret = paddle::string::str_to_float(str.data(), value); float unseen_day = value[common_feature_value.UnseenDaysIndex()]; common_feature_value.UnseenDays(value) = (uint16_t)(unseen_day); common_feature_value.PassId(value) = 0; CHECK(ret >= 7) << "expect more than 7 real:" << ret; return ret; } bool CtrDymfAccessor::SaveMemCache(float* value, int param, double global_cache_threshold, uint16_t pass_id) { return common_feature_value.Show(value) > global_cache_threshold || common_feature_value.PassId(value) >= pass_id; } void CtrDymfAccessor::UpdatePassId(float* value, uint16_t pass_id) { common_feature_value.PassId(value) = pass_id; } } // namespace distributed } // namespace paddle
[ "noreply@github.com" ]
PaddlePaddle.noreply@github.com
eb533d1b00318226d1a132c355d4017b9cdc26ad
f06394eb49f055ce3a51c93eb56249350d64ddbb
/tests/generation-tests/kdm/event/ConsumesEvent.hpp
98577bf518b411f5327c12b91c5cb817b7ba4b65
[]
no_license
happyj/e4c
a3c6eb523cf1d346a73b138c45a6cdfc83766710
59646a43d50749ddfc983e9a1f3a3c70fc5eb218
refs/heads/master
2020-03-26T05:15:09.814976
2014-02-22T11:20:12
2014-02-22T11:20:12
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,090
hpp
#ifndef EMF_CPP_KDM_EVENT_CONSUMESEVENT__HPP #define EMF_CPP_KDM_EVENT_CONSUMESEVENT__HPP #include <kdm/event/fwd.hpp> #include <kdm/event/meta.hpp> #include <kdm/event/AbstractEventRelationship.hpp> #include <e4c/mapping.hpp> namespace kdm { namespace event { class ConsumesEvent : public virtual ::kdm::event::AbstractEventRelationship { public: typedef ConsumesEvent_ptr ptr_type; ConsumesEvent(); virtual ~ConsumesEvent(); typedef kdm::event::Event_ptr to_t; typedef kdm::event::Transition_ptr from_t; to_t getTo() const; void setTo(to_t to_); from_t getFrom() const; void setFrom(from_t from_); /*PROTECTED REGION ID(kdm::event::ConsumesEvent public) START*/ /*PROTECTED REGION END*/ protected: friend class EventPackage; kdm::event::Event_ptr m_to; kdm::event::Transition_ptr m_from; virtual ecore::EClass_ptr eClassImpl() const; /*PROTECTED REGION ID(kdm::event::ConsumesEvent protected) START*/ /*PROTECTED REGION END*/ }; } // event } // kdm #endif // EMF_CPP_KDM_EVENT_CONSUMESEVENT__HPP
[ "andres@senac.es" ]
andres@senac.es
506154e53dd0b512585df088521088756867c588
c62710853eaaaaa554fe2ef348db1b615ec814fb
/c/lufuxing/chapter03/p108_1.cpp
b5b78d35a6bb782895808a84e5bde70892eddad1
[]
no_license
CodingWD/course
e38d75871e17627d1ce24beef6700ef65e606640
e80eeba61be9c0960002259a452babce44ee84a1
refs/heads/master
2023-04-06T21:47:54.940420
2021-04-15T10:25:30
2021-04-15T10:25:30
null
0
0
null
null
null
null
UTF-8
C++
false
false
830
cpp
#include<iostream> #include<ctime> #include<cstdlib> using namespace std; int main() { const int sz=5; int a[sz],b[sz],i; srand((unsigned) time (NULL) ); for(i=0;i<sz;i++) a[i]=rand()%10; cout<<"系统数据已经生成,请输入您猜测的5个数字(0-9),可以重复:"<<endl; int uVal; for(i=0;i<sz;i++) if(cin>>uVal) b[i]=uVal; cout<<"系统生成的数据是:"<<endl; for(auto val:a) cout<<val<<" "; cout<<endl; cout<<"您猜测的数据是:"<<endl; for(auto val : b) cout<<val<<" "; cout <<endl; int *p=begin(a),*q=begin(b); while(p !=end(a) &&q != end(b)) { if(*p != *q) { cout<<"您的猜测错误,两个数组不相等"<<endl; return -1; } p++; q++; } cout<<"恭喜您全部猜对了!"<<endl; return 0; }
[ "15803824671@163.com" ]
15803824671@163.com
624967001c2f4ed8db4ffe0114e92a8d1263c687
334558bf31b6a8fd3caaf09c24898ff331c7e2da
/GenieWindow/plugins/GeniePlugin_Wireless/QGenieConfirmMessageBox.cpp
7d9ee03d9964f64b0d9ab9217c8f8826a147ff07
[]
no_license
roygaogit/Bigit_Genie
e38bac558e81d9966ec6efbdeef0a7e2592156a7
936a56154a5f933b1e9c049ee044d76ff1d6d4db
refs/heads/master
2020-03-31T04:20:04.177461
2013-12-09T03:38:15
2013-12-09T03:38:15
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,570
cpp
#include "QGenieConfirmMessageBox.h" #include "GeniePlugin_Wireless.h" #include <QHBoxLayout> #include <QVBoxLayout> QGenieConfirmMessageBox::QGenieConfirmMessageBox(QWidget *parent) : GeniePopupDialog(parent) { m_ok_btn = new QPushButton(this); m_no_btn = new QPushButton(this); m_prompt_lb = new QLabel(this); QHBoxLayout *btn_layout = new QHBoxLayout(); btn_layout->setSpacing(16); btn_layout->addStretch(1); btn_layout->addWidget(m_ok_btn); btn_layout->addWidget(m_no_btn); btn_layout->addStretch(1); QVBoxLayout *rootlayout = new QVBoxLayout(this); rootlayout->setContentsMargins(0,5,0,0); rootlayout->setSpacing(10); rootlayout->addWidget(m_prompt_lb); rootlayout->addLayout(btn_layout); rootlayout->setStretch(0,1); connect(m_ok_btn,SIGNAL(clicked()),SLOT(accept())); connect(m_no_btn,SIGNAL(clicked()),this,SLOT(reject())); retranslateUi(); } void QGenieConfirmMessageBox::retranslateUi() { m_ok_btn->setText(GeniePlugin_Wireless::translateText(L_WIRELESS_IMB_YES_TEXT)); m_no_btn->setText(GeniePlugin_Wireless::translateText(L_WIRELESS_IMB_NO_TEXT)); m_prompt_lb->setText(GeniePlugin_Wireless::translateText(L_WIRELESS_CMB_CONTENT)/*"Be sure to delete this profile ?"*/); setWindowTitle(GeniePlugin_Wireless::translateText(L_WIRELESS_CMB_TITLE)/*"Delete profile"*/); } void QGenieConfirmMessageBox::changeEvent(QEvent *event) { if(event->type() == QEvent::LanguageChange) { retranslateUi(); } GeniePopupDialog::changeEvent(event); }
[ "raylq@qq.com" ]
raylq@qq.com
378c0d1baf11dec1f0806c83aed66519b03f1b21
a602297469e640a846c0e07b022fbd254bd06ec9
/C/src/server-copy.cc
dc21d91b4f0f6661fd81bc23a27f7b41aa08ef03
[]
no_license
bill-rui/Streaming
aa93b8439f1d86492f5edf987e180ae2d52286fc
0a94a2689854017f489a02132666e6746ad3aaed
refs/heads/master
2023-06-27T00:04:14.389869
2021-08-03T22:55:21
2021-08-03T22:55:21
387,906,228
0
0
null
null
null
null
UTF-8
C++
false
false
5,503
cc
#pragma clang diagnostic push #pragma ide diagnostic ignored "EndlessLoop" #include "server.h" #include "signal_handler.h" #include "udp_client.h" #include "udp_server.h" #include <iostream> #pragma clang diagnostic push class StreamReceiver{ private: UDPServer server; UDPClient sender; SignalHandler signal_handler; unsigned char rx_buffer; public: StreamReceiver(const int kBuffSize, const int kMaxRxSize, const int kServerPort, const std::string kAddr, const int kForwardingPort, const unsigned long kSendPktSize){ this->rx_buffer[kBuffSize + kSendPktSize]; this->server(kServerPort, kBuffSize); this->sender; } Forward(){ unsigned long leftover_data; unsigned long total_rx_data = 0; bool print_progress = false; // remove auto *send_ptr = reinterpret_cast<uint8_t *>(&rx_buffer); auto *rcv_ptr = send_ptr; server.MakeBlocking(1); signal_handler.SetupSignalHandlers(); std::cout << "Forwarding to address: " << kAddr << ":" << kForwardingPort << "\n"; std::cout << "Sending packet size: " << kSendPktSize << " bytes" << std::endl; while (!SignalHandler::GotExitSignal()) { ssize_t packet_size = server.Recv(rcv_ptr, kBuffSize); if (packet_size < 0) { throw std::runtime_error("Receive failed"); } else if (packet_size > kMaxRxSize){ throw std::runtime_error("Received packet larger than max receive size, check input"); } if (print_progress) // remove std::cout << "packet received: " << packet_size << std::endl; total_rx_data += packet_size; unsigned int packet_count = static_cast<int>(total_rx_data / kSendPktSize); leftover_data = total_rx_data % kSendPktSize; for (unsigned int i = 0; i < packet_count; i++) { // send packets try { ssize_t s = sender.Send(kAddr, kForwardingPort, send_ptr, kSendPktSize); if (print_progress) // remove std::cout << "packet sent: " << s << std::endl; } catch (std::runtime_error &e) { std::cout << "Sending error: " << e.what() << std::endl; } send_ptr += kSendPktSize; } // move data to front if possible overflow if (send_ptr + leftover_data + kMaxRxSize - reinterpret_cast<const uint8_t *>(&rx_buffer) > kBuffSize) { if (print_progress) // remove std::cout << "data moved to front" << std::endl; memcpy(&rx_buffer, send_ptr, leftover_data); //move buffer to front send_ptr = reinterpret_cast<uint8_t *>(&rx_buffer); } rcv_ptr = send_ptr + leftover_data; total_rx_data -= packet_count * kSendPktSize; } } }; void Forward(const int kBuffSize, const int kMaxRxSize, const int kServerPort, const std::string kAddr, const int kForwardingPort, const unsigned long kSendPktSize){ unsigned char rx_buffer[kBuffSize + kSendPktSize]; UDPServer server(kServerPort, kBuffSize); UDPClient sender; SignalHandler signal_handler; unsigned long leftover_data; unsigned long total_rx_data = 0; bool print_progress = false; // remove auto *send_ptr = reinterpret_cast<uint8_t *>(&rx_buffer); auto *rcv_ptr = send_ptr; server.MakeBlocking(1); signal_handler.SetupSignalHandlers(); std::cout << "Forwarding to address: " << kAddr << ":" << kForwardingPort << "\n"; std::cout << "Sending packet size: " << kSendPktSize << " bytes" << std::endl; while (!SignalHandler::GotExitSignal()) { ssize_t packet_size = server.Recv(rcv_ptr, kBuffSize); if (packet_size < 0) { throw std::runtime_error("Receive failed"); } else if (packet_size > kMaxRxSize){ throw std::runtime_error("Received packet larger than max receive size, check input"); } if (print_progress) // remove std::cout << "packet received: " << packet_size << std::endl; total_rx_data += packet_size; unsigned int packet_count = static_cast<int>(total_rx_data / kSendPktSize); leftover_data = total_rx_data % kSendPktSize; for (unsigned int i = 0; i < packet_count; i++) { // send packets try { ssize_t s = sender.Send(kAddr, kForwardingPort, send_ptr, kSendPktSize); if (print_progress) // remove std::cout << "packet sent: " << s << std::endl; } catch (std::runtime_error &e) { std::cout << "Sending error: " << e.what() << std::endl; } send_ptr += kSendPktSize; } // move data to front if possible overflow if (send_ptr + leftover_data + kMaxRxSize - reinterpret_cast<const uint8_t *>(&rx_buffer) > kBuffSize) { if (print_progress) // remove std::cout << "data moved to front" << std::endl; memcpy(&rx_buffer, send_ptr, leftover_data); //move buffer to front send_ptr = reinterpret_cast<uint8_t *>(&rx_buffer); } rcv_ptr = send_ptr + leftover_data; total_rx_data -= packet_count * kSendPktSize; } } void SendData(std::string addr, int port, const unsigned char* buffer, ssize_t len){ UDPClient sender; sender.Send(addr, port, buffer, len); } void ReceiveData(int port, uint8_t *buffer, ssize_t len){ UDPServer receiver(port, 4000); receiver.MakeBlocking(); receiver.Recv(buffer, len); } #pragma clang diagnostic pop
[ "74115078+bill-rui@users.noreply.github.com" ]
74115078+bill-rui@users.noreply.github.com
c5a57f80316ceef8e759e419df3f4202b0abdda5
9c310296d6b2a75d9af3a45579bc3c249a7ed7e9
/src/RpcExt/StubBufferMap.cpp
74b9c182b14cc56678ffb7272dd78af04ffb6049
[]
no_license
temp1352/rpcext
836abfe0c76564462bd9d50a7211e7aad8dba475
94db5a343d86af8808f876bfad45cdf9afd82a75
refs/heads/main
2023-07-18T07:12:54.845469
2021-09-12T10:10:09
2021-09-12T10:10:09
404,338,869
0
0
null
null
null
null
UTF-8
C++
false
false
8,295
cpp
#include "StdAfx.h" #include "StubBufferMap.h" #include "RpcExt.h" #include "HashMap.h" #include "InterfaceMap.h" RpcStubBuffer::RpcStubBuffer() { _logFile.Write(LogCategory::Misc, LogLevel::General, LogOption::Std, "RpcStubBuffer::RpcStubBuffer"); m_ref = 0; m_hash = 0; m_conected = false; m_pRawBuffer = nullptr; m_pUnkServer = nullptr; m_iid = IID_NULL; m_ipid = IID_NULL; m_pNext = nullptr; } RpcStubBuffer::~RpcStubBuffer() { _logFile.WriteV(LogCategory::Misc, LogLevel::General, LogOption::Std, "RpcStubBuffer::~RpcStubBuffer, this : 0x%08x, m_pRawBuffer = 0x%08x", this, m_pRawBuffer); ComApi::Release(&m_pUnkServer); if (m_pRawBuffer) { if (m_conected) { m_pRawBuffer->Disconnect(); } m_pRawBuffer->Release(); } } HRESULT RpcStubBuffer::CreateInstance(REFIID riid, IUnknown* pUnkServer, IRpcStubBuffer* pRawBuffer, IRpcStubBuffer** ppStubBuffer) { MarshaledInterfaceList::_Node* pNode = _rpcExt.m_miList.Lookup(riid, pUnkServer); if (!pNode) { *ppStubBuffer = pRawBuffer; pRawBuffer->AddRef(); return S_OK; } auto p = new RpcStubBuffer; if (!p) return E_OUTOFMEMORY; if (_logFile.m_outLevel >= LogLevel::Details) { CStringA strItf; _interfaceMap.GetInterfaceName(riid, strItf); _logFile.WriteV(LogCategory::Misc, LogLevel::Details, LogOption::Std, "RpcStubBuffer::CreateInstance, interface : %s", strItf); } pNode->pBuffer = ComApi::AddRef(p); p->Lock(); pRawBuffer->AddRef(); pUnkServer->AddRef(); p->m_pRawBuffer = pRawBuffer; p->m_pUnkServer = pUnkServer; p->m_iid = riid; p->m_conected = true; HRESULT hr = p->QueryInterface(IID_IRpcStubBuffer, (void**)ppStubBuffer); p->Unlock(); return hr; } STDMETHODIMP RpcStubBuffer::QueryInterface(REFIID riid, void** ppv) { if (!ppv) return E_POINTER; if (InlineIsEqualGUID(riid, __uuidof(RpcStubBuffer))) { *ppv = this; AddRef(); return S_OK; } else if (InlineIsEqualGUID(riid, IID_IRpcStubBuffer) || InlineIsEqualGUID(riid, IID_IUnknown)) { *ppv = static_cast<IRpcStubBuffer*>(this); AddRef(); return S_OK; } return E_NOINTERFACE; } STDMETHODIMP_(ULONG) RpcStubBuffer::AddRef() { ULONG ref = InterlockedIncrement(&m_ref); return ref; } STDMETHODIMP_(ULONG) RpcStubBuffer::Release() { ULONG ref = _Release(); if (ref == 1) { _rpcExt.m_stubBufMap.Remove(this); } return ref; } ULONG RpcStubBuffer::_Release() { ULONG ref = InterlockedDecrement(&m_ref); if (ref == 0) { delete this; } return ref; } STDMETHODIMP RpcStubBuffer::Connect(IUnknown* pUnkServer) { _logFile.WriteV(LogCategory::Misc, LogLevel::General, LogOption::Std, "RpcStubBuffer::Connect, this : %08x", this); if (!pUnkServer) return E_POINTER; Lock(); HRESULT hr = E_FAIL; if (pUnkServer == m_pUnkServer) { hr = m_pRawBuffer->Connect(pUnkServer); if (SUCCEEDED(hr)) { m_conected = true; } } else { _logFile.WriteV(LogCategory::Misc, LogLevel::General, LogOption::Std, "RpcStubBuffer::Connect, this : %08x, pUnkServer != m_pUnkServer", this); } Unlock(); return hr; } STDMETHODIMP_(void) RpcStubBuffer::Disconnect() { Lock(); _logFile.WriteV(LogCategory::Misc, LogLevel::General, LogOption::Std, "RpcStubBuffer::Disconnect, this : #%08x", this); m_pRawBuffer->Disconnect(); m_conected = false; Unlock(); } STDMETHODIMP RpcStubBuffer::Invoke(RPCOLEMESSAGE* prpcmsg, IRpcChannelBuffer* pRpcChannelBuffer) { _logFile.WriteV(LogCategory::Misc, LogLevel::General, LogOption::Std, "RpcStubBuffer::Invoke, this : #%08x", this); Lock(); HRESULT hr = E_FAIL; if (!m_conected) { hr = m_pRawBuffer->Connect(m_pUnkServer); if (FAILED(hr)) { Unlock(); _logFile.WriteV(LogCategory::Misc, LogLevel::Error, LogOption::Std, "RpcStubBuffer::Invoke, this : #%08x, conne", this); return hr; } m_conected = true; } hr = m_pRawBuffer->Invoke(prpcmsg, pRpcChannelBuffer); Unlock(); return hr; } STDMETHODIMP_(IRpcStubBuffer*) RpcStubBuffer::IsIIDSupported(REFIID riid) { _logFile.Write(LogCategory::Misc, LogLevel::General, LogOption::Std, "RpcStubBuffer::IsIIDSupported"); Lock(); IRpcStubBuffer* pBuffer = m_pRawBuffer->IsIIDSupported(riid); Unlock(); return pBuffer; } STDMETHODIMP_(ULONG) RpcStubBuffer::CountRefs() { _logFile.Write(LogCategory::Misc, LogLevel::General, LogOption::Std, "RpcStubBuffer::CountRefs"); Lock(); ULONG ref = m_pRawBuffer->CountRefs(); Unlock(); return ref; } STDMETHODIMP RpcStubBuffer::DebugServerQueryInterface(void** ppv) { _logFile.Write(LogCategory::Misc, LogLevel::General, LogOption::Std, "RpcStubBuffer::DebugServerQueryInterface"); Lock(); HRESULT hr = m_pRawBuffer->DebugServerQueryInterface(ppv); Unlock(); return hr; } STDMETHODIMP_(void) RpcStubBuffer::DebugServerRelease(void* pv) { _logFile.Write(LogCategory::Misc, LogLevel::General, LogOption::Std, "RpcStubBuffer::DebugServerRelease"); Lock(); m_pRawBuffer->DebugServerRelease(pv); Unlock(); } // RpcStubBufferMap RpcStubBufferMap::RpcStubBufferMap() { m_binCount = 0; m_ppBins = nullptr; } RpcStubBufferMap::~RpcStubBufferMap() { _Clear(); } HRESULT RpcStubBufferMap::Initialize() { return S_OK; } void RpcStubBufferMap::Uninitialize() { Clear(); } HRESULT RpcStubBufferMap::Insert(RpcStubBuffer* pStubBuffer) { if (!pStubBuffer) return E_POINTER; CComCritSecLock<CComAutoCriticalSection> lock(m_cs); HRESULT hr = Lookup(pStubBuffer->m_ipid, nullptr); if (hr == S_OK) return S_FALSE; if (!m_ppBins) { hr = InitBins(); if (hr != S_OK) return hr; } pStubBuffer->m_hash = RpcHashMap::Hash(pStubBuffer->m_ipid); int binIdx = pStubBuffer->m_hash % m_binCount; pStubBuffer->m_pNext = m_ppBins[binIdx]; m_ppBins[binIdx] = ComApi::AddRef(pStubBuffer); //_logFile.WriteV(LogCategory::Misc, LogLevel::General, LogOption::Std, "RpcStubBufferMap::Insert, hash : %d, binIdx : %d, ipid = ", pStubBuffer->m_hash, binIdx); //_logFile.WriteBinary(LogCategory::Misc, LogLevel::General, LogOption::Std, &pStubBuffer->m_ipid, sizeof(IPID)); return S_OK; } HRESULT RpcStubBufferMap::Lookup(const IPID& ipid, RpcStubBuffer** ppStubBuffer) { CComCritSecLock<CComAutoCriticalSection> lock(m_cs); if (!m_ppBins || !m_binCount) return S_FALSE; UINT hash = RpcHashMap::Hash(ipid); int binIdx = hash % m_binCount; //_logFile.WriteV(LogCategory::Misc, LogLevel::General, LogOption::Std, "RpcStubBufferMap::Lookup, hash : %d, binIdx : %d, ipid = ", hash, binIdx); //_logFile.WriteBinary(LogCategory::Misc, LogLevel::General, LogOption::Std, &ipid, sizeof(IPID)); RpcStubBuffer* pNode = m_ppBins[binIdx]; while (pNode) { if (pNode->m_hash == hash && InlineIsEqualGUID(pNode->m_ipid, ipid)) { if (ppStubBuffer) { *ppStubBuffer = ComApi::AddRef(pNode); } return S_OK; } pNode = pNode->m_pNext; } return S_FALSE; } BOOL RpcStubBufferMap::Remove(RpcStubBuffer* pStubBuffer) { CComCritSecLock<CComAutoCriticalSection> lock(m_cs); if (!m_ppBins || !m_binCount) return FALSE; int binIdx = pStubBuffer->m_hash % m_binCount; ; RpcStubBuffer* pNode = m_ppBins[binIdx]; RpcStubBuffer* pPrev = nullptr; while (pNode) { if (pNode == pStubBuffer) { break; } pPrev = pNode; pNode = pNode->m_pNext; } if (pNode == nullptr) return FALSE; if (pPrev) pPrev->m_pNext = pNode->m_pNext; else m_ppBins[binIdx] = pNode->m_pNext; pStubBuffer->m_hash = 0; pStubBuffer->m_pNext = nullptr; pStubBuffer->Release(); return TRUE; } HRESULT RpcStubBufferMap::InitBins() { if (!m_ppBins) { ULONG binCount = RpcHashMap::BinSize(100); m_ppBins = (RpcStubBuffer**)malloc(binCount * sizeof(RpcStubBuffer*)); if (!m_ppBins) { SetLastError(ERROR_OUTOFMEMORY); return E_OUTOFMEMORY; } memset(m_ppBins, 0, binCount * sizeof(RpcStubBuffer*)); m_binCount = binCount; } return S_OK; } void RpcStubBufferMap::Clear() { CComCritSecLock<CComAutoCriticalSection> lock(m_cs); _Clear(); } void RpcStubBufferMap::_Clear() { if (m_ppBins) { for (ULONG i = 0; i < m_binCount; ++i) { RpcStubBuffer *pNode = m_ppBins[i], *pTemp; while (pNode) { pTemp = pNode; pNode = pNode->m_pNext; pTemp->m_hash = 0; pTemp->m_pNext = nullptr; pTemp->_Release(); } } free(m_ppBins); m_ppBins = nullptr; m_binCount = 0; } }
[ "temp1352@live.com" ]
temp1352@live.com
d4e324267bce05f83b289a303f28a64e3696fa0c
fe8970bd7e24924bb6a696cae83cb3d781ee8881
/src/crypter.cpp
52708b34b2f4a80b84804f7bc37c2284dea2d730
[ "MIT" ]
permissive
worldpaycoin/WPAY
2fb48e59886e4acab842093e74cf5e5f10e2c9e1
51c2e7fc8c68bf108c44b46909efadfc27f4ce81
refs/heads/master
2021-06-09T02:33:49.090558
2021-04-26T10:26:11
2021-04-26T10:26:11
170,187,121
0
1
null
null
null
null
UTF-8
C++
false
false
15,061
cpp
// Copyright (c) 2009-2013 The Bitcoin developers // Copyright (c) 2017-2018 The ZillionFLUX developers // Copyright (c) 2018 The WPAY developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "crypter.h" #include "script/script.h" #include "script/standard.h" #include "util.h" #include "init.h" #include "uint256.h" #include <boost/foreach.hpp> #include <openssl/aes.h> #include <openssl/evp.h> #include "wallet.h" bool CCrypter::SetKeyFromPassphrase(const SecureString& strKeyData, const std::vector<unsigned char>& chSalt, const unsigned int nRounds, const unsigned int nDerivationMethod) { if (nRounds < 1 || chSalt.size() != WALLET_CRYPTO_SALT_SIZE) return false; int i = 0; if (nDerivationMethod == 0) i = EVP_BytesToKey(EVP_aes_256_cbc(), EVP_sha512(), &chSalt[0], (unsigned char*)&strKeyData[0], strKeyData.size(), nRounds, chKey, chIV); if (i != (int)WALLET_CRYPTO_KEY_SIZE) { OPENSSL_cleanse(chKey, sizeof(chKey)); OPENSSL_cleanse(chIV, sizeof(chIV)); return false; } fKeySet = true; return true; } bool CCrypter::SetKey(const CKeyingMaterial& chNewKey, const std::vector<unsigned char>& chNewIV) { if (chNewKey.size() != WALLET_CRYPTO_KEY_SIZE || chNewIV.size() != WALLET_CRYPTO_KEY_SIZE) return false; memcpy(&chKey[0], &chNewKey[0], sizeof chKey); memcpy(&chIV[0], &chNewIV[0], sizeof chIV); fKeySet = true; return true; } bool CCrypter::Encrypt(const CKeyingMaterial& vchPlaintext, std::vector<unsigned char>& vchCiphertext) { if (!fKeySet) return false; // max ciphertext len for a n bytes of plaintext is // n + AES_BLOCK_SIZE - 1 bytes int nLen = vchPlaintext.size(); int nCLen = nLen + AES_BLOCK_SIZE, nFLen = 0; vchCiphertext = std::vector<unsigned char>(nCLen); bool fOk = true; EVP_CIPHER_CTX* ctx = EVP_CIPHER_CTX_new(); if (fOk) fOk = EVP_EncryptInit_ex(ctx, EVP_aes_256_cbc(), NULL, chKey, chIV) != 0; if (fOk) fOk = EVP_EncryptUpdate(ctx, &vchCiphertext[0], &nCLen, &vchPlaintext[0], nLen) != 0; if (fOk) fOk = EVP_EncryptFinal_ex(ctx, (&vchCiphertext[0]) + nCLen, &nFLen) != 0; EVP_CIPHER_CTX_free(ctx); if (!fOk) return false; vchCiphertext.resize(nCLen + nFLen); return true; } bool CCrypter::Decrypt(const std::vector<unsigned char>& vchCiphertext, CKeyingMaterial& vchPlaintext) { if (!fKeySet) return false; // plaintext will always be equal to or lesser than length of ciphertext int nLen = vchCiphertext.size(); int nPLen = nLen, nFLen = 0; vchPlaintext = CKeyingMaterial(nPLen); bool fOk = true; EVP_CIPHER_CTX* ctx = EVP_CIPHER_CTX_new(); if (fOk) fOk = EVP_DecryptInit_ex(ctx, EVP_aes_256_cbc(), NULL, chKey, chIV) != 0; if (fOk) fOk = EVP_DecryptUpdate(ctx, &vchPlaintext[0], &nPLen, &vchCiphertext[0], nLen) != 0; if (fOk) fOk = EVP_DecryptFinal_ex(ctx, (&vchPlaintext[0]) + nPLen, &nFLen) != 0; EVP_CIPHER_CTX_free(ctx); if (!fOk) return false; vchPlaintext.resize(nPLen + nFLen); return true; } bool EncryptSecret(const CKeyingMaterial& vMasterKey, const CKeyingMaterial& vchPlaintext, const uint256& nIV, std::vector<unsigned char>& vchCiphertext) { CCrypter cKeyCrypter; std::vector<unsigned char> chIV(WALLET_CRYPTO_KEY_SIZE); memcpy(&chIV[0], &nIV, WALLET_CRYPTO_KEY_SIZE); if (!cKeyCrypter.SetKey(vMasterKey, chIV)) return false; return cKeyCrypter.Encrypt(*((const CKeyingMaterial*)&vchPlaintext), vchCiphertext); } // General secure AES 256 CBC encryption routine bool EncryptAES256(const SecureString& sKey, const SecureString& sPlaintext, const std::string& sIV, std::string& sCiphertext) { // max ciphertext len for a n bytes of plaintext is // n + AES_BLOCK_SIZE - 1 bytes int nLen = sPlaintext.size(); int nCLen = nLen + AES_BLOCK_SIZE; int nFLen = 0; // Verify key sizes if (sKey.size() != 32 || sIV.size() != AES_BLOCK_SIZE) { LogPrintf("crypter EncryptAES256 - Invalid key or block size: Key: %d sIV:%d\n", sKey.size(), sIV.size()); return false; } // Prepare output buffer sCiphertext.resize(nCLen); // Perform the encryption EVP_CIPHER_CTX* ctx; bool fOk = true; ctx = EVP_CIPHER_CTX_new(); if (fOk) fOk = EVP_EncryptInit_ex(ctx, EVP_aes_256_cbc(), NULL, (const unsigned char*)&sKey[0], (const unsigned char*)&sIV[0]); if (fOk) fOk = EVP_EncryptUpdate(ctx, (unsigned char*)&sCiphertext[0], &nCLen, (const unsigned char*)&sPlaintext[0], nLen); if (fOk) fOk = EVP_EncryptFinal_ex(ctx, (unsigned char*)(&sCiphertext[0]) + nCLen, &nFLen); EVP_CIPHER_CTX_free(ctx); if (!fOk) return false; sCiphertext.resize(nCLen + nFLen); return true; } bool DecryptSecret(const CKeyingMaterial& vMasterKey, const std::vector<unsigned char>& vchCiphertext, const uint256& nIV, CKeyingMaterial& vchPlaintext) { CCrypter cKeyCrypter; std::vector<unsigned char> chIV(WALLET_CRYPTO_KEY_SIZE); memcpy(&chIV[0], &nIV, WALLET_CRYPTO_KEY_SIZE); if (!cKeyCrypter.SetKey(vMasterKey, chIV)) return false; return cKeyCrypter.Decrypt(vchCiphertext, *((CKeyingMaterial*)&vchPlaintext)); } bool DecryptAES256(const SecureString& sKey, const std::string& sCiphertext, const std::string& sIV, SecureString& sPlaintext) { // plaintext will always be equal to or lesser than length of ciphertext int nLen = sCiphertext.size(); int nPLen = nLen, nFLen = 0; // Verify key sizes if (sKey.size() != 32 || sIV.size() != AES_BLOCK_SIZE) { LogPrintf("crypter DecryptAES256 - Invalid key or block size\n"); return false; } sPlaintext.resize(nPLen); EVP_CIPHER_CTX* ctx; bool fOk = true; ctx = EVP_CIPHER_CTX_new(); if (fOk) fOk = EVP_DecryptInit_ex(ctx, EVP_aes_256_cbc(), NULL, (const unsigned char*)&sKey[0], (const unsigned char*)&sIV[0]); if (fOk) fOk = EVP_DecryptUpdate(ctx, (unsigned char*)&sPlaintext[0], &nPLen, (const unsigned char*)&sCiphertext[0], nLen); if (fOk) fOk = EVP_DecryptFinal_ex(ctx, (unsigned char*)(&sPlaintext[0]) + nPLen, &nFLen); EVP_CIPHER_CTX_free(ctx); if (!fOk) return false; sPlaintext.resize(nPLen + nFLen); return true; } bool CCryptoKeyStore::SetCrypted() { LOCK(cs_KeyStore); if (fUseCrypto) return true; if (!mapKeys.empty()) return false; fUseCrypto = true; return true; } bool CCryptoKeyStore::Lock() { if (!SetCrypted()) return false; { LOCK(cs_KeyStore); vMasterKey.clear(); pwalletMain->zwalletMain->Lock(); } NotifyStatusChanged(this); return true; } bool CCryptoKeyStore::Unlock(const CKeyingMaterial& vMasterKeyIn) { { LOCK(cs_KeyStore); if (!SetCrypted()) return false; bool keyPass = false; bool keyFail = false; CryptedKeyMap::const_iterator mi = mapCryptedKeys.begin(); for (; mi != mapCryptedKeys.end(); ++mi) { const CPubKey& vchPubKey = (*mi).second.first; const std::vector<unsigned char>& vchCryptedSecret = (*mi).second.second; CKeyingMaterial vchSecret; if (!DecryptSecret(vMasterKeyIn, vchCryptedSecret, vchPubKey.GetHash(), vchSecret)) { keyFail = true; break; } if (vchSecret.size() != 32) { keyFail = true; break; } CKey key; key.Set(vchSecret.begin(), vchSecret.end(), vchPubKey.IsCompressed()); if (key.GetPubKey() != vchPubKey) { keyFail = true; break; } keyPass = true; if (fDecryptionThoroughlyChecked) break; } if (keyPass && keyFail) { LogPrintf("The wallet is probably corrupted: Some keys decrypt but not all."); assert(false); } if (keyFail || !keyPass) return false; vMasterKey = vMasterKeyIn; fDecryptionThoroughlyChecked = true; uint256 hashSeed; if (CWalletDB(pwalletMain->strWalletFile).ReadCurrentSeedHash(hashSeed)) { uint256 nSeed; if (!GetDeterministicSeed(hashSeed, nSeed)) { return error("Failed to read zWPAY seed from DB. Wallet is probably corrupt."); } pwalletMain->zwalletMain->SetMasterSeed(nSeed, false); } else { // First time this wallet has been unlocked with dzWPAY // Borrow random generator from the key class so that we don't have to worry about randomness CKey key; key.MakeNewKey(true); uint256 seed = key.GetPrivKey_256(); LogPrintf("%s: first run of zpiv wallet detected, new seed generated. Seedhash=%s\n", __func__, Hash(seed.begin(), seed.end()).GetHex()); pwalletMain->zwalletMain->SetMasterSeed(seed, true); pwalletMain->zwalletMain->GenerateMintPool(); } } NotifyStatusChanged(this); return true; } bool CCryptoKeyStore::AddKeyPubKey(const CKey& key, const CPubKey& pubkey) { { LOCK(cs_KeyStore); if (!IsCrypted()) return CBasicKeyStore::AddKeyPubKey(key, pubkey); if (IsLocked()) return false; std::vector<unsigned char> vchCryptedSecret; CKeyingMaterial vchSecret(key.begin(), key.end()); if (!EncryptSecret(vMasterKey, vchSecret, pubkey.GetHash(), vchCryptedSecret)) return false; if (!AddCryptedKey(pubkey, vchCryptedSecret)) return false; } return true; } bool CCryptoKeyStore::AddCryptedKey(const CPubKey& vchPubKey, const std::vector<unsigned char>& vchCryptedSecret) { { LOCK(cs_KeyStore); if (!SetCrypted()) return false; mapCryptedKeys[vchPubKey.GetID()] = make_pair(vchPubKey, vchCryptedSecret); } return true; } bool CCryptoKeyStore::GetKey(const CKeyID& address, CKey& keyOut) const { { LOCK(cs_KeyStore); if (!IsCrypted()) return CBasicKeyStore::GetKey(address, keyOut); CryptedKeyMap::const_iterator mi = mapCryptedKeys.find(address); if (mi != mapCryptedKeys.end()) { const CPubKey& vchPubKey = (*mi).second.first; const std::vector<unsigned char>& vchCryptedSecret = (*mi).second.second; CKeyingMaterial vchSecret; if (!DecryptSecret(vMasterKey, vchCryptedSecret, vchPubKey.GetHash(), vchSecret)) return false; if (vchSecret.size() != 32) return false; keyOut.Set(vchSecret.begin(), vchSecret.end(), vchPubKey.IsCompressed()); return true; } } return false; } bool CCryptoKeyStore::GetPubKey(const CKeyID& address, CPubKey& vchPubKeyOut) const { { LOCK(cs_KeyStore); if (!IsCrypted()) return CKeyStore::GetPubKey(address, vchPubKeyOut); CryptedKeyMap::const_iterator mi = mapCryptedKeys.find(address); if (mi != mapCryptedKeys.end()) { vchPubKeyOut = (*mi).second.first; return true; } } return false; } bool CCryptoKeyStore::EncryptKeys(CKeyingMaterial& vMasterKeyIn) { { LOCK(cs_KeyStore); if (!mapCryptedKeys.empty() || IsCrypted()) return false; fUseCrypto = true; BOOST_FOREACH (KeyMap::value_type& mKey, mapKeys) { const CKey& key = mKey.second; CPubKey vchPubKey = key.GetPubKey(); CKeyingMaterial vchSecret(key.begin(), key.end()); std::vector<unsigned char> vchCryptedSecret; if (!EncryptSecret(vMasterKeyIn, vchSecret, vchPubKey.GetHash(), vchCryptedSecret)) return false; if (!AddCryptedKey(vchPubKey, vchCryptedSecret)) return false; } mapKeys.clear(); } return true; } bool CCryptoKeyStore::AddDeterministicSeed(const uint256& seed) { CWalletDB db(pwalletMain->strWalletFile); string strErr; uint256 hashSeed = Hash(seed.begin(), seed.end()); if(IsCrypted()) { if (!IsLocked()) { //if we have password CKeyingMaterial kmSeed(seed.begin(), seed.end()); vector<unsigned char> vchSeedSecret; //attempt encrypt if (EncryptSecret(vMasterKey, kmSeed, hashSeed, vchSeedSecret)) { //write to wallet with hashSeed as unique key if (db.WriteZWPAYSeed(hashSeed, vchSeedSecret)) { return true; } } strErr = "encrypt seed"; } strErr = "save since wallet is locked"; } else { //wallet not encrypted if (db.WriteZWPAYSeed(hashSeed, ToByteVector(seed))) { return true; } strErr = "save zpivseed to wallet"; } //the use case for this is no password set seed, mint dzWPAY, return error("s%: Failed to %s\n", __func__, strErr); } bool CCryptoKeyStore::GetDeterministicSeed(const uint256& hashSeed, uint256& seedOut) { CWalletDB db(pwalletMain->strWalletFile); string strErr; if (IsCrypted()) { if(!IsLocked()) { //if we have password vector<unsigned char> vchCryptedSeed; //read encrypted seed if (db.ReadZWPAYSeed(hashSeed, vchCryptedSeed)) { uint256 seedRetrieved = uint256(ReverseEndianString(HexStr(vchCryptedSeed))); //this checks if the hash of the seed we just read matches the hash given, meaning it is not encrypted //the use case for this is when not crypted, seed is set, then password set, the seed not yet crypted in memory if(hashSeed == Hash(seedRetrieved.begin(), seedRetrieved.end())) { seedOut = seedRetrieved; return true; } CKeyingMaterial kmSeed; //attempt decrypt if (DecryptSecret(vMasterKey, vchCryptedSeed, hashSeed, kmSeed)) { seedOut = uint256(ReverseEndianString(HexStr(kmSeed))); return true; } strErr = "decrypt seed"; } else { strErr = "read seed from wallet"; } } else { strErr = "read seed; wallet is locked"; } } else { vector<unsigned char> vchSeed; // wallet not crypted if (db.ReadZWPAYSeed(hashSeed, vchSeed)) { seedOut = uint256(ReverseEndianString(HexStr(vchSeed))); return true; } strErr = "read seed from wallet"; } return error("%s: Failed to %s\n", __func__, strErr); // return error("Failed to decrypt deterministic seed %s", IsLocked() ? "Wallet is locked!" : ""); }
[ "alonewolf2ksk@gmail.com" ]
alonewolf2ksk@gmail.com
01702fb79167018c38b1a35259d1e54dbfe45edd
1d928c3f90d4a0a9a3919a804597aa0a4aab19a3
/c++/Halide/2016/4/DeviceInterface.cpp
42cd86e8874b65ad2765a145373467ec0239469e
[]
no_license
rosoareslv/SED99
d8b2ff5811e7f0ffc59be066a5a0349a92cbb845
a062c118f12b93172e31e8ca115ce3f871b64461
refs/heads/main
2023-02-22T21:59:02.703005
2021-01-28T19:40:51
2021-01-28T19:40:51
306,497,459
1
1
null
2020-11-24T20:56:18
2020-10-23T01:18:07
null
UTF-8
C++
false
false
6,825
cpp
#include "JITModule.h" #include "Target.h" #include "runtime/HalideRuntime.h" #include "runtime/HalideRuntimeCuda.h" #include "runtime/HalideRuntimeOpenCL.h" #include "runtime/HalideRuntimeOpenGL.h" #include "runtime/HalideRuntimeOpenGLCompute.h" using namespace Halide; using namespace Halide::Internal; namespace { template <typename fn_type> bool lookup_runtime_routine(const char *name, const Target &target, fn_type &result) { std::vector<JITModule> runtime( JITSharedRuntime::get(nullptr, target.with_feature(Target::JIT))); for (size_t i = 0; i < runtime.size(); i++) { std::map<std::string, JITModule::Symbol>::const_iterator f = runtime[i].exports().find(name); if (f != runtime[i].exports().end()) { result = reinterpret_bits<fn_type>(f->second.address); return true; } } return false; } } extern "C" { /** Release all data associated with the current GPU backend, in particular * all resources (memory, texture, context handles) allocated by Halide. Must * be called explicitly when using AOT compilation. */ void halide_device_release(void *user_context, const halide_device_interface *device_interface) { user_assert(user_context == nullptr) << "Cannot provide user_context to libHalide.a halide_device_release\n"; Target target(get_host_target()); void (*fn)(void *user_context, const halide_device_interface *device_interface); if (lookup_runtime_routine("halide_device_release", target, fn)) { (*fn)(user_context, device_interface); } } /** Copy image data from device memory to host memory. This must be called * explicitly to copy back the results of a GPU-based filter. */ int halide_copy_to_host(void *user_context, struct buffer_t *buf) { user_assert(user_context == nullptr) << "Cannot provide user_context to libHalide.a halide_copy_to_host\n"; // Skip if there is no device buffer. if (buf->dev == 0) return 0; Target target(get_host_target()); int (*fn)(void *user_context, struct buffer_t *buf); if (lookup_runtime_routine("halide_copy_to_host", target, fn)) { return (*fn)(user_context, buf); } return -1; } /** Copy image data from host memory to device memory. This should not * be called directly; Halide handles copying to the device * automatically. If interface is nullptr and the bug has a non-zero dev * field, the device associated with the dev handle will be * used. Otherwise if the dev field is 0 and interface is nullptr, an * error is returned. */ int halide_copy_to_device(void *user_context, struct buffer_t *buf, const halide_device_interface *device_interface) { user_assert(user_context == nullptr) << "Cannot provide user_context to libHalide.a halide_copy_to_device\n"; Target target(get_host_target()); int (*fn)(void *user_context, struct buffer_t *buf, const halide_device_interface *device_interface); if (lookup_runtime_routine("halide_copy_to_device", target, fn)) { return (*fn)(user_context, buf, device_interface); } return -1; } /** Wait for current GPU operations to complete. Calling this explicitly * should rarely be necessary, except maybe for profiling. */ int halide_device_sync(void *user_context, struct buffer_t *buf) { user_assert(user_context == nullptr) << "Cannot provide user_context to libHalide.a halide_device_sync\n"; Target target(get_host_target()); int (*fn)(void *user_context, struct buffer_t *buf); if (lookup_runtime_routine("halide_device_sync", target, fn)) { return (*fn)(user_context, buf); } return -1; } /** Allocate device memory to back a buffer_t. */ int halide_device_malloc(void *user_context, struct buffer_t *buf, const halide_device_interface *device_interface) { user_assert(user_context == nullptr) << "Cannot provide user_context to libHalide.a halide_device_malloc\n"; Target target(get_host_target()); int (*fn)(void *user_context, struct buffer_t *buf, const halide_device_interface *device_interface); if (lookup_runtime_routine("halide_device_malloc", target, fn)) { return (*fn)(user_context, buf, device_interface); } return -1; } int halide_device_free(void *user_context, struct buffer_t *buf) { user_assert(user_context == nullptr) << "Cannot provide user_context to libHalide.a halide_device_free\n"; // Skip if there is no device buffer. if (buf->dev == 0) return 0; Target target(get_host_target()); int (*fn)(void *user_context, struct buffer_t *buf); if (lookup_runtime_routine("halide_device_free", target, fn)) { return (*fn)(user_context, buf); } if (buf->dev != 0) { return -1; } else { return 0; } } const struct halide_device_interface *halide_cuda_device_interface() { Target target(get_host_target()); target.set_feature(Target::CUDA); struct halide_device_interface *(*fn)(); if (lookup_runtime_routine("halide_cuda_device_interface", target, fn)) { return (*fn)(); } return nullptr; } const struct halide_device_interface *halide_opencl_device_interface() { Target target(get_host_target()); target.set_feature(Target::OpenCL); struct halide_device_interface *(*fn)(); if (lookup_runtime_routine("halide_opencl_device_interface", target, fn)) { return (*fn)(); } return nullptr; } const struct halide_device_interface *halide_opengl_device_interface() { Target target(get_host_target()); target.set_feature(Target::OpenGL); struct halide_device_interface *(*fn)(); if (lookup_runtime_routine("halide_opengl_device_interface", target, fn)) { return (*fn)(); } return nullptr; } const struct halide_device_interface *halide_openglcompute_device_interface() { Target target(get_host_target()); target.set_feature(Target::OpenGLCompute); struct halide_device_interface *(*fn)(); if (lookup_runtime_routine("halide_openglcompute_device_interface", target, fn)) { return (*fn)(); } return nullptr; } const struct halide_device_interface *halide_renderscript_device_interface() { Target target(get_host_target()); target.set_feature(Target::Renderscript); struct halide_device_interface *(*fn)(); if (lookup_runtime_routine("halide_renderscript_device_interface", target, fn)) { return (*fn)(); } return nullptr; } const struct halide_device_interface *halide_metal_device_interface() { Target target(get_host_target()); target.set_feature(Target::Metal); struct halide_device_interface *(*fn)(); if (lookup_runtime_routine("halide_metal_device_interface", target, fn)) { return (*fn)(); } return nullptr; } }
[ "rodrigosoaresilva@gmail.com" ]
rodrigosoaresilva@gmail.com
3d096d16f5d2c93cb592d4f9b49052403fe2f399
c4891b64e7145dbf3ea14201919b4969dce54fb5
/practices/cpp/level1/p11_Fighters/test.cpp
ccba73e0caa3f2cc72e01e907a4a088bb1e6211d
[]
no_license
qiaopengju/CCpp2017
aedd1d457737f071cf385b22ea5b238da8c22976
2c81176cea6ec022f3dc0c53c0486bb0dac058c7
refs/heads/master
2021-06-18T16:15:10.500073
2017-06-23T12:23:44
2017-06-23T12:23:44
null
0
0
null
null
null
null
UTF-8
C++
false
false
924
cpp
#include <SFML/Graphics.hpp> #include <iostream> using namespace std; sf :: RenderWindow window(sf :: VideoMode(500, 500), "a"); void play(); int main(){ while (window.isOpen()){ sf :: Event event; while (window.pollEvent(event)){ if (event.type == sf :: Event :: Closed) window.close(); } play(); } return 0; } void play(){ std :: string diePath = "Character/Enemy/sms/die/"; sf :: Texture t; sf :: Sprite sp; for (int i = 1; i <= 120; i++){ window.clear(); int hun = i / 100 + '0', ten = i % 100 / 10 + '0', dig = i % 10 + '0'; char q[4] = {hun, ten, dig}; std :: string Image = q; Image += ".png"; std :: cout << diePath + Image << std :: endl; t.loadFromFile(diePath + Image); sp.setTexture(t); window.draw(sp); window.display(); sf :: Clock clock; for (sf :: Time time = clock.getElapsedTime(); time.asSeconds() <= 0.03f; ) time = clock.getElapsedTime(); } }
[ "holmesqiao@gmail.com" ]
holmesqiao@gmail.com
fe85b5e8c2e51a0ce03603a13841ebfb50d63cae
6889dcc1bd55c309d240142ccba5c979efe37399
/tests/self-sufficiency/function_hpp.cpp
2db7d910fb6388ab66b43d6e1ff3ca6f9d9d1501
[ "MIT" ]
permissive
agnat/ncd
c6e8b3afa8de3228676d114be80b104f87b1e296
23c928d101dda3146f7a1701deab9ab00c9937b9
refs/heads/master
2021-05-07T09:32:11.528371
2017-11-22T00:38:47
2017-11-22T00:38:47
109,622,900
1
0
null
null
null
null
UTF-8
C++
false
false
133
cpp
// Copyright 2017 David Siegel. Distributed under the MIT license. See LICENSE. #include <ncd/function.hpp> int main() { return 0; }
[ "agnat@me.com" ]
agnat@me.com
1d29bd58a79ed2291943600e9cf2735c9eefb97c
e363b63383c617acc55c5b43bd0fa524d9e64dff
/game/client/swarm/vgui/objectivepanel.h
ec5223522b0c9fd7233d6cb9fc19192723b07172
[]
no_license
paralin/hl2sdk-dota
63a17b641e2cc9d6d030df9244c03d60e013737d
e0fe36f0132b36ba9b1ca56aa10f888f66e9b2bf
refs/heads/master
2016-09-09T22:37:57.509357
2014-04-09T13:26:01
2014-04-09T13:26:01
18,719,255
4
2
null
null
null
null
UTF-8
C++
false
false
697
h
#ifndef OBJECTIVEPANEL_H #define OBJECTIVEPANEL_H #ifdef _WIN32 #pragma once #endif #include <vgui/VGUI.h> #include <vgui_controls/Panel.h> class C_ASW_Player; class Label; class ImagePanel; // this panel is used during the briefing to show a particular objective name and image in the list on the left class ObjectivePanel : public vgui::Panel { DECLARE_CLASS_SIMPLE( ObjectivePanel, vgui::Panel ); public: ObjectivePanel(Panel *parent, const char *name); virtual ~ObjectivePanel(); virtual void PerformLayout(); vgui::Label* m_ObjectiveLabel; vgui::ImagePanel* m_ObjectiveImagePanel; bool m_bImageSet, m_bTextSet; }; #endif // OBJECTIVEPANEL_H
[ "ds@alliedmods.net" ]
ds@alliedmods.net
8f816fdd0f48ba8982a1abce7f7575f781f03c9b
47f24d8a8ddb142f7b24860052e2195aa1f3c6e8
/Omni V1/mcp_can_2.h
4e31d90b82bbda392cc148a3e8c27aa10ef49d3d
[]
no_license
mathbrook/learningCpp
f41a0652ed1a93d3549dee84466a7acfcdde43f2
894e93411748773fbf767db12cd0aa2e012c21e3
refs/heads/master
2022-03-06T12:38:02.803760
2022-02-22T16:08:05
2022-02-22T16:08:05
230,959,023
0
0
null
null
null
null
UTF-8
C++
false
false
4,194
h
#ifndef _MCP2515_H_ #define _MCP2515_H_ #include "mcp_can_2_dfs.h" #define MAX_CHAR_IN_MESSAGE 8 class MCP_CAN { private: INT8U m_nExtFlg; /* identifier xxxID */ /* either extended (the 29 LSB) */ /* or standard (the 11 LSB) */ INT32U m_nID; /* can id */ INT8U m_nDlc; /* data length: */ INT8U m_nDta[MAX_CHAR_IN_MESSAGE]; /* data */ INT8U m_nRtr; /* rtr */ INT8U m_nfilhit; INT8U SPICS; /* * mcp2515 driver function */ // private: private: void mcp2515_reset(void); /* reset mcp2515 */ void mcp2515_initCANBuffers(void); void mcp2515_modifyRegister(const INT8U address, /* set bit of one register */ const INT8U mask, const INT8U data); INT8U mcp2515_readStatus(void); /* read mcp2515's Status */ INT8U mcp2515_configRate(const INT8U canSpeed); /* set boadrate */ INT8U mcp2515_init(const INT8U canSpeed); /* mcp2515init */ void mcp2515_write_id(const INT8U mcp_addr, /* write can id */ const INT8U ext, const INT32U id); void mcp2515_read_id(const INT8U mcp_addr, /* read can id */ INT8U *ext, INT32U *id); void mcp2515_write_canMsg(const INT8U buffer_sidh_addr); /* write can msg */ void mcp2515_read_canMsg(const INT8U buffer_sidh_addr); /* read can msg */ void mcp2515_start_transmit(const INT8U mcp_addr); /* start transmit */ INT8U mcp2515_getNextFreeTXBuf(INT8U *txbuf_n); /* get Next free txbuf */ /* * can operator function */ INT8U setMsg(INT32U id, INT8U ext, INT8U len, INT8U *pData); /* set message */ INT8U clearMsg(); /* clear all message to zero */ INT8U readMsg(); /* read message */ INT8U sendMsg(); /* send message */ public: MCP_CAN(INT8U _CS); INT8U mcp2515_setCANCTRL_Mode(const INT8U newmode); /* set mode */ INT8U begin(INT8U speedset); /* init can */ INT8U init_Mask(INT8U num, INT8U ext, INT32U ulData); /* init Masks */ INT8U init_Filt(INT8U num, INT8U ext, INT32U ulData); /* init filters */ INT8U sendMsgBuf(INT32U id, INT8U ext, INT8U len, INT8U *buf); /* send buf */ INT8U readMsgBuf(INT8U *len, INT8U *buf); /* read buf */ INT8U checkReceive(void); /* if something received */ INT8U checkError(void); /* if something error */ INT32U getCanId(void); /* get can id when receive */ INT8U mcp2515_readRegister(const INT8U address); /* read mcp2515's register */ void mcp2515_readRegisterS(const INT8U address, INT8U values[], const INT8U n); void mcp2515_setRegister(const INT8U address, /* set mcp2515's register */ const INT8U value); void mcp2515_setRegisterS(const INT8U address, /* set mcp2515's registers */ const INT8U values[], const INT8U n); }; #endif /********************************************************************************************************* END FILE *********************************************************************************************************/
[ "mathos.brook@gmail.com" ]
mathos.brook@gmail.com
bc6a4c84238040d0d74bc709d04ae215183a996d
baebe8a00a7b3aa662b8078bd000c424bb214cc6
/src/geometry/triangle.cpp
4275f4820c39c7ee4d4efb66cf6200356618e65c
[ "MIT" ]
permissive
jonike/lumen
8ffd85f64018eba0d5adea401c44f740b6ea0032
c35259f45a265d470afccb8b6282c8520eabdc95
refs/heads/master
2021-04-25T04:03:36.864204
2017-06-02T17:49:11
2017-07-15T00:10:37
115,495,859
2
0
null
2017-12-27T07:45:31
2017-12-27T07:45:31
null
UTF-8
C++
false
false
3,006
cpp
#include <algorithm> #include <cassert> #include <sampler.h> #include <triangle.h> #include "nex\util.h" namespace lumen { triangle::triangle(const nex::matrix& world, const bsdf_ptr& bsdf, const vertex& v0, const vertex& v1, const vertex& v2) : geometry(world, bsdf), normal(nex::cross(v1.position - v0.position, v2.position - v0.position)), area(2.0f / nex::magnitude(normal)) { vertices[0] = v0; vertices[1] = v1; vertices[2] = v2; nex::normalize(normal); float minx = std::min(std::min(v0.position.x, v1.position.x), v2.position.x); float miny = std::min(std::min(v0.position.y, v1.position.y), v2.position.y); float minz = std::min(std::min(v0.position.z, v1.position.z), v2.position.z); float maxx = std::max(std::max(v0.position.x, v1.position.x), v2.position.x); float maxy = std::max(std::max(v0.position.y, v1.position.y), v2.position.y); float maxz = std::max(std::max(v0.position.z, v1.position.z), v2.position.z); set_bound(nex::point(minx, miny, minz), nex::point(maxx, maxy, maxz)); } float triangle::pdf() const { return area; } bool triangle::intersect(const nex::ray& ray, float* t, nex::vector* norm, nex::point* texcoord) const { // compute the determinant and check for division by zero nex::vector b = vertices[1].position - vertices[0].position; nex::vector c = vertices[2].position - vertices[0].position; nex::vector d_cross_c = nex::cross(ray.direction, c); float det = nex::dot(b, d_cross_c); if (std::abs(det) < nex::EPSILON) { return false; } float one_over_det = 1.0f / det; // compute the u barycentric coordinate nex::vector a = ray.origin - vertices[0].position; float u = one_over_det * nex::dot(a, d_cross_c); if ((u < 0.0f) || (u > 1.0f)) { return false; } // compute the v barycentric coordinate nex::vector a_cross_b = nex::cross(a, b); float v = one_over_det * nex::dot(ray.direction, a_cross_b); if ((v < 0.0f) || ((u + v) > 1.0f)) { return false; } // compute the ray intersection parameter *t = one_over_det * nex::dot(c, a_cross_b); *norm = vertices[0].normal * (1.0f - u - v) + vertices[1].normal * u + vertices[2].normal * v; *texcoord = vertices[0].texcoord * (1.0f - u - v) + vertices[1].texcoord * u + vertices[2].texcoord * v; return true; } void triangle::get_surface_sample(const sample& sample, nex::point* pos, nex::vector* norm) const { *pos = (1.0f - sample.x - sample.y) * vertices[0].position + sample.x * vertices[1].position + sample.y * vertices[2].position; *norm = (1.0f - sample.x - sample.y) * vertices[0].normal + sample.x * vertices[1].normal + sample.y * vertices[2].normal; } }
[ "jeremy.adam.lukacs@gmail.com" ]
jeremy.adam.lukacs@gmail.com
f182660832b5f8766bf5840de681c9adf8d051d5
6313406bb6dd2fdca60c31cbc77a32af11b19a78
/uvaOnlineJudge/uva10755.cpp
416e4e2e96bef465210742aa3fe40baa8fc931d0
[]
no_license
jackschu/icpcPrep
4b37a5fef24d5a2c3d4302c11ba4740c81da0272
755567da6d03c81587891bb0c02980dd932d8dfb
refs/heads/master
2021-12-23T20:03:25.832857
2021-12-16T06:30:24
2021-12-16T06:30:24
127,687,709
0
0
null
null
null
null
UTF-8
C++
false
false
2,087
cpp
#include <algorithm> #include <bitset> #include <cctype> #include <climits> #include <cmath> #include <cstring> #include <functional> #include <iostream> #include <iterator> #include <list> #include <map> #include <queue> #include <set> #include <sstream> #include <stack> #include <stdint.h> #include <unordered_map> #include <unordered_set> #include <vector> #define DEBUG if (false) using namespace std; typedef pair<int, int> ii; typedef vector<ii> vii; typedef vector<int> vi; int main() { int tc; cin >> tc; for (int ic = 0; ic < tc; ic++) { if (ic != 0) cout << endl; vector<vector<vector<long>>> slices; int a, b, c; cin >> a >> b >> c; for (int k = 0; k < a; k++) { vector<vector<long>> data; data.reserve(b); for (int i = 0; i < b; i++) { data.push_back({}); data[i].reserve(c); for (int j = 0; j < c; j++) { long x; cin >> x; if (i > 0) x += data[i - 1][j]; if (j > 0) x += data[i][j - 1]; if (i > 0 && j > 0) x -= data[i - 1][j - 1]; data[i].push_back(x); } } for (auto row : data) { for (auto elem : row) { DEBUG cout << elem << " "; } DEBUG cout << endl; } slices.push_back(data); } long best = slices[0][0][0]; for (int i1 = 0; i1 < b; i1++) { for (int j1 = 0; j1 < c; j1++) { for (int i2 = i1; i2 < b; i2++) { for (int j2 = j1; j2 < c; j2++) { long sum = 0; for (int k = 0; k < a; k++) { auto &slice = slices[k]; long x = slice[i2][j2]; if (i1 > 0) x -= slice[i1 - 1][j2]; if (j1 > 0) x -= slice[i2][j1 - 1]; if (j1 > 0 && i1 > 0) x += slice[i1 - 1][j1 - 1]; sum += x; best = max(best, sum); if (sum < 0) sum = 0; } } } } } cout << best << endl; } }
[ "js9pa@virginia.edu" ]
js9pa@virginia.edu
870c3d7a01a50eb354b4b8b54c52314f91708db5
1faeffc0315846f3fc056a0dcb482d6ae89e6d38
/PayPalRESTStore/PayPalRESTStore.Windows/MainPage.xaml.cpp
2f9c9dbad341f7d9b7504446bf9a2923aa861b27
[]
no_license
MavenRain/PayPalRESTStore
f2c2d676199e3e6138efd601c0128a508cc7077e
1bcb5418dc6805cd4e8205b9ab05614ef567e7ee
refs/heads/master
2016-09-15T20:18:06.449840
2015-01-06T06:53:11
2015-01-06T06:53:11
28,850,760
0
0
null
null
null
null
UTF-8
C++
false
false
2,700
cpp
// // MainPage.xaml.cpp // Implementation of the MainPage class. // #include "pch.h" #include "MainPage.xaml.h" // The Blank Page item template is documented at http://go.microsoft.com/fwlink/?LinkId=234238 MainPage::MainPage() { InitializeComponent(); } void PayPalRESTStore::MainPage::Button_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e) { String^ bufferString = CryptographicBuffer::EncodeToBase64String(CryptographicBuffer::ConvertStringToBinary(ref new String(L"AXVXPhBYtwEl_oJV1U8BohrSTFUG7A8IPOpYLaP3A_30cZ7L_w94r3G2gvsa:EJQ_ZhBDtIGpd1yGmtDsKyihcfcQ_9dzpHXjaTSVX39Li7zP91kiBkd8BiJk"), BinaryStringEncoding::Utf8)); Uri^ uri = ref new Uri(ref new String(L"https://api.sandbox.paypal.com/v1/oauth2/token")); HttpRequestMessage^ request = ref new HttpRequestMessage(HttpMethod::Post, uri); request->Headers->Append("Accept", "application/json"); request->Headers->Authorization = ref new HttpCredentialsHeaderValue("Basic", bufferString); Map<String^, String^>^ iMap = ref new Map<String^, String^>(); iMap->Insert(ref new String(L"grant_type"), ref new String(L"client_credentials")); iMap->Insert(ref new String(L"content-type"), ref new String(L"application/x-www-form-urlencoded")); request->Content = ref new HttpFormUrlEncodedContent(iMap); HttpClient^ httpClient = ref new HttpClient(); create_task(httpClient->SendRequestAsync(request)).then([this](HttpResponseMessage^ response) { JsonObject^ jsonObject = JsonObject::Parse(response->Content->ReadAsStringAsync()->GetResults()); String^ accessToken = jsonObject->GetNamedString("access_token", ""); Uri^ uri = ref new Uri(ref new String(L"https://api.sandbox.paypal.com/v1/identity/openidconnect/userinfo/?schema=openid")); HttpRequestMessage^ request = ref new HttpRequestMessage(HttpMethod::Post, uri); request->Headers->Authorization = ref new HttpCredentialsHeaderValue("Bearer", accessToken); /* Map<String^, String^>^ iMap = ref new Map<String^, String^>(); iMap->Insert(ref new String(L"content-type"), ref new String(L"application/json")); String^ jsonContent = ref new String(L"{\"intent\":\"sale\"},\"payer\":{\"payment_method\":\"paypal\"},\"transactions\":[{\"amount\":{\"total\":\"1\",\"currency\":\"USD\"}}]}"); request->Content = ref new HttpStringContent(jsonContent); */ HttpClient^ httpClient = ref new HttpClient(); create_task(httpClient->SendRequestAsync(request)).then([this](HttpResponseMessage^ response) { _response->Text = JsonObject::Parse(response->Content->ReadAsStringAsync()->GetResults())->GetNamedString("user_id", ""); }); }, task_continuation_context::use_current()); }
[ "v-oniobi@v-oniobi-1217.redmond.corp.microsoft.com" ]
v-oniobi@v-oniobi-1217.redmond.corp.microsoft.com
2fb7b241a28797bab086b78b840f3cdbf87fe74e
1e07d601e6fd3a9f38636d4f209b9f9a1a00d5bd
/TESTs/denso/LED_tikatika/LED_tikatika.ino
9950e550a93ef1fb32fbfee883fc737801b765ba
[]
no_license
tockn/myArduinoProjects
b8d73a824c44b4e4578eaf640831d529284ce10c
a2a0ee54e8135624b207a35912a2bf56a3c0766b
refs/heads/master
2020-03-20T05:10:31.446567
2018-06-19T12:53:34
2018-06-19T12:53:34
137,205,774
1
0
null
null
null
null
UTF-8
C++
false
false
242
ino
/* * LEDの足が長い方ーArduinoの13番ピン * LEDの足が短い方ーArduinoのGND */ void setup() { pinMode(13, OUTPUT); } void loop() { digitalWrite(13, HIGH); delay(1000); digitalWrite(13, LOW); delay(1000); }
[ "takuto.sato.5g@stu.hosei.ac.jp" ]
takuto.sato.5g@stu.hosei.ac.jp
acf16db2e9bb91c81e0bc5775442da2a78a6ae5a
75b7c38dbc490fb5f5c929687ebdd59b481a73e5
/src/imageprocess/ImageDeskew.h
434df3c57e49462104e466b2a97936d4c36697ae
[]
no_license
wxjwz/ocrstyle
bcd457ae60a3696e518d3edefc69c6e540e3681c
537a7385d1acf26dbffff7c0d4e952d7c685b7af
refs/heads/master
2020-03-17T09:09:15.925954
2019-11-19T05:33:12
2019-11-19T05:33:12
133,463,270
0
0
null
null
null
null
UTF-8
C++
false
false
3,334
h
// Copyright 2013, Zaoqibu Inc. // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Zaoqibu Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Author: vwarship@163.com (Junjian Wang) // // The Optical Character Recognition (OCR Style) #ifndef IMAGEDESKEW_H #define IMAGEDESKEW_H #include <cmath> #include <vector> namespace cv { class Mat; } class ImageDeskew { //Representation of a line in the image. struct HoughLine { HoughLine() : count(0), index(0), alpha(0.0), d(0.0) { } // count of points in the line int count; // index in matrix. int index; // the line is represented as all x, y that solve y * cos(alpha) - x * // sin(alpha) = d double alpha; double d; }; public: ImageDeskew(cv::Mat *image); // calculate the skew angle of the image m_image double getSkewAngle(); private: // Hough Transformation void calc(); void init(); double getAlpha(int index) { return m_alphaStart + (index * m_alphaStep); } // calculate the count lines in the image with most points void getTopHoughLines(std::vector<HoughLine> &houghLines); // calculate all lines through the point (x,y) void calc(int x, int y); bool isBlack(int x, int y); bool isBlack(int x, int y, int luminanceCutOff); private: static const double PI; // the range of angles to search for lines static const double m_alphaStart; static const double m_alphaStep; static const int m_steps; // pre-calculation of sin and cos std::vector<double> m_sinA; std::vector<double> m_cosA; // range of d double m_dMin; static const double m_dStep; int m_dCount; // count of points that fit in a line std::vector<int> m_hMatrix; // the source image cv::Mat *m_image; }; #endif // IMAGEDESKEW_H
[ "vwarship@163.com" ]
vwarship@163.com
b6b50b630a02eb988b513a84dc36562e98496bbc
6a7007918e745bc623129cf1d0ab7e5ce046730f
/astro/PCDM.h
b7c3abd580a6ac18a967bc87b6337fcbab8efe60
[]
no_license
LarsFlaeten/astro
c0ded9ac68556ef9075dd450f0e48df6c5fbf742
a2a9f5e482b19509dd21c8861d4a23965ab655b7
refs/heads/master
2021-04-28T01:09:04.821478
2019-08-06T18:00:57
2019-08-06T18:00:57
122,268,301
0
1
null
null
null
null
UTF-8
C++
false
false
769
h
#ifndef _ASTRO_PCDM_H_ #define _ASTRO_PCDM_H_ #include <vector> #include "Time.h" #include "State.h" #include "ODE.h" namespace astro { // Implementation of the Predictor-Corrector Direct Multiplication algorithm // by Zhao/van Wachem for numerical integration of rotation ODEs with quternions // http://calliope.dem.uniud.it/COST/downloads/paper1_BVW.pdf class PCDM { public: struct Result { RotState rs; EphemerisTime et; }; static Result doStep(const RotODE& rode, const RotState& s, const EphemerisTime& et, const TimeDelta& dt); static std::vector<Result> doSteps(const RotODE& rode, const RotState& s, const EphemerisTime& et0, const EphemerisTime& et1, const TimeDelta& dt); }; } #endif
[ "lars.flaeten@gmail.com" ]
lars.flaeten@gmail.com
af8bb1ebc526f5e64dcf4cb4c796cbc5147674b0
09907daaa32f79743ada4901d5de178932ab117d
/SERVER/ALM/NodeManagerIF.hpp
34c399e79224e8dd5d3ee4cccc76f06337fb9c0f
[]
no_license
Ntels-sup/SRC_ATOM_BE
64c6923d78e1db66cdd87dbf0c6f89d8f35db71e
cd9dc2d92314c20f4840b395761ea610bf28188e
refs/heads/master
2021-01-19T06:27:42.768707
2016-06-14T00:23:05
2016-06-14T00:23:05
59,884,040
0
0
null
null
null
null
UTF-8
C++
false
false
1,039
hpp
#ifndef __NODE_MANAGER_IF_HPP__ #define __NODE_MANAGER_IF_HPP__ #include <cstring> #include <string> #include <vector> #include "CMesgExchSocket.hpp" #include "AlarmDataDef.hpp" class NodeManagerIF { public: NodeManagerIF(); ~NodeManagerIF(); bool Init(); bool Connect(const char * _ip, int _port); void Close(); bool Register(); bool GetData(); int GetCommand(); void TakeOutBody(std::string & _body); int GetRequestNodeNo(); bool Response(std::string & _body); bool Notify(int _command_id, int _dest_node, int _dest_proc, std::string & _body); bool NotifyForConnect(); private: void saveHeaderForResponse(); bool sendRegister(); bool recvRegister(); private: bool bConnected_; CMesgExchSocket sock_; std::vector<char> vec_body_; ST_ProtocolHeader header_; }; #endif // __NODE_MANAGER_IF_HPP__
[ "kslee@ntels.com" ]
kslee@ntels.com
8d768860505f6d0ca1e58297969743a7b39715e2
20a3d5dd3e6af0a7d87ea79edbf0f817ec8b7166
/src/plugins/Analysis/dirc_hists/DEventProcessor_dirc_hists.cc
03071bbafb28c60b918bc227fc29c58d2ab047ab
[]
no_license
kading-che/halld_recon
06b3350933b439cf27ca27639233868d054e514e
29851f3ae1995e1ada58aba9eabce178e9ecf32a
refs/heads/master
2021-10-18T21:03:48.222149
2019-01-16T00:56:23
2019-01-16T00:56:23
null
0
0
null
null
null
null
UTF-8
C++
false
false
10,803
cc
// ----------------------------------------- // DEventProcessor_dirc_hists.cc // ----------------------------------------- #include "DEventProcessor_dirc_hists.h" // Routine used to create our DEventProcessor extern "C" { void InitPlugin(JApplication *app) { InitJANAPlugin(app); app->AddProcessor(new DEventProcessor_dirc_hists()); } } DEventProcessor_dirc_hists::DEventProcessor_dirc_hists() { } DEventProcessor_dirc_hists::~DEventProcessor_dirc_hists() { } jerror_t DEventProcessor_dirc_hists::init(void) { DIRC_TRUTH_BARHIT = false; if(gPARMS->Exists("DIRC:TRUTH_BARHIT")) gPARMS->GetParameter("DIRC:TRUTH_BARHIT",DIRC_TRUTH_BARHIT); TDirectory *dir = new TDirectoryFile("DIRC","DIRC"); dir->cd(); // list of particle IDs for histograms (and alternate hypotheses for likelihood diff) deque<TString> locLikelihoodName; dFinalStatePIDs.push_back(Positron); locLikelihoodName.push_back("ln L(e+) - ln L(#pi+)"); dFinalStatePIDs.push_back(Electron); locLikelihoodName.push_back("ln L(e-) - ln L(#pi-)"); dFinalStatePIDs.push_back(PiPlus); locLikelihoodName.push_back("ln L(#pi+) - ln L(K+)"); dFinalStatePIDs.push_back(PiMinus); locLikelihoodName.push_back("ln L(#pi-) - ln L(K-)"); dFinalStatePIDs.push_back(KPlus); locLikelihoodName.push_back("ln L(#pi+) - ln L(K+)"); dFinalStatePIDs.push_back(KMinus); locLikelihoodName.push_back("ln L(#pi-) - ln L(K-)"); dFinalStatePIDs.push_back(Proton); locLikelihoodName.push_back("ln L(K+) - ln L(p)"); dFinalStatePIDs.push_back(AntiProton); locLikelihoodName.push_back("ln L(K-) - ln L(#bar{p}"); dMaxChannels = 108*64; // plots for each bar TDirectory *locBarDir = new TDirectoryFile("PerBarDiagnostic","PerBarDiagnostic"); locBarDir->cd(); for(int i=0; i<48; i++) { hDiffBar[i] = new TH2I(Form("hDiff_bar%02d",i), Form("Bar %02d; Channel ID; t_{calc}-t_{measured} [ns]; entries [#]", i), dMaxChannels, 0, dMaxChannels, 400,-20,20); hNphCBar[i] = new TH1I(Form("hNphC_bar%02d",i), Form("Bar %02d; # photons", i), 150, 0, 150); } dir->cd(); // plots for each hypothesis for(uint loc_i=0; loc_i<dFinalStatePIDs.size(); loc_i++) { Particle_t locPID = dFinalStatePIDs[loc_i]; string locParticleName = ParticleType(locPID); string locParticleROOTName = ParticleName_ROOT(locPID); TDirectory *locParticleDir = new TDirectoryFile(locParticleName.data(),locParticleName.data()); locParticleDir->cd(); hDiff[locPID] = new TH1I(Form("hDiff_%s",locParticleName.data()), Form("; %s t_{calc}-t_{measured} [ns]; entries [#]", locParticleName.data()), 400,-20,20); hNphC[locPID] = new TH1I(Form("hNphC_%s",locParticleName.data()), Form("# photons; %s # photons", locParticleROOTName.data()), 150, 0, 150); hThetaC[locPID] = new TH1I(Form("hThetaC_%s",locParticleName.data()), Form("cherenkov angle; %s #theta_{C} [rad]", locParticleROOTName.data()), 250, 0.6, 1.0); hDeltaThetaC[locPID] = new TH1I(Form("hDeltaThetaC_%s",locParticleName.data()), Form("cherenkov angle; %s #Delta#theta_{C} [rad]", locParticleROOTName.data()), 200,-0.2,0.2); hLikelihood[locPID] = new TH1I(Form("hLikelihood_%s",locParticleName.data()), Form("; %s -lnL; entries [#]", locParticleROOTName.data()),1000,0.,1000.); hLikelihoodDiff[locPID] = new TH1I(Form("hLikelihoodDiff_%s",locParticleName.data()), Form("; %s;entries [#]", locLikelihoodName[loc_i].Data()),100,-200.,200.); hThetaCVsP[locPID] = new TH2I(Form("hThetaCVsP_%s",locParticleName.data()), Form("cherenkov angle vs. momentum; p (GeV/c); %s #theta_{C} [rad]", locParticleROOTName.data()), 120, 0.0, 12.0, 250, 0.75, 0.85); hDeltaThetaCVsP[locPID] = new TH2I(Form("hDeltaThetaCVsP_%s",locParticleName.data()), Form("cherenkov angle vs. momentum; p (GeV/c); %s #Delta#theta_{C} [rad]", locParticleROOTName.data()), 120, 0.0, 12.0, 200,-0.2,0.2); hLikelihoodDiffVsP[locPID] = new TH2I(Form("hLikelihoodDiffVsP_%s",locParticleName.data()), Form("; p (GeV/c); %s", locLikelihoodName[loc_i].Data()), 120, 0.0, 12.0, 100, -200, 200); hDeltaTVsP[locPID] = new TH2I(Form("hDeltaTVsP_%s",locParticleName.data()), Form("#Delta T vs. momentum; p (GeV/c); %s #Delta T (ns)", locParticleROOTName.data()), 120, 0.0, 12.0, 100, -1.5, 1.5); dir->cd(); } gDirectory->cd("/"); return NOERROR; } jerror_t DEventProcessor_dirc_hists::brun(jana::JEventLoop *loop, int32_t runnumber) { // get PID algos const DParticleID* locParticleID = NULL; loop->GetSingle(locParticleID); dParticleID = locParticleID; vector<const DDIRCGeometry*> locDIRCGeometry; loop->Get(locDIRCGeometry); dDIRCGeometry = locDIRCGeometry[0]; // Initialize DIRC LUT loop->GetSingle(dDIRCLut); return NOERROR; } jerror_t DEventProcessor_dirc_hists::evnt(JEventLoop *loop, uint64_t eventnumber) { // retrieve tracks and detector matches vector<const DTrackTimeBased*> locTimeBasedTracks; loop->Get(locTimeBasedTracks); vector<const DDIRCPmtHit*> locDIRCPmtHits; loop->Get(locDIRCPmtHits); const DDetectorMatches* locDetectorMatches = NULL; loop->GetSingle(locDetectorMatches); DDetectorMatches locDetectorMatch = (DDetectorMatches)locDetectorMatches[0]; // plot DIRC LUT variables for specific tracks for (unsigned int loc_i = 0; loc_i < locTimeBasedTracks.size(); loc_i++){ const DTrackTimeBased* locTrackTimeBased = locTimeBasedTracks[loc_i]; // require well reconstructed tracks for initial studies int locDCHits = locTrackTimeBased->Ndof + 5; double locTheta = locTrackTimeBased->momentum().Theta()*180/TMath::Pi(); double locP = locTrackTimeBased->momentum().Mag(); if(locDCHits < 15 || locTheta < 1.0 || locTheta > 12.0 || locP > 12.0) continue; // require has good match to TOF hit for cleaner sample shared_ptr<const DTOFHitMatchParams> locTOFHitMatchParams; bool foundTOF = dParticleID->Get_BestTOFMatchParams(locTrackTimeBased, locDetectorMatches, locTOFHitMatchParams); if(!foundTOF || locTOFHitMatchParams->dDeltaXToHit > 10.0 || locTOFHitMatchParams->dDeltaYToHit > 10.0) continue; Particle_t locPID = locTrackTimeBased->PID(); double locMass = ParticleMass(locPID); // get DIRC match parameters (contains LUT information) shared_ptr<const DDIRCMatchParams> locDIRCMatchParams; bool foundDIRC = dParticleID->Get_DIRCMatchParams(locTrackTimeBased, locDetectorMatches, locDIRCMatchParams); if(foundDIRC) { TVector3 posInBar = locDIRCMatchParams->dExtrapolatedPos; TVector3 momInBar = locDIRCMatchParams->dExtrapolatedMom; double locExpectedThetaC = locDIRCMatchParams->dExpectedThetaC; double locExtrapolatedTime = locDIRCMatchParams->dExtrapolatedTime; int locBar = dDIRCGeometry->GetBar(posInBar.Y()); double locAngle = dDIRCLut->CalcAngle(momInBar, locMass); map<Particle_t, double> locExpectedAngle = dDIRCLut->CalcExpectedAngles(momInBar); // get map of DIRCMatches to PMT hits map<shared_ptr<const DDIRCMatchParams>, vector<const DDIRCPmtHit*> > locDIRCTrackMatchParamsMap; locDetectorMatch.Get_DIRCTrackMatchParamsMap(locDIRCTrackMatchParamsMap); map<Particle_t, double> logLikelihoodSum; // loop over associated hits for LUT diagnostic plots for(uint loc_i=0; loc_i<locDIRCPmtHits.size(); loc_i++) { vector<pair<double, double>> locDIRCPhotons = dDIRCLut->CalcPhoton(locDIRCPmtHits[loc_i], locExtrapolatedTime, posInBar, momInBar, locExpectedAngle, locAngle, locPID, logLikelihoodSum); double locHitTime = locDIRCPmtHits[loc_i]->t - locExtrapolatedTime; int locChannel = locDIRCPmtHits[loc_i]->ch%dMaxChannels; if(locDIRCPhotons.size() > 0) { // loop over candidate photons for(uint loc_j = 0; loc_j<locDIRCPhotons.size(); loc_j++) { double locDeltaT = locDIRCPhotons[loc_j].first - locHitTime; double locThetaC = locDIRCPhotons[loc_j].second; japp->RootFillLock(this); //ACQUIRE ROOT FILL LOCK if(fabs(locThetaC-locExpectedThetaC)<0.02) { hDiff[locPID]->Fill(locDeltaT); hDiffBar[locBar]->Fill(locChannel,locDeltaT); } // fill histograms for candidate photons in timing cut if(fabs(locDeltaT) < 2.0) { hThetaC[locPID]->Fill(locThetaC); hDeltaThetaC[locPID]->Fill(locThetaC-locExpectedThetaC); hDeltaThetaCVsP[locPID]->Fill(momInBar.Mag(), locThetaC-locExpectedThetaC); } japp->RootFillUnLock(this); //RELEASE ROOT FILL LOCK } } } // remove final states not considered if(std::find(dFinalStatePIDs.begin(),dFinalStatePIDs.end(),locPID) == dFinalStatePIDs.end()) continue; japp->RootFillLock(this); //ACQUIRE ROOT FILL LOCK // fill histograms with per-track quantities hNphC[locPID]->Fill(locDIRCMatchParams->dNPhotons); hNphCBar[locBar]->Fill(locDIRCMatchParams->dNPhotons); hThetaCVsP[locPID]->Fill(momInBar.Mag(), locDIRCMatchParams->dThetaC); hDeltaTVsP[locPID]->Fill(momInBar.Mag(), locDIRCMatchParams->dDeltaT); // for likelihood and difference for given track mass hypothesis if(locPID == Positron || locPID == Electron) { hLikelihood[locPID]->Fill(-1. * locDIRCMatchParams->dLikelihoodElectron); hLikelihoodDiff[locPID]->Fill(locDIRCMatchParams->dLikelihoodElectron - locDIRCMatchParams->dLikelihoodPion); hLikelihoodDiffVsP[locPID]->Fill(locP, locDIRCMatchParams->dLikelihoodElectron - locDIRCMatchParams->dLikelihoodPion); } else if(locPID == PiPlus || locPID == PiMinus) { hLikelihood[locPID]->Fill(-1. * locDIRCMatchParams->dLikelihoodPion); hLikelihoodDiff[locPID]->Fill(locDIRCMatchParams->dLikelihoodPion - locDIRCMatchParams->dLikelihoodKaon); hLikelihoodDiffVsP[locPID]->Fill(locP, locDIRCMatchParams->dLikelihoodPion - locDIRCMatchParams->dLikelihoodKaon); } else if(locPID == KPlus || locPID == KMinus) { hLikelihood[locPID]->Fill(-1. * locDIRCMatchParams->dLikelihoodKaon); hLikelihoodDiff[locPID]->Fill(locDIRCMatchParams->dLikelihoodPion - locDIRCMatchParams->dLikelihoodKaon); hLikelihoodDiffVsP[locPID]->Fill(locP, locDIRCMatchParams->dLikelihoodPion - locDIRCMatchParams->dLikelihoodKaon); } else if(locPID == Proton) { hLikelihood[locPID]->Fill(-1. * locDIRCMatchParams->dLikelihoodProton); hLikelihoodDiff[locPID]->Fill(locDIRCMatchParams->dLikelihoodProton - locDIRCMatchParams->dLikelihoodKaon); hLikelihoodDiffVsP[locPID]->Fill(locP, locDIRCMatchParams->dLikelihoodProton - locDIRCMatchParams->dLikelihoodKaon); } japp->RootFillUnLock(this); //RELEASE ROOT FILL LOCK } } return NOERROR; } jerror_t DEventProcessor_dirc_hists::erun(void) { return NOERROR; } jerror_t DEventProcessor_dirc_hists::fini(void) { return NOERROR; }
[ "jrsteven@jlab.org" ]
jrsteven@jlab.org
887f373ce659c96c9b6324d43635728e2bc38e22
ec761bcc8a3c2fbc4554f6d36d81d13223e78974
/include/nesl2c/AST/ExpBinds.h
ee09a4e0eb815d4cc889ea0066e1c41e3459450d
[]
no_license
tclin914/NESL2C
63c254881a03fad67a0c007c2a0ccb70e68e842c
1df2829c858d7a6f4e050af542b168fe7af9eb60
refs/heads/master
2021-01-01T05:52:53.906396
2017-08-22T02:26:10
2017-08-22T02:26:10
95,673,455
1
0
null
2017-07-06T02:00:10
2017-06-28T13:44:23
C
UTF-8
C++
false
false
538
h
//===- ExpBinds.h -------------------------------------------------===// // // Tsung-Chun Lin <tclin914@gmail.com> // // Copyright (C) 2017, Programming Language and System Lab // //===--------------------------------------------------------------===// #ifndef NESL2C_AST_EXP_BINDS_H #define NESL2C_AST_EXP_BINDS_H #include "nesl2c/AST/BinaryNode.h" namespace nesl2c { class ExpBinds : public BinaryNode { public: ExpBinds(Node*, Node*); void Accept(Visitor*); }; } // namespace of nesl2c #endif // NESL2C_AST_EXP_BINDS_H
[ "tclin914@gmail.com" ]
tclin914@gmail.com
9caec0308baadbe7236bec8b5cb9f6cd13e4ab3c
ffd817cb151f47704738ea3ae0d22d317a4da692
/src/potential_perfect_ellipsoid.cpp
b5a0bad0f0517ed9106b07c272becbbba865683c
[]
no_license
alekseygenerozov/Agama
427d99f56a2625ff752e3e968b8f1c28ff390472
42499dd5e222455c193409da23ca3a29956906e1
refs/heads/master
2020-06-28T16:07:48.264491
2016-12-03T03:49:37
2016-12-03T03:49:37
74,489,235
0
0
null
2016-11-22T16:00:56
2016-11-22T16:00:56
null
UTF-8
C++
false
false
3,040
cpp
#include "potential_perfect_ellipsoid.h" #include <cmath> #include <cassert> #include <stdexcept> namespace potential{ OblatePerfectEllipsoid::OblatePerfectEllipsoid (double _mass, double major_axis, double minor_axis) : mass(_mass), coordSys(pow_2(major_axis)-pow_2(minor_axis)), minorAxis(minor_axis) { if(minor_axis<=0 || minor_axis>=major_axis) throw std::invalid_argument("Error in OblatePerfectEllipsoid: " "minor axis must be positive and strictly smaller than major axis"); } void OblatePerfectEllipsoid::evalScalar(const coord::PosProlSph& pos, double* val, coord::GradProlSph* deriv, coord::HessProlSph* deriv2) const { assert(&(pos.coordsys)==&coordSys); // make sure we're not bullshited double absnu = fabs(pos.nu); double signu = pos.nu>=0 ? 1 : -1; double lmn = pos.lambda-absnu; if(absnu>coordSys.delta || pos.lambda<coordSys.delta) throw std::invalid_argument("Error in OblatePerfectEllipsoid: " "incorrect values of spheroidal coordinates"); double Glambda, dGdlambda, d2Gdlambda2, Gnu, dGdnu, d2Gdnu2; // values and derivatives of G(lambda) and G(|nu|) evalDeriv(pos.lambda, &Glambda, &dGdlambda, &d2Gdlambda2); evalDeriv(absnu, &Gnu, &dGdnu, &d2Gdnu2); double coef=(Glambda-Gnu)/pow_2(lmn); // common subexpression if(val!=NULL) *val = (absnu*Gnu - pos.lambda*Glambda) / lmn; if(deriv!=NULL) { deriv->dlambda = coef*absnu - dGdlambda*pos.lambda / lmn; deriv->dnu = (-coef*pos.lambda + dGdnu*absnu / lmn) * signu; deriv->dphi = 0; } if(deriv2!=NULL) { deriv2->dlambda2 = (2*absnu *(-coef + dGdlambda/lmn) - d2Gdlambda2*pos.lambda) / lmn; deriv2->dnu2 = (2*pos.lambda*(-coef + dGdnu /lmn) + d2Gdnu2 *absnu ) / lmn; deriv2->dlambdadnu = ((pos.lambda+absnu)*coef - (pos.lambda*dGdlambda + absnu*dGdnu) / lmn ) / lmn * signu; } } void OblatePerfectEllipsoid::evalDeriv(double tau, double* G, double* deriv, double* deriv2) const { // G is defined by eq.27 in de Zeeuw(1985), except that we use // tau = {tau_deZeeuw}+{gamma_deZeeuw}, which ranges from 0 to inf. if(tau<0) throw std::invalid_argument("Error in OblatePerfectEllipsoid: " "incorrect value of tau"); double c2 = pow_2(minorAxis); double fac = mass/minorAxis*(2./M_PI); double tauc = tau/c2; double arct = 1; // value for the limiting case tau==0 if(tau > 1e-16) { double sqtc = sqrt(tauc); arct = atan(sqtc)/sqtc; } if(G) *G = fac * arct; if(deriv) *deriv = tauc > 1e-8 ? fac * 0.5 * (1 / (1+tauc) - arct) / tau : fac * (-1./3 + 2./5 * tauc) / c2; // asymptotic expansion for tau->0 if(deriv2!=NULL) *deriv2 = tauc > 1e-5 ? fac * 0.75 * (arct - (1+(5./3)*tauc) / pow_2(1+tauc)) / pow_2(tau) : fac * (2./5 - 6./7 * tauc) / pow_2(c2); } } // namespace potential
[ "eugvas@lpi.ru" ]
eugvas@lpi.ru
1576ca16c3f875393673fb744030e1f474518369
be3f3c3e407ad5eba2a477a12c405adc02c106ac
/Games/Minesweeper/main.cpp
42029fcfd9a73445d9c1ed293321e3f0e3003cb3
[ "BSD-2-Clause" ]
permissive
asuperpower/serenity
ae7becc2012d53511c46958e72caff272501fe21
acb7710a62886babd852f8d5e3294c85d1f8c5e6
refs/heads/master
2022-02-17T01:26:20.635287
2019-07-21T19:57:22
2019-07-21T19:57:22
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,817
cpp
#include "Field.h" #include <LibCore/CConfigFile.h> #include <LibGUI/GAction.h> #include <LibGUI/GApplication.h> #include <LibGUI/GBoxLayout.h> #include <LibGUI/GButton.h> #include <LibGUI/GLabel.h> #include <LibGUI/GMenu.h> #include <LibGUI/GMenuBar.h> #include <LibGUI/GWindow.h> int main(int argc, char** argv) { GApplication app(argc, argv); auto* window = new GWindow; window->set_should_exit_event_loop_on_close(true); window->set_resizable(false); window->set_title("Minesweeper"); window->set_rect(100, 100, 139, 175); auto* widget = new GWidget; window->set_main_widget(widget); widget->set_layout(make<GBoxLayout>(Orientation::Vertical)); widget->layout()->set_spacing(0); auto* container = new GWidget(widget); container->set_fill_with_background_color(true); container->set_size_policy(SizePolicy::Fill, SizePolicy::Fixed); container->set_preferred_size(0, 36); container->set_layout(make<GBoxLayout>(Orientation::Horizontal)); auto* flag_icon_label = new GLabel(container); flag_icon_label->set_icon(GraphicsBitmap::load_from_file("/res/icons/minesweeper/flag.png")); auto* flag_label = new GLabel(container); auto* face_button = new GButton(container); face_button->set_button_style(ButtonStyle::CoolBar); face_button->set_size_policy(SizePolicy::Fixed, SizePolicy::Fill); face_button->set_preferred_size(36, 0); auto* time_icon_label = new GLabel(container); time_icon_label->set_icon(GraphicsBitmap::load_from_file("/res/icons/minesweeper/timer.png")); auto* time_label = new GLabel(container); auto* field = new Field(*flag_label, *time_label, *face_button, widget, [&](Size size) { size.set_height(size.height() + container->preferred_size().height()); window->resize(size); }); auto menubar = make<GMenuBar>(); auto app_menu = make<GMenu>("Minesweeper"); RefPtr<GAction> chord_toggler_action; chord_toggler_action = GAction::create("Single-click chording", [&](const GAction&) { bool toggled = !field->is_single_chording(); field->set_single_chording(toggled); chord_toggler_action->set_checked(toggled); }); chord_toggler_action->set_checkable(true); chord_toggler_action->set_checked(field->is_single_chording()); app_menu->add_action(*chord_toggler_action); app_menu->add_separator(); app_menu->add_action(GAction::create("Quit", { Mod_Alt, Key_F4 }, [](const GAction&) { GApplication::the().quit(0); return; })); menubar->add_menu(move(app_menu)); auto game_menu = make<GMenu>("Game"); game_menu->add_action(GAction::create("New game", { Mod_None, Key_F2 }, [field](const GAction&) { field->reset(); })); game_menu->add_separator(); game_menu->add_action(GAction::create("Beginner", { Mod_Ctrl, Key_B }, [field](const GAction&) { field->set_field_size(9, 9, 10); })); game_menu->add_action(GAction::create("Intermediate", { Mod_Ctrl, Key_I }, [field](const GAction&) { field->set_field_size(16, 16, 40); })); game_menu->add_action(GAction::create("Expert", { Mod_Ctrl, Key_E }, [field](const GAction&) { field->set_field_size(16, 30, 99); })); game_menu->add_action(GAction::create("Madwoman", { Mod_Ctrl, Key_M }, [field](const GAction&) { field->set_field_size(32, 60, 350); })); menubar->add_menu(move(game_menu)); auto help_menu = make<GMenu>("Help"); help_menu->add_action(GAction::create("About", [](const GAction&) { dbgprintf("FIXME: Implement Help/About\n"); })); menubar->add_menu(move(help_menu)); app.set_menubar(move(menubar)); window->show(); window->set_icon_path("/res/icons/minesweeper/mine.png"); return app.exec(); }
[ "awesomekling@gmail.com" ]
awesomekling@gmail.com
a4843f42b33e462123881ff99fcad293cf230b2f
2f84d8c9868277f5aae4825f1f841734a9acc489
/gym/100947/k.cpp
0ab0e91f93d48bcd542a63e34523cfbfe9b8aed9
[]
no_license
lkmtue/cp
5a380f34427c4d4478355c88f88c1e19bae04f20
3915012f7bb20f8d18638e35ba20303483bc7a23
refs/heads/master
2021-01-10T08:14:15.982944
2016-09-18T15:27:00
2016-09-18T15:27:00
50,479,884
0
0
null
null
null
null
UTF-8
C++
false
false
1,215
cpp
#include <algorithm> #include <cstdio> #include <cstring> #include <iostream> #include <map> #include <queue> #include <set> #include <vector> using namespace std; typedef long long ll; typedef pair<int, int> pii; #define FOR(i, a, b) for (int i = (a); i <= (b); i++) #define FORN(i, a, b) for (int i = (a); i < (b); i++) #define REP(i, n) for (int i = 0; i < (n); i++) #define FORD(i, a, b) for (int i = (a); i >= (b); i--) #define BUG(x) cerr << #x << " = " << x << endl int a[111][111]; int main() { int _; cin >> _; while (_--) { int n; cin >> n; FOR (i, 1, n) FOR (j, 1, n) cin >> a[i][j]; int d = 0; vector<int> all; FOR (i, 1, 2 * n - 1) { int x, y; if (i <= n) { x = i; y = 1; } else { x = n; y = i - n + 1; } vector<int> res; while (1 <= x && x <= n && 1 <= y && y <= n) { res.push_back(a[x][y]); x -= 1; y +=1 ; } if (d == 1) { reverse(res.begin(), res.end()); } REP (i, res.size()) all.push_back(res[i]); d = 1 - d; } REP(i, all.size()) { cout << all[i] << " "; if (i % n == n - 1) cout << endl; } } }
[ "lkmth1@gmail.com" ]
lkmth1@gmail.com
52d1dc3c5530811003d9f24a41fd430eb4425ba3
5f6c47e58f4377423e1fa064ddeb92d02e17c967
/2/server.cpp
21297ec86926eb7df700a64624fc958094702c0f
[]
no_license
themostfreeboy/TCP
e38ffcb44da8d9460145c4d8b7b3116210028a9e
541026531bbc68c279e4fa77f88dc5b8fb57cc47
refs/heads/master
2020-03-08T13:29:16.708134
2018-04-05T04:33:20
2018-04-05T04:33:20
128,159,176
1
0
null
null
null
null
GB18030
C++
false
false
1,769
cpp
//server //#include "stdafx.h" #include <stdio.h> #include <winsock2.h> #pragma comment(lib,"ws2_32.lib") int main(int argc, char* argv[]) { //初始化WSA WORD sockVersion = MAKEWORD(2,2); WSADATA wsaData; if(WSAStartup(sockVersion, &wsaData)!=0) { return 0; } //创建套接字 SOCKET slisten = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); if(slisten == INVALID_SOCKET) { printf("socket error !"); return 0; } //绑定IP和端口 sockaddr_in sin; sin.sin_family = AF_INET; sin.sin_port = htons(8888); sin.sin_addr.S_un.S_addr = INADDR_ANY; if(bind(slisten, (LPSOCKADDR)&sin, sizeof(sin)) == SOCKET_ERROR) { printf("bind error !"); } //开始监听 if(listen(slisten, 5) == SOCKET_ERROR) { printf("listen error !"); return 0; } //循环接收数据 SOCKET sClient; sockaddr_in remoteAddr; int nAddrlen = sizeof(remoteAddr); char revData[255]; while (true) { printf("等待连接...\n"); sClient = accept(slisten, (SOCKADDR *)&remoteAddr, &nAddrlen); if(sClient == INVALID_SOCKET) { printf("accept error !"); continue; } printf("接受到一个连接:%s \r\n", inet_ntoa(remoteAddr.sin_addr)); //接收数据 int ret = recv(sClient, revData, 255, 0); if(ret > 0) { revData[ret] = 0x00; printf(revData); } //发送数据 char * sendData = "你好,TCP客户端!\n"; send(sClient, sendData, strlen(sendData), 0); closesocket(sClient); } closesocket(slisten); WSACleanup(); return 0; }
[ "361425474@qq.com" ]
361425474@qq.com
3683a089bacd61857c5ac67ee392f28e5d8c3c4a
0202c7495ff3513cac263ed9efda87269cb5f49a
/hazelcast/src/hazelcast/client/spi/impl/ClientClusterServiceImpl.cpp
444d30117ca6e80aa36c1a0537637e4d37f4f436
[ "Apache-2.0" ]
permissive
dpwegener/hazelcast-cpp-client
66ebf2aadd5c8ba63ceabca75485b1d554e4ede0
3b50b88f434fbc49e39c8b00601756233990c2a8
refs/heads/master
2020-03-19T04:38:18.089140
2018-06-01T11:36:42
2018-06-01T11:36:42
135,848,799
0
0
Apache-2.0
2018-06-02T20:08:35
2018-06-02T20:08:35
null
UTF-8
C++
false
false
8,805
cpp
/* * Copyright (c) 2008-2018, Hazelcast, Inc. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <boost/foreach.hpp> #include "hazelcast/client/spi/impl/ClientClusterServiceImpl.h" #include "hazelcast/client/spi/ClientContext.h" #include "hazelcast/client/ClientConfig.h" #include "hazelcast/util/UuidUtil.h" #include "hazelcast/client/InitialMembershipEvent.h" #include "hazelcast/client/InitialMembershipListener.h" #include "hazelcast/client/spi/impl/ClientMembershipListener.h" namespace hazelcast { namespace client { namespace spi { namespace impl { impl::ClientClusterServiceImpl::ClientClusterServiceImpl(hazelcast::client::spi::ClientContext &client) : client(client) { ClientConfig &config = client.getClientConfig(); const std::set<boost::shared_ptr<MembershipListener> > &membershipListeners = config.getManagedMembershipListeners(); BOOST_FOREACH(const boost::shared_ptr<MembershipListener> &listener, membershipListeners) { addMembershipListenerWithoutInit(listener); } } std::string ClientClusterServiceImpl::addMembershipListenerWithoutInit( const boost::shared_ptr<MembershipListener> &listener) { std::string id = util::UuidUtil::newUnsecureUuidString(); listeners.put(id, listener); listener->setRegistrationId(id); return id; } boost::shared_ptr<Member> ClientClusterServiceImpl::getMember(const Address &address) { std::map<Address, boost::shared_ptr<Member> > currentMembers = members.get(); const std::map<hazelcast::client::Address, boost::shared_ptr<hazelcast::client::Member> >::iterator &it = currentMembers.find( address); if (it == currentMembers.end()) { return boost::shared_ptr<Member>(); } return it->second; } boost::shared_ptr<Member> ClientClusterServiceImpl::getMember(const std::string &uuid) { std::vector<Member> memberList = getMemberList(); BOOST_FOREACH(const Member &member, memberList) { if (uuid == member.getUuid()) { return boost::shared_ptr<Member>(new Member(member)); } } return boost::shared_ptr<Member>(); } std::vector<Member> ClientClusterServiceImpl::getMemberList() { typedef std::map<Address, boost::shared_ptr<Member> > MemberMap; MemberMap memberMap = members.get(); std::vector<Member> memberList; BOOST_FOREACH(const MemberMap::value_type &entry, memberMap) { memberList.push_back(*entry.second); } return memberList; } void ClientClusterServiceImpl::initMembershipListener(MembershipListener &listener) { if (listener.shouldRequestInitialMembers()) { Cluster &cluster = client.getCluster(); std::vector<Member> memberCollection = getMemberList(); InitialMembershipEvent event(cluster, std::set<Member>(memberCollection.begin(), memberCollection.end())); ((InitialMembershipListener &) listener).init(event); } } void ClientClusterServiceImpl::start() { clientMembershipListener.reset(new ClientMembershipListener(client)); } void ClientClusterServiceImpl::handleMembershipEvent(const MembershipEvent &event) { util::LockGuard guard(initialMembershipListenerMutex); const Member &member = event.getMember(); std::map<Address, boost::shared_ptr<Member> > newMap = members.get(); if (event.getEventType() == MembershipEvent::MEMBER_ADDED) { newMap[member.getAddress()] = boost::shared_ptr<Member>(new Member(member)); } else { newMap.erase(member.getAddress()); } members = newMap; fireMembershipEvent(event); } void ClientClusterServiceImpl::fireMembershipEvent(const MembershipEvent &event) { BOOST_FOREACH(const boost::shared_ptr<MembershipListener> &listener, listeners.values()) { if (event.getEventType() == MembershipEvent::MEMBER_ADDED) { listener->memberAdded(event); } else { listener->memberRemoved(event); } } } void ClientClusterServiceImpl::fireMemberAttributeEvent(const MemberAttributeEvent &event) { BOOST_FOREACH(const boost::shared_ptr<MembershipListener> &listener, listeners.values()) { listener->memberAttributeChanged(event); } } void ClientClusterServiceImpl::handleInitialMembershipEvent(const InitialMembershipEvent &event) { util::LockGuard guard(initialMembershipListenerMutex); const std::vector<Member> &initialMembers = event.getMembers(); std::map<Address, boost::shared_ptr<Member> > newMap; BOOST_FOREACH (const Member &initialMember, initialMembers) { newMap[initialMember.getAddress()] = boost::shared_ptr<Member>( new Member(initialMember)); } members.set(newMap); fireInitialMembershipEvent(event); } void ClientClusterServiceImpl::fireInitialMembershipEvent(const InitialMembershipEvent &event) { BOOST_FOREACH (const boost::shared_ptr<MembershipListener> &listener, listeners.values()) { if (listener->shouldRequestInitialMembers()) { ((InitialMembershipListener *) listener.get())->init(event); } } } void ClientClusterServiceImpl::shutdown() { } void ClientClusterServiceImpl::listenMembershipEvents( const boost::shared_ptr<connection::Connection> &ownerConnection) { clientMembershipListener->listenMembershipEvents(clientMembershipListener, ownerConnection); } std::string ClientClusterServiceImpl::addMembershipListener(const boost::shared_ptr<MembershipListener> &listener) { if (listener.get() == NULL) { throw exception::NullPointerException("ClientClusterServiceImpl::addMembershipListener", "listener can't be null"); } util::LockGuard guard(initialMembershipListenerMutex); std::string id = addMembershipListenerWithoutInit(listener); initMembershipListener(*listener); return id; } bool ClientClusterServiceImpl::removeMembershipListener(const std::string &registrationId) { return listeners.remove(registrationId).get() != NULL; } } } } }
[ "noreply@github.com" ]
dpwegener.noreply@github.com
4081e28a60df5ff890b70359191ec7b95ec810ca
b04a512a26e7f38d90c25346545f27ffe288cc98
/Record.cpp
ac16dfc2653ef1c3ede83a7900668fb2a3af1c8e
[]
no_license
EverettMelanson/Covid-19_Visualizer
8e2b9eb1654b58781b9da187950e21f223cc4006
58e336ee05caade08fbcf9803901077a0ac7b0a2
refs/heads/main
2023-04-06T17:06:23.972130
2021-04-12T15:08:39
2021-04-12T15:08:39
null
0
0
null
null
null
null
UTF-8
C++
false
false
956
cpp
/* Author: Everett Melanson Description: Contains functions to pharse, sort, store and display covid-19 data Date: October 7, 2020 */ #include "Record.h" //Constructor Record::Record(std::string _name, std::string _code, int _newCases, int _newDeaths, int _newRecovery, int _totalCases, int _totalDeaths, int _totalRecovery) { name = _name; code = _code; newCases = _newCases; newDeaths = _newDeaths; newRecovery = _newRecovery; totalCases = _totalCases; totalDeaths = _totalDeaths; totalRecovery = _totalRecovery; } //Getter methods used to access record data int Record::getNewCases() { return newCases; } int Record::getNewDeaths() { return newDeaths; } int Record::getNewRecovery() { return newRecovery; } int Record::getTotalCases() { return totalCases; } int Record::getTotalDeaths() { return totalDeaths; } int Record::getTotalRecovery() { return totalRecovery; } Record::~Record() {}
[ "noreply@github.com" ]
EverettMelanson.noreply@github.com