blob_id
stringlengths
40
40
directory_id
stringlengths
40
40
path
stringlengths
3
264
content_id
stringlengths
40
40
detected_licenses
listlengths
0
85
license_type
stringclasses
2 values
repo_name
stringlengths
5
140
snapshot_id
stringlengths
40
40
revision_id
stringlengths
40
40
branch_name
stringclasses
905 values
visit_date
timestamp[us]date
2015-08-09 11:21:18
2023-09-06 10:45:07
revision_date
timestamp[us]date
1997-09-14 05:04:47
2023-09-17 19:19:19
committer_date
timestamp[us]date
1997-09-14 05:04:47
2023-09-06 06:22:19
github_id
int64
3.89k
681M
star_events_count
int64
0
209k
fork_events_count
int64
0
110k
gha_license_id
stringclasses
22 values
gha_event_created_at
timestamp[us]date
2012-06-07 00:51:45
2023-09-14 21:58:39
gha_created_at
timestamp[us]date
2008-03-27 23:40:48
2023-08-21 23:17:38
gha_language
stringclasses
141 values
src_encoding
stringclasses
34 values
language
stringclasses
1 value
is_vendor
bool
1 class
is_generated
bool
2 classes
length_bytes
int64
3
10.4M
extension
stringclasses
115 values
content
stringlengths
3
10.4M
authors
listlengths
1
1
author_id
stringlengths
0
158
aaae40a85bb68fc7d6d8eef801b9d7bdcd7c5080
bcc3b015d9ed6cfab5821602a3db1d8268511675
/D2DEngine_V2/Sprite.cpp
4809d8d1fad35653c21ab040ac60a4a06613021f
[]
no_license
fatdai/D2DEngine_V2
1b9c0ceca683e5b97744b645e27a1e8eaa0f4e24
7e4d1110494659b1debce845eeb2f9cf2108eed7
refs/heads/master
2021-01-16T18:44:24.551624
2015-08-16T15:07:13
2015-08-16T15:07:13
40,477,278
0
0
null
null
null
null
UTF-8
C++
false
false
3,502
cpp
// // Sprite.cpp // D2DEngine_V2 // // Created by dai on 15/8/15. // Copyright (c) 2015年 mac. All rights reserved. // #include "Sprite.h" #include "ShaderUtil.h" #include "Director.h" #include "Utils.h" #include "globals.h" #include <assert.h> namespace D2D { Sprite::Sprite(Texture2D* texture): _texture(texture) { assert(texture); _color[0] = _color[1] = _color[2] = _color[3] = 1.0f; _shader = ShaderUtil::getInstance()->getShader(ShaderType::Shader_Sprite); setContentSize(_texture->getWidth(),_texture->getHeight()); // 按照 0,1,2, 0,2,3 顺序 //---- vertices _vertices[0] = 0; _vertices[1] = 0; _vertices[2] = _texture->getWidth(); _vertices[3] = 0; _vertices[4] = _texture->getWidth(); _vertices[5] = _texture->getHeight(); _vertices[6] = 0; _vertices[7] = 0; _vertices[8] = _texture->getWidth(); _vertices[9] = _texture->getHeight(); _vertices[10] = 0; _vertices[11] = _texture->getHeight(); //---- texCoords _texCoords[0] = 0; _texCoords[1] = 1; _texCoords[2] = 1; _texCoords[3] = 1; _texCoords[4] = 1; _texCoords[5] = 0; _texCoords[6] = 0; _texCoords[7] = 1; _texCoords[8] = 1; _texCoords[9] = 0; _texCoords[10] = 0; _texCoords[11] = 0; } void Sprite::setTexture(Texture2D* texture){ assert(texture); _texture = texture; //---- vertices _vertices[0] = 0; _vertices[1] = 0; _vertices[2] = _texture->getWidth(); _vertices[3] = 0; _vertices[4] = _texture->getWidth(); _vertices[5] = _texture->getHeight(); _vertices[6] = 0; _vertices[7] = 0; _vertices[8] = _texture->getWidth(); _vertices[9] = _texture->getHeight(); _vertices[10] = 0; _vertices[11] = _texture->getHeight(); } void Sprite::drawSelf(){ // log("Sprite::drawSelf...................."); glUseProgram(_shader->getProgramId()); Mat4 mvpMatrix; Mat4::multiply(Director::getInstance()->getProjMat4(),_modelMatrix,&mvpMatrix); glUniformMatrix4fv(_shader->get_U_MatrixId(),1, GL_FALSE,mvpMatrix.m); glUniform4fv(_shader->get_U_ColorId(),1,_color); glVertexAttribPointer(_shader->get_A_PositionId(),2,GL_FLOAT,GL_FALSE,0,_vertices); glEnableVertexAttribArray(_shader->get_A_PositionId()); glVertexAttribPointer(_shader->get_A_TexCoordsId(),2,GL_FLOAT,GL_FALSE,0,_texCoords); glEnableVertexAttribArray(_shader->get_A_TexCoordsId()); glBindTexture(GL_TEXTURE_2D,_texture->getTextureId()); if (_texture->hasAlpha()) { glEnable(GL_BLEND); glBlendFunc(GL_SRC_ALPHA,GL_ONE_MINUS_SRC_ALPHA); }else{ glDisable(GL_BLEND); } glDrawArrays(GL_TRIANGLES,0,6); CheckGLError(); glDisableVertexAttribArray(_shader->get_A_PositionId()); glDisableVertexAttribArray(_shader->get_A_TexCoordsId()); if (_texture->hasAlpha()) { glDisable(GL_BLEND); } } };
[ "1012607376@qq.com" ]
1012607376@qq.com
7a4c8c5db1e439f31d918350ac9bf9bcc462862d
8c65df6a098b3ea65e5447a1c4d27aba571b9817
/include/sky/utility.hpp
25596f55dbbb77ab2d3320df9a671edcce42ff23
[]
no_license
tianyu/sky
24956da0e946cf92203f83f63de10517951ea58b
a46e1a8eb0125ed2d8dd5a2afddfaffcb6a8fd64
refs/heads/master
2020-04-09T15:11:21.874971
2013-07-23T05:12:30
2013-07-23T05:12:30
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,002
hpp
#ifndef UTILITY_HPP #define UTILITY_HPP #include <type_traits> #include <utility> namespace sky { /** * @brief A reference forwarding helper class. * * This class is designed specifically for use with contructors. * * Programmers and compilers can generally work together to enable optimizations * for argument passing. For regular functions, fully optimized argument passing * can be realized with relatively little effort. Constructors, however, often * use their arguments to initialize their class's member variables. This can * cause unnecessary copy or move operations. * * Several techniques are used to optimize the number of copy/move operations in * a constructor. However each of them have problems: * * - Variadic templates + perfect forwarding: Achieves optimality, but only * works when the constructor takes a variable number of arguments. * - Regular templates + perfect forwarding: Handles a constant number of * arguments, but can cause issues with multiple constructors that can only * be solved with complex template-metaprogramming (e.g. enable_if). * - rvalue references + std::move: No longer depends on templates, but requires * an exponential number of constructors for optimality. * * This class is therefore designed to handle the optimal passing of a constant * number of arguments without an exponential number of overloads. fwd objects * remember lvalue/rvalue-ness of the reference they are constructed with and * will copy or move the referenced object as appropriate. */ template <typename T> class fwd { static_assert(!std::is_reference<T>::value, "T cannot be a reference type."); static_assert(!std::is_const<T>::value, "T cannot be a const type."); public: /** * @brief Capture l-value references to be forwarded. */ fwd(T const&); /** * @brief Capture r-value references to be forwarded. */ fwd(T &&); /** * @brief Move constructor */ fwd(fwd &&); /** * @brief Copy constructor is disabled. */ fwd(fwd const&) = delete; /** @{ * @brief Assignment is disabled. */ fwd &operator =(fwd const&) = delete; fwd &operator =(fwd &&) = delete; /// @} /** * @brief Convert the forwarded reference to an object. * * Moves the captured reference if it was an r-value reference. * Copies the captured reference otherwise. */ operator T(); private: union { T const*to_copy; T *to_move; }; const bool movable; }; template<typename T> fwd<T>::fwd(fwd &&f) : to_copy(std::move(f.to_copy)), movable(f.movable) {} template<typename T> fwd<T>::fwd(T const&ref) : to_copy(&ref), movable(false) {} template<typename T> fwd<T>::fwd(T &&ref) : to_move(&ref), movable(true) {} template<typename T> fwd<T>::operator T() { if (movable) return std::move(*to_move); return *to_copy; } } // namespace sky #endif // UTILITY_HPP
[ "tian.tian098@gmail.com" ]
tian.tian098@gmail.com
d326a5b50ed231eb1e1b947ee28b053624a7c950
41532cdd28d28d84b444374bcd32c18644f10ac7
/Recollection_Console/stdafx.cpp
4939da9701bf149be3f73e46fc497e395043a2bd
[]
no_license
ProjectsInCpp/-2016-Std11-14-STL-NokiaRecruit-
c3895735b7b50f86f0a9e2076b376d0f9498aa22
f8e2d186e4ab6ee662923f05a9ac5cf74e4ef748
refs/heads/master
2020-12-21T00:37:40.829239
2016-08-15T13:20:41
2016-08-15T13:20:41
56,694,044
0
0
null
null
null
null
UTF-8
C++
false
false
299
cpp
// stdafx.cpp : source file that includes just the standard includes // Recollection_Console.pch will be the pre-compiled header // stdafx.obj will contain the pre-compiled type information #include "stdafx.h" // TODO: reference any additional headers you need in STDAFX.H // and not in this file
[ "209826@student.pwr.wroc.pl" ]
209826@student.pwr.wroc.pl
b50c9db5ad3ee946ec57eb3e165ee4116545a8c8
a5b3c21b7dc0ebfc7096e877228dbd4740713bab
/C++ProgrammingCourse/section-7/7.3_ExplicitDataConversions/main.cpp
50f099b26813ba6b3432dd720763360a3cd2b4ba
[]
no_license
Cameron-Calpin/Code
7dd1ee7d8b83e3d325510ef14a92d36f254bc078
fc32e0ed2464efb64b0ebad7f76270a369e2a829
refs/heads/master
2023-07-07T06:37:54.397181
2023-07-01T23:06:58
2023-07-01T23:06:58
91,615,709
0
0
null
null
null
null
UTF-8
C++
false
false
835
cpp
#include <iostream> int main() { // Implicit cast will add up the doubles, // then turn result into int for assignment double x { 12.5 }; double y { 34.6 }; int sum = x + y; std::cout << "The sum is : " << sum << std::endl; // Explicitly cast : cast then sum up sum = static_cast<int>(x) + static_cast<int>(y); std::cout << "The sum is : " << sum << std::endl; // Explicit cast : sum up the cast, same thing as implicit cast sum = static_cast<int>(x + y); std::cout << "Sum up then cast, result : " << sum << std::endl; // Old style C-cast double PI {3.14}; int int_pi = (int) (PI); // int int_pi = static_cast<int>(PI); // same statement as above std::cout << "PI : " << PI << std::endl; std::cout << "int_pi : " << int_pi << std::endl; return 0; }
[ "cameron.calpin.14@cnu.edu" ]
cameron.calpin.14@cnu.edu
e05bbac8c0d44812e55975516182592301255748
1cdcc9cab308afa31141e55baf71d225a090dfb3
/cpp/opencvexp/src/face/face.cpp
ad65158b259bc15d9c529c845b34fcf047d5800f
[ "Apache-2.0" ]
permissive
orri93/experimental
b256391206a56557dc202f1fc6732237dd39e23e
6aa8ef71656c6086d3660faafe91fa57b5aff80a
refs/heads/master
2022-08-30T11:55:33.746451
2022-07-27T09:02:17
2022-07-27T09:02:17
241,103,958
0
0
Apache-2.0
2021-04-30T20:26:41
2020-02-17T12:37:08
JavaScript
UTF-8
C++
false
false
1,135
cpp
#include <cstdlib> #include <iostream> #include <QApplication> #include <QCommandLineParser> #include <viewer.h> #define DEVICE_ID 0 int main(int argc, char* argv[]) { int device; QApplication application(argc, argv); QGuiApplication::setApplicationDisplayName(FaceViewer::tr("Face Viewer")); QCommandLineParser commandLineParser; commandLineParser.addHelpOption(); commandLineParser.addPositionalArgument(FaceViewer::tr("[Device]"), FaceViewer::tr("Capture device to open.")); commandLineParser.process(QCoreApplication::arguments()); if (commandLineParser.positionalArguments().isEmpty()) { device = DEVICE_ID; } else { bool isok = false; QString front = commandLineParser.positionalArguments().front(); device = front.toInt(&isok); if (!isok) { std::cerr << "Failed to parse '" << front.toStdString() << "' as the Video Capture device id" << std::endl; return EXIT_FAILURE; } } FaceViewer viewer(device); viewer.show(); return application.exec(); //capture.open(device); //std::cerr << "Failed to open the default Video Capture device" << std::endl; }
[ "geirmundur.sigurdsson@nov.cm" ]
geirmundur.sigurdsson@nov.cm
27d1d361038fb34917c91f52d4f686d4aa548581
51567987c9b1a714a35228823ed1a7f3b0cbd224
/resolution/methods/tabu.h
855ebf55cf4b61df75503c128c9446e3d4822fdb
[]
no_license
lia-univali/CaixeiroViajante
095fa498cfc5a7ce09a469e828c1bf91370002a2
19f9ab8a486b87e82e6b80800535e6921d38cfb9
refs/heads/master
2021-08-24T08:01:42.069577
2017-12-08T19:13:46
2017-12-08T19:13:46
105,024,261
0
0
null
null
null
null
UTF-8
C++
false
false
6,736
h
#ifndef TABU_H #define TABU_H #include "resolution/solution.h" #include <vector> using Tabu = std::pair<int, int>; bool hasTabuConfig(Tabu tabus[], std::vector<int> path, int tabuLength) { for(int i = 0; i < path.size(); i++) { int source = path.at(i); int target = path.at((i + 1) % path.size()); for(int j = 0; j < tabuLength; j++) { if(tabus[j].first == source && tabus[j].second == target) { // || (tabus[j].second == source && tabus[j].first == target)) { return true; } } } return false; } bool configAlreadyExists(Tabu tabus[], Tabu tabu, int tabuLength) { for(int i = 0; i < tabuLength; i++) { if(tabus[i].first == tabu.first && tabus[i].second == tabu.second) return true; // if(tabus[i].first == tabu.second && tabus[i].second == tabu.first) // return true; } return false; } Tabu newTabu(int source, int target, std::vector<int> &path) { if(source < 0) source = path.size() - 1; if(source == path.size()) source = 0; if(target < 0) target = path.size() - 1; if(target == path.size()) target = 0; Tabu tabu; tabu.first = path.at(source); tabu.second = path.at(target); return tabu; } Solution tabuSearch(std::vector<Coordinate> &coordinates, Solution &sol, std::function<void(const Solution&)> setSolution = nullptr, std::function<void(std::string)> log = nullptr, std::function<void(double)> chartLog = nullptr, std::function<void(std::string)> logIterations = nullptr, std::function<bool()> stopRequested = nullptr, int tabuLength = 5, int itMax = 1000) { Tabu tabus[tabuLength]; Solution bestSol = sol; Solution currentSol = sol; auto start = std::chrono::steady_clock::now(); log("Iniciado"); int it = 0; do { Solution nextSol; nextSol.distance = INT_MAX; double tabuDistance = INT_MAX; int tabuSource, tabuTarget; for(int i = 0; i < sol.path.size(); i++) { for(int j = i + 1; j < sol.path.size(); j++) { Solution neighbor = currentSol; neighbor.distance -= getDistanceBetween( getCoordinate(coordinates, neighbor.path, i - 1), getCoordinate(coordinates, neighbor.path, i), getCoordinate(coordinates, neighbor.path, i + 1) ); neighbor.distance -= getDistanceBetween( getCoordinate(coordinates, neighbor.path, j - 1), getCoordinate(coordinates, neighbor.path, j), getCoordinate(coordinates, neighbor.path, j + 1) ); std::swap(neighbor.path.at(i), neighbor.path.at(j)); double tmp = euclidianDistance( getCoordinate(coordinates, neighbor.path, i - 1), getCoordinate(coordinates, neighbor.path, i) ); neighbor.distance += tmp; if(tmp < tabuDistance && !configAlreadyExists(tabus, newTabu(i - 1, i, neighbor.path), tabuLength)) { tabuDistance = tmp; tabuSource = i - 1; tabuTarget = i; } tmp = euclidianDistance( getCoordinate(coordinates, neighbor.path, i), getCoordinate(coordinates, neighbor.path, i + 1) ); neighbor.distance += tmp; if(tmp < tabuDistance && !configAlreadyExists(tabus, newTabu(i, i + 1, neighbor.path), tabuLength)) { tabuDistance = tmp; tabuSource = i; tabuTarget = i + 1; } tmp = euclidianDistance( getCoordinate(coordinates, neighbor.path, j - 1), getCoordinate(coordinates, neighbor.path, j) ); neighbor.distance += tmp; if(tmp < tabuDistance && !configAlreadyExists(tabus, newTabu(j - 1, j, neighbor.path), tabuLength)) { tabuDistance = tmp; tabuSource = j - 1; tabuTarget = j; } tmp = euclidianDistance( getCoordinate(coordinates, neighbor.path, j), getCoordinate(coordinates, neighbor.path, j + 1) ); neighbor.distance += tmp; if(tmp < tabuDistance && !configAlreadyExists(tabus, newTabu(j, j + 1, neighbor.path), tabuLength)) { tabuDistance = tmp; tabuSource = j; tabuTarget = j + 1; } if(hasTabuConfig(tabus, neighbor.path, tabuLength)) { continue; } if(neighbor.distance < nextSol.distance) { nextSol = neighbor; } if(neighbor.distance < bestSol.distance) { bestSol = neighbor; auto now = std::chrono::steady_clock::now(); double seconds = std::chrono::duration<double>(now-start).count(); log( "[ "+ std::to_string(seconds) +" segundos ] Distância melhorada: " + std::to_string(currentSol.distance) ); } } } Tabu tabu = newTabu(tabuSource, tabuTarget, nextSol.path); tabus[it % tabuLength] = tabu; currentSol = nextSol; setSolution( currentSol ); chartLog( currentSol.distance ); it++; } while(!stopRequested()/*it < itMax*/); return bestSol; } Solution tabuSearch(std::vector<Coordinate> &coordinates, std::function<void(const Solution&)> setSolution = nullptr, std::function<void(std::string)> log = nullptr, std::function<void(double)> chartLog = nullptr, std::function<void(std::string)> logIterations = nullptr, std::function<bool()> stopRequested = nullptr, int tabuLength = 5, int itMax = 1000) { Solution sol; for(int i = 0; i < coordinates.size(); i++) { sol.path.push_back(i); } std::random_shuffle(sol.path.begin(), sol.path.end()); sol.distance = getPathDistance(coordinates, sol.path); return tabuSearch(coordinates, sol, setSolution, log, chartLog, logIterations, stopRequested, tabuLength, itMax); } #endif // TABU_H
[ "rudsonm@edu.univali.br" ]
rudsonm@edu.univali.br
602f0e6e562729957d50bf795d3b893aaa57e527
1f5da7b878de9b283f6ecff55f81379992e01ec6
/Week 1/task2/main.cpp
2caa3fa8c5d3c7c728067c382ec5779ec9e1c90a
[]
no_license
rad1k4l/development-basics-cpp-white-tasks
edc739b0e9a8a20c780ea976a402cc86d35665c8
891bbb0b5cfe51f82f599c7ee8daaa6dcc5dea05
refs/heads/master
2022-12-02T07:48:13.889809
2020-08-19T19:50:15
2020-08-19T19:50:15
286,238,625
10
1
null
null
null
null
UTF-8
C++
false
false
294
cpp
#include <iostream> #include <string> using namespace std; int main() { string x, y, z; cin >> x >> y >> z; string minimum = x; if (minimum > y) { minimum = y; } if (minimum > z) { minimum = z; } cout << minimum; return 0; }
[ "zeynalli169@gmail.com" ]
zeynalli169@gmail.com
9f7c68c6009853ebb3c0bb6bd2b4dfa80708cf3a
b395eb3bb484de6ca12830c746a795cd43abe5dc
/src/profile.cpp
c2623eb49310dd8cfa0c061fc71ca85af66825eb
[ "MIT" ]
permissive
PubFork/fake
b366f45c4ed9de74daffdc4a7734af9327211bad
2e5b38e66dc02e7f793a34bdbc45aa801fb4341f
refs/heads/master
2022-04-07T03:40:16.927085
2020-01-08T03:20:44
2020-01-08T03:20:44
null
0
0
null
null
null
null
UTF-8
C++
false
false
7,834
cpp
#include "profile.h" #include "fake.h" void profile::add_func_sample(const char * func, uint32_t calltime) { profilefuncele * p = m_shh.get(func); if (!p) { profilefuncele tmp; tmp.callnum = 1; tmp.calltime = calltime; m_shh.add(func, tmp); return; } p->callnum++; p->calltime += calltime; } void profile::add_code_sample(int code) { if (LIKE(code >= 0 && code< OPCODE_MAX)) { m_codetype[code]++; } } void profile::add_gc_sample(int type, uint32_t calltime) { profilefuncele * p = m_gcshh.get(type); if (!p) { profilefuncele tmp; tmp.callnum = 1; tmp.calltime = calltime; m_gcshh.add(type, tmp); return; } p->callnum++; p->calltime += calltime; } typedef std::pair<String, profilefuncele> sortele; struct profilefuncelesort { bool operator()(const sortele & l, const sortele & r) { return l.second.calltime > r.second.calltime; } }; const char * profile::dump() { std::vector<sortele> sortelevec; for (const stringhashmap::ele * p = m_shh.first(); p != 0; p = m_shh.next()) { const profilefuncele & ele = *p->t; sortelevec.push_back(std::make_pair(p->k, ele)); } std::sort(sortelevec.begin(), sortelevec.end(), profilefuncelesort()); std::vector<sortele> gcsortelevec; for (const gchashmap::ele * p = m_gcshh.first(); p != 0; p = m_gcshh.next()) { const profilefuncele & ele = *p->t; gcsortelevec.push_back(std::make_pair(get_gc_type_name(p->k), ele)); } std::sort(gcsortelevec.begin(), gcsortelevec.end(), profilefuncelesort()); m_dumpstr.clear(); int wraplen = 30; m_dumpstr += "Call Func:\n"; m_dumpstr += "\t"; m_dumpstr += fix_string_wrap("Func", wraplen); m_dumpstr += fix_string_wrap("Calls", wraplen); m_dumpstr += fix_string_wrap("TotalTime(ms)", wraplen); m_dumpstr += fix_string_wrap("PerCallTime(ms)", wraplen); m_dumpstr += "\n"; for (int i = 0; i < (int)sortelevec.size(); i++) { const sortele & se = sortelevec[i]; const profilefuncele & ele = se.second; m_dumpstr += "\t"; m_dumpstr += fix_string_wrap(se.first, wraplen); m_dumpstr += fix_string_wrap(fkitoa(ele.callnum), wraplen); m_dumpstr += fix_string_wrap(fkitoa(ele.calltime), wraplen); m_dumpstr += fix_string_wrap(fkitoa(ele.callnum ? ele.calltime / ele.callnum : 0), wraplen); m_dumpstr += "\n"; } m_dumpstr += "GC:\n"; m_dumpstr += "\t"; m_dumpstr += fix_string_wrap("Type", wraplen); m_dumpstr += fix_string_wrap("Calls", wraplen); m_dumpstr += fix_string_wrap("TotalTime(ms)", wraplen); m_dumpstr += fix_string_wrap("PerCallTime(ms)", wraplen); m_dumpstr += "\n"; for (int i = 0; i < (int)gcsortelevec.size(); i++) { const sortele & se = gcsortelevec[i]; const profilefuncele & ele = se.second; m_dumpstr += "\t"; m_dumpstr += fix_string_wrap(se.first, wraplen); m_dumpstr += fix_string_wrap(fkitoa(ele.callnum), wraplen); m_dumpstr += fix_string_wrap(fkitoa(ele.calltime), wraplen); m_dumpstr += fix_string_wrap(fkitoa(ele.callnum ? ele.calltime / ele.callnum : 0), wraplen); m_dumpstr += "\n"; } m_dumpstr += "Code Num:\n"; for (int i = 0; i < OPCODE_MAX; i++) { m_dumpstr += "\t"; m_dumpstr += OpCodeStr(i); for (int j = 0; j < (int)(20 - strlen(OpCodeStr(i))); j++) { m_dumpstr += " "; } m_dumpstr += fkitoa(m_codetype[i]); m_dumpstr += "\n"; } return m_dumpstr.c_str(); } const char * profile::dumpstat() { m_dumpstr.clear(); int wraplen = 40; m_dumpstr += fix_string_wrap("Func Map size:", wraplen); m_dumpstr += fkitoa(m_fk->fm.size()); m_dumpstr += "\n"; m_dumpstr += fix_string_wrap("String Heap size:", wraplen); m_dumpstr += fkitoa(m_fk->sh.size()); m_dumpstr += "\n"; m_dumpstr += fix_string_wrap("System String Heap size:", wraplen); m_dumpstr += fkitoa(m_fk->sh.sys_size()); m_dumpstr += "\n"; m_dumpstr += fix_string_wrap("Stack String Heap size:", wraplen); m_dumpstr += fkitoa(m_fk->sh.size() - m_fk->sh.sys_size()); m_dumpstr += "\n"; m_dumpstr += fix_string_wrap("String Heap Byte size:", wraplen); m_dumpstr += fkitoa(m_fk->sh.bytesize()); m_dumpstr += "\n"; m_dumpstr += fix_string_wrap("System String Heap Byte size:", wraplen); m_dumpstr += fkitoa(m_fk->sh.sys_bytesize()); m_dumpstr += "\n"; m_dumpstr += fix_string_wrap("Stack String Heap Byte size:", wraplen); m_dumpstr += fkitoa(m_fk->sh.bytesize() - m_fk->sh.sys_bytesize()); m_dumpstr += "\n"; m_dumpstr += fix_string_wrap("Pointer Heap size:", wraplen); m_dumpstr += fkitoa(m_fk->ph.size()); m_dumpstr += "\n"; m_dumpstr += fix_string_wrap("Processor Pool size:", wraplen); m_dumpstr += fkitoa(POOL_GROW_SIZE(m_fk->pp)); m_dumpstr += "\n"; m_dumpstr += fix_string_wrap("Map Container Pool size:", wraplen); m_dumpstr += fkitoa(m_fk->con.get_map_size()); m_dumpstr += "\n"; m_dumpstr += fix_string_wrap("Array Container Pool size:", wraplen); m_dumpstr += fkitoa(m_fk->con.get_array_size()); m_dumpstr += "\n"; m_dumpstr += fix_string_wrap("Variant Container Pool size:", wraplen); m_dumpstr += fkitoa(m_fk->con.get_variant_size()); m_dumpstr += "\n"; m_dumpstr += fix_string_wrap("Const Map Container Pool size:", wraplen); m_dumpstr += fkitoa(m_fk->con.get_cmap_size()); m_dumpstr += "\n"; m_dumpstr += fix_string_wrap("Const Array Container Pool size:", wraplen); m_dumpstr += fkitoa(m_fk->con.get_carray_size()); m_dumpstr += "\n"; m_dumpstr += fix_string_wrap("Const Variant Container Pool size:", wraplen); m_dumpstr += fkitoa(m_fk->con.get_cvariant_size()); m_dumpstr += "\n"; return m_dumpstr.c_str(); } const char * profile::dumpmem() { if (!m_isopen) { return "not open profile\n"; } m_dumpstr.clear(); int wraplen = 20; m_dumpstr += fix_string_wrap("Malloc Num:", wraplen); m_dumpstr += fkitoa(m_memmalloc_num); m_dumpstr += "\n"; m_dumpstr += fix_string_wrap("Free Num:", wraplen); m_dumpstr += fkitoa(m_memfree_num); m_dumpstr += "\n"; m_dumpstr += fix_string_wrap("Malloc Size:", wraplen); m_dumpstr += fkitoa(m_memmalloc_size); m_dumpstr += "\n"; m_dumpstr += fix_string_wrap("Free Size:", wraplen); m_dumpstr += fkitoa(m_memfree_size); m_dumpstr += "\n"; m_dumpstr += fix_string_wrap("Mem Pointer Num:", wraplen); m_dumpstr += fkitoa(m_memuse.size()); m_dumpstr += "\n"; size_t memnumtotal[emt_max]; size_t memsizetotal[emt_max]; memset(memnumtotal, 0, sizeof(memnumtotal)); memset(memsizetotal, 0, sizeof(memsizetotal)); for (memhashmap::iterator it = m_memuse.begin(); it != m_memuse.end(); it++) { const profilememele & ele = it->second; assert(ele.type >= 0 && ele.type < emt_max); memsizetotal[ele.type] += ele.size; memnumtotal[ele.type]++; } m_dumpstr += "[Mem Type Num]:\n"; for (int i = 0; i < emt_max; i++) { e_mem_type type = (e_mem_type)i; m_dumpstr += fix_string_wrap(get_mem_type_name(type), wraplen); m_dumpstr += ":"; m_dumpstr += fkitoa(memnumtotal[type]); m_dumpstr += "\n"; } m_dumpstr += "[Mem Type Size]:\n"; for (int i = 0; i < emt_max; i++) { e_mem_type type = (e_mem_type)i; m_dumpstr += fix_string_wrap(get_mem_type_name(type), wraplen); m_dumpstr += ":"; m_dumpstr += fkitoa(memsizetotal[type]); m_dumpstr += "\n"; } return m_dumpstr.c_str(); } void profile::add_mem(void * p, size_t size, e_mem_type type) { memhashmap::iterator it = m_memuse.find(p); if (it == m_memuse.end()) { profilememele tmp; tmp.type = type; tmp.size = size; m_memuse[p] = tmp; m_memmalloc_num++; m_memmalloc_size += size; } else { assert(0); } } void profile::dec_mem(void * p) { memhashmap::iterator it = m_memuse.find(p); if (it == m_memuse.end()) { assert(0); } else { m_memfree_num++; m_memfree_size += it->second.size; m_memuse.erase(p); } }
[ "zhaoxin29@baidu.com" ]
zhaoxin29@baidu.com
0f0b05e85e1ca2acd1ef504bfec94c5e8381614c
182887fc8ee4cfd51d2124e5ea13489417efa006
/codingbook.cpp
e335eb2ff366b8a42f2b9357bb14773b41fae2cb
[]
no_license
devSC/cpp-demos
dc94a58b80b9c517024517f210055c3ac4d1083f
bae0f27acea1402c3a85d78b8378ddaa87da0d32
refs/heads/master
2021-05-05T10:34:13.068822
2017-10-10T06:43:05
2017-10-10T06:43:05
104,299,874
0
0
null
null
null
null
UTF-8
C++
false
false
455
cpp
// // Created by Wilson-Yuan on 2017/9/22. // #include <mach/mach_types.h> #include "codingbook.h" #include <iostream> codingbook::codingbook(language lang, char *t, double p):book(t,p) { this->lang = lang; } void codingbook::setlang(language lang) { lang = lang; } language codingbook::getlang(language lang) { return lang; } void codingbook::display() { book::display(); std::cout << "The language is " << lang << std::endl; }
[ "xiaochong2154@163.com" ]
xiaochong2154@163.com
7ff526fd2ea36f6a6c46a89dd4f7cf206f854480
3438e8c139a5833836a91140af412311aebf9e86
/chrome/browser/chromeos/login/session/user_session_manager.cc
751d50e1e2246766723fedc0ef55532efd8ae715
[ "BSD-3-Clause" ]
permissive
Exstream-OpenSource/Chromium
345b4336b2fbc1d5609ac5a67dbf361812b84f54
718ca933938a85c6d5548c5fad97ea7ca1128751
refs/heads/master
2022-12-21T20:07:40.786370
2016-10-18T04:53:43
2016-10-18T04:53:43
71,210,435
0
2
BSD-3-Clause
2022-12-18T12:14:22
2016-10-18T04:58:13
null
UTF-8
C++
false
false
75,141
cc
// Copyright 2014 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/chromeos/login/session/user_session_manager.h" #include <stddef.h> #include <set> #include <string> #include <vector> #include "base/base_paths.h" #include "base/bind.h" #include "base/command_line.h" #include "base/location.h" #include "base/logging.h" #include "base/memory/ptr_util.h" #include "base/metrics/histogram_macros.h" #include "base/path_service.h" #include "base/single_thread_task_runner.h" #include "base/strings/string16.h" #include "base/strings/stringprintf.h" #include "base/sys_info.h" #include "base/task_runner_util.h" #include "base/threading/thread_task_runner_handle.h" #include "base/threading/worker_pool.h" #include "chrome/browser/about_flags.h" #include "chrome/browser/app_mode/app_mode_utils.h" #include "chrome/browser/browser_process.h" #include "chrome/browser/browser_process_platform_part_chromeos.h" #include "chrome/browser/browser_shutdown.h" #include "chrome/browser/chrome_notification_types.h" #include "chrome/browser/chromeos/accessibility/accessibility_manager.h" #include "chrome/browser/chromeos/arc/arc_auth_service.h" #include "chrome/browser/chromeos/base/locale_util.h" #include "chrome/browser/chromeos/boot_times_recorder.h" #include "chrome/browser/chromeos/first_run/first_run.h" #include "chrome/browser/chromeos/first_run/goodies_displayer.h" #include "chrome/browser/chromeos/input_method/input_method_util.h" #include "chrome/browser/chromeos/login/auth/chrome_cryptohome_authenticator.h" #include "chrome/browser/chromeos/login/chrome_restart_request.h" #include "chrome/browser/chromeos/login/demo_mode/demo_app_launcher.h" #include "chrome/browser/chromeos/login/easy_unlock/easy_unlock_key_manager.h" #include "chrome/browser/chromeos/login/existing_user_controller.h" #include "chrome/browser/chromeos/login/helper.h" #include "chrome/browser/chromeos/login/lock/screen_locker.h" #include "chrome/browser/chromeos/login/profile_auth_data.h" #include "chrome/browser/chromeos/login/saml/saml_offline_signin_limiter.h" #include "chrome/browser/chromeos/login/saml/saml_offline_signin_limiter_factory.h" #include "chrome/browser/chromeos/login/signin/oauth2_login_manager.h" #include "chrome/browser/chromeos/login/signin/oauth2_login_manager_factory.h" #include "chrome/browser/chromeos/login/signin/token_handle_fetcher.h" #include "chrome/browser/chromeos/login/startup_utils.h" #include "chrome/browser/chromeos/login/ui/input_events_blocker.h" #include "chrome/browser/chromeos/login/ui/login_display_host.h" #include "chrome/browser/chromeos/login/user_flow.h" #include "chrome/browser/chromeos/login/users/chrome_user_manager.h" #include "chrome/browser/chromeos/login/users/supervised_user_manager.h" #include "chrome/browser/chromeos/login/wizard_controller.h" #include "chrome/browser/chromeos/policy/browser_policy_connector_chromeos.h" #include "chrome/browser/chromeos/profiles/profile_helper.h" #include "chrome/browser/chromeos/settings/cros_settings.h" #include "chrome/browser/component_updater/ev_whitelist_component_installer.h" #include "chrome/browser/component_updater/sth_set_component_installer.h" #include "chrome/browser/first_run/first_run.h" #include "chrome/browser/google/google_brand_chromeos.h" #include "chrome/browser/lifetime/application_lifetime.h" #include "chrome/browser/net/crl_set_fetcher.h" #include "chrome/browser/net/nss_context.h" #include "chrome/browser/prefs/session_startup_pref.h" #include "chrome/browser/profiles/profile.h" #include "chrome/browser/profiles/profile_manager.h" #include "chrome/browser/signin/account_tracker_service_factory.h" #include "chrome/browser/signin/easy_unlock_service.h" #include "chrome/browser/signin/signin_manager_factory.h" #include "chrome/browser/supervised_user/child_accounts/child_account_service.h" #include "chrome/browser/supervised_user/child_accounts/child_account_service_factory.h" #include "chrome/browser/ui/app_list/start_page_service.h" #include "chrome/browser/ui/ash/ash_util.h" #include "chrome/browser/ui/ash/multi_user/multi_user_util.h" #include "chrome/browser/ui/startup/startup_browser_creator.h" #include "chrome/common/chrome_switches.h" #include "chrome/common/logging_chrome.h" #include "chrome/common/pref_names.h" #include "chromeos/cert_loader.h" #include "chromeos/chromeos_switches.h" #include "chromeos/cryptohome/cryptohome_parameters.h" #include "chromeos/cryptohome/cryptohome_util.h" #include "chromeos/dbus/cryptohome_client.h" #include "chromeos/dbus/dbus_thread_manager.h" #include "chromeos/dbus/session_manager_client.h" #include "chromeos/login/auth/stub_authenticator.h" #include "chromeos/login/user_names.h" #include "chromeos/network/portal_detector/network_portal_detector.h" #include "chromeos/network/portal_detector/network_portal_detector_strategy.h" #include "chromeos/settings/cros_settings_names.h" #include "components/arc/arc_bridge_service.h" #include "components/arc/arc_service_manager.h" #include "components/component_updater/component_updater_service.h" #include "components/flags_ui/pref_service_flags_storage.h" #include "components/policy/core/common/cloud/cloud_policy_constants.h" #include "components/prefs/pref_member.h" #include "components/prefs/pref_registry_simple.h" #include "components/prefs/pref_service.h" #include "components/quirks/quirks_manager.h" #include "components/session_manager/core/session_manager.h" #include "components/signin/core/account_id/account_id.h" #include "components/signin/core/browser/account_tracker_service.h" #include "components/signin/core/browser/signin_manager_base.h" #include "components/user_manager/known_user.h" #include "components/user_manager/user.h" #include "components/user_manager/user_manager.h" #include "components/user_manager/user_type.h" #include "content/public/browser/browser_thread.h" #include "content/public/browser/notification_service.h" #include "content/public/browser/storage_partition.h" #include "content/public/common/content_switches.h" #include "net/cert/sth_distributor.h" #include "ui/base/ime/chromeos/input_method_descriptor.h" #include "ui/base/ime/chromeos/input_method_manager.h" #include "url/gurl.h" #if defined(ENABLE_RLZ) #include "chrome/browser/rlz/chrome_rlz_tracker_delegate.h" #include "components/rlz/rlz_tracker.h" #endif namespace chromeos { namespace { // Milliseconds until we timeout our attempt to fetch flags from the child // account service. static const int kFlagsFetchingLoginTimeoutMs = 1000; // The maximum ammount of time that we are willing to delay a browser restart // for, waiting for a session restore to finish. static const int kMaxRestartDelaySeconds = 10; // ChromeVox tutorial URL (used in place of "getting started" url when // accessibility is enabled). const char kChromeVoxTutorialURLPattern[] = "http://www.chromevox.com/tutorial/index.html?lang=%s"; void InitLocaleAndInputMethodsForNewUser( UserSessionManager* session_manager, Profile* profile, const std::string& public_session_locale, const std::string& public_session_input_method) { PrefService* prefs = profile->GetPrefs(); std::string locale; if (!public_session_locale.empty()) { // If this is a public session and the user chose a |public_session_locale|, // write it to |prefs| so that the UI switches to it. locale = public_session_locale; prefs->SetString(prefs::kApplicationLocale, locale); // Suppress the locale change dialog. prefs->SetString(prefs::kApplicationLocaleAccepted, locale); } else { // Otherwise, assume that the session will use the current UI locale. locale = g_browser_process->GetApplicationLocale(); } // First, we'll set kLanguagePreloadEngines. input_method::InputMethodManager* manager = input_method::InputMethodManager::Get(); input_method::InputMethodDescriptor preferred_input_method; if (!public_session_input_method.empty()) { // If this is a public session and the user chose a valid // |public_session_input_method|, use it as the |preferred_input_method|. const input_method::InputMethodDescriptor* const descriptor = manager->GetInputMethodUtil()->GetInputMethodDescriptorFromId( public_session_input_method); if (descriptor) { preferred_input_method = *descriptor; } else { LOG(WARNING) << "Public session is initialized with an invalid IME" << ", id=" << public_session_input_method; } } // If |preferred_input_method| is not set, use the currently active input // method. if (preferred_input_method.id().empty()) { preferred_input_method = session_manager->GetDefaultIMEState(profile)->GetCurrentInputMethod(); const input_method::InputMethodDescriptor* descriptor = manager->GetInputMethodUtil()->GetInputMethodDescriptorFromId( manager->GetInputMethodUtil()->GetHardwareInputMethodIds()[0]); // If the hardware input method's keyboard layout is the same as the // default input method (e.g. from GaiaScreen), use the hardware input // method. Note that the hardware input method can be non-login-able. // Refer to the issue chrome-os-partner:48623. if (descriptor && descriptor->GetPreferredKeyboardLayout() == preferred_input_method.GetPreferredKeyboardLayout()) { preferred_input_method = *descriptor; } } // Derive kLanguagePreloadEngines from |locale| and |preferred_input_method|. std::vector<std::string> input_method_ids; manager->GetInputMethodUtil()->GetFirstLoginInputMethodIds( locale, preferred_input_method, &input_method_ids); // Save the input methods in the user's preferences. StringPrefMember language_preload_engines; language_preload_engines.Init(prefs::kLanguagePreloadEngines, prefs); language_preload_engines.SetValue(base::JoinString(input_method_ids, ",")); BootTimesRecorder::Get()->AddLoginTimeMarker("IMEStarted", false); // Second, we'll set kLanguagePreferredLanguages. std::vector<std::string> language_codes; // The current locale should be on the top. language_codes.push_back(locale); // Add input method IDs based on the input methods, as there may be // input methods that are unrelated to the current locale. Example: the // hardware keyboard layout xkb:us::eng is used for logging in, but the // UI language is set to French. In this case, we should set "fr,en" // to the preferred languages preference. std::vector<std::string> candidates; manager->GetInputMethodUtil()->GetLanguageCodesFromInputMethodIds( input_method_ids, &candidates); for (size_t i = 0; i < candidates.size(); ++i) { const std::string& candidate = candidates[i]; // Skip if it's already in language_codes. if (std::count(language_codes.begin(), language_codes.end(), candidate) == 0) { language_codes.push_back(candidate); } } // Save the preferred languages in the user's preferences. prefs->SetString(prefs::kLanguagePreferredLanguages, base::JoinString(language_codes, ",")); // Indicate that we need to merge the syncable input methods when we sync, // since we have not applied the synced prefs before. prefs->SetBoolean(prefs::kLanguageShouldMergeInputMethods, true); } #if defined(ENABLE_RLZ) // Flag file that disables RLZ tracking, when present. const base::FilePath::CharType kRLZDisabledFlagName[] = FILE_PATH_LITERAL(".rlz_disabled"); base::FilePath GetRlzDisabledFlagPath() { base::FilePath homedir; PathService::Get(base::DIR_HOME, &homedir); return homedir.Append(kRLZDisabledFlagName); } #endif // Callback to GetNSSCertDatabaseForProfile. It starts CertLoader using the // provided NSS database. It must be called for primary user only. void OnGetNSSCertDatabaseForUser(net::NSSCertDatabase* database) { if (!CertLoader::IsInitialized()) return; CertLoader::Get()->StartWithNSSDB(database); } // Returns new CommandLine with per-user flags. base::CommandLine CreatePerSessionCommandLine(Profile* profile) { base::CommandLine user_flags(base::CommandLine::NO_PROGRAM); flags_ui::PrefServiceFlagsStorage flags_storage_(profile->GetPrefs()); about_flags::ConvertFlagsToSwitches(&flags_storage_, &user_flags, flags_ui::kAddSentinels); return user_flags; } // Returns true if restart is needed to apply per-session flags. bool NeedRestartToApplyPerSessionFlags( const base::CommandLine& user_flags, std::set<base::CommandLine::StringType>* out_command_line_difference) { // Don't restart browser if it is not first profile in session. if (user_manager::UserManager::Get()->GetLoggedInUsers().size() != 1) return false; // Only restart if needed and if not going into managed mode. if (user_manager::UserManager::Get()->IsLoggedInAsSupervisedUser()) return false; if (about_flags::AreSwitchesIdenticalToCurrentCommandLine( user_flags, *base::CommandLine::ForCurrentProcess(), out_command_line_difference)) { return false; } return true; } bool CanPerformEarlyRestart() { // Desktop build is used for development only. Early restart is not supported. if (!base::SysInfo::IsRunningOnChromeOS()) return false; if (!ChromeUserManager::Get() ->GetCurrentUserFlow() ->SupportsEarlyRestartToApplyFlags()) { return false; } const ExistingUserController* controller = ExistingUserController::current_controller(); if (!controller) return true; // Early restart is possible only if OAuth token is up to date. if (controller->password_changed()) return false; if (controller->auth_mode() != LoginPerformer::AUTH_MODE_INTERNAL) return false; // No early restart if Easy unlock key needs to be updated. if (UserSessionManager::GetInstance()->NeedsToUpdateEasyUnlockKeys()) return false; return true; } void LogCustomSwitches(const std::set<std::string>& switches) { if (!VLOG_IS_ON(1)) return; for (std::set<std::string>::const_iterator it = switches.begin(); it != switches.end(); ++it) { VLOG(1) << "Switch leading to restart: '" << *it << "'"; } } void RestartOnTimeout() { LOG(WARNING) << "Restarting Chrome because the time out was reached." "The session restore has not finished."; chrome::AttemptRestart(); } } // namespace UserSessionManagerDelegate::~UserSessionManagerDelegate() { } void UserSessionStateObserver::PendingUserSessionsRestoreFinished() { } UserSessionStateObserver::~UserSessionStateObserver() { } // static UserSessionManager* UserSessionManager::GetInstance() { return base::Singleton<UserSessionManager, base::DefaultSingletonTraits< UserSessionManager>>::get(); } // static void UserSessionManager::OverrideHomedir() { // Override user homedir, check for ProfileManager being initialized as // it may not exist in unit tests. if (g_browser_process->profile_manager()) { user_manager::UserManager* user_manager = user_manager::UserManager::Get(); if (user_manager->GetLoggedInUsers().size() == 1) { base::FilePath homedir = ProfileHelper::GetProfilePathByUserIdHash( user_manager->GetPrimaryUser()->username_hash()); // This path has been either created by cryptohome (on real Chrome OS // device) or by ProfileManager (on chromeos=1 desktop builds). PathService::OverrideAndCreateIfNeeded(base::DIR_HOME, homedir, true /* path is absolute */, false /* don't create */); } } } // static void UserSessionManager::RegisterPrefs(PrefRegistrySimple* registry) { registry->RegisterStringPref(prefs::kRLZBrand, std::string()); registry->RegisterBooleanPref(prefs::kRLZDisabled, false); registry->RegisterBooleanPref(prefs::kCanShowOobeGoodiesPage, true); } UserSessionManager::UserSessionManager() : delegate_(nullptr), authenticator_(nullptr), has_auth_cookies_(false), user_sessions_restored_(false), user_sessions_restore_in_progress_(false), exit_after_session_restore_(false), session_restore_strategy_( OAuth2LoginManager::RESTORE_FROM_SAVED_OAUTH2_REFRESH_TOKEN), running_easy_unlock_key_ops_(false), should_obtain_handles_(true), should_launch_browser_(true), waiting_for_child_account_status_(false), weak_factory_(this) { net::NetworkChangeNotifier::AddConnectionTypeObserver(this); user_manager::UserManager::Get()->AddSessionStateObserver(this); } UserSessionManager::~UserSessionManager() { // UserManager is destroyed before singletons, so we need to check if it // still exists. // TODO(nkostylev): fix order of destruction of UserManager // / UserSessionManager objects. if (user_manager::UserManager::IsInitialized()) user_manager::UserManager::Get()->RemoveSessionStateObserver(this); net::NetworkChangeNotifier::RemoveConnectionTypeObserver(this); } void UserSessionManager::SetShouldObtainHandleInTests( bool should_obtain_handles) { should_obtain_handles_ = should_obtain_handles; if (!should_obtain_handles_) { token_handle_fetcher_.reset(); } } void UserSessionManager::CompleteGuestSessionLogin(const GURL& start_url) { VLOG(1) << "Completing guest session login"; // For guest session we ask session_manager to restart Chrome with --bwsi // flag. We keep only some of the arguments of this process. const base::CommandLine& browser_command_line = *base::CommandLine::ForCurrentProcess(); base::CommandLine command_line(browser_command_line.GetProgram()); GetOffTheRecordCommandLine(start_url, StartupUtils::IsOobeCompleted(), browser_command_line, &command_line); // This makes sure that Chrome restarts with no per-session flags. The guest // profile will always have empty set of per-session flags. If this is not // done and device owner has some per-session flags, when Chrome is relaunched // the guest profile session flags will not match the current command line and // another restart will be attempted in order to reset the user flags for the // guest user. const base::CommandLine user_flags(base::CommandLine::NO_PROGRAM); if (!about_flags::AreSwitchesIdenticalToCurrentCommandLine( user_flags, *base::CommandLine::ForCurrentProcess(), NULL)) { DBusThreadManager::Get()->GetSessionManagerClient()->SetFlagsForUser( cryptohome::Identification(login::GuestAccountId()), base::CommandLine::StringVector()); } RestartChrome(command_line); } scoped_refptr<Authenticator> UserSessionManager::CreateAuthenticator( AuthStatusConsumer* consumer) { // Screen locker needs new Authenticator instance each time. if (ScreenLocker::default_screen_locker()) { if (authenticator_.get()) authenticator_->SetConsumer(NULL); authenticator_ = NULL; } if (authenticator_.get() == NULL) { if (injected_user_context_) { authenticator_ = new StubAuthenticator(consumer, *injected_user_context_.get()); } else { authenticator_ = new ChromeCryptohomeAuthenticator(consumer); } } else { // TODO(nkostylev): Fix this hack by improving Authenticator dependencies. authenticator_->SetConsumer(consumer); } return authenticator_; } void UserSessionManager::StartSession( const UserContext& user_context, StartSessionType start_session_type, bool has_auth_cookies, bool has_active_session, UserSessionManagerDelegate* delegate) { delegate_ = delegate; start_session_type_ = start_session_type; VLOG(1) << "Starting user session."; PreStartSession(); CreateUserSession(user_context, has_auth_cookies); if (!has_active_session) StartCrosSession(); // TODO(nkostylev): Notify UserLoggedIn() after profile is actually // ready to be used (http://crbug.com/361528). NotifyUserLoggedIn(); if (!user_context.GetDeviceId().empty()) { user_manager::known_user::SetDeviceId(user_context.GetAccountId(), user_context.GetDeviceId()); } PrepareProfile(); } void UserSessionManager::DelegateDeleted(UserSessionManagerDelegate* delegate) { if (delegate_ == delegate) delegate_ = nullptr; } void UserSessionManager::PerformPostUserLoggedInActions() { user_manager::UserManager* user_manager = user_manager::UserManager::Get(); if (user_manager->GetLoggedInUsers().size() == 1) { if (network_portal_detector::IsInitialized()) { network_portal_detector::GetInstance()->SetStrategy( PortalDetectorStrategy::STRATEGY_ID_SESSION); } } } void UserSessionManager::RestoreAuthenticationSession(Profile* user_profile) { user_manager::UserManager* user_manager = user_manager::UserManager::Get(); // We need to restore session only for logged in GAIA (regular) users. // Note: stub user is a special case that is used for tests, running // linux_chromeos build on dev workstations w/o user_id parameters. // Stub user is considered to be a regular GAIA user but it has special // user_id (kStubUser) and certain services like restoring OAuth session are // explicitly disabled for it. if (!user_manager->IsUserLoggedIn() || !user_manager->IsLoggedInAsUserWithGaiaAccount() || user_manager->IsLoggedInAsStub()) { return; } const user_manager::User* user = ProfileHelper::Get()->GetUserByProfile(user_profile); DCHECK(user); if (!net::NetworkChangeNotifier::IsOffline()) { pending_signin_restore_sessions_.erase(user->email()); RestoreAuthSessionImpl(user_profile, false /* has_auth_cookies */); } else { // Even if we're online we should wait till initial // OnConnectionTypeChanged() call. Otherwise starting fetchers too early may // end up canceling all request when initial network connection type is // processed. See http://crbug.com/121643. pending_signin_restore_sessions_.insert(user->email()); } } void UserSessionManager::RestoreActiveSessions() { user_sessions_restore_in_progress_ = true; DBusThreadManager::Get()->GetSessionManagerClient()->RetrieveActiveSessions( base::Bind(&UserSessionManager::OnRestoreActiveSessions, AsWeakPtr())); } bool UserSessionManager::UserSessionsRestored() const { DCHECK_CURRENTLY_ON(content::BrowserThread::UI); return user_sessions_restored_; } bool UserSessionManager::UserSessionsRestoreInProgress() const { DCHECK_CURRENTLY_ON(content::BrowserThread::UI); return user_sessions_restore_in_progress_; } void UserSessionManager::InitRlz(Profile* profile) { #if defined(ENABLE_RLZ) if (!g_browser_process->local_state()->HasPrefPath(prefs::kRLZBrand)) { // Read brand code asynchronously from an OEM data and repost ourselves. google_brand::chromeos::InitBrand( base::Bind(&UserSessionManager::InitRlz, AsWeakPtr(), profile)); return; } base::PostTaskAndReplyWithResult( base::WorkerPool::GetTaskRunner(false).get(), FROM_HERE, base::Bind(&base::PathExists, GetRlzDisabledFlagPath()), base::Bind(&UserSessionManager::InitRlzImpl, AsWeakPtr(), profile)); #endif } void UserSessionManager::SetFirstLoginPrefs( Profile* profile, const std::string& public_session_locale, const std::string& public_session_input_method) { VLOG(1) << "Setting first login prefs"; InitLocaleAndInputMethodsForNewUser( this, profile, public_session_locale, public_session_input_method); } bool UserSessionManager::GetAppModeChromeClientOAuthInfo( std::string* chrome_client_id, std::string* chrome_client_secret) { if (!chrome::IsRunningInForcedAppMode() || chrome_client_id_.empty() || chrome_client_secret_.empty()) { return false; } *chrome_client_id = chrome_client_id_; *chrome_client_secret = chrome_client_secret_; return true; } void UserSessionManager::SetAppModeChromeClientOAuthInfo( const std::string& chrome_client_id, const std::string& chrome_client_secret) { if (!chrome::IsRunningInForcedAppMode()) return; chrome_client_id_ = chrome_client_id; chrome_client_secret_ = chrome_client_secret; } void UserSessionManager::DoBrowserLaunch(Profile* profile, LoginDisplayHost* login_host) { DoBrowserLaunchInternal(profile, login_host, false /* locale_pref_checked */); } bool UserSessionManager::RespectLocalePreference( Profile* profile, const user_manager::User* user, const locale_util::SwitchLanguageCallback& callback) const { // TODO(alemate): http://crbug.com/288941 : Respect preferred language list in // the Google user profile. if (g_browser_process == NULL) return false; user_manager::UserManager* user_manager = user_manager::UserManager::Get(); if (!user || (user_manager->IsUserLoggedIn() && user != user_manager->GetPrimaryUser())) { return false; } // In case of multi-profiles session we don't apply profile locale // because it is unsafe. if (user_manager->GetLoggedInUsers().size() != 1) return false; const PrefService* prefs = profile->GetPrefs(); if (prefs == NULL) return false; std::string pref_locale; const std::string pref_app_locale = prefs->GetString(prefs::kApplicationLocale); const std::string pref_bkup_locale = prefs->GetString(prefs::kApplicationLocaleBackup); pref_locale = pref_app_locale; if (pref_locale.empty()) pref_locale = pref_bkup_locale; const std::string* account_locale = NULL; if (pref_locale.empty() && user->has_gaia_account()) { if (user->GetAccountLocale() == NULL) return false; // wait until Account profile is loaded. account_locale = user->GetAccountLocale(); pref_locale = *account_locale; } const std::string global_app_locale = g_browser_process->GetApplicationLocale(); if (pref_locale.empty()) pref_locale = global_app_locale; DCHECK(!pref_locale.empty()); VLOG(1) << "RespectLocalePreference: " << "app_locale='" << pref_app_locale << "', " << "bkup_locale='" << pref_bkup_locale << "', " << (account_locale != NULL ? (std::string("account_locale='") + (*account_locale) + "'. ") : (std::string("account_locale - unused. "))) << " Selected '" << pref_locale << "'"; profile->ChangeAppLocale( pref_locale, user->GetType() == user_manager::USER_TYPE_PUBLIC_ACCOUNT ? Profile::APP_LOCALE_CHANGED_VIA_PUBLIC_SESSION_LOGIN : Profile::APP_LOCALE_CHANGED_VIA_LOGIN); // Here we don't enable keyboard layouts for normal users. Input methods // are set up when the user first logs in. Then the user may customize the // input methods. Hence changing input methods here, just because the user's // UI language is different from the login screen UI language, is not // desirable. Note that input method preferences are synced, so users can use // their farovite input methods as soon as the preferences are synced. // // For Guest mode, user locale preferences will never get initialized. // So input methods should be enabled somewhere. const bool enable_layouts = user_manager::UserManager::Get()->IsLoggedInAsGuest(); locale_util::SwitchLanguage(pref_locale, enable_layouts, false /* login_layouts_only */, callback, profile); return true; } bool UserSessionManager::RestartToApplyPerSessionFlagsIfNeed( Profile* profile, bool early_restart) { if (ProfileHelper::IsSigninProfile(profile)) return false; if (early_restart && !CanPerformEarlyRestart()) return false; // We can't really restart if we've already restarted as a part of // user session restore after crash of in case when flags were changed inside // user session. if (base::CommandLine::ForCurrentProcess()->HasSwitch(switches::kLoginUser)) return false; // We can't restart if that's a second user sign in that is happening. if (user_manager::UserManager::Get()->GetLoggedInUsers().size() > 1) return false; const base::CommandLine user_flags(CreatePerSessionCommandLine(profile)); std::set<base::CommandLine::StringType> command_line_difference; if (!NeedRestartToApplyPerSessionFlags(user_flags, &command_line_difference)) return false; LogCustomSwitches(command_line_difference); about_flags::ReportAboutFlagsHistogram( "Login.CustomFlags", command_line_difference, std::set<std::string>()); base::CommandLine::StringVector flags; // argv[0] is the program name |base::CommandLine::NO_PROGRAM|. flags.assign(user_flags.argv().begin() + 1, user_flags.argv().end()); LOG(WARNING) << "Restarting to apply per-session flags..."; DBusThreadManager::Get()->GetSessionManagerClient()->SetFlagsForUser( cryptohome::Identification( user_manager::UserManager::Get()->GetActiveUser()->GetAccountId()), flags); AttemptRestart(profile); return true; } bool UserSessionManager::NeedsToUpdateEasyUnlockKeys() const { return user_context_.GetAccountId().is_valid() && user_manager::User::TypeHasGaiaAccount(user_context_.GetUserType()) && user_context_.GetKey() && !user_context_.GetKey()->GetSecret().empty(); } bool UserSessionManager::CheckEasyUnlockKeyOps(const base::Closure& callback) { if (!running_easy_unlock_key_ops_) return false; // Assumes only one deferred callback is needed. DCHECK(easy_unlock_key_ops_finished_callback_.is_null()); easy_unlock_key_ops_finished_callback_ = callback; return true; } void UserSessionManager::AddSessionStateObserver( chromeos::UserSessionStateObserver* observer) { DCHECK_CURRENTLY_ON(content::BrowserThread::UI); session_state_observer_list_.AddObserver(observer); } void UserSessionManager::RemoveSessionStateObserver( chromeos::UserSessionStateObserver* observer) { DCHECK_CURRENTLY_ON(content::BrowserThread::UI); session_state_observer_list_.RemoveObserver(observer); } void UserSessionManager::OnSessionRestoreStateChanged( Profile* user_profile, OAuth2LoginManager::SessionRestoreState state) { user_manager::User::OAuthTokenStatus user_status = user_manager::User::OAUTH_TOKEN_STATUS_UNKNOWN; OAuth2LoginManager* login_manager = OAuth2LoginManagerFactory::GetInstance()->GetForProfile(user_profile); bool connection_error = false; switch (state) { case OAuth2LoginManager::SESSION_RESTORE_DONE: user_status = user_manager::User::OAUTH2_TOKEN_STATUS_VALID; break; case OAuth2LoginManager::SESSION_RESTORE_FAILED: user_status = user_manager::User::OAUTH2_TOKEN_STATUS_INVALID; break; case OAuth2LoginManager::SESSION_RESTORE_CONNECTION_FAILED: connection_error = true; break; case OAuth2LoginManager::SESSION_RESTORE_NOT_STARTED: case OAuth2LoginManager::SESSION_RESTORE_PREPARING: case OAuth2LoginManager::SESSION_RESTORE_IN_PROGRESS: return; } // We should not be clearing existing token state if that was a connection // error. http://crbug.com/295245 if (!connection_error) { // We are in one of "done" states here. user_manager::UserManager::Get()->SaveUserOAuthStatus( user_manager::UserManager::Get()->GetLoggedInUser()->GetAccountId(), user_status); } login_manager->RemoveObserver(this); if (exit_after_session_restore_ && (state == OAuth2LoginManager::SESSION_RESTORE_DONE || state == OAuth2LoginManager::SESSION_RESTORE_FAILED || state == OAuth2LoginManager::SESSION_RESTORE_CONNECTION_FAILED)) { LOG(WARNING) << "Restarting Chrome after session restore finishes, " << "most likely due to custom flags."; // We need to restart cleanly in this case to make sure OAuth2 RT is // actually saved. chrome::AttemptRestart(); } else { // Schedule another flush after session restore for non-ephemeral profile // if not restarting. if (!ProfileHelper::IsEphemeralUserProfile(user_profile)) ProfileHelper::Get()->FlushProfile(user_profile); } } void UserSessionManager::OnConnectionTypeChanged( net::NetworkChangeNotifier::ConnectionType type) { bool is_running_test = base::CommandLine::ForCurrentProcess()->HasSwitch( ::switches::kTestName) || base::CommandLine::ForCurrentProcess()->HasSwitch(::switches::kTestType); user_manager::UserManager* user_manager = user_manager::UserManager::Get(); if (type == net::NetworkChangeNotifier::CONNECTION_NONE || !user_manager->IsUserLoggedIn() || !user_manager->IsLoggedInAsUserWithGaiaAccount() || user_manager->IsLoggedInAsStub() || is_running_test) { return; } // Need to iterate over all users and their OAuth2 session state. const user_manager::UserList& users = user_manager->GetLoggedInUsers(); for (user_manager::UserList::const_iterator it = users.begin(); it != users.end(); ++it) { if (!(*it)->is_profile_created()) continue; Profile* user_profile = ProfileHelper::Get()->GetProfileByUserUnsafe(*it); bool should_restore_session = pending_signin_restore_sessions_.find((*it)->email()) != pending_signin_restore_sessions_.end(); OAuth2LoginManager* login_manager = OAuth2LoginManagerFactory::GetInstance()->GetForProfile(user_profile); if (login_manager->SessionRestoreIsRunning()) { // If we come online for the first time after successful offline login, // we need to kick off OAuth token verification process again. login_manager->ContinueSessionRestore(); } else if (should_restore_session) { pending_signin_restore_sessions_.erase((*it)->email()); RestoreAuthSessionImpl(user_profile, false /* has_auth_cookies */); } } } void UserSessionManager::OnProfilePrepared(Profile* profile, bool browser_launched) { if (!base::CommandLine::ForCurrentProcess()->HasSwitch( ::switches::kTestName)) { // Did not log in (we crashed or are debugging), need to restore Sync. // TODO(nkostylev): Make sure that OAuth state is restored correctly for all // users once it is fully multi-profile aware. http://crbug.com/238987 // For now if we have other user pending sessions they'll override OAuth // session restore for previous users. RestoreAuthenticationSession(profile); } // Restore other user sessions if any. RestorePendingUserSessions(); } void UserSessionManager::ChildAccountStatusReceivedCallback(Profile* profile) { StopChildStatusObserving(profile); } void UserSessionManager::StopChildStatusObserving(Profile* profile) { if (waiting_for_child_account_status_ && !SessionStartupPref::TypeIsManaged(profile->GetPrefs())) { InitializeStartUrls(); } waiting_for_child_account_status_ = false; } void UserSessionManager::CreateUserSession(const UserContext& user_context, bool has_auth_cookies) { user_context_ = user_context; has_auth_cookies_ = has_auth_cookies; InitSessionRestoreStrategy(); StoreUserContextDataBeforeProfileIsCreated(); } void UserSessionManager::PreStartSession() { // Switch log file as soon as possible. if (base::SysInfo::IsRunningOnChromeOS()) logging::RedirectChromeLogging(*(base::CommandLine::ForCurrentProcess())); } void UserSessionManager::StoreUserContextDataBeforeProfileIsCreated() { // Store obfuscated GAIA ID. if (!user_context_.GetGaiaID().empty()) { user_manager::known_user::UpdateGaiaID(user_context_.GetAccountId(), user_context_.GetGaiaID()); } } void UserSessionManager::StartCrosSession() { BootTimesRecorder* btl = BootTimesRecorder::Get(); btl->AddLoginTimeMarker("StartSession-Start", false); DBusThreadManager::Get()->GetSessionManagerClient()->StartSession( cryptohome::Identification(user_context_.GetAccountId())); btl->AddLoginTimeMarker("StartSession-End", false); } void UserSessionManager::NotifyUserLoggedIn() { BootTimesRecorder* btl = BootTimesRecorder::Get(); btl->AddLoginTimeMarker("UserLoggedIn-Start", false); user_manager::UserManager* user_manager = user_manager::UserManager::Get(); user_manager->UserLoggedIn(user_context_.GetAccountId(), user_context_.GetUserIDHash(), false); btl->AddLoginTimeMarker("UserLoggedIn-End", false); } void UserSessionManager::PrepareProfile() { const bool is_demo_session = DemoAppLauncher::IsDemoAppSession(user_context_.GetAccountId()); // TODO(nkostylev): Figure out whether demo session is using the right profile // path or not. See https://codereview.chromium.org/171423009 g_browser_process->profile_manager()->CreateProfileAsync( ProfileHelper::GetProfilePathByUserIdHash(user_context_.GetUserIDHash()), base::Bind(&UserSessionManager::OnProfileCreated, AsWeakPtr(), user_context_, is_demo_session), base::string16(), std::string(), std::string()); } void UserSessionManager::OnProfileCreated(const UserContext& user_context, bool is_incognito_profile, Profile* profile, Profile::CreateStatus status) { CHECK(profile); switch (status) { case Profile::CREATE_STATUS_CREATED: // Profile created but before initializing extensions and promo resources. InitProfilePreferences(profile, user_context); break; case Profile::CREATE_STATUS_INITIALIZED: // Profile is created, extensions and promo resources are initialized. // At this point all other Chrome OS services will be notified that it is // safe to use this profile. UserProfileInitialized(profile, is_incognito_profile, user_context.GetAccountId()); break; case Profile::CREATE_STATUS_LOCAL_FAIL: case Profile::CREATE_STATUS_REMOTE_FAIL: case Profile::CREATE_STATUS_CANCELED: case Profile::MAX_CREATE_STATUS: NOTREACHED(); break; } } void UserSessionManager::InitProfilePreferences( Profile* profile, const UserContext& user_context) { const user_manager::User* user = ProfileHelper::Get()->GetUserByProfile(profile); if (user->GetType() == user_manager::USER_TYPE_KIOSK_APP && profile->IsNewProfile()) { ChromeUserManager::Get()->SetIsCurrentUserNew(true); } if (user->is_active()) { input_method::InputMethodManager* manager = input_method::InputMethodManager::Get(); manager->SetState(GetDefaultIMEState(profile)); } if (user_manager::UserManager::Get()->IsCurrentUserNew()) { SetFirstLoginPrefs(profile, user_context.GetPublicSessionLocale(), user_context.GetPublicSessionInputMethod()); } if (user_manager::UserManager::Get()->IsLoggedInAsSupervisedUser()) { user_manager::User* active_user = user_manager::UserManager::Get()->GetActiveUser(); std::string supervised_user_sync_id = ChromeUserManager::Get()->GetSupervisedUserManager()->GetUserSyncId( active_user->GetAccountId().GetUserEmail()); profile->GetPrefs()->SetString(prefs::kSupervisedUserId, supervised_user_sync_id); } else if (user_manager::UserManager::Get()-> IsLoggedInAsUserWithGaiaAccount()) { // Get the Gaia ID from the user context. If it's not available, this may // not be available when unlocking a previously opened profile, or when // creating a supervised users. However, in these cases the gaia_id should // be already available in the account tracker. std::string gaia_id = user_context.GetGaiaID(); if (gaia_id.empty()) { AccountTrackerService* account_tracker = AccountTrackerServiceFactory::GetForProfile(profile); const AccountInfo info = account_tracker->FindAccountInfoByEmail( user_context.GetAccountId().GetUserEmail()); gaia_id = info.gaia; DCHECK(!gaia_id.empty()); } // Make sure that the google service username is properly set (we do this // on every sign in, not just the first login, to deal with existing // profiles that might not have it set yet). SigninManagerBase* signin_manager = SigninManagerFactory::GetForProfile(profile); signin_manager->SetAuthenticatedAccountInfo( gaia_id, user_context.GetAccountId().GetUserEmail()); // Backfill GAIA ID in user prefs stored in Local State. std::string tmp_gaia_id; if (!user_manager::known_user::FindGaiaID(user_context.GetAccountId(), &tmp_gaia_id) && !gaia_id.empty()) { user_manager::known_user::UpdateGaiaID(user_context.GetAccountId(), gaia_id); } } } void UserSessionManager::UserProfileInitialized(Profile* profile, bool is_incognito_profile, const AccountId& account_id) { // Demo user signed in. if (is_incognito_profile) { profile->OnLogin(); // Send the notification before creating the browser so additional objects // that need the profile (e.g. the launcher) can be created first. content::NotificationService::current()->Notify( chrome::NOTIFICATION_LOGIN_USER_PROFILE_PREPARED, content::NotificationService::AllSources(), content::Details<Profile>(profile)); if (delegate_) delegate_->OnProfilePrepared(profile, false); return; } BootTimesRecorder* btl = BootTimesRecorder::Get(); btl->AddLoginTimeMarker("UserProfileGotten", false); if (user_context_.IsUsingOAuth()) { // Retrieve the policy that indicates whether to continue copying // authentication cookies set by a SAML IdP on subsequent logins after the // first. bool transfer_saml_auth_cookies_on_subsequent_login = false; if (has_auth_cookies_) { const user_manager::User* user = user_manager::UserManager::Get()->FindUser(account_id); if (user->IsAffiliated()) { CrosSettings::Get()->GetBoolean( kAccountsPrefTransferSAMLCookies, &transfer_saml_auth_cookies_on_subsequent_login); } } // Transfers authentication-related data from the profile that was used for // authentication to the user's profile. The proxy authentication state is // transferred unconditionally. If the user authenticated via an auth // extension, authentication cookies and channel IDs will be transferred as // well when the user's cookie jar is empty. If the cookie jar is not empty, // the authentication states in the browser context and the user's profile // must be merged using /MergeSession instead. Authentication cookies set by // a SAML IdP will also be transferred when the user's cookie jar is not // empty if |transfer_saml_auth_cookies_on_subsequent_login| is true. const bool transfer_auth_cookies_and_channel_ids_on_first_login = has_auth_cookies_; net::URLRequestContextGetter* auth_request_context = GetAuthRequestContext(); // Authentication request context may be missing especially if user didn't // sign in using GAIA (webview) and webview didn't yet initialize. if (auth_request_context) { ProfileAuthData::Transfer( auth_request_context, profile->GetRequestContext(), transfer_auth_cookies_and_channel_ids_on_first_login, transfer_saml_auth_cookies_on_subsequent_login, base::Bind( &UserSessionManager::CompleteProfileCreateAfterAuthTransfer, AsWeakPtr(), profile)); } else { // We need to post task so that OnProfileCreated() caller sends out // NOTIFICATION_PROFILE_CREATED which marks user profile as initialized. base::ThreadTaskRunnerHandle::Get()->PostTask( FROM_HERE, base::Bind( &UserSessionManager::CompleteProfileCreateAfterAuthTransfer, AsWeakPtr(), profile)); } return; } FinalizePrepareProfile(profile); } void UserSessionManager::CompleteProfileCreateAfterAuthTransfer( Profile* profile) { RestoreAuthSessionImpl(profile, has_auth_cookies_); FinalizePrepareProfile(profile); } void UserSessionManager::FinalizePrepareProfile(Profile* profile) { BootTimesRecorder* btl = BootTimesRecorder::Get(); // Own TPM device if, for any reason, it has not been done in EULA screen. CryptohomeClient* client = DBusThreadManager::Get()->GetCryptohomeClient(); btl->AddLoginTimeMarker("TPMOwn-Start", false); if (cryptohome_util::TpmIsEnabled() && !cryptohome_util::TpmIsBeingOwned()) { if (cryptohome_util::TpmIsOwned()) client->CallTpmClearStoredPasswordAndBlock(); else client->TpmCanAttemptOwnership(EmptyVoidDBusMethodCallback()); } btl->AddLoginTimeMarker("TPMOwn-End", false); user_manager::UserManager* user_manager = user_manager::UserManager::Get(); if (user_manager->IsLoggedInAsUserWithGaiaAccount()) { if (user_context_.GetAuthFlow() == UserContext::AUTH_FLOW_GAIA_WITH_SAML) user_manager::known_user::UpdateUsingSAML(user_context_.GetAccountId(), true); SAMLOfflineSigninLimiter* saml_offline_signin_limiter = SAMLOfflineSigninLimiterFactory::GetForProfile(profile); if (saml_offline_signin_limiter) saml_offline_signin_limiter->SignedIn(user_context_.GetAuthFlow()); } profile->OnLogin(); g_browser_process->platform_part()->SessionManager()->SetSessionState( session_manager::SESSION_STATE_LOGGED_IN_NOT_ACTIVE); // Send the notification before creating the browser so additional objects // that need the profile (e.g. the launcher) can be created first. content::NotificationService::current()->Notify( chrome::NOTIFICATION_LOGIN_USER_PROFILE_PREPARED, content::NotificationService::AllSources(), content::Details<Profile>(profile)); // Initialize various services only for primary user. const user_manager::User* user = ProfileHelper::Get()->GetUserByProfile(profile); if (user_manager->GetPrimaryUser() == user) { InitRlz(profile); InitializeCerts(profile); InitializeCRLSetFetcher(user); InitializeCertificateTransparencyComponents(user); if (arc::ArcBridgeService::GetEnabled( base::CommandLine::ForCurrentProcess())) { const AccountId& account_id = multi_user_util::GetAccountIdFromProfile(profile); std::unique_ptr<BooleanPrefMember> arc_enabled_pref = base::MakeUnique<BooleanPrefMember>(); arc_enabled_pref->Init(prefs::kArcEnabled, profile->GetPrefs()); DCHECK(arc::ArcServiceManager::Get()); arc::ArcServiceManager::Get()->OnPrimaryUserProfilePrepared( account_id, std::move(arc_enabled_pref)); arc::ArcAuthService* arc_auth_service = arc::ArcAuthService::Get(); DCHECK(arc_auth_service); arc_auth_service->OnPrimaryUserProfilePrepared(profile); } } UpdateEasyUnlockKeys(user_context_); user_context_.ClearSecrets(); if (TokenHandlesEnabled()) { CreateTokenUtilIfMissing(); if (token_handle_util_->ShouldObtainHandle(user->GetAccountId())) { if (!token_handle_fetcher_.get()) { token_handle_fetcher_.reset(new TokenHandleFetcher( token_handle_util_.get(), user->GetAccountId())); token_handle_fetcher_->BackfillToken( profile, base::Bind(&UserSessionManager::OnTokenHandleObtained, weak_factory_.GetWeakPtr())); } } } // Now that profile is ready, proceed to either alternative login flows or // launch browser. bool browser_launched = InitializeUserSession(profile); // Only allow Quirks downloads after login is finished. quirks::QuirksManager::Get()->OnLoginCompleted(); // If needed, create browser observer to display first run OOBE Goodies page. first_run::GoodiesDisplayer::Init(); // Schedule a flush if profile is not ephemeral. if (!ProfileHelper::IsEphemeralUserProfile(profile)) ProfileHelper::Get()->FlushProfile(profile); // TODO(nkostylev): This pointer should probably never be NULL, but it looks // like OnProfileCreated() may be getting called before // UserSessionManager::PrepareProfile() has set |delegate_| when Chrome is // killed during shutdown in tests -- see http://crosbug.com/18269. Replace // this 'if' statement with a CHECK(delegate_) once the underlying issue is // resolved. if (delegate_) delegate_->OnProfilePrepared(profile, browser_launched); } void UserSessionManager::ActivateWizard(const std::string& screen_name) { LoginDisplayHost* host = LoginDisplayHost::default_host(); CHECK(host); host->StartWizard(screen_name); } void UserSessionManager::InitializeStartUrls() const { // Child account status should be known by the time of this call. std::vector<std::string> start_urls; user_manager::UserManager* user_manager = user_manager::UserManager::Get(); bool can_show_getstarted_guide = user_manager->GetActiveUser()->GetType() == user_manager::USER_TYPE_REGULAR; // Skip the default first-run behavior for public accounts. if (!user_manager->IsLoggedInAsPublicAccount()) { if (AccessibilityManager::Get()->IsSpokenFeedbackEnabled()) { const char* url = kChromeVoxTutorialURLPattern; PrefService* prefs = g_browser_process->local_state(); const std::string current_locale = base::ToLowerASCII(prefs->GetString(prefs::kApplicationLocale)); std::string vox_url = base::StringPrintf(url, current_locale.c_str()); start_urls.push_back(vox_url); can_show_getstarted_guide = false; } } // Only show getting started guide for a new user. const bool should_show_getstarted_guide = user_manager->IsCurrentUserNew(); if (can_show_getstarted_guide && should_show_getstarted_guide) { // Don't open default Chrome window if we're going to launch the first-run // app. Because we don't want the first-run app to be hidden in the // background. base::CommandLine::ForCurrentProcess()->AppendSwitch( ::switches::kSilentLaunch); first_run::MaybeLaunchDialogAfterSessionStart(); } else { for (size_t i = 0; i < start_urls.size(); ++i) { base::CommandLine::ForCurrentProcess()->AppendArg(start_urls[i]); } } } bool UserSessionManager::InitializeUserSession(Profile* profile) { ChildAccountService* child_service = ChildAccountServiceFactory::GetForProfile(profile); child_service->AddChildStatusReceivedCallback( base::Bind(&UserSessionManager::ChildAccountStatusReceivedCallback, weak_factory_.GetWeakPtr(), profile)); base::ThreadTaskRunnerHandle::Get()->PostDelayedTask( FROM_HERE, base::Bind(&UserSessionManager::StopChildStatusObserving, weak_factory_.GetWeakPtr(), profile), base::TimeDelta::FromMilliseconds(kFlagsFetchingLoginTimeoutMs)); user_manager::UserManager* user_manager = user_manager::UserManager::Get(); // Kiosk apps has their own session initialization pipeline. if (user_manager->IsLoggedInAsKioskApp()) return false; if (start_session_type_ == PRIMARY_USER_SESSION) { UserFlow* user_flow = ChromeUserManager::Get()->GetCurrentUserFlow(); WizardController* oobe_controller = WizardController::default_controller(); base::CommandLine* cmdline = base::CommandLine::ForCurrentProcess(); bool skip_post_login_screens = user_flow->ShouldSkipPostLoginScreens() || (oobe_controller && oobe_controller->skip_post_login_screens()) || cmdline->HasSwitch(chromeos::switches::kOobeSkipPostLogin); if (user_manager->IsCurrentUserNew() && !skip_post_login_screens) { // Don't specify start URLs if the administrator has configured the start // URLs via policy. if (!SessionStartupPref::TypeIsManaged(profile->GetPrefs())) { if (child_service->IsChildAccountStatusKnown()) InitializeStartUrls(); else waiting_for_child_account_status_ = true; } // Mark the device as registered., i.e. the second part of OOBE as // completed. if (!StartupUtils::IsDeviceRegistered()) StartupUtils::MarkDeviceRegistered(base::Closure()); ActivateWizard(WizardController::kTermsOfServiceScreenName); return false; } } DoBrowserLaunch(profile, LoginDisplayHost::default_host()); return true; } void UserSessionManager::InitSessionRestoreStrategy() { base::CommandLine* command_line = base::CommandLine::ForCurrentProcess(); bool in_app_mode = chrome::IsRunningInForcedAppMode(); // Are we in kiosk app mode? if (in_app_mode) { if (command_line->HasSwitch(::switches::kAppModeOAuth2Token)) { user_context_.SetRefreshToken(command_line->GetSwitchValueASCII( ::switches::kAppModeOAuth2Token)); } if (command_line->HasSwitch(::switches::kAppModeAuthCode)) { user_context_.SetAuthCode(command_line->GetSwitchValueASCII( ::switches::kAppModeAuthCode)); } DCHECK(!has_auth_cookies_); } if (has_auth_cookies_) { session_restore_strategy_ = OAuth2LoginManager::RESTORE_FROM_COOKIE_JAR; } else if (!user_context_.GetRefreshToken().empty()) { session_restore_strategy_ = OAuth2LoginManager::RESTORE_FROM_PASSED_OAUTH2_REFRESH_TOKEN; } else { session_restore_strategy_ = OAuth2LoginManager::RESTORE_FROM_SAVED_OAUTH2_REFRESH_TOKEN; } } void UserSessionManager::RestoreAuthSessionImpl( Profile* profile, bool restore_from_auth_cookies) { CHECK((authenticator_.get() && authenticator_->authentication_context()) || !restore_from_auth_cookies); if (chrome::IsRunningInForcedAppMode() || base::CommandLine::ForCurrentProcess()->HasSwitch( chromeos::switches::kDisableGaiaServices)) { return; } exit_after_session_restore_ = false; // Remove legacy OAuth1 token if we have one. If it's valid, we should already // have OAuth2 refresh token in OAuth2TokenService that could be used to // retrieve all other tokens and user_context. OAuth2LoginManager* login_manager = OAuth2LoginManagerFactory::GetInstance()->GetForProfile(profile); login_manager->AddObserver(this); net::URLRequestContextGetter* auth_request_context = GetAuthRequestContext(); // Authentication request context may not be available if user was not // signing in with GAIA webview (i.e. webview instance hasn't been // initialized at all). Use fallback request context if authenticator was // provided. // Authenticator instance may not be initialized for session // restore case when Chrome is restarting after crash or to apply custom user // flags. In that case auth_request_context will be nullptr which is accepted // by RestoreSession() for session restore case. if (!auth_request_context && (authenticator_.get() && authenticator_->authentication_context())) { auth_request_context = content::BrowserContext::GetDefaultStoragePartition( authenticator_->authentication_context())->GetURLRequestContext(); } login_manager->RestoreSession(auth_request_context, session_restore_strategy_, user_context_.GetRefreshToken(), user_context_.GetAccessToken()); } void UserSessionManager::InitRlzImpl(Profile* profile, bool disabled) { #if defined(ENABLE_RLZ) PrefService* local_state = g_browser_process->local_state(); if (disabled) { // Empty brand code means an organic install (no RLZ pings are sent). google_brand::chromeos::ClearBrandForCurrentSession(); } if (disabled != local_state->GetBoolean(prefs::kRLZDisabled)) { // When switching to RLZ enabled/disabled state, clear all recorded events. rlz::RLZTracker::ClearRlzState(); local_state->SetBoolean(prefs::kRLZDisabled, disabled); } // Init the RLZ library. int ping_delay = profile->GetPrefs()->GetInteger( ::first_run::GetPingDelayPrefName().c_str()); // Negative ping delay means to send ping immediately after a first search is // recorded. rlz::RLZTracker::SetRlzDelegate( base::WrapUnique(new ChromeRLZTrackerDelegate)); rlz::RLZTracker::InitRlzDelayed( user_manager::UserManager::Get()->IsCurrentUserNew(), ping_delay < 0, base::TimeDelta::FromMilliseconds(abs(ping_delay)), ChromeRLZTrackerDelegate::IsGoogleDefaultSearch(profile), ChromeRLZTrackerDelegate::IsGoogleHomepage(profile), ChromeRLZTrackerDelegate::IsGoogleInStartpages(profile)); #endif } void UserSessionManager::InitializeCerts(Profile* profile) { // Now that the user profile has been initialized // |GetNSSCertDatabaseForProfile| is safe to be used. if (CertLoader::IsInitialized() && base::SysInfo::IsRunningOnChromeOS()) { GetNSSCertDatabaseForProfile(profile, base::Bind(&OnGetNSSCertDatabaseForUser)); } } void UserSessionManager::InitializeCRLSetFetcher( const user_manager::User* user) { const std::string username_hash = user->username_hash(); if (!username_hash.empty()) { base::FilePath path; path = ProfileHelper::GetProfilePathByUserIdHash(username_hash); component_updater::ComponentUpdateService* cus = g_browser_process->component_updater(); CRLSetFetcher* crl_set = g_browser_process->crl_set_fetcher(); if (crl_set && cus) crl_set->StartInitialLoad(cus, path); } } void UserSessionManager::InitializeCertificateTransparencyComponents( const user_manager::User* user) { const std::string username_hash = user->username_hash(); component_updater::ComponentUpdateService* cus = g_browser_process->component_updater(); if (!username_hash.empty() && cus) { const base::FilePath path = ProfileHelper::GetProfilePathByUserIdHash(username_hash); // EV whitelist. RegisterEVWhitelistComponent(cus, path); // STH set fetcher. RegisterSTHSetComponent(cus, path); } } void UserSessionManager::OnRestoreActiveSessions( const SessionManagerClient::ActiveSessionsMap& sessions, bool success) { if (!success) { LOG(ERROR) << "Could not get list of active user sessions after crash."; // If we could not get list of active user sessions it is safer to just // sign out so that we don't get in the inconsistent state. DBusThreadManager::Get()->GetSessionManagerClient()->StopSession(); return; } // One profile has been already loaded on browser start. user_manager::UserManager* user_manager = user_manager::UserManager::Get(); DCHECK_EQ(1u, user_manager->GetLoggedInUsers().size()); DCHECK(user_manager->GetActiveUser()); const cryptohome::Identification active_cryptohome_id = cryptohome::Identification(user_manager->GetActiveUser()->GetAccountId()); SessionManagerClient::ActiveSessionsMap::const_iterator it; for (it = sessions.begin(); it != sessions.end(); ++it) { if (active_cryptohome_id == it->first) continue; pending_user_sessions_[(it->first).GetAccountId()] = it->second; } RestorePendingUserSessions(); } void UserSessionManager::RestorePendingUserSessions() { if (pending_user_sessions_.empty()) { user_manager::UserManager::Get()->SwitchToLastActiveUser(); NotifyPendingUserSessionsRestoreFinished(); return; } // Get next user to restore sessions and delete it from list. PendingUserSessions::const_iterator it = pending_user_sessions_.begin(); const AccountId account_id = it->first; std::string user_id_hash = it->second; DCHECK(account_id.is_valid()); DCHECK(!user_id_hash.empty()); pending_user_sessions_.erase(account_id); // Check that this user is not logged in yet. user_manager::UserList logged_in_users = user_manager::UserManager::Get()->GetLoggedInUsers(); bool user_already_logged_in = false; for (user_manager::UserList::const_iterator it = logged_in_users.begin(); it != logged_in_users.end(); ++it) { const user_manager::User* user = (*it); if (user->GetAccountId() == account_id) { user_already_logged_in = true; break; } } DCHECK(!user_already_logged_in); if (!user_already_logged_in) { UserContext user_context(account_id); user_context.SetUserIDHash(user_id_hash); user_context.SetIsUsingOAuth(false); // Will call OnProfilePrepared() once profile has been loaded. // Only handling secondary users here since primary user profile // (and session) has been loaded on Chrome startup. StartSession(user_context, SECONDARY_USER_SESSION_AFTER_CRASH, false, // has_auth_cookies true, // has_active_session, this is restart after crash this); } else { RestorePendingUserSessions(); } } void UserSessionManager::NotifyPendingUserSessionsRestoreFinished() { DCHECK_CURRENTLY_ON(content::BrowserThread::UI); user_sessions_restored_ = true; user_sessions_restore_in_progress_ = false; for (auto& observer : session_state_observer_list_) observer.PendingUserSessionsRestoreFinished(); } void UserSessionManager::UpdateEasyUnlockKeys(const UserContext& user_context) { // Skip key update because FakeCryptohomeClient always return success // and RefreshKeys op expects a failure to stop. As a result, some tests would // timeout. // TODO(xiyuan): Revisit this when adding tests. if (!base::SysInfo::IsRunningOnChromeOS()) return; // Only update Easy unlock keys for regular user. // TODO(xiyuan): Fix inconsistency user type of |user_context| introduced in // authenticator. const user_manager::User* user = user_manager::UserManager::Get()->FindUser(user_context.GetAccountId()); if (!user || !user->HasGaiaAccount()) return; // Bail if |user_context| does not have secret. if (user_context.GetKey()->GetSecret().empty()) return; const base::ListValue* device_list = NULL; EasyUnlockService* easy_unlock_service = EasyUnlockService::GetForUser(*user); if (easy_unlock_service) { device_list = easy_unlock_service->GetRemoteDevices(); easy_unlock_service->SetHardlockState( EasyUnlockScreenlockStateHandler::NO_HARDLOCK); } base::ListValue empty_list; if (!device_list) device_list = &empty_list; EasyUnlockKeyManager* key_manager = GetEasyUnlockKeyManager(); running_easy_unlock_key_ops_ = true; key_manager->RefreshKeys( user_context, *device_list, base::Bind(&UserSessionManager::OnEasyUnlockKeyOpsFinished, AsWeakPtr(), user_context.GetAccountId().GetUserEmail())); } net::URLRequestContextGetter* UserSessionManager::GetAuthRequestContext() const { net::URLRequestContextGetter* auth_request_context = nullptr; if (StartupUtils::IsWebviewSigninEnabled()) { // Webview uses different partition storage than iframe. We need to get // cookies from the right storage for url request to get auth token into // session. content::StoragePartition* signin_partition = login::GetSigninPartition(); if (signin_partition) auth_request_context = signin_partition->GetURLRequestContext(); } else if (authenticator_.get() && authenticator_->authentication_context()) { auth_request_context = content::BrowserContext::GetDefaultStoragePartition( authenticator_->authentication_context())->GetURLRequestContext(); } return auth_request_context; } void UserSessionManager::AttemptRestart(Profile* profile) { // Restart unconditionally in case if we are stuck somewhere in a session // restore process. http://crbug.com/520346. base::ThreadTaskRunnerHandle::Get()->PostDelayedTask( FROM_HERE, base::Bind(RestartOnTimeout), base::TimeDelta::FromSeconds(kMaxRestartDelaySeconds)); if (CheckEasyUnlockKeyOps(base::Bind(&UserSessionManager::AttemptRestart, AsWeakPtr(), profile))) { return; } if (session_restore_strategy_ != OAuth2LoginManager::RESTORE_FROM_COOKIE_JAR) { chrome::AttemptRestart(); return; } // We can't really quit if the session restore process that mints new // refresh token is still in progress. OAuth2LoginManager* login_manager = OAuth2LoginManagerFactory::GetInstance()->GetForProfile(profile); if (login_manager->state() != OAuth2LoginManager::SESSION_RESTORE_PREPARING && login_manager->state() != OAuth2LoginManager::SESSION_RESTORE_IN_PROGRESS) { chrome::AttemptRestart(); return; } LOG(WARNING) << "Attempting browser restart during session restore."; exit_after_session_restore_ = true; } void UserSessionManager::OnEasyUnlockKeyOpsFinished( const std::string& user_id, bool success) { running_easy_unlock_key_ops_ = false; if (!easy_unlock_key_ops_finished_callback_.is_null()) easy_unlock_key_ops_finished_callback_.Run(); const user_manager::User* user = user_manager::UserManager::Get()->FindUser( AccountId::FromUserEmail(user_id)); EasyUnlockService* easy_unlock_service = EasyUnlockService::GetForUser(*user); easy_unlock_service->CheckCryptohomeKeysAndMaybeHardlock(); } void UserSessionManager::ActiveUserChanged( const user_manager::User* active_user) { if (!user_manager::UserManager::Get()->IsCurrentUserNew()) SendUserPodsMetrics(); Profile* profile = ProfileHelper::Get()->GetProfileByUser(active_user); // If profile has not yet been initialized, delay initialization of IME. if (!profile) return; input_method::InputMethodManager* manager = input_method::InputMethodManager::Get(); manager->SetState( GetDefaultIMEState(ProfileHelper::Get()->GetProfileByUser(active_user))); manager->MaybeNotifyImeMenuActivationChanged(); } scoped_refptr<input_method::InputMethodManager::State> UserSessionManager::GetDefaultIMEState(Profile* profile) { scoped_refptr<input_method::InputMethodManager::State> state = default_ime_states_[profile]; if (!state.get()) { // Profile can be NULL in tests. state = input_method::InputMethodManager::Get()->CreateNewState(profile); default_ime_states_[profile] = state; } return state; } void UserSessionManager::CheckEolStatus(Profile* profile) { std::map<Profile*, std::unique_ptr<EolNotification>, ProfileCompare>::iterator iter = eol_notification_handler_.find(profile); if (iter == eol_notification_handler_.end()) { auto eol_notification = base::MakeUnique<EolNotification>(profile); iter = eol_notification_handler_ .insert(std::make_pair(profile, std::move(eol_notification))) .first; } iter->second->CheckEolStatus(); } EasyUnlockKeyManager* UserSessionManager::GetEasyUnlockKeyManager() { if (!easy_unlock_key_manager_) easy_unlock_key_manager_.reset(new EasyUnlockKeyManager); return easy_unlock_key_manager_.get(); } void UserSessionManager::DoBrowserLaunchInternal(Profile* profile, LoginDisplayHost* login_host, bool locale_pref_checked) { if (browser_shutdown::IsTryingToQuit()) return; if (!locale_pref_checked) { RespectLocalePreferenceWrapper( profile, base::Bind(&UserSessionManager::DoBrowserLaunchInternal, AsWeakPtr(), profile, login_host, true /* locale_pref_checked */)); return; } if (!ChromeUserManager::Get()->GetCurrentUserFlow()->ShouldLaunchBrowser()) { ChromeUserManager::Get()->GetCurrentUserFlow()->LaunchExtraSteps(profile); return; } if (RestartToApplyPerSessionFlagsIfNeed(profile, false)) return; if (login_host) { login_host->SetStatusAreaVisible(true); login_host->BeforeSessionStart(); } BootTimesRecorder::Get()->AddLoginTimeMarker("BrowserLaunched", false); VLOG(1) << "Launching browser..."; TRACE_EVENT0("login", "LaunchBrowser"); if (should_launch_browser_) { StartupBrowserCreator browser_creator; chrome::startup::IsFirstRun first_run = ::first_run::IsChromeFirstRun() ? chrome::startup::IS_FIRST_RUN : chrome::startup::IS_NOT_FIRST_RUN; browser_creator.LaunchBrowser( *base::CommandLine::ForCurrentProcess(), profile, base::FilePath(), chrome::startup::IS_PROCESS_STARTUP, first_run); // Triggers app launcher start page service to load start page web contents. app_list::StartPageService::Get(profile); } else { LOG(WARNING) << "Browser hasn't been launched, should_launch_browser_" << " is false. This is normal in some tests."; } if (HatsNotificationController::ShouldShowSurveyToProfile(profile)) hats_notification_controller_ = new HatsNotificationController(profile); if (QuickUnlockNotificationController::ShouldShow(profile) && quick_unlock_notification_handler_.find(profile) == quick_unlock_notification_handler_.end()) { auto* qu_feature_notification_controller = new QuickUnlockNotificationController(profile); quick_unlock_notification_handler_.insert( std::make_pair(profile, qu_feature_notification_controller)); } // Mark login host for deletion after browser starts. This // guarantees that the message loop will be referenced by the // browser before it is dereferenced by the login host. if (login_host) login_host->Finalize(); user_manager::UserManager::Get()->SessionStarted(); chromeos::BootTimesRecorder::Get()->LoginDone( user_manager::UserManager::Get()->IsCurrentUserNew()); // Check to see if this profile should show EndOfLife Notification and show // the message accordingly. if (ShouldShowEolNotification(profile)) CheckEolStatus(profile); } void UserSessionManager::RespectLocalePreferenceWrapper( Profile* profile, const base::Closure& callback) { if (browser_shutdown::IsTryingToQuit()) return; // InputEventsBlocker is not available in Mash if (chrome::IsRunningInMash()) { callback.Run(); return; } const user_manager::User* const user = ProfileHelper::Get()->GetUserByProfile(profile); locale_util::SwitchLanguageCallback locale_switched_callback(base::Bind( &UserSessionManager::RunCallbackOnLocaleLoaded, callback, base::Owned(new InputEventsBlocker))); // Block UI events until // the ResourceBundle is // reloaded. if (!RespectLocalePreference(profile, user, locale_switched_callback)) callback.Run(); } // static void UserSessionManager::RunCallbackOnLocaleLoaded( const base::Closure& callback, InputEventsBlocker* /* input_events_blocker */, const locale_util::LanguageSwitchResult& /* result */) { callback.Run(); } void UserSessionManager::RemoveProfileForTesting(Profile* profile) { default_ime_states_.erase(profile); } void UserSessionManager::InjectStubUserContext( const UserContext& user_context) { injected_user_context_.reset(new UserContext(user_context)); authenticator_ = NULL; } void UserSessionManager::SendUserPodsMetrics() { bool show_users_on_signin; CrosSettings::Get()->GetBoolean(kAccountsPrefShowUserNamesOnSignIn, &show_users_on_signin); bool is_enterprise_managed = g_browser_process->platform_part() ->browser_policy_connector_chromeos() ->IsEnterpriseManaged(); UserPodsDisplay display; if (show_users_on_signin) { if (is_enterprise_managed) display = USER_PODS_DISPLAY_ENABLED_MANAGED; else display = USER_PODS_DISPLAY_ENABLED_REGULAR; } else { if (is_enterprise_managed) display = USER_PODS_DISPLAY_DISABLED_MANAGED; else display = USER_PODS_DISPLAY_DISABLED_REGULAR; } UMA_HISTOGRAM_ENUMERATION("UserSessionManager.UserPodsDisplay", display, NUM_USER_PODS_DISPLAY); } void UserSessionManager::OnOAuth2TokensFetched(UserContext context) { if (StartupUtils::IsWebviewSigninEnabled() && TokenHandlesEnabled()) { CreateTokenUtilIfMissing(); if (!token_handle_util_->HasToken(context.GetAccountId())) { token_handle_fetcher_.reset(new TokenHandleFetcher( token_handle_util_.get(), context.GetAccountId())); token_handle_fetcher_->FillForNewUser( context.GetAccessToken(), base::Bind(&UserSessionManager::OnTokenHandleObtained, weak_factory_.GetWeakPtr())); } } } void UserSessionManager::OnTokenHandleObtained(const AccountId& account_id, bool success) { if (!success) LOG(ERROR) << "OAuth2 token handle fetch failed."; token_handle_fetcher_.reset(); } bool UserSessionManager::TokenHandlesEnabled() { if (!should_obtain_handles_) return false; bool ephemeral_users_enabled = false; bool show_names_on_signin = true; auto* cros_settings = CrosSettings::Get(); cros_settings->GetBoolean(kAccountsPrefEphemeralUsersEnabled, &ephemeral_users_enabled); cros_settings->GetBoolean(kAccountsPrefShowUserNamesOnSignIn, &show_names_on_signin); return show_names_on_signin && !ephemeral_users_enabled; } void UserSessionManager::Shutdown() { if (arc::ArcBridgeService::GetEnabled( base::CommandLine::ForCurrentProcess())) { DCHECK(arc::ArcServiceManager::Get()); arc::ArcAuthService* arc_auth_service = arc::ArcAuthService::Get(); if (arc_auth_service) arc_auth_service->Shutdown(); } token_handle_fetcher_.reset(); token_handle_util_.reset(); first_run::GoodiesDisplayer::Delete(); } void UserSessionManager::CreateTokenUtilIfMissing() { if (!token_handle_util_.get()) token_handle_util_.reset(new TokenHandleUtil()); } bool UserSessionManager::ShouldShowEolNotification(Profile* profile) { if (base::CommandLine::ForCurrentProcess()->HasSwitch( chromeos::switches::kDisableEolNotification)) { return false; } // Do not show end of life notification if this device is managed by // enterprise user. if (g_browser_process->platform_part() ->browser_policy_connector_chromeos() ->IsEnterpriseManaged()) { return false; } // Do not show end of life notification if this is a guest session return !profile->IsGuestSession(); } } // namespace chromeos
[ "support@opentext.com" ]
support@opentext.com
63ec101a928864974b83281a4ac148d6ba24d9ea
f5f7b0a55c524efeec5bd9d132cc131bb1becc07
/Kode introuker/side-scroller/side-scroller.ino
c6d0d59d804e4e00fc07491381843b2989722c0d
[]
no_license
torabjerk/Elsys-GK
b5feb53cd7e1a4b6b5c8e26e2c77574f3d466a83
5ae7d0a83daacbdd41a8140e320534b5bedb464d
refs/heads/master
2022-12-24T13:19:58.334337
2020-10-08T12:57:13
2020-10-08T12:57:13
273,241,646
0
1
null
2020-08-06T14:51:53
2020-06-18T13:09:44
C++
UTF-8
C++
false
false
8,762
ino
#include <LiquidCrystal.h> #define PIN_BUTTON 2 #define PIN_AUTOPLAY 1 #define PIN_READWRITE 10 #define PIN_CONTRAST 12 #define SPRITE_RUN1 1 #define SPRITE_RUN2 2 #define SPRITE_JUMP 3 #define SPRITE_JUMP_UPPER '.' // Use the '.' character for the head #define SPRITE_JUMP_LOWER 4 #define SPRITE_TERRAIN_EMPTY ' ' // User the ' ' character #define SPRITE_TERRAIN_SOLID 5 #define SPRITE_TERRAIN_SOLID_RIGHT 6 #define SPRITE_TERRAIN_SOLID_LEFT 7 #define HERO_HORIZONTAL_POSITION 1 // Horizontal position of hero on screen #define TERRAIN_WIDTH 16 #define TERRAIN_EMPTY 0 #define TERRAIN_LOWER_BLOCK 1 #define TERRAIN_UPPER_BLOCK 2 #define HERO_POSITION_OFF 0 // Hero is invisible #define HERO_POSITION_RUN_LOWER_1 1 // Hero is running on lower row (pose 1) #define HERO_POSITION_RUN_LOWER_2 2 // (pose 2) #define HERO_POSITION_JUMP_1 3 // Starting a jump #define HERO_POSITION_JUMP_2 4 // Half-way up #define HERO_POSITION_JUMP_3 5 // Jump is on upper row #define HERO_POSITION_JUMP_4 6 // Jump is on upper row #define HERO_POSITION_JUMP_5 7 // Jump is on upper row #define HERO_POSITION_JUMP_6 8 // Jump is on upper row #define HERO_POSITION_JUMP_7 9 // Half-way down #define HERO_POSITION_JUMP_8 10 // About to land #define HERO_POSITION_RUN_UPPER_1 11 // Hero is running on upper row (pose 1) #define HERO_POSITION_RUN_UPPER_2 12 // (pose 2) LiquidCrystal lcd(11, 9, 6, 5, 4, 3); static char terrainUpper[TERRAIN_WIDTH + 1]; static char terrainLower[TERRAIN_WIDTH + 1]; static bool buttonPushed = false; // Set the button to not pressed void initializeGraphics(){ static byte graphics[] = { // Run position 1 B01100, B01100, B00000, B01110, B11100, B01100, B11010, B10011, // Run position 2 B01100, B01100, B00000, B01100, B01100, B01100, B01100, B01110, // Jump B01100, B01100, B00000, B11110, B01101, B11111, B10000, B00000, // Jump lower B11110, B01101, B11111, B10000, B00000, B00000, B00000, B00000, // Ground B11111, B11111, B11111, B11111, B11111, B11111, B11111, B11111, // Ground right B00011, B00011, B00011, B00011, B00011, B00011, B00011, B00011, // Ground left B11000, B11000, B11000, B11000, B11000, B11000, B11000, B11000, }; int i; // Skip using character 0, this allows lcd.print() to be used to // quickly draw multiple characters for (i = 0; i < 7; ++i) { lcd.createChar(i + 1, &graphics[i * 8]); } for (i = 0; i < TERRAIN_WIDTH; ++i) { terrainUpper[i] = SPRITE_TERRAIN_EMPTY; terrainLower[i] = SPRITE_TERRAIN_EMPTY; } } // Slide the terrain to the left in half-character increments // void advanceTerrain(char* terrain, byte newTerrain){ for (int i = 0; i < TERRAIN_WIDTH; ++i) { char current = terrain[i]; char next = (i == TERRAIN_WIDTH-1) ? newTerrain : terrain[i+1]; switch (current){ case SPRITE_TERRAIN_EMPTY: terrain[i] = (next == SPRITE_TERRAIN_SOLID) ? SPRITE_TERRAIN_SOLID_RIGHT : SPRITE_TERRAIN_EMPTY; break; case SPRITE_TERRAIN_SOLID: terrain[i] = (next == SPRITE_TERRAIN_EMPTY) ? SPRITE_TERRAIN_SOLID_LEFT : SPRITE_TERRAIN_SOLID; break; case SPRITE_TERRAIN_SOLID_RIGHT: terrain[i] = SPRITE_TERRAIN_SOLID; break; case SPRITE_TERRAIN_SOLID_LEFT: terrain[i] = SPRITE_TERRAIN_EMPTY; break; } } } bool drawHero(byte position, char* terrainUpper, char* terrainLower, unsigned int score) { bool collide = false; char upperSave = terrainUpper[HERO_HORIZONTAL_POSITION]; char lowerSave = terrainLower[HERO_HORIZONTAL_POSITION]; byte upper, lower; switch (position) { case HERO_POSITION_OFF: upper = lower = SPRITE_TERRAIN_EMPTY; break; case HERO_POSITION_RUN_LOWER_1: upper = SPRITE_TERRAIN_EMPTY; lower = SPRITE_RUN1; break; case HERO_POSITION_RUN_LOWER_2: upper = SPRITE_TERRAIN_EMPTY; lower = SPRITE_RUN2; break; case HERO_POSITION_JUMP_1: case HERO_POSITION_JUMP_8: upper = SPRITE_TERRAIN_EMPTY; lower = SPRITE_JUMP; break; case HERO_POSITION_JUMP_2: case HERO_POSITION_JUMP_7: upper = SPRITE_JUMP_UPPER; lower = SPRITE_JUMP_LOWER; break; case HERO_POSITION_JUMP_3: case HERO_POSITION_JUMP_4: case HERO_POSITION_JUMP_5: case HERO_POSITION_JUMP_6: upper = SPRITE_JUMP; lower = SPRITE_TERRAIN_EMPTY; break; case HERO_POSITION_RUN_UPPER_1: upper = SPRITE_RUN1; lower = SPRITE_TERRAIN_EMPTY; break; case HERO_POSITION_RUN_UPPER_2: upper = SPRITE_RUN2; lower = SPRITE_TERRAIN_EMPTY; break; } if (upper != ' ') { terrainUpper[HERO_HORIZONTAL_POSITION] = upper; collide = (upperSave == SPRITE_TERRAIN_EMPTY) ? false : true; } if (lower != ' ') { terrainLower[HERO_HORIZONTAL_POSITION] = lower; collide |= (lowerSave == SPRITE_TERRAIN_EMPTY) ? false : true; } byte digits = (score > 9999) ? 5 : (score > 999) ? 4 : (score > 99) ? 3 : (score > 9) ? 2 : 1; // Draw the scene terrainUpper[TERRAIN_WIDTH] = '\0'; terrainLower[TERRAIN_WIDTH] = '\0'; char temp = terrainUpper[16-digits]; terrainUpper[16-digits] = '\0'; lcd.setCursor(0,0); lcd.print(terrainUpper); terrainUpper[16-digits] = temp; lcd.setCursor(0,1); lcd.print(terrainLower); lcd.setCursor(16 - digits,0); lcd.print(score); terrainUpper[HERO_HORIZONTAL_POSITION] = upperSave; terrainLower[HERO_HORIZONTAL_POSITION] = lowerSave; return collide; } // Handle the button push as an interrupt void buttonPush() { buttonPushed = true; } void setup(){ pinMode(PIN_READWRITE, OUTPUT); digitalWrite(PIN_READWRITE, LOW); pinMode(PIN_CONTRAST, OUTPUT); digitalWrite(PIN_CONTRAST, LOW); pinMode(PIN_BUTTON, INPUT); digitalWrite(PIN_BUTTON, HIGH); pinMode(PIN_AUTOPLAY, OUTPUT); digitalWrite(PIN_AUTOPLAY, HIGH); // Digital pin 2 maps to interrupt 0 attachInterrupt(0/*PIN_BUTTON*/, buttonPush, FALLING); initializeGraphics(); lcd.begin(16, 2); } void loop(){ static byte heroPos = HERO_POSITION_RUN_LOWER_1; static byte newTerrainType = TERRAIN_EMPTY; static byte newTerrainDuration = 1; static bool playing = false; static bool blink = false; static unsigned int distance = 0; if (!playing) { drawHero((blink) ? HERO_POSITION_OFF : heroPos, terrainUpper, terrainLower, distance >> 3); if (blink) { lcd.setCursor(0,0); lcd.print("Press Start"); } delay(250); blink = !blink; if (buttonPushed) { initializeGraphics(); heroPos = HERO_POSITION_RUN_LOWER_1; playing = true; buttonPushed = false; distance = 0; } return; } // Shift the terrain to the left advanceTerrain(terrainLower, newTerrainType == TERRAIN_LOWER_BLOCK ? SPRITE_TERRAIN_SOLID : SPRITE_TERRAIN_EMPTY); advanceTerrain(terrainUpper, newTerrainType == TERRAIN_UPPER_BLOCK ? SPRITE_TERRAIN_SOLID : SPRITE_TERRAIN_EMPTY); // Make new terrain to enter on the right if (--newTerrainDuration == 0) { if (newTerrainType == TERRAIN_EMPTY) { newTerrainType = (random(3) == 0) ? TERRAIN_UPPER_BLOCK : TERRAIN_LOWER_BLOCK; newTerrainDuration = 2 + random(10); } else { newTerrainType = TERRAIN_EMPTY; newTerrainDuration = 10 + random(10); } } if (buttonPushed) { if (heroPos <= HERO_POSITION_RUN_LOWER_2) heroPos = HERO_POSITION_JUMP_1; // Get the hero to jump when the button is pressed buttonPushed = false; } if (drawHero(heroPos, terrainUpper, terrainLower, distance >> 3)) { playing = false; // The hero collided with something. Too bad. } else { if (heroPos == HERO_POSITION_RUN_LOWER_2 || heroPos == HERO_POSITION_JUMP_8) { heroPos = HERO_POSITION_RUN_LOWER_1; } else if ((heroPos >= HERO_POSITION_JUMP_3 && heroPos <= HERO_POSITION_JUMP_5) && terrainLower[HERO_HORIZONTAL_POSITION] != SPRITE_TERRAIN_EMPTY) { heroPos = HERO_POSITION_RUN_UPPER_1; } else if (heroPos >= HERO_POSITION_RUN_UPPER_1 && terrainLower[HERO_HORIZONTAL_POSITION] == SPRITE_TERRAIN_EMPTY) { heroPos = HERO_POSITION_JUMP_5; } else if (heroPos == HERO_POSITION_RUN_UPPER_2) { heroPos = HERO_POSITION_RUN_UPPER_1; } else { ++heroPos; } ++distance; digitalWrite(PIN_AUTOPLAY, terrainLower[HERO_HORIZONTAL_POSITION + 2] == SPRITE_TERRAIN_EMPTY ? HIGH : LOW); } delay(100); }
[ "torabjerk@hotmail.com" ]
torabjerk@hotmail.com
9149ef9769b86551e8be205c0a1209c58eb87b1e
cfbb6ecc432edaab066e7b3fb8b407a3203ca448
/Plugins/MineSlater/Source/MineSlater/Public/SMineSlater.h
93e853d4eb9a4f225ffdabc083519c4e29a1714d
[]
no_license
perry-express/MineSlater
a8c14b82b3eb5884badac75f782cec54f6a7ae95
53c56c36ff1a4b01e63a1a856edb8e34c3afb218
refs/heads/master
2023-04-04T12:33:32.509577
2021-04-08T15:35:27
2021-04-08T15:35:27
355,962,022
0
0
null
null
null
null
UTF-8
C++
false
false
1,990
h
#pragma once #include "CoreMinimal.h" #include "Widgets/SCompoundWidget.h" enum class EGridValue : uint8 { Empty, Bomb, RevealedEmpty, RevealedBomb }; enum class EGameResult : uint8 { Playing, Win, Lose }; /** * Top level widget that holds the Minesweeper game. */ class MINESLATER_API SMineSlater : public SCompoundWidget { public: SLATE_BEGIN_ARGS(SMineSlater) {} SLATE_END_ARGS() SMineSlater(); virtual ~SMineSlater(); void Construct(const FArguments& InArgs); private: static TArray<int32> GetBombIndices(int32 NumBombs, int32 GridCount); void PopulateGridPanel(); int32 HandleWidthSliderValue() const; int32 HandleHeightSliderValue() const; int32 HandleBombCountSliderValue() const; void HandleWidthSliderChanged(int32 NewValue); void HandleHeightSliderChanged(int32 NewValue); void HandleBombCountSliderChanged(int32 NewValue); ECheckBoxState HandleIsCheatingChecked() const; void HandleCheatStateChanged(ECheckBoxState NewState); void RecalculatePendingBombCount(); bool GameSettingChangesPending() const; FReply HandleNewGameButtonClicked(); void SetGridValue(int32 Column, int32 Row, EGridValue NewValue); EGridValue GetGridValue(int32 Column, int32 Row) const; int32 GetNumberOfAdjacentBombs(int32 Column, int32 Row) const; bool HandleButtonEnabled(int32 Column, int32 Row) const; FReply HandleButtonClicked(int32 Column, int32 Row); FText HandleCellText(int32 Column, int32 Row) const; FSlateColor HandleCellForegroundColor(int32 Column, int32 Row) const; EVisibility HandleGameResultOverlayVisibility() const; FText HandleGameResultText() const; FSlateColor HandleGameResultButtonBackgroundColor() const; void RevealCell(int32 Column, int32 Row); private: int32 Width; int32 Height; int32 BombCount; int32 PendingWidth; int32 PendingHeight; int32 PendingBombCount; int32 NumReveals; TArray<EGridValue> GridValues; EGameResult GameResult; bool bCheat; TSharedPtr<class SUniformGridPanel> GridPanel; };
[ "alex@alexgeek.co.uk" ]
alex@alexgeek.co.uk
c7b25dffe6e86b7e010452a2bb59c3e892167e31
d55500b7de7a29ba2eda6031317826b2828275c9
/Components/include/Light.h
2656eb502f4735b1bd0a7fe4eb683b97d78575ef
[ "MIT" ]
permissive
matheusvxf/Rasterizer
0938137c3d05dcc54e41ce4d14f143148ae9a6f0
6b07de725705134bd4099bab1a77f1286c99a8b6
refs/heads/master
2021-01-17T13:00:43.304771
2015-04-21T22:53:54
2015-04-21T22:53:54
34,140,669
0
0
null
null
null
null
UTF-8
C++
false
false
264
h
#pragma once #include "Vector4.h" #include "Color.h" #include "Object.h" class Light : public Object { protected: Color color; public: Light(); Light(double x, double y, double z, float r, float g, float b); ~Light(); Color& getColor(); };
[ "matheusventuryne@gmail.com" ]
matheusventuryne@gmail.com
6462203c6e32ada981f19b21b9699d39fa74e5ce
91a882547e393d4c4946a6c2c99186b5f72122dd
/Source/XPSP1/NT/admin/wmi/wbem/winmgmt/provsubsys/provider/include/service.h
fc83d87709cb42b8b778f7547a303fa0edbe6b48
[]
no_license
IAmAnubhavSaini/cryptoAlgorithm-nt5src
94f9b46f101b983954ac6e453d0cf8d02aa76fc7
d9e1cdeec650b9d6d3ce63f9f0abe50dabfaf9e2
refs/heads/master
2023-09-02T10:14:14.795579
2021-11-20T13:47:06
2021-11-20T13:47:06
null
0
0
null
null
null
null
UTF-8
C++
false
false
7,201
h
/*++ Copyright (C) 1996-2001 Microsoft Corporation Module Name: ProvResv.H Abstract: History: --*/ #ifndef _Provider_IWbemServices_H #define _Provider_IWbemServices_H class CProvider_IWbemServices : public IWbemServices , public IWbemPropertyProvider , public IWbemProviderInit , public IWbemShutdown { private: LONG m_ReferenceCount ; //Object reference count WmiAllocator &m_Allocator ; CRITICAL_SECTION m_CriticalSection ; IWbemServices *m_CoreService ; BSTR m_Namespace ; BSTR m_Locale ; BSTR m_User ; BSTR m_ComputerName ; BSTR m_OperatingSystemVersion ; BSTR m_OperatingSystemRunning ; BSTR m_ProductName ; IWbemClassObject *m_Win32_ProcessEx_Object ; private: HRESULT GetProductInformation () ; HRESULT GetProcessExecutable ( HANDLE a_Process , wchar_t *&a_ExecutableName ) ; HRESULT CProvider_IWbemServices :: NextProcessBlock ( SYSTEM_PROCESS_INFORMATION *a_ProcessBlock , SYSTEM_PROCESS_INFORMATION *&a_NextProcessBlock ) ; HRESULT GetProcessBlocks ( SYSTEM_PROCESS_INFORMATION *&a_ProcessInformation ) ; HRESULT GetProcessInformation ( SYSTEM_PROCESS_INFORMATION *&a_ProcessInformation ) ; HRESULT GetProcessParameters ( HANDLE a_Process , wchar_t *&a_ProcessCommandLine ) ; HRESULT CreateInstanceEnumAsync_Process_Load ( SYSTEM_PROCESS_INFORMATION *a_ProcessInformation , IWbemClassObject *a_Instance ) ; HRESULT CreateInstanceEnumAsync_Process_Single ( IWbemClassObject *a_ClassObject , long a_Flags , IWbemContext __RPC_FAR *a_Context, IWbemObjectSink FAR *a_Sink ) ; HRESULT CreateInstanceEnumAsync_Process_Batched ( IWbemClassObject *a_ClassObject , long a_Flags , IWbemContext __RPC_FAR *a_Context, IWbemObjectSink FAR *a_Sink ) ; public: CProvider_IWbemServices ( WmiAllocator &a_Allocator ) ; ~CProvider_IWbemServices () ; public: //Non-delegating object IUnknown STDMETHODIMP QueryInterface ( REFIID , LPVOID FAR * ) ; STDMETHODIMP_( ULONG ) AddRef () ; STDMETHODIMP_( ULONG ) Release () ; /* IWbemServices methods */ HRESULT STDMETHODCALLTYPE OpenNamespace ( const BSTR a_Namespace , long a_Flags , IWbemContext *a_Context , IWbemServices **a_Service , IWbemCallResult **a_CallResult ) ; HRESULT STDMETHODCALLTYPE CancelAsyncCall ( IWbemObjectSink *a_Sink ) ; HRESULT STDMETHODCALLTYPE QueryObjectSink ( long a_Flags , IWbemObjectSink **a_Sink ) ; HRESULT STDMETHODCALLTYPE GetObject ( const BSTR a_ObjectPath , long a_Flags , IWbemContext *a_Context , IWbemClassObject **ppObject , IWbemCallResult **a_CallResult ) ; HRESULT STDMETHODCALLTYPE GetObjectAsync ( const BSTR a_ObjectPath , long a_Flags , IWbemContext *a_Context , IWbemObjectSink *a_Sink ) ; HRESULT STDMETHODCALLTYPE PutClass ( IWbemClassObject *a_Object , long a_Flags , IWbemContext *a_Context , IWbemCallResult **a_CallResult ) ; HRESULT STDMETHODCALLTYPE PutClassAsync ( IWbemClassObject *a_Object , long a_Flags , IWbemContext *a_Context , IWbemObjectSink *a_Sink ) ; HRESULT STDMETHODCALLTYPE DeleteClass ( const BSTR a_Class , long a_Flags , IWbemContext *a_Context , IWbemCallResult **a_CallResult ) ; HRESULT STDMETHODCALLTYPE DeleteClassAsync ( const BSTR a_Class , long a_Flags , IWbemContext *a_Context , IWbemObjectSink *a_Sink ) ; HRESULT STDMETHODCALLTYPE CreateClassEnum ( const BSTR a_Superclass , long a_Flags , IWbemContext *a_Context , IEnumWbemClassObject **a_Enum ) ; HRESULT STDMETHODCALLTYPE CreateClassEnumAsync ( const BSTR a_Superclass , long a_Flags , IWbemContext *a_Context , IWbemObjectSink *a_Sink ) ; HRESULT STDMETHODCALLTYPE PutInstance ( IWbemClassObject *a_Instance , long a_Flags , IWbemContext *a_Context , IWbemCallResult **a_CallResult ) ; HRESULT STDMETHODCALLTYPE PutInstanceAsync ( IWbemClassObject *a_Instance , long a_Flags , IWbemContext *a_Context , IWbemObjectSink *a_Sink ) ; HRESULT STDMETHODCALLTYPE DeleteInstance ( const BSTR a_ObjectPath , long a_Flags , IWbemContext *a_Context , IWbemCallResult **a_CallResult ) ; HRESULT STDMETHODCALLTYPE DeleteInstanceAsync ( const BSTR a_ObjectPath, long a_Flags, IWbemContext *a_Context , IWbemObjectSink *a_Sink ) ; HRESULT STDMETHODCALLTYPE CreateInstanceEnum ( const BSTR a_Class , long a_Flags , IWbemContext *a_Context , IEnumWbemClassObject **a_Enum ) ; HRESULT STDMETHODCALLTYPE CreateInstanceEnumAsync ( const BSTR a_Class , long a_Flags , IWbemContext *a_Context , IWbemObjectSink *a_Sink ) ; HRESULT STDMETHODCALLTYPE ExecQuery ( const BSTR a_QueryLanguage, const BSTR a_Query, long a_Flags , IWbemContext *a_Context , IEnumWbemClassObject **a_Enum ) ; HRESULT STDMETHODCALLTYPE ExecQueryAsync ( const BSTR a_QueryLanguage , const BSTR a_Query , long a_Flags , IWbemContext *a_Context , IWbemObjectSink *a_Sink ) ; HRESULT STDMETHODCALLTYPE ExecNotificationQuery ( const BSTR a_QueryLanguage , const BSTR a_Query , long a_Flags , IWbemContext *a_Context , IEnumWbemClassObject **a_Enum ) ; HRESULT STDMETHODCALLTYPE ExecNotificationQueryAsync ( const BSTR a_QueryLanguage , const BSTR a_Query , long a_Flags , IWbemContext *a_Context , IWbemObjectSink *a_Sink ) ; HRESULT STDMETHODCALLTYPE ExecMethod ( const BSTR a_ObjectPath , const BSTR a_MethodName , long a_Flags , IWbemContext *a_Context , IWbemClassObject *a_InParams , IWbemClassObject **a_OutParams , IWbemCallResult **a_CallResult ) ; HRESULT STDMETHODCALLTYPE ExecMethodAsync ( const BSTR a_ObjectPath , const BSTR a_MethodName , long a_Flags , IWbemContext *a_Context , IWbemClassObject *a_InParams , IWbemObjectSink *a_Sink ) ; HRESULT STDMETHODCALLTYPE GetProperty ( long a_Flags , const BSTR a_Locale , const BSTR a_ClassMapping , const BSTR a_InstanceMapping , const BSTR a_PropertyMapping , VARIANT *a_Value ) ; HRESULT STDMETHODCALLTYPE PutProperty ( long a_Flags , const BSTR a_Locale , const BSTR a_ClassMapping , const BSTR a_InstanceMapping , const BSTR a_PropertyMapping , const VARIANT *a_Value ) ; /* IWbemProviderInit methods */ HRESULT STDMETHODCALLTYPE Initialize ( LPWSTR a_User , LONG a_Flags , LPWSTR a_Namespace , LPWSTR a_Locale , IWbemServices *a_Core , IWbemContext *a_Context , IWbemProviderInitSink *a_Sink ) ; // IWmi_UnInitialize members HRESULT STDMETHODCALLTYPE Shutdown ( LONG a_Flags , ULONG a_MaxMilliSeconds , IWbemContext *a_Context ) ; } ; #endif // _Provider_IWbemServices_H
[ "support@cryptoalgo.cf" ]
support@cryptoalgo.cf
b963eabb1bed25fe773e8eb9ecacd0555fd36bf7
a5f35d0dfaddb561d3595c534b6b47f304dbb63d
/Source/BansheeEngine/Resources/BsGameResourceManager.h
3474ad3fdd65784076aadf55ece026e62a8a0934
[]
no_license
danielkrupinski/BansheeEngine
3ff835e59c909853684d4985bd21bcfa2ac86f75
ae820eb3c37b75f2998ddeaf7b35837ceb1bbc5e
refs/heads/master
2021-05-12T08:30:30.564763
2018-01-27T12:55:25
2018-01-27T12:55:25
117,285,819
1
0
null
2018-01-12T20:38:41
2018-01-12T20:38:41
null
UTF-8
C++
false
false
3,771
h
//********************************** Banshee Engine (www.banshee3d.com) **************************************************// //**************** Copyright (c) 2016 Marko Pintera (marko.pintera@gmail.com). All rights reserved. **********************// #pragma once #include "BsPrerequisites.h" #include "Utility/BsModule.h" namespace bs { /** @addtogroup Resources-Engine-Internal * @{ */ /** * Provides a way to map one resource path to another path. Useful if the resources are being referenced using a path * that is not the path to their physical location. */ class BS_EXPORT ResourceMapping : public IReflectable { public: /** Returns the resource path map. */ const UnorderedMap<Path, Path>& getMap() const { return mMapping; } /** Adds a new entry to the resource map. Translated from path @p from to path @p to. */ void add(const Path& from, const Path& to); /** Creates a new empty resource mapping. */ static SPtr<ResourceMapping> create(); private: UnorderedMap<Path, Path> mMapping; /************************************************************************/ /* RTTI */ /************************************************************************/ public: friend class ResourceMappingRTTI; static RTTITypeBase* getRTTIStatic(); RTTITypeBase* getRTTI() const override; }; /** Interface that can be implemented by the resource loaders required by GameResourceManager. */ class BS_EXPORT IGameResourceLoader { public: virtual ~IGameResourceLoader() { } /** Loads the resource at the specified path. */ virtual HResource load(const Path& path, bool keepLoaded) const = 0; /** @copydoc GameResourceManager::setMapping */ virtual void setMapping(const SPtr<ResourceMapping>& mapping) { } }; /** Handles loading of game resources when the standalone game is running. */ class BS_EXPORT StandaloneResourceLoader : public IGameResourceLoader { public: /** @copydoc IGameResourceLoader::load */ HResource load(const Path& path, bool keepLoaded) const override; /** @copydoc IGameResourceLoader::setMapping */ void setMapping(const SPtr<ResourceMapping>& mapping) override; private: UnorderedMap<Path, Path> mMapping; }; /** * Keeps track of resources that can be dynamically loaded during runtime. These resources will be packed with the game * build so that they're available on demand. * * Internal resource handle can be overridden so that editor or other systems can handle resource loading more directly. */ class BS_EXPORT GameResourceManager : public Module<GameResourceManager> { public: GameResourceManager(); /** * Loads the resource at the specified path. * * @see Resources::load */ HResource load(const Path& path, bool keepLoaded) const; /** @copydoc load */ template <class T> ResourceHandle<T> load(const Path& filePath, bool keepLoaded) { return static_resource_cast<T>(load(filePath, keepLoaded)); } /** * Sets an optional mapping that be applied to any path provided to load(). This allows you to reference files * using different names and/or folder structure than they are actually in. * * For example normally in script code you would reference resources based on their path relative to the project * resoruces folder, but in standalone there is no such folder and we need to map the values. * * Provided paths should be relative to the working directory. */ void setMapping(const SPtr<ResourceMapping>& mapping); /** Sets the resource loader implementation that determines how are the paths provided to load() loaded. */ void setLoader(const SPtr<IGameResourceLoader>& loader); private: SPtr<IGameResourceLoader> mLoader; }; /** @} */ }
[ "bearishsun@gmail.com" ]
bearishsun@gmail.com
1e1b726a09369b5ed8295892480b79927d4a4e2a
59b3fe0a05342c83be8cbb32151f02ae456d7827
/P2PClient.cpp
59175ac57618bc6793ceaaa1819f5136cf0c04f0
[]
no_license
alexliyu7352/P2PCommunication
05884fbe59fba183e9b14b94ae57d41ba52cda41
26fc1a0b672377a47cf719eb4b4b04e5914f92a3
refs/heads/master
2022-04-08T12:31:06.051625
2020-03-29T10:28:27
2020-03-29T10:28:27
null
0
0
null
null
null
null
UTF-8
C++
false
false
12,631
cpp
#include <unistd.h> #include <string.h> #include <string> #include <vector> #include <pthread.h> #include "Socket.h" #include "common.h" using namespace std; #define BUFLEN_MAX 10000 #define MENU_BUFLEN 10 #define CMD_BUFLEN 30 #define NAMELEN_MAX 50 #define MAX_WAIT_COUNT 4 #define DEFAULT_RECV_TIME 5 #define THREAD_SLEEP_TIME_MS 20 enum INTERACT { INTERACT_MAIN_MENU, INTERACT_ROOM_MENU, }; char *arrInteract[] = { " [1] Join the room\n\ [2] Exit\n", " [1] List all users.\n\ [2] Select one to chat.\n\ [3] Exit room." }; enum CLIENT_STATUS { STATUS_INIT, STATUS_EXIT, STATUS_JOIN_ROOM, STATUS_EXIT_ROOM, STATUS_CHATTING, }; enum NAT_TYPE { NAT_CONE, // 锥形NAT NAT_SYMMETRY, // 对称NAT }; static void *RoomListenThread(void *arg); class CP2PClient { public: CP2PClient(char *userName, char *serverIP, char *serverPort) :m_objSocket(SOCK_DGRAM, AF_INET, DEFAULT_RECV_TIME), m_userName(userName), m_serverIP(serverIP), m_serverPort(serverPort), m_clientStatus(STATUS_INIT), m_natType(NAT_CONE) { pthread_mutex_init(&m_threadLock,NULL); pthread_mutex_init(&m_scanfLock,NULL); } virtual ~CP2PClient() { pthread_mutex_destroy(&m_threadLock); pthread_mutex_destroy(&m_scanfLock); } int ReadAndSend() { char buf[BUFLEN_MAX] = {0}; while(1) { printf("please input content (\"quit\" to exit): \n"); scanf("%s", buf); printf("\n"); if (strcmp(buf, "quit") == 0) break; m_objSocket.SendTo(buf, BUFLEN_MAX, m_serverIP, m_serverPort); usleep(300); } } int BeginChat() { char key[MENU_BUFLEN] = {0}; while(1) { printf("%s\n", arrInteract[INTERACT_MAIN_MENU]); scanf("%s", key); __ParseMainMenu(key); if (STATUS_EXIT == m_clientStatus) break; memset(key, 0, MENU_BUFLEN); usleep(300); } return 0; } void UpdateNatType(char *server1, char *port1, char *server2, char *port2) { int status = 0; char recvBuf1[BUFLEN_MAX] = {0}; char recvBuf2[BUFLEN_MAX] = {0}; printf("arrCmd[CMD_QUERY_SELF_ADDR] = %s, size = %d\n", arrCmd[CMD_QUERY_SELF_ADDR], strlen(arrCmd[CMD_QUERY_SELF_ADDR])); status = m_objSocket.SendTo(arrCmd[CMD_QUERY_SELF_ADDR], strlen(arrCmd[CMD_QUERY_SELF_ADDR]), server1, atoi(port1)); status |= m_objSocket.RecvFrom(recvBuf1, BUFLEN_MAX, NULL); status |= m_objSocket.SendTo(arrCmd[CMD_QUERY_SELF_ADDR], strlen(arrCmd[CMD_QUERY_SELF_ADDR]), server2, atoi(port2)); status |= m_objSocket.RecvFrom(recvBuf2, BUFLEN_MAX, NULL); if (SOCK_SUCCESS != status) return; LOG("recvBuf1 = %s\n recvBuf2 = %s\n", recvBuf1, recvBuf2); if (strstr(recvBuf1, arrCmd[CMD_QUERY_SELF_ADDR+1]) != NULL && strstr(recvBuf2, arrCmd[CMD_QUERY_SELF_ADDR+1]) != NULL && strcmp(recvBuf1, recvBuf2) != 0) { LOG("change m_natType to NAT_SYMMETRY\n"); m_natType = NAT_SYMMETRY; } } void __ParseRoomerInfo(char *info) { m_vecUserList.clear(); string strInfo(info); vector<string> vecUserInfo; string::size_type position; int pos_begin = 0; while((position = strInfo.find("\n", position)) != string::npos) { vecUserInfo.push_back(string(strInfo, pos_begin, position - pos_begin)); position++; pos_begin = position; } string::size_type position1 = 0; string::size_type position2 = 0; position = 0; for(int i = 0; i < vecUserInfo.size(); i++) { printf("vecUserInfo: %s\n", vecUserInfo[i].c_str()); position1 = vecUserInfo[i].find(",", 0); position2 = vecUserInfo[i].find(",", position1 + 1); position = vecUserInfo[i].find("name: ", 0); string name(vecUserInfo[i], position+strlen("name: "), position1-position-strlen("name: ")); position = vecUserInfo[i].find("ip: ", 0); string ip(vecUserInfo[i], position+strlen("ip: "), position2-position-strlen("ip: ")); position = vecUserInfo[i].find("port: ", 0); int port = atoi(string(vecUserInfo[i], position+strlen("port: ")).c_str()); //printf("vec: name:%s; ip:%s; port:%d;\n", name.c_str(), ip.c_str(), port); m_vecUserList.push_back(CUser(name, ip, port)); } } // if no data, please input NULL int __SendCommand(COMMAND_TYPE cmd, const char *sendData, char *recvData) { char buf[BUFLEN_MAX] = {0}; string strCMD = string(arrCmd[cmd]); if (NULL != sendData) strCMD += string(sendData); pthread_mutex_lock(&m_threadLock); LOG("__SendCommand buf : %s\n", strCMD.c_str()); m_objSocket.SendTo(strCMD.c_str(), strCMD.size(), m_serverIP, m_serverPort); struct sockaddr_in addr; int status = m_objSocket.RecvFrom(buf, BUFLEN_MAX, (struct sockaddr *)&addr); pthread_mutex_unlock(&m_threadLock); if (SOCK_SUCCESS != status) { LOG("recv ACK failed!\n"); return -1; } if (strstr(buf, arrCmd[cmd+1]) != NULL) { printf("%s execute success!\n", arrCmd[cmd]); if (NULL != recvData && strlen(buf) != strlen(arrCmd[cmd+1])) strcpy(recvData, buf+strlen(arrCmd[cmd+1])); return 0; } else { printf("cmd recv = %s\n", buf); printf("%s execute failed!\n", arrCmd[cmd]); return -1; } } private: void __StepIntoChat() { m_clientStatus = STATUS_JOIN_ROOM; char key[MENU_BUFLEN] = {0}; while(1) { pthread_mutex_lock(&m_scanfLock); printf("%s\n", arrInteract[INTERACT_ROOM_MENU]); scanf("%s", key); if (m_clientStatus != STATUS_CHATTING) __ParseRoomMenu(key); memset(key, 0, MENU_BUFLEN); if (m_clientStatus == STATUS_EXIT_ROOM) break; pthread_mutex_unlock(&m_scanfLock); usleep(300); } } void __ParseMainMenu(char *key) { int nKey = atoi(key); int status; int tStatus; switch(nKey) { case 1: status = __SendCommand(CMD_JOIN, m_userName, NULL); if(status == 0) { if ((tStatus = pthread_create(&m_listenThread, NULL, RoomListenThread, this)) != 0) { printf("pthread_create failed, erroNum = %d\n", tStatus); printf("Join the room failed!\n"); break; } __StepIntoChat(); } break; case 2: m_clientStatus = STATUS_EXIT; break; default: break; } } void __ParseRoomMenu(char *key) { int nKey = atoi(key); int status; char recvData[BUFLEN_MAX] = {0}; char frientName[NAMELEN_MAX] = {0}; vector<CUser>::iterator iter; switch(nKey) { case 1: status = __SendCommand(CMD_LIST_USERS, NULL, recvData); if(status == 0) printf("%s\n", recvData); break; case 2: { status = __SendCommand(CMD_LIST_USERS, NULL, recvData); __ParseRoomerInfo(recvData); memset(recvData, 0, BUFLEN_MAX); printf("please input the name to chat: \n"); scanf("%s", frientName); for (iter = m_vecUserList.begin(); iter != m_vecUserList.end(); iter++) { if (iter->strUserName.find(frientName) != string::npos) { break; } } if (iter == m_vecUserList.end()) break; string strChat = string(m_userName)+string("+")+string(frientName); status = __SendCommand(CMD_BEGIN_CHAT, strChat.c_str(), recvData); string strData(m_userName); strData += string(" trying connecting..."); printf("SendTo ip->%s, port->%d, Data: %s\n", iter->strUserIP.c_str(), iter->nUserPort, strData.c_str()); m_objSocket.SendTo(strData.c_str(), strData.size(), iter->strUserIP.c_str(), iter->nUserPort); int nCount = 0; char charAckBuf[CMD_BUFLEN] = {0}; struct sockaddr_in apply_addr; do { status = m_objSocket.RecvFrom(charAckBuf, CMD_BUFLEN, (struct sockaddr *)&apply_addr); nCount++; } while (status != 0 && nCount < MAX_WAIT_COUNT); if (nCount != MAX_WAIT_COUNT) printf("chat apply ack buf: %s, ip->%s, port->%d\n", charAckBuf, inet_ntoa(apply_addr.sin_addr), ntohs(apply_addr.sin_port)); if (nCount != MAX_WAIT_COUNT && strcmp(inet_ntoa(apply_addr.sin_addr), iter->strUserIP.c_str()) == 0 && ntohs(apply_addr.sin_port) == iter->nUserPort && strcmp(charAckBuf, arrCmd[CMD_CHAT_AGREE]) == 0) { printf("applyer agree chat!\n"); } } break; case 3: status = __SendCommand(CMD_EXIT_ROOM, m_userName, NULL); m_clientStatus = STATUS_EXIT_ROOM; pthread_mutex_unlock(&m_scanfLock); pthread_join(m_listenThread, NULL); break; default: break; } } private: char *m_userName; char *m_serverIP; char *m_serverPort; pthread_t m_listenThread; public: CSocket m_objSocket; int m_clientStatus; pthread_mutex_t m_threadLock; pthread_mutex_t m_scanfLock; vector<CUser> m_vecUserList; int m_natType; }; static void *RoomListenThread(void *arg) { CP2PClient *client = (CP2PClient *)arg; char recvBuf[BUFLEN_MAX] = {0}; char cmdData[NAMELEN_MAX] = {0}; char scanfBuf[CMD_BUFLEN] = {0}; struct sockaddr_in addr; int status = 0; while(client->m_clientStatus != STATUS_EXIT_ROOM) { memset(recvBuf, 0, BUFLEN_MAX); memset(cmdData, 0, NAMELEN_MAX); pthread_mutex_lock(&client->m_threadLock); client->m_objSocket.SetTimeOut(0, 1000 * THREAD_SLEEP_TIME_MS); status = client->m_objSocket.RecvFrom(recvBuf, BUFLEN_MAX, (struct sockaddr *)&addr); if (status != SOCK_SUCCESS) { //printf("RoomListenThread: m_objSocket.RecvFrom ----- 0 \n"); client->m_objSocket.SetTimeOut(DEFAULT_RECV_TIME, 0); pthread_mutex_unlock(&client->m_threadLock); usleep(1000 * THREAD_SLEEP_TIME_MS); continue; } printf("RoomListenThread buf: %s\n", recvBuf); int cmd = ParseCmd(recvBuf, cmdData); if (cmd < 0) { client->m_objSocket.SetTimeOut(DEFAULT_RECV_TIME, 0); pthread_mutex_unlock(&client->m_threadLock); LOG("ParseCmd failed!\n"); continue; } switch (client->m_clientStatus) { case STATUS_JOIN_ROOM: if (cmd == CMD_BEGIN_CHAT) { client->m_clientStatus = STATUS_CHATTING; //pthread_mutex_lock(&client->m_scanfLock); if (client->m_clientStatus == STATUS_EXIT_ROOM) break; printf("%s apply for chatting, (y/n):\n", cmdData); //scanf("%s", scanfBuf); //if (strstr(scanfBuf, "y") != NULL) { printf("RoomListenThread -------------------- 0\n"); pthread_mutex_unlock(&client->m_threadLock); char recvData[BUFLEN_MAX] = {0}; if(client->__SendCommand(CMD_LIST_USERS, NULL, recvData) == 0) client->__ParseRoomerInfo(recvData); pthread_mutex_lock(&client->m_threadLock); printf("RoomListenThread -------------------- 2\n"); vector<CUser>::iterator iter; int status = 0, nCount = 0; char chatAckBuf[CMD_BUFLEN] = {0}; struct sockaddr_in apply_addr; printf("RoomListenThread -------------------- 3\n"); for (iter = client->m_vecUserList.begin(); iter != client->m_vecUserList.end(); iter++) { if (iter->strUserName.find(cmdData) != string::npos) if (strcmp(iter->strUserName.c_str(), cmdData) == 0) { printf("send agree chat buf: %s, ip->%s, port->%d\n", arrCmd[CMD_CHAT_AGREE], iter->strUserIP.c_str(), iter->nUserPort); client->m_objSocket.SendTo(arrCmd[CMD_CHAT_AGREE], sizeof(arrCmd[CMD_CHAT_AGREE]), iter->strUserIP.c_str(), iter->nUserPort); client->m_objSocket.SendTo(arrCmd[CMD_CHAT_AGREE], sizeof(arrCmd[CMD_CHAT_AGREE]), iter->strUserIP.c_str(), iter->nUserPort); client->m_objSocket.SendTo(arrCmd[CMD_CHAT_AGREE], sizeof(arrCmd[CMD_CHAT_AGREE]), iter->strUserIP.c_str(), iter->nUserPort); do { status = client->m_objSocket.RecvFrom(chatAckBuf, CMD_BUFLEN, (struct sockaddr *)&apply_addr); nCount++; } while (status != 0 && nCount < MAX_WAIT_COUNT); } } printf("RoomListenThread -------------------- 4 nCount = %d\n", MAX_WAIT_COUNT); if (iter != client->m_vecUserList.end() && nCount != MAX_WAIT_COUNT && strcmp(inet_ntoa(apply_addr.sin_addr), iter->strUserIP.c_str()) == 0 && ntohs(apply_addr.sin_port) == iter->nUserPort && strcmp(chatAckBuf, arrCmd[CMD_CHAT_AGREE_ACK]) == 0) { printf("recver agree chat!\n", iter->strUserName.c_str()); } printf("RoomListenThread -------------------- 5\n"); } //pthread_mutex_unlock(&client->m_scanfLock); } break; case STATUS_CHATTING: break; } client->m_clientStatus = STATUS_JOIN_ROOM; client->m_objSocket.SetTimeOut(DEFAULT_RECV_TIME, 0); pthread_mutex_unlock(&client->m_threadLock); usleep(1000 * THREAD_SLEEP_TIME_MS); } } int main(int argc, char* argv[]) { if (argc < 4) { LOG("Usage: ./P2PClient UserName IP Port\n"); return 0; } CP2PClient client(argv[1], argv[2], argv[3]); if (argc > 5) client.UpdateNatType(argv[2], argv[3], argv[4], argv[5]); //client.ReadAndSend(); client.BeginChat(); printf("Exit the client!\n"); return 0; }
[ "zhaosj_1991@163.com" ]
zhaosj_1991@163.com
d0dfecc37a434efde45d587d09ddd0314cf9a906
4f3b56d95d53bfbd4dac935173f5eb3fedf48649
/apps/photobox/photobox/src/ofApp.cpp
df7dd04b7a4b68025650b087aa63e2a103bdc57c
[]
no_license
brinoausrino/of_piApps
b0a50a8d13aeba301d94e26a187c3e92daa0d351
75c8c89acf6ee644d198bac55fb5f6a21df1f607
refs/heads/master
2021-03-13T00:06:54.844033
2015-07-14T15:30:53
2015-07-14T15:30:53
39,026,156
0
0
null
null
null
null
UTF-8
C++
false
false
6,706
cpp
#include "ofApp.h" //-------------------------------------------------------------- void ofApp::setup(){ ofxXmlSettings XML; if( XML.loadFile("mySettings.xml") ){ cout << "mySettings.xml loaded!" << endl; }else{ cout << "unable to load mySettings.xml check data/ folder" << endl; } _delay = XML.getValue("SETTINGS:IMAGEDELAY", 200); _frequency = XML.getValue("SETTINGS:FREQUENCY", 200); _captureTime = ("SETTINGS:CAPTURETIME", 2000); _resX = ("SETTINGS:RESX", 320); _resY = ("SETTINGS:RESY", 240); _imageDir = XML.getValue("SETTINGS:IMAGEDIR", "images0000"); //setup directory ofDirectory dir; if (!dir.doesDirectoryExist(_imageDir)) { dir.createDirectory(_imageDir); } _hasPictures = false; setupCamera(); setupProjector(); setupCaptureProcessor(); //camera stuff _isDrawingCamera = false; if (_dir.listDir(_imageDir) >0) { _hasPictures = true; } } //-------------------------------------------------------------- void ofApp::update(){ updateCamera(); if (!_isDrawingCamera) { updateProjector(); } updateCaptureProcessor(); } //-------------------------------------------------------------- void ofApp::draw(){ if (_isDrawingCamera && _hasPictures) { ofSetColor(255, 255, 255); _colorImageCam.draw(0,0,ofGetWindowWidth(),ofGetWindowHeight()); } else if (_hasPictures) { ofSetColor(255, 255, 255); _projectorImage.draw(0,0,ofGetWindowWidth(),ofGetWindowHeight()); } } //-------------------------------------------------------------- void ofApp::keyPressed(int key){ switch (key){ case ' ': shot(); break; case 'c': if (_isDrawingCamera) _isDrawingCamera = false; else _isDrawingCamera = true; break; case 'd': _nSeq = _dir.listDir(_imageDir); break; } } //-------------------------------------------------------------- void ofApp::keyReleased(int key){ } //-------------------------------------------------------------- void ofApp::mouseMoved(int x, int y ){ } //-------------------------------------------------------------- void ofApp::mouseDragged(int x, int y, int button){ } //-------------------------------------------------------------- void ofApp::mousePressed(int x, int y, int button){ if(!_isShooting && button == 0) shot(); else if (button == 1 || button == 2) changeImageDir(); } //-------------------------------------------------------------- void ofApp::mouseReleased(int x, int y, int button){ } //-------------------------------------------------------------- void ofApp::windowResized(int w, int h){ } //-------------------------------------------------------------- void ofApp::gotMessage(ofMessage msg){ } //-------------------------------------------------------------- void ofApp::dragEvent(ofDragInfo dragInfo){ } void ofApp::shot() { initCaptureProcessor(); cout<< "init capture " <<endl; } void ofApp::setupCamera(){ _vidGrabber.listDevices(); _vidGrabber.setVerbose(true); _vidGrabber.initGrabber(_resX,_resY); _colorImageCam.allocate(_resX,_resY); } void ofApp::updateCamera(){ _vidGrabber.update(); if (_vidGrabber.isFrameNew()){ _colorImageCam.setFromPixels(_vidGrabber.getPixels(), _resX,_resY); } } void ofApp::setupProjector(){ _nSeq = 0; _nPic = 0; _stepSeq = 0; _stepPic = 0; _lastPlayed = ofGetElapsedTimeMillis(); _image.allocate(_resX,_resY, OF_IMAGE_COLOR); _cvImage.allocate(_resX, _resY); _projectorImage.allocate(_resX, _resY); } void ofApp::updateProjector(){ if (_hasPictures) { if(ofGetElapsedTimeMillis() - _lastPlayed > _delay) { _nSeq = _dir.listDir(_imageDir); if (_stepPic >= _nPic) { _stepSeq++; if (_stepSeq < _nSeq) { _stepPic = 0; _file = _imageDir + "/"; _file += ofToString(_stepSeq); _nPic = _dir.listDir(_file); } else { _stepSeq = 0; _stepPic = 0; _file = _imageDir + "/"; _file += ofToString(_stepSeq); _nPic = _dir.listDir(_file); } } _file = _imageDir + "/"; _file += ofToString(_stepSeq); _file += "/"; _file += ofToString(_stepPic); _file += ".jpg"; _image.loadImage(_file); _stepPic++; _lastPlayed = ofGetElapsedTimeMillis(); } _cvImage.setFromPixels(_image.getPixels(), _image.getWidth(), _image.getHeight()); _projectorImage = _cvImage; } } void ofApp::setupCaptureProcessor(){ _lastShot = 0; _isShooting = false; _startTime = 0; _image.allocate(_resX,_resY, OF_IMAGE_COLOR); } void ofApp::initCaptureProcessor(){ ofDirectory dir; _nSeqCap = dir.listDir(_imageDir + "/"); _nPicCap = 0; string nameDir = _imageDir + "/"; nameDir += ofToString(_nSeqCap); ofDirectory::createDirectory(nameDir); _isShooting = true; _startTime = ofGetElapsedTimeMillis(); //cout<< "init capture started" <<endl; } void ofApp::updateCaptureProcessor(){ //check if to stop if (_isShooting) { //check is to stop if (ofGetElapsedTimeMillis() - _startTime > _captureTime) { _isShooting = false; } else { //check if new photo if (ofGetElapsedTimeMillis() - _lastShot > _frequency) { saveCaptureProcessor(); if (!_hasPictures) { _hasPictures = true; } } } } } void ofApp::saveCaptureProcessor(){ string file = ofToDataPath(_imageDir + "/", true); file.append(ofToString(_nSeqCap)); file.append("/"); file.append(ofToString(_nPicCap)); file.append(".jpg"); //_image.setFromPixels(_inputDevice->getColorImage()->getPixelsRef()); _image.setFromPixels(_colorImageCam.getPixelsRef()); _image.saveImage(file); //cout<< "pic saved " << file <<endl; _lastShot = ofGetElapsedTimeMillis(); ++_nPicCap; } void ofApp::changeImageDir(){ int n = ofToInt(_imageDir.substr(6,9)); _imageDir = "images" + ofToString(n+1); _hasPictures = false; ofxXmlSettings XML; if( XML.loadFile("mySettings.xml") ){ cout << "mySettings.xml loaded!" << endl; }else{ cout << "unable to load mySettings.xml check data/ folder" << endl; } XML.setValue("SETTINGS:IMAGEDIR", _imageDir); XML.save("mySettings.xml"); }
[ "hi@brinoausrino.com" ]
hi@brinoausrino.com
4d89c73de6a2beb642d5cff7524a711c7793ca02
3faf84b52c9dac137aa8e72c4a42dfd79c9f8e97
/examples/CBuildr3/TxtEdit2.h
f2c4b4b51adbcab22b8f997eb4ad4047a4f27824
[]
no_license
lynxnake/TurboPower-Orpheus
e3d9b7c03d946ea0d7c6c663d8cf3649e1deb48a
18748d4a79a0a82503796d40a019e243704e866e
refs/heads/master
2021-07-14T07:26:01.044028
2019-01-11T12:35:45
2019-01-11T12:35:45
144,685,117
4
4
null
2020-05-20T19:01:57
2018-08-14T07:33:47
Pascal
UTF-8
C++
false
false
969
h
//--------------------------------------------------------------------------- #ifndef TxtEdit2H #define TxtEdit2H //--------------------------------------------------------------------------- #include <vcl\Classes.hpp> #include <vcl\Controls.hpp> #include <vcl\StdCtrls.hpp> #include <vcl\Forms.hpp> #include <vcl\Buttons.hpp> //--------------------------------------------------------------------------- class TEditAbout : public TForm { __published: // IDE-managed Components TLabel *Label1; TLabel *Label2; TLabel *Label3; TLabel *Label4; TLabel *Label5; TButton *Button1; void __fastcall Button1Click(TObject *Sender); private: // User declarations public: // User declarations __fastcall TEditAbout(TComponent* Owner); }; //--------------------------------------------------------------------------- extern TEditAbout *EditAbout; //--------------------------------------------------------------------------- #endif
[ "romankassebaum@fbd941df-1b1f-4d16-88fd-9a14aed2154d" ]
romankassebaum@fbd941df-1b1f-4d16-88fd-9a14aed2154d
b255cc6e0e32b22b62b02d6571e465c02754a2ee
043eb9b100070cef1a522ffea1c48f8f8d969ac7
/ios_proj/wwj/Classes/Native/AssemblyU2DCSharp_Req_GetPrizeUserLists_Response_I2653692112.h
67d81b7a2b0f7a2a3ac6bd9fe499cfa1efa3c6f5
[]
no_license
spidermandl/wawaji
658076fcac0c0f5975eb332a52310a61a5396c25
209ef57c14f7ddd1b8309fc808501729dda58071
refs/heads/master
2021-01-18T16:38:07.528225
2017-10-19T09:57:00
2017-10-19T09:57:00
100,465,677
1
2
null
null
null
null
UTF-8
C++
false
false
3,774
h
#pragma once #include "il2cpp-config.h" #ifndef _MSC_VER # include <alloca.h> #else # include <malloc.h> #endif #include <stdint.h> #include "mscorlib_System_Object2689449295.h" // System.String struct String_t; #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // Req_GetPrizeUserLists/Response/Info struct Info_t2653692112 : public Il2CppObject { public: // System.String Req_GetPrizeUserLists/Response/Info::user_id String_t* ___user_id_0; // System.String Req_GetPrizeUserLists/Response/Info::pic String_t* ___pic_1; // System.String Req_GetPrizeUserLists/Response/Info::phone String_t* ___phone_2; // System.String Req_GetPrizeUserLists/Response/Info::type String_t* ___type_3; // System.String Req_GetPrizeUserLists/Response/Info::user_name String_t* ___user_name_4; // System.String Req_GetPrizeUserLists/Response/Info::prize_id String_t* ___prize_id_5; // System.String Req_GetPrizeUserLists/Response/Info::name String_t* ___name_6; public: inline static int32_t get_offset_of_user_id_0() { return static_cast<int32_t>(offsetof(Info_t2653692112, ___user_id_0)); } inline String_t* get_user_id_0() const { return ___user_id_0; } inline String_t** get_address_of_user_id_0() { return &___user_id_0; } inline void set_user_id_0(String_t* value) { ___user_id_0 = value; Il2CppCodeGenWriteBarrier(&___user_id_0, value); } inline static int32_t get_offset_of_pic_1() { return static_cast<int32_t>(offsetof(Info_t2653692112, ___pic_1)); } inline String_t* get_pic_1() const { return ___pic_1; } inline String_t** get_address_of_pic_1() { return &___pic_1; } inline void set_pic_1(String_t* value) { ___pic_1 = value; Il2CppCodeGenWriteBarrier(&___pic_1, value); } inline static int32_t get_offset_of_phone_2() { return static_cast<int32_t>(offsetof(Info_t2653692112, ___phone_2)); } inline String_t* get_phone_2() const { return ___phone_2; } inline String_t** get_address_of_phone_2() { return &___phone_2; } inline void set_phone_2(String_t* value) { ___phone_2 = value; Il2CppCodeGenWriteBarrier(&___phone_2, value); } inline static int32_t get_offset_of_type_3() { return static_cast<int32_t>(offsetof(Info_t2653692112, ___type_3)); } inline String_t* get_type_3() const { return ___type_3; } inline String_t** get_address_of_type_3() { return &___type_3; } inline void set_type_3(String_t* value) { ___type_3 = value; Il2CppCodeGenWriteBarrier(&___type_3, value); } inline static int32_t get_offset_of_user_name_4() { return static_cast<int32_t>(offsetof(Info_t2653692112, ___user_name_4)); } inline String_t* get_user_name_4() const { return ___user_name_4; } inline String_t** get_address_of_user_name_4() { return &___user_name_4; } inline void set_user_name_4(String_t* value) { ___user_name_4 = value; Il2CppCodeGenWriteBarrier(&___user_name_4, value); } inline static int32_t get_offset_of_prize_id_5() { return static_cast<int32_t>(offsetof(Info_t2653692112, ___prize_id_5)); } inline String_t* get_prize_id_5() const { return ___prize_id_5; } inline String_t** get_address_of_prize_id_5() { return &___prize_id_5; } inline void set_prize_id_5(String_t* value) { ___prize_id_5 = value; Il2CppCodeGenWriteBarrier(&___prize_id_5, value); } inline static int32_t get_offset_of_name_6() { return static_cast<int32_t>(offsetof(Info_t2653692112, ___name_6)); } inline String_t* get_name_6() const { return ___name_6; } inline String_t** get_address_of_name_6() { return &___name_6; } inline void set_name_6(String_t* value) { ___name_6 = value; Il2CppCodeGenWriteBarrier(&___name_6, value); } }; #ifdef __clang__ #pragma clang diagnostic pop #endif
[ "Desmond@Desmonds-MacBook-Pro.local" ]
Desmond@Desmonds-MacBook-Pro.local
03fdc360d6c685fe127ab6fe2769e1c171117bd1
6bbcdfcd6cbdcaab3a3e65fddb1724691070b8fd
/Source/CoopGame/Private/SWeapon.cpp
f598372ebd03350ed4ed3b2e2f33d92d5e6b5c08
[]
no_license
osssx/CoopGame
9af235dddb4a31134824b33fd3e72e6c729463ae
9bf8f03baee6a6a178233eba4082e20f677004a2
refs/heads/master
2020-03-23T02:57:11.802799
2018-08-02T04:15:59
2018-08-02T04:15:59
141,001,360
0
0
null
null
null
null
UTF-8
C++
false
false
4,766
cpp
// Fill out your copyright notice in the Description page of Project Settings. #include "SWeapon.h" #include "DrawDebugHelpers.h" #include "Kismet/GameplayStatics.h" #include "Components/SkeletalMeshComponent.h" #include "Particles/ParticleSystemComponent.h" #include "CoopGame.h" #include "PhysicalMaterials/PhysicalMaterial.h" #include "UnrealNetwork.h" static int32 DebugWeaponDrawing = 0; FAutoConsoleVariableRef CVARDebugWeaponDrawing( TEXT("COOP.DebugWeapons"), DebugWeaponDrawing, TEXT("Draw Debug Lines for Weapons"), ECVF_Cheat); // Sets default values ASWeapon::ASWeapon() { MeshComp = CreateDefaultSubobject<USkeletalMeshComponent>(TEXT("MeshComp")); RootComponent = MeshComp; MuzzleSocketName = "MuzzleSocket"; TracerTagetName = "Target"; BaseDamage = 20.f; FireRate = 600; SetReplicates(true); NetUpdateFrequency = 66.f; MinNetUpdateFrequency = 33.f; } void ASWeapon::BeginPlay() { Super::BeginPlay(); TimeBetweenShot = 60 / FireRate; } void ASWeapon::Fire() { if (Role < ROLE_Authority) { ServerFire(); } AActor* MyOwner = GetOwner(); if (MyOwner) { FVector EyeLocation; FRotator EyeRotation; MyOwner->GetActorEyesViewPoint(EyeLocation, EyeRotation); FVector ShotDircetion = EyeRotation.Vector(); FVector TraceEnd = EyeLocation + (ShotDircetion * 10000); FCollisionQueryParams QueryParams; QueryParams.AddIgnoredActor(MyOwner); QueryParams.AddIgnoredActor(this); QueryParams.bTraceComplex = true; QueryParams.bReturnPhysicalMaterial = true; FVector TracerEndPoint = TraceEnd; EPhysicalSurface SurfaceType = SurfaceType_Default; FHitResult Hit; if (GetWorld()->LineTraceSingleByChannel(Hit, EyeLocation, TraceEnd, WEAPON_COLLISION, QueryParams)) { //Block Hit! AActor* HitActor = Hit.GetActor(); EPhysicalSurface SurfaceType = UPhysicalMaterial::DetermineSurfaceType(Hit.PhysMaterial.Get()); float ActualDamage = BaseDamage; if (SurfaceType == SURFACE_FLESHVULNERABLE) { ActualDamage *= 4.f; } UGameplayStatics::ApplyPointDamage(HitActor, ActualDamage, ShotDircetion, Hit, MyOwner->GetInstigatorController(), this, DamageType); PlayImpactEffect(SurfaceType, Hit.ImpactPoint); TracerEndPoint = Hit.ImpactPoint; HitScanTrace.SurfaceType = SurfaceType; } if (DebugWeaponDrawing > 0) { DrawDebugLine(GetWorld(), EyeLocation, TraceEnd, FColor::Red, false, 1.f, 0, 0.1f); } PlayFireEffect(TracerEndPoint); if (Role == ROLE_Authority) { HitScanTrace.TraceTo = TracerEndPoint; HitScanTrace.SurfaceType = SurfaceType; } LastFireTime = GetWorld()->TimeSeconds; } } void ASWeapon::OnRep_HitScanTrace() { //Play Effect PlayFireEffect(HitScanTrace.TraceTo); PlayImpactEffect(HitScanTrace.SurfaceType, HitScanTrace.TraceTo); } void ASWeapon::ServerFire_Implementation() { Fire(); } bool ASWeapon::ServerFire_Validate() { return true; } void ASWeapon::StartFire() { float FirstDelay = FMath::Max(LastFireTime + TimeBetweenShot - GetWorld()->TimeSeconds,0.0f); GetWorldTimerManager().SetTimer(TimerHandle_TimeBetweenShot, this,&ASWeapon::Fire,TimeBetweenShot, true,FirstDelay); } void ASWeapon::StopFire() { GetWorldTimerManager().ClearTimer(TimerHandle_TimeBetweenShot); } void ASWeapon::PlayFireEffect(FVector TraceEnd) { if (MuzzleEffect) { UGameplayStatics::SpawnEmitterAttached(MuzzleEffect, MeshComp, MuzzleSocketName); } if (TracerEffect) { FVector MuzzleLocation = MeshComp->GetSocketLocation(MuzzleSocketName); UParticleSystemComponent* TracerComp = UGameplayStatics::SpawnEmitterAtLocation(GetWorld(), TracerEffect, MuzzleLocation); if (TracerComp) { TracerComp->SetVectorParameter(TracerTagetName, TraceEnd); } } APawn* MyOwner = Cast<APawn>(GetOwner()); if (MyOwner) { APlayerController* PC = Cast<APlayerController>(MyOwner->GetController()); if (PC) { PC->ClientPlayCameraShake(FireCamShake); } } } void ASWeapon::PlayImpactEffect(EPhysicalSurface SurfaceType,FVector ImpactPoint) { UParticleSystem* SelectedEffect = nullptr; switch (SurfaceType) { case SURFACE_FLESHDEFAULT: case SURFACE_FLESHVULNERABLE: SelectedEffect = FleshImpactEffect; break; default: SelectedEffect = DefaultImpactEffect; break; } if (SelectedEffect) { FVector MuzzleLocation = MeshComp->GetSocketLocation(MuzzleSocketName); FVector ShotDirection = ImpactPoint - MuzzleLocation; ShotDirection.Normalize(); UGameplayStatics::SpawnEmitterAtLocation(GetWorld(), SelectedEffect, ImpactPoint, ShotDirection.Rotation()); } } void ASWeapon::GetLifetimeReplicatedProps(TArray<FLifetimeProperty>& OutLifetimeProps) const { Super::GetLifetimeReplicatedProps(OutLifetimeProps); DOREPLIFETIME_CONDITION(ASWeapon, HitScanTrace, COND_SkipOwner); }
[ "bilibilis@163.com" ]
bilibilis@163.com
2a186e3fac91fbb92d4d667925b7e51c65776173
c68c58941421f6c97912fb53675c899d29926837
/Engine/Rendering/D3D12Renderer/D3D12Resource.h
1e5a780697431e1ab317c0a3de8533543b15271d
[]
no_license
nickjfree/renderer
de21b4e662c25cc62a8ab958ac0e065786620ca6
1ebd25ad0e8bd3a4460886c9e4c15aa5a560da68
refs/heads/master
2021-12-29T19:07:21.134223
2021-12-26T17:43:06
2021-12-26T17:43:06
58,398,579
7
2
null
null
null
null
UTF-8
C++
false
false
13,791
h
#ifndef __D3D12_RESOURCE__ #define __D3D12_RESOURCE__ #include "D3D12Common.h" namespace D3D12Renderer { class UploadHeap; // const buffer constexpr auto max_upload_heap_size = 2048 * 256; constexpr auto const_buffer_align = 256; // resource pool constexpr auto max_texture_number = 8192; constexpr auto max_buffer_number = 8192; constexpr auto max_geometry_number = 8192; constexpr auto max_rt_geometry_number = 8192; // backbuffer count constexpr auto backbuffer_count = 2; /* resource describe */ typedef struct ResourceDescribe { union { R_TEXTURE2D_DESC textureDesc; R_BUFFER_DESC bufferDesc; R_GEOMETRY_DESC geometryDesc; R_RT_GEOMETRY_DESC rtGeometryDesc; }; }ResourceDescribe; /* directx resource base class */ class D3D12Resource { public: // Create virtual void Create(ID3D12Device * d3d12Device, ResourceDescribe* resourceDesc) = 0; // Release virtual void Release() = 0; // Get ID3D12Resource* GetResource() { return resource; } // set state (issue a transfer barrier) virtual void SetResourceState(D3D12CommandContext *cmdContext, D3D12_RESOURCE_STATES targetState); // get state virtual D3D12_RESOURCE_STATES GetResourceState() { return state; } // create descriptor handles in cpuHeap virtual void CreateViews(ID3D12Device* d3d12Device, ResourceDescribe* resourceDesc, D3D12DescriptorHeap** descHeaps); // srv D3D12_CPU_DESCRIPTOR_HANDLE GetSrv() { return views[static_cast<int>(D3D12DescriptorHeap::DESCRIPTOR_HANDLE_TYPES::SRV)]; } // uav D3D12_CPU_DESCRIPTOR_HANDLE GetUav() { return views[static_cast<int>(D3D12DescriptorHeap::DESCRIPTOR_HANDLE_TYPES::UAV)]; } // rtv D3D12_CPU_DESCRIPTOR_HANDLE GetRtv() { return views[static_cast<int>(D3D12DescriptorHeap::DESCRIPTOR_HANDLE_TYPES::RTV)]; } // dsv D3D12_CPU_DESCRIPTOR_HANDLE GetDsv() { return views[static_cast<int>(D3D12DescriptorHeap::DESCRIPTOR_HANDLE_TYPES::DSV)]; } private: public: // resource types enum class RESOURCE_TYPES { BUFFER, TEXTURE, GEOMETRY, BLAS, TLAS, COUNT, }; // resource state D3D12_RESOURCE_STATES state = D3D12_RESOURCE_STATE_COMMON; protected: // views D3D12_CPU_DESCRIPTOR_HANDLE views[(int)D3D12DescriptorHeap::DESCRIPTOR_HANDLE_TYPES::COUNT] = {}; // resource ID3D12Resource* resource = nullptr; }; /* pool resource */ template <class T, int size> class PoolResource : public ResourcePool<T, size>, public D3D12Resource { public: static T* CreateResource(ID3D12Device* d3d12Device, ResourceDescribe* resourceDesc); }; template <class T, int size> T* PoolResource<T, size>::CreateResource(ID3D12Device* d3d12Device, ResourceDescribe* resourceDesc) { T* resource = Alloc(); resource->Create(d3d12Device, resourceDesc); return resource; } /* buffer (shader resource or uav) */ class BufferResource : public PoolResource<BufferResource, max_buffer_number> { public: // create void Create(ID3D12Device* d3d12Device, ResourceDescribe* resourceDesc); // release void Release(); // update void Upload(ID3D12Device* d3d12Device, D3D12CommandContext* copyContext, UploadHeap* uploadHeap, void* cpuData, unsigned int size); // create descriptors in cpu heap void CreateViews(ID3D12Device* d3d12Device, ResourceDescribe* resourceDesc, D3D12DescriptorHeap** descHeaps); }; /* texture ( render targets, shader resource or uav) */ class D3D12BackBuffer; class TextureResource : public PoolResource<TextureResource, max_texture_number> { friend D3D12BackBuffer; public: // create void Create(ID3D12Device* d3d12Device, ResourceDescribe* resourceDesc); // release void Release(); // upload void Upload(ID3D12Device* d3d12Device, D3D12CommandContext* cmdContext, UploadHeap* uploadHeap, std::vector<D3D12_SUBRESOURCE_DATA>& subresources); // create descriptors in cpu heap void CreateViews(ID3D12Device* d3d12Device, ResourceDescribe* resourceDesc, D3D12DescriptorHeap** descHeaps); // get rtv format DXGI_FORMAT GetRtvFormat() { return rtvFormat; } // get dsv format DXGI_FORMAT GetDsvFormat() { return dsvFormat; } private: // isCube bool isCube = false; // rtv dsv format used for pipelinestate union { DXGI_FORMAT dsvFormat = DXGI_FORMAT_UNKNOWN; DXGI_FORMAT rtvFormat; }; }; /* raytracing as */ class Geometry; class RaytracingGeomtry: public PoolResource<RaytracingGeomtry, max_rt_geometry_number> { friend D3D12CommandContext; public: // retire all static void RetireAllTransientGeometry(); // create void Create(ID3D12Device* d3d12Device, ResourceDescribe* resourceDesc); // retire void Retire(); // release void Release(); // transinet void SetTransient(); // set resource state virtual void SetResourceState(D3D12CommandContext* cmdContext, D3D12_RESOURCE_STATES targetState); // isInitialized bool IsInitialized() { return initialized; } // pre-build void PreBuild(D3D12CommandContext* cmdContext); // build void Build(D3D12CommandContext* cmdContext); // post-build void PostBuild(D3D12CommandContext* cmdContext); // GetBottomLevel ID3D12Resource* GetBottomLevel() { return asBuffer; } private: // parent geometry Geometry* geometry = nullptr; // transient bool isTransient = false; // init bool initialized = false; // as buffers BufferResource* transientBuffer = nullptr; ID3D12Resource* asBuffer = nullptr; ID3D12Resource* scratchBuffer = nullptr; // inflight transient items static Vector<RaytracingGeomtry*> inflightRtGeometries; // geometry desc D3D12_RAYTRACING_GEOMETRY_DESC geometryDesc = {}; // build inputs D3D12_BUILD_RAYTRACING_ACCELERATION_STRUCTURE_INPUTS bottomLevelInputs = {}; }; /* vertexbuffer + indexbuffer */ class Geometry: public PoolResource<Geometry, max_geometry_number> { friend D3D12CommandContext; friend RaytracingGeomtry; public: // create void Create(ID3D12Device* d3d12Device, ResourceDescribe* resourceDesc); // release void Release(); // create regeomtry int CreateRtGeometry(ID3D12Device* d3d12Device, bool isTransient); private: // buffers BufferResource* vertexBuffer = nullptr; BufferResource* indexBuffer = nullptr; // vertex stride unsigned int vertexStride = 0; // vertex size unsigned int vertexBufferSize = 0; // index num unsigned int numIndices = 0; // toplogy format R_PRIMITIVE_TOPOLOGY primitiveToplogy = R_PRIMITIVE_TOPOLOGY_UNDEFINED; // rt geometries Vector<RaytracingGeomtry*> transientRtGeometries; // static rtgeometry RaytracingGeomtry* staticRtGeometry = nullptr; }; /* backbuffer */ class D3D12BackBuffer { public: // create void Create(ID3D12Device* d3d12Device, IDXGIFactory4* pFactory, HWND hWnd, int width, int height, D3D12DescriptorHeap* rtvHeap); // get rtv D3D12_CPU_DESCRIPTOR_HANDLE GetRtv(); // GetResource ID3D12Resource* GetResource(); // get frameIndex int GetFrameIndex() { return frameIndex; } // present UINT64 Present(D3D12CommandContext* cmdContext); // set status void SetResourceState(D3D12CommandContext* cmdContext, D3D12_RESOURCE_STATES targetState); // wait for next void WaitForNextFrame(); public: // backbuffer size int width; int height; HWND hWnd; private: // backbufer textures TextureResource backBuffers[backbuffer_count]; // swapchains IDXGISwapChain3* swapChain = nullptr; // current backbuffer index int frameIndex = -1; // prev frame fence UINT64 prevFrameFence[backbuffer_count]; }; /* UploadHeap */ class UploadHeap : public Transient<UploadHeap> { friend Transient<UploadHeap>; public: // Alloc transient static UploadHeap* AllocTransient(ID3D12Device* d3d12Device, unsigned int size); // Alloc static UploadHeap* Alloc(ID3D12Device* d3d12Device, UINT64 size); // release resource void Release(); // suballoc bool SubAlloc(unsigned int allocSize); // gpu virtual address D3D12_GPU_VIRTUAL_ADDRESS GetCurrentGpuVirtualAddress(); // cpu address void* GetCurrentCpuVirtualAddress(); // get ID3D12Resource* Get() { return resource; } private: // reset void resetTransient() { currentOffset = 0; currentRear = 0; } // create void create(ID3D12Device* d3d12Device, UINT64 size); private: // resource ID3D12Resource* resource = nullptr; // current offset unsigned int currentOffset = 0; // current end offset unsigned int currentRear = 0; // ALIGN unsigned int align = 256; // size UINT64 size = 0; // mapped cpu address void* cpuBaseAddress = nullptr; }; /* shader idetifier */ typedef struct ShaderIdetifier { unsigned char identifier[D3D12_SHADER_IDENTIFIER_SIZE_IN_BYTES]; }ShaderIdetifier; // shader record (64 bytes) typedef struct ShaderRecord { // shader identifier 32 bytes ShaderIdetifier identifier; // 4 root parameters 32 bytes UINT64 rootParams[4]; }ShaderRecord; /* shader binding table */ constexpr auto max_ray_types = 4; constexpr auto default_sbt_size = 1024 * 1024; constexpr unsigned int raygen_table_offset = 0; constexpr unsigned int miss_table_offset = max_ray_types * sizeof(ShaderRecord); constexpr unsigned int hitgroup_table_offset = 2 * max_ray_types * sizeof(ShaderRecord); constexpr unsigned int raygen_table_size = max_ray_types * sizeof(ShaderRecord); constexpr unsigned int miss_table_size = max_ray_types * sizeof(ShaderRecord); class ShaderBindingTable { public: // alloc ShaderRecord* AllocShaderRecord(int materialId); // reset void Reset(); // create void Create(ID3D12Device* d3d12Device); // Set ray void SetRay(int shaderId, int rayIndex); // stage void Stage(D3D12CommandContext* cmdContext, D3D12_DISPATCH_RAYS_DESC* rayDesc); // isDirty bool IsDirty() { return dirty; } private: // SBT data Vector<ShaderRecord> hitGroups; // raygen table ShaderRecord rayGen[max_ray_types]; // miss table ShaderRecord miss[max_ray_types]; // sbt size UINT64 sbtSize = 0; // sbt in gpu ID3D12Resource* sbt = nullptr; // upload heap ID3D12Resource* sbtCpu = nullptr; // sbt ptr void* sbtPtr = nullptr; // devuce ID3D12Device* d3d12Device = nullptr; // dirty bool dirty = false; }; /* rt Scene */ constexpr auto default_top_level_as_size = 1024 * 1024 * 4; class RaytracingScene : public Transient<RaytracingScene> { friend Transient<RaytracingScene>; public: // Alloc transient static RaytracingScene* AllocTransient(ID3D12Device* d3d12Device); // alloc shader record ShaderRecord* AllocShaderRecord(int materialId); // add instance void AddInstance(RaytracingGeomtry* rtGeometry, Matrix4x4& transform, int numRays); // build void Build(D3D12CommandContext* cmdContext); // trace ray void TraceRay(D3D12CommandContext* cmdContext, int shaderIndex, int rayId, unsigned int width, unsigned int height); // get desc heap D3D12DescriptorHeap* GetDescriptorHeap(); // get lcoal rs D3D12RootSignature* GetLocalRootSignature() { return localRootSignature; } // get srv D3D12_CPU_DESCRIPTOR_HANDLE GetSrv(); private: // create void create(ID3D12Device* d3d12Device); // reset transient virtual void resetTransient(); private: // instances to build Vector<D3D12_RAYTRACING_INSTANCE_DESC> instanceDesc; // bottom level as to build Vector<RaytracingGeomtry*> bottomLevelGeometries; // toplevel as ID3D12Resource* topLevelAs = nullptr; // toplevel scratch ID3D12Resource* topLevelScratch = nullptr; // instance buffer ID3D12Resource* instanceBuffer = nullptr; // sizes UINT64 topLevelSize = 0; UINT64 scratchSize = 0; UINT64 instanceSize = 0; // instance buffer pointer void* instancePtr = nullptr; // descripter heap D3D12DescriptorHeap* descHeap = nullptr; // binding heap D3D12DescriptorHeap* bindingHeap = nullptr; // local rs D3D12RootSignature* localRootSignature = nullptr; // shader binding table ShaderBindingTable sbt = {}; // rtpso RaytracingStateObject stateObject = {}; // ray desc D3D12_DISPATCH_RAYS_DESC rayDesc = {}; // device ID3D12Device* d3d12Device = nullptr; // rtxDevice ID3D12Device5* rtxDevice = nullptr; }; /* ring constant buffer */ class RingConstantBuffer { public: // Alloc transient constant buffer void* AllocTransientConstantBuffer(unsigned int size, D3D12_GPU_VIRTUAL_ADDRESS* gpuAddress); // reset void Reset(); // release void Release(); // create static RingConstantBuffer* Alloc(ID3D12Device* d3d12Device); private: // current upload heap UploadHeap* currentUploadHeap = nullptr; // device ID3D12Device* d3d12Device = nullptr; }; /* input layouts */ class D3D12InputLayout : public ResourcePool<D3D12InputLayout, 512> { public: D3D12_INPUT_LAYOUT_DESC Layout; D3D12_INPUT_ELEMENT_DESC Element[32]; char Names[32][32]; }; /* shaders */ class D3D12Shader : public ResourcePool<D3D12Shader, 512> { public: D3D12_SHADER_BYTECODE ByteCode; void* RawCode; }; /* raytracing shader and collection */ class RaytracingShader : public ResourcePool<RaytracingShader, 512> { public: // public: // collection ID3D12StateObject* collection; // shader indentifier ShaderIdetifier raygen; ShaderIdetifier hitGroup; ShaderIdetifier miss; }; /* state describe */ typedef struct StateDescribe { union { R_BLEND_STATUS blendDesc; R_RASTERIZER_DESC rasterizerDesc; R_DEPTH_STENCIL_DESC depthStencilDesc; }; }StateDescribe; /* * render state */ class D3D12RenderState : public ResourcePool<D3D12RenderState, 512> { public: union { D3D12_DEPTH_STENCIL_DESC Depth; D3D12_RASTERIZER_DESC Raster; D3D12_BLEND_DESC Blend; }; unsigned char StencilRef; }; } #endif
[ "nick12@live.cn" ]
nick12@live.cn
d2edfc7d74a4147ab4cdeee7e5d4686800e192b0
229ac4e7185f89c333f55ca3899223e5ba8e0e10
/include/toy/parser/Translator.hpp
7d2808d2fe0b6747947a1e161c1080a0fac24d5f
[ "Unlicense" ]
permissive
ToyAuthor/ToyBox
ab2d83a1b09ff6ea2f387fb672a56e4dbd4063a2
f517a64d00e00ccaedd76e33ed5897edc6fde55e
refs/heads/master
2021-01-17T01:31:55.985845
2020-10-01T14:05:28
2020-10-01T14:05:28
19,876,055
5
1
null
null
null
null
UTF-8
C++
false
false
632
hpp
#pragma once #include "toy/Standard.hpp" #include "toy/parser/Export.hpp" namespace toy{ namespace parser{ class Dictionary; class TOY_API_PARSER Translator { public: typedef std::shared_ptr<Dictionary> DictionaryPtr; Translator(); ~Translator(); void transle(std::string key); void publishNextLine(); void publishUnknown(std::string key); bool isExist(std::string key); void pushDictionary(DictionaryPtr); void popDictionary(int number=1); void drop(); DictionaryPtr getDictionary(); private: std::vector<DictionaryPtr> _data; }; }//namespace parser }//namespace toy
[ "eye5002003@gmail.com" ]
eye5002003@gmail.com
39e909e05dc7dfed15df72bd344cb408cedd5a74
079207f3cda54a6c5d7e841b5010f1a486e0cdb4
/touch_handlers.cpp
2e61669f7123e9c9d790566af966b9fe9c223045
[]
no_license
aft3rthought/ATLCrossPlatform
b98969f0683f346ef93b529d30c27742123715c3
eb81b69e48ce1bb4b9d806fb01b474ef922d57d5
refs/heads/master
2022-10-31T20:57:05.298226
2022-10-20T04:24:56
2022-10-20T04:24:56
58,298,664
0
0
null
null
null
null
UTF-8
C++
false
false
639
cpp
#include "./touch_handlers.h" namespace atl { touch_handlers::touch_handlers(std::function<void(uint32_t, const atl::point2f &)> inTouchStartHandler, std::function<void(uint32_t, const atl::point2f &)> inTouchMovedHandler, std::function<void(uint32_t, const atl::point2f &)> inTouchEndHandler, std::function<void(uint32_t)> inTouchLostHandler) : mTouchStartHandler(inTouchStartHandler), mTouchMovedHandler(inTouchMovedHandler), mTouchEndHandler(inTouchEndHandler), mTouchLostHandler(inTouchLostHandler) {} }
[ "mcrpublic@gmail.com" ]
mcrpublic@gmail.com
5a700b23fc3142e6fe10acdc309c20b0aefd8ddd
bcd3c5f71d6f4a216a6e04ca6ba9af8d6e04d915
/GraphicsEngine/main.cpp
b031e78d52b64479ce574eb28f1569887986a91a
[]
no_license
PeterCarragher/3D_OpenGL_Engine
29514ca50ea3f32f1ecf91ea72ef297d1066d274
210055a3e1de17e723c2a2a5997ab595bd2f14c8
refs/heads/master
2021-01-11T02:09:51.527316
2016-10-20T14:30:01
2016-10-20T14:30:01
70,799,628
1
0
null
null
null
null
UTF-8
C++
false
false
13,635
cpp
#define GLEW_STATIC #include <GL/glew.h> #include <GLFW/glfw3.h> #include <SOIL/SOIL.h> #include <glm/glm.hpp> #include <glm/gtc/matrix_transform.hpp> #include <glm/gtc/type_ptr.hpp> #include "camera.h" #include "globals.h" #include "shader.h" #include "model.h" #include <iostream> //Fucntion prototypes void key_callback(GLFWwindow* window, int key, int scancode, int action, int mode); void mouse_callback(GLFWwindow* window, double xpos, double ypos); void scroll_callback(GLFWwindow* window, double xoffset, double yoffset); void do_movement(); bool keys[1024]; bool torchOn = false; GLfloat deltaTime = 0.0f; // Time between current frame and last frame GLfloat lastFrame = 0.0f; // Time of last frame GLfloat lastX = 400, lastY = 300; //CURSOR initial position bool firstMouse = true; Camera camera(glm::vec3(3.0f, -0.3f, -3.9f), glm::vec3(0.0f, 1.0f, 0.0f), -180.f, 0.f); glm::vec3 lightPos = glm::vec3(1.2f, 2.0f, -2.0f); glm::vec3 lightColor = glm::vec3(1.0f, 1.0f, 1.0f); int main(){ //-----------------SET UP AND INITIALISE GLFW & GLEW------------------// glfwInit(); glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3); glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3); glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE); glfwWindowHint(GLFW_RESIZABLE, GL_FALSE); GLFWwindow* window = glfwCreateWindow(WIDTH, HEIGHT, "GraphicsEngine", nullptr, nullptr); glfwMakeContextCurrent(window); if (window == NULL){ std::cout << "Failed to create GLFW window" << std::endl; glfwTerminate(); return -1; } // Initialize GLEW to setup the OpenGL Function pointers glewExperimental = GL_TRUE; if (glewInit() != GLEW_OK){ std::cout << "Failed to initialise GLEW" << std::endl; return -1; } //------------------VERTEX DATA AND VAO'S------------------// GLfloat cubeVertices[] { // Positions // Normals // Texture Coords -0.5f, -0.5f, -0.5f, 0.0f, 0.0f, -1.0f, 0.0f, 0.0f, 0.5f, -0.5f, -0.5f, 0.0f, 0.0f, -1.0f, 1.0f, 0.0f, 0.5f, 0.5f, -0.5f, 0.0f, 0.0f, -1.0f, 1.0f, 1.0f, 0.5f, 0.5f, -0.5f, 0.0f, 0.0f, -1.0f, 1.0f, 1.0f, -0.5f, 0.5f, -0.5f, 0.0f, 0.0f, -1.0f, 0.0f, 1.0f, -0.5f, -0.5f, -0.5f, 0.0f, 0.0f, -1.0f, 0.0f, 0.0f, -0.5f, -0.5f, 0.5f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 0.5f, -0.5f, 0.5f, 0.0f, 0.0f, 1.0f, 1.0f, 0.0f, 0.5f, 0.5f, 0.5f, 0.0f, 0.0f, 1.0f, 1.0f, 1.0f, 0.5f, 0.5f, 0.5f, 0.0f, 0.0f, 1.0f, 1.0f, 1.0f, -0.5f, 0.5f, 0.5f, 0.0f, 0.0f, 1.0f, 0.0f, 1.0f, -0.5f, -0.5f, 0.5f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, -0.5f, 0.5f, 0.5f, -1.0f, 0.0f, 0.0f, 1.0f, 0.0f, -0.5f, 0.5f, -0.5f, -1.0f, 0.0f, 0.0f, 1.0f, 1.0f, -0.5f, -0.5f, -0.5f, -1.0f, 0.0f, 0.0f, 0.0f, 1.0f, -0.5f, -0.5f, -0.5f, -1.0f, 0.0f, 0.0f, 0.0f, 1.0f, -0.5f, -0.5f, 0.5f, -1.0f, 0.0f, 0.0f, 0.0f, 0.0f, -0.5f, 0.5f, 0.5f, -1.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.5f, 0.5f, 0.5f, 1.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.5f, 0.5f, -0.5f, 1.0f, 0.0f, 0.0f, 1.0f, 1.0f, 0.5f, -0.5f, -0.5f, 1.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.5f, -0.5f, -0.5f, 1.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.5f, -0.5f, 0.5f, 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.5f, 0.5f, 0.5f, 1.0f, 0.0f, 0.0f, 1.0f, 0.0f, -0.5f, -0.5f, -0.5f, 0.0f, -1.0f, 0.0f, 0.0f, 1.0f, 0.5f, -0.5f, -0.5f, 0.0f, -1.0f, 0.0f, 1.0f, 1.0f, 0.5f, -0.5f, 0.5f, 0.0f, -1.0f, 0.0f, 1.0f, 0.0f, 0.5f, -0.5f, 0.5f, 0.0f, -1.0f, 0.0f, 1.0f, 0.0f, -0.5f, -0.5f, 0.5f, 0.0f, -1.0f, 0.0f, 0.0f, 0.0f, -0.5f, -0.5f, -0.5f, 0.0f, -1.0f, 0.0f, 0.0f, 1.0f, -0.5f, 0.5f, -0.5f, 0.0f, 1.0f, 0.0f, 0.0f, 1.0f, 0.5f, 0.5f, -0.5f, 0.0f, 1.0f, 0.0f, 1.0f, 1.0f, 0.5f, 0.5f, 0.5f, 0.0f, 1.0f, 0.0f, 1.0f, 0.0f, 0.5f, 0.5f, 0.5f, 0.0f, 1.0f, 0.0f, 1.0f, 0.0f, -0.5f, 0.5f, 0.5f, 0.0f, 1.0f, 0.0f, 0.0f, 0.0f, -0.5f, 0.5f, -0.5f, 0.0f, 1.0f, 0.0f, 0.0f, 1.0f }; glm::vec3 cubePositions[] { glm::vec3(0.0f, 0.0f, 0.0f), glm::vec3(2.0f, 5.0f, -15.0f), glm::vec3(-1.5f, -2.2f, -2.5f), glm::vec3(-3.8f, -2.0f, -12.3f), glm::vec3(2.4f, -0.4f, -3.5f), glm::vec3(-1.7f, 3.0f, -7.5f), glm::vec3(1.3f, -2.0f, -2.5f), glm::vec3(1.5f, 2.0f, -2.5f), glm::vec3(1.5f, 0.2f, -1.5f), glm::vec3(-1.3f, 1.0f, -1.5f) }; GLuint indices[]{ // Note that we start from 0! 0, 1, 3, // First Triangle 1, 2, 3 // Second Triangle }; glm::vec3 pointLightPositions[] { glm::vec3(2.217, 1.0714, 4.066) }; glm::vec3 spotLightPositions[] { // position direction glm::vec3(-2.405, 0.14, -1.106), glm::vec3(0.0f, -1.0f, 0.0f), glm::vec3(2.801, 0.14, -0.949), glm::vec3(0.0f, -1.0f, 0.0f), glm::vec3(3.637, -1.4, 0.954), glm::vec3(-0.737, -0.216, 0.641) }; int NUM_SPOT_LIGHTS = 3; GLuint cubeVBO; //sets up openGL object, cubeVBO glGenBuffers(1, &cubeVBO); //binds buffer with ID 1 to cubeVBO //light VAO GLuint lightVAO; glGenVertexArrays(1, &lightVAO); glBindVertexArray(lightVAO); glBindBuffer(GL_ARRAY_BUFFER, cubeVBO); glBufferData(GL_ARRAY_BUFFER, sizeof(cubeVertices), cubeVertices, GL_STATIC_DRAW); glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 8 * sizeof(GLfloat), (GLvoid*)0); //how to interpret vertex data glEnableVertexAttribArray(0); //vertex attributes are defauly disabled. enable attribute 0 (layout) glBindVertexArray(0); //set openGL attributes glViewport(0, 0, WIDTH, HEIGHT); //set viewport on current window context glEnable(GL_DEPTH_TEST); //Compile shaders Shader lightingShader("simpleShader.vert", "simpleLightShader.frag"); //register callbacks via GLFW glfwSetKeyCallback(window, key_callback); //key_callback is regiestered to window context glfwSetCursorPosCallback(window, mouse_callback); glfwSetScrollCallback(window, scroll_callback); //glPolygonMode(GL_FRONT_AND_BACK, GL_LINE); //WIREFRAME POLYGONS glfwSetInputMode(window, GLFW_CURSOR, GLFW_CURSOR_DISABLED); //load models Model flashlight("Assets/Models/Lights/Flashlight/flashlight.obj"); Model scene("Assets/Models/scene/scene.obj"); //---------------GAME LOOP-------------------// while (!glfwWindowShouldClose(window)){ GLfloat currentFrame = glfwGetTime(); deltaTime = currentFrame - lastFrame; lastFrame = currentFrame; // Check and call events glfwPollEvents(); do_movement(); // Clear the colorbuffer glClearColor(0.0f, 0.0f, 0.0f, 1.0f); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); lightingShader.Use(); // Transformation matrices glm::mat4 model; glm::mat4 projection = glm::perspective(45.0f, (float)WIDTH / (float)HEIGHT, 0.1f, 100.0f); glm::mat4 view = camera.GetCameraViewMatrix(); glUniformMatrix4fv(glGetUniformLocation(lightingShader.Program, "projection"), 1, GL_FALSE, glm::value_ptr(projection)); glUniformMatrix4fv(glGetUniformLocation(lightingShader.Program, "view"), 1, GL_FALSE, glm::value_ptr(view)); // Set the lighting uniforms //directional light /* glUniform3f(glGetUniformLocation(lightingShader.Program, "dirLight.direction"), -0.2f, -1.0f, -0.3f); glUniform3f(glGetUniformLocation(lightingShader.Program, "dirLight.ambient"), 0.05f, 0.05f, 0.05f); glUniform3f(glGetUniformLocation(lightingShader.Program, "dirLight.diffuse"), 0.4f, 0.4f, 0.4f); glUniform3f(glGetUniformLocation(lightingShader.Program, "dirLight.specular"), 0.5f, 0.5f, 0.5f); glUniform3f(glGetUniformLocation(lightingShader.Program, "viewPos"), camera.getPos().x, camera.getPos().y, camera.getPos().z);*/ // Point light 1 glUniform3f(glGetUniformLocation(lightingShader.Program, "pointLights[0].position"), spotLightPositions[0].x, spotLightPositions[0].y-0.5, spotLightPositions[0].z); glUniform3f(glGetUniformLocation(lightingShader.Program, "pointLights[0].ambient"), 0.05f, 0.05f, 0.05f); glUniform3f(glGetUniformLocation(lightingShader.Program, "pointLights[0].diffuse"), 0.25f, 0.3f, 0.25f); glUniform3f(glGetUniformLocation(lightingShader.Program, "pointLights[0].specular"), 0.25f, 0.3f, 0.25f); glUniform1f(glGetUniformLocation(lightingShader.Program, "pointLights[0].constant"), 1.0f); glUniform1f(glGetUniformLocation(lightingShader.Program, "pointLights[0].linear"), 0.009); glUniform1f(glGetUniformLocation(lightingShader.Program, "pointLights[0].quadratic"), 0.0032); //spotlight for flashlight glUniform3f(glGetUniformLocation(lightingShader.Program, "spotLight[0].position"), camera.getPos().x, camera.getPos().y, camera.getPos().z); glUniform3f(glGetUniformLocation(lightingShader.Program, "spotLight[0].direction"), camera.getDir().x, camera.getDir().y, camera.getDir().z); glUniform1f(glGetUniformLocation(lightingShader.Program, "spotLight[0].innerCutOff"), glm::cos(glm::radians(20.0f))); glUniform1f(glGetUniformLocation(lightingShader.Program, "spotLight[0].outerCutOff"), glm::cos(glm::radians(35.0f))); glUniform1f(glGetUniformLocation(lightingShader.Program, "spotLight[0].constant"), 1.0f); glUniform1f(glGetUniformLocation(lightingShader.Program, "spotLight[0].linear"), 0.009); glUniform1f(glGetUniformLocation(lightingShader.Program, "spotLight[0].quadratic"), 0.0032); glUniform3f(glGetUniformLocation(lightingShader.Program, "spotLight[0].diffuse"), 1.0f, 1.0f, 1.0f); glUniform3f(glGetUniformLocation(lightingShader.Program, "spotLight[0].ambient"), 0.05f, 0.05f, 0.05f); glUniform3f(glGetUniformLocation(lightingShader.Program, "spotLight[0].specular"), 1.0f, 1.0f, 1.0f); glUniform1i(glGetUniformLocation(lightingShader.Program, "spotLight[0].torchOn"), torchOn); for (int x = 0; x < NUM_SPOT_LIGHTS*2; x+=2){ float flicker; if (x == 0) { flicker = 1; } else{ flicker = floor((sin(glfwGetTime() * 20) / 2 + 0.5) + 0.7); } glm::vec3 pos = spotLightPositions[x]; glm::vec3 dir = spotLightPositions[x + 1]; string name = "spotLight[" + to_string((x / 2) + 1) + "]."; glUniform3f(glGetUniformLocation(lightingShader.Program, (name + "position").c_str()), pos.x, pos.y, pos.z); glUniform3f(glGetUniformLocation(lightingShader.Program, (name + "direction").c_str()), dir.x, dir.y, dir.z); glUniform1f(glGetUniformLocation(lightingShader.Program, (name + "innerCutOff").c_str()), glm::cos(glm::radians(30.0f))); glUniform1f(glGetUniformLocation(lightingShader.Program, (name + "outerCutOff").c_str()), glm::cos(glm::radians(50.0f))); glUniform1f(glGetUniformLocation(lightingShader.Program, (name + "constant").c_str()), 1.0f); glUniform1f(glGetUniformLocation(lightingShader.Program, (name + "linear").c_str()), 0.009); glUniform1f(glGetUniformLocation(lightingShader.Program, (name + "quadratic").c_str()), 0.0032); glUniform3f(glGetUniformLocation(lightingShader.Program, (name + "diffuse").c_str()), flicker*0.5f, flicker*0.45f, flicker*0.5f); glUniform3f(glGetUniformLocation(lightingShader.Program, (name + "ambient").c_str()), flicker*0.02f, flicker*0.05f, flicker*0.02f); glUniform3f(glGetUniformLocation(lightingShader.Program, (name + "specular").c_str()), 0.5f, 0.45f, 0.5f); glUniform1i(glGetUniformLocation(lightingShader.Program, (name + "torchOn").c_str()), true); } // Draw the loaded wood_house model = glm::translate(model, glm::vec3(0.0f, -1.75f, 0.0f)); // Translate it down a bit so it's at the center of the scene model = glm::scale(model, glm::vec3(0.2f, 0.2f, 0.2f)); // It's a bit too big for our scene, so scale it down glUniformMatrix4fv(glGetUniformLocation(lightingShader.Program, "model"), 1, GL_FALSE, glm::value_ptr(model)); scene.Draw(lightingShader); //draw torch on character model = glm::mat4(); model = glm::translate(model, camera.getPos()); model = glm::rotate(model, glm::radians(180.0f), glm::vec3(1.0f, 0.0f, 0.0f)); model = glm::rotate(model, glm::radians(camera.getYaw()+90.0f), glm::vec3(0.0f, 1.0f, 0.0f)); model = glm::rotate(model, glm::radians(camera.getPitch()), glm::vec3(1.0f, 0.0f, 0.0f)); model = glm::translate(model, glm::vec3(-0.1f, 0.2f, 0.0f)); //place near hand glUniformMatrix4fv(glGetUniformLocation(lightingShader.Program, "model"), 1, GL_FALSE, glm::value_ptr(model)); flashlight.Draw(lightingShader); glBindVertexArray(0); glfwSwapBuffers(window); } glDeleteVertexArrays(1, &lightVAO); glDeleteBuffers(1, &cubeVBO); glfwTerminate(); //cleans up GLFW allocations return 0; } void key_callback(GLFWwindow* window, int key, int scancode, int action, int mode){ //if escape pressed, windowShouldClose = true if (key == GLFW_KEY_ESCAPE && action == GLFW_PRESS){ glfwSetWindowShouldClose(window, GL_TRUE); } if (action == GLFW_PRESS) keys[key] = true; else if (action == GLFW_RELEASE) keys[key] = false; if (action == GLFW_PRESS && key == GLFW_KEY_F) torchOn = !torchOn; if (action == GLFW_PRESS && key == GLFW_KEY_L){ std::cout << "\nPOSITION \n --------- \nx: " << camera.getPos().x << "\ny: " << camera.getPos().y << "\nz: " << camera.getPos().z << "\n\nDIRECTION \n --------- \nx: " << camera.getDir().x << "\ny: " << camera.getDir().y << "\nz: " << camera.getDir().z << endl; } } void do_movement() { if (keys[GLFW_KEY_W]) camera.ProcessKeyboardInput(FORWARD, deltaTime); if (keys[GLFW_KEY_S]) camera.ProcessKeyboardInput(BACKWARD, deltaTime); if (keys[GLFW_KEY_A]) camera.ProcessKeyboardInput(LEFT, deltaTime); if (keys[GLFW_KEY_D]) camera.ProcessKeyboardInput(RIGHT, deltaTime); } void mouse_callback(GLFWwindow* window, double xpos, double ypos) { if (firstMouse) { lastX = xpos; lastY = ypos; firstMouse = false; } GLfloat xoffset = xpos - lastX; GLfloat yoffset = lastY - ypos; lastX = xpos; lastY = ypos; camera.ProcessMouseInput(xoffset, yoffset, GL_TRUE); } void scroll_callback(GLFWwindow* window, double xoffset, double yoffset){ camera.ProcessScrollInput(yoffset); }
[ "petercarragher6@gmail.com" ]
petercarragher6@gmail.com
5c2431805bc3700f91007768835e4ea3e3fb831d
7935a2329c7314016b39b2ad31ae693c5679491c
/EventSystem/Event.cpp
976315ef8b280e49c1008e70cd501e4f877f209e
[]
no_license
Hemmy123/summer-game-engine
49a6626944cc869a32dc403317a053c682c838b2
ff5dfceb4a1046e76507c64e0432c0395efbd73a
refs/heads/master
2020-03-30T06:29:01.306582
2018-09-29T13:00:54
2018-09-29T13:00:54
150,864,789
0
0
null
null
null
null
UTF-8
C++
false
false
183
cpp
////======================================== // Class: Event // Author: Hemmy // Date: 12/06/2018 // Description: // // ======================================== #include "Event.hpp"
[ "M.he8@newcastle.ac.uk" ]
M.he8@newcastle.ac.uk
0a23ea2a18055862a6154145da1479676c1a3944
272c3b13339d0e7871c27a9c5d555a171380afe4
/libFileRevisor/StaticUtilities/Type.h
fd1c6b5b34d26bd43c9649d60fd8b8307e032760
[ "MIT" ]
permissive
NeilJustice/FileRevisor
4b219a8b6dfafdcb8994365bf7df941c964022ca
a12d7d57503cfe6f2a0dcd6fa8dd31a2ff8a005a
refs/heads/main
2023-08-16T15:42:29.221920
2023-08-12T18:30:48
2023-08-12T18:30:48
151,807,150
0
0
null
null
null
null
UTF-8
C++
false
false
888
h
#pragma once #if defined __linux__|| defined __APPLE__ #include <cxxabi.h> #endif class Type { friend class TypeTests; private: static std::unordered_map<const char*, std::string> s_mangledToDemangledTypeName; public: static string GetExceptionClassNameAndMessage(const exception* ex); template<typename T> static const std::string* GetName(const T& variable) { return TypeInfoToTypeName(typeid(variable)); } template<typename T> static const std::string* GetName() { return TypeInfoToTypeName(typeid(T)); } Type() = delete; private: static const std::string* TypeInfoToTypeName(const std::type_info& typeInfo); #if defined __linux__|| defined __APPLE__ static std::string Demangle(const char* mangledTypeName); #elif _WIN32 static std::string Demangle(const char* mangledTypeName); #endif };
[ "njjustice@gmail.com" ]
njjustice@gmail.com
ecc714d7784adfff682b1d0a8cf67d9e87b7eff9
363176993f80d8acdf6f53ef0eb742a69afb008a
/chromecast/media/audio/cma_audio_output_stream.cc
b45246fd95486cd3a027c69bb91062cc92260069
[ "BSD-3-Clause" ]
permissive
nico/chromium
1ab2f891d6f05c8914f2f5a80e08e3564fd43110
777ca4b71dcae380958a8255a9f8e35c4623f5dc
refs/heads/master
2023-03-14T16:29:08.617171
2020-03-19T23:11:13
2020-03-19T23:11:13
248,628,027
1
0
BSD-3-Clause
2020-03-19T23:46:43
2020-03-19T23:46:43
null
UTF-8
C++
false
false
11,237
cc
// Copyright 2019 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chromecast/media/audio/cma_audio_output_stream.h" #include <algorithm> #include <limits> #include <utility> #include "base/bind.h" #include "base/location.h" #include "base/logging.h" #include "base/synchronization/waitable_event.h" #include "chromecast/base/task_runner_impl.h" #include "chromecast/media/base/default_monotonic_clock.h" #include "chromecast/media/cma/backend/cma_backend_factory.h" #include "chromecast/media/cma/base/decoder_buffer_adapter.h" #include "chromecast/media/cma/base/decoder_config_adapter.h" #include "chromecast/public/media/media_pipeline_device_params.h" #include "chromecast/public/volume_control.h" #include "media/audio/audio_device_description.h" #include "media/base/audio_bus.h" #include "media/base/decoder_buffer.h" namespace chromecast { namespace media { namespace { constexpr base::TimeDelta kRenderBufferSize = base::TimeDelta::FromSeconds(4); AudioContentType GetContentType(const std::string& device_id) { if (::media::AudioDeviceDescription::IsCommunicationsDevice(device_id)) { return AudioContentType::kCommunication; } return AudioContentType::kMedia; } } // namespace CmaAudioOutputStream::CmaAudioOutputStream( const ::media::AudioParameters& audio_params, base::TimeDelta buffer_duration, const std::string& device_id, CmaBackendFactory* cma_backend_factory) : is_audio_prefetch_(audio_params.effects() & ::media::AudioParameters::AUDIO_PREFETCH), audio_params_(audio_params), device_id_(device_id), cma_backend_factory_(cma_backend_factory), timestamp_helper_(audio_params_.sample_rate()), buffer_duration_(buffer_duration), render_buffer_size_estimate_(kRenderBufferSize) { DCHECK(cma_backend_factory_); DETACH_FROM_THREAD(media_thread_checker_); LOG(INFO) << "Enable audio prefetch: " << is_audio_prefetch_; } CmaAudioOutputStream::~CmaAudioOutputStream() = default; void CmaAudioOutputStream::SetRunning(bool running) { base::AutoLock lock(running_lock_); running_ = running; } void CmaAudioOutputStream::Initialize( const std::string& application_session_id, chromecast::mojom::MultiroomInfoPtr multiroom_info) { DCHECK_CALLED_ON_VALID_THREAD(media_thread_checker_); DCHECK(cma_backend_factory_); if (cma_backend_state_ != CmaBackendState::kUninitialized) return; cma_backend_task_runner_ = std::make_unique<TaskRunnerImpl>(); MediaPipelineDeviceParams device_params( MediaPipelineDeviceParams::kModeIgnorePts, MediaPipelineDeviceParams::kAudioStreamNormal, cma_backend_task_runner_.get(), GetContentType(device_id_), device_id_); device_params.session_id = application_session_id; device_params.multiroom = multiroom_info->multiroom; device_params.audio_channel = multiroom_info->audio_channel; device_params.output_delay_us = multiroom_info->output_delay.InMicroseconds(); cma_backend_ = cma_backend_factory_->CreateBackend(device_params); if (!cma_backend_) { encountered_error_ = true; return; } audio_decoder_ = cma_backend_->CreateAudioDecoder(); if (!audio_decoder_) { encountered_error_ = true; return; } audio_decoder_->SetDelegate(this); AudioConfig audio_config; audio_config.codec = kCodecPCM; audio_config.channel_layout = DecoderConfigAdapter::ToChannelLayout(audio_params_.channel_layout()); audio_config.sample_format = kSampleFormatS16; audio_config.bytes_per_channel = 2; audio_config.channel_number = audio_params_.channels(); audio_config.samples_per_second = audio_params_.sample_rate(); DCHECK(IsValidConfig(audio_config)); if (!audio_decoder_->SetConfig(audio_config)) { encountered_error_ = true; return; } if (!cma_backend_->Initialize()) { encountered_error_ = true; return; } cma_backend_state_ = CmaBackendState::kStopped; audio_bus_ = ::media::AudioBus::Create(audio_params_); timestamp_helper_.SetBaseTimestamp(base::TimeDelta()); } void CmaAudioOutputStream::Start( ::media::AudioOutputStream::AudioSourceCallback* source_callback) { DCHECK(source_callback); DCHECK_CALLED_ON_VALID_THREAD(media_thread_checker_); if (cma_backend_state_ == CmaBackendState::kPendingClose) return; source_callback_ = source_callback; if (encountered_error_) { source_callback_->OnError( ::media::AudioOutputStream::AudioSourceCallback::ErrorType::kUnknown); return; } if (cma_backend_state_ == CmaBackendState::kPaused || cma_backend_state_ == CmaBackendState::kStopped) { if (cma_backend_state_ == CmaBackendState::kPaused) { cma_backend_->Resume(); } else { cma_backend_->Start(0); render_buffer_size_estimate_ = kRenderBufferSize; } next_push_time_ = base::TimeTicks::Now(); last_push_complete_time_ = base::TimeTicks::Now(); cma_backend_state_ = CmaBackendState::kStarted; } if (!push_in_progress_) { PushBuffer(); } } void CmaAudioOutputStream::Stop(base::WaitableEvent* finished) { DCHECK_CALLED_ON_VALID_THREAD(media_thread_checker_); // Prevent further pushes to the audio buffer after stopping. push_timer_.Stop(); // Don't actually stop the backend. Stop() gets called when the stream is // paused. We rely on Flush() to stop the backend. if (cma_backend_) { cma_backend_->Pause(); cma_backend_state_ = CmaBackendState::kPaused; } source_callback_ = nullptr; finished->Signal(); } void CmaAudioOutputStream::Flush(base::WaitableEvent* finished) { DCHECK_CALLED_ON_VALID_THREAD(media_thread_checker_); // Prevent further pushes to the audio buffer after stopping. push_timer_.Stop(); if (cma_backend_ && (cma_backend_state_ == CmaBackendState::kPaused || cma_backend_state_ == CmaBackendState::kStarted)) { cma_backend_->Stop(); cma_backend_state_ = CmaBackendState::kStopped; } push_in_progress_ = false; source_callback_ = nullptr; finished->Signal(); } void CmaAudioOutputStream::Close(base::OnceClosure closure) { DCHECK_CALLED_ON_VALID_THREAD(media_thread_checker_); // Prevent further pushes to the audio buffer after stopping. push_timer_.Stop(); // Only stop the backend if it was started. if (cma_backend_ && cma_backend_state_ != CmaBackendState::kStopped) { cma_backend_->Stop(); } push_in_progress_ = false; source_callback_ = nullptr; cma_backend_state_ = CmaBackendState::kPendingClose; audio_bus_.reset(); cma_backend_.reset(); cma_backend_task_runner_.reset(); std::move(closure).Run(); } void CmaAudioOutputStream::SetVolume(double volume) { DCHECK_CALLED_ON_VALID_THREAD(media_thread_checker_); if (!audio_decoder_) { return; } if (encountered_error_) { return; } audio_decoder_->SetVolume(volume); } void CmaAudioOutputStream::PushBuffer() { DCHECK_CALLED_ON_VALID_THREAD(media_thread_checker_); // Acquire running_lock_ for the scope of this push call to // prevent the source callback from closing the output stream // mid-push. base::AutoLock lock(running_lock_); DCHECK(!push_in_progress_); // Do not fill more buffers if we have stopped running. if (!running_) return; // It is possible that this function is called when we are stopped. // Return quickly if so. if (!source_callback_ || encountered_error_ || cma_backend_state_ != CmaBackendState::kStarted) { return; } CmaBackend::AudioDecoder::RenderingDelay rendering_delay = audio_decoder_->GetRenderingDelay(); base::TimeDelta delay; if (rendering_delay.delay_microseconds < 0 || rendering_delay.timestamp_microseconds < 0) { // This occurs immediately after start/resume when there isn't a good // estimate of the buffer delay. Use the last known good delay. delay = last_rendering_delay_; } else { // The rendering delay to account for buffering is not included in // rendering_delay.delay_microseconds but is in delay_timestamp which isn't // used by AudioOutputStreamImpl. delay = base::TimeDelta::FromMicroseconds( rendering_delay.delay_microseconds + rendering_delay.timestamp_microseconds - MonotonicClockNow()); if (delay.InMicroseconds() < 0) { delay = base::TimeDelta(); } } last_rendering_delay_ = delay; int frame_count = source_callback_->OnMoreData(delay, base::TimeTicks(), 0, audio_bus_.get()); DVLOG(3) << "frames_filled=" << frame_count << " with latency=" << delay; if (frame_count == 0) { OnPushBufferComplete(CmaBackend::BufferStatus::kBufferFailed); return; } auto decoder_buffer = base::MakeRefCounted<DecoderBufferAdapter>(new ::media::DecoderBuffer( frame_count * audio_bus_->channels() * sizeof(int16_t))); audio_bus_->ToInterleaved<::media::SignedInt16SampleTypeTraits>( frame_count, reinterpret_cast<int16_t*>(decoder_buffer->writable_data())); decoder_buffer->set_timestamp(timestamp_helper_.GetTimestamp()); timestamp_helper_.AddFrames(frame_count); push_in_progress_ = true; BufferStatus status = audio_decoder_->PushBuffer(std::move(decoder_buffer)); if (status != CmaBackend::BufferStatus::kBufferPending) OnPushBufferComplete(status); } void CmaAudioOutputStream::OnPushBufferComplete(BufferStatus status) { DCHECK_CALLED_ON_VALID_THREAD(media_thread_checker_); DCHECK_NE(status, CmaBackend::BufferStatus::kBufferPending); push_in_progress_ = false; if (!source_callback_ || encountered_error_) return; DCHECK_EQ(cma_backend_state_, CmaBackendState::kStarted); if (status != CmaBackend::BufferStatus::kBufferSuccess) { source_callback_->OnError( ::media::AudioOutputStream::AudioSourceCallback::ErrorType::kUnknown); return; } // Schedule next push buffer. const base::TimeTicks now = base::TimeTicks::Now(); base::TimeDelta delay; if (is_audio_prefetch_) { // For multizone-playback, we don't care about AV sync and want to pre-fetch // audio. render_buffer_size_estimate_ -= buffer_duration_; render_buffer_size_estimate_ += now - last_push_complete_time_; last_push_complete_time_ = now; if (render_buffer_size_estimate_ >= buffer_duration_) { delay = base::TimeDelta::FromSeconds(0); } else { delay = buffer_duration_; } } else { next_push_time_ = std::max(now, next_push_time_ + buffer_duration_); delay = next_push_time_ - now; } DVLOG(3) << "render_buffer_size_estimate_=" << render_buffer_size_estimate_ << " delay=" << delay << " buffer_duration_=" << buffer_duration_; push_timer_.Start(FROM_HERE, delay, this, &CmaAudioOutputStream::PushBuffer); } void CmaAudioOutputStream::OnDecoderError() { DLOG(INFO) << this << ": " << __func__; DCHECK_CALLED_ON_VALID_THREAD(media_thread_checker_); encountered_error_ = true; if (source_callback_) { source_callback_->OnError( ::media::AudioOutputStream::AudioSourceCallback::ErrorType::kUnknown); } } } // namespace media } // namespace chromecast
[ "commit-bot@chromium.org" ]
commit-bot@chromium.org
44c11433a6b43be99b9d4adf5b83f982f234a9c8
ad822f849322c5dcad78d609f28259031a96c98e
/SDK/Researchable_Crust_Tundra_01_classes.h
5dc89bc9117683f4562045002f556972803e01f2
[]
no_license
zH4x-SDK/zAstroneer-SDK
1cdc9c51b60be619202c0258a0dd66bf96898ac4
35047f506eaef251a161792fcd2ddd24fe446050
refs/heads/main
2023-07-24T08:20:55.346698
2021-08-27T13:33:33
2021-08-27T13:33:33
null
0
0
null
null
null
null
UTF-8
C++
false
false
717
h
#pragma once // Name: Astroneer-SDK, Version: 1.0.0 #ifdef _MSC_VER #pragma pack(push, 0x8) #endif namespace SDK { //--------------------------------------------------------------------------- // Classes //--------------------------------------------------------------------------- // BlueprintGeneratedClass Researchable_Crust_Tundra_01.Researchable_Crust_Tundra_01_C // 0x0000 (0x06D8 - 0x06D8) class AResearchable_Crust_Tundra_01_C : public AResearchable_Base_Mineral_C { public: static UClass* StaticClass() { static auto ptr = UObject::FindClass("BlueprintGeneratedClass Researchable_Crust_Tundra_01.Researchable_Crust_Tundra_01_C"); return ptr; } }; } #ifdef _MSC_VER #pragma pack(pop) #endif
[ "zp2kshield@gmail.com" ]
zp2kshield@gmail.com
f46daa30f47601711bf7674c8f0d41abd51c23bb
0f0e480eba320847b689c38f9ba885d81db1d166
/Map.hpp
38f21b84242964baf07ac598a8b2c977835b924c
[]
no_license
Jalapena42/std-map
78a9ed4d2d2fda9b4077dd10eaf8ef60ccbcc191
a8f0aef9c6285816bdf87af2d6e68e8c0b51e6e7
refs/heads/master
2022-02-16T17:05:26.649784
2019-09-01T02:21:01
2019-09-01T02:21:01
null
0
0
null
null
null
null
UTF-8
C++
false
false
21,449
hpp
#ifndef XXYYXX_MAP_HPP #define XXYYXX_MAP_HPP #include "SkipList.hpp" #include <stdexcept> namespace cs540 { template <typename T1, typename T2> class Map { private: SkipList <T1, T2> sl; size_t size_; public: class ConstIterator; // Forward decleration class Iterator { private: public: Node <T1, T2> * iter; Node <T1, T2> * header; Iterator (Node <T1, T2> * n, Node <T1, T2> * h) : iter(n), header(h) { }; Iterator () = delete; // Iterator (const Iterator &); // Copy Constructor -> (These might not be needed) // ~ Iterator (); // Destructor // Iterator & operator = (const Iterator &); // Copy Assignment Operator void operator = (const Iterator & it); Iterator operator ++ (int); // i++, post increment Iterator & operator ++ (); // ++i, pre increment Iterator operator -- (int); Iterator & operator -- (); bool operator == (const Iterator & it); // iter == iter bool operator == (const ConstIterator & it); // iter == const iter bool operator != (const Iterator & it); // iter != iter bool operator != (const ConstIterator & it); // iter != const iter std::pair <T1, T2> & operator * () const; std::pair <T1, T2> * operator -> () const; }; class ConstIterator { private: public: Node <T1, T2> * iter; Node <T1, T2> * header; ConstIterator (Node <T1, T2> * n, Node <T1, T2> * h) : iter(n), header(h) { }; ConstIterator () = delete; // ConstIterator (const Iterator &); // Copy Constructor -> (These might not be needed) // ~ ConstIterator (); // Destructor // ConstIterator & operator = (const Iterator &); // Copy Assignment Operator void operator = (const ConstIterator & it); ConstIterator operator ++ (int); // i++, post increment ConstIterator & operator ++ (); // ++i, pre increment ConstIterator operator -- (int); ConstIterator & operator -- (); bool operator == (const ConstIterator & it); // const iter == const iter bool operator == (const Iterator & it); // const iter == iter bool operator != (const ConstIterator & it); // const iter != const iter bool operator != (const Iterator & it); // const iter != iter const std::pair <T1, T2> & operator * () const; const std::pair <T1, T2> * operator -> () const; }; class ReverseIterator { private: public: Node <T1, T2> * iter; Node <T1, T2> * header; ReverseIterator (Node <T1, T2> * n, Node <T1, T2> * h) : iter(n), header(h) {}; ReverseIterator () = delete; // ConstIterator (const Iterator &); // ~ ConstIterator (); // ConstIterator & operator = (const Iterator &); void operator = (const ReverseIterator & it); ReverseIterator operator ++ (int); ReverseIterator & operator ++ (); ReverseIterator operator -- (int); ReverseIterator & operator -- (); bool operator == (const ReverseIterator &); bool operator != (const ReverseIterator &); std::pair <T1, T2> & operator * () const; std::pair <T1, T2> * operator -> () const; }; Map () : size_(0) { }; Map (const Map & m); // Copy constructor, These should be O(N) Map (std::initializer_list <std::pair <const T1, T2>> l); // Initializer list constructor Map & operator = (const Map & m); // Copy assignment operator ~ Map (); /***** FIX THIS ******/ size_t size () const; bool empty() const; std::pair <Iterator, bool> insert (std::pair <T1, T2> pair); template <typename IT_T> void insert (IT_T range_beg, IT_T range_end); /***** FIX THIS ******/ void erase (Iterator i); void erase (const T1 & key); void clear (); Iterator find (const T1 & key); Iterator begin (); Iterator end (); ConstIterator find (const T1 & key) const; ConstIterator begin() const; ConstIterator end() const; ReverseIterator rbegin (); ReverseIterator rend (); T2 & at (const T1 & key); const T2 & at (const T1 & key) const; T2 & operator [] (const T1 & key); bool operator == (const Map & m); bool operator != (const Map & m); bool operator < (const Map & m); }; /* * * MAP FUNCTIONS * */ template <typename T1, typename T2> Map <T1, T2> ::Map (const Map & m) // Copy constructor { this -> size_ = m.size_; this -> sl = m.sl; } template <typename T1, typename T2> Map <T1, T2> ::Map (std::initializer_list <std::pair <const T1, T2>> l) // Initializer list constructor { for (auto p : l) { this -> sl.insert(p); size_++; } } template <typename T1, typename T2> Map <T1, T2> ::~ Map () // Destructor { sl.clear(); if (sl.header != nullptr) { sl.header = nullptr; delete sl.header; } } template <typename T1, typename T2> Map <T1, T2> & Map <T1, T2> ::operator = (const Map & m) // Copy assignment operator { this -> size_ = m.size_; this -> sl = m.sl; return (* this); } template <typename T1, typename T2> size_t Map <T1, T2> ::size () const { return size_; } template <typename T1, typename T2> bool Map <T1, T2> ::empty() const { if (size_) return true; else return false; } template <typename T1, typename T2> std::pair <typename Map <T1, T2> ::Iterator, bool> Map <T1, T2> ::insert (std::pair <T1, T2> pair) { bool added = false; Node <T1, T2> * n = sl.insert(pair); if (n != nullptr) { size_++; added = true; } Iterator i(n, sl.header); std::pair <Iterator, bool> p = std::pair <Iterator, bool> (i, added); return p; } template <typename T1, typename T2> void Map <T1, T2> ::erase (Iterator i) { if (i.iter == nullptr) return; bool found = sl.remove(i.iter -> pair -> first); if (!found) throw std::out_of_range ("Erase(Iterator): Iter not Found !"); size_--; i.iter = nullptr; } template <typename T1, typename T2> void Map <T1, T2> ::erase (const T1 & key) { bool found = sl.remove(key); if (found) size_--; else throw std::out_of_range ("Erase(key): Key not Found !"); } template <typename T1, typename T2> void Map <T1, T2> ::clear () { sl.clear(); size_ = 0; } template <typename T1, typename T2> typename Map <T1, T2> ::Iterator Map <T1, T2> ::find (const T1 & key) { //std::cout << "Iter find called.\n"; Node <T1, T2> * n = sl.search(key); if (n == nullptr) return end(); else { Iterator i(n, sl.header); return i; } } template <typename T1, typename T2> typename Map <T1, T2> ::Iterator Map <T1, T2> ::begin () { Node <T1, T2> * n = sl.header -> forward[0]; Iterator i(n, sl.header); return i; } template <typename T1, typename T2> typename Map <T1, T2> ::Iterator Map <T1, T2> ::end () { Node <T1, T2> * n = sl.header -> forward[0]; while (n != NULL) n = n -> forward[0]; Iterator i(n, sl.header); return i; } template <typename T1, typename T2> typename Map <T1, T2> ::ConstIterator Map <T1, T2> ::find (const T1 & key) const { //std::cout << "Const Iter find called.\n"; Node <T1, T2> * n = sl.search(key); if (n == nullptr) return end(); else { ConstIterator i(n, sl.header); return i; } } template <typename T1, typename T2> typename Map <T1, T2> ::ConstIterator Map <T1, T2> ::begin () const { Node <T1, T2> * n = sl.header -> forward[0]; ConstIterator i(n, sl.header); return i; } template <typename T1, typename T2> typename Map <T1, T2> ::ConstIterator Map <T1, T2> ::end () const { Node <T1, T2> * n = sl.header -> forward[0]; while (n != NULL) n = n -> forward[0]; ConstIterator i(n, sl.header); return i; } template <typename T1, typename T2> typename Map <T1, T2> ::ReverseIterator Map <T1, T2> ::rbegin () { if (size_ == 0) assert(false); // Map has no elements if (size_ == 1) { Node <T1, T2> * n = sl.header -> forward[0]; ReverseIterator i(n, sl.header); return i; } Node <T1, T2> * n = sl.header -> forward[0]; Node <T1, T2> * n_next = n -> forward[0]; while (n_next != NULL) { n = n -> forward[0]; n_next = n_next -> forward[0]; } ReverseIterator i(n, sl.header); return i; } template <typename T1, typename T2> typename Map <T1, T2> ::ReverseIterator Map <T1, T2> ::rend () { Node <T1, T2> * n = sl.header; ReverseIterator i(n, sl.header); return i; } template <typename T1, typename T2> T2 & Map <T1, T2> ::at (const T1 & key) { Node <T1, T2> * n = sl.search(key); if (n == nullptr) throw std::out_of_range ("At(key): Key is not found !"); else return n -> pair -> second; } template <typename T1, typename T2> const T2 & Map <T1, T2> ::at (const T1 & key) const { Node <T1, T2> * n = sl.search(key); if (n == nullptr) throw std::out_of_range ("At(key) const: Key is not found !"); else return n -> pair -> second; } template <typename T1, typename T2> T2 & Map <T1, T2> ::operator [] (const T1 & key) { Node <T1, T2> * n = sl.search(key); if (n == nullptr) { T2 value = T2(); Node <T1, T2> * n = sl.insert(std::make_pair(key, value)); size_++; return n -> pair -> second; } else return n -> pair -> second; } template <typename T1, typename T2> bool Map <T1, T2> ::operator == (const Map <T1, T2> & m) { if (this -> size_ == m.size_ && this -> sl == m.sl) return true; else return false; } template <typename T1, typename T2> bool Map <T1, T2> ::operator != (const Map <T1, T2> & m) { if (this -> size_ != m.size_ || !(this -> sl == m.sl)) return true; else return false; } template <typename T1, typename T2> bool Map <T1, T2> ::operator < (const Map <T1, T2> & m) { size_t m1_size = this -> size_; size_t m2_size = m.size_; char res = this -> sl < m.sl; if (res == 0) return true; else if (res == 1) return false; else if (res == 2) { if (m1_size < m2_size) return true; else return false; } else assert(false); } /* * * ITERATOR FUNCTIONS * */ template <typename T1, typename T2> void Map <T1, T2> ::Iterator ::operator = (const Iterator & it) { this -> iter = it.iter; this -> header = it.header; } template <typename T1, typename T2> typename Map <T1, T2> ::Iterator Map <T1, T2> ::Iterator ::operator ++ (int) // i++, post increment { Node <T1, T2> * original = this -> iter; this -> iter = this -> iter -> forward[0]; return Iterator(original, this -> header); } template <typename T1, typename T2> typename Map <T1, T2> ::Iterator & Map <T1, T2> ::Iterator ::operator ++ () // ++i, pre increment { if (this -> iter == nullptr) return * this; if (this -> iter -> forward[0] == nullptr) { this -> iter = nullptr; return * this; } Node <T1, T2> * n = this -> iter -> forward[0]; this -> iter = n; return * this; } template <typename T1, typename T2> typename Map <T1, T2> ::Iterator Map <T1, T2> ::Iterator ::operator -- (int) { Node <T1, T2> * original = this -> iter; Node <T1, T2> * n = this -> header -> forward[0]; Node <T1, T2> * prev_n = nullptr; bool iter_from_end = false; while (n != this -> iter) { if (!n -> forward[0]) { iter_from_end = true; break; } prev_n = n; n = n -> forward[0]; } if (iter_from_end) { this -> iter = n; } else { this -> iter = prev_n; } return Iterator(original, this -> header); } template <typename T1, typename T2> typename Map <T1, T2> ::Iterator & Map <T1, T2> ::Iterator ::operator -- () { Node <T1, T2> * n = this -> header -> forward[0]; Node <T1, T2> * prev_n = nullptr; bool iter_from_end = false; while (n != this -> iter) { if (!n -> forward[0]) { iter_from_end = true; break; } prev_n = n; n = n -> forward[0]; } if (iter_from_end) { this -> iter = n; } else { this -> iter = prev_n; } return * this; } template <typename T1, typename T2> bool Map <T1, T2> ::Iterator ::operator == (const Iterator & it) { // If both nullptr, in case both sides are end() if (it.iter == nullptr && this -> iter == nullptr) return true; // If one is nullptr, in case one side is end() if (it.iter == nullptr || this -> iter == nullptr) return false; if (this -> iter -> pair -> first == it.iter -> pair -> first) return true; else return false; } template <typename T1, typename T2> bool Map <T1, T2> ::Iterator ::operator == (const ConstIterator & it) { // If both nullptr, in case both sides are end() if (it.iter == nullptr && this -> iter == nullptr) return true; // If one is nullptr, in case one side is end() if (it.iter == nullptr || this -> iter == nullptr) return false; if (this -> iter -> pair -> first == it.iter -> pair -> first) return true; else return false; } template <typename T1, typename T2> bool Map <T1, T2> ::Iterator ::operator != (const Iterator & it) { // In case of i++ resulting NULL is first operand to == if (this -> iter == nullptr) return false; // In case of map::end() is second operand to != if (it.iter == nullptr) return true; if (it.iter == nullptr || this -> iter == nullptr) return false; if (this -> iter -> pair -> first == it.iter -> pair -> first) return false; else return true; } template <typename T1, typename T2> bool Map <T1, T2> ::Iterator ::operator != (const ConstIterator & it) { // In case of i++ resulting NULL is first operand to == if (this -> iter == nullptr) return false; // In case of map::end() is second operand to != if (it.iter == nullptr) return true; if (it.iter == nullptr || this -> iter == nullptr) return false; if (this -> iter -> pair -> first == it.iter -> pair -> first) return false; else return true; } template <typename T1, typename T2> std::pair <T1, T2> & Map <T1, T2> ::Iterator ::operator * () const { return * (this -> iter -> pair); } template <typename T1, typename T2> std::pair <T1, T2> * Map <T1, T2> ::Iterator ::operator -> () const { return this -> iter -> pair; } /* * * CONST ITERATOR FUNCTIONS * */ template <typename T1, typename T2> void Map <T1, T2> ::ConstIterator ::operator = (const ConstIterator & it) { this -> iter = it.iter; this -> header = it.header; } template <typename T1, typename T2> typename Map <T1, T2> ::ConstIterator Map <T1, T2> ::ConstIterator ::operator ++ (int) // i++, post increment { Node <T1, T2> * original = this -> iter; this -> iter = this -> iter -> forward[0];; return ConstIterator(original, this -> header); } template <typename T1, typename T2> typename Map <T1, T2> ::ConstIterator & Map <T1, T2> ::ConstIterator ::operator ++ () // ++i, pre increment { Node <T1, T2> * n = this -> iter -> forward[0]; this -> iter = n; return * this; } template <typename T1, typename T2> typename Map <T1, T2> ::ConstIterator Map <T1, T2> ::ConstIterator ::operator -- (int) { Node <T1, T2> * original = this -> iter; Node <T1, T2> * n = this -> header -> forward[0]; Node <T1, T2> * prev_n = nullptr; bool iter_from_end = false; while (n != this -> iter) { if (!n -> forward[0]) { iter_from_end = true; break; } prev_n = n; n = n -> forward[0]; } if (iter_from_end) { this -> iter = n; } else { this -> iter = prev_n; } return ConstIterator(original, this -> header); } template <typename T1, typename T2> typename Map <T1, T2> ::ConstIterator & Map <T1, T2> ::ConstIterator ::operator -- () { Node <T1, T2> * n = this -> header -> forward[0]; Node <T1, T2> * prev_n = nullptr; bool iter_from_end = false; while (n != this -> iter) { if (!n -> forward[0]) { iter_from_end = true; break; } prev_n = n; n = n -> forward[0]; } if (iter_from_end) { this -> iter = n; } else { this -> iter = prev_n; } return * this; } template <typename T1, typename T2> bool Map <T1, T2> ::ConstIterator ::operator == (const ConstIterator & it) { // If both nullptr, in case both sides are end() if (it.iter == nullptr && this -> iter == nullptr) return true; // If one is nullptr, in case one side is end() if (it.iter == nullptr || this -> iter == nullptr) return false; if (this -> iter -> pair -> first == it.iter -> pair -> first) return true; else return false; } template <typename T1, typename T2> bool Map <T1, T2> ::ConstIterator ::operator == (const Iterator & it) { // If both nullptr, in case both sides are end() if (it.iter == nullptr && this -> iter == nullptr) return true; // If one is nullptr, in case one side is end() if (it.iter == nullptr || this -> iter == nullptr) return false; if (this -> iter -> pair -> first == it.iter -> pair -> first) return true; else return false; } template <typename T1, typename T2> bool Map <T1, T2> ::ConstIterator ::operator != (const ConstIterator & it) { // In case of i++ resulting NULL is first operand to == if (this -> iter == nullptr) return false; // In case of map::end() is second operand to != if (it.iter == nullptr) return true; if (it.iter == nullptr || this -> iter == nullptr) return false; if (this -> iter -> pair -> first == it.iter -> pair -> first) return false; else return true; } template <typename T1, typename T2> bool Map <T1, T2> ::ConstIterator ::operator != (const Iterator & it) { // In case of i++ resulting NULL is first operand to == if (this -> iter == nullptr) return false; // In case of map::end() is second operand to != if (it.iter == nullptr) return true; if (it.iter == nullptr || this -> iter == nullptr) return false; if (this -> iter -> pair -> first == it.iter -> pair -> first) return false; else return true; } template <typename T1, typename T2> const std::pair <T1, T2> & Map <T1, T2> ::ConstIterator ::operator * () const { return * (this -> iter -> pair); } template <typename T1, typename T2> const std::pair <T1, T2> * Map <T1, T2> ::ConstIterator ::operator -> () const { return this -> iter -> pair; } /* * * REVERSE ITERATOR FUNCTIONS * */ template <typename T1, typename T2> void Map <T1, T2> ::ReverseIterator ::operator = (const ReverseIterator & it) { this -> iter = it.iter; this -> header = it.header; } template <typename T1, typename T2> typename Map <T1, T2> ::ReverseIterator Map <T1, T2> ::ReverseIterator ::operator ++ (int) // i++, post increment (actually post decrement) { Node <T1, T2> * original = this -> iter; Node <T1, T2> * n = this -> header -> forward[0]; Node <T1, T2> * prev_n = nullptr; bool iter_from_end = false; while (n != this -> iter) { if (!n -> forward[0]) { iter_from_end = true; break; } prev_n = n; n = n -> forward[0]; } if (iter_from_end) { this -> iter = n; } else { this -> iter = prev_n; } return ReverseIterator(original, this -> header); } template <typename T1, typename T2> typename Map <T1, T2> ::ReverseIterator & Map <T1, T2> ::ReverseIterator ::operator ++ () // ++i, pre increment (Actually pre decrement) { Node <T1, T2> * n = this -> header -> forward[0]; Node <T1, T2> * prev_n = this -> header; bool iter_from_end = false; while (n != this -> iter) { if (!n -> forward[0]) { iter_from_end = true; break; } prev_n = n; n = n -> forward[0]; } if (iter_from_end) { this -> iter = n; } else { this -> iter = prev_n; } return * this; } template <typename T1, typename T2> typename Map <T1, T2> ::ReverseIterator Map <T1, T2> ::ReverseIterator ::operator -- (int) { Node <T1, T2> * original = this -> iter; this -> iter = this -> iter -> forward[0];; return ReverseIterator(original, this -> header); } template <typename T1, typename T2> typename Map <T1, T2> ::ReverseIterator & Map <T1, T2> ::ReverseIterator ::operator -- () { Node <T1, T2> * n = this -> iter -> forward[0]; this -> iter = n; return * this; } template <typename T1, typename T2> bool Map <T1, T2> ::ReverseIterator ::operator == (const ReverseIterator & it) { // If both nullptr, in case both sides are end() if (it.iter == nullptr && this -> iter == nullptr) return true; // If one is nullptr, in case one side is end() if (it.iter == nullptr || this -> iter == nullptr) return false; if (this -> iter -> pair -> first == it.iter -> pair -> first) return true; else return false; } template <typename T1, typename T2> bool Map <T1, T2> ::ReverseIterator ::operator != (const ReverseIterator & it) { // In case of i++ resulting NULL is first operand to == if (this -> iter == nullptr) return false; // In case of map::end() is second operand to != if (it.iter == nullptr) return true; if (this -> iter -> is_header && it.iter -> is_header) return false; // In case of map::rend() is second operand to != if (it.iter -> is_header) return true; if (this -> iter -> pair -> first == it.iter -> pair -> first) return false; else return true; } template <typename T1, typename T2> std::pair <T1, T2> & Map <T1, T2> ::ReverseIterator ::operator * () const { return * (this -> iter -> pair); } template <typename T1, typename T2> std::pair <T1, T2> * Map <T1, T2> ::ReverseIterator ::operator -> () const { return this -> iter -> pair; } } #endif
[ "aeker1@binghamton.edu" ]
aeker1@binghamton.edu
49592c6b10d7e5ec4e562111c3b2c06906179662
e5ae77536c1f37e716c1ff0fda0bd17420a23bd8
/adventure2019/lib/MiniGame/Games/TicTacToe/src/TicTacToe.cpp
4877a7fe3a8c0b5f3975b431bc956c9d55692898
[ "MIT" ]
permissive
Shimychu/Adventure2019-academic-
b7f9485d5112ef453eb60a16f41171aa1cb35eaa
73d9c00ffa8f8f1e735b02e8d764f4e2c4027556
refs/heads/master
2020-12-26T13:21:00.239557
2020-01-31T21:55:01
2020-01-31T21:55:01
null
0
0
null
null
null
null
UTF-8
C++
false
false
4,161
cpp
#include "TicTacToe.h" #include <boost/asio.hpp> #include <boost/algorithm/string.hpp> #include <boost/algorithm/string/split.hpp> std::string TicTacToe::getBoard() { return board.displayBoard(); } std::string TicTacToe::processInputBrowser(Input &input) { std::vector<Input> messageTokens; boost::split(messageTokens, input, boost::is_any_of(INPUT_SEPARATOR)); if (quit(input)) { return QUIT_CODE; } if (!initialSetupDone()) { return getInitialSetup(); } if (reset(messageTokens)) { reset(); } if (!reset(messageTokens) && !isGameOver) { processCoordinates(input, messageTokens); } return GAME_WINDOW + " \t" + getGameState() + "\n" + getBoard(); } std::string TicTacToe::processInputTerminal(const Input &input) { std::vector<Input> messageTokens; boost::split(messageTokens, input, boost::is_any_of(INPUT_SEPARATOR)); if (quit(input)) { return QUIT_CODE; } if (!initialSetupDone()) { return getInitialSetup(); } if (reset(messageTokens)) { reset(); } if (!reset(messageTokens) && !isGameOver) { processCoordinates(input, messageTokens); } return getGameState() + "\n" + getBoard(); } void TicTacToe::processCoordinates(const Input &input, std::vector<Input> messageTokens) { if (!containsCoordinateSeparator(input)) { return; } boost::split(messageTokens, input, boost::is_any_of(COORDINATE_SEPARATOR)); if (!correctNumCoordinates(messageTokens)) { return; } if (coordinatesEmpty(messageTokens)) { return; } if (coordinatesNumeric(messageTokens)) { makeMove(stoi(messageTokens[ROW]), stoi(messageTokens[COL])); } } void TicTacToe::makeMove(int row, int col) { if (validBoardMove(row, col)) { makePlayerMove(row, col); if (isWin()) { setXWin(); } else { if (getMoveNumber() == MOVES_TILL_TIE) { setGameTie(); } else { makeAIMove(); if (isWin()) { setOWin(); } } } } } void TicTacToe::makePlayerMove(int row, int col) { board.makeMove(x, row, col); incrementMoveNumber(); } void TicTacToe::makeAIMove() { ai.makeMove(board); incrementMoveNumber(); } void TicTacToe::reset() { this->currentGameState = GameState::PLAYING_GAMESTATE; setGameOver(false); this->moveNumber = 0; board.initializeBoard(); } bool TicTacToe::quit(const Input &input) { if ((input + INPUT_SEPARATOR) == QUIT_CODE) { reset(); return true; } return false; } bool TicTacToe::reset(const std::vector<Input> &messageTokens) { if (messageTokens[RESET_TOKEN] == RESET_CODE) { return true; } else { return false; } } bool TicTacToe::containsCoordinateSeparator(const Input &input) { if (input.find(COORDINATE_SEPARATOR) != std::string::npos) { return true; } else { return false; } } bool TicTacToe::correctNumCoordinates(const std::vector<Input> &messageTokens) { if (messageTokens.size() == NUM_COORDINATES) { return true; } else { return false; } } bool TicTacToe::coordinatesEmpty(const std::vector<Input> &messageTokens) { if (!((messageTokens[ROW]).empty()) && !((messageTokens[COL]).empty())) { return false; } else { return true; } } bool TicTacToe::coordinatesNumeric(const std::vector<Input> &messageTokens) { if (numeric(messageTokens[ROW]) && numeric(messageTokens[COL])) { return true; } else { return false; } } bool TicTacToe::validBoardMove(int row, int col) { if (!board.spotTaken(row, col)) { if (board.validBounds(row, col)) { return true; } } return false; } std::string TicTacToe::getInitialSetup() { //TODO nothing yet, will implement in phase 2 //TODO could implement feature to choose your piece of x or o //TODO Later add option to choose to play ai or another player return ""; }
[ "jta113@sfu.ca" ]
jta113@sfu.ca
e592d05eb689650669eadae0a2711a3f8ed120c1
60f3c2cad5ab7d55774c3a9be4c2fc664e4f0343
/LesserDemonstar/Asteroid.h
b2bc2d5c5d74cf10ddcb20003e0bf6ba5e83b91d
[]
no_license
popabogdannnn/LesserDemonstar
3681af6a0d977fe65be373b5e54538d4a8125d04
ae7dc5a5a77e93d26e4e8880cf437a9b9e6947b8
refs/heads/master
2022-08-01T15:00:42.483435
2020-05-17T13:55:39
2020-05-17T13:55:39
257,067,136
0
0
null
null
null
null
UTF-8
C++
false
false
228
h
#pragma once #include "Object.h" class Asteroid : public Object { private: int damage; int HP; public: void updateHP(int x); int getDamage(); int getHP(); Asteroid(float, float, float, sf::Texture); ~Asteroid(); };
[ "popa_bogdanioan@yahoo.com" ]
popa_bogdanioan@yahoo.com
e7f40b3c5e4ce01463dd392cd636840f79dc2643
1cbeefdc5889282184a81f2dfd0ef6a6855cfce4
/test/common/upstream/original_dst_cluster_test.cc
ce083b82f01bf25d102113a091821b58f4e595f6
[ "Apache-2.0", "LicenseRef-scancode-unknown-license-reference" ]
permissive
crazyproger/envoy
6e332775e6c451c11119f55dc48a530e09dfe009
3f21e3a038b07a29ae6fa3f4e9c00924d82e94e7
refs/heads/master
2021-01-19T20:14:59.185498
2017-08-24T00:09:37
2017-08-24T00:09:37
101,224,003
0
0
null
null
null
null
UTF-8
C++
false
false
15,274
cc
#include <chrono> #include <memory> #include <string> #include <tuple> #include <vector> #include "common/network/address_impl.h" #include "common/network/utility.h" #include "common/upstream/original_dst_cluster.h" #include "common/upstream/upstream_impl.h" #include "test/common/upstream/utility.h" #include "test/mocks/common.h" #include "test/mocks/network/mocks.h" #include "test/mocks/runtime/mocks.h" #include "test/mocks/ssl/mocks.h" #include "test/test_common/utility.h" #include "gmock/gmock.h" #include "gtest/gtest.h" using testing::Invoke; using testing::NiceMock; using testing::Return; using testing::ReturnRef; using testing::SaveArg; using testing::_; namespace Envoy { namespace Upstream { namespace OriginalDstClusterTest { class TestLoadBalancerContext : public LoadBalancerContext { public: TestLoadBalancerContext(const Network::Connection* connection) : connection_(connection) {} // Upstream::LoadBalancerContext Optional<uint64_t> hashKey() const override { return 0; } const Network::Connection* downstreamConnection() const override { return connection_; } Optional<uint64_t> hash_key_; const Network::Connection* connection_; }; class OriginalDstClusterTest : public testing::Test { public: // cleanup timer must be created before the cluster (in setup()), so that we can set expectations // on it. Ownership is transferred to the cluster at the cluster constructor, so the cluster will // take care of destructing it! OriginalDstClusterTest() : cleanup_timer_(new Event::MockTimer(&dispatcher_)) {} void setup(const std::string& json) { cluster_.reset(new OriginalDstCluster(parseClusterFromJson(json), runtime_, stats_store_, ssl_context_manager_, dispatcher_, false)); cluster_->addMemberUpdateCb( [&](const std::vector<HostSharedPtr>&, const std::vector<HostSharedPtr>&) -> void { membership_updated_.ready(); }); cluster_->setInitializedCb([&]() -> void { initialized_.ready(); }); } Stats::IsolatedStoreImpl stats_store_; Ssl::MockContextManager ssl_context_manager_; ClusterSharedPtr cluster_; ReadyWatcher membership_updated_; ReadyWatcher initialized_; NiceMock<Runtime::MockLoader> runtime_; NiceMock<Event::MockDispatcher> dispatcher_; Event::MockTimer* cleanup_timer_; }; TEST(OriginalDstClusterConfigTest, BadConfig) { std::string json = R"EOF( { "name": "name", "connect_timeout_ms": 250, "type": "original_dst", "lb_type": "original_dst_lb", "hosts": [{"url": "tcp://foo.bar.com:443"}] } )EOF"; // Help Emacs balance quotation marks: " EXPECT_THROW(parseClusterFromJson(json), EnvoyException); } TEST(OriginalDstClusterConfigTest, GoodConfig) { std::string json = R"EOF( { "name": "name", "connect_timeout_ms": 250, "type": "original_dst", "lb_type": "original_dst_lb", "cleanup_interval_ms": 1000 } )EOF"; // Help Emacs balance quotation marks: " EXPECT_TRUE(parseClusterFromJson(json).has_cleanup_interval()); } TEST_F(OriginalDstClusterTest, CleanupInterval) { std::string json = R"EOF( { "name": "name", "connect_timeout_ms": 250, "type": "original_dst", "lb_type": "original_dst_lb", "cleanup_interval_ms": 1000 } )EOF"; // Help Emacs balance quotation marks: " EXPECT_CALL(initialized_, ready()); EXPECT_CALL(membership_updated_, ready()).Times(0); EXPECT_CALL(*cleanup_timer_, enableTimer(std::chrono::milliseconds(1000))); setup(json); EXPECT_EQ(0UL, cluster_->hosts().size()); EXPECT_EQ(0UL, cluster_->healthyHosts().size()); } TEST_F(OriginalDstClusterTest, NoContext) { std::string json = R"EOF( { "name": "name", "connect_timeout_ms": 1250, "type": "original_dst", "lb_type": "original_dst_lb" } )EOF"; EXPECT_CALL(initialized_, ready()); EXPECT_CALL(membership_updated_, ready()).Times(0); EXPECT_CALL(*cleanup_timer_, enableTimer(_)); setup(json); EXPECT_EQ(0UL, cluster_->hosts().size()); EXPECT_EQ(0UL, cluster_->healthyHosts().size()); EXPECT_EQ(0UL, cluster_->hostsPerZone().size()); EXPECT_EQ(0UL, cluster_->healthyHostsPerZone().size()); // No downstream connection => no host. { TestLoadBalancerContext lb_context(nullptr); OriginalDstCluster::LoadBalancer lb(*cluster_, cluster_); EXPECT_CALL(dispatcher_, post(_)).Times(0); HostConstSharedPtr host = lb.chooseHost(&lb_context); EXPECT_EQ(host, nullptr); } // Downstream connection is not using original dst => no host. { NiceMock<Network::MockConnection> connection; TestLoadBalancerContext lb_context(&connection); EXPECT_CALL(connection, usingOriginalDst()).WillOnce(Return(false)); // First argument is normally the reference to the ThreadLocalCluster's HostSet, but in these // tests we do not have the thread local clusters, so we pass a reference to the HostSet of the // primary cluster. The implementation handles both cases the same. OriginalDstCluster::LoadBalancer lb(*cluster_, cluster_); EXPECT_CALL(dispatcher_, post(_)).Times(0); HostConstSharedPtr host = lb.chooseHost(&lb_context); EXPECT_EQ(host, nullptr); } // No host for non-IP address { NiceMock<Network::MockConnection> connection; TestLoadBalancerContext lb_context(&connection); Network::Address::PipeInstance local_address("unix://foo"); EXPECT_CALL(connection, localAddress()).WillRepeatedly(ReturnRef(local_address)); EXPECT_CALL(connection, usingOriginalDst()).WillRepeatedly(Return(true)); OriginalDstCluster::LoadBalancer lb(*cluster_, cluster_); EXPECT_CALL(dispatcher_, post(_)).Times(0); HostConstSharedPtr host = lb.chooseHost(&lb_context); EXPECT_EQ(host, nullptr); } } TEST_F(OriginalDstClusterTest, Membership) { std::string json = R"EOF( { "name": "name", "connect_timeout_ms": 1250, "type": "original_dst", "lb_type": "original_dst_lb" } )EOF"; EXPECT_CALL(initialized_, ready()); EXPECT_CALL(*cleanup_timer_, enableTimer(_)); setup(json); EXPECT_EQ(0UL, cluster_->hosts().size()); EXPECT_EQ(0UL, cluster_->healthyHosts().size()); EXPECT_EQ(0UL, cluster_->hostsPerZone().size()); EXPECT_EQ(0UL, cluster_->healthyHostsPerZone().size()); EXPECT_CALL(membership_updated_, ready()); // Host gets the local address of the downstream connection. NiceMock<Network::MockConnection> connection; TestLoadBalancerContext lb_context(&connection); Network::Address::Ipv4Instance local_address("10.10.11.11"); EXPECT_CALL(connection, localAddress()).WillRepeatedly(ReturnRef(local_address)); EXPECT_CALL(connection, usingOriginalDst()).WillRepeatedly(Return(true)); OriginalDstCluster::LoadBalancer lb(*cluster_, cluster_); Event::PostCb post_cb; EXPECT_CALL(dispatcher_, post(_)).WillOnce(SaveArg<0>(&post_cb)); HostConstSharedPtr host = lb.chooseHost(&lb_context); post_cb(); auto cluster_hosts = cluster_->hosts(); ASSERT_NE(host, nullptr); EXPECT_EQ(local_address, *host->address()); EXPECT_EQ(1UL, cluster_->hosts().size()); EXPECT_EQ(1UL, cluster_->healthyHosts().size()); EXPECT_EQ(0UL, cluster_->hostsPerZone().size()); EXPECT_EQ(0UL, cluster_->healthyHostsPerZone().size()); EXPECT_EQ(host, cluster_->hosts()[0]); EXPECT_EQ(local_address, *cluster_->hosts()[0]->address()); // Same host is returned on the 2nd call HostConstSharedPtr host2 = lb.chooseHost(&lb_context); EXPECT_EQ(host2, host); // Make host time out, no membership changes happen on the first timeout. ASSERT_EQ(1UL, cluster_->hosts().size()); EXPECT_EQ(true, cluster_->hosts()[0]->used()); EXPECT_CALL(*cleanup_timer_, enableTimer(_)); cleanup_timer_->callback_(); EXPECT_EQ(cluster_hosts, cluster_->hosts()); // hosts vector remains the same // host gets removed on the 2nd timeout. ASSERT_EQ(1UL, cluster_->hosts().size()); EXPECT_EQ(false, cluster_->hosts()[0]->used()); EXPECT_CALL(*cleanup_timer_, enableTimer(_)); EXPECT_CALL(membership_updated_, ready()); cleanup_timer_->callback_(); EXPECT_NE(cluster_hosts, cluster_->hosts()); // hosts vector changes EXPECT_EQ(0UL, cluster_->hosts().size()); cluster_hosts = cluster_->hosts(); // New host gets created EXPECT_CALL(membership_updated_, ready()); EXPECT_CALL(dispatcher_, post(_)).WillOnce(SaveArg<0>(&post_cb)); HostConstSharedPtr host3 = lb.chooseHost(&lb_context); post_cb(); EXPECT_NE(host3, nullptr); EXPECT_NE(host3, host); EXPECT_NE(cluster_hosts, cluster_->hosts()); // hosts vector changes EXPECT_EQ(1UL, cluster_->hosts().size()); EXPECT_EQ(host3, cluster_->hosts()[0]); } TEST_F(OriginalDstClusterTest, Membership2) { std::string json = R"EOF( { "name": "name", "connect_timeout_ms": 1250, "type": "original_dst", "lb_type": "original_dst_lb" } )EOF"; EXPECT_CALL(initialized_, ready()); EXPECT_CALL(*cleanup_timer_, enableTimer(_)); setup(json); EXPECT_EQ(0UL, cluster_->hosts().size()); EXPECT_EQ(0UL, cluster_->healthyHosts().size()); EXPECT_EQ(0UL, cluster_->hostsPerZone().size()); EXPECT_EQ(0UL, cluster_->healthyHostsPerZone().size()); // Host gets the local address of the downstream connection. NiceMock<Network::MockConnection> connection1; TestLoadBalancerContext lb_context1(&connection1); Network::Address::Ipv4Instance local_address1("10.10.11.11"); EXPECT_CALL(connection1, localAddress()).WillRepeatedly(ReturnRef(local_address1)); EXPECT_CALL(connection1, usingOriginalDst()).WillRepeatedly(Return(true)); NiceMock<Network::MockConnection> connection2; TestLoadBalancerContext lb_context2(&connection2); Network::Address::Ipv4Instance local_address2("10.10.11.12"); EXPECT_CALL(connection2, localAddress()).WillRepeatedly(ReturnRef(local_address2)); EXPECT_CALL(connection2, usingOriginalDst()).WillRepeatedly(Return(true)); OriginalDstCluster::LoadBalancer lb(*cluster_, cluster_); EXPECT_CALL(membership_updated_, ready()); Event::PostCb post_cb; EXPECT_CALL(dispatcher_, post(_)).WillOnce(SaveArg<0>(&post_cb)); HostConstSharedPtr host1 = lb.chooseHost(&lb_context1); post_cb(); ASSERT_NE(host1, nullptr); EXPECT_EQ(local_address1, *host1->address()); EXPECT_CALL(membership_updated_, ready()); EXPECT_CALL(dispatcher_, post(_)).WillOnce(SaveArg<0>(&post_cb)); HostConstSharedPtr host2 = lb.chooseHost(&lb_context2); post_cb(); ASSERT_NE(host2, nullptr); EXPECT_EQ(local_address2, *host2->address()); EXPECT_EQ(2UL, cluster_->hosts().size()); EXPECT_EQ(2UL, cluster_->healthyHosts().size()); EXPECT_EQ(0UL, cluster_->hostsPerZone().size()); EXPECT_EQ(0UL, cluster_->healthyHostsPerZone().size()); EXPECT_EQ(host1, cluster_->hosts()[0]); EXPECT_EQ(local_address1, *cluster_->hosts()[0]->address()); EXPECT_EQ(host2, cluster_->hosts()[1]); EXPECT_EQ(local_address2, *cluster_->hosts()[1]->address()); auto cluster_hosts = cluster_->hosts(); // Make hosts time out, no membership changes happen on the first timeout. ASSERT_EQ(2UL, cluster_->hosts().size()); EXPECT_EQ(true, cluster_->hosts()[0]->used()); EXPECT_EQ(true, cluster_->hosts()[1]->used()); EXPECT_CALL(*cleanup_timer_, enableTimer(_)); cleanup_timer_->callback_(); EXPECT_EQ(cluster_hosts, cluster_->hosts()); // hosts vector remains the same // both hosts get removed on the 2nd timeout. ASSERT_EQ(2UL, cluster_->hosts().size()); EXPECT_EQ(false, cluster_->hosts()[0]->used()); EXPECT_EQ(false, cluster_->hosts()[1]->used()); EXPECT_CALL(*cleanup_timer_, enableTimer(_)); EXPECT_CALL(membership_updated_, ready()); cleanup_timer_->callback_(); EXPECT_NE(cluster_hosts, cluster_->hosts()); // hosts vector changes EXPECT_EQ(0UL, cluster_->hosts().size()); } TEST_F(OriginalDstClusterTest, Connection) { std::string json = R"EOF( { "name": "name", "connect_timeout_ms": 1250, "type": "original_dst", "lb_type": "original_dst_lb" } )EOF"; EXPECT_CALL(initialized_, ready()); EXPECT_CALL(*cleanup_timer_, enableTimer(_)); setup(json); EXPECT_EQ(0UL, cluster_->hosts().size()); EXPECT_EQ(0UL, cluster_->healthyHosts().size()); EXPECT_EQ(0UL, cluster_->hostsPerZone().size()); EXPECT_EQ(0UL, cluster_->healthyHostsPerZone().size()); EXPECT_CALL(membership_updated_, ready()); // Connection to the host is made to the downstream connection's local address. NiceMock<Network::MockConnection> connection; TestLoadBalancerContext lb_context(&connection); Network::Address::Ipv6Instance local_address("FD00::1"); EXPECT_CALL(connection, localAddress()).WillRepeatedly(ReturnRef(local_address)); EXPECT_CALL(connection, usingOriginalDst()).WillRepeatedly(Return(true)); OriginalDstCluster::LoadBalancer lb(*cluster_, cluster_); Event::PostCb post_cb; EXPECT_CALL(dispatcher_, post(_)).WillOnce(SaveArg<0>(&post_cb)); HostConstSharedPtr host = lb.chooseHost(&lb_context); post_cb(); ASSERT_NE(host, nullptr); EXPECT_EQ(local_address, *host->address()); EXPECT_CALL(dispatcher_, createClientConnection_(PointeesEq(&local_address))) .WillOnce(Return(new NiceMock<Network::MockClientConnection>())); host->createConnection(dispatcher_); } TEST_F(OriginalDstClusterTest, MultipleClusters) { std::string json = R"EOF( { "name": "name", "connect_timeout_ms": 1250, "type": "original_dst", "lb_type": "original_dst_lb" } )EOF"; EXPECT_CALL(initialized_, ready()); EXPECT_CALL(*cleanup_timer_, enableTimer(_)); setup(json); HostSetImpl second; cluster_->addMemberUpdateCb([&](const std::vector<HostSharedPtr>& added, const std::vector<HostSharedPtr>& removed) -> void { // Update second hostset accordingly; HostVectorSharedPtr new_hosts(new std::vector<HostSharedPtr>(cluster_->hosts())); HostVectorSharedPtr healthy_hosts(new std::vector<HostSharedPtr>(cluster_->hosts())); const HostListsConstSharedPtr empty_host_lists{new std::vector<std::vector<HostSharedPtr>>()}; second.updateHosts(new_hosts, healthy_hosts, empty_host_lists, empty_host_lists, added, removed); }); EXPECT_CALL(membership_updated_, ready()); // Connection to the host is made to the downstream connection's local address. NiceMock<Network::MockConnection> connection; TestLoadBalancerContext lb_context(&connection); Network::Address::Ipv6Instance local_address("FD00::1"); EXPECT_CALL(connection, localAddress()).WillRepeatedly(ReturnRef(local_address)); EXPECT_CALL(connection, usingOriginalDst()).WillRepeatedly(Return(true)); OriginalDstCluster::LoadBalancer lb1(*cluster_, cluster_); OriginalDstCluster::LoadBalancer lb2(second, cluster_); Event::PostCb post_cb; EXPECT_CALL(dispatcher_, post(_)).WillOnce(SaveArg<0>(&post_cb)); HostConstSharedPtr host = lb1.chooseHost(&lb_context); post_cb(); ASSERT_NE(host, nullptr); EXPECT_EQ(local_address, *host->address()); EXPECT_EQ(1UL, cluster_->hosts().size()); // Check that lb2 also gets updated EXPECT_EQ(1UL, second.hosts().size()); EXPECT_EQ(host, cluster_->hosts()[0]); EXPECT_EQ(host, second.hosts()[0]); } } // namespace OriginalDstClusterTest } // namespace Upstream } // namespace Envoy
[ "mattklein123@users.noreply.github.com" ]
mattklein123@users.noreply.github.com
307f1d1d7cc39b7fa51b7fdede8d3948218e0896
ded15d1597d5e55d08afabccd300894e0aea482c
/pvz_gui/pvz_gui/market.h
76c79157375cb67d16d633bb6f6a04fd1dce5c28
[]
no_license
nju-xy/PVZ
1a2d7ef2f5dc502ee92453f99a555034ef863e78
b26ea6f99e2cd5678b4937f1fbd7fea885877f58
refs/heads/main
2023-02-12T21:51:44.182218
2021-01-09T02:19:03
2021-01-09T02:19:03
310,612,960
0
0
null
null
null
null
UTF-8
C++
false
false
1,518
h
// // Created by xy on 2020/11/7. // #ifndef PVZ_MARKET_H #define PVZ_MARKET_H #include "common.h" #include "plants.h" class Item { private: int cd; int timer; int cost; int plant_no; public: Item(int _no, int _cost, double _cd) : plant_no(_no), cd(int(_cd * 10)), cost(_cost), timer(0) {} int get_cd() const { return cd; } int get_cost() const { return cost; } int get_timer() const { return timer; } Plant *get_plant() const; int get_no() const { return plant_no; } void update_timer() { if (timer > 0) timer--; } void reset_timer() { timer = cd; } }; class Market { private: bool shovel; vector<Item *> items; Item *chosen_item; // 商店中选中的植物 public: Market(); void choose_shovel() { shovel = 1; } void cancel_choose_shovel() { shovel = 0; } bool get_shovel() const { return shovel; } int get_number() const { return items.size(); } void choose_item(int no) { chosen_item = items[no]; } Item *get_chosen() const { return chosen_item; } void cancel_choose() { chosen_item = nullptr; } int number_of_items() const { return items.size(); } Item *get_item_k(int k) const { if (k < items.size()) return items[k]; assert(0); return nullptr; } }; #endif //PVZ_MARKET_H
[ "171240536@smail.nju.edu.cn" ]
171240536@smail.nju.edu.cn
aec1815a59caa234285f855419625f2f6e324a8c
fa7a76c7646ced5f8ffbd009d4a21f05e187495a
/UVA Problems/Test/TEST/LazyPropagation.cpp
aa510229115ec4f405a387337cc2eeb0486bd7e0
[]
no_license
osama-afifi/Online-Judges-Solutions
5273018f8373f377b9dafa85521c97beaa6574a0
f49130f8ccbe8abc062f1b51a204edb819699b3a
refs/heads/master
2021-01-10T19:54:34.488053
2015-04-23T21:42:54
2015-04-23T21:42:54
21,754,051
0
0
null
null
null
null
UTF-8
C++
false
false
1,338
cpp
//#include <iostream> //#include <cstdio> //#include <vector> //#include <string> //#include <cmath> //using namespace std; // // ////Range Minimum Query //#define N 100000 //int arr[N+9]; //int L[N<<3]; //int T[N<<3]; // //void init(int i, int j, int node) //{ // if(i>j)return; // if(i==j) // { // T[node] = arr[i]; // return; // } // init(i, (i+j)/2 , node*2); // init(((i+j)/2)+1 , j , node*2); // T[node] = T[node*2] + T[node*2+1]; //} //void update(int i, int j ,int x , int y , int v, int node) //{ // if(i>y || j<x || i>j)return; // if(L[node]!=0) // { // T[node]+=L[node]; // if(i!=j) // not leaf // { // L[node*2]=L[node]; // L[node*2+1]=L[node]; // } // L[node]=0; // } // if(i>=x&&j<=y) // { // T[node]+=v; // if(i!=j) // { // L[node*2]=v; // L[node*2+1]=v; // } // return; // } // // update(i, (i+j)/2 ,x,y,v,node*2); // update(((i+j)/2)+1, j ,x,y,v,node*2+1); // T[node] = T[node*2]+T[node*2+1]; // //} //int query(int i , int j , int x , int y , int node) //{ // if(i>y || j<x || i>j)return; // if(L[node]!=0) // { // T[node]+=L[node]; // if(i!=j) // not leaf // { // L[node*2]=L[node]; // L[node*2+1]=L[node]; // } // L[node]=0; // } // if(i>=x&&j<=y) // return T[node]; // return query(i,(i+j)/2, x, y , node*2) + query(((i+j)/2)+1,j, x, y , node*2+1); //} // //int main() //{ // // // //}
[ "osama.egt@gmail.com" ]
osama.egt@gmail.com
ad304f257ef57e88c8d23c59532b810c448526fd
b9fec31908e40cfc52400e13f847ac0f4e8c48bb
/matlab tests/DH/libs/opengl/src/CFBORender.cpp
8e55499348b1e277d2585b9601579dd5a9ed90e3
[ "BSD-3-Clause" ]
permissive
DavidRicardoGarcia/measurement-of-angles
e7ff8e9f15a9e50bc57c0d45f5807fcf1fa0ec74
ab16ca937262e05bf9f82dca5f425791cacfa459
refs/heads/master
2021-07-16T12:30:53.523173
2021-06-24T07:16:49
2021-06-24T07:16:49
122,414,543
2
1
null
null
null
null
UTF-8
C++
false
false
9,254
cpp
/* +---------------------------------------------------------------------------+ | Mobile Robot Programming Toolkit (MRPT) | | http://www.mrpt.org/ | | | | Copyright (c) 2005-2017, Individual contributors, see AUTHORS file | | See: http://www.mrpt.org/Authors - All rights reserved. | | Released under BSD License. See details in http://www.mrpt.org/License | +---------------------------------------------------------------------------+ */ #include "opengl-precomp.h" // Precompiled header #include <mrpt/opengl/CFBORender.h> #include "opengl_internals.h" using namespace std; using namespace mrpt; using namespace mrpt::utils; using namespace mrpt::opengl; /*--------------------------------------------------------------- Constructor ---------------------------------------------------------------*/ CFBORender::CFBORender( unsigned int width, unsigned int height, const bool skip_glut_window ) : m_width(width), m_height(height), m_win_used(!skip_glut_window), m_default_bk_color(.6f,.6f,.6f,1) { #if MRPT_HAS_OPENCV && MRPT_HAS_OPENGL_GLUT MRPT_START if (m_win_used) { // check a previous initialization of the GLUT if(!glutGet(GLUT_INIT_STATE)) { // create the context (a little trick) int argc = 1; char *argv[1] = { NULL }; glutInit(&argc, argv); } // create a hidden window m_win = glutCreateWindow("CFBORender"); glutHideWindow(); } // call after creating the hidden window if(!isExtensionSupported("GL_EXT_framebuffer_object")) THROW_EXCEPTION("Framebuffer Object extension unsupported"); // In win32 we have to load the pointers to the functions: #ifdef MRPT_OS_WINDOWS glGenFramebuffersEXT = (PFNGLGENFRAMEBUFFERSEXTPROC)wglGetProcAddress("glGenFramebuffersEXT"); glDeleteFramebuffersEXT = (PFNGLDELETEFRAMEBUFFERSEXTPROC)wglGetProcAddress("glDeleteFramebuffersEXT"); glBindFramebufferEXT = (PFNGLBINDFRAMEBUFFEREXTPROC)wglGetProcAddress("glBindFramebufferEXT"); glFramebufferTexture2DEXT = (PFNGLFRAMEBUFFERTEXTURE2DEXTPROC) wglGetProcAddress("glFramebufferTexture2DEXT"); ASSERT_(glGenFramebuffersEXT!=NULL) ASSERT_(glDeleteFramebuffersEXT!=NULL) ASSERT_(glBindFramebufferEXT!=NULL) ASSERT_(glFramebufferTexture2DEXT!=NULL) #endif // gen the frambuffer object (FBO), similar manner as a texture glGenFramebuffersEXT(1, &m_fbo); // bind the framebuffer, fbo, so operations will now occur on it glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, m_fbo); // change viewport size (in pixels) glViewport(0, 0, m_width, m_height); // make a texture glGenTextures(1, &m_tex); // initialize texture that will store the framebuffer image const GLenum texTarget = # if defined(GL_TEXTURE_RECTANGLE_NV) GL_TEXTURE_RECTANGLE_NV; # elif defined(GL_TEXTURE_RECTANGLE_ARB) GL_TEXTURE_RECTANGLE_ARB; # else GL_TEXTURE_RECTANGLE_EXT; # endif glBindTexture(texTarget, m_tex); glTexImage2D(texTarget, 0, GL_RGB, m_width, m_height, 0, GL_RGB, GL_UNSIGNED_BYTE, NULL); // bind this texture to the current framebuffer obj. as color_attachement_0 glFramebufferTexture2DEXT(GL_FRAMEBUFFER_EXT, GL_COLOR_ATTACHMENT0_EXT, texTarget, m_tex, 0); //'unbind' the frambuffer object, so subsequent drawing ops are not drawn into the FBO. // '0' means "windowing system provided framebuffer glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, 0); MRPT_END //#else // THROW_EXCEPTION("MRPT compiled without OpenCV and/or OpenGL support!!") #endif } /*--------------------------------------------------------------- Destructor: ---------------------------------------------------------------*/ CFBORender::~CFBORender() { #if MRPT_HAS_OPENGL_GLUT // delete the current texture, the framebuffer object and the GLUT window glDeleteTextures(1, &m_tex); glDeleteFramebuffersEXT(1, &m_fbo); if (m_win_used) glutDestroyWindow(m_win); #endif } /*--------------------------------------------------------------- Set the scene camera ---------------------------------------------------------------*/ void CFBORender::setCamera( const COpenGLScene& scene, const CCamera& camera ) { MRPT_START scene.getViewport("main")->getCamera() = camera; MRPT_END } /*--------------------------------------------------------------- Get the scene camera ---------------------------------------------------------------*/ CCamera& CFBORender::getCamera( const COpenGLScene& scene ) { MRPT_START return scene.getViewport("main")->getCamera(); MRPT_END } /*--------------------------------------------------------------- Render the scene and get the rendered rgb image. This function resizes the image buffer if it is necessary ---------------------------------------------------------------*/ void CFBORender::getFrame( const COpenGLScene& scene, CImage& buffer ) { #if MRPT_HAS_OPENCV && MRPT_HAS_OPENGL_GLUT MRPT_START // resize the buffer if it is necessary if( buffer.getWidth() != static_cast<size_t>(m_width) || buffer.getHeight() != static_cast<size_t>(m_height) || buffer.getChannelCount() != 3 || buffer.isOriginTopLeft() != false ) { buffer.resize(m_width, m_height, 3, false); } // Go on. getFrame2(scene,buffer);; MRPT_END #else MRPT_UNUSED_PARAM(scene); MRPT_UNUSED_PARAM(buffer); #endif } /*--------------------------------------------------------------- Render the scene and get the rendered rgb image. This function does not resize the image buffer. ---------------------------------------------------------------*/ void CFBORender::getFrame2( const COpenGLScene& scene, CImage& buffer ) { #if MRPT_HAS_OPENGL_GLUT MRPT_START // check the buffer size ASSERT_EQUAL_( buffer.getWidth(), static_cast<size_t>(m_width) ) ASSERT_EQUAL_( buffer.getHeight(),static_cast<size_t>(m_height) ) ASSERT_EQUAL_( buffer.getChannelCount(), 3 ) ASSERT_EQUAL_( buffer.isOriginTopLeft(), false ) // bind the framebuffer, fbo, so operations will now occur on it glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, m_fbo); glClearColor(m_default_bk_color.R,m_default_bk_color.G,m_default_bk_color.B,m_default_bk_color.A); // Render opengl objects: // --------------------------- scene.render(); // If any, draw the 2D text messages: // ---------------------------------- render_text_messages(m_width,m_height); // TODO NOTE: This should fail if the image has padding bytes. See glPixelStore() etc. glReadPixels(0, 0, m_width, m_height, GL_BGR_EXT, GL_UNSIGNED_BYTE, buffer(0,0) ); //'unbind' the frambuffer object, so subsequent drawing ops are not drawn into the FBO. // '0' means "windowing system provided framebuffer glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, 0); MRPT_END #else MRPT_UNUSED_PARAM(scene); MRPT_UNUSED_PARAM(buffer); #endif } /*--------------------------------------------------------------- Resize the image size ---------------------------------------------------------------*/ void CFBORender::resize( unsigned int width, unsigned int height ) { #if MRPT_HAS_OPENCV && MRPT_HAS_OPENGL_GLUT MRPT_START // update members m_width = width; m_height = height; // bind the framebuffer, fbo, so operations will now occur on it glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, m_fbo); // change viewport size (in pixels) glViewport(0, 0, m_width, m_height); // change texture size const GLenum texTarget = # if defined(GL_TEXTURE_RECTANGLE_NV) GL_TEXTURE_RECTANGLE_NV; # elif defined(GL_TEXTURE_RECTANGLE_ARB) GL_TEXTURE_RECTANGLE_ARB; # else GL_TEXTURE_RECTANGLE_EXT; # endif glBindTexture(texTarget, m_tex); glTexImage2D(texTarget, 0, GL_RGB, m_width, m_height, 0, GL_RGB, GL_UNSIGNED_BYTE, NULL); //'unbind' the frambuffer object, so subsequent drawing ops are not drawn into the FBO. // '0' means "windowing system provided framebuffer glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, 0); MRPT_END //#else // THROW_EXCEPTION("MRPT compiled without OpenCV and/or OpenGL support!!") #else MRPT_UNUSED_PARAM(width); MRPT_UNUSED_PARAM(height); #endif } /*--------------------------------------------------------------- Provide information on Framebuffer object extension ---------------------------------------------------------------*/ int CFBORender::isExtensionSupported( const char* extension ) { #if MRPT_HAS_OPENGL_GLUT MRPT_START const GLubyte *extensions = NULL; const GLubyte *start; GLubyte *where, *terminator; /* Extension names should not have spaces. */ where = (GLubyte *) strchr(extension, ' '); if (where || *extension == '\0') return 0; extensions = glGetString(GL_EXTENSIONS); /* It takes a bit of care to be fool-proof about parsing the OpenGL extensions string. Don't be fooled by sub-strings, etc. */ start = extensions; for (;;) { where = (GLubyte *) strstr((const char *) start, extension); if (!where) break; terminator = where + strlen(extension); if (where == start || *(where - 1) == ' ') if (*terminator == ' ' || *terminator == '\0') return 1; start = terminator; } MRPT_END //#else // THROW_EXCEPTION("MRPT compiled without OpenGL support!!") #else MRPT_UNUSED_PARAM(extension); #endif return 0; }
[ "davidnf.44@gmail.com" ]
davidnf.44@gmail.com
21f95fda2e882d875e7654044d4f966ce462d7e7
54c9a08deccb6ca465205b6d99554795b2c8ea19
/Aulas/P2/7(SobreCarga)/SobrecargaAtribuicaoConstrutorCopiaPonteiro/main.cpp
400da275d79fdca7e176e90d8745efbf5262fbdc
[]
no_license
PabloFreitas-lib/Prog3-UFSC-2018.2
2ff284bb4ec43702090b95f0745b6cef5f35f907
6950628e0819d4f472f4bc11b54873c0ebe76c00
refs/heads/master
2022-06-27T04:00:43.487131
2019-09-08T03:44:54
2019-09-08T03:44:54
195,102,246
0
0
null
null
null
null
UTF-8
C++
false
false
1,018
cpp
#include <iostream> using namespace std; #define SEM_CONSTRUTOR_COPIA false #define SEM_ATRIBUICAO false class Inteiro { int *recurso; public: Inteiro(int x = 0) { recurso = new int(x); } #if SEM_CONSTRUTOR_COPIA == false Inteiro(const Inteiro &outro) //Construtor de cópia { recurso = new int; *recurso = *(outro.recurso); } #endif // SEM_CONSTRUTOR_COPIA ~Inteiro() { delete recurso; } #if SEM_ATRIBUICAO == false const Inteiro &operator=(const Inteiro &outro) { *recurso = *(outro.recurso); return *this; } #endif // SEM_CONSTRUTOR_COPIA int getValor(void) { return *recurso; } }; int main() { Inteiro inteiro1(5); Inteiro inteiro2(inteiro1); Inteiro inteiro3; inteiro3 = inteiro1; cout << "inteiro 1 = " << inteiro1.getValor() << endl; cout << "inteiro 2 = " << inteiro2.getValor() << endl; cout << "inteiro 3 = " << inteiro3.getValor() << endl; return 0; }
[ "pablo.santos1999@gmail.com" ]
pablo.santos1999@gmail.com
91ee05ebd58edebfe9d47750557dd59d055e9be9
1b0598f5ebb90fa09c49350b0b20ff8ae720eb2d
/Temp/il2cppOutput/il2cppOutput/Il2CppCompilerCalculateTypeValues_18Table.cpp
8554ba9692a2ee020e3268b93f316616144c0b82
[]
no_license
casterfile/B-elotero-En-gage
566921bf96f156f04d999ef6ff84da2a30d5746e
6815be07e4269d8b261faac4c94199435a57fdff
refs/heads/master
2020-09-25T16:35:23.632084
2019-12-05T09:08:32
2019-12-05T09:08:32
226,044,808
0
0
null
null
null
null
UTF-8
C++
false
false
48,196
cpp
#include "il2cpp-config.h" #ifndef _MSC_VER # include <alloca.h> #else # include <malloc.h> #endif #include <cstring> #include <string.h> #include <stdio.h> #include <cmath> #include <limits> #include <assert.h> #include <stdint.h> #include "il2cpp-class-internals.h" #include "codegen/il2cpp-codegen.h" #include "il2cpp-object-internals.h" // System.String struct String_t; // UnityEngine.Object struct Object_t631007953; // UnityEngine.GameObject struct GameObject_t1113636619; // System.Collections.Generic.List`1<UnityEngine.Analytics.TriggerRule> struct List_1_t3418373063; // System.Char[] struct CharU5BU5D_t3528271667; // System.Void struct Void_t1185182177; // System.Reflection.MethodInfo struct MethodInfo_t; // System.DelegateData struct DelegateData_t1677132599; // UnityEngine.Analytics.TrackableField struct TrackableField_t1772682203; // UnityEngine.Analytics.ValueProperty struct ValueProperty_t1868393739; // UnityEngine.Analytics.TriggerListContainer struct TriggerListContainer_t2032715483; // UnityEngine.Analytics.EventTrigger/OnTrigger struct OnTrigger_t4184125570; // UnityEngine.Analytics.TriggerMethod struct TriggerMethod_t582536534; // System.IAsyncResult struct IAsyncResult_t767004451; // System.AsyncCallback struct AsyncCallback_t3962456242; // UnityEngine.UI.Text struct Text_t1901882714; #ifndef U3CMODULEU3E_T692745546_H #define U3CMODULEU3E_T692745546_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // <Module> struct U3CModuleU3E_t692745546 { public: public: }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // U3CMODULEU3E_T692745546_H #ifndef RUNTIMEOBJECT_H #define RUNTIMEOBJECT_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // System.Object #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // RUNTIMEOBJECT_H #ifndef FIELDWITHTARGET_T3058750293_H #define FIELDWITHTARGET_T3058750293_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // UnityEngine.Analytics.TrackableProperty/FieldWithTarget struct FieldWithTarget_t3058750293 : public RuntimeObject { public: // System.String UnityEngine.Analytics.TrackableProperty/FieldWithTarget::m_ParamName String_t* ___m_ParamName_0; // UnityEngine.Object UnityEngine.Analytics.TrackableProperty/FieldWithTarget::m_Target Object_t631007953 * ___m_Target_1; // System.String UnityEngine.Analytics.TrackableProperty/FieldWithTarget::m_FieldPath String_t* ___m_FieldPath_2; // System.String UnityEngine.Analytics.TrackableProperty/FieldWithTarget::m_TypeString String_t* ___m_TypeString_3; // System.Boolean UnityEngine.Analytics.TrackableProperty/FieldWithTarget::m_DoStatic bool ___m_DoStatic_4; // System.String UnityEngine.Analytics.TrackableProperty/FieldWithTarget::m_StaticString String_t* ___m_StaticString_5; public: inline static int32_t get_offset_of_m_ParamName_0() { return static_cast<int32_t>(offsetof(FieldWithTarget_t3058750293, ___m_ParamName_0)); } inline String_t* get_m_ParamName_0() const { return ___m_ParamName_0; } inline String_t** get_address_of_m_ParamName_0() { return &___m_ParamName_0; } inline void set_m_ParamName_0(String_t* value) { ___m_ParamName_0 = value; Il2CppCodeGenWriteBarrier((&___m_ParamName_0), value); } inline static int32_t get_offset_of_m_Target_1() { return static_cast<int32_t>(offsetof(FieldWithTarget_t3058750293, ___m_Target_1)); } inline Object_t631007953 * get_m_Target_1() const { return ___m_Target_1; } inline Object_t631007953 ** get_address_of_m_Target_1() { return &___m_Target_1; } inline void set_m_Target_1(Object_t631007953 * value) { ___m_Target_1 = value; Il2CppCodeGenWriteBarrier((&___m_Target_1), value); } inline static int32_t get_offset_of_m_FieldPath_2() { return static_cast<int32_t>(offsetof(FieldWithTarget_t3058750293, ___m_FieldPath_2)); } inline String_t* get_m_FieldPath_2() const { return ___m_FieldPath_2; } inline String_t** get_address_of_m_FieldPath_2() { return &___m_FieldPath_2; } inline void set_m_FieldPath_2(String_t* value) { ___m_FieldPath_2 = value; Il2CppCodeGenWriteBarrier((&___m_FieldPath_2), value); } inline static int32_t get_offset_of_m_TypeString_3() { return static_cast<int32_t>(offsetof(FieldWithTarget_t3058750293, ___m_TypeString_3)); } inline String_t* get_m_TypeString_3() const { return ___m_TypeString_3; } inline String_t** get_address_of_m_TypeString_3() { return &___m_TypeString_3; } inline void set_m_TypeString_3(String_t* value) { ___m_TypeString_3 = value; Il2CppCodeGenWriteBarrier((&___m_TypeString_3), value); } inline static int32_t get_offset_of_m_DoStatic_4() { return static_cast<int32_t>(offsetof(FieldWithTarget_t3058750293, ___m_DoStatic_4)); } inline bool get_m_DoStatic_4() const { return ___m_DoStatic_4; } inline bool* get_address_of_m_DoStatic_4() { return &___m_DoStatic_4; } inline void set_m_DoStatic_4(bool value) { ___m_DoStatic_4 = value; } inline static int32_t get_offset_of_m_StaticString_5() { return static_cast<int32_t>(offsetof(FieldWithTarget_t3058750293, ___m_StaticString_5)); } inline String_t* get_m_StaticString_5() const { return ___m_StaticString_5; } inline String_t** get_address_of_m_StaticString_5() { return &___m_StaticString_5; } inline void set_m_StaticString_5(String_t* value) { ___m_StaticString_5 = value; Il2CppCodeGenWriteBarrier((&___m_StaticString_5), value); } }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // FIELDWITHTARGET_T3058750293_H #ifndef TRIGGERMETHOD_T582536534_H #define TRIGGERMETHOD_T582536534_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // UnityEngine.Analytics.TriggerMethod struct TriggerMethod_t582536534 : public RuntimeObject { public: public: }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // TRIGGERMETHOD_T582536534_H #ifndef VALUETYPE_T3640485471_H #define VALUETYPE_T3640485471_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // System.ValueType struct ValueType_t3640485471 : public RuntimeObject { public: public: }; #ifdef __clang__ #pragma clang diagnostic pop #endif // Native definition for P/Invoke marshalling of System.ValueType struct ValueType_t3640485471_marshaled_pinvoke { }; // Native definition for COM marshalling of System.ValueType struct ValueType_t3640485471_marshaled_com { }; #endif // VALUETYPE_T3640485471_H #ifndef TRACKABLETRIGGER_T621205209_H #define TRACKABLETRIGGER_T621205209_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // UnityEngine.Analytics.TrackableTrigger struct TrackableTrigger_t621205209 : public RuntimeObject { public: // UnityEngine.GameObject UnityEngine.Analytics.TrackableTrigger::m_Target GameObject_t1113636619 * ___m_Target_0; // System.String UnityEngine.Analytics.TrackableTrigger::m_MethodPath String_t* ___m_MethodPath_1; public: inline static int32_t get_offset_of_m_Target_0() { return static_cast<int32_t>(offsetof(TrackableTrigger_t621205209, ___m_Target_0)); } inline GameObject_t1113636619 * get_m_Target_0() const { return ___m_Target_0; } inline GameObject_t1113636619 ** get_address_of_m_Target_0() { return &___m_Target_0; } inline void set_m_Target_0(GameObject_t1113636619 * value) { ___m_Target_0 = value; Il2CppCodeGenWriteBarrier((&___m_Target_0), value); } inline static int32_t get_offset_of_m_MethodPath_1() { return static_cast<int32_t>(offsetof(TrackableTrigger_t621205209, ___m_MethodPath_1)); } inline String_t* get_m_MethodPath_1() const { return ___m_MethodPath_1; } inline String_t** get_address_of_m_MethodPath_1() { return &___m_MethodPath_1; } inline void set_m_MethodPath_1(String_t* value) { ___m_MethodPath_1 = value; Il2CppCodeGenWriteBarrier((&___m_MethodPath_1), value); } }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // TRACKABLETRIGGER_T621205209_H #ifndef TRIGGERLISTCONTAINER_T2032715483_H #define TRIGGERLISTCONTAINER_T2032715483_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // UnityEngine.Analytics.TriggerListContainer struct TriggerListContainer_t2032715483 : public RuntimeObject { public: // System.Collections.Generic.List`1<UnityEngine.Analytics.TriggerRule> UnityEngine.Analytics.TriggerListContainer::m_Rules List_1_t3418373063 * ___m_Rules_0; public: inline static int32_t get_offset_of_m_Rules_0() { return static_cast<int32_t>(offsetof(TriggerListContainer_t2032715483, ___m_Rules_0)); } inline List_1_t3418373063 * get_m_Rules_0() const { return ___m_Rules_0; } inline List_1_t3418373063 ** get_address_of_m_Rules_0() { return &___m_Rules_0; } inline void set_m_Rules_0(List_1_t3418373063 * value) { ___m_Rules_0 = value; Il2CppCodeGenWriteBarrier((&___m_Rules_0), value); } }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // TRIGGERLISTCONTAINER_T2032715483_H #ifndef ENUM_T4135868527_H #define ENUM_T4135868527_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // System.Enum struct Enum_t4135868527 : public ValueType_t3640485471 { public: public: }; struct Enum_t4135868527_StaticFields { public: // System.Char[] System.Enum::split_char CharU5BU5D_t3528271667* ___split_char_0; public: inline static int32_t get_offset_of_split_char_0() { return static_cast<int32_t>(offsetof(Enum_t4135868527_StaticFields, ___split_char_0)); } inline CharU5BU5D_t3528271667* get_split_char_0() const { return ___split_char_0; } inline CharU5BU5D_t3528271667** get_address_of_split_char_0() { return &___split_char_0; } inline void set_split_char_0(CharU5BU5D_t3528271667* value) { ___split_char_0 = value; Il2CppCodeGenWriteBarrier((&___split_char_0), value); } }; #ifdef __clang__ #pragma clang diagnostic pop #endif // Native definition for P/Invoke marshalling of System.Enum struct Enum_t4135868527_marshaled_pinvoke { }; // Native definition for COM marshalling of System.Enum struct Enum_t4135868527_marshaled_com { }; #endif // ENUM_T4135868527_H #ifndef VOID_T1185182177_H #define VOID_T1185182177_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // System.Void struct Void_t1185182177 { public: public: }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // VOID_T1185182177_H #ifndef INTPTR_T_H #define INTPTR_T_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // System.IntPtr struct IntPtr_t { public: // System.Void* System.IntPtr::m_value void* ___m_value_0; public: inline static int32_t get_offset_of_m_value_0() { return static_cast<int32_t>(offsetof(IntPtr_t, ___m_value_0)); } inline void* get_m_value_0() const { return ___m_value_0; } inline void** get_address_of_m_value_0() { return &___m_value_0; } inline void set_m_value_0(void* value) { ___m_value_0 = value; } }; struct IntPtr_t_StaticFields { public: // System.IntPtr System.IntPtr::Zero intptr_t ___Zero_1; public: inline static int32_t get_offset_of_Zero_1() { return static_cast<int32_t>(offsetof(IntPtr_t_StaticFields, ___Zero_1)); } inline intptr_t get_Zero_1() const { return ___Zero_1; } inline intptr_t* get_address_of_Zero_1() { return &___Zero_1; } inline void set_Zero_1(intptr_t value) { ___Zero_1 = value; } }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // INTPTR_T_H #ifndef DELEGATE_T1188392813_H #define DELEGATE_T1188392813_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // System.Delegate struct Delegate_t1188392813 : public RuntimeObject { public: // System.IntPtr System.Delegate::method_ptr Il2CppMethodPointer ___method_ptr_0; // System.IntPtr System.Delegate::invoke_impl intptr_t ___invoke_impl_1; // System.Object System.Delegate::m_target RuntimeObject * ___m_target_2; // System.IntPtr System.Delegate::method intptr_t ___method_3; // System.IntPtr System.Delegate::delegate_trampoline intptr_t ___delegate_trampoline_4; // System.IntPtr System.Delegate::method_code intptr_t ___method_code_5; // System.Reflection.MethodInfo System.Delegate::method_info MethodInfo_t * ___method_info_6; // System.Reflection.MethodInfo System.Delegate::original_method_info MethodInfo_t * ___original_method_info_7; // System.DelegateData System.Delegate::data DelegateData_t1677132599 * ___data_8; public: inline static int32_t get_offset_of_method_ptr_0() { return static_cast<int32_t>(offsetof(Delegate_t1188392813, ___method_ptr_0)); } inline Il2CppMethodPointer get_method_ptr_0() const { return ___method_ptr_0; } inline Il2CppMethodPointer* get_address_of_method_ptr_0() { return &___method_ptr_0; } inline void set_method_ptr_0(Il2CppMethodPointer value) { ___method_ptr_0 = value; } inline static int32_t get_offset_of_invoke_impl_1() { return static_cast<int32_t>(offsetof(Delegate_t1188392813, ___invoke_impl_1)); } inline intptr_t get_invoke_impl_1() const { return ___invoke_impl_1; } inline intptr_t* get_address_of_invoke_impl_1() { return &___invoke_impl_1; } inline void set_invoke_impl_1(intptr_t value) { ___invoke_impl_1 = value; } inline static int32_t get_offset_of_m_target_2() { return static_cast<int32_t>(offsetof(Delegate_t1188392813, ___m_target_2)); } inline RuntimeObject * get_m_target_2() const { return ___m_target_2; } inline RuntimeObject ** get_address_of_m_target_2() { return &___m_target_2; } inline void set_m_target_2(RuntimeObject * value) { ___m_target_2 = value; Il2CppCodeGenWriteBarrier((&___m_target_2), value); } inline static int32_t get_offset_of_method_3() { return static_cast<int32_t>(offsetof(Delegate_t1188392813, ___method_3)); } inline intptr_t get_method_3() const { return ___method_3; } inline intptr_t* get_address_of_method_3() { return &___method_3; } inline void set_method_3(intptr_t value) { ___method_3 = value; } inline static int32_t get_offset_of_delegate_trampoline_4() { return static_cast<int32_t>(offsetof(Delegate_t1188392813, ___delegate_trampoline_4)); } inline intptr_t get_delegate_trampoline_4() const { return ___delegate_trampoline_4; } inline intptr_t* get_address_of_delegate_trampoline_4() { return &___delegate_trampoline_4; } inline void set_delegate_trampoline_4(intptr_t value) { ___delegate_trampoline_4 = value; } inline static int32_t get_offset_of_method_code_5() { return static_cast<int32_t>(offsetof(Delegate_t1188392813, ___method_code_5)); } inline intptr_t get_method_code_5() const { return ___method_code_5; } inline intptr_t* get_address_of_method_code_5() { return &___method_code_5; } inline void set_method_code_5(intptr_t value) { ___method_code_5 = value; } inline static int32_t get_offset_of_method_info_6() { return static_cast<int32_t>(offsetof(Delegate_t1188392813, ___method_info_6)); } inline MethodInfo_t * get_method_info_6() const { return ___method_info_6; } inline MethodInfo_t ** get_address_of_method_info_6() { return &___method_info_6; } inline void set_method_info_6(MethodInfo_t * value) { ___method_info_6 = value; Il2CppCodeGenWriteBarrier((&___method_info_6), value); } inline static int32_t get_offset_of_original_method_info_7() { return static_cast<int32_t>(offsetof(Delegate_t1188392813, ___original_method_info_7)); } inline MethodInfo_t * get_original_method_info_7() const { return ___original_method_info_7; } inline MethodInfo_t ** get_address_of_original_method_info_7() { return &___original_method_info_7; } inline void set_original_method_info_7(MethodInfo_t * value) { ___original_method_info_7 = value; Il2CppCodeGenWriteBarrier((&___original_method_info_7), value); } inline static int32_t get_offset_of_data_8() { return static_cast<int32_t>(offsetof(Delegate_t1188392813, ___data_8)); } inline DelegateData_t1677132599 * get_data_8() const { return ___data_8; } inline DelegateData_t1677132599 ** get_address_of_data_8() { return &___data_8; } inline void set_data_8(DelegateData_t1677132599 * value) { ___data_8 = value; Il2CppCodeGenWriteBarrier((&___data_8), value); } }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // DELEGATE_T1188392813_H #ifndef OBJECT_T631007953_H #define OBJECT_T631007953_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // UnityEngine.Object struct Object_t631007953 : public RuntimeObject { public: // System.IntPtr UnityEngine.Object::m_CachedPtr intptr_t ___m_CachedPtr_0; public: inline static int32_t get_offset_of_m_CachedPtr_0() { return static_cast<int32_t>(offsetof(Object_t631007953, ___m_CachedPtr_0)); } inline intptr_t get_m_CachedPtr_0() const { return ___m_CachedPtr_0; } inline intptr_t* get_address_of_m_CachedPtr_0() { return &___m_CachedPtr_0; } inline void set_m_CachedPtr_0(intptr_t value) { ___m_CachedPtr_0 = value; } }; struct Object_t631007953_StaticFields { public: // System.Int32 UnityEngine.Object::OffsetOfInstanceIDInCPlusPlusObject int32_t ___OffsetOfInstanceIDInCPlusPlusObject_1; public: inline static int32_t get_offset_of_OffsetOfInstanceIDInCPlusPlusObject_1() { return static_cast<int32_t>(offsetof(Object_t631007953_StaticFields, ___OffsetOfInstanceIDInCPlusPlusObject_1)); } inline int32_t get_OffsetOfInstanceIDInCPlusPlusObject_1() const { return ___OffsetOfInstanceIDInCPlusPlusObject_1; } inline int32_t* get_address_of_OffsetOfInstanceIDInCPlusPlusObject_1() { return &___OffsetOfInstanceIDInCPlusPlusObject_1; } inline void set_OffsetOfInstanceIDInCPlusPlusObject_1(int32_t value) { ___OffsetOfInstanceIDInCPlusPlusObject_1 = value; } }; #ifdef __clang__ #pragma clang diagnostic pop #endif // Native definition for P/Invoke marshalling of UnityEngine.Object struct Object_t631007953_marshaled_pinvoke { intptr_t ___m_CachedPtr_0; }; // Native definition for COM marshalling of UnityEngine.Object struct Object_t631007953_marshaled_com { intptr_t ___m_CachedPtr_0; }; #endif // OBJECT_T631007953_H #ifndef TRIGGERTYPE_T105272677_H #define TRIGGERTYPE_T105272677_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // UnityEngine.Analytics.TriggerType struct TriggerType_t105272677 { public: // System.Int32 UnityEngine.Analytics.TriggerType::value__ int32_t ___value___1; public: inline static int32_t get_offset_of_value___1() { return static_cast<int32_t>(offsetof(TriggerType_t105272677, ___value___1)); } inline int32_t get_value___1() const { return ___value___1; } inline int32_t* get_address_of_value___1() { return &___value___1; } inline void set_value___1(int32_t value) { ___value___1 = value; } }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // TRIGGERTYPE_T105272677_H #ifndef TRIGGEROPERATOR_T3611898925_H #define TRIGGEROPERATOR_T3611898925_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // UnityEngine.Analytics.TriggerOperator struct TriggerOperator_t3611898925 { public: // System.Int32 UnityEngine.Analytics.TriggerOperator::value__ int32_t ___value___1; public: inline static int32_t get_offset_of_value___1() { return static_cast<int32_t>(offsetof(TriggerOperator_t3611898925, ___value___1)); } inline int32_t get_value___1() const { return ___value___1; } inline int32_t* get_address_of_value___1() { return &___value___1; } inline void set_value___1(int32_t value) { ___value___1 = value; } }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // TRIGGEROPERATOR_T3611898925_H #ifndef TRIGGERLIFECYCLEEVENT_T3193146760_H #define TRIGGERLIFECYCLEEVENT_T3193146760_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // UnityEngine.Analytics.TriggerLifecycleEvent struct TriggerLifecycleEvent_t3193146760 { public: // System.Int32 UnityEngine.Analytics.TriggerLifecycleEvent::value__ int32_t ___value___1; public: inline static int32_t get_offset_of_value___1() { return static_cast<int32_t>(offsetof(TriggerLifecycleEvent_t3193146760, ___value___1)); } inline int32_t get_value___1() const { return ___value___1; } inline int32_t* get_address_of_value___1() { return &___value___1; } inline void set_value___1(int32_t value) { ___value___1 = value; } }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // TRIGGERLIFECYCLEEVENT_T3193146760_H #ifndef TRIGGERBOOL_T501031542_H #define TRIGGERBOOL_T501031542_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // UnityEngine.Analytics.TriggerBool struct TriggerBool_t501031542 { public: // System.Int32 UnityEngine.Analytics.TriggerBool::value__ int32_t ___value___1; public: inline static int32_t get_offset_of_value___1() { return static_cast<int32_t>(offsetof(TriggerBool_t501031542, ___value___1)); } inline int32_t get_value___1() const { return ___value___1; } inline int32_t* get_address_of_value___1() { return &___value___1; } inline void set_value___1(int32_t value) { ___value___1 = value; } }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // TRIGGERBOOL_T501031542_H #ifndef TRIGGERRULE_T1946298321_H #define TRIGGERRULE_T1946298321_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // UnityEngine.Analytics.TriggerRule struct TriggerRule_t1946298321 : public RuntimeObject { public: // UnityEngine.Analytics.TrackableField UnityEngine.Analytics.TriggerRule::m_Target TrackableField_t1772682203 * ___m_Target_0; // UnityEngine.Analytics.TriggerOperator UnityEngine.Analytics.TriggerRule::m_Operator int32_t ___m_Operator_1; // UnityEngine.Analytics.ValueProperty UnityEngine.Analytics.TriggerRule::m_Value ValueProperty_t1868393739 * ___m_Value_2; // UnityEngine.Analytics.ValueProperty UnityEngine.Analytics.TriggerRule::m_Value2 ValueProperty_t1868393739 * ___m_Value2_3; public: inline static int32_t get_offset_of_m_Target_0() { return static_cast<int32_t>(offsetof(TriggerRule_t1946298321, ___m_Target_0)); } inline TrackableField_t1772682203 * get_m_Target_0() const { return ___m_Target_0; } inline TrackableField_t1772682203 ** get_address_of_m_Target_0() { return &___m_Target_0; } inline void set_m_Target_0(TrackableField_t1772682203 * value) { ___m_Target_0 = value; Il2CppCodeGenWriteBarrier((&___m_Target_0), value); } inline static int32_t get_offset_of_m_Operator_1() { return static_cast<int32_t>(offsetof(TriggerRule_t1946298321, ___m_Operator_1)); } inline int32_t get_m_Operator_1() const { return ___m_Operator_1; } inline int32_t* get_address_of_m_Operator_1() { return &___m_Operator_1; } inline void set_m_Operator_1(int32_t value) { ___m_Operator_1 = value; } inline static int32_t get_offset_of_m_Value_2() { return static_cast<int32_t>(offsetof(TriggerRule_t1946298321, ___m_Value_2)); } inline ValueProperty_t1868393739 * get_m_Value_2() const { return ___m_Value_2; } inline ValueProperty_t1868393739 ** get_address_of_m_Value_2() { return &___m_Value_2; } inline void set_m_Value_2(ValueProperty_t1868393739 * value) { ___m_Value_2 = value; Il2CppCodeGenWriteBarrier((&___m_Value_2), value); } inline static int32_t get_offset_of_m_Value2_3() { return static_cast<int32_t>(offsetof(TriggerRule_t1946298321, ___m_Value2_3)); } inline ValueProperty_t1868393739 * get_m_Value2_3() const { return ___m_Value2_3; } inline ValueProperty_t1868393739 ** get_address_of_m_Value2_3() { return &___m_Value2_3; } inline void set_m_Value2_3(ValueProperty_t1868393739 * value) { ___m_Value2_3 = value; Il2CppCodeGenWriteBarrier((&___m_Value2_3), value); } }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // TRIGGERRULE_T1946298321_H #ifndef MULTICASTDELEGATE_T_H #define MULTICASTDELEGATE_T_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // System.MulticastDelegate struct MulticastDelegate_t : public Delegate_t1188392813 { public: // System.MulticastDelegate System.MulticastDelegate::prev MulticastDelegate_t * ___prev_9; // System.MulticastDelegate System.MulticastDelegate::kpm_next MulticastDelegate_t * ___kpm_next_10; public: inline static int32_t get_offset_of_prev_9() { return static_cast<int32_t>(offsetof(MulticastDelegate_t, ___prev_9)); } inline MulticastDelegate_t * get_prev_9() const { return ___prev_9; } inline MulticastDelegate_t ** get_address_of_prev_9() { return &___prev_9; } inline void set_prev_9(MulticastDelegate_t * value) { ___prev_9 = value; Il2CppCodeGenWriteBarrier((&___prev_9), value); } inline static int32_t get_offset_of_kpm_next_10() { return static_cast<int32_t>(offsetof(MulticastDelegate_t, ___kpm_next_10)); } inline MulticastDelegate_t * get_kpm_next_10() const { return ___kpm_next_10; } inline MulticastDelegate_t ** get_address_of_kpm_next_10() { return &___kpm_next_10; } inline void set_kpm_next_10(MulticastDelegate_t * value) { ___kpm_next_10 = value; Il2CppCodeGenWriteBarrier((&___kpm_next_10), value); } }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // MULTICASTDELEGATE_T_H #ifndef COMPONENT_T1923634451_H #define COMPONENT_T1923634451_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // UnityEngine.Component struct Component_t1923634451 : public Object_t631007953 { public: public: }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // COMPONENT_T1923634451_H #ifndef EVENTTRIGGER_T2527451695_H #define EVENTTRIGGER_T2527451695_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // UnityEngine.Analytics.EventTrigger struct EventTrigger_t2527451695 : public RuntimeObject { public: // System.Boolean UnityEngine.Analytics.EventTrigger::m_IsTriggerExpanded bool ___m_IsTriggerExpanded_0; // UnityEngine.Analytics.TriggerType UnityEngine.Analytics.EventTrigger::m_Type int32_t ___m_Type_1; // UnityEngine.Analytics.TriggerLifecycleEvent UnityEngine.Analytics.EventTrigger::m_LifecycleEvent int32_t ___m_LifecycleEvent_2; // System.Boolean UnityEngine.Analytics.EventTrigger::m_ApplyRules bool ___m_ApplyRules_3; // UnityEngine.Analytics.TriggerListContainer UnityEngine.Analytics.EventTrigger::m_Rules TriggerListContainer_t2032715483 * ___m_Rules_4; // UnityEngine.Analytics.TriggerBool UnityEngine.Analytics.EventTrigger::m_TriggerBool int32_t ___m_TriggerBool_5; // System.Single UnityEngine.Analytics.EventTrigger::m_InitTime float ___m_InitTime_6; // System.Single UnityEngine.Analytics.EventTrigger::m_RepeatTime float ___m_RepeatTime_7; // System.Int32 UnityEngine.Analytics.EventTrigger::m_Repetitions int32_t ___m_Repetitions_8; // System.Int32 UnityEngine.Analytics.EventTrigger::repetitionCount int32_t ___repetitionCount_9; // UnityEngine.Analytics.EventTrigger/OnTrigger UnityEngine.Analytics.EventTrigger::m_TriggerFunction OnTrigger_t4184125570 * ___m_TriggerFunction_10; // UnityEngine.Analytics.TriggerMethod UnityEngine.Analytics.EventTrigger::m_Method TriggerMethod_t582536534 * ___m_Method_11; public: inline static int32_t get_offset_of_m_IsTriggerExpanded_0() { return static_cast<int32_t>(offsetof(EventTrigger_t2527451695, ___m_IsTriggerExpanded_0)); } inline bool get_m_IsTriggerExpanded_0() const { return ___m_IsTriggerExpanded_0; } inline bool* get_address_of_m_IsTriggerExpanded_0() { return &___m_IsTriggerExpanded_0; } inline void set_m_IsTriggerExpanded_0(bool value) { ___m_IsTriggerExpanded_0 = value; } inline static int32_t get_offset_of_m_Type_1() { return static_cast<int32_t>(offsetof(EventTrigger_t2527451695, ___m_Type_1)); } inline int32_t get_m_Type_1() const { return ___m_Type_1; } inline int32_t* get_address_of_m_Type_1() { return &___m_Type_1; } inline void set_m_Type_1(int32_t value) { ___m_Type_1 = value; } inline static int32_t get_offset_of_m_LifecycleEvent_2() { return static_cast<int32_t>(offsetof(EventTrigger_t2527451695, ___m_LifecycleEvent_2)); } inline int32_t get_m_LifecycleEvent_2() const { return ___m_LifecycleEvent_2; } inline int32_t* get_address_of_m_LifecycleEvent_2() { return &___m_LifecycleEvent_2; } inline void set_m_LifecycleEvent_2(int32_t value) { ___m_LifecycleEvent_2 = value; } inline static int32_t get_offset_of_m_ApplyRules_3() { return static_cast<int32_t>(offsetof(EventTrigger_t2527451695, ___m_ApplyRules_3)); } inline bool get_m_ApplyRules_3() const { return ___m_ApplyRules_3; } inline bool* get_address_of_m_ApplyRules_3() { return &___m_ApplyRules_3; } inline void set_m_ApplyRules_3(bool value) { ___m_ApplyRules_3 = value; } inline static int32_t get_offset_of_m_Rules_4() { return static_cast<int32_t>(offsetof(EventTrigger_t2527451695, ___m_Rules_4)); } inline TriggerListContainer_t2032715483 * get_m_Rules_4() const { return ___m_Rules_4; } inline TriggerListContainer_t2032715483 ** get_address_of_m_Rules_4() { return &___m_Rules_4; } inline void set_m_Rules_4(TriggerListContainer_t2032715483 * value) { ___m_Rules_4 = value; Il2CppCodeGenWriteBarrier((&___m_Rules_4), value); } inline static int32_t get_offset_of_m_TriggerBool_5() { return static_cast<int32_t>(offsetof(EventTrigger_t2527451695, ___m_TriggerBool_5)); } inline int32_t get_m_TriggerBool_5() const { return ___m_TriggerBool_5; } inline int32_t* get_address_of_m_TriggerBool_5() { return &___m_TriggerBool_5; } inline void set_m_TriggerBool_5(int32_t value) { ___m_TriggerBool_5 = value; } inline static int32_t get_offset_of_m_InitTime_6() { return static_cast<int32_t>(offsetof(EventTrigger_t2527451695, ___m_InitTime_6)); } inline float get_m_InitTime_6() const { return ___m_InitTime_6; } inline float* get_address_of_m_InitTime_6() { return &___m_InitTime_6; } inline void set_m_InitTime_6(float value) { ___m_InitTime_6 = value; } inline static int32_t get_offset_of_m_RepeatTime_7() { return static_cast<int32_t>(offsetof(EventTrigger_t2527451695, ___m_RepeatTime_7)); } inline float get_m_RepeatTime_7() const { return ___m_RepeatTime_7; } inline float* get_address_of_m_RepeatTime_7() { return &___m_RepeatTime_7; } inline void set_m_RepeatTime_7(float value) { ___m_RepeatTime_7 = value; } inline static int32_t get_offset_of_m_Repetitions_8() { return static_cast<int32_t>(offsetof(EventTrigger_t2527451695, ___m_Repetitions_8)); } inline int32_t get_m_Repetitions_8() const { return ___m_Repetitions_8; } inline int32_t* get_address_of_m_Repetitions_8() { return &___m_Repetitions_8; } inline void set_m_Repetitions_8(int32_t value) { ___m_Repetitions_8 = value; } inline static int32_t get_offset_of_repetitionCount_9() { return static_cast<int32_t>(offsetof(EventTrigger_t2527451695, ___repetitionCount_9)); } inline int32_t get_repetitionCount_9() const { return ___repetitionCount_9; } inline int32_t* get_address_of_repetitionCount_9() { return &___repetitionCount_9; } inline void set_repetitionCount_9(int32_t value) { ___repetitionCount_9 = value; } inline static int32_t get_offset_of_m_TriggerFunction_10() { return static_cast<int32_t>(offsetof(EventTrigger_t2527451695, ___m_TriggerFunction_10)); } inline OnTrigger_t4184125570 * get_m_TriggerFunction_10() const { return ___m_TriggerFunction_10; } inline OnTrigger_t4184125570 ** get_address_of_m_TriggerFunction_10() { return &___m_TriggerFunction_10; } inline void set_m_TriggerFunction_10(OnTrigger_t4184125570 * value) { ___m_TriggerFunction_10 = value; Il2CppCodeGenWriteBarrier((&___m_TriggerFunction_10), value); } inline static int32_t get_offset_of_m_Method_11() { return static_cast<int32_t>(offsetof(EventTrigger_t2527451695, ___m_Method_11)); } inline TriggerMethod_t582536534 * get_m_Method_11() const { return ___m_Method_11; } inline TriggerMethod_t582536534 ** get_address_of_m_Method_11() { return &___m_Method_11; } inline void set_m_Method_11(TriggerMethod_t582536534 * value) { ___m_Method_11 = value; Il2CppCodeGenWriteBarrier((&___m_Method_11), value); } }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // EVENTTRIGGER_T2527451695_H #ifndef BEHAVIOUR_T1437897464_H #define BEHAVIOUR_T1437897464_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // UnityEngine.Behaviour struct Behaviour_t1437897464 : public Component_t1923634451 { public: public: }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // BEHAVIOUR_T1437897464_H #ifndef ONTRIGGER_T4184125570_H #define ONTRIGGER_T4184125570_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // UnityEngine.Analytics.EventTrigger/OnTrigger struct OnTrigger_t4184125570 : public MulticastDelegate_t { public: public: }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // ONTRIGGER_T4184125570_H #ifndef MONOBEHAVIOUR_T3962482529_H #define MONOBEHAVIOUR_T3962482529_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // UnityEngine.MonoBehaviour struct MonoBehaviour_t3962482529 : public Behaviour_t1437897464 { public: public: }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // MONOBEHAVIOUR_T3962482529_H #ifndef GAMECONTROLLER_T2330501625_H #define GAMECONTROLLER_T2330501625_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // GameController struct GameController_t2330501625 : public MonoBehaviour_t3962482529 { public: // System.Single GameController::timeLeft float ___timeLeft_2; // System.Single GameController::ScoreNum float ___ScoreNum_3; // UnityEngine.UI.Text GameController::CountD Text_t1901882714 * ___CountD_4; // UnityEngine.UI.Text GameController::TxtScoreNum Text_t1901882714 * ___TxtScoreNum_5; // UnityEngine.GameObject GameController::PT1 GameObject_t1113636619 * ___PT1_6; // UnityEngine.GameObject GameController::PT2 GameObject_t1113636619 * ___PT2_7; // UnityEngine.GameObject GameController::PT3 GameObject_t1113636619 * ___PT3_8; // UnityEngine.GameObject GameController::btnWrongTouch GameObject_t1113636619 * ___btnWrongTouch_9; // UnityEngine.GameObject GameController::btnTouch01 GameObject_t1113636619 * ___btnTouch01_10; public: inline static int32_t get_offset_of_timeLeft_2() { return static_cast<int32_t>(offsetof(GameController_t2330501625, ___timeLeft_2)); } inline float get_timeLeft_2() const { return ___timeLeft_2; } inline float* get_address_of_timeLeft_2() { return &___timeLeft_2; } inline void set_timeLeft_2(float value) { ___timeLeft_2 = value; } inline static int32_t get_offset_of_ScoreNum_3() { return static_cast<int32_t>(offsetof(GameController_t2330501625, ___ScoreNum_3)); } inline float get_ScoreNum_3() const { return ___ScoreNum_3; } inline float* get_address_of_ScoreNum_3() { return &___ScoreNum_3; } inline void set_ScoreNum_3(float value) { ___ScoreNum_3 = value; } inline static int32_t get_offset_of_CountD_4() { return static_cast<int32_t>(offsetof(GameController_t2330501625, ___CountD_4)); } inline Text_t1901882714 * get_CountD_4() const { return ___CountD_4; } inline Text_t1901882714 ** get_address_of_CountD_4() { return &___CountD_4; } inline void set_CountD_4(Text_t1901882714 * value) { ___CountD_4 = value; Il2CppCodeGenWriteBarrier((&___CountD_4), value); } inline static int32_t get_offset_of_TxtScoreNum_5() { return static_cast<int32_t>(offsetof(GameController_t2330501625, ___TxtScoreNum_5)); } inline Text_t1901882714 * get_TxtScoreNum_5() const { return ___TxtScoreNum_5; } inline Text_t1901882714 ** get_address_of_TxtScoreNum_5() { return &___TxtScoreNum_5; } inline void set_TxtScoreNum_5(Text_t1901882714 * value) { ___TxtScoreNum_5 = value; Il2CppCodeGenWriteBarrier((&___TxtScoreNum_5), value); } inline static int32_t get_offset_of_PT1_6() { return static_cast<int32_t>(offsetof(GameController_t2330501625, ___PT1_6)); } inline GameObject_t1113636619 * get_PT1_6() const { return ___PT1_6; } inline GameObject_t1113636619 ** get_address_of_PT1_6() { return &___PT1_6; } inline void set_PT1_6(GameObject_t1113636619 * value) { ___PT1_6 = value; Il2CppCodeGenWriteBarrier((&___PT1_6), value); } inline static int32_t get_offset_of_PT2_7() { return static_cast<int32_t>(offsetof(GameController_t2330501625, ___PT2_7)); } inline GameObject_t1113636619 * get_PT2_7() const { return ___PT2_7; } inline GameObject_t1113636619 ** get_address_of_PT2_7() { return &___PT2_7; } inline void set_PT2_7(GameObject_t1113636619 * value) { ___PT2_7 = value; Il2CppCodeGenWriteBarrier((&___PT2_7), value); } inline static int32_t get_offset_of_PT3_8() { return static_cast<int32_t>(offsetof(GameController_t2330501625, ___PT3_8)); } inline GameObject_t1113636619 * get_PT3_8() const { return ___PT3_8; } inline GameObject_t1113636619 ** get_address_of_PT3_8() { return &___PT3_8; } inline void set_PT3_8(GameObject_t1113636619 * value) { ___PT3_8 = value; Il2CppCodeGenWriteBarrier((&___PT3_8), value); } inline static int32_t get_offset_of_btnWrongTouch_9() { return static_cast<int32_t>(offsetof(GameController_t2330501625, ___btnWrongTouch_9)); } inline GameObject_t1113636619 * get_btnWrongTouch_9() const { return ___btnWrongTouch_9; } inline GameObject_t1113636619 ** get_address_of_btnWrongTouch_9() { return &___btnWrongTouch_9; } inline void set_btnWrongTouch_9(GameObject_t1113636619 * value) { ___btnWrongTouch_9 = value; Il2CppCodeGenWriteBarrier((&___btnWrongTouch_9), value); } inline static int32_t get_offset_of_btnTouch01_10() { return static_cast<int32_t>(offsetof(GameController_t2330501625, ___btnTouch01_10)); } inline GameObject_t1113636619 * get_btnTouch01_10() const { return ___btnTouch01_10; } inline GameObject_t1113636619 ** get_address_of_btnTouch01_10() { return &___btnTouch01_10; } inline void set_btnTouch01_10(GameObject_t1113636619 * value) { ___btnTouch01_10 = value; Il2CppCodeGenWriteBarrier((&___btnTouch01_10), value); } }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // GAMECONTROLLER_T2330501625_H #ifndef WINLOSTDISPLAY_T1726081124_H #define WINLOSTDISPLAY_T1726081124_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // WinLostDisplay struct WinLostDisplay_t1726081124 : public MonoBehaviour_t3962482529 { public: // UnityEngine.GameObject WinLostDisplay::YLost GameObject_t1113636619 * ___YLost_2; // UnityEngine.GameObject WinLostDisplay::YWin GameObject_t1113636619 * ___YWin_3; public: inline static int32_t get_offset_of_YLost_2() { return static_cast<int32_t>(offsetof(WinLostDisplay_t1726081124, ___YLost_2)); } inline GameObject_t1113636619 * get_YLost_2() const { return ___YLost_2; } inline GameObject_t1113636619 ** get_address_of_YLost_2() { return &___YLost_2; } inline void set_YLost_2(GameObject_t1113636619 * value) { ___YLost_2 = value; Il2CppCodeGenWriteBarrier((&___YLost_2), value); } inline static int32_t get_offset_of_YWin_3() { return static_cast<int32_t>(offsetof(WinLostDisplay_t1726081124, ___YWin_3)); } inline GameObject_t1113636619 * get_YWin_3() const { return ___YWin_3; } inline GameObject_t1113636619 ** get_address_of_YWin_3() { return &___YWin_3; } inline void set_YWin_3(GameObject_t1113636619 * value) { ___YWin_3 = value; Il2CppCodeGenWriteBarrier((&___YWin_3), value); } }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // WINLOSTDISPLAY_T1726081124_H #ifndef LOADSCENEWHENCLICK_T4237803189_H #define LOADSCENEWHENCLICK_T4237803189_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // LoadSceneWhenClick struct LoadSceneWhenClick_t4237803189 : public MonoBehaviour_t3962482529 { public: public: }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // LOADSCENEWHENCLICK_T4237803189_H #ifndef GVAR_T585717320_H #define GVAR_T585717320_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // GVar struct GVar_t585717320 : public MonoBehaviour_t3962482529 { public: public: }; struct GVar_t585717320_StaticFields { public: // System.Boolean GVar::isWin bool ___isWin_2; public: inline static int32_t get_offset_of_isWin_2() { return static_cast<int32_t>(offsetof(GVar_t585717320_StaticFields, ___isWin_2)); } inline bool get_isWin_2() const { return ___isWin_2; } inline bool* get_address_of_isWin_2() { return &___isWin_2; } inline void set_isWin_2(bool value) { ___isWin_2 = value; } }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // GVAR_T585717320_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize1800 = { sizeof (FieldWithTarget_t3058750293), -1, 0, 0 }; extern const int32_t g_FieldOffsetTable1800[6] = { FieldWithTarget_t3058750293::get_offset_of_m_ParamName_0(), FieldWithTarget_t3058750293::get_offset_of_m_Target_1(), FieldWithTarget_t3058750293::get_offset_of_m_FieldPath_2(), FieldWithTarget_t3058750293::get_offset_of_m_TypeString_3(), FieldWithTarget_t3058750293::get_offset_of_m_DoStatic_4(), FieldWithTarget_t3058750293::get_offset_of_m_StaticString_5(), }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize1801 = { sizeof (TriggerBool_t501031542)+ sizeof (RuntimeObject), sizeof(int32_t), 0, 0 }; extern const int32_t g_FieldOffsetTable1801[4] = { TriggerBool_t501031542::get_offset_of_value___1() + static_cast<int32_t>(sizeof(RuntimeObject)), 0, 0, 0, }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize1802 = { sizeof (TriggerLifecycleEvent_t3193146760)+ sizeof (RuntimeObject), sizeof(int32_t), 0, 0 }; extern const int32_t g_FieldOffsetTable1802[9] = { TriggerLifecycleEvent_t3193146760::get_offset_of_value___1() + static_cast<int32_t>(sizeof(RuntimeObject)), 0, 0, 0, 0, 0, 0, 0, 0, }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize1803 = { sizeof (TriggerOperator_t3611898925)+ sizeof (RuntimeObject), sizeof(int32_t), 0, 0 }; extern const int32_t g_FieldOffsetTable1803[9] = { TriggerOperator_t3611898925::get_offset_of_value___1() + static_cast<int32_t>(sizeof(RuntimeObject)), 0, 0, 0, 0, 0, 0, 0, 0, }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize1804 = { sizeof (TriggerType_t105272677)+ sizeof (RuntimeObject), sizeof(int32_t), 0, 0 }; extern const int32_t g_FieldOffsetTable1804[5] = { TriggerType_t105272677::get_offset_of_value___1() + static_cast<int32_t>(sizeof(RuntimeObject)), 0, 0, 0, 0, }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize1805 = { sizeof (TriggerListContainer_t2032715483), -1, 0, 0 }; extern const int32_t g_FieldOffsetTable1805[1] = { TriggerListContainer_t2032715483::get_offset_of_m_Rules_0(), }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize1806 = { sizeof (EventTrigger_t2527451695), -1, 0, 0 }; extern const int32_t g_FieldOffsetTable1806[12] = { EventTrigger_t2527451695::get_offset_of_m_IsTriggerExpanded_0(), EventTrigger_t2527451695::get_offset_of_m_Type_1(), EventTrigger_t2527451695::get_offset_of_m_LifecycleEvent_2(), EventTrigger_t2527451695::get_offset_of_m_ApplyRules_3(), EventTrigger_t2527451695::get_offset_of_m_Rules_4(), EventTrigger_t2527451695::get_offset_of_m_TriggerBool_5(), EventTrigger_t2527451695::get_offset_of_m_InitTime_6(), EventTrigger_t2527451695::get_offset_of_m_RepeatTime_7(), EventTrigger_t2527451695::get_offset_of_m_Repetitions_8(), EventTrigger_t2527451695::get_offset_of_repetitionCount_9(), EventTrigger_t2527451695::get_offset_of_m_TriggerFunction_10(), EventTrigger_t2527451695::get_offset_of_m_Method_11(), }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize1807 = { sizeof (OnTrigger_t4184125570), sizeof(Il2CppMethodPointer), 0, 0 }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize1808 = { sizeof (TrackableTrigger_t621205209), -1, 0, 0 }; extern const int32_t g_FieldOffsetTable1808[2] = { TrackableTrigger_t621205209::get_offset_of_m_Target_0(), TrackableTrigger_t621205209::get_offset_of_m_MethodPath_1(), }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize1809 = { sizeof (TriggerMethod_t582536534), -1, 0, 0 }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize1810 = { sizeof (TriggerRule_t1946298321), -1, 0, 0 }; extern const int32_t g_FieldOffsetTable1810[4] = { TriggerRule_t1946298321::get_offset_of_m_Target_0(), TriggerRule_t1946298321::get_offset_of_m_Operator_1(), TriggerRule_t1946298321::get_offset_of_m_Value_2(), TriggerRule_t1946298321::get_offset_of_m_Value2_3(), }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize1811 = { sizeof (U3CModuleU3E_t692745546), -1, 0, 0 }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize1812 = { sizeof (GameController_t2330501625), -1, 0, 0 }; extern const int32_t g_FieldOffsetTable1812[9] = { GameController_t2330501625::get_offset_of_timeLeft_2(), GameController_t2330501625::get_offset_of_ScoreNum_3(), GameController_t2330501625::get_offset_of_CountD_4(), GameController_t2330501625::get_offset_of_TxtScoreNum_5(), GameController_t2330501625::get_offset_of_PT1_6(), GameController_t2330501625::get_offset_of_PT2_7(), GameController_t2330501625::get_offset_of_PT3_8(), GameController_t2330501625::get_offset_of_btnWrongTouch_9(), GameController_t2330501625::get_offset_of_btnTouch01_10(), }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize1813 = { sizeof (GVar_t585717320), -1, sizeof(GVar_t585717320_StaticFields), 0 }; extern const int32_t g_FieldOffsetTable1813[1] = { GVar_t585717320_StaticFields::get_offset_of_isWin_2(), }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize1814 = { sizeof (LoadSceneWhenClick_t4237803189), -1, 0, 0 }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize1815 = { sizeof (WinLostDisplay_t1726081124), -1, 0, 0 }; extern const int32_t g_FieldOffsetTable1815[2] = { WinLostDisplay_t1726081124::get_offset_of_YLost_2(), WinLostDisplay_t1726081124::get_offset_of_YWin_3(), }; #ifdef __clang__ #pragma clang diagnostic pop #endif
[ "tonyMac@tonys-MacBook-Pro.local" ]
tonyMac@tonys-MacBook-Pro.local
460c0f5f011961dbae6077213bcfe6db54e72323
2696a4f1f21c8ef7c225855dd5c8a683a86886dd
/Library/Model/ListeEleveModel.cpp
c50851ad1b21ba422ae49cfbd2879c1151fb0b5c
[]
no_license
MPercieduSert/NoteCpp
d9c6dfa3b116c19a7198c8d81d0295b33ab97473
330d80d465dbc3cd9f4a8eda0e8b0a2cfc15f236
refs/heads/master
2020-12-24T16:34:12.858504
2017-10-07T08:03:47
2017-10-07T08:03:47
42,960,354
0
0
null
null
null
null
UTF-8
C++
false
false
2,640
cpp
#include "ListeEleveModel.h" ListeEleveModel::ListeEleveModel(Bdd *bdd, const Classe &classe, QObject *parent) : ListeElevesModel(bdd,bdd->getMap<Eleve,ClasseEleve>(ClasseEleve::IdEl,ClasseEleve::IdCl,classe.id()),parent), m_classe(classe) {} QVariant ListeEleveModel::dataPropre(const Indice &indice, int /*role*/) const { if(indice.first < m_dataD.count()) return m_dataD[indice.first][indice.second].valeur(); return QVariant(); } bool ListeEleveModel::insertColumn(const Donnee &dn) { beginInsertColumns(QModelIndex(),columnCount(),columnCount()); appendIdCol(m_dataD.count()); headerInsert(m_dataD.count(),dn.nom()); MapPtr<CibleDonnee> MapCbDn; for(QVector<int>::const_iterator i = m_idRow.cbegin(); i != m_idRow.cend(); ++i) { MapCbDn.insert(*i,CibleDonnee(dn.id(),*i,bdd::cible::EleveCb)); m_bdd->getUnique(MapCbDn[*i]); } m_dataD.append(std::move(MapCbDn)); endInsertColumns(); return true; } //bool ListeEleveModel::insertRows(int position, int rows, const QModelIndex & /*parent*/) //{ // beginInsertRows(QModelIndex(), position, position+rows-1); // for (int row = 0; row < rows; ++row) // m_dataE.insert(position, new Eleve()); // endInsertRows(); // return true; //} //bool ListeEleveModel::removeRows(int position, int rows, const QModelIndex & /*parent*/) //{ // beginRemoveRows(QModelIndex(), position, position+rows-1); // for (int row = 0; row < rows; ++row) // { // m_dataE.removeAt(position); // for(QVector<VectorPtr<CibleDonnee>>::iterator i = m_dataD.begin(); i != m_dataD.end(); ++i) // i->removeAt(position); // } // endRemoveRows(); // return true; //} void ListeEleveModel::save() { m_bdd->save(m_eleve); for(QVector<MapPtr<CibleDonnee>>::const_iterator i = m_dataD.cbegin(); i != m_dataD.cend(); ++i) m_bdd->save(*i); } bool ListeEleveModel::setDataPropre(const Indice &indice, const QVariant &value, int /*role*/) { if(indice.first < m_dataD.count()) { m_dataD[indice.first][indice.second].setValeur(value); return true; } else return false; } void ListeEleveModel::sortPropre(int column, Qt::SortOrder order) { if(column < m_dataD.count()) std::sort(m_idRow.begin(),m_idRow.end(),[order,column,this] (int i, int j) -> bool {return order == Qt::SortOrder::AscendingOrder ? m_dataD[column][i].valeur() < m_dataD[column][j].valeur() : m_dataD[column][i].valeur() > m_dataD[column][j].valeur();}); }
[ "maximeperciedusert@hotmail.fr" ]
maximeperciedusert@hotmail.fr
c201db38ba89bd380bd53044655960c1fe14f963
2281ed576a752605c855025ee862fddfffd8a036
/MCRayTracer/SourceCode/GivenInclude/AntiAliasDlg.h
905a715603694c2c3dfcfa6f9a3d0ce8cc683ee5
[]
no_license
FieryMonolith/historical
5e7b8eae22274a8a86e9c321be01f9d2bb05110b
11a688c09f436abfdd13341f3078833e412245f0
refs/heads/master
2021-01-05T04:18:21.798572
2020-02-17T07:21:33
2020-02-17T07:21:33
240,873,646
0
0
null
null
null
null
UTF-8
C++
false
false
499
h
#pragma once // CAntiAliasDlg dialog class CAntiAliasDlg : public CDialog { DECLARE_DYNAMIC(CAntiAliasDlg) public: CAntiAliasDlg(CWnd* pParent = NULL); // standard constructor virtual ~CAntiAliasDlg(); int GetIterations() { return m_iterations; } // Dialog Data //enum { IDD = IDD_ANTIALIAS }; enum { IDD = IDD_Alias }; protected: virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV support DECLARE_MESSAGE_MAP() public: int m_iterations; };
[ "jason.stredwick@gmail.com" ]
jason.stredwick@gmail.com
78dee4d699b54da47920e9724a3e8cc510f0a932
ac0ae7f42f80131ec34490eec2498f50d96adf92
/output/messages/MapRunningFightListMessage.cpp
f44ed0a82ba70586da286c56e36e5cd0124bbf60
[]
no_license
w0dm4n/Protocol-builder-Ankama-2.4x
2fad5d35467ee2cb0a5cfe7b2729c9b0170bae00
1b521c9e9eed8ebc3f62b72a699cf27c2ba139f8
refs/heads/master
2021-01-20T09:07:33.673393
2017-05-04T08:19:16
2017-05-04T08:19:16
90,224,495
3
1
null
null
null
null
UTF-8
C++
false
false
1,051
cpp
#include "MapRunningFightListMessage.hpp" MapRunningFightListMessage::MapRunningFightListMessage(std::vector<FightExternalInformations> fights) { this->fights = fights; } MapRunningFightListMessage::MapRunningFightListMessage() { } ushort MapRunningFightListMessage::getId() { return id; } std::string MapRunningFightListMessage::getName() { return "MapRunningFightListMessage"; } void MapRunningFightListMessage::serialize(BinaryWriter& writer) { writer.writeShort(this->fights.size()); int _loc2_ = 0; while(_loc2_ < this->fights.size()) { (this->fights[_loc2_]).serialize(writer); _loc2_++; } } void MapRunningFightListMessage::deserialize(BinaryReader& reader) { { FightExternalInformations _loc4_; int _loc2_ = reader.readUnsignedShort(); int _loc3_ = 0; while(_loc3_ < _loc2_) { _loc4_.deserialize(reader); this->fights.push_back(_loc4_); _loc3_++; } } }
[ "w0dm4n@hotmail.fr" ]
w0dm4n@hotmail.fr
a550a6b607520a334ff27931af8abce57db38796
47f53bed9d6a4e8f2f84c1931ebe773cf58256b9
/src/MikesDemoWindow_Main.cpp
91d58b40be5c1aa2d9043037fb199d78efb13af0
[ "Libpng", "LicenseRef-scancode-unknown-license-reference", "MIT", "Zlib", "LicenseRef-scancode-warranty-disclaimer" ]
permissive
michaelellison/Mike-s-Demo-App
a105ac46bbd29df0403423190579d24e0c4a4746
c0ba505e935bb1d98925c3b6bf04d3d5e2afa19a
refs/heads/master
2021-01-17T06:28:45.247677
2011-06-09T00:25:00
2011-06-09T00:25:00
1,840,197
0
0
null
null
null
null
UTF-8
C++
false
false
10,734
cpp
/// \file MikesDemoWindow_Main.cpp /// \brief Main Window class for MikesDemo /// \ingroup MikesDemo /// /// Copyright (c) 2011 by Michael Ellison. /// See COPYING.txt for license (MIT License). /// #include "MikesDemoWindow_Main.h" #include "CATEventDefs.h" #include "CATSwitch.h" #include "CAT3DVideo.h" #include "CATFileSystem.h" #include "CATMenu.h" #include "CATTab.h" #include "CATTreeCtrl.h" #include "CATPictureMulti.h" #include "CATLabel.h" // Joystick scan from old scanner (in skin directory) const char* k3dScanFile = "GoodStick.3sc"; MikesDemoWindow_Main::MikesDemoWindow_Main( const CATString& element, const CATString& rootDir) :CATWindow(element,rootDir) { // Controls that we grab fView3d = 0; fTabCtrl = 0; fProTree = 0; fProPic = 0; fProLogo = 0; fProText = 0; // 3D data fNum3dPoints = 0; f3dPoints = 0; fPointScanArray = 0; fPointScanHeight = 0; fPointScanScans = 0; } MikesDemoWindow_Main::~MikesDemoWindow_Main() { Clear3dPoints(); } void MikesDemoWindow_Main::OnCreate() { CATResult result = CAT_SUCCESS; CATWindow::OnCreate(); // Grab controls we'll be accessing fView3d = (CAT3DVideo*)this->FindControlAndVerify("Video3D","Video3D"); fTabCtrl= (CATTab*)this->Find(L"Tabs",L"Tab"); fProTree= (CATTreeCtrl*)this->FindControlAndVerify("ProTree","Tree"); fProLogo= (CATPictureMulti*)FindControlAndVerify("ProLogos","PictureMulti"); fProPic = (CATPictureMulti*)FindControlAndVerify("ProPics","PictureMulti"); fProText = (CATLabel*)FindControlAndVerify("ProText","Label"); if (fProTree) fProTree->SetCurItem(fProTree->GetRootItem(0),true); // Load in old 3D scan to display if (fView3d) { CATString pointFile = gApp->GetGlobalFileSystem()->BuildPath(gApp->GetSkinDir(), k3dScanFile); if (!pointFile.IsEmpty()) { if (CATSUCCEEDED(result = LoadRawScan(pointFile))) { // Display it and rotate it. fView3d->Set3dFacets(this->f3dPoints, fPointScanScans,fPointScanHeight); } } } } void MikesDemoWindow_Main::OnDestroy() { if (fView3d) fView3d->Stop(); CATWindow::OnDestroy(); } #define kMikesTableLen 8 static MikesDemoWindow_Main::CATWINDOWCMDFUNC MikesCmdTable[kMikesTableLen] = { {"DoLogoLink", (CATWindow::CATCOMMANDFUNC)&MikesDemoWindow_Main::OnLogoLink, false, false}, {"TabSelect", (CATWindow::CATCOMMANDFUNC)&MikesDemoWindow_Main::OnTabSelect, false, false}, {"ProSelect", (CATWindow::CATCOMMANDFUNC)&MikesDemoWindow_Main::OnProSelect, false, false}, {"Go3d", (CATWindow::CATCOMMANDFUNC)&MikesDemoWindow_Main::OnGo3d, false, false}, {"Hue", (CATWindow::CATCOMMANDFUNC)&MikesDemoWindow_Main::OnHue, false, false}, {"Gamma", (CATWindow::CATCOMMANDFUNC)&MikesDemoWindow_Main::OnGamma, false, false}, {"Compress", (CATWindow::CATCOMMANDFUNC)&MikesDemoWindow_Main::OnCompress, false, false}, {"ColorSim", (CATWindow::CATCOMMANDFUNC)&MikesDemoWindow_Main::OnColorSim, false, false} }; void MikesDemoWindow_Main::OnCommand(CATCommand& command, CATControl* ctrl) { CATResult result = ProcessCommandTable(command,ctrl,&MikesCmdTable[0],kMikesTableLen,false); if (CATFAILED(result)) CATWindow::OnCommand(command,ctrl); } void MikesDemoWindow_Main::OnLogoLink( CATCommand& command, CATControl* control) { CATUInt32 linkIndex = 0; if (fProLogo) linkIndex = CATRound(fProLogo->GetValue()); switch(linkIndex) { case 0: CATExecute(L"http://www.line6.com/podfarm"); break; case 1: CATExecute(L"http://www.reflectsystems.com"); break; case 2: CATExecute(L"http://www.freepatentsonline.com/6597381.html"); break; case 3: CATExecute(L"http://www.nadatech.com"); break; } } void MikesDemoWindow_Main::OnTabSelect( CATCommand& command, CATControl* control) { if (fTabCtrl) fTabCtrl->SetCurTab((CATUInt32)command.GetValue()); CATWindow::OnCommand(command,control); } void MikesDemoWindow_Main::OnProSelect( CATCommand& command, CATControl* control) { if (fProTree) { CATTREEINFO* curItem = fProTree->GetCurItem(); if (curItem) OnProTreeChange((CATUInt32)curItem->DataPtr - 1); } } void MikesDemoWindow_Main::OnGo3d( CATCommand& command, CATControl* control) { if (fTabCtrl) fTabCtrl->SetCurTab(2); CATWindow::OnCommand(CATCommand("TabSelect",2),control); } void MikesDemoWindow_Main::OnHue( CATCommand& command, CATControl* control) { if (fView3d) fView3d->GetImageProcessor()->SetHue(command.GetValue()); } void MikesDemoWindow_Main::OnGamma( CATCommand& command, CATControl* control) { if (fView3d) fView3d->GetImageProcessor()->SetGamma(command.GetValue()); } void MikesDemoWindow_Main::OnCompress( CATCommand& command, CATControl* control) { if (fView3d) fView3d->GetImageProcessor()->SetCompress(command.GetValue()); } void MikesDemoWindow_Main::OnColorSim( CATCommand& command, CATControl* control) { CATInt32 simInt = CATRound(command.GetValue()); switch (simInt) { case 0: // normal { fView3d->GetImageProcessor()->SetMergeType(CBMagInfo::MERGE_NONE); fView3d->GetImageProcessor()->SetSeverity(0.0f); MarkDirty(); break; } case 1: // red { fView3d->GetImageProcessor()->SetMergeType(CBMagInfo::MERGE_Red); fView3d->GetImageProcessor()->SetSeverity(1.0f); MarkDirty(); break; } case 2: // green { fView3d->GetImageProcessor()->SetMergeType(CBMagInfo::MERGE_Green); fView3d->GetImageProcessor()->SetSeverity(1.0f); MarkDirty(); break; } case 3: // blue { fView3d->GetImageProcessor()->SetMergeType(CBMagInfo::MERGE_Blue); fView3d->GetImageProcessor()->SetSeverity(1.0f); MarkDirty(); break; } } CATWindow::OnCommand(command,control); } void MikesDemoWindow_Main::OnProTreeChange(CATUInt32 index) { if (fProLogo) fProLogo->SetValue((CATFloat32)index,false); if (fProPic) fProPic->SetValue((CATFloat32)index,false); if (fProText) fProText->SetString(gApp->GetString(CAT_STR_MIKE_RESUME_LINE6 + index)); } void MikesDemoWindow_Main::OnShow() { // Start the video if (fSkin) { if (fView3d) fView3d->Start(); } } CATResult MikesDemoWindow_Main::OnEvent ( const CATEvent& eventStruct, CATInt32& retVal) { switch (eventStruct.fEventCode) { case CATEVENT_WINDOW_SHOWN: if (eventStruct.fVoidParam == this) { this->OnShow(); } break; default: break; } return CATWindow::OnEvent(eventStruct,retVal); } //--------------------------------------------------------------------------- // 3D Scanner functions // 3D constants from old scanner const CATFloat64 kMinZ = -6.0; const CATFloat64 kMaxZ = 6.0; const CATFloat64 kBottomLine = 4.0; // Y - location of bottom line. CATResult MikesDemoWindow_Main::LoadRawScan(const CATString& fname) { CATResult result = CAT_SUCCESS; CATTRACE((CATString)"Loading Raw Scan: " << fname << "..."); CATInt32 i,j; CATStreamFile lastScan; CATInt32 numScans,height; if (CATSUCCEEDED(result = lastScan.Open(fname,CATStream::READ_ONLY))) { CATUInt32 wout; // Read height of scan wout = sizeof(CATInt32); if (CATFAILED(result = lastScan.Read(&height,wout))) { CATTRACE("Error loading raw scan - couldn't read height."); lastScan.Close(); result; } // Read number of scans wout = sizeof(CATInt32); if (CATFAILED(result = lastScan.Read(&numScans,wout))) { CATTRACE("Error loading raw scan - couldn't read number of scans."); lastScan.Close(); return result; } if (fPointScanArray != 0) { delete [] fPointScanArray; fPointScanArray = 0; fPointScanHeight = 0; fPointScanScans = 0; } fPointScanArray = new CATScanPoint[numScans*height]; fPointScanHeight = height; fPointScanScans = numScans; if (0 == fPointScanArray) { CATTRACE("Error: Couldn't allocate enough memory to load scan!"); lastScan.Close(); return CAT_ERR_OUT_OF_MEMORY; } // Read data directly into a raw buffer.... unsigned char* rawBuf = new unsigned char[numScans*height*(sizeof(CATFloat64)*3 + sizeof(CATUInt32))]; if (!rawBuf) { CATTRACE("Not enough memory to load scan!"); lastScan.Close(); return CAT_ERR_OUT_OF_MEMORY; } wout = numScans*height*(sizeof(CATFloat64)*3 + sizeof(CATUInt32)); if (CATSUCCEEDED(result = lastScan.Read(rawBuf, wout))) { // Now read data for (i = 0; i < numScans; i++) { for (j=0; j < height; j++) { CATInt32 step = ((sizeof(CATFloat64)*3) + sizeof(CATUInt32)); CATInt32 curPos = (i * height) + j; // Read points from memory buffer fPointScanArray[curPos].y = *((CATFloat64*)&rawBuf[curPos*step]); fPointScanArray[curPos].z = *((CATFloat64*)&rawBuf[curPos*step + sizeof(CATFloat64)]); fPointScanArray[curPos].rotation = *((CATFloat64*)&rawBuf[curPos*step + sizeof(CATFloat64)*2]); fPointScanArray[curPos].color = *(CATUInt32*)((CATFloat64*)&rawBuf[curPos*step + sizeof(CATFloat64)*3]); // woops, r/b flipped. CATSwap(((CATCOLOR*)(&fPointScanArray[curPos].color))->r, ((CATCOLOR*)(&fPointScanArray[curPos].color))->b); } } } else { result = CAT_ERROR; } delete [] rawBuf; lastScan.Close(); if (CATFAILED(result)) { return result; } if (!(GetPointsFromRawScan(fPointScanScans,fPointScanHeight,fPointScanArray))) { return CAT_ERROR; } CATTRACE("Raw scan loaded."); return CAT_SUCCESS; } return result; } bool MikesDemoWindow_Main::GetPointsFromRawScan(CATInt32 numScans, CATInt32 height, CATScanPoint* pointArray) { if (pointArray == 0) { return false; } // calculate the rotated 3D points from a raw scan array Clear3dPoints(); CATInt32 i,j; fNum3dPoints = numScans * height; f3dPoints = new CATC3DPoint[fNum3dPoints]; for (i = 0; i < numScans; i++) { for (j=0; j < height; j++) { CATC3DPoint* point3d = 0; CATInt32 curPos = (i * height) + j; // Skip blank points if ((pointArray[curPos].y == 0) && (pointArray[curPos].z == 0)) { continue; } // Check for points below stage and ignore if (pointArray[curPos].y > kBottomLine) { continue; } // Check for points outside of table diameter if ((pointArray[curPos].z > kMaxZ) || (pointArray[curPos].z < kMinZ)) { continue; } f3dPoints[curPos].FromScannedPolar( pointArray[curPos].y, pointArray[curPos].z, pointArray[curPos].rotation, pointArray[curPos].color); } } CATTRACE((CATString)"Got " << fNum3dPoints << " points from raw scan."); return true; } void MikesDemoWindow_Main::Clear3dPoints() { if (f3dPoints != 0) { delete [] f3dPoints; f3dPoints = 0; } fNum3dPoints = 0; }
[ "me@michaelellison.me" ]
me@michaelellison.me
bfdda64444050bbeb3178320db84c1bd25052278
9594cfe4a08808dba1f29580b0e2451570a604f4
/source/source/Lesson08-拾取选择(1)/GLES20Frame.hpp
9ee9dd6893b74837a1e13db45747a4e3f6d5f900
[]
no_license
cyt2017/Opengl_Mid
489d9952e36673518e0cd7f6710760c5860aa55b
4a59f9322072eb6e6f11080f1c007e5512a97b84
refs/heads/master
2021-08-22T20:32:30.792872
2017-12-01T06:23:47
2017-12-01T06:23:47
112,703,052
0
0
null
null
null
null
GB18030
C++
false
false
28,454
hpp
#pragma once #include "CELLFrame.hpp" #include "rapidxml.hpp" #include <map> #include <string> using namespace std; namespace CELL { class PROGRAM_P2_T2_C3 :public ProgramId { public: typedef int location; public: location _positionAttr; location _colorAttr; location _uvAttr; location _MVP; location _texture; public: PROGRAM_P2_T2_C3() { _positionAttr = -1; _colorAttr = -1; _uvAttr = -1; _MVP = -1; } ~PROGRAM_P2_T2_C3() { } /// 初始化函数 virtual bool initialize(CELLOpenGL& device) { const char* vs = { "uniform mat4 _MVP;" "attribute vec3 _position;" "attribute vec4 _color;" "attribute vec2 _uv;" "varying vec4 _outColor;" "varying vec2 _outUV;" "void main()" "{" " vec4 pos = vec4(_position.x,_position.y,_position.z,1);" " gl_Position = _MVP * pos;" " _outColor = _color;" " _outUV = _uv;" "}" }; const char* ps = { "precision lowp float; " "uniform sampler2D _texture;\n" "varying vec4 _outColor;\n" "varying vec2 _outUV;" "void main()" "{" " vec4 color = texture2D(_texture,_outUV);" " gl_FragColor = color * _outColor;" "}" }; ProgramId& prgId = *this; prgId = device.createProgram(vs,ps); _positionAttr = glGetAttribLocation(_programId, "_position"); _colorAttr = glGetAttribLocation(_programId, "_color"); _uvAttr = glGetAttribLocation(_programId, "_uv"); _MVP = glGetUniformLocation(_programId,"_MVP"); _texture = glGetUniformLocation(_programId,"_texture"); return true; } /** * 使用程序 */ virtual void begin() { glUseProgram(_programId); glEnableVertexAttribArray(_positionAttr); glEnableVertexAttribArray(_uvAttr); glEnableVertexAttribArray(_colorAttr); } /** * 使用完成 */ virtual void end() { glDisableVertexAttribArray(_positionAttr); glDisableVertexAttribArray(_uvAttr); glDisableVertexAttribArray(_colorAttr); glUseProgram(0); } }; class PROGRAM_DIR_LIGHT0 :public ProgramId { public: typedef int uniform; typedef int attribute; public: attribute _positionAttr; attribute _normal; uniform modelViewProjection; uniform modelViewInverse; uniform eyePosition; uniform lightVector; public: PROGRAM_DIR_LIGHT0() { _positionAttr = -1; _normal = -1; } ~PROGRAM_DIR_LIGHT0() { } /// 初始化函数 virtual bool initialize(CELLOpenGL& device) { const char* vs = { "attribute vec3 _position;" "attribute vec3 _normal;" "varying vec4 _outColor;" "uniform mat4 modelViewProjection;" "uniform mat4 modelViewInverse;" "uniform vec3 eyePosition;" "uniform vec3 lightVector;" "void main(){" "gl_Position = modelViewProjection * vec4(_position,1);" "vec4 normal = modelViewInverse * vec4(_normal,1);" "normal = normalize(normal);" "vec3 light = normalize( lightVector );" "vec3 eye = eyePosition;" "vec3 v = normalize( _position);" "vec3 halfs = normalize( light + eye);" // 使用兰伯特余弦定律(Lambert' cosine law)计算漫反射 "float diffuse = dot( normal.xyz, light );" // 使用比林 - 冯着色模型(Blinn - Phong shading model)来计算镜面反射 "float specular = dot( normal.xyz, halfs );" "specular = pow( specular, 32.0 );" "vec4 ambientColor = vec4( 0.4, 0.4, 0.4, 0.4 );" "vec4 diffuseColor = vec4( 1, 1, 1, 1.0 );" "vec4 specularMaterial = vec4( 1.0, 1.0, 1.0, 1.0 );" "_outColor = diffuse * diffuseColor + specular * specularMaterial + ambientColor;" "}" }; const char* ps = { "precision lowp float; " "varying vec4 _outColor;" "void main(){" "gl_FragColor = _outColor;" "}" }; ProgramId& prgId = *this; prgId = device.createProgram(vs,ps); _positionAttr = glGetAttribLocation(_programId, "_position"); _normal = glGetAttribLocation(_programId, "_normal"); modelViewProjection = glGetUniformLocation(_programId,"modelViewProjection"); modelViewInverse = glGetUniformLocation(_programId,"modelViewInverse"); eyePosition = glGetUniformLocation(_programId,"eyePosition"); lightVector = glGetUniformLocation(_programId,"lightVector"); return true; } /** * 使用程序 */ virtual void begin() { glUseProgram(_programId); glEnableVertexAttribArray(_positionAttr); glEnableVertexAttribArray(_normal); } /** * 使用完成 */ virtual void end() { glDisableVertexAttribArray(_positionAttr); glDisableVertexAttribArray(_normal); glUseProgram(0); } }; class CELL3RDCamera { public: float3 _eye; float3 _up; float3 _right; float3 _target; float3 _dir; float _radius; matrix4 _matView; matrix4 _matProj; matrix4 _matWorld; float2 _viewSize; float _yaw; public: CELL3RDCamera() { _radius = 400; _yaw = 0; _viewSize = float2(100,100); _matView.identify(); _matProj.identify(); _matWorld.identify(); } float getRadius() const { return _radius; } void setRadius(float val) { _radius = val; } CELL::float3 getEye() const { return _eye; } /** * 设置眼睛的位置 */ void setEye(CELL::float3 val) { _eye = val; } /** * 计算方向 */ void calcDir() { _dir = _target - _eye; _dir = normalize(_dir); } CELL::float3 getTarget() const { return _target; } void setTarget(CELL::float3 val) { _target = val; } CELL::float3 getUp() const { return _up; } void setUp(CELL::float3 val) { _up = val; } float3 getDir() const { return _dir; } float3 getRight() const { return _right; } void update() { float3 upDir = normalize(_up); _eye = _target - _dir * _radius; _right = normalize(cross(_dir, upDir)); _matView = CELL::lookAt(_eye,_target,_up); } void setViewSize(const float2& viewSize) { _viewSize = viewSize; } void setViewSize(float x,float y) { _viewSize = float2(x,y); } float2 getViewSize() { return _viewSize; } void setProject(const matrix4& proj) { _matProj = proj; } const matrix4& getProject() const { return _matProj; } const matrix4& getView() const { return _matView; } void perspective(float fovy, float aspect, float zNear, float zFar) { _matProj = CELL::perspective<float>(fovy,aspect,zNear,zFar); } /** * 世界坐标转化为窗口坐标 */ bool project( const float4& world, float4& screen ) { screen = (_matProj * _matView * _matWorld) * world; if (screen.w == 0.0f) { return false; } screen.x /= screen.w; screen.y /= screen.w; screen.z /= screen.w; // map to range 0 - 1 screen.x = screen.x * 0.5f + 0.5f; screen.y = screen.y * 0.5f + 0.5f; screen.z = screen.z * 0.5f + 0.5f; // map to viewport screen.x = screen.x * _viewSize.x; screen.y = _viewSize.y - (screen.y * _viewSize.y); return true; } /** * 世界坐标转化为窗口坐标 */ float2 worldToScreen( const float3& world) { float4 worlds(world.x,world.y,world.z,1); float4 screens; project(worlds,screens); return float2(screens.x,screens.y); } /** * 窗口坐标转化为世界坐标 */ float3 screenToWorld(const float2& screen) { float4 screens(screen.x,screen.y,0,1); float4 world; unProject(screens,world); return float3(world.x,world.y,world.z); } float3 screenToWorld(float x,float y) { float4 screens(x,y,0,1); float4 world; unProject(screens,world); return float3(world.x,world.y,world.z); } /** * 窗口坐标转化为世界坐标 */ bool unProject( const float4& screen, float4& world ) { float4 v; v.x = screen.x; v.y = screen.y; v.z = screen.z; v.w = 1.0; // map from viewport to 0 - 1 v.x = (v.x) /_viewSize.x; v.y = (_viewSize.y - v.y) /_viewSize.y; //v.y = (v.y - _viewPort.Y) / _viewPort.Height; // map to range -1 to 1 v.x = v.x * 2.0f - 1.0f; v.y = v.y * 2.0f - 1.0f; v.z = v.z * 2.0f - 1.0f; CELL::matrix4 inverse = (_matProj * _matView * _matWorld).inverse(); v = v * inverse; if (v.w == 0.0f) { return false; } world = v / v.w; return true; } Ray createRayFromScreen(int x,int y) { float4 minWorld; float4 maxWorld; float4 screen(float(x),float(y),0,1); float4 screen1(float(x),float(y),1,1); unProject(screen,minWorld); unProject(screen1,maxWorld); Ray ray; ray.setOrigin(float3(minWorld.x,minWorld.y,minWorld.z)); float3 dir(maxWorld.x - minWorld.x,maxWorld.y - minWorld.y, maxWorld.z - minWorld.z); ray.setDirection(normalize(dir)); return ray; } /** * 下面的函数的功能是将摄像机的观察方向绕某个方向轴旋转一定的角度 * 改变观察者的位置,目标的位置不变化 */ void rotateView(float angle) { _dir = rotateY<float>(_dir,angle); } }; class Role { public: float3 _pos; float3 _target; float _speed; public: Role() { _speed = 5; } /** * 设置移动的目标点 */ void setTarget(float3 target) { _target = target; } /** * 更新位置 */ void setPosition(float3 pos) { _pos = pos; _pos.y = 1; } void moveCheck(const float elasped) { /** * 目标位置不是当前位置。 */ if (_target == _pos) { return; } /** * 获取当前玩家位置与目标位置的偏移量 */ float3 offset = _target - _pos; /** * 获取到移动的方向 */ float3 dir = normalize(offset); if (distance(_target,_pos) > 1) { float speed = elasped * _speed; _pos += float3(dir.x * speed,0,dir.z * speed) ; } else { _target = _pos; } } /** * 绘制角色 */ void render(float fElapsed) { moveCheck(fElapsed); } }; struct Vertex { float x, y, z; float u,v; float r, g, b,a; float nx,ny,nz; }; Vertex boxVertex[36] = { // tu tv r g b a nx ny nz x y z {-1.0f,-1.0f, 1.0f, 0.0f,0.0f, 1.0f,1.0f,1.0f,1.0f, 0.0f, 0.0f, 1.0f }, { 1.0f,-1.0f, 1.0f, 1.0f,0.0f, 1.0f,1.0f,1.0f,1.0f, 0.0f, 0.0f, 1.0f }, { 1.0f, 1.0f, 1.0f, 1.0f,1.0f, 1.0f,1.0f,1.0f,1.0f, 0.0f, 0.0f, 1.0f }, {-1.0f,-1.0f, 1.0f, 0.0f,0.0f, 1.0f,1.0f,1.0f,1.0f, 0.0f, 0.0f, 1.0f }, { 1.0f, 1.0f, 1.0f, 1.0f,1.0f, 1.0f,1.0f,1.0f,1.0f, 0.0f, 0.0f, 1.0f }, {-1.0f, 1.0f, 1.0f, 0.0f,1.0f, 1.0f,1.0f,1.0f,1.0f, 0.0f, 0.0f, 1.0f }, {-1.0f,-1.0f,-1.0f, 1.0f,0.0f, 1.0f,1.0f,1.0f,1.0f, 0.0f, 0.0f,-1.0f }, {-1.0f, 1.0f,-1.0f, 1.0f,1.0f, 1.0f,1.0f,1.0f,1.0f, 0.0f, 0.0f,-1.0f }, { 1.0f, 1.0f,-1.0f, 0.0f,1.0f, 1.0f,1.0f,1.0f,1.0f, 0.0f, 0.0f,-1.0f }, {-1.0f,-1.0f,-1.0f, 1.0f,0.0f, 1.0f,1.0f,1.0f,1.0f, 0.0f, 0.0f,-1.0f }, { 1.0f, 1.0f,-1.0f, 0.0f,1.0f, 1.0f,1.0f,1.0f,1.0f, 0.0f, 0.0f,-1.0f }, { 1.0f,-1.0f,-1.0f, 0.0f,0.0f, 1.0f,1.0f,1.0f,1.0f, 0.0f, 0.0f,-1.0f }, {-1.0f, 1.0f,-1.0f, 0.0f,1.0f, 1.0f,1.0f,1.0f,1.0f, 0.0f, 1.0f, 0.0f }, {-1.0f, 1.0f, 1.0f, 0.0f,0.0f, 1.0f,1.0f,1.0f,1.0f, 0.0f, 1.0f, 0.0f }, { 1.0f, 1.0f, 1.0f, 1.0f,0.0f, 1.0f,1.0f,1.0f,1.0f, 0.0f, 1.0f, 0.0f }, {-1.0f, 1.0f,-1.0f, 0.0f,1.0f, 1.0f,1.0f,1.0f,1.0f, 0.0f, 1.0f, 0.0f }, { 1.0f, 1.0f, 1.0f, 1.0f,0.0f, 1.0f,1.0f,1.0f,1.0f, 0.0f, 1.0f, 0.0f }, { 1.0f, 1.0f,-1.0f, 1.0f,1.0f, 1.0f,1.0f,1.0f,1.0f, 0.0f, 1.0f, 0.0f }, {-1.0f,-1.0f,-1.0f, 1.0f,1.0f, 1.0f,1.0f,1.0f,1.0f, 0.0f,-1.0f, 0.0f }, { 1.0f,-1.0f,-1.0f, 0.0f,1.0f, 1.0f,1.0f,1.0f,1.0f, 0.0f,-1.0f, 0.0f }, { 1.0f,-1.0f, 1.0f, 0.0f,0.0f, 1.0f,1.0f,1.0f,1.0f, 0.0f,-1.0f, 0.0f }, {-1.0f,-1.0f,-1.0f, 1.0f,1.0f, 1.0f,1.0f,1.0f,1.0f, 0.0f,-1.0f, 0.0f }, { 1.0f,-1.0f, 1.0f, 0.0f,0.0f, 1.0f,1.0f,1.0f,1.0f, 0.0f,-1.0f, 0.0f }, {-1.0f,-1.0f, 1.0f, 1.0f,0.0f, 1.0f,1.0f,1.0f,1.0f, 0.0f,-1.0f, 0.0f }, { 1.0f,-1.0f,-1.0f, 1.0f,0.0f, 1.0f,1.0f,1.0f,1.0f, 1.0f, 0.0f, 0.0f }, { 1.0f, 1.0f,-1.0f, 1.0f,1.0f, 1.0f,1.0f,1.0f,1.0f, 1.0f, 0.0f, 0.0f }, { 1.0f, 1.0f, 1.0f, 0.0f,1.0f, 1.0f,1.0f,1.0f,1.0f, 1.0f, 0.0f, 0.0f }, { 1.0f,-1.0f,-1.0f, 1.0f,0.0f, 1.0f,1.0f,1.0f,1.0f, 1.0f, 0.0f, 0.0f }, { 1.0f, 1.0f, 1.0f, 0.0f,1.0f, 1.0f,1.0f,1.0f,1.0f, 1.0f, 0.0f, 0.0f }, { 1.0f,-1.0f, 1.0f, 0.0f,0.0f, 1.0f,1.0f,1.0f,1.0f, 1.0f, 0.0f, 0.0f }, {-1.0f,-1.0f,-1.0f, 0.0f,0.0f, 1.0f,1.0f,1.0f,1.0f, -1.0f, 0.0f, 0.0f }, {-1.0f,-1.0f, 1.0f, 1.0f,0.0f, 1.0f,1.0f,1.0f,1.0f, -1.0f, 0.0f, 0.0f }, {-1.0f, 1.0f, 1.0f, 1.0f,1.0f, 1.0f,1.0f,1.0f,1.0f, -1.0f, 0.0f, 0.0f }, {-1.0f,-1.0f,-1.0f, 0.0f,0.0f, 1.0f,1.0f,1.0f,1.0f, -1.0f, 0.0f, 0.0f }, {-1.0f, 1.0f, 1.0f, 1.0f,1.0f, 1.0f,1.0f,1.0f,1.0f, -1.0f, 0.0f, 0.0f }, {-1.0f, 1.0f,-1.0f, 0.0f,1.0f, 1.0f,1.0f,1.0f,1.0f, -1.0f, 0.0f, 0.0f } }; class GLES20Frame :public CELLFrame { protected: PROGRAM_P2_T2_C3 _shader; Texture2dId _texture; Texture2dId _textureRole; CELL3RDCamera _camera; PROGRAM_DIR_LIGHT0 _lighting; Role _role; bool _rightButtonDown; float2 _mousePos; Vertex _ptLine[2]; aabb3d _aabbBox; aabb3d _aabbTran; public: GLES20Frame(CELLOpenGL& device,void* user = 0) :CELLFrame(device,user) { _rightButtonDown = false; float3 vMin(FLT_MAX,FLT_MAX,FLT_MAX); float3 vMax(-FLT_MAX,-FLT_MAX,-FLT_MAX); for (size_t i = 0 ;i < 36 ; ++ i ) { vMin.x = min(boxVertex[i].x,vMin.x); vMin.y = min(boxVertex[i].y,vMin.y); vMin.z = min(boxVertex[i].z,vMin.z); vMax.x = max(boxVertex[i].x,vMax.x); vMax.y = max(boxVertex[i].y,vMax.y); vMax.z = max(boxVertex[i].z,vMax.z); } _aabbBox.setExtents(vMin,vMax); } /** * 入口函数 */ virtual int main(int /*argc*/,char** /*argv*/) { _device.enableRenderState(GL_DEPTH_TEST); _shader.initialize(_device); _lighting.initialize(_device); _texture = _device.createTexture2DFromFile("data/image/1.tex"); _textureRole= _device.createTexture2DFromFile("data/image/main.tex"); _role.setPosition(float3(0,0,0)); _role.setTarget(float3(50,0,50)); _camera.setRadius(50); _camera.setEye(float3(50,50,50)); _camera.setTarget(float3(0,0,0)); _camera.calcDir(); _camera.setUp(float3(0,1,0)); return 0; } /** * 绘制函数 */ virtual void onRender(const FrameEvent& /*evt*/,int width,int height) { glClear(GL_DEPTH_BUFFER_BIT | GL_COLOR_BUFFER_BIT); glViewport(0,0,width,height); _camera.setViewSize(width,height); _role.render(1.0f/60.0f); _camera.setTarget(_role._pos); _camera.update(); CELL::matrix4 matModel; matModel.translate(_role._pos); CELL::matrix4 matView = _camera.getView(); CELL::matrix4 matProj = CELL::perspective<float>(45.0f,float(width)/float(height),0.1f,1000.0f); _camera.setProject(matProj); CELL::matrix4 MVP = matProj * matView ; float gSize = 100; float gPos = 0; float rept = 100; Vertex grounds[] = { { -gSize, gPos,-gSize,0.0f, 0.0f,1.0f, 1.0f, 1.0f,1.0f,0,1,0 }, { gSize, gPos,-gSize,rept, 0.0f,1.0f, 1.0f, 1.0f,1.0f,0,1,0 }, { gSize, gPos, gSize,rept, rept,1.0f, 1.0f, 1.0f,1.0f,0,1,0 }, { -gSize, gPos,-gSize,0.0f, 0.0f,1.0f, 1.0f, 1.0f,1.0f,0,1,0 }, { gSize, gPos, gSize,rept, rept,1.0f, 1.0f, 1.0f,1.0f,0,1,0 }, { -gSize, gPos, gSize,0.0f, rept,1.0f, 1.0f, 1.0f,1.0f,0,1,0 }, }; _device.bindTexture2D(&_texture); _shader.begin(); { _device.setUniformMatrix4fv(_shader._MVP,1,false,MVP.data()); _device.setUniform1i(_shader._texture,0); _device.attributePointer(_shader._positionAttr, 3, GL_FLOAT,false,sizeof(Vertex),&grounds[0].x); _device.attributePointer(_shader._uvAttr, 2, GL_FLOAT,false,sizeof(Vertex),&grounds[0].u); _device.attributePointer(_shader._colorAttr, 4, GL_FLOAT,false,sizeof(Vertex),&grounds[0].r); _device.drawArray(GL_TRIANGLES,0,6); _device.setLineWidth(5); _device.attributePointer(_shader._positionAttr, 3, GL_FLOAT,false,sizeof(Vertex),&_ptLine[0].x); _device.attributePointer(_shader._uvAttr, 2, GL_FLOAT,false,sizeof(Vertex),&_ptLine[0].u); _device.attributePointer(_shader._colorAttr, 4, GL_FLOAT,false,sizeof(Vertex),&_ptLine[0].r); _device.drawArray(GL_LINES,0,2); } _shader.end(); _lighting.begin(); { CELL::matrix4 matRot(1); CELL::matrix4 matModel; matModel.translate(_role._pos); static float agle = 0; matRot.rotateYXZ(agle,agle,agle); agle += 1.0f; MVP = matProj * matView * ( matModel * matRot ); CELL::matrix4 mv = matView *(matModel * matRot); CELL::matrix4 mvInv = mv.inverse(); _aabbTran = _aabbBox; CELL::matrix4 matTra = matModel * matRot; _aabbTran.transform(matTra); float3 arBox[8]; Vertex vertexBox[8]; _aabbTran.getAllCorners(arBox); for (size_t i = 0 ; i < 8 ;++ i ) { vertexBox[i].x = arBox[i].x; vertexBox[i].y = arBox[i].y; vertexBox[i].z = arBox[i].z; } short boxIndex[24] = { 0,1,2,3, 2,3,7,4, 4,5,6,7, 0,1,5,6, 1,2,4,5, 0,3,7,6 }; float fEyePosition[] = { _camera._eye.x, _camera._eye.y, _camera._eye.z, 0.0f}; float fLightVector[] = { 0.0f, 1.0f, 0.0f, 0.0f}; // Normalize light vector float fLength = sqrtf( fLightVector[0]*fLightVector[0] + fLightVector[1]*fLightVector[1] + fLightVector[2]*fLightVector[2] ); fLightVector[0] /= fLength; fLightVector[1] /= fLength; fLightVector[2] /= fLength; //! 绘制地面 glUniformMatrix4fv(_lighting.modelViewProjection, 1, false, MVP.data()); //! 绘制地面 glUniformMatrix4fv(_lighting.modelViewInverse, 1, false, mvInv.data()); glUniform3fv(_lighting.eyePosition, 1,fEyePosition); glUniform3fv(_lighting.lightVector, 1,fLightVector); glVertexAttribPointer(_lighting._positionAttr,3, GL_FLOAT, false, sizeof(Vertex),&boxVertex[0].x); glVertexAttribPointer(_lighting._normal,3, GL_FLOAT, false, sizeof(Vertex),&boxVertex[0].nx); glDrawArrays(GL_TRIANGLES,0,36 ); MVP = matProj * matView; glUniformMatrix4fv(_lighting.modelViewProjection, 1, false, MVP.data()); glVertexAttribPointer(_lighting._positionAttr,3, GL_FLOAT, false, sizeof(Vertex),&vertexBox[0].x); glVertexAttribPointer(_lighting._normal,3, GL_FLOAT, false, sizeof(Vertex),&vertexBox[0].nx); glDrawElements(GL_LINE_STRIP,4,GL_UNSIGNED_SHORT, &boxIndex[0]); glDrawElements(GL_LINE_STRIP,4,GL_UNSIGNED_SHORT, &boxIndex[4]); glDrawElements(GL_LINE_STRIP,4,GL_UNSIGNED_SHORT, &boxIndex[8]); glDrawElements(GL_LINE_STRIP,4,GL_UNSIGNED_SHORT, &boxIndex[12]); glDrawElements(GL_LINE_STRIP,4,GL_UNSIGNED_SHORT, &boxIndex[16]); glDrawElements(GL_LINE_STRIP,4,GL_UNSIGNED_SHORT, &boxIndex[20]); } _lighting.end(); } /** * 鼠标移动 */ virtual void onMouseMove(int absx, int absy, int absz) { if (absz > 0) { _camera._radius = _camera._radius * 1.1f; } else if(absz < 0) { _camera._radius = _camera._radius * 0.9f; } else if(_rightButtonDown) { float2 curPos(absx,absy); float2 offset = curPos - _mousePos; _mousePos = curPos; _camera.rotateView(offset.x * 0.1f); _camera.update(); } } /** * 鼠标按下 */ virtual void onMousePress(int absx, int absy, CELL::MouseButton id) { if (id == CELL::MouseButton::Left) { Ray ray = _camera.createRayFromScreen(absx,absy); float3 pos = ray.getOrigin(); float tm = abs((pos.y) / ray.getDirection().y); float3 target = ray.getPoint(tm); _role.setTarget(float3(target.x,0,target.z)); _ptLine[0].x = pos.x; _ptLine[0].y = pos.y; _ptLine[0].z = pos.z; _ptLine[1].x = target.x; _ptLine[1].y = 0; _ptLine[1].z = target.z; if (ray.intersects(_aabbTran).first) { int i = 0; } else { int ss = 0; } } else if( id== CELL::MouseButton::Right) { _mousePos = float2(absx,absy); _rightButtonDown = true; } } /** * 鼠标释放 */ virtual void onMouseRelease(int /*absx*/, int /*absy*/, CELL::MouseButton id) { if( id == CELL::MouseButton::Right) { _rightButtonDown = false; } } }; }
[ "xietiexiang@126.com" ]
xietiexiang@126.com
82c5a7912a3b43c02b9a9702b10e92b221e64c7b
4a3dabf3f5e0a6e3db59d6595c6e3f44c49f4ab2
/superSingleCell-c3dEngine/singleCellGame/gameObjs/ground.h
381cd828f24636138510996433d9d529b55e193e
[]
no_license
Michael-Z/superSingleCell-c3dEngine
20ae96cbf31d9a7835c22e857470fb8914bd166d
3227b3747a436a5c8d3710e5c4a96ed3c86e787e
refs/heads/master
2020-12-25T22:19:21.340755
2014-03-21T16:12:00
2014-03-21T16:12:00
null
0
0
null
null
null
null
UTF-8
C++
false
false
748
h
// // ground.h // HelloOpenGL // // Created by wantnon (yang chao) on 14-2-4. // // #ifndef __HelloOpenGL__ground__ #define __HelloOpenGL__ground__ #include <iostream> using namespace std; #include "terrain.h" class Cground:public Cterrain { protected: bool m_isDoTexBlend;//是否通进纹理混合 public: void loadConfig(const string&fileNameWithExt); void loadConfig_texBlend(const string&fileNameWithExt); Cground(){ m_isDoTexBlend=false; } virtual~Cground(){} void setIsDoTexBlend(bool value){ m_isDoTexBlend=value; } bool getIsDoTexBlend()const { return m_isDoTexBlend; } }; #endif /* defined(__HelloOpenGL__ground__) */
[ "yangchao1@chukong-inc.com" ]
yangchao1@chukong-inc.com
4dd0f828ca8c4423e918be05f84e274263ba1a9d
3f160b2ca26d03b104f9dcabf67218bd6d7afc8a
/B&B ConSume/3D_Game/Texture.cpp
6fd89b76acec2d47b123a97578d0d330eeaec647
[]
no_license
hwenradiant0/B-BConsume
3afdb92320ae796604b999d2a015f643f9c5248d
d0f936f39d2aacba1751b06547b0088b3455affb
refs/heads/master
2020-04-28T05:17:13.206910
2019-03-11T14:17:54
2019-03-11T14:17:54
175,013,986
0
0
null
null
null
null
UTF-8
C++
false
false
1,508
cpp
#include "Texture.h" CTexture::CTexture() { m_pTx = NULL; memset(&m_Img, 0, sizeof m_Img); } CTexture::~CTexture() { Destroy(); } void CTexture::Destroy() { if(m_pTx) { m_pTx->Release(); m_pTx= NULL; } } INT CTexture::Create(char* sFile) { DWORD dColorKey = NULL; if(FAILED(D3DXCreateTextureFromFileEx( Get_Device , sFile , D3DX_DEFAULT , D3DX_DEFAULT , 1 , 0 , D3DFMT_UNKNOWN , D3DPOOL_MANAGED , D3DX_FILTER_NONE , D3DX_FILTER_NONE , dColorKey , &m_Img , NULL , &m_pTx )) ) { m_pTx = NULL; MessageBox( GetActiveWindow() , "Create Texture Failed" , "Err" , MB_ICONEXCLAMATION ); return -1; } return 0; } INT CTexture::Arry_Create(char* sFile[], int num) { DWORD dColorKey = NULL; for(int i=0 ; i<num ; ++i) { if(FAILED(D3DXCreateTextureFromFileEx( Get_Device , sFile[i] , D3DX_DEFAULT , D3DX_DEFAULT , 1 , 0 , D3DFMT_UNKNOWN , D3DPOOL_MANAGED , D3DX_FILTER_NONE , D3DX_FILTER_NONE , dColorKey , &m_Img , NULL , &m_arr_pTx[i] )) ) { m_arr_pTx[i] = NULL; MessageBox( GetActiveWindow() , "Create Texture Failed" , "Err" , MB_ICONEXCLAMATION ); return -1; } } return 0; } LPDIRECT3DTEXTURE9 CTexture::GetTexture() { return m_pTx; } D3DXIMAGE_INFO CTexture::GetImageInfo() { return m_Img; } LPDIRECT3DTEXTURE9* CTexture::Arry_GetTexture() { return m_arr_pTx; } D3DXIMAGE_INFO* CTexture::Arry_GetImageInfo() { return m_arr_Img; }
[ "hwenradiant0@gmail.com" ]
hwenradiant0@gmail.com
d05e86e7d4566a52c68afa20d0ee4dbf4db7782f
154dfd2a2130a3a7731a9a9b431e8295fbf82cd2
/TIOJ/TIOJ1152.cpp
eefbc080a02cd4ee0c1e181521c1ccdb21c3e9a7
[]
no_license
ltf0501/Competitive-Programming
1f898318eaecae14b6e040ffc7e36a9497ee288c
9660b28d979721f2befcb590182975f10c9b6ac8
refs/heads/master
2022-11-20T21:08:45.651706
2020-07-23T11:55:05
2020-07-23T11:55:05
245,600,907
0
0
null
null
null
null
UTF-8
C++
false
false
640
cpp
#include<cstdio> #include<algorithm> #include<cstring> #include<vector> using namespace std; #define maxn 10000+5 vector<int> G[maxn]; int n; int max_d,max_v; void dfs(int u,int fa,int d) { if(d>max_d)max_d=d,max_v=u; for(int i=0;i<G[u].size();i++) { int v=G[u][i]; if(v==fa)continue; dfs(v,u,d+1); } } main() { scanf("%d",&n); for(int i=0;i<n;i++) { int a; while(~scanf("%d",&a) && a!=-1)G[i].push_back(a),G[a].push_back(i); } max_d=0; dfs(0,-1,0); max_d=0; dfs(max_v,-1,0); printf("%d\n",max_d); return 0; }
[ "0110420@stu.nknush.kh.edu.tw" ]
0110420@stu.nknush.kh.edu.tw
0bfabd326430c4eb088db32bcab5bf0f95574079
a9b82319f728c950032d46f57cb776a801f80ac8
/src/Core/TypeStringifier.cpp
5159896cd1b81521badd7685ebc5018fe005ebb3
[]
no_license
shikang/BlackHole-Engine
eebea87a2b06be27601804470e26441ff1f1e0b1
8dc2324d7ac4c3b553d67ae04231e6438cf81af0
refs/heads/master
2021-01-20T17:06:22.647627
2016-08-08T09:38:22
2016-08-08T09:38:22
60,777,549
0
0
null
null
null
null
UTF-8
C++
false
false
2,293
cpp
// Precompiled Headers #include "Core/StdAfx.h" #include "Core/TypeStringifier.h" namespace BH { TypeStringifier::TypeStringifier() { } TypeStringifier::~TypeStringifier() { } void TypeStringifier::ToStringEnum( String & str, const Type * type, const void * obj, const FieldAttributes * attr ) { if ( attr && attr->Hex != 0 ) { std::ostringstream o; o << std::hex << std::showbase << *reinterpret_cast<const u32 *>( obj ); str = o.str(); return; } if ( *reinterpret_cast<const u32 *>( obj ) == 0 ) { str = "0"; return; } if ( const EnumConst * e = type->GetEnum( *reinterpret_cast<const u32 *>( obj ) ) ) str = e->Name.Text; else str = ""; } void TypeStringifier::FromStringEnum( const String & str, const Type * type, void * obj, const FieldAttributes * attr ) { if ( attr && attr->Hex != 0 ) { std::istringstream i( str ); i >> std::hex >> ( *reinterpret_cast<u32*>( obj ) ); return; } if ( str == "0" ) { *reinterpret_cast<u32*>( obj ) = 0; return; } if ( const EnumConst* e = type->GetEnum( CName( str.c_str() ) ) ) *reinterpret_cast<u32*>( obj ) = e->Value; } template<> void TypeStringifier::FromStringDef<bool>( const String & str, const Type *, void * obj, const FieldAttributes * ) { if ( str.length() > 0 ) { if ( str.length() == 1 ) { switch ( str[0] ) { case '1': ( *reinterpret_cast<bool*>( obj ) ) = true; break; case '0': ( *reinterpret_cast<bool*>( obj ) ) = false; break; } return; } String tstr = str; std::transform( tstr.begin(), tstr.end(), tstr.begin(), tolower ); // In the case of using custom string if ( tstr == "true" ) ( *reinterpret_cast<bool*>( obj ) ) = true; else if ( tstr == "false" ) ( *reinterpret_cast<bool*>( obj ) ) = false; } } TypeStringifier::ToString TypeStringifier::GetToString( const Type * type ) { ToStringMap::iterator it = mToStringMap.find( type->Name ); if ( it != mToStringMap.end() ) return it->second; return nullptr; } TypeStringifier::FmString TypeStringifier::GetFromString( const Type * type ) { FmStringMap::iterator it = mFmStringMap.find( type->Name ); if ( it != mFmStringMap.end() ) return it->second; return nullptr; } }
[ "shikang.n@digipen.edu" ]
shikang.n@digipen.edu
9807fd34beebcada135a98e42de73e2d985e930f
b179ee1c603139301b86fa44ccbbd315a148c47b
/engine/commands/screens/include/ScreenKeyboardCommandMap.hpp
fd80d608e6a64686f186125678dc99e38884e777
[ "MIT", "Zlib" ]
permissive
prolog/shadow-of-the-wyrm
06de691e94c2cb979756cee13d424a994257b544
cd419efe4394803ff3d0553acf890f33ae1e4278
refs/heads/master
2023-08-31T06:08:23.046409
2023-07-08T14:45:27
2023-07-08T14:45:27
203,472,742
71
9
MIT
2023-07-08T14:45:29
2019-08-21T00:01:37
C++
UTF-8
C++
false
false
640
hpp
#pragma once #include "KeyboardCommandMap.hpp" class ScreenKeyboardCommandMap : public KeyboardCommandMap { public: ScreenKeyboardCommandMap(); virtual ~ScreenKeyboardCommandMap(); // Fail silently. virtual void command_not_found(const std::string& keyboard_input) override; std::string get_settings_prefix() const override; // serialize/deserialize taken care of by KeyboardCommandMap virtual KeyboardCommandMap* clone() override; protected: virtual void initialize_command_mapping(const Settings& settings) override; private: ClassIdentifier internal_class_identifier() const override; };
[ "jcd748@mail.usask.ca" ]
jcd748@mail.usask.ca
3908cd3e3f34a72d83bd6ee649e3706985950495
d8decc0da74b655a4204884088c20d30d5ee501b
/this summer/contest/prime path.cpp
c74321f670424458ff78779f0f9f6d2b63ff263a
[]
no_license
bobshih/competitive_coding
b002714d59a0e58811234994cf67f1a6fb9c89f1
2f0e6eb574a11cbe386d9457f6d80569391eb9a2
refs/heads/master
2020-04-14T23:40:57.330314
2019-01-10T17:09:25
2019-01-10T17:09:25
164,211,752
0
0
null
null
null
null
UTF-8
C++
false
false
2,914
cpp
#include <iostream> #include <cmath> #include <cstdio> #include <cstring> #include <queue> using namespace std; //int prime[1229]; bool prime[10001]; int prime_d[10001]; bool used[10001]; bool ispri(int a){ for(int i = 2;i <= sqrt(a);i++){ if(a%i == 0){return 0;} } return 1; } void BFS(int start,int ended){ if(start == ended){ //cout <<"start = "<<start<<" ended = "<<ended<<"level = "<<prime_d[ended]<<endl; //system("pause"); return ;} //cout <<"start = "<<start<<" ended = "<<ended<<endl; int a[5]; a[4] = 0; int temp; queue<int> aqueue; aqueue.push(start); while(!aqueue.empty()){ temp = aqueue.front(); for(int j = 3;j >= 0 ;j--){ int p = pow(10.0,j); int t = temp/p; a[j] = t; temp = temp-a[j]*p; //cout <<a[j]<<endl; for(int i = 0;i < 10;i++){ //cout <<"i = "<<i<<endl; if(j == 3 && i == 0)continue; int change = aqueue.front()-a[j]*pow(10.0,j)+i*pow(10.0,j); if(!used[change] && prime[change]){ used[change] = true;prime_d[change] = prime_d[aqueue.front()] + 1; //cout <<"start = "<<aqueue.front()<<" change = "<<change<<"level = "<<prime_d[change]<<endl; //system("pause"); aqueue.push(change); } } //system("pause"); } aqueue.pop(); } /*for(int i = 0;i < 10;i++){ system("pause"); for(int j = 0;j < 4;j++){ system("pause"); int t = pow(10.0,j+1); int p = pow(10.0,j); cout <<"t = "<<t<<endl; int temp = start/t*t; temp = start - temp; temp = start - temp + i*p; cout <<"start = "<<start<<" temp = "<<temp<<endl; if(!used[temp] && prime[temp]){ used[temp] = 1;prime_d[temp] = prime_d[start] + 1; BFS(temp,ended); } } }*/ } int main() { int test; scanf("%d",&test); memset(prime,0,10001); for(int i = 2;i < 10000;i++){ if(ispri(i)){ //cout <<"a = "<<a<<" i = "<<i<<endl; //system("pause"); prime[i] = 1; //if(a == 1229)break; } } for(int i = 0;i < 10001;i++){ //if(prime[i])cout <<i<<endl; //system("pause");} }//cout <<"a = "<<a<<endl; int temp1,temp2; int cost; for(int a = 0;a < test;a++){ scanf("%d %d",&temp1,&temp2); memset(prime_d,-1,10001); memset(used,0,10001); prime_d[temp1] = 0; used[temp1] = 1; BFS(temp1,temp2); if(used[temp2] == 0){ printf("Impossible\n"); }else {printf("%d\n",prime_d[temp2]);} } return 0; }
[ "施帛辰 bob" ]
施帛辰 bob
3c8ea5ebf2a316dce0528ceb6603b3798c075f3a
4a65b0e5b77d57a6dde55e2bf001c415f148ef21
/Src/Emoticon.h
bf5a3e1f628bfcd2d1612c693af627a858733989
[ "MIT" ]
permissive
thinkpractice/bme
99829da10f79b224cececb996ba1480d11dab2d1
8f55457fa2900e41ff112188b8683b4312e99d73
refs/heads/master
2021-06-01T22:26:05.779520
2016-11-19T17:24:40
2016-11-19T17:24:40
56,915,046
1
0
null
null
null
null
UTF-8
C++
false
false
840
h
/***************************************************************** * Copyright (c) 2005 Tim de Jong * * * * All rights reserved. * * Distributed under the terms of the MIT License. * *****************************************************************/ #ifndef EMOTICON_H #define EMOTICON_H #include <interface/Bitmap.h> #include <support/String.h> #include <vector> using namespace std; class Emoticon { public: Emoticon(); virtual ~Emoticon(); void AddIcon(BBitmap *icon); vector<BBitmap*> Icons(); void SetName(BString name); BString Name(); void AddText(BString text); vector<BString> GetTextRepresentations(); private: vector<BBitmap*> m_icons; vector<BString> m_textRepresentations; BString m_name; }; #endif
[ "opensource@thinkpractice.nl" ]
opensource@thinkpractice.nl
6b6ab04bbd70770ea1c4c7ec566e54b38afa79da
c470e3038d7f8e68a9485fa7dd1f1cd15b175ef2
/WrapCef/IPC.h
8e27e5e2bb09bc04be06c1fce441649ccf041e85
[]
no_license
oamates/cefui
2d365131536d6fa26bd6998c14163e7d6ac9f491
c4475fab3d6a501b1ed92af86ae75327aeb1efa6
refs/heads/master
2021-07-23T12:31:57.827970
2017-11-03T02:29:12
2017-11-03T02:29:12
null
0
0
null
null
null
null
GB18030
C++
false
false
6,172
h
#ifndef _IPC_H #define _IPC_H #pragma once #include <windows.h> #include "DataProcessQueue.h" #include "ipcio.h" #include <functional> #include "cjpickle.h" #include <vector> #include <map> #define BUF_SIZE 8192 namespace cyjh{ class IPC; typedef std::function< void(const unsigned char*, DWORD)> recv_cb; typedef std::function< void()> disconst_cb; enum _state{ CONNECTING_STATE, READING_STATE, }; struct _SENDPACKET { _IPC_MESSAGE* m_IPC_Data; _SENDPACKET() { m_IPC_Data = NULL; } ~_SENDPACKET() { if (m_IPC_Data) { delete m_IPC_Data; } } }; //缓存数据,存放需要封包的数据 struct _CACHEDATA { unsigned int m_nLen; //数据长度 unsigned int m_nCurr; //当前存放多少数据 unsigned char *m_pData; //缓存空间 #ifdef _DEBUG unsigned int m_writeTimes; unsigned int m_test; #endif _CACHEDATA(unsigned int nLen) { #ifdef _DEBUG m_writeTimes = 0; m_test = 0; #endif m_nCurr = 0; m_nLen = nLen; m_pData = new unsigned char[nLen]; } ~_CACHEDATA() { delete[]m_pData; } const unsigned char * GetData() { return m_pData; } bool WriteData(unsigned char* pSrc, unsigned int nlen, unsigned int nOffset) { #ifdef _DEBUG ++m_writeTimes; #endif //errno_t err = memcpy_s(m_pData + m_nCurr, m_nLen - m_nCurr, pSrc, nlen); errno_t err = memcpy_s(m_pData + nOffset, nlen, pSrc, nlen); if (err == 0) { m_nCurr += nlen; } return (err == 0); } const bool complate(){ return m_nCurr == m_nLen; } }; typedef std::map<int, std::shared_ptr<_CACHEDATA> > CACHEDATA_MAP; //组装数据包 class _IPC_MESSAGE_ITEM { public: _IPC_MESSAGE_ITEM(IPC* inst) :ipc_(inst), total_msg_size_(sizeof(_IPC_MESSAGE)) { memset(&msg_, 0, sizeof(msg_)); curr_ = reinterpret_cast<unsigned char*>(&msg_); //total_msg_size_ = sizeof(_IPC_MESSAGE); write_size_ = 0; } virtual ~_IPC_MESSAGE_ITEM(){} void Append(const unsigned char* data, const DWORD len); const _IPC_MESSAGE* GetMsg(){ return &msg_; } private: _IPC_MESSAGE msg_; unsigned char *curr_; IPC* ipc_; DWORD write_size_; const DWORD total_msg_size_; }; class IPC : public CDataProcessQueue<_SENDPACKET> { friend _IPC_MESSAGE_ITEM; public: IPC(IPC* inst); virtual ~IPC(); /*const bool isValidHandle(const HANDLE& handle) { return handle != NULL && handle != INVALID_HANDLE_VALUE; }*/ virtual bool Send(const unsigned char* data, DWORD len, DWORD nTimeout); const WCHAR* getName() const{ return name_; } virtual bool Close() = 0; protected: bool IPC::proxy_send(const unsigned char* data, DWORD len, DWORD nTimeout); virtual BOOL ProcDataPack(std::shared_ptr<_SENDPACKET>) override; BOOL SubmitPack(_IPC_MESSAGE * data, unsigned int nTimeout); virtual void RecvData(_IPC_MESSAGE*); virtual void RecvData(unsigned char* recv_buf_, DWORD len); //还回true,表示收到完整_IPC_MESSAGE数据包, void CombinPack(unsigned char* recv_buf_, DWORD len); virtual void NotifyRecvData(unsigned char*, DWORD len) = 0; const int& generateID(); protected: OVERLAPPED op_; HANDLE srvpipe_, remotepipe_; HANDLE hEvents_[2]; unsigned char recv_buf_[BUF_SIZE]; _IPC_MESSAGE_ITEM msg_item_; CACHEDATA_MAP m_cacheMap; int seriaNum_; //发送id std::mutex seriaNumberMutex_; WCHAR name_[64]; HANDLE hFin_; }; class IPCPipeSrv : public IPC { public: IPCPipeSrv(const WCHAR* name); virtual ~IPCPipeSrv(); //virtual bool Send(char* data, int len) override; virtual bool Close() override; protected: //virtual BOOL ProcDataPack(std::shared_ptr<_SENDPACKET>) override; static unsigned int __stdcall WorkThread(void*); //virtual void RecvData(_IPC_MESSAGE*) override; //virtual void RecvData(unsigned char* recv_buf_, DWORD len) override; virtual void NotifyRecvData(unsigned char*, DWORD len) override{ } private: bool succCreate_; bool bPendingIO_; }; class IPCPipeClient : public IPC { public: IPCPipeClient(const WCHAR* name); virtual ~IPCPipeClient(); void SetRecvCallback(recv_cb cb){ cb_ = cb; } template<typename T> void BindDisconstCallback(void (T::*function)(), T* obj){ disconstCB_ = std::bind(function, obj); } //virtual bool Send(char* data, int len) override; virtual bool Close() override; protected: //virtual BOOL ProcDataPack(std::shared_ptr<_SENDPACKET>) override; static unsigned int __stdcall WorkThread(void*); virtual void RecvData(_IPC_MESSAGE*) override; virtual void RecvData(unsigned char* recv_buf_, DWORD len) override; virtual void NotifyRecvData(unsigned char*, DWORD len) override; private: // HANDLE pipe_; recv_cb cb_; disconst_cb disconstCB_; }; class IPCUnit{ public: IPCUnit(const WCHAR* srv_ame, const WCHAR* cli_name); virtual ~IPCUnit(); bool Send(const unsigned char* data, DWORD len, DWORD nTimeout); void NotifyDisconst(); template<typename T> void BindRecvCallback(void (T::*function)(const unsigned char*, DWORD), T* obj){ recv_cb cb = std::bind(function, obj, std::placeholders::_1, std::placeholders::_2); cli_.SetRecvCallback(cb); } int getID(){ return id_; } const WCHAR* getSrvName(){ return srv_.getName(); } const WCHAR* getCliName(){ return cli_.getName(); } void Close(); void Attach(); void Detch(); const int& AttachNum(){ std::unique_lock<std::mutex> lock(attach_mutex_); return attach_num_; } private: IPCPipeSrv srv_; IPCPipeClient cli_; int id_; bool close_; int attach_num_; std::mutex attach_mutex_; }; class IPC_Manager { public: virtual ~IPC_Manager(){} static IPC_Manager& getInstance(){ return s_inst; } std::shared_ptr<IPCUnit> GenerateIPC(const WCHAR*, const WCHAR*); std::shared_ptr<IPCUnit> GetIpc(const int& id); int MatchIpc(const WCHAR*, const WCHAR*); void Destruct(int id); static IPC_Manager s_inst; protected: IPC_Manager(){} //std::vector<std::shared_ptr<IPCUnit>> ipcs_; std::map<int, std::shared_ptr<IPCUnit>> ipcs_; private: static volatile int id_; private: }; } #endif
[ "lincolnfz@gmail.com" ]
lincolnfz@gmail.com
2b6ef164e42650a6c26f27a76497ba4c18cd3ab2
bfa40191bb6837f635d383d9cd7520160d0b03ac
/LightNote/Source/Dependencies/CEGUI/src/XMLParserModules/TinyXML/XMLParser_tinyxml.cpp
3920a7f1cdb6a58d7f957a3b29146a0d370e83bb
[ "MIT" ]
permissive
lriki/LightNote
87ec6969c16f2919d04fdaac9d0e7ed389f403ad
a38542691d0c7453dd108bcf1d653a08bb1b6b6b
refs/heads/master
2021-01-10T19:16:33.199071
2015-02-01T08:41:06
2015-02-01T08:41:06
25,684,431
0
0
null
null
null
null
UTF-8
C++
false
false
6,032
cpp
/*********************************************************************** filename: CEGUITinyXMLParser.cpp created: Sun Mar 13 2005 author: Paul D Turner *************************************************************************/ /*************************************************************************** * Copyright (C) 2004 - 2006 Paul D Turner & The CEGUI Development Team * * 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 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 "CEGUI/XMLParserModules/TinyXML/XMLParser.h" #include "CEGUI/ResourceProvider.h" #include "CEGUI/System.h" #include "CEGUI/XMLHandler.h" #include "CEGUI/XMLAttributes.h" #include "CEGUI/Logger.h" #include "CEGUI/Exceptions.h" #include "tinyxml.h" //---------------------------------------------------------------------------// // These are to support the <=2.5 and >=2.6 API versions #ifdef CEGUI_TINYXML_HAS_2_6_API # define CEGUI_TINYXML_ELEMENT TINYXML_ELEMENT # define CEGUI_TINYXML_TEXT TINYXML_TEXT #else # define CEGUI_TINYXML_ELEMENT ELEMENT # define CEGUI_TINYXML_TEXT TEXT #endif // Start of CEGUI namespace section namespace CEGUI { class TinyXMLDocument : public TiXmlDocument { public: TinyXMLDocument(XMLHandler& handler, const RawDataContainer& source, const String& schemaName); ~TinyXMLDocument() {} protected: void processElement(const TiXmlElement* element); private: XMLHandler* d_handler; }; TinyXMLDocument::TinyXMLDocument(XMLHandler& handler, const RawDataContainer& source, const String& /*schemaName*/) { d_handler = &handler; // Create a buffer with extra bytes for a newline and a terminating null size_t size = source.getSize(); char* buf = new char[size + 2]; memcpy(buf, source.getDataPtr(), size); // PDT: The addition of the newline is a kludge to resolve an issue // whereby parse returns 0 if the xml file has no newline at the end but // is otherwise well formed. buf[size] = '\n'; buf[size+1] = 0; // Parse the document TiXmlDocument doc; if (!doc.Parse((const char*)buf)) { // error detected, cleanup out buffers delete[] buf; // throw exception CEGUI_THROW(FileIOException("an error occurred while " "parsing the XML document - check it for potential errors!.")); } const TiXmlElement* currElement = doc.RootElement(); if (currElement) { CEGUI_TRY { // function called recursively to parse xml data processElement(currElement); } CEGUI_CATCH(...) { delete [] buf; CEGUI_RETHROW; } } // if (currElement) // Free memory delete [] buf; } void TinyXMLDocument::processElement(const TiXmlElement* element) { // build attributes block for the element XMLAttributes attrs; const TiXmlAttribute *currAttr = element->FirstAttribute(); while (currAttr) { attrs.add((encoded_char*)currAttr->Name(), (encoded_char*)currAttr->Value()); currAttr = currAttr->Next(); } // start element d_handler->elementStart((encoded_char*)element->Value(), attrs); // do children const TiXmlNode* childNode = element->FirstChild(); while (childNode) { switch(childNode->Type()) { case CEGUI_TINYXML_ELEMENT: processElement(childNode->ToElement()); break; case CEGUI_TINYXML_TEXT: if (childNode->ToText()->Value() != '\0') d_handler->text((encoded_char*)childNode->ToText()->Value()); break; // Silently ignore unhandled node type }; childNode = childNode->NextSibling(); } // end element d_handler->elementEnd((encoded_char*)element->Value()); } TinyXMLParser::TinyXMLParser(void) { // set ID string d_identifierString = "CEGUI::TinyXMLParser - Official tinyXML based parser module for CEGUI"; } TinyXMLParser::~TinyXMLParser(void) {} void TinyXMLParser::parseXML(XMLHandler& handler, const RawDataContainer& source, const String& schemaName) { TinyXMLDocument doc(handler, source, schemaName); } bool TinyXMLParser::initialiseImpl(void) { // This used to prevent deletion of line ending in the middle of a text. // WhiteSpace cleaning will be available throught the use of String methods directly //TiXmlDocument::SetCondenseWhiteSpace(false); return true; } void TinyXMLParser::cleanupImpl(void) {} } // End of CEGUI namespace section
[ "ilys.vianote@gmail.com" ]
ilys.vianote@gmail.com
1c9000bf3514463aafd73326b19578348cab16d3
27841012ed226ef2139a166713f997558b1cc460
/FileStream.h
f5cfc8e9ae52a01a1c8139a1611169a6b7326d9a
[]
no_license
J-CITY/CBCMAC-with-AES
2fac8d081bb67cf7b8492f96c830c039021cbab3
9472e401a88d56e0f3416fd1654e6c57cc1057ec
refs/heads/master
2021-09-06T01:44:53.397655
2018-02-01T11:24:08
2018-02-01T11:24:08
115,849,526
0
0
null
null
null
null
WINDOWS-1251
C++
false
false
4,708
h
#ifndef FILESTREAM_H_INCLUDED #define FILESTREAM_H_INCLUDED #include <iostream> #include <vector> #include <string> #include <windows.h> #include <dirent.h> #include <sstream> #include "AES.h" #include "CBC-MAC.h" class FileStream { std::string KEY_1 = "1234567890-=qwertyuiop[]asdfghjk"; std::string KEY_2 = "1234567890-=qwertyuiop[]asdfghjq"; std::string KEY_3 = "1234567890-=qwertyuiop[]asdfghjk"; CBCMAC *tag; AES *aes; std::vector<std::vector<char>> fileBlocks; void printBar(double load) { COORD p = { 0, 5 }; SetConsoleCursorPosition( GetStdHandle( STD_OUTPUT_HANDLE ), p ); std::cout << "["; for (int j = 0; j < 10; j++) { std::cout << ((j < load) ? "#" : " "); } std::cout << "]"; } public: int bufferInByte = 1000000; FileStream(const int keySize = AES::KEY_SIZE_256) { aes = new AES(keySize); tag = new CBCMAC(keySize); } ~FileStream() { delete aes; delete tag; } void SetKeys(std::string k1, std::string k2, std::string k3) { KEY_1 = k1; KEY_2 = k2; KEY_3 = k3; } void PackFile(std::string fileName) { std::string pack = fileName + "_pack"; std::cout << "Pack file: " << pack << std::endl; if(!CreateDirectory(pack.c_str(), NULL) && ERROR_ALREADY_EXISTS != GetLastError()) { return; } std::ifstream fin(fileName, std::ifstream::binary); std::vector<char> buffer(bufferInByte, 0); std::streamsize s; while(fin.read(buffer.data(), buffer.size())) { s = fin.gcount(); fileBlocks.push_back(buffer); } if (s = fin.gcount()) { buffer.resize(s); fin.read(buffer.data(), s); fileBlocks.push_back(buffer); } COORD p = { 0, 4 }; SetConsoleCursorPosition( GetStdHandle( STD_OUTPUT_HANDLE ), p ); std::cout << "Pack...\n"; std::ofstream fout; tag->SetKey(KEY_1, KEY_2); std::string tagStr = ""; double step = 10.0/fileBlocks.size()+1; double load = 0; for (int i = fileBlocks.size()-1; i >= 0; i--) { fout.open(pack + "/" + std::to_string(i+1) + ".pk", std::ifstream::binary); std::string str(fileBlocks[i].begin(), fileBlocks[i].end()); if (i != fileBlocks.size()-1) { str = tagStr + str; } tag->SetText(str, INPUT_TYPE::TEXT_FROM_STRING); tagStr = tag->GetTag(); fout.write(str.c_str(), str.size()); fout.close(); load += step; printBar(load); } printBar(10); fout.open(pack + "/0.pk", std::ifstream::binary); fout.write(tagStr.c_str(), tagStr.size()); fout.close(); } std::string readFile(const std::string& fileName) { std::ifstream f(fileName); f.seekg(0, std::ios::end); size_t size = f.tellg(); std::string s(size, ' '); f.seekg(0); f.read(&s[0], size); // по стандарту можно в C++11, по факту работает и на старых компиляторах return s; } void UnpackFile(std::string fileName) { std::string unpack = fileName + ".mp3"; std::cout << "Unpack file: " << unpack << std::endl; int file_count = 0; DIR *dp; struct dirent *ep; dp = opendir (fileName.c_str()); if (dp != NULL) { while (ep = readdir(dp)) file_count++; (void) closedir(dp); } file_count -= 2; std::string tagStr = ""; tag->SetKey(KEY_1, KEY_2); double step = 10.0/file_count; double load = 0; std::ofstream fout(unpack, std::ifstream::binary);//+std::to_string(i) for (int i = 0; i < file_count; ++i) { std::string name = fileName + "/" + std::to_string(i)+".pk"; std::string content = readFile(name); if (i != 0) { if (!tag->Check(content, INPUT_TYPE::TEXT_FROM_STRING, tagStr)) { exit(-1); } else { fout.write(i == file_count-1 ? content.c_str() : content.c_str() + 16, i == file_count-1 ? content.size() : content.size() - 16); } } if (i != file_count-1) { tagStr = content.substr(0, 16); } load+=step; printBar(load); } fout.close(); printBar(10); } }; #endif // FILESTREAM_H_INCLUDED
[ "J-CITY" ]
J-CITY
63d9a2f65664bffae73936155f25239311fb8af7
af69e335fc0ff9632964d061833713b672abad01
/Temp/StagingArea/Data/il2cppOutput/System_System_Text_RegularExpressions_Syntax_Backs3656518667.h
a9101f9fedfa8c6e44f95a1e9e686a4a52289729
[]
no_license
PruthvishMShirur/Solar-System
ca143ab38cef582705f0beb76f7fef8b28e25ef9
5cf3eaa66949801aa9a34cd3cf80eeefa64d2342
refs/heads/master
2023-05-26T17:53:37.489349
2021-06-16T19:56:48
2021-06-16T19:56:48
377,611,177
0
0
null
null
null
null
UTF-8
C++
false
false
1,522
h
#pragma once #include "il2cpp-config.h" #ifndef _MSC_VER # include <alloca.h> #else # include <malloc.h> #endif #include <stdint.h> #include "System_System_Text_RegularExpressions_Syntax_Refer1799410108.h" // System.String struct String_t; #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // System.Text.RegularExpressions.Syntax.BackslashNumber struct BackslashNumber_t3656518667 : public Reference_t1799410108 { public: // System.String System.Text.RegularExpressions.Syntax.BackslashNumber::literal String_t* ___literal_2; // System.Boolean System.Text.RegularExpressions.Syntax.BackslashNumber::ecma bool ___ecma_3; public: inline static int32_t get_offset_of_literal_2() { return static_cast<int32_t>(offsetof(BackslashNumber_t3656518667, ___literal_2)); } inline String_t* get_literal_2() const { return ___literal_2; } inline String_t** get_address_of_literal_2() { return &___literal_2; } inline void set_literal_2(String_t* value) { ___literal_2 = value; Il2CppCodeGenWriteBarrier(&___literal_2, value); } inline static int32_t get_offset_of_ecma_3() { return static_cast<int32_t>(offsetof(BackslashNumber_t3656518667, ___ecma_3)); } inline bool get_ecma_3() const { return ___ecma_3; } inline bool* get_address_of_ecma_3() { return &___ecma_3; } inline void set_ecma_3(bool value) { ___ecma_3 = value; } }; #ifdef __clang__ #pragma clang diagnostic pop #endif
[ "42893637+PruthvishMShirur@users.noreply.github.com" ]
42893637+PruthvishMShirur@users.noreply.github.com
8747ff5834e3b580823f8f179da77d4105845bc1
193c601ee5808aee6c5cdb133ef4085ec171848a
/IMAT2905_LabBook1_Shapes/Dot.cpp
8ccf65f2fc0b6ec44219cfdb7fdd3fbe97b413ec
[]
no_license
kaneg79/IMAT2905_LabBook1_Shape
e057a36852da511acf1cb495c90cd1b8f0d55bbb
42faf5c8d8326030ec3877925abf183aa80c1cf8
refs/heads/master
2023-08-25T10:33:48.474275
2021-11-06T13:51:32
2021-11-06T13:51:32
420,979,850
0
0
null
null
null
null
UTF-8
C++
false
false
526
cpp
#include "Dot.h" #include"SFML/Graphics.hpp" Dot::Dot() { dotArray.resize(size); dotArray.setPrimitiveType(sf::LineStrip); dotArray[0] = sf::Vector2f(100, 100); dotArray[1] = sf::Vector2f(100, 100); } Dot::Dot(sf::Vector2f point1, sf::Vector2f point2) { dotArray.resize(size); dotArray.setPrimitiveType(sf::LinesStrip); dotArray[0] = point1; dotArray[0].color = sf::Color::Yellow; dotArray[1] = point2; } void Dot::draw(sf::RenderTarget& target, sf::RenderStates states) const { target.draw(dotArray, states); }
[ "kanegarrett@hotmail.com" ]
kanegarrett@hotmail.com
1253e2864486e165805881777769656a26aabe04
0871d79a4b247c5d9c8eb0a40601804de746e18e
/Fund.h
2a5b83099cf7287bebea5390289a26d2e34c3971
[]
no_license
harmand7/JollyBanker-CSS342
d645960487f29cacb4c9849851801b53dd5257d8
829f4aae96ca25f27dd65ca40df105c885f4333c
refs/heads/master
2021-01-10T11:37:13.504069
2016-02-18T09:38:18
2016-02-18T09:38:18
51,996,930
0
0
null
null
null
null
UTF-8
C++
false
false
620
h
#pragma once #include <string> #include <vector> #include "Transactions.h" using namespace std; class Fund { public: Fund(); Fund(string name); ~Fund(); int getBalance() const; bool setBalance(int money); string getFundName() const; bool setFundName(string Name); void printHisotryFund()const; bool addFunds(int moneyIn); bool subFunds(int moneyOut); bool enoughFundsWithdrawl(int moneyOut)const; bool addTransaction(Transactions transaction); Fund operator=(const Fund& ref); private: string fundName; int balance = 0; vector<Transactions> fundHistory; };
[ "harmand7@uw.edu" ]
harmand7@uw.edu
4dce2b769ba337f2e830975d8294e85889f68884
462cb4e9ccef43ea9703f17b2bf4c6ab6514346d
/factory/virtual_test.cc
9b1ae3a1f7a5fa299d54c31d7439858ed5abbd27
[]
no_license
wwmmqq/design_pattern
e710156b39f54857d5d8fb72c8b8ed43f06170c1
a9cff1fb94481a4d63dd5796d9633892067cd73f
refs/heads/master
2021-01-18T03:05:44.551834
2016-04-27T12:45:06
2016-04-27T12:45:06
56,960,181
0
1
null
null
null
null
UTF-8
C++
false
false
522
cc
#include <iostream> using namespace std; class A { public: virtual void foo() //定义他为虚函数是为了允许用基类的指针来调用子类的这个函数。 { cout<<"A::foo() is called"<<endl; } }; class B:public A { public: void foo() { cout<<"B::foo() is called"<<endl; } }; int main(void) { A *a = new B(); a->foo(); // 在这里,a虽然是指向A的指针,但是被调用的函数(foo)却是B的! return 0; }
[ "myqway@outlook.com" ]
myqway@outlook.com
dbc7d110590a0cad9c84e529e055c6ad3e9182f1
362adf7d74d537d4efac5cb8c6219dfed588906a
/cpp codes/island.cpp
90b416cb9c6cfd4da702c8b1e03dfe64acf83846
[]
no_license
Alquama00s/opencodes
53891de2e9627a532ca45e04195e85945c46f3f5
eaa263f4390c419b62818e293b3430e16ee4a944
refs/heads/master
2022-12-22T20:08:46.051120
2020-09-22T01:20:21
2020-09-22T01:20:21
250,563,349
0
0
null
null
null
null
UTF-8
C++
false
false
527
cpp
//https://www.codechef.com/problems/COAD03 #include<iostream> #include<vector> using namespace std; int main(){ ios_base::sync_with_stdio(0); int t,n; vector<int> dpo; cin>>t; while (t-->0) { cin>>n; dpo.clear(); dpo.resize(n,0); dpo[0]=1; for(int i=1;i<n;i++){ if((i+1)%2==0){ dpo[i]=min(dpo[i-1]+1,dpo[(i-1)/2]+2); }else{ dpo[i]=dpo[i-1]+1;} } cout<<dpo[n-1]<<"\n"; } return 0; }
[ "alquama00s@outlook.com" ]
alquama00s@outlook.com
15fe7c685db94bcffe3ad9b52c06825ba34d2651
44322818a7979c703ba9767bbaf7b29c70e9d859
/App/GameApp.hpp
2696b6fef00da4851020cfcb25bb0913195b5622
[]
no_license
artcampo/2013_3D_unfinished_game
6fcc9c3f059b73ef4c7dc246023f5c1a37f94bb1
1d618f80f52f3b4fb447302a01e359039c585cbf
refs/heads/master
2021-01-11T09:41:47.232014
2016-12-29T14:05:44
2016-12-29T14:05:44
77,616,187
0
0
null
null
null
null
UTF-8
C++
false
false
628
hpp
#include "../BaseDX.hpp" #include <vector> class Game; class ShaderManager; #include "Shader/ShaderManager.hpp" class GameApp : public BaseDX { public: GameApp(HINSTANCE& handler, int width, int height, bool isFullmWindowsScreen, std::wstring wTitle, bool showFPS); ~GameApp(); // Main Game int main(); void onResize(); void drawScene(); private: std::auto_ptr<Game> mGame; ShaderManager mShaderManager; double mLastTime; bool mTimeInitalized; private: double getLapsedTime(); void displayFPSandDebugInfo(); };
[ "arturocampos82@gmail.com" ]
arturocampos82@gmail.com
ad8ef31394a9dd05364ebe4387fd56571f3d136f
3c852abf357d18e46f63e5599c94d5931ea3fa75
/TicTacToeLowLevel.h
46f60c377091b93f78289eb8d6b90a80b395724f
[]
no_license
adipeled2244/Game-Project
390591b27eebdfa42c1569572a4f235e86247a3f
1f31a0d098b47b89145f1f17e6028fd9fb6405b9
refs/heads/master
2023-05-30T17:52:47.902241
2021-06-04T16:42:49
2021-06-04T16:42:49
373,903,457
0
0
null
null
null
null
UTF-8
C++
false
false
179
h
#pragma once #include <iostream> #include "TicTacToe.h" class TicTacToeLowLevel : public TicTacToe { public: TicTacToeLowLevel():TicTacToe(){} void set_computer_move(); };
[ "adipeled224@gmail.com" ]
adipeled224@gmail.com
e4d3263b1cd06a93fa6795296f9a1e145487d559
c7a3dcabe12b59c3eaefb32be20a367a1d87a2f0
/main/mywebserver.cpp
da17414fd1f187f1cf34321d13981b10a7572486
[]
no_license
opiopan/irserver
feaee9935466ff1d6f40b561de7afd1fdf0777d0
ec9121e261d097c8e106ae9842f15812ffb269aa
refs/heads/master
2021-04-26T23:50:17.766813
2018-05-26T16:45:27
2018-05-26T16:45:27
123,830,769
1
0
null
null
null
null
UTF-8
C++
false
false
8,423
cpp
#include <esp_log.h> #include <string.h> #include <Task.h> #include <lwip/sockets.h> #include <lwip/netdb.h> #include <mongoose.h> #include "Mutex.h" #include "mywebserver.h" #include "htdigestfs.h" #include "reboot.h" #include "boardconfig.h" #include "sdkconfig.h" static const char* tag = "webserver"; class ConnectionContext { public: virtual ~ConnectionContext(){}; }; class HttpServerTask : public Task { private: mg_mgr mgr; mg_connection *nc; public: HttpServerTask(); bool init(const char* port); private: void run(void *data) override; static void defHandler(struct mg_connection *nc, int ev, void *p); static void downloadHandler(struct mg_connection *nc, int ev, void *p); }; HttpServerTask::HttpServerTask(){ } bool HttpServerTask::init(const char* port){ mg_mgr_init(&mgr, NULL); nc = mg_bind(&mgr, port, defHandler); if (nc == NULL) { ESP_LOGE(tag, "Error setting up listener!"); return false; } mg_set_protocol_http_websocket(nc); mg_register_http_endpoint(nc, "/download", downloadHandler); return true; } void HttpServerTask::run(void *data){ while (1) { mg_mgr_poll(&mgr, 1000); } } void HttpServerTask::defHandler(struct mg_connection *nc, int ev, void *p) { static const char *reply_fmt = "HTTP/1.0 200 OK\r\n" "Connection: close\r\n" "Content-Type: text/plain\r\n" "\r\n" "Hello %s\n"; switch (ev) { case MG_EV_ACCEPT: { char addr[32]; mg_sock_addr_to_str(&nc->sa, addr, sizeof(addr), MG_SOCK_STRINGIFY_IP | MG_SOCK_STRINGIFY_PORT); ESP_LOGI(tag, "Connection %p from %s", nc, addr); break; } case MG_EV_HTTP_REQUEST: { char addr[32]; struct http_message *hm = (struct http_message *) p; mg_sock_addr_to_str(&nc->sa, addr, sizeof(addr), MG_SOCK_STRINGIFY_IP | MG_SOCK_STRINGIFY_PORT); ESP_LOGI(tag, "HTTP request from %s: %.*s %.*s", addr, (int) hm->method.len, hm->method.p, (int) hm->uri.len, hm->uri.p); mg_printf(nc, reply_fmt, addr); nc->flags |= MG_F_SEND_AND_CLOSE; break; } case MG_EV_CLOSE: { ESP_LOGI(tag, "Connection %p closed", nc); ConnectionContext* ctx = (ConnectionContext*)nc->user_data; delete ctx; break; } case MG_EV_HTTP_MULTIPART_REQUEST: { char addr[32]; struct http_message *hm = (struct http_message *) p; mg_sock_addr_to_str(&nc->sa, addr, sizeof(addr), MG_SOCK_STRINGIFY_IP | MG_SOCK_STRINGIFY_PORT); ESP_LOGI(tag, "HTTP mp req from %s: %.*s %.*s", addr, (int) hm->method.len, hm->method.p, (int) hm->uri.len, hm->uri.p); break; } case MG_EV_HTTP_MULTIPART_REQUEST_END: { ESP_LOGI(tag, "HTTP mp req end"); mg_printf(nc, "HTTP/1.1 200 OK\r\n" "Content-Type: text/plain\r\n" "Connection: close\r\n\r\n" "Written POST data to a temp file\n\n"); nc->flags |= MG_F_SEND_AND_CLOSE; break; } case MG_EV_HTTP_PART_BEGIN: { struct mg_http_multipart_part *mp = (struct mg_http_multipart_part *) p; ESP_LOGI(tag, "part begin: key = %s", mp->var_name); break; } case MG_EV_HTTP_PART_DATA: { struct mg_http_multipart_part *mp = (struct mg_http_multipart_part *) p; ESP_LOGI(tag, "part data: %d byte", mp->data.len); break; } case MG_EV_HTTP_PART_END: { ESP_LOGI(tag, "part end"); break; } } } #include "ota.h" class DLContext : public ConnectionContext { public: bool image; OTA* ota; bool reply; DLContext() : image(false), ota(NULL), reply(false){}; virtual ~DLContext(){ if (ota){ end(false); } }; void start(OTA* in){ ota = in; image = true; }; OTARESULT end(bool needCommit){ OTARESULT rc = ::endOTA(ota, needCommit); ota = NULL; return rc; } }; static const struct mg_str getMethod = MG_MK_STR("GET"); static const struct mg_str postMethod = MG_MK_STR("POST"); static int isEqual(const struct mg_str *s1, const struct mg_str *s2) { return s1->len == s2->len && memcmp(s1->p, s2->p, s2->len) == 0; } void HttpServerTask::downloadHandler(struct mg_connection *nc, int ev, void *p) { const char* domain = "opiopan"; const char* invReqMsg = "HTTP/1.1 200 OK\r\n" "Content-Type: text/plain\r\n" "Connection: close\r\n\r\n" "need to spcecify valid params and request as post\r\n"; if (ev == MG_EV_HTTP_REQUEST){ ESP_LOGI(tag, "HTTP dowonload req"); ESP_LOGE(tag, "invalid request"); mg_printf(nc, invReqMsg); nc->flags |= MG_F_SEND_AND_CLOSE; }else if (ev == MG_EV_HTTP_MULTIPART_REQUEST){ ESP_LOGI(tag, "HTTP download mpart req"); struct http_message *hm = (struct http_message *) p; if (!isEqual(&hm->method, &postMethod)){ ESP_LOGE(tag, "invalid request"); mg_printf(nc, invReqMsg); nc->flags |= MG_F_SEND_AND_CLOSE; return; } static const char * domain = "opiopan"; FILE* fp = htdigestfs_fp(); fseek(fp, 0, SEEK_SET); if (!mg_http_check_digest_auth(hm, domain, fp)){ ESP_LOGE(tag, "authorize failed"); mg_http_send_digest_auth_request(nc, domain); nc->flags |= MG_F_SEND_AND_CLOSE;; return; } ESP_LOGI(tag, "user authorized"); mg_str* sizeStr = mg_get_http_header(hm, "X-OTA-Image-Size"); size_t imageSize = 0; if (sizeStr){ for (int i = 0; i < sizeStr->len; i++){ int digit = sizeStr->p[i]; if (digit >= '0' && digit <= '9'){ imageSize *= 10; imageSize += digit - '0'; }else{ imageSize = 0; break; } } ESP_LOGI(tag, "image size: %d", imageSize); } DLContext* ctx = new DLContext(); nc->user_data = ctx; OTA* ota = NULL; if (startOTA("/spiffs/public-key.pem", imageSize, &ota) != OTA_SUCCEED){ ESP_LOGE(tag, "downloading in parallel"); mg_printf( nc, "HTTP/1.1 200 OK\r\n" "Content-Type: text/plain\r\n" "Connection: close\r\n\r\n" "firmware downloading is proceeding in parallel\r\n"); nc->flags |= MG_F_SEND_AND_CLOSE; return; } ctx->start(ota); mg_str* value = mg_get_http_header(hm, "Expect"); static const mg_str CONTINUE = MG_MK_STR("100-continue"); if (value != NULL && isEqual(value, &CONTINUE)) { ESP_LOGI(tag, "response 100 continue"); mg_printf(nc,"HTTP/1.1 100 continue\r\n\r\n"); } }else if (ev == MG_EV_HTTP_MULTIPART_REQUEST_END){ DLContext* ctx = (DLContext*)nc->user_data; if (ctx && !ctx->image){ ESP_LOGE(tag, "no image part"); mg_http_send_digest_auth_request(nc, domain); nc->flags |= MG_F_SEND_AND_CLOSE; return; } ESP_LOGI(tag, "end mpart req"); nc->flags |= MG_F_SEND_AND_CLOSE; }else if (ev == MG_EV_HTTP_PART_BEGIN) { struct mg_http_multipart_part *mp = (struct mg_http_multipart_part *) p; DLContext* ctx = (DLContext*)nc->user_data; if (ctx && ctx->ota && strcmp(mp->var_name, "image") == 0){ ESP_LOGI(tag, "begin update firmware"); } }else if (ev == MG_EV_HTTP_PART_DATA){ DLContext* ctx = (DLContext*)nc->user_data; if (ctx && ctx->ota){ struct mg_http_multipart_part *mp = (struct mg_http_multipart_part *) p; //ESP_LOGI(tag, "update data: %d bytes", mp->data.len); OTARESULT rc = ctx->ota->addDataFlagment(mp->data.p, mp->data.len); if (rc != OTA_SUCCEED){ ESP_LOGE(tag, "update data failed"); mg_printf( nc, "HTTP/1.1 200 OK\r\n" "Content-Type: text/plain\r\n" "Connection: close\r\n\r\n" "update data failed: 0x%x\r\n", rc); //nc->flags |= MG_F_SEND_AND_CLOSE; ctx->reply = true; ctx->end(false); return; } } }else if (ev == MG_EV_HTTP_PART_END){ DLContext* ctx = (DLContext*)nc->user_data; if (ctx && ctx->ota){ ESP_LOGI(tag, "end update firmware"); OTARESULT rc = ctx->end(true); if (rc != OTA_SUCCEED){ ESP_LOGE(tag, "commit failed"); mg_printf( nc, "HTTP/1.1 200 OK\r\n" "Content-Type: text/plain\r\n" "Connection: close\r\n\r\n" "update data failed: 0x%x\r\n", rc); nc->flags |= MG_F_SEND_AND_CLOSE; return; } mg_printf(nc, "HTTP/1.1 200 OK\r\n" "Content-Type: text/plain\r\n" "Connection: close\r\n\r\n" "firmware updating finished\r\n"); nc->flags |= MG_F_SEND_AND_CLOSE; rebootIn(2000); } } } HttpServerTask* server; bool startHttpServer(){ if (server == NULL){ server = new HttpServerTask(); server->init(HTTP_SERVER_PORT); server->start(); ESP_LOGI(tag, "HTTP server has been started. port: %s", HTTP_SERVER_PORT); } return true; }
[ "opiopan@gmail.com" ]
opiopan@gmail.com
051924c12c66e06b02eabe413a8342f98e1498c6
fa3ba58549de5049a277ca57342e6b3bd59e304e
/Program_files/prisoner.h
aefcb4997dae03fe5c6c9f7b7174ae50f736fb0c
[]
no_license
DaltonCole/evolutionary_algorithms_IPD
70a1ba99996071c894db2ae2a6e753ebf5da350a
2e523c37536ab7d3d33a9bfdede3344023087407
refs/heads/master
2021-08-23T04:05:42.137399
2017-12-03T05:06:05
2017-12-03T05:06:05
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,937
h
////////////////////////////////////////////////////////////////////// /// @file prisoner.h /// @author Dalton Cole, CS5201 A assignment 2b /// @brief Class declaration of Prisoner ////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////// /// @class Prisoner /// @brief Represents a prisoner in the prisoner's Dilemma problem ////////////////////////////////////////////////////////////////////// #ifndef PRISONER_H #define PRISONER_H #include <iostream> #include <memory> #include <deque> #include <stdlib.h> /* srand, rand */ #include <math.h> #include <algorithm> #include <string> #include "config.h" #include "move.h" using namespace std; class Prisoner; ostream& operator <<(ostream& os, Prisoner p); class Prisoner { public: Prisoner(); Prisoner(const Prisoner& rhs); const Prisoner & operator =(const Prisoner& rhs); Prisoner(Prisoner&& other); Prisoner& operator =(Prisoner&& other); bool operator ==(const Prisoner& rhs) const; void randomly_initalize_tree(); unique_ptr<Prisoner> generate_full_tree(const int depth) const; unique_ptr<Prisoner> generate_branch(int depth) const; string random_operator() const; int random_leaf() const; void assign_fitness(); void coevolutionary_assign_fitness(vector<Prisoner>& population, int& fintess_evaulations, const int bad_index); int append_move_to_queues(Prisoner* p); bool find_value() const; bool recursively_find_value(const Prisoner& branch) const; bool get_move_value(const int m) const; int fitness_function(const bool p, const bool o) const; float get_fitness() const; int assign_depth(Prisoner& p); void sub_tree_crossover(Prisoner& other); Prisoner* equal_level_branch(Prisoner& p, const int & goal_depth); void sub_tree_mutation(); void recursive_sub_tree_mutation(Prisoner& branch); friend deque<Move> generate_move_queue(); bool less_than(const Prisoner& rhs) const; bool operator <(const Prisoner& rhs); friend bool operator <(const Prisoner& a, const Prisoner& b); friend bool operator >(const Prisoner& a, const Prisoner& b); friend ostream& operator <<(ostream& os, Prisoner p); friend string to_string(const Prisoner& p); static Config config; static deque<Move> move_queue; private: string op; int leaf_lhs; int leaf_rhs; unique_ptr<Prisoner> left_branch; unique_ptr<Prisoner> right_branch; int current_depth; float fitness; deque<Move> current_move_queue; }; string leaf_to_string(const int leaf); namespace std { template<> struct hash<Prisoner> { size_t operator()(const Prisoner& obj) const { return hash<string>()(to_string(obj)); } }; } #endif ////////////////////////////////////////////////////////////////////// /// @fn /// @brief /// @pre /// @post /// @param /// @return //////////////////////////////////////////////////////////////////////
[ "dalton_cl@yahoo.com" ]
dalton_cl@yahoo.com
ddf27fb99483670bfee2df80e4f247e56b458684
53715d472778dbe9797897bf40ed6351492619b7
/DTN/DTN2/servlib/prophet/Dictionary.cc
0a3f1d8d0c88247761e9cade374036be2a17fa3a
[ "Apache-2.0", "MIT" ]
permissive
xyongcn/dtn2
1194fd7fa591728ad1dde7a51d48098260a8b0b9
8da09477442896f1a36a1467f3a5dc6ba27405db
refs/heads/master
2020-05-21T20:36:33.127193
2019-09-20T05:49:52
2019-09-20T05:49:52
63,227,016
1
1
null
null
null
null
UTF-8
C++
false
false
4,762
cc
/* * Copyright 2007 Baylor University * * 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 "Dictionary.h" namespace prophet { // Reserve 0xffff as in-band error report const u_int16_t Dictionary::INVALID_SID = 0xffff; const std::string Dictionary::NULL_STR; Dictionary::Dictionary(const std::string& sender, const std::string& receiver) : sender_(sender), receiver_(receiver) {} Dictionary::Dictionary(const Dictionary& d) : sender_(d.sender_), receiver_(d.receiver_), ribd_(d.ribd_), rribd_(d.rribd_) {} u_int16_t Dictionary::find(const std::string& dest_id) const { // weed out the oddball if (dest_id == "") return INVALID_SID; // answer the easy ones before troubling map::find if (dest_id == sender_) return 0; if (dest_id == receiver_) return 1; // OK, now we fall back to the Google ribd::const_iterator i = (ribd::const_iterator) ribd_.find(dest_id); if (i != ribd_.end()) return (*i).second; // you fail it! return INVALID_SID; } const std::string& Dictionary::find(u_int16_t id) const { // answer the easy ones first if (id == 0) return sender_; if (id == 1) return receiver_; // fall back to reverse RIBD const_iterator i = (const_iterator) rribd_.find(id); if (i != rribd_.end()) return (*i).second; // no dice return NULL_STR; } u_int16_t Dictionary::insert(const std::string& dest_id) { // weed out the oddball if (dest_id == "") return INVALID_SID; // only assign once if (find(dest_id) != INVALID_SID) return INVALID_SID; // our dirty little secret: just increment the internal // SID by skipping the first two (implicit sender & receiver) u_int16_t sid = ribd_.size() + 2; // somehow the dictionary filled up!? if (sid == INVALID_SID) return INVALID_SID; bool res = assign(dest_id,sid); while (res == false) { res = assign(dest_id,++sid); if (sid == INVALID_SID) // sad times ... ? return INVALID_SID; } return sid; } bool Dictionary::assign(const std::string& dest_id, u_int16_t sid) { // weed out the oddball if (dest_id == "") return false; // these shouldn't get out of sync if (ribd_.size() != rribd_.size()) return false; // enforce sender/receiver definitions if (sid == 0) { if (sender_ == "" && dest_id != "") { sender_.assign(dest_id); return true; } return false; } else if (sid == 1) { if (receiver_ == "" && dest_id != "") { receiver_.assign(dest_id); return true; } return false; } else if (sid == INVALID_SID) { // what were you thinking? return false; } // attempt to insert into forward lookup bool res = ribd_.insert(ribd::value_type(dest_id,sid)).second; if ( ! res ) return false; // move on to reverse lookup res = rribd_.insert(rribd::value_type(sid,dest_id)).second; if ( ! res ) ribd_.erase(dest_id); // complain if we get out of sync return res && (ribd_.size() == rribd_.size()); } size_t Dictionary::guess_ribd_size(size_t RASsz) const { size_t retval = 0; for (const_iterator i = rribd_.begin(); i != rribd_.end(); i++) { retval += FOUR_BYTE_ALIGN( RASsz + (*i).second.length() ); } return retval; } void Dictionary::clear() { // wipe out everything from the dictionary sender_.assign(""); receiver_.assign(""); ribd_.clear(); rribd_.clear(); } void Dictionary::dump(BundleCore* core,const char* file,u_int line) const { if (core == NULL) return; core->print_log("dictionary", BundleCore::LOG_DEBUG, "%s(%u): 0 -> %s", file, line, sender_.c_str()); core->print_log("dictionary", BundleCore::LOG_DEBUG, "%s(%u): 1 -> %s", file, line, receiver_.c_str()); for (const_iterator i = rribd_.begin(); i != rribd_.end(); i++) core->print_log("dictionary", BundleCore::LOG_DEBUG, "%s(%u): %u -> %s", file, line, (*i).first, (*i).second.c_str()); } }; // namespace prophet
[ "346268668@qq.com" ]
346268668@qq.com
f2c3ba06cd6c78b2d0b63dbc08c1c47c8cfa7f89
6515c9136b9f32ea7ecec746cc685b65b6fb8513
/yamr_engine/yamr_engine.cpp
c6f0847413d80b53e14de88d185aa28911504885
[]
no_license
Alkud/OTUS_HOMEWORK_14
d32554ac5cebce9153c0d5a57f1194cd6b63f4af
964611a1b2cf41e5fedc3e78e2d1f9cbdb1df99a
refs/heads/master
2020-03-25T07:14:45.638807
2019-07-18T15:27:40
2019-07-18T15:27:40
143,550,040
0
0
null
null
null
null
UTF-8
C++
false
false
12,952
cpp
#include "yamr_engine.h" #include <fstream> #include <iostream> #include <set> #include <algorithm> #include <numeric> #include <cctype> #include <iterator> #include <sstream> YamrEngine::YamrEngine(size_t newMappingThreadCount, size_t newReducingThreadCount, const SharedFunctor& newMapper, const SharedFunctor& newReducer) : mappingThreadCount{newMappingThreadCount}, reducingThreadCount{newReducingThreadCount}, mapper{newMapper}, reducer{newReducer}, splittedMappedData{}, mergedMappedData{nullptr} { } FileBoundsList YamrEngine::splitFile(const std::string& fileName, const size_t partsCount) { std::ifstream fileToSplit{fileName, std::ifstream::ate | std::ifstream::binary}; if (!fileToSplit) { throw std::invalid_argument{"File not found"}; } if (0 == partsCount) { throw std::invalid_argument{"Wrong number of parts"}; } auto fileSize{static_cast<size_t>(fileToSplit.tellg())}; FileBoundsList sectionBounds{}; if (0 == fileSize) { return sectionBounds; } auto averageSectionSize{fileSize / partsCount}; if (0 == averageSectionSize) { averageSectionSize = 1; } int64_t sectionBegin{0}; int64_t sectionEnd{-1}; for (size_t idx {1}; idx < partsCount; ++idx) { auto currentSeekPosition{idx * averageSectionSize}; size_t previousSectionEnd{}; if (sectionBounds.empty() != true) { previousSectionEnd = sectionBounds.back().second; } if (currentSeekPosition <= previousSectionEnd && previousSectionEnd < fileSize - 2) { currentSeekPosition = previousSectionEnd + 1; } fileToSplit.seekg(currentSeekPosition); if (fileToSplit.peek() != '\n') { auto nextNewLinePosition{findNewLine(fileToSplit, fileSize, FileReadDirection::forward)}; fileToSplit.seekg(currentSeekPosition); auto previousNewLinePosition{findNewLine(fileToSplit, fileSize, FileReadDirection::backward)}; if (-1 == nextNewLinePosition) { /* next '\n' not found */ if(-1 != previousNewLinePosition) { sectionEnd = previousNewLinePosition; } } else { /* previous '\n' not found */ if(-1 == previousNewLinePosition) { sectionEnd = nextNewLinePosition; } else { sectionEnd = (currentSeekPosition - previousNewLinePosition) > (nextNewLinePosition - currentSeekPosition) ? nextNewLinePosition : previousNewLinePosition; } } } else { sectionEnd = currentSeekPosition; } if (-1 == sectionEnd) { break; } if (sectionEnd != static_cast<int64_t>(previousSectionEnd)) { sectionBounds.push_back(std::make_pair(sectionBegin, sectionEnd)); if (sectionEnd < static_cast<int64_t>(fileSize - 2)) { sectionBegin = sectionEnd + 1; } } } sectionBounds.push_back(std::make_pair(sectionBegin, fileSize - 1)); return sectionBounds; } ListSharedStringList YamrEngine::mapData(const std::string& fileName, const size_t resultPartsCount, SharedFunctor mapper) { auto sectionBounds{splitFile(fileName, resultPartsCount)}; std::vector<std::future<SharedStringList>> mappingResults{}; std::mutex fileLock{}; for (const auto& bounds : sectionBounds) { mappingResults.push_back(std::async(std::launch::async, &YamrEngine::readAndMap, std::ref(fileName), bounds, mapper, std::ref(fileLock))); } ListSharedStringList mappedData{}; for (auto& result : mappingResults) { if (result.valid()) { auto nextList{result.get()}; nextList->sort(); mappedData.push_back(nextList); } } return mappedData; } const ListSharedStringList YamrEngine::getMappedData() { return splittedMappedData; } ListSharedStringList YamrEngine::mergeData(const ListSharedStringList& mappedData, const size_t resultPartsCount) { std::vector<std::thread> shufflingThreads{}; std::vector<std::shared_ptr<SortedListsMerger>> mergers{}; ListSharedStringList mergedData{}; for (size_t idx{}; idx < resultPartsCount; ++idx) { mergers.emplace_back(new SortedListsMerger{}); } for (const auto& listToMerge : mappedData) { shufflingThreads.push_back(std::thread{&YamrEngine::dispenseSortedLists, std::ref(listToMerge), mergers}); } for (auto& thread : shufflingThreads) { if (thread.joinable()) { thread.join(); } } std::vector<std::future<SharedStringList>> mergingResults{}; for (const auto& merger : mergers) { mergingResults.push_back(std::async(std::launch::async, [merger](){return merger->getMergedData();})); } for (auto& result : mergingResults) { if (result.valid()) { mergedData.push_back(result.get()); } } return mergedData; } const ListSharedStringList YamrEngine::getMergedData() { return mergedMappedData; } ListSharedStringList YamrEngine::reduceData(const ListSharedStringList& mergedData, SharedFunctor reducer) { ListSharedStringList reducedData{}; std::vector<std::future<SharedStringList>> reducingResults{}; for (const auto& listToReduce : mergedData) { reducingResults.push_back(std::async(std::launch::async, [&listToReduce, reducer]() {return reduce(listToReduce, reducer);})); } for (auto& result : reducingResults) { if (result.valid()) { reducedData.push_back(result.get()); } } return reducedData; } ListSharedStringList YamrEngine::reduceAndSaveData(const ListSharedStringList& mergedData, SharedFunctor reducer) { ListSharedStringList reducedData{}; std::vector<std::future<SharedStringList>> reducingResults{}; for (const auto& listToReduce : mergedData) { reducingResults.push_back(std::async(std::launch::async, [&listToReduce, reducer]() {return reduce(listToReduce, reducer);})); } size_t partsCount{reducingResults.size()}; size_t partIndex{1}; for (auto& result : reducingResults) { if (result.valid()) { reducedData.push_back(result.get()); std::string fileName{std::string{"reduced_data_"} + std::to_string(partIndex) + "_of_" + std::to_string(partsCount) + ".txt"}; saveListToFile(fileName, reducedData.back()); ++partIndex; } } return reducedData; } const ListSharedStringList YamrEngine::getReducedData() { return reducedData; } void YamrEngine::saveListToFile(const std::string& fileName, const SharedStringList& data) { std::ofstream outputFile{fileName}; if (!outputFile) { std::cerr << "Can not create file " << fileName << "\n"; throw std::ios_base::failure {"File creation error"}; } for (const auto& nextString : *data) { outputFile << nextString << "\n"; } outputFile.close(); std::ifstream checkFile{fileName}; if (!checkFile) { std::cerr << "Can not write to file " << fileName << "\n"; throw std::ios_base::failure {"File writing error"}; } } void YamrEngine::mapReduce(const std::string& fileName) { splittedMappedData = mapData(fileName, mappingThreadCount, mapper); mergedMappedData = mergeData(splittedMappedData, reducingThreadCount); reducedData = reduceAndSaveData(mergedMappedData, reducer); } size_t YamrEngine::FNVHash(const std::string& str) { const size_t fnv_prime {1099511628211u}; size_t hash {14695981039346656037u}; auto stringLength {str.length()}; for (size_t idx{0}; idx < stringLength; ++idx) { hash *= fnv_prime; hash ^= (str[idx]); } return hash; } int64_t YamrEngine::findNewLine(std::ifstream& file, const size_t fileSize, FileReadDirection direction) { auto currentPosition {static_cast<size_t>(file.tellg())}; if (FileReadDirection::forward == direction) { while(currentPosition < fileSize - 1) { ++currentPosition; file.seekg(currentPosition); if (file.peek() == '\n') { return currentPosition; } } return -1; } else { while(currentPosition > 0) { --currentPosition; file.seekg(currentPosition); if (file.peek() == '\n') { return currentPosition; } } return -1; } } SharedStringList YamrEngine::readAndMap(const std::string& fileName, const FileBounds bounds, SharedFunctor mapper, std::mutex& fileLock) { try { const auto startPosition{bounds.first}; const auto endPosition{bounds.second}; auto localData {std::make_shared<StringList>()}; { std::lock_guard<std::mutex> lockFile{fileLock}; std::ifstream inputFile{fileName}; if (!inputFile) { return nullptr; } inputFile.seekg(startPosition); auto currentPosition{startPosition}; std::string nextString{}; while(inputFile && inputFile.tellg() < static_cast<std::ofstream::pos_type>(endPosition)) { if (std::getline(inputFile, nextString)) { std::transform(nextString.begin(), nextString.end(), nextString.begin(), ::tolower); mapper->operator()(std::to_string(currentPosition) + "\t" + nextString, *localData); currentPosition = inputFile.tellg(); } } } return localData; } catch (const std::exception& ex) { std::cerr << ex.what(); return nullptr; } } void YamrEngine::dispenseSortedLists(const SharedStringList& listToDispense, const std::vector<std::shared_ptr<SortedListsMerger> >& mergers) { try { size_t mergerCount{mergers.size()}; size_t mergerIndex{}; size_t nextHash{}; while(listToDispense->empty() != true) { auto nextString{listToDispense->front()}; listToDispense->pop_front(); auto tabPosition{nextString.find('\t', 0)}; auto nextKey {tabPosition != std::string::npos ? nextString.substr(0, tabPosition) : nextString}; nextHash = FNVHash(nextKey); mergerIndex = nextHash % mergerCount; mergers[mergerIndex]->offer(nextString); } } catch (const std::exception& ex) { std::cerr << ex.what(); return; } } SharedStringList YamrEngine::reduce(const SharedStringList& listToReduce, SharedFunctor reducer) { try { auto result{std::make_shared<StringList>()}; for (const auto& nextString : *listToReduce) { reducer->operator()(nextString, *result); } return result; } catch (const std::exception& ex) { std::cerr << ex.what(); return nullptr; } } void YamrEngine::SortedListsMerger::offer(const std::string& nextString) { auto splitResult{extractKeyValue(nextString)}; auto nextKey{splitResult.first}; auto nextValue{splitResult.second}; std::lock_guard<std::mutex> lockAccess{accessLock}; collector[nextKey].insert(nextValue); } SharedStringList YamrEngine::SortedListsMerger::getMergedData() const { try { auto result{std::make_shared<StringList>()}; std::lock_guard<std::mutex> lockAccess{accessLock}; for (const auto& collection : collector) { std::stringstream collectedString{}; collectedString << collection.first << "\t"; // key_tab_value_value_value_value_... for (const auto& value : collection.second) { collectedString << value << " "; } auto keyValuesString{collectedString.str()}; result->push_back(keyValuesString.substr(0, keyValuesString.size() - 1)); } return result; } catch (const std::exception& ex) { std::cerr << ex.what(); return nullptr; } } std::pair<std::string, std::string> YamrEngine::SortedListsMerger::extractKeyValue(const std::string& tabSeparatedData) { auto tabPosition{tabSeparatedData.find('\t', 0)}; if (tabPosition == std::string::npos || tabPosition == tabSeparatedData.size() - 1) { return std::make_pair(tabSeparatedData, std::string{}); } auto key {tabSeparatedData.substr(0, tabPosition)}; auto value {tabSeparatedData.substr(tabPosition + 1)}; return std::make_pair(key, value); }
[ "alexandr_kudinov@mail.ru" ]
alexandr_kudinov@mail.ru
3d4cb69293cdc3dadb47674f54872cfe1e3e7348
f088ea3d2a6cc02497a0f57d92585e88f0a87572
/DataStructures/Queue/queue.cpp
cf81f513270d7ce4a451f85b2321d459203afbcf
[]
no_license
prince776/Data-Structures-and-Algorithms
dbeda78ec5294303e21d20f00875c590981e58cb
d5754bf83d19e65b853683f1c35dbc9a646af579
refs/heads/master
2022-12-04T14:52:48.737484
2022-04-26T07:55:33
2022-04-26T07:55:33
252,471,103
66
13
null
2022-12-15T12:42:41
2020-04-02T13:59:30
C++
UTF-8
C++
false
false
797
cpp
// Implements Queue Data Structure. #include <bits/stdc++.h> using namespace std; struct QueueNode { int data; QueueNode* next; QueueNode(int data) : data(data), next(NULL) { } }; struct Queue { QueueNode* rear, *front; Queue() : rear(0), front (0) { } void enQueue(int data) { QueueNode* temp = new QueueNode(data); if (!rear) { front = temp; rear = temp; return; } rear->next = temp; rear = temp; } void deQueue() { if (!front) return; QueueNode* temp = front; front = front->next; if (!front) rear = NULL; delete temp; } }; int main() { Queue q; q.enQueue(10); q.enQueue(15); q.enQueue(20); q.enQueue(25); q.deQueue(); q.deQueue(); cout << "Front: " << q.front->data << "\n"; cout << "Rear: " << q.rear->data << "\n"; return 0; }
[ "princemit776@gmail.com" ]
princemit776@gmail.com
2aba43e3a6f94714b3989174ba514c8c22f86ce9
05048aa617d2a712a4fafcfcf2ad33e267a810ea
/Lab/Lab 7/Gaddis_6thEd_Chap3_Prob17/main.cpp
4bbd248887aa35a1ed3e53da2c40f0a938fa40d7
[]
no_license
AyinDJ/HeXiaojun_46090
b56ba1da9e7cff4ae770c1d70a7242eec2ae9b81
1c3dd473cb7e8dae9fe604d5ff2194a9fe644c40
refs/heads/master
2016-09-06T19:56:14.035606
2015-07-17T00:21:48
2015-07-17T00:21:48
38,069,622
3
0
null
null
null
null
UTF-8
C++
false
false
1,634
cpp
/* * File: main.cpp * Author: Xiaojun He * Purpose:Monthly Payments * * Created on July 1, 2015, 11:03 AM */ #include <iostream> #include <iomanip> using namespace std; //User Libraries //Global constant //Function Prototypes //Execution Begins Here! int main(int argc, char** argv) { //Declare Variables Here unsigned char nMonths=36; //Number of months to payoff loan unsigned short loan=10000; //Loan amount in $'s float ir=0.01f; //Inter Rate par Month float mnthPay; //Monthly Payment in $'s float temp=1.0f; //Intermediate value found in Monthly Payment equation float cstLoan; //cost of the loan in$'s float totCost; //Total paid back to lender //Calculate the intermediate value float onePlsi=(1+ir); for(int months=1;months<=nMonths;months++){ temp*=onePlsi; } //Calculate the monthly payment mnthPay=ir*temp*loan/(temp-1); mnthPay=static_cast<int>(mnthPay*100)/100.0f; //Exact amount in pennies totCost=nMonths*mnthPay; cstLoan=totCost-loan; //Output the results cout.setf(ios::fixed); cout.setf(ios::showpoint); cout.precision(2); cout<<"Loan Amount: $"<<setw(8)<<loan*1.0f<<endl; cout<<"Monthly interest Rate: "<<setw(8)<<ir*100<<"%"<<endl; cout<<"Number of Payments: "<<setw(8)<<static_cast<int>(nMonths)<<endl; cout<<"Monthly Payment $"<<setw(8)<<mnthPay<<endl; cout<<"Amount paid Back: $"<<setw(8)<<totCost<<endl; cout<<"Interest Paid: $"<<setw(8)<<cstLoan<<endl; cout<<mnthPay<<endl; //Exit stage right return 0; }
[ "amazinghxj@gmail.com" ]
amazinghxj@gmail.com
b0a19068a1203f00bb39f207f74aa4177c425fc2
a68823773e764142c7b5c69f31bf2f916ca02c5f
/Code/SARibbonBar/SARibbonDrawHelper.h
85effad7631bae526bb02af390082e80009fff86
[ "BSD-3-Clause" ]
permissive
hh-wu/FastCAE-linux
0a4b8ac6e1535a43f4047027cb2e01d5f2816f2d
4ab6f653e5251acfd707e678bd63437666b3900b
refs/heads/main
2023-06-16T13:43:56.204083
2021-07-12T16:20:39
2021-07-12T16:20:39
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,186
h
#ifndef SARIBBONDRAWHELPER_H #define SARIBBONDRAWHELPER_H #include <QIcon> #include <QStylePainter> #include <QStyleOption> #include <QPixmap> #include "SARibbonGlobal.h" /// /// \brief 绘图辅助 /// class SA_RIBBON_EXPORT SARibbonDrawHelper { public: SARibbonDrawHelper(); static QPixmap iconToPixmap(const QIcon &icon, QWidget* widget, const QStyleOption *opt, const QSize &icoSize); static void drawIcon(const QIcon &icon, QPainter *painter, const QStyleOption *opt , int x, int y, int width, int height); static void drawIcon(const QIcon &icon, QPainter *painter, const QStyleOption *opt , const QRect& rect); static QSize iconActualSize(const QIcon &icon, const QStyleOption* opt, const QSize& iconSize); static void drawText(const QString& text, QStylePainter *painter, const QStyleOption *opt , Qt::Alignment al, int x, int y, int width, int height); static void drawText(const QString& text, QStylePainter *painter, const QStyleOption *opt , Qt::Alignment al, const QRect& rect); }; #endif // SARIBBONDRAWHELPER_H
[ "1229331300@qq.com" ]
1229331300@qq.com
cf0b3de429ce8c5bb13990fb381aa27a26563057
3b1a979f7f5ef4b6881939b4152f51b70c32614f
/Latency/Latency.cpp
8ff18edef2885e18037cd4c46cc5befe1a100572
[]
no_license
zarond/OMPTasks
f2a567492a490dc620001757ded6b6cabc97ff7c
190ac48292637d32d469cdad9341807090c5fde3
refs/heads/master
2023-09-06T07:49:27.661645
2021-10-11T11:13:57
2021-10-11T11:13:57
414,342,044
0
0
null
null
null
null
UTF-8
C++
false
false
5,983
cpp
#include <omp.h> #include <iostream> #include <random> #include <chrono> //#include <ctime> #include <limits> #include <cstddef> #define REAL #ifdef REAL typedef double T; #else typedef int T; #endif #define MINLIMIT -std::numeric_limits<T>::max() void generate_random(T* Data, unsigned int n) { std::random_device rd; //Will be used to obtain a seed for the random number engine std::mt19937 gen(rd()); //Standard mersenne_twister_engine seeded with rd() #ifdef REAL std::uniform_real_distribution<T> dis(T(-1), T(1)); #else std::uniform_int_distribution<T> dis(0, 10); #endif //Data = new T[n]; for (int i = 0; i < n; ++i) { Data[i] = dis(gen); } } T work(const T* Mat, const int n, const int m) { T min = Mat[0]; for (int i = 0; i < n; ++i) { for (int j = 0; j < m; ++j) { T v = Mat[i * m + j]; if (min > v) min = v; } } return min; } T work_omp(const T* Mat, const int n, const int m) { T min = Mat[0]; #pragma omp parallel for schedule(static,1) firstprivate(min) lastprivate(min) for (int i = 0; i < n; ++i) { for (int j = 0; j < m; ++j) { T v = Mat[i * m + j]; if (min > v) min = v; } } return min; } void array_delay(int delaylength, double a[1]) { int i; a[0] = 1.0; for (i = 0; i < delaylength; i++) a[0] += i; if (a[0] < 0) printf("%f \n", a[0]); } double* light(const long long n) { double a[1]; { array_delay(n, a); } return a; } double* light_omp(const long long n) { double a[1]; #pragma omp parallel private(a) //numthreads() { array_delay(n, a); } return a; } #define eps T(0.00001) #define REPEATS 1000 int main(int argc, char** argv) { int N = 2000; //int Ns[] = { 16, 5, 10, 20, 30, 40, 50, 60 }; //int Ms[] = { 1, 10, 100, 200, 500, 1000, 2000, 5000 }; int M = 2000; int cores = omp_get_num_procs(); bool silent = false; /* if (argc >= 2) { N = std::atoi(argv[1]); M = N; } if (argc >= 3) { cores = std::atoi(argv[2]); } if (argc >= 4) { silent = true; }*/ /* omp_set_num_threads(cores); if (!silent) { std::cout << "matrix N, M: " << N << ", " << M << std::endl; std::cout << "number of omp threads: " << cores << std::endl; } */ T* Mat = new T[N * M * 16]; generate_random(Mat, N * M); if (N <= 0 || M <= 0 || cores <= 0 || Mat == nullptr) throw std::overflow_error("error"); auto start = std::chrono::high_resolution_clock::now(); auto end = start; T DP0, DP1, DP2; std::cout << "----------------------" << "bench work 1" << std::endl; /* for (int j = 0; j < 8; ++j) { int n0 = N;// Ns[j]; int m = Ms[j]; for (int k = 1; k <= 16; ++k) { omp_set_num_threads(k); int n = n0 * k; start = std::chrono::high_resolution_clock::now(); for (int i = 0; i < REPEATS; ++i) DP0 = work(Mat, n0, m); end = std::chrono::high_resolution_clock::now(); auto diff = std::chrono::duration_cast<std::chrono::microseconds>(end - start).count() / REPEATS; start = std::chrono::high_resolution_clock::now(); for (int i = 0; i < REPEATS; ++i) DP1 = work_omp(Mat, n0, m); end = std::chrono::high_resolution_clock::now(); auto diff1 = std::chrono::duration_cast<std::chrono::microseconds>(end - start).count() / REPEATS; start = std::chrono::high_resolution_clock::now(); for (int i = 0; i < REPEATS; ++i) DP2 = work_omp(Mat, n, m); end = std::chrono::high_resolution_clock::now(); auto diff2 = std::chrono::duration_cast<std::chrono::microseconds>(end - start).count() / REPEATS; std::cout << n0 << " " << m << " " << k << " "; std::cout << diff << " " << diff1 << " " << diff2 << std::endl; } }*/ std::cout << "----------------------" << "bench work 2" << std::endl; int n0 = 1;// Ns[j]; int m = 1;// Ms[j]; for (int k = 1; k <= 32; ++k) { omp_set_num_threads(k); int n = n0 * k; start = std::chrono::high_resolution_clock::now(); for (int i = 0; i < REPEATS; ++i) DP0 = work(Mat, n0, m); end = std::chrono::high_resolution_clock::now(); auto diff = std::chrono::duration_cast<std::chrono::nanoseconds>(end - start).count() / REPEATS; start = std::chrono::high_resolution_clock::now(); for (int i = 0; i < REPEATS; ++i) DP2 = work_omp(Mat, n, m); end = std::chrono::high_resolution_clock::now(); auto diff1 = std::chrono::duration_cast<std::chrono::nanoseconds>(end - start).count() / REPEATS; std::cout << n0 << " " << m << " " << k << " "; std::cout << diff << " " << diff1 << std::endl; } std::cout << "----------------------" << "light bench" << std::endl; for (int z = 12; z <= 20; z+=2) for (int k = 1; k <= 32; ++k) { omp_set_num_threads(k); long long n = 1; n <<= z; //std::clock_t c_start = std::clock(); start = std::chrono::high_resolution_clock::now(); for (int i = 0; i < REPEATS; ++i) DP0 = *light(n); //std::clock_t c_end = std::clock(); end = std::chrono::high_resolution_clock::now(); auto diff = std::chrono::duration_cast<std::chrono::nanoseconds>(end - start).count() / REPEATS; //auto c_diff = (1000000000.0 / REPEATS) * (c_end - c_start) / (CLOCKS_PER_SEC);// (c_end - c_start) / REPEATS; //c_start = std::clock(); start = std::chrono::high_resolution_clock::now(); for (int i = 0; i < REPEATS; ++i) DP2 = *light_omp(n); //c_end = std::clock(); end = std::chrono::high_resolution_clock::now(); auto diff1 = std::chrono::duration_cast<std::chrono::nanoseconds>(end - start).count() / REPEATS; //auto c_diff1 = (1000000000.0 / REPEATS) * (c_end - c_start) / (CLOCKS_PER_SEC); std::cout << n << " " << k << " "; std::cout << diff << " " << diff1 << std::endl; //std::cout << " " << c_diff << " " << c_diff1 << std::endl; } /* if (!silent) { std::clog << "time(us): \t\t" << diff << std::endl; std::clog << "time(us) omp: \t\t" << diff1 << std::endl; //std::clog << "time(us) omp threadprivate: \t" << diff3 << std::endl; } else { std::cout << N << " " << cores << " "; std::cout << diff << " " << diff1 << std::endl; } */ delete[] Mat; return 0; }
[ "55189420+zarond@users.noreply.github.com" ]
55189420+zarond@users.noreply.github.com
d6c14025fc6236df4696547fb3afffc935f11de7
6ca3828c85920b0017758f1356a30bee4b560070
/bvm/Shaders/upgradable2/Test/test_app.cpp
32bacd51a6a46f056734796f7cbd10872f0c5a32
[ "Apache-2.0" ]
permissive
jonathancross/beam
196b7ce1cd6e66950ea00963e35971367ef3c72d
06e39a3ad4a8c4d32f370d555bb9d2e54afc2463
refs/heads/master
2023-03-16T19:38:43.623617
2022-09-28T19:41:31
2022-09-28T19:41:31
340,680,884
0
0
Apache-2.0
2021-02-20T15:00:55
2021-02-20T15:00:55
null
UTF-8
C++
false
false
5,231
cpp
#include "../app_common_impl.h" #include "test.h" #define UpgrTest_manager_deploy_version(macro) #define UpgrTest_manager_view(macro) #define UpgrTest_manager_view_params(macro) macro(ContractID, cid) #define UpgrTest_manager_my_admin_key(macro) #define UpgrTest_manager_deploy_contract(macro) Upgradable2_deploy(macro) #define UpgrTest_manager_schedule_upgrade(macro) Upgradable2_schedule_upgrade(macro) #define UpgrTest_manager_explicit_upgrade(macro) macro(ContractID, cid) #define UpgrTestRole_manager(macro) \ macro(manager, deploy_version) \ macro(manager, view) \ macro(manager, deploy_contract) \ macro(manager, schedule_upgrade) \ macro(manager, explicit_upgrade) \ macro(manager, view_params) \ macro(manager, my_admin_key) #define UpgrTestRoles_All(macro) \ macro(manager) BEAM_EXPORT void Method_0() { // scheme Env::DocGroup root(""); { Env::DocGroup gr("roles"); #define THE_FIELD(type, name) Env::DocAddText(#name, #type); #define THE_METHOD(role, name) { Env::DocGroup grMethod(#name); UpgrTest_##role##_##name(THE_FIELD) } #define THE_ROLE(name) { Env::DocGroup grRole(#name); UpgrTestRole_##name(THE_METHOD) } UpgrTestRoles_All(THE_ROLE) #undef THE_ROLE #undef THE_METHOD #undef THE_FIELD } } #define THE_FIELD(type, name) const type& name, #define ON_METHOD(role, name) void On_##role##_##name(UpgrTest_##role##_##name(THE_FIELD) int unused = 0) void OnError(const char* sz) { Env::DocAddText("error", sz); } const char g_szAdminSeed[] = "test-11433"; struct MyKeyID :public Env::KeyID { MyKeyID() :Env::KeyID(&g_szAdminSeed, sizeof(g_szAdminSeed)) {} }; ON_METHOD(manager, view) { static const ShaderID s_pSid[] = { Upgradable2::Test::s_SID_0, Upgradable2::Test::s_SID_1 // latest version }; ContractID pVerCid[_countof(s_pSid)]; Height pVerDeploy[_countof(s_pSid)]; ManagerUpgadable2::Walker wlk; wlk.m_VerInfo.m_Count = _countof(s_pSid); wlk.m_VerInfo.s_pSid = s_pSid; wlk.m_VerInfo.m_pCid = pVerCid; wlk.m_VerInfo.m_pHeight = pVerDeploy; MyKeyID kid; wlk.ViewAll(&kid); } ON_METHOD(manager, deploy_version) { Env::GenerateKernel(nullptr, 0, nullptr, 0, nullptr, 0, nullptr, 0, "Deploy test bytecode", 0); } static const Amount g_DepositCA = 3000 * g_Beam2Groth; // 3K beams ON_METHOD(manager, deploy_contract) { MyKeyID kid; PubKey pk; kid.get_Pk(pk); Upgradable2::Create arg; if (!ManagerUpgadable2::FillDeployArgs(arg, &pk)) return; Env::GenerateKernel(nullptr, 0, &arg, sizeof(arg), nullptr, 0, nullptr, 0, "Deploy testo contract", ManagerUpgadable2::get_ChargeDeploy() + Env::Cost::SaveVar_For(sizeof(Upgradable2::Test::State))); } ON_METHOD(manager, schedule_upgrade) { MyKeyID kid; ManagerUpgadable2::MultiSigRitual::Perform_ScheduleUpgrade(cid, kid, cidVersion, hTarget); } ON_METHOD(manager, explicit_upgrade) { const uint32_t nChargeExtra = Env::Cost::LoadVar_For(sizeof(Upgradable2::Settings)) + Env::Cost::LoadVar_For(sizeof(Upgradable2::State)) + Env::Cost::SaveVar * 2 + // delete vars of Upgradable2 Env::Cost::SaveVar_For(sizeof(Upgradable2::State)) + Env::Cost::UpdateShader_For(2000); ManagerUpgadable2::MultiSigRitual::Perform_ExplicitUpgrade(cid, nChargeExtra); } Amount get_ContractLocked(AssetID aid, const ContractID& cid) { Env::Key_T<AssetID> key; _POD_(key.m_Prefix.m_Cid) = cid; key.m_Prefix.m_Tag = KeyTag::LockedAmount; key.m_KeyInContract = Utils::FromBE(aid); struct AmountBig { Amount m_Hi; Amount m_Lo; }; AmountBig val; if (!Env::VarReader::Read_T(key, val)) return 0; return Utils::FromBE(val.m_Lo); } ON_METHOD(manager, view_params) { Env::Key_T<uint8_t> key; _POD_(key.m_Prefix.m_Cid) = cid; key.m_KeyInContract = Upgradable2::Test::State::s_Key; Upgradable2::Test::State s; if (Env::VarReader::Read_T(key, s)) Env::DocAddNum("iVer", s.m_iVer); } ON_METHOD(manager, my_admin_key) { PubKey pk; MyKeyID kid; kid.get_Pk(pk); Env::DocAddBlob_T("admin_key", pk); } #undef ON_METHOD #undef THE_FIELD BEAM_EXPORT void Method_1() { Env::DocGroup root(""); char szRole[0x20], szAction[0x20]; if (!Env::DocGetText("role", szRole, sizeof(szRole))) return OnError("Role not specified"); if (!Env::DocGetText("action", szAction, sizeof(szAction))) return OnError("Action not specified"); const char* szErr = nullptr; #define PAR_READ(type, name) type arg_##name; Env::DocGet(#name, arg_##name); #define PAR_PASS(type, name) arg_##name, #define THE_METHOD(role, name) \ if (!Env::Strcmp(szAction, #name)) { \ UpgrTest_##role##_##name(PAR_READ) \ On_##role##_##name(UpgrTest_##role##_##name(PAR_PASS) 0); \ return; \ } #define THE_ROLE(name) \ if (!Env::Strcmp(szRole, #name)) { \ UpgrTestRole_##name(THE_METHOD) \ return OnError("invalid Action"); \ } UpgrTestRoles_All(THE_ROLE) #undef THE_ROLE #undef THE_METHOD #undef PAR_PASS #undef PAR_READ OnError("unknown Role"); }
[ "valdo@beam-mw.com" ]
valdo@beam-mw.com
2b201eae1d7bf90db6171f97dd2a75f01494a3e9
5a237a20af98165f56de7841a9f0637b1ab376ea
/pared.h
5f1d984bafc112592da6ee8023839f57ca796742
[]
no_license
GGost00/Practica_5
663de7098ee0b9efa4eb4047bb9096eef0521c38
00722e9ffc6b4b8c575432c1f5877dbcb60e051f
refs/heads/master
2023-02-01T04:59:48.505623
2020-12-18T12:54:20
2020-12-18T12:54:20
318,556,257
0
0
null
null
null
null
UTF-8
C++
false
false
449
h
#ifndef PARED_H #define PARED_H #include <QGraphicsItem> #include <QPainter> class pared: public QGraphicsItem { int w,h; int posx, posy; public: pared(int w_, int h_, int x, int y); QRectF boundingRect() const; void paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget = nullptr); int getPosx() const; int getPosy() const; int getW() const; int getH() const; }; #endif // PARED_H
[ "gabriel.restrepoi@gmail.com" ]
gabriel.restrepoi@gmail.com
436a86bace4cc941ad1c5a5c761f346832624771
dfe38e8e745482af557a4a9f62d1c23f78d035bc
/src/Shapes.re
6f8fac2ca800fa643f5a99a41feda63a9bcacd26
[]
no_license
yukims19/tetris-game
6a53f5369b324e09d90eb04d742ed6757f603447
54d9e3d075e734dd50da3127f62a1abd687d1b35
refs/heads/master
2020-04-28T07:55:09.548648
2019-03-14T17:40:21
2019-03-14T17:40:21
175,107,309
1
0
null
null
null
null
UTF-8
C++
false
false
1,102
re
type point = (int, int); type shape = | Z | S | T | O | L | I | J; let getTargetShape = shape: list(list(point)) => switch (shape) { | Z => [ [(3, 0), (2, 1), (3, 1), (2, 2)], [(1, 1), (2, 1), (2, 2), (3, 2)], ] | S => [ [(2, 0), (2, 1), (3, 1), (3, 2)], [(2, 1), (3, 1), (1, 2), (2, 2)], ] | T => [ [(2, 0), (2, 1), (2, 2), (3, 1)], [(2, 0), (1, 1), (2, 1), (3, 1)], [(2, 0), (1, 1), (2, 1), (2, 2)], [(1, 1), (2, 1), (3, 1), (2, 2)], ] | O => [[(2, 0), (3, 0), (2, 1), (3, 1)]] | L => [ [(2, 0), (2, 1), (2, 2), (3, 2)], [(3, 0), (1, 1), (2, 1), (3, 1)], [(1, 0), (2, 0), (2, 1), (2, 2)], [(1, 1), (2, 1), (3, 1), (1, 2)], ] | I => [ [(2, 0), (2, 1), (2, 2), (2, 3)], [(0, 1), (1, 1), (2, 1), (3, 1)], ] | J => [ [(2, 0), (3, 0), (2, 1), (2, 2)], [(1, 0), (1, 1), (2, 1), (3, 1)], [(2, 0), (2, 1), (2, 2), (1, 2)], [(1, 1), (2, 1), (3, 1), (3, 2)], ] }; let getShapeVariationNum = shape: int => getTargetShape(shape) |> List.length;
[ "yukims19@gmail.com" ]
yukims19@gmail.com
7bbf1fc0ae084a31be32afc0797ec92fb046347e
be4594dfed78a484b825e6954f0d51590b1818fb
/lmcu/lib/regs/STM32/STM32F100VC.h
3e6dfccbfd4020c0baa9db88d403ad49709648f7
[ "MIT" ]
permissive
a-sv/lmcu
7f218b994c63a01755e7356cd79a05a522e51f36
4dd3e0e97ef85c4a26cd5b03fae34e6ad14d6b92
refs/heads/master
2023-02-20T15:38:16.157242
2023-02-17T22:06:38
2023-02-17T22:06:38
124,688,140
0
0
null
null
null
null
UTF-8
C++
false
false
4,772
h
/**************************************************************************************************/ /** AUTO-GENERATED FILE. DO NOT MODIFY! **/ /**************************************************************************************************/ #pragma once #include "../common.h" namespace lmcu::device { static constexpr auto name = "STM32F100VC"; static constexpr auto cpu_arch = arch::CM3; static constexpr auto cpu_endian = endian::little; static constexpr uint32_t rom_size = 262144; static constexpr uint32_t ram_size = 24576; static constexpr uint32_t pins = 100; static constexpr uint32_t nvic_prio_bits = 4; } // namespace lmcu::device namespace lmcu::device { enum class irqn : int32_t { invalid_irqn = -15, wwdg = 0, pvd = 1, tamper = 2, rtc = 3, flash = 4, rcc = 5, exti0 = 6, exti1 = 7, exti2 = 8, exti3 = 9, exti4 = 10, dma1_channel1 = 11, dma1_channel2 = 12, dma1_channel3 = 13, dma1_channel4 = 14, dma1_channel5 = 15, dma1_channel6 = 16, dma1_channel7 = 17, adc1 = 18, adc2 = 18, usb_hp = 19, can1_tx = 19, usb_lp = 20, can1_rx0 = 20, can1_rx1 = 21, can1_sce = 22, exti9_5 = 23, tim1_brk = 24, tim1_up = 25, tim1_trg_com = 26, tim1_cc = 27, tim2 = 28, tim3 = 29, tim4 = 30, i2c1_ev = 31, i2c1_er = 32, i2c2_ev = 33, i2c2_er = 34, spi1 = 35, spi2 = 36, usart1 = 37, usart2 = 38, usart3 = 39, exti15_10 = 40, rtc_alarm = 41, usb_wkup = 42, tim8_brk = 43, tim8_up = 44, tim8_trg_com = 45, tim8_cc = 46, adc3 = 47, fsmc = 48, sdio = 49, tim5 = 50, spi3 = 51, uart4 = 52, uart5 = 53, tim6 = 54, tim7 = 55, dma2_channel1 = 56, dma2_channel2 = 57, dma2_channel3 = 58, dma2_channel4 = 59, dma2_channel5 = 59, nmi = -14, hard_fault = -13, mem_manage = -12, bus_fault = -11, usage_fault = -10, sv_call = -5, debug_mon = -4, pend_sv = -2, sys_tick = -1, }; constexpr irqn find_irqn(const char *name) noexcept { constexpr std::pair<const char*, irqn> irqlst[] = { {"wwdg", irqn::wwdg}, {"pvd", irqn::pvd}, {"tamper", irqn::tamper}, {"rtc", irqn::rtc}, {"flash", irqn::flash}, {"rcc", irqn::rcc}, {"exti0", irqn::exti0}, {"exti1", irqn::exti1}, {"exti2", irqn::exti2}, {"exti3", irqn::exti3}, {"exti4", irqn::exti4}, {"dma1_channel1", irqn::dma1_channel1}, {"dma1_channel2", irqn::dma1_channel2}, {"dma1_channel3", irqn::dma1_channel3}, {"dma1_channel4", irqn::dma1_channel4}, {"dma1_channel5", irqn::dma1_channel5}, {"dma1_channel6", irqn::dma1_channel6}, {"dma1_channel7", irqn::dma1_channel7}, {"adc1", irqn::adc1}, {"adc2", irqn::adc2}, {"usb_hp", irqn::usb_hp}, {"can1_tx", irqn::can1_tx}, {"usb_lp", irqn::usb_lp}, {"can1_rx0", irqn::can1_rx0}, {"can1_rx1", irqn::can1_rx1}, {"can1_sce", irqn::can1_sce}, {"exti9_5", irqn::exti9_5}, {"tim1_brk", irqn::tim1_brk}, {"tim1_up", irqn::tim1_up}, {"tim1_trg_com", irqn::tim1_trg_com}, {"tim1_cc", irqn::tim1_cc}, {"tim2", irqn::tim2}, {"tim3", irqn::tim3}, {"tim4", irqn::tim4}, {"i2c1_ev", irqn::i2c1_ev}, {"i2c1_er", irqn::i2c1_er}, {"i2c2_ev", irqn::i2c2_ev}, {"i2c2_er", irqn::i2c2_er}, {"spi1", irqn::spi1}, {"spi2", irqn::spi2}, {"usart1", irqn::usart1}, {"usart2", irqn::usart2}, {"usart3", irqn::usart3}, {"exti15_10", irqn::exti15_10}, {"rtc_alarm", irqn::rtc_alarm}, {"usb_wkup", irqn::usb_wkup}, {"tim8_brk", irqn::tim8_brk}, {"tim8_up", irqn::tim8_up}, {"tim8_trg_com", irqn::tim8_trg_com}, {"tim8_cc", irqn::tim8_cc}, {"adc3", irqn::adc3}, {"fsmc", irqn::fsmc}, {"sdio", irqn::sdio}, {"tim5", irqn::tim5}, {"spi3", irqn::spi3}, {"uart4", irqn::uart4}, {"uart5", irqn::uart5}, {"tim6", irqn::tim6}, {"tim7", irqn::tim7}, {"dma2_channel1", irqn::dma2_channel1}, {"dma2_channel2", irqn::dma2_channel2}, {"dma2_channel3", irqn::dma2_channel3}, {"dma2_channel4", irqn::dma2_channel4}, {"dma2_channel5", irqn::dma2_channel5}, {"nmi", irqn::nmi}, {"hard_fault", irqn::hard_fault}, {"mem_manage", irqn::mem_manage}, {"bus_fault", irqn::bus_fault}, {"usage_fault", irqn::usage_fault}, {"sv_call", irqn::sv_call}, {"debug_mon", irqn::debug_mon}, {"pend_sv", irqn::pend_sv}, {"sys_tick", irqn::sys_tick}, }; auto cmp = [](const char *a, const char *b) { while(*a && *b) { if(*a++ != *b++) { return false; } } return *a == *b; }; for(auto irq : irqlst) { if(cmp(name, irq.first)) { return irq.second; } } return irqn::invalid_irqn; } } // namespace lmcu::device
[ "runtime.rnt@gmail.com" ]
runtime.rnt@gmail.com
5df5fc49af5aba3dffe1d12844727f8e04d4d3a0
5d7728b1066ce8075b3e0aa6f9845b6e84260b7a
/libopenglwrapperlegacy/src/OpenGLWrapperLegacyConcrete.hpp
89b960a503810b8f54503ac59aec61295e7c030a
[]
no_license
bartekordek/OpenGLWrapperLegacy
7396d2a8d4a9faf4a8c5bed072fa31544517637b
9e9da467607e818d48990da7630615d7618ce651
refs/heads/master
2020-09-06T16:37:22.727334
2019-11-30T11:17:18
2019-12-28T16:57:41
220,482,828
0
0
null
null
null
null
UTF-8
C++
false
false
2,310
hpp
#pragma once #include "libopenglwrapperlegacy/IOpenGLWrapperLegacy.hpp" #include "SDL2Wrapper/ISDL2Wrapper.hpp" #include "SDL2Wrapper/IMPORT_SDL_video.hpp" #include "CUL/STL_IMPORTS/STD_functional.hpp" #include "CUL/STL_IMPORTS/STD_thread.hpp" #include "CUL/GenericUtils/LckPrim.hpp" #include "CUL/STL_IMPORTS/STD_vector.hpp" NAMESPACE_BEGIN( OGLWL ) #if _MSC_VER #pragma warning( push ) #pragma warning( disable: 4820 ) // warning C4820: 'OGLWL::OpenGLWrapperLegacyConcrete': '6' bytes padding added after data member. #endif class OpenGLWrapperLegacyConcrete final: public IOpenGLwrapperLegacy { public: explicit OpenGLWrapperLegacyConcrete( SDL2W::ISDL2Wrapper* sdl2w ); protected: private: using CustomSteps = std::map<Cunt, std::function<void()>>; using LckBool = CUL::GUTILS::LckBool; void mainLoop(); void initialize() override; void beginRenderingLoop() override; void endRenderingLoop() override; void renderFrame() override; void setProjection(); void clearFrame(); void clearTransformations(); void renderObjects(); void customFrameSteps(); void updateBuffers(); void addCustomFrameStep( const std::function<void()>& callback, Cunt id ) override; void removeCustomFrameStep( Cunt id ) override; const bool customFrameStepExists( Cunt id ) const override; void cleanup(); ~OpenGLWrapperLegacyConcrete(); ProjectionType m_projectionType = ProjectionType::PERSPECTIVE; LckBool m_runMainLoop = true; LckBool m_clearEveryFrame = true; LckBool m_clearTransformations = true; LckBool m_updateBuffers = true; SDL2W::ISDL2Wrapper* m_sdl2w = nullptr; SDL2W::IWindow* m_currentWindow = nullptr; SDL_GLContext m_oglContext = nullptr; std::thread m_renderingLoopThread; CustomSteps m_customSteps; double m_fovAngle = 90.0; unsigned m_afterFrameSleepMicroSeconds = 12800; // Removed. private: OpenGLWrapperLegacyConcrete() = delete; OpenGLWrapperLegacyConcrete( const OpenGLWrapperLegacyConcrete& arg ) = delete; OpenGLWrapperLegacyConcrete& operator=( const OpenGLWrapperLegacyConcrete& rhv ) = delete; }; #ifdef _MSC_VER #pragma warning( pop ) #endif NAMESPACE_END( OGLWL )
[ "bartekordek@gmail.com" ]
bartekordek@gmail.com
49c1e06e50bcb77c194551ae5d149453534b4ff8
83212a5d8b3d8b6fb057c75a0524de4b9aac2348
/DataBase/build-lab3_4-Desktop_Qt_5_13_1_MinGW_64_bit-Debug/debug/qrc_myResources.cpp
8a63ddcbe3886607ecf8dc0502b918e4c3ba7629
[]
no_license
Alextek777/Object_Oriented_Programming
c52d65a9c54d08e47a38fad856c86b9424abbc1e
eab16090fc2efefbd085d859bac18b5e2805621c
refs/heads/master
2020-09-10T17:43:02.976404
2020-05-15T22:05:51
2020-05-15T22:05:51
221,781,257
0
1
null
null
null
null
UTF-8
C++
false
false
15,235
cpp
/**************************************************************************** ** Resource object code ** ** Created by: The Resource Compiler for Qt version 5.13.1 ** ** WARNING! All changes made in this file will be lost! *****************************************************************************/ static const unsigned char qt_resource_data[] = { // C:/Users/alext/Documents/Object_Oriented_Programming/DataBase/lab3_4/icon.png 0x0,0x0,0x9,0x9c, 0x89, 0x50,0x4e,0x47,0xd,0xa,0x1a,0xa,0x0,0x0,0x0,0xd,0x49,0x48,0x44,0x52,0x0, 0x0,0x0,0xd8,0x0,0x0,0x0,0xe9,0x8,0x3,0x0,0x0,0x0,0x71,0xd8,0x9,0xd7, 0x0,0x0,0x0,0xc0,0x50,0x4c,0x54,0x45,0xff,0xff,0xff,0x14,0x12,0x13,0x11,0x12, 0x24,0x0,0x0,0x0,0xda,0xda,0xdb,0xe8,0xe8,0xe8,0x10,0xe,0xf,0x9b,0x9b,0x9b, 0xef,0xef,0xef,0xcd,0xcc,0xcd,0xc0,0xc0,0xc0,0x1a,0x17,0x18,0x63,0x62,0x62,0xe0, 0xe0,0xe0,0xeb,0xeb,0xeb,0xd,0xb,0xc,0x78,0x78,0x78,0xad,0xad,0xad,0x30,0x2f, 0x2f,0x0,0x0,0x1a,0xbb,0xba,0xbb,0x72,0x72,0x72,0x0,0x0,0x17,0x83,0x83,0x83, 0x0,0x0,0x15,0xa,0xc,0x20,0xf9,0xf9,0xf9,0x6,0x0,0x4,0x11,0x12,0x23,0x38, 0x36,0x37,0x1f,0x1d,0x1e,0x89,0x89,0x89,0x93,0x93,0x93,0x55,0x54,0x55,0x8d,0x8d, 0x95,0x6f,0x6f,0x78,0x89,0x89,0x91,0xa3,0xa2,0xa2,0x2b,0x29,0x2a,0x45,0x45,0x45, 0x5f,0x5e,0x5e,0x23,0x25,0x33,0x79,0x79,0x81,0x29,0x2a,0x38,0x41,0x41,0x4c,0x0, 0x0,0x1d,0x55,0x55,0x5f,0x0,0x0,0xe,0x5c,0x5c,0x64,0x44,0x44,0x4f,0x4f,0x4d, 0x4e,0x3e,0x3c,0x3d,0x19,0x1b,0x2a,0x34,0x33,0x40,0x67,0x68,0x71,0xa9,0xa9,0xaf, 0x37,0x39,0x46,0x9b,0x9d,0xa4,0x68,0x6b,0x74,0x9f,0x9f,0xa7,0x8b,0x8d,0x94,0x60, 0x60,0x69,0x78,0x78,0x83,0xc8,0xc8,0xcb,0x53,0xec,0xd7,0x97,0x0,0x0,0x8,0x97, 0x49,0x44,0x41,0x54,0x78,0x9c,0xed,0x9d,0xd,0x7f,0x9a,0x3c,0x17,0x87,0xd1,0x60, 0xea,0x3b,0xb3,0x58,0x25,0xe2,0x3b,0xa8,0x15,0x14,0x65,0x55,0xab,0xf7,0xda,0xed, 0xfb,0x7f,0xab,0x3b,0x11,0x5b,0x83,0x82,0xdb,0xc3,0x9d,0x40,0xdd,0x73,0xae,0xfd, 0x5a,0x1,0x69,0xe,0x7f,0x92,0x9c,0x24,0x27,0x81,0x29,0xa,0x0,0x0,0x0,0x0, 0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0, 0x0,0x0,0x0,0x0,0x0,0x0,0x40,0x86,0x14,0xcb,0x9,0x28,0x66,0x7d,0xd5,0xbf, 0xa5,0xf3,0x84,0x12,0xf1,0xd4,0xc9,0xfa,0xca,0x6f,0xd3,0xe9,0xa1,0x5c,0x22,0x50, 0xef,0x6b,0x2b,0x6b,0x27,0xd4,0x45,0x95,0xb5,0xb3,0xbe,0xf6,0x5b,0x14,0xfb,0x5a, 0x52,0x61,0x5a,0xff,0x2b,0xd7,0xb3,0x5a,0xe2,0xc,0xa3,0x59,0x56,0xcb,0xfa,0xea, 0x6f,0x70,0x12,0xa6,0x71,0xe0,0x8f,0x3,0x1f,0x39,0x73,0xda,0xc2,0xc1,0x57,0xa7, 0x8f,0x3b,0x11,0xf6,0xc8,0xd1,0xa7,0xd7,0x6d,0xb2,0xd,0x33,0xb8,0xfe,0xde,0xe3, 0x23,0x3b,0x9,0x57,0x1e,0x1f,0xa7,0x38,0x87,0xfb,0xc1,0x19,0x77,0x21,0x4c,0x7b, 0xe4,0xf,0xd,0x50,0xce,0x9c,0xb1,0x8d,0xa7,0xa3,0x68,0x53,0x55,0x94,0x2a,0xa, 0x64,0xd0,0x4f,0xd4,0x50,0x94,0x6f,0xe8,0x4e,0x84,0xe1,0x7e,0x7b,0x30,0x68,0xff, 0x52,0x94,0x3a,0xfd,0x1c,0xcc,0xb4,0xe3,0xd5,0x2b,0x4a,0xe9,0x78,0xfd,0x1a,0x75, 0xeb,0x5,0x13,0xa3,0x81,0xa2,0x34,0x98,0xbe,0x7b,0x12,0x96,0xc3,0xac,0xc5,0x7d, 0x56,0x94,0x26,0xfb,0xd4,0xa8,0xd0,0xa2,0x52,0x28,0x29,0xca,0xcb,0xb1,0x72,0x31, 0x49,0x13,0x34,0xa5,0xf2,0x10,0xbe,0x37,0x61,0xc7,0xcb,0xac,0x32,0x61,0xc1,0x66, 0x9b,0x95,0xba,0xe,0x95,0x13,0xec,0x52,0x8d,0xa3,0x32,0xfd,0x61,0xbb,0xf7,0x2d, 0x4c,0xa5,0xb9,0x83,0x9a,0x4a,0xfd,0xe4,0x21,0x7b,0xc7,0x53,0x1b,0xc7,0x2f,0xef, 0x59,0x98,0xf6,0xc2,0xae,0x9d,0xc9,0xa9,0x9e,0x14,0xd0,0xc2,0x18,0x14,0xc4,0xfb, 0x16,0x46,0xf3,0xaa,0xc8,0x2a,0x5b,0xe9,0xe4,0x3e,0x72,0x1a,0xa6,0x7d,0x8c,0xe1, 0x49,0xcd,0xfd,0xa,0xc3,0xb4,0x76,0x75,0x1e,0x86,0xc3,0x21,0x55,0x13,0x74,0xb8, 0xa8,0x18,0xb5,0xd3,0x9,0xda,0xb5,0x3b,0x16,0xc6,0x77,0x6e,0x8f,0xee,0x3,0x7d, 0xa3,0xe5,0xb0,0x4d,0x4f,0xc5,0x77,0x2e,0xac,0xa6,0xd4,0xfb,0x48,0xd3,0x10,0xf5, 0x21,0x45,0x2a,0x6,0x8d,0x14,0xe5,0x99,0x15,0xcc,0xf2,0x7d,0xbb,0x7b,0xa6,0x63, 0x82,0x30,0x85,0x65,0xdd,0x13,0xd2,0xa6,0x45,0x76,0xdc,0xa4,0x1e,0xe5,0xe1,0x8e, 0x1a,0xe8,0x42,0x48,0x58,0x99,0x5d,0x39,0x6d,0xb1,0x66,0xc7,0xaa,0xc5,0x7a,0x5a, 0xd4,0x7d,0xd4,0x94,0x4e,0x8e,0xee,0xa3,0xc9,0x51,0x11,0x2f,0xac,0x90,0xf5,0xd5, 0x5f,0xd3,0x29,0xd,0x47,0x53,0x8d,0xe6,0x4a,0xe,0xe7,0xce,0x4,0x7b,0xb4,0x8b, 0x7b,0xea,0xfe,0xd2,0x13,0xfa,0xb9,0x4a,0x3f,0x87,0x2,0x17,0x92,0xcb,0xb1,0x4e, 0xf0,0xf9,0x2f,0xe8,0x26,0xc6,0xda,0xf4,0x79,0x58,0xfa,0x2a,0x63,0xe9,0xc2,0xa0, 0xcf,0xba,0x4e,0xac,0xb8,0x85,0x74,0x5,0x7b,0xdc,0xc1,0xe3,0xe6,0xe7,0x7e,0xb0, 0x11,0xfe,0x9a,0x2a,0xa3,0x49,0x4d,0x87,0x5f,0x62,0xcc,0x39,0x40,0x88,0xd7,0x23, 0x0,0xd,0xe1,0x87,0xac,0x55,0x29,0x6a,0x5f,0xb4,0x2c,0x6,0x46,0xbd,0x8c,0x5d, 0x49,0x13,0x25,0xe,0x72,0xdc,0xc6,0x64,0x5e,0x27,0x3b,0x1a,0x32,0xb2,0x2b,0x40, 0xcb,0x52,0x59,0x39,0xa4,0x2b,0x59,0xa4,0x34,0x84,0xc9,0x25,0x87,0xd9,0xf8,0x26, 0x1b,0xa,0xbc,0x2e,0x3a,0xb4,0x9c,0x94,0xfe,0x23,0xf,0x23,0xc4,0x85,0xb9,0x34, 0x9c,0x95,0xdf,0xaf,0x22,0xee,0xf6,0x56,0x85,0xd4,0x76,0x75,0xc4,0x29,0xa3,0xbd, 0xca,0x4c,0x28,0xf1,0xba,0x1a,0xa2,0x52,0x9d,0x9c,0x8b,0x1,0xa6,0xdd,0xcb,0x2c, 0xe0,0x32,0x4c,0x64,0x45,0x6f,0x70,0xc9,0x66,0x12,0xf6,0xae,0x73,0x17,0x30,0x14, 0x99,0xf0,0xb7,0xcf,0x84,0xb1,0x99,0x45,0x2d,0x1b,0x7e,0xda,0xd7,0xa6,0x42,0x13, 0xee,0x9c,0xb,0xa3,0xb8,0x12,0xfe,0x3f,0xc0,0x99,0x17,0xdc,0x1,0x6a,0xcb,0xba, 0x65,0x7f,0x44,0xf3,0x5c,0x60,0x44,0xf,0x38,0x54,0xee,0x9e,0xa5,0xdf,0x96,0x8d, 0x42,0x43,0x2f,0xb1,0x7c,0xff,0x6c,0xa8,0xd1,0x93,0xe8,0xb4,0x7f,0x87,0xca,0xb9, 0xe,0xe1,0x77,0x95,0x2b,0xd,0x5a,0xda,0xc3,0xcf,0x81,0xd4,0x7a,0x60,0x9e,0xcb, 0xe2,0x44,0x7c,0xea,0xb7,0xe8,0x54,0xa4,0x9a,0xe6,0x6e,0x5b,0x4f,0x7c,0xea,0xb7, 0x68,0x70,0xae,0x43,0x42,0x5b,0x53,0xe0,0xa,0xfa,0x2f,0xf1,0xc9,0xdf,0xa0,0xf7, 0x39,0xc,0x93,0xd3,0xa1,0x3b,0xf7,0x6a,0xd8,0xb4,0x4d,0x7a,0xf0,0xae,0x43,0x4a, 0x7f,0xae,0xcc,0x19,0xa8,0xcb,0x30,0x10,0xc3,0xd3,0xa7,0x5d,0xf3,0xbb,0x14,0x3, 0x1d,0xae,0x48,0xc,0xa4,0x58,0x88,0xa4,0x88,0xa5,0x77,0x7a,0x1e,0x38,0xaf,0x9b, 0x5e,0x87,0x71,0x22,0xd7,0x75,0x30,0x8a,0x5c,0xef,0xa3,0x29,0xc7,0xc4,0x89,0xda, 0x64,0x30,0x6c,0x9c,0x5a,0xcb,0x97,0x14,0xca,0xc9,0xb9,0xb4,0xb3,0x28,0x39,0xa3, 0xd0,0x18,0xe,0x26,0xa2,0x83,0x57,0xc5,0x6a,0x10,0x94,0xe8,0xb5,0xcb,0x75,0x7e, 0x84,0x29,0x2f,0x2e,0xcd,0x1b,0xa9,0x29,0xf5,0x72,0xbb,0x17,0x5c,0x41,0x55,0x68, 0x30,0xb5,0xd3,0x3f,0x99,0xd1,0x10,0xc2,0xa3,0x99,0x76,0x79,0x33,0x65,0x70,0x76, 0x1f,0xe6,0x68,0x84,0xd1,0x47,0x9c,0xf,0x9,0x5d,0x9a,0xc4,0x47,0x22,0xb0,0x79, 0xe,0x25,0xca,0xc,0x91,0x71,0x23,0x69,0xd3,0xe4,0xa3,0x46,0x2,0x6f,0x26,0x57, 0x2c,0x42,0x68,0x8f,0x12,0x1d,0x56,0xb1,0x12,0x13,0xb3,0x14,0xd8,0xe9,0x1e,0xc4, 0x8,0x13,0x1b,0x12,0xb8,0xe4,0x5b,0x9c,0x55,0x71,0xe,0xeb,0x29,0xda,0x84,0xf0, 0x11,0x66,0x18,0x35,0x4e,0x98,0xb8,0x31,0x5a,0x35,0xda,0x84,0xf8,0x11,0x66,0x98, 0x99,0x29,0xdb,0x6c,0x9c,0x30,0xc9,0xe3,0xf6,0xa6,0xf4,0xfb,0x19,0x2d,0x4c,0x7e, 0xa4,0x25,0x7a,0xca,0x43,0xba,0x30,0xf9,0x83,0xdb,0x68,0xa7,0x25,0x5b,0x18,0xd6, 0xa4,0x8f,0x27,0x6a,0x91,0x59,0x26,0x50,0x58,0xa4,0xe3,0x4d,0x23,0x80,0xf4,0x1c, 0x69,0x58,0xdc,0xd0,0xb6,0x11,0x99,0x7e,0xa,0x33,0x6,0xe5,0x48,0xc3,0xe2,0x46, 0x4a,0x45,0x7c,0x5d,0x24,0xb4,0x99,0xb0,0xe4,0x6f,0x30,0xbd,0x9e,0x9,0xc6,0x58, 0x60,0x67,0x71,0x78,0x7d,0xe7,0xd2,0x89,0x8b,0x45,0xb8,0xf,0xb1,0xdd,0x9d,0xd1, 0x95,0x81,0x74,0xa6,0x88,0xaf,0x9b,0x32,0xc1,0x3,0x8a,0x4e,0xf5,0x72,0x79,0x40, 0x3a,0x13,0x21,0xf,0x17,0xc2,0x34,0x54,0x15,0xdd,0xef,0x6e,0x56,0xc2,0xb,0x55, 0x52,0x89,0x64,0x86,0x1f,0x29,0xa1,0x83,0xc1,0x9c,0x8c,0x30,0x81,0xda,0x7c,0xc, 0x2d,0x12,0x98,0x36,0x6a,0x5,0xa9,0xd4,0x26,0x95,0x90,0xae,0x59,0x53,0x92,0x23, 0x2e,0x86,0xdb,0x4b,0x4d,0xc0,0xfa,0x87,0xdf,0x10,0xb2,0x87,0x73,0x72,0x64,0x5d, 0x17,0xf8,0xb4,0x91,0x56,0xad,0x5f,0x24,0x2d,0x2f,0xfa,0x53,0x24,0x5,0x67,0x63, 0x7,0x7e,0xa9,0x81,0x25,0x2d,0x42,0x8d,0x68,0xa5,0x53,0x46,0x52,0xa7,0x60,0x96, 0x71,0x49,0x94,0x35,0x64,0x2f,0x66,0x9e,0x61,0x92,0x2,0xea,0x31,0x3,0xf5,0x54, 0x91,0x12,0x8c,0x48,0xfe,0xc0,0xac,0x40,0x61,0x32,0x96,0xd4,0x3e,0x66,0x5e,0xc5, 0x58,0xb0,0x5b,0xbc,0xae,0x8e,0xbc,0xc5,0xa4,0x7f,0xe,0x46,0xe2,0x85,0xc5,0x85, 0xb9,0xd3,0x45,0x42,0x88,0xf6,0x2b,0xf8,0xe,0x29,0xa3,0xc0,0xb8,0xf8,0x7d,0xba, 0x48,0x68,0xa2,0x23,0x3,0x46,0xa9,0x23,0x61,0xf1,0xc5,0x55,0xbf,0xc3,0x8c,0x5e, 0x87,0x9d,0xd0,0xc5,0xe0,0xe8,0x71,0xcb,0xa5,0x51,0xf1,0x33,0x8d,0x9d,0xb,0x6f, 0x8f,0xd1,0xa8,0x1a,0xc5,0x28,0xd9,0x13,0x6,0xa8,0x12,0x99,0x5a,0xf5,0xe5,0x32, 0x34,0x20,0x3c,0x36,0x56,0xec,0x87,0x7,0x7d,0x5a,0x5c,0x1f,0xa0,0x96,0xe4,0x5, 0x11,0xe8,0x39,0xae,0xaf,0x34,0x9,0x2b,0x13,0x3f,0xd5,0x58,0x8,0x37,0x63,0x37, 0xba,0x0,0x9,0xdc,0xe7,0xad,0x89,0xb6,0x51,0x68,0x2e,0x9,0xb,0x7f,0x39,0xc6, 0xc5,0xb,0x2d,0x6e,0xb8,0xdd,0x4,0xd,0x1e,0xae,0xc4,0x1b,0xe,0x4f,0x3a,0xe2, 0x8a,0xe8,0x9,0x3,0x10,0x6,0xc2,0x40,0x18,0x8,0x3,0x61,0x20,0xc,0x84,0x81, 0xb0,0xec,0x84,0xc5,0x8f,0x8b,0x92,0x4,0x8c,0xe3,0x27,0xea,0xb9,0x55,0xcf,0xa9, 0x8,0xa3,0xbd,0xe0,0x62,0x34,0x89,0x9e,0x20,0xd6,0xa6,0xa5,0xe8,0xd4,0xa,0x17, 0x4b,0x4c,0xe4,0xb,0xcb,0x21,0x54,0x89,0x42,0x4b,0x16,0xcc,0xd2,0x50,0x2e,0x32, 0x39,0x74,0x61,0x36,0x5,0x61,0xc1,0x3b,0xf,0xae,0x49,0x22,0x2b,0x3e,0xb9,0xab, 0xb3,0x52,0x10,0x96,0x9,0x20,0xc,0x84,0x81,0x30,0xb9,0x80,0x30,0x10,0x6,0xc2, 0xe4,0x2,0xc2,0x40,0xd8,0xff,0xa3,0x30,0x19,0xcb,0xde,0xbe,0x82,0x30,0xf4,0x20, 0x9e,0xd8,0xe9,0xd3,0x54,0x85,0x9,0xb6,0xc4,0xa8,0x7f,0x9,0x61,0x72,0x1f,0xc9, 0x7,0x61,0x9,0x1,0x61,0x42,0x0,0x61,0xff,0x1d,0x10,0x26,0x84,0x14,0x85,0x15, 0xe2,0xe2,0x85,0x52,0x56,0x7d,0xc6,0xae,0x66,0x15,0xff,0x5f,0x6a,0x5c,0x2e,0x60, 0x39,0x9b,0x7a,0x11,0x6c,0xe9,0x68,0x2d,0x17,0x73,0x1b,0x25,0x3c,0xdc,0x15,0xf3, 0x2c,0xb4,0xa4,0xf7,0x43,0xa4,0x68,0x2d,0x66,0xd5,0xbd,0xa4,0x87,0xbc,0xd3,0xb4, 0x16,0xbd,0x26,0x58,0xd6,0x53,0xf9,0xd1,0xcf,0xe3,0x4b,0x59,0x13,0x1c,0xf1,0x70, 0x1c,0x7b,0x11,0xa6,0xc,0x4b,0x81,0xb5,0xeb,0xc0,0xbd,0xac,0xe7,0x5d,0x7,0x1f, 0xef,0x6f,0x3e,0x61,0x22,0x99,0x6f,0x51,0x68,0x5f,0x5b,0x93,0xf6,0x5a,0xe4,0x5a, 0x7b,0xc6,0x3d,0x5b,0x95,0x9b,0xd,0xa4,0xbe,0x44,0xe1,0xc2,0xda,0x77,0xb9,0xd6, 0xf8,0x59,0x39,0x99,0x76,0xb2,0xb0,0x6,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0, 0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0, 0x0,0xc0,0xef,0x51,0xff,0x52,0x14,0x19,0xcf,0x12,0x7d,0x5,0x94,0xfc,0x5f,0xa, 0x8,0xbb,0x37,0x4e,0xc2,0xc8,0xe9,0x27,0xcf,0x7d,0xe6,0xf3,0xba,0x9e,0x27,0xe7, 0x3d,0xb6,0xa5,0x9f,0x77,0xbf,0x38,0x81,0x30,0xb2,0x27,0x79,0xe2,0x6e,0x82,0xed, 0x6d,0x37,0xf8,0xaa,0xdb,0x5a,0x7b,0x86,0xbb,0xff,0x90,0xb2,0xf1,0x49,0x77,0xbe, 0xde,0xde,0x8b,0xb2,0x40,0xd8,0x72,0xf7,0xae,0xb7,0xde,0x5a,0x46,0xab,0xdb,0x32, 0xd0,0xdb,0x86,0x18,0x86,0x4e,0xc,0xf4,0x4a,0xb1,0xe,0xc8,0x40,0x88,0x10,0x84, 0xb6,0x25,0x84,0xf6,0xb6,0x9f,0xa6,0xb0,0xee,0x1f,0x1d,0xed,0x46,0xee,0x9d,0x72, 0x6c,0x33,0x36,0x36,0x8e,0x33,0xb4,0x91,0x33,0xb6,0x9c,0xc3,0x76,0x7c,0x70,0xfc, 0x83,0xa7,0x7a,0x8,0x59,0xf5,0xf5,0x58,0x2d,0xb9,0xb,0x55,0xf5,0x7f,0x2d,0x54, 0x77,0xb1,0x4f,0x35,0xc7,0x68,0x45,0x8,0x2a,0x9,0x61,0xdb,0xe4,0xf4,0xf9,0x79, 0x84,0xed,0x74,0x75,0x9d,0xe8,0xf4,0xc8,0x92,0xd0,0xf,0x9d,0x90,0x65,0x48,0x58, 0xde,0x18,0x77,0x77,0x96,0xd5,0xb2,0xac,0x9d,0x69,0xda,0xcb,0xb7,0x3c,0xb2,0x7e, 0x7a,0xab,0x45,0xa9,0xe6,0x58,0x43,0xb7,0x84,0xde,0x5f,0xcb,0x7b,0x34,0xaf,0xab, 0x3a,0x21,0x69,0xea,0x22,0xdb,0xdd,0xc2,0xdb,0x2c,0xf3,0xf3,0x3d,0x99,0x13,0xe2, 0xdb,0xde,0xbe,0xe5,0xb6,0xf2,0xf3,0x7f,0x68,0x55,0x77,0x97,0x2e,0x3d,0xbe,0x59, 0xae,0x3d,0x7b,0x77,0xd8,0x38,0xef,0xde,0xf,0xcb,0xde,0xda,0x9e,0xf5,0x46,0x7f, 0xe9,0xbc,0x30,0xfd,0x7d,0x6d,0xaf,0xc7,0xbb,0x9d,0xe3,0xeb,0x86,0x4d,0xe,0x2b, 0x63,0x67,0xfb,0xfa,0xa,0x2d,0x55,0x67,0xe8,0x35,0xd1,0xbe,0xf9,0x6b,0xb5,0x72, 0xb,0xa5,0x79,0xca,0x15,0xac,0x65,0xdb,0xfe,0xab,0x33,0xf6,0x7f,0xf8,0x8e,0x73, 0xf0,0x6c,0xff,0x40,0x6f,0xbe,0x4d,0x35,0xac,0x2c,0x8a,0xf3,0x6a,0xbf,0x79,0x3f, 0xd1,0x6e,0xb7,0xa3,0xe7,0xac,0x6c,0xc7,0x76,0x5e,0xff,0x39,0x90,0xd7,0x83,0x15, 0x12,0x96,0x27,0xaf,0xce,0x66,0x4c,0x5c,0xf7,0x40,0xe6,0xeb,0x77,0x6b,0x9d,0x1f, 0xaf,0xbd,0xe5,0xc1,0x7a,0x63,0xc5,0x4f,0xb5,0xca,0xce,0x5b,0xd3,0x59,0x94,0x7c, 0x75,0x95,0xae,0x30,0xdd,0xa2,0x72,0x16,0x3f,0x16,0xb6,0xe7,0xd8,0x3f,0xdd,0xf7, 0x83,0xed,0xbc,0x53,0x31,0xb6,0xbd,0xb1,0x69,0x46,0x8d,0x87,0x9e,0xb7,0x73,0xd6, 0xf6,0xdc,0xf1,0xc7,0x63,0xcb,0xdb,0x1c,0xbc,0x31,0xad,0x41,0x8e,0xfd,0xc3,0x8, 0x9,0xd3,0xad,0xb9,0xee,0xe,0x1c,0xe2,0xbe,0x59,0xab,0x1d,0xda,0xd9,0x73,0x77, 0x4b,0xbc,0xa1,0xd3,0x32,0xd6,0xfe,0x72,0xfc,0x6e,0xac,0xac,0x37,0xd7,0x42,0xd6, 0x22,0x6d,0x9f,0xb8,0xd1,0xf7,0x9b,0xcd,0x7e,0x73,0x2c,0x8c,0x3e,0x99,0xe7,0x7d, 0x83,0xed,0x6d,0xd,0x5f,0x5f,0xe8,0x2e,0xfb,0xc6,0xf5,0x7c,0xdf,0x9d,0xbb,0x73, 0x42,0xf,0xd2,0xdf,0xfb,0xd5,0x76,0x9e,0xf,0x9,0x63,0x2d,0x14,0x69,0xe9,0xc7, 0x1f,0x3d,0xbf,0x6c,0xb1,0xda,0xa4,0x1b,0x2d,0x76,0x9c,0x18,0xb4,0x42,0xea,0xc6, 0xb1,0x6e,0xa6,0xac,0x2b,0x7f,0x74,0x13,0x24,0xdf,0x25,0xf9,0x8f,0x7f,0x5d,0xd2, 0x25,0x1f,0xdb,0xc7,0x2f,0x8f,0x74,0x4f,0x27,0x92,0xcf,0x86,0xf7,0x6f,0xef,0x79, 0xfc,0x7d,0x80,0xb0,0x7b,0xe3,0x5f,0x1b,0x4d,0xe9,0xfe,0x4a,0xd1,0x8e,0xc,0x0, 0x0,0x0,0x0,0x49,0x45,0x4e,0x44,0xae,0x42,0x60,0x82, }; static const unsigned char qt_resource_name[] = { // icons 0x0,0x5, 0x0,0x6f,0xa6,0x53, 0x0,0x69, 0x0,0x63,0x0,0x6f,0x0,0x6e,0x0,0x73, // icon.png 0x0,0x8, 0xa,0x61,0x5a,0xa7, 0x0,0x69, 0x0,0x63,0x0,0x6f,0x0,0x6e,0x0,0x2e,0x0,0x70,0x0,0x6e,0x0,0x67, }; static const unsigned char qt_resource_struct[] = { // : 0x0,0x0,0x0,0x0,0x0,0x2,0x0,0x0,0x0,0x1,0x0,0x0,0x0,0x1, 0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0, // :/icons 0x0,0x0,0x0,0x0,0x0,0x2,0x0,0x0,0x0,0x1,0x0,0x0,0x0,0x2, 0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0, // :/icons/icon.png 0x0,0x0,0x0,0x10,0x0,0x0,0x0,0x0,0x0,0x1,0x0,0x0,0x0,0x0, 0x0,0x0,0x1,0x70,0x2d,0x52,0x8c,0x6f, }; #ifdef QT_NAMESPACE # define QT_RCC_PREPEND_NAMESPACE(name) ::QT_NAMESPACE::name # define QT_RCC_MANGLE_NAMESPACE0(x) x # define QT_RCC_MANGLE_NAMESPACE1(a, b) a##_##b # define QT_RCC_MANGLE_NAMESPACE2(a, b) QT_RCC_MANGLE_NAMESPACE1(a,b) # define QT_RCC_MANGLE_NAMESPACE(name) QT_RCC_MANGLE_NAMESPACE2( \ QT_RCC_MANGLE_NAMESPACE0(name), QT_RCC_MANGLE_NAMESPACE0(QT_NAMESPACE)) #else # define QT_RCC_PREPEND_NAMESPACE(name) name # define QT_RCC_MANGLE_NAMESPACE(name) name #endif #ifdef QT_NAMESPACE namespace QT_NAMESPACE { #endif bool qRegisterResourceData(int, const unsigned char *, const unsigned char *, const unsigned char *); bool qUnregisterResourceData(int, const unsigned char *, const unsigned char *, const unsigned char *); #ifdef QT_NAMESPACE } #endif int QT_RCC_MANGLE_NAMESPACE(qInitResources_myResources)(); int QT_RCC_MANGLE_NAMESPACE(qInitResources_myResources)() { int version = 3; QT_RCC_PREPEND_NAMESPACE(qRegisterResourceData) (version, qt_resource_struct, qt_resource_name, qt_resource_data); return 1; } int QT_RCC_MANGLE_NAMESPACE(qCleanupResources_myResources)(); int QT_RCC_MANGLE_NAMESPACE(qCleanupResources_myResources)() { int version = 3; QT_RCC_PREPEND_NAMESPACE(qUnregisterResourceData) (version, qt_resource_struct, qt_resource_name, qt_resource_data); return 1; } namespace { struct initializer { initializer() { QT_RCC_MANGLE_NAMESPACE(qInitResources_myResources)(); } ~initializer() { QT_RCC_MANGLE_NAMESPACE(qCleanupResources_myResources)(); } } dummy; }
[ "alextek2010@gmail.com" ]
alextek2010@gmail.com
bd44d52c17c6dea63cf7e1f47885527b78f67c3e
64670663c35bd63f578ec68b2f9c223c72a03b50
/Sudoku/Sudoku.h
aa1394bdffa5ce33fcfc53a9d8ca0d3325e2758d
[]
no_license
wchan614/sudokuSolver
bb6e4443a0027ca0f73021fb416f442d656220dd
51257f52a27484bde26c9f8fb12519b1c6efe524
refs/heads/main
2023-07-14T01:42:25.282791
2021-08-25T12:07:19
2021-08-25T12:07:19
398,054,361
0
0
null
null
null
null
UTF-8
C++
false
false
1,014
h
#ifndef SUDOKU_H #define SUDOKU_H #include <vector> #include <unordered_map> #include <utility> #include <set> class Sudoku { public: int numVarAssign; int ** grid; // [9][9] std::set<std::pair<int,int>> unassignedSet; std::unordered_map<std::pair<int,int>, std::vector<int>> fcTable; Sudoku(int** grid); void solve(); void display(); private: // need set variable // need to do unassigned, unassignedSet, unassignedMap, fcTable void constructTable(); bool isLegalTable(); int tryUpdateTable(std::pair<int,int> pos, int value); void updateTable(std::pair<int,int> pos, int value); std::pair<int,int> getNextMCVar(); std::vector<int> getNextValue(std::pair<int,int> pos); bool canPlace(std::pair<int,int> pos, int value); void updateCell(std::pair<int,int> pos, int value); bool doneSolving(); bool backtrackSearch(); void revert(std::unordered_map<std::pair<int,int>, std::vector<int>> table, pair<int,int> pos); }; #endif
[ "williamchan614@outlook.com" ]
williamchan614@outlook.com
398386134d220c4707e99ac3803f903c7e7c6bbe
8dc84558f0058d90dfc4955e905dab1b22d12c08
/cc/layers/picture_layer_impl.cc
4c2b45831eeeb324f1f8018051a590c42819feea
[ "LicenseRef-scancode-unknown-license-reference", "BSD-3-Clause" ]
permissive
meniossin/src
42a95cc6c4a9c71d43d62bc4311224ca1fd61e03
44f73f7e76119e5ab415d4593ac66485e65d700a
refs/heads/master
2022-12-16T20:17:03.747113
2020-09-03T10:43:12
2020-09-03T10:43:12
263,710,168
1
0
BSD-3-Clause
2020-05-13T18:20:09
2020-05-13T18:20:08
null
UTF-8
C++
false
false
72,687
cc
// Copyright 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "cc/layers/picture_layer_impl.h" #include <stddef.h> #include <stdint.h> #include <algorithm> #include <cmath> #include <limits> #include <set> #include "base/sys_info.h" #include "base/metrics/histogram_macros.h" #include "base/time/time.h" #include "base/trace_event/trace_event_argument.h" #include "build/build_config.h" #include "cc/base/math_util.h" #include "cc/benchmarks/micro_benchmark_impl.h" #include "cc/debug/debug_colors.h" #include "cc/layers/append_quads_data.h" #include "cc/layers/solid_color_layer_impl.h" #include "cc/paint/display_item_list.h" #include "cc/tiles/tile_manager.h" #include "cc/tiles/tiling_set_raster_queue_all.h" #include "cc/trees/layer_tree_impl.h" #include "cc/trees/occlusion.h" #include "components/viz/common/frame_sinks/begin_frame_args.h" #include "components/viz/common/quads/debug_border_draw_quad.h" #include "components/viz/common/quads/picture_draw_quad.h" #include "components/viz/common/quads/solid_color_draw_quad.h" #include "components/viz/common/quads/tile_draw_quad.h" #include "components/viz/common/traced_value.h" #include "ui/gfx/geometry/quad_f.h" #include "ui/gfx/geometry/rect_conversions.h" #include "ui/gfx/geometry/size_conversions.h" namespace cc { namespace { // This must be > 1 as we multiply or divide by this to find a new raster // scale during pinch. const float kMaxScaleRatioDuringPinch = 2.0f; // When creating a new tiling during pinch, snap to an existing // tiling's scale if the desired scale is within this ratio. const float kSnapToExistingTilingRatio = 1.2f; // Even for really wide viewports, at some point GPU raster should use // less than 4 tiles to fill the viewport. This is set to 256 as a // sane minimum for now, but we might want to tune this for low-end. const int kMinHeightForGpuRasteredTile = 256; // When making odd-sized tiles, round them up to increase the chances // of using the same tile size. const int kTileRoundUp = 64; // Round GPU default tile sizes to a multiple of 32. This helps prevent // rounding errors during compositing. const int kGpuDefaultTileRoundUp = 32; // For performance reasons and to support compressed tile textures, tile // width and height should be an even multiple of 4 in size. const int kTileMinimalAlignment = 4; // Large contents scale can cause overflow issues. Cap the ideal contents scale // by this constant, since scales larger than this are usually not correct or // their scale doesn't matter as long as it's large. Content scales usually // closely match the default device-scale factor (so it's usually <= 5). See // Renderer4.IdealContentsScale UMA (deprecated) for distribution of content // scales. const float kMaxIdealContentsScale = 10000.f; // Intersect rects which may have right() and bottom() that overflow integer // boundaries. This code is similar to gfx::Rect::Intersect with the exception // that the types are promoted to int64_t when there is a chance of overflow. gfx::Rect SafeIntersectRects(const gfx::Rect& one, const gfx::Rect& two) { if (one.IsEmpty() || two.IsEmpty()) return gfx::Rect(); int rx = std::max(one.x(), two.x()); int ry = std::max(one.y(), two.y()); int64_t rr = std::min(static_cast<int64_t>(one.x()) + one.width(), static_cast<int64_t>(two.x()) + two.width()); int64_t rb = std::min(static_cast<int64_t>(one.y()) + one.height(), static_cast<int64_t>(two.y()) + two.height()); if (rx > rr || ry > rb) return gfx::Rect(); return gfx::Rect(rx, ry, static_cast<int>(rr - rx), static_cast<int>(rb - ry)); } // This function converts the given |device_pixels_size| to the expected size // of content which was generated to fill it at 100%. This takes into account // the ceil operations that occur as device pixels are converted to/from DIPs // (content size must be a whole number of DIPs). gfx::Size ApplyDsfAdjustment(gfx::Size device_pixels_size, float dsf) { gfx::Size content_size_in_dips = gfx::ScaleToCeiledSize(device_pixels_size, 1.0f / dsf); gfx::Size content_size_in_dps = gfx::ScaleToCeiledSize(content_size_in_dips, dsf); return content_size_in_dps; } // For GPU rasterization, we pick an ideal tile size using the viewport so we // don't need any settings. The current approach uses 4 tiles to cover the // viewport vertically. gfx::Size CalculateGpuTileSize(const gfx::Size& base_tile_size, const gfx::Size& content_bounds, const gfx::Size& max_tile_size) { int tile_width = base_tile_size.width(); // Increase the height proportionally as the width decreases, and pad by our // border texels to make the tiles exactly match the viewport. int divisor = 4; if (content_bounds.width() <= base_tile_size.width() / 2) divisor = 2; if (content_bounds.width() <= base_tile_size.width() / 4) divisor = 1; int tile_height = MathUtil::UncheckedRoundUp(base_tile_size.height(), divisor) / divisor; // Grow default sizes to account for overlapping border texels. tile_width += 2 * PictureLayerTiling::kBorderTexels; tile_height += 2 * PictureLayerTiling::kBorderTexels; // Round GPU default tile sizes to a multiple of kGpuDefaultTileAlignment. // This helps prevent rounding errors in our CA path. https://crbug.com/632274 tile_width = MathUtil::UncheckedRoundUp(tile_width, kGpuDefaultTileRoundUp); tile_height = MathUtil::UncheckedRoundUp(tile_height, kGpuDefaultTileRoundUp); tile_height = std::max(tile_height, kMinHeightForGpuRasteredTile); if (!max_tile_size.IsEmpty()) { tile_width = std::min(tile_width, max_tile_size.width()); tile_height = std::min(tile_height, max_tile_size.height()); } return gfx::Size(tile_width, tile_height); } } // namespace PictureLayerImpl::PictureLayerImpl(LayerTreeImpl* tree_impl, int id, Layer::LayerMaskType mask_type) : LayerImpl(tree_impl, id), twin_layer_(nullptr), tilings_(CreatePictureLayerTilingSet()), ideal_page_scale_(0.f), ideal_device_scale_(0.f), ideal_source_scale_(0.f), ideal_contents_scale_(0.f), raster_page_scale_(0.f), raster_device_scale_(0.f), raster_source_scale_(0.f), raster_contents_scale_(0.f), low_res_raster_contents_scale_(0.f), mask_type_(mask_type), was_screen_space_transform_animating_(false), only_used_low_res_last_append_quads_(false), nearest_neighbor_(false), use_transformed_rasterization_(false), is_directly_composited_image_(false), can_use_lcd_text_(true) { layer_tree_impl()->RegisterPictureLayerImpl(this); } PictureLayerImpl::~PictureLayerImpl() { if (twin_layer_) twin_layer_->twin_layer_ = nullptr; layer_tree_impl()->UnregisterPictureLayerImpl(this); // Unregister for all images on the current raster source. UnregisterAnimatedImages(); } void PictureLayerImpl::SetLayerMaskType(Layer::LayerMaskType mask_type) { if (mask_type_ == mask_type) return; // It is expected that a layer can never change from being a mask to not being // one and vice versa. Only changes that make mask layer single <-> multi are // expected. DCHECK(mask_type_ != Layer::LayerMaskType::NOT_MASK && mask_type != Layer::LayerMaskType::NOT_MASK); mask_type_ = mask_type; } const char* PictureLayerImpl::LayerTypeAsString() const { return "cc::PictureLayerImpl"; } std::unique_ptr<LayerImpl> PictureLayerImpl::CreateLayerImpl( LayerTreeImpl* tree_impl) { return PictureLayerImpl::Create(tree_impl, id(), mask_type()); } void PictureLayerImpl::PushPropertiesTo(LayerImpl* base_layer) { PictureLayerImpl* layer_impl = static_cast<PictureLayerImpl*>(base_layer); LayerImpl::PushPropertiesTo(base_layer); layer_impl->SetLayerMaskType(mask_type()); // Twin relationships should never change once established. DCHECK(!twin_layer_ || twin_layer_ == layer_impl); DCHECK(!twin_layer_ || layer_impl->twin_layer_ == this); // The twin relationship does not need to exist before the first // PushPropertiesTo from pending to active layer since before that the active // layer can not have a pile or tilings, it has only been created and inserted // into the tree at that point. twin_layer_ = layer_impl; layer_impl->twin_layer_ = this; layer_impl->SetNearestNeighbor(nearest_neighbor_); layer_impl->SetUseTransformedRasterization(use_transformed_rasterization_); // Solid color layers have no tilings. DCHECK(!raster_source_->IsSolidColor() || tilings_->num_tilings() == 0); // The pending tree should only have a high res (and possibly low res) tiling. DCHECK_LE(tilings_->num_tilings(), layer_tree_impl()->create_low_res_tiling() ? 2u : 1u); layer_impl->set_gpu_raster_max_texture_size(gpu_raster_max_texture_size_); layer_impl->UpdateRasterSource(raster_source_, &invalidation_, tilings_.get()); DCHECK(invalidation_.IsEmpty()); // After syncing a solid color layer, the active layer has no tilings. DCHECK(!raster_source_->IsSolidColor() || layer_impl->tilings_->num_tilings() == 0); layer_impl->raster_page_scale_ = raster_page_scale_; layer_impl->raster_device_scale_ = raster_device_scale_; layer_impl->raster_source_scale_ = raster_source_scale_; layer_impl->raster_contents_scale_ = raster_contents_scale_; layer_impl->low_res_raster_contents_scale_ = low_res_raster_contents_scale_; layer_impl->is_directly_composited_image_ = is_directly_composited_image_; // Simply push the value to the active tree without any extra invalidations, // since the pending tree tiles would have this handled. This is here to // ensure the state is consistent for future raster. layer_impl->can_use_lcd_text_ = can_use_lcd_text_; layer_impl->SanityCheckTilingState(); // We always need to push properties. // See http://crbug.com/303943 // TODO(danakj): Stop always pushing properties since we don't swap tilings. layer_tree_impl()->AddLayerShouldPushProperties(this); } void PictureLayerImpl::AppendQuads(viz::RenderPass* render_pass, AppendQuadsData* append_quads_data) { // The bounds and the pile size may differ if the pile wasn't updated (ie. // PictureLayer::Update didn't happen). In that case the pile will be empty. DCHECK(raster_source_->GetSize().IsEmpty() || bounds() == raster_source_->GetSize()) << " bounds " << bounds().ToString() << " pile " << raster_source_->GetSize().ToString(); viz::SharedQuadState* shared_quad_state = render_pass->CreateAndAppendSharedQuadState(); if (raster_source_->IsSolidColor()) { // TODO(sunxd): Solid color non-mask layers are forced to have contents // scale = 1. This is a workaround to temperarily fix // https://crbug.com/796558. // We need to investigate into the ca layers logic and remove this // workaround after fixing the bug. float max_contents_scale = !(mask_type_ == Layer::LayerMaskType::MULTI_TEXTURE_MASK) ? 1 : CanHaveTilings() ? ideal_contents_scale_ : std::min(kMaxIdealContentsScale, std::max(GetIdealContentsScale(), MinimumContentsScale())); // The downstream CA layers use shared_quad_state to generate resources of // the right size even if it is a solid color picture layer. PopulateScaledSharedQuadState(shared_quad_state, max_contents_scale, max_contents_scale, contents_opaque()); AppendDebugBorderQuad(render_pass, gfx::Rect(bounds()), shared_quad_state, append_quads_data); gfx::Rect scaled_visible_layer_rect = shared_quad_state->visible_quad_layer_rect; Occlusion occlusion; // TODO(sunxd): Compute the correct occlusion for mask layers. if (mask_type_ == Layer::LayerMaskType::NOT_MASK) { occlusion = draw_properties().occlusion_in_content_space; } SolidColorLayerImpl::AppendSolidQuads( render_pass, occlusion, shared_quad_state, scaled_visible_layer_rect, raster_source_->GetSolidColor(), !layer_tree_impl()->settings().enable_edge_anti_aliasing, append_quads_data); return; } float device_scale_factor = layer_tree_impl()->device_scale_factor(); float max_contents_scale = MaximumTilingContentsScale(); PopulateScaledSharedQuadState(shared_quad_state, max_contents_scale, max_contents_scale, contents_opaque()); Occlusion scaled_occlusion; if (mask_type_ == Layer::LayerMaskType::NOT_MASK) { scaled_occlusion = draw_properties() .occlusion_in_content_space.GetOcclusionWithGivenDrawTransform( shared_quad_state->quad_to_target_transform); } if (current_draw_mode_ == DRAW_MODE_RESOURCELESS_SOFTWARE) { DCHECK(shared_quad_state->quad_layer_rect.origin() == gfx::Point(0, 0)); AppendDebugBorderQuad( render_pass, shared_quad_state->quad_layer_rect, shared_quad_state, append_quads_data, DebugColors::DirectPictureBorderColor(), DebugColors::DirectPictureBorderWidth(device_scale_factor)); gfx::Rect geometry_rect = shared_quad_state->visible_quad_layer_rect; gfx::Rect visible_geometry_rect = scaled_occlusion.GetUnoccludedContentRect(geometry_rect); bool needs_blending = !contents_opaque(); // The raster source may not be valid over the entire visible rect, // and rastering outside of that may cause incorrect pixels. gfx::Rect scaled_recorded_viewport = gfx::ScaleToEnclosingRect( raster_source_->RecordedViewport(), max_contents_scale); geometry_rect.Intersect(scaled_recorded_viewport); visible_geometry_rect.Intersect(scaled_recorded_viewport); if (visible_geometry_rect.IsEmpty()) return; DCHECK(raster_source_->HasRecordings()); gfx::Rect quad_content_rect = shared_quad_state->visible_quad_layer_rect; gfx::Size texture_size = quad_content_rect.size(); gfx::RectF texture_rect = gfx::RectF(gfx::SizeF(texture_size)); auto* quad = render_pass->CreateAndAppendDrawQuad<viz::PictureDrawQuad>(); quad->SetNew(shared_quad_state, geometry_rect, visible_geometry_rect, needs_blending, texture_rect, texture_size, nearest_neighbor_, viz::RGBA_8888, quad_content_rect, max_contents_scale, raster_source_->GetDisplayItemList()); ValidateQuadResources(quad); return; } // If we're doing a regular AppendQuads (ie, not solid color or resourceless // software draw, and if the visible rect is scrolled far enough away, then we // may run into a floating point precision in AA calculations in the renderer. // See crbug.com/765297. In order to avoid this, we shift the quads up from // where they logically reside and adjust the shared_quad_state's transform // instead. We only do this in a scale/translate matrices to ensure the math // is correct. gfx::Vector2d quad_offset; if (shared_quad_state->quad_to_target_transform.IsScaleOrTranslation()) { const auto& visible_rect = shared_quad_state->visible_quad_layer_rect; quad_offset = gfx::Vector2d(-visible_rect.x(), -visible_rect.y()); } gfx::Rect debug_border_rect(shared_quad_state->quad_layer_rect); debug_border_rect.Offset(quad_offset); AppendDebugBorderQuad(render_pass, debug_border_rect, shared_quad_state, append_quads_data); if (ShowDebugBorders(DebugBorderType::LAYER)) { for (PictureLayerTilingSet::CoverageIterator iter( tilings_.get(), max_contents_scale, shared_quad_state->visible_quad_layer_rect, ideal_contents_scale_); iter; ++iter) { SkColor color; float width; if (*iter && iter->draw_info().IsReadyToDraw()) { TileDrawInfo::Mode mode = iter->draw_info().mode(); if (mode == TileDrawInfo::SOLID_COLOR_MODE) { color = DebugColors::SolidColorTileBorderColor(); width = DebugColors::SolidColorTileBorderWidth(device_scale_factor); } else if (mode == TileDrawInfo::OOM_MODE) { color = DebugColors::OOMTileBorderColor(); width = DebugColors::OOMTileBorderWidth(device_scale_factor); } else if (iter->draw_info().has_compressed_resource()) { color = DebugColors::CompressedTileBorderColor(); width = DebugColors::CompressedTileBorderWidth(device_scale_factor); } else if (iter.resolution() == HIGH_RESOLUTION) { color = DebugColors::HighResTileBorderColor(); width = DebugColors::HighResTileBorderWidth(device_scale_factor); } else if (iter.resolution() == LOW_RESOLUTION) { color = DebugColors::LowResTileBorderColor(); width = DebugColors::LowResTileBorderWidth(device_scale_factor); } else if (iter->contents_scale_key() > max_contents_scale) { color = DebugColors::ExtraHighResTileBorderColor(); width = DebugColors::ExtraHighResTileBorderWidth(device_scale_factor); } else { color = DebugColors::ExtraLowResTileBorderColor(); width = DebugColors::ExtraLowResTileBorderWidth(device_scale_factor); } } else { color = DebugColors::MissingTileBorderColor(); width = DebugColors::MissingTileBorderWidth(device_scale_factor); } auto* debug_border_quad = render_pass->CreateAndAppendDrawQuad<viz::DebugBorderDrawQuad>(); gfx::Rect geometry_rect = iter.geometry_rect(); geometry_rect.Offset(quad_offset); gfx::Rect visible_geometry_rect = geometry_rect; debug_border_quad->SetNew(shared_quad_state, geometry_rect, visible_geometry_rect, color, width); } } // Keep track of the tilings that were used so that tilings that are // unused can be considered for removal. last_append_quads_tilings_.clear(); // Ignore missing tiles outside of viewport for tile priority. This is // normally the same as draw viewport but can be independently overridden by // embedders like Android WebView with SetExternalTilePriorityConstraints. gfx::Rect scaled_viewport_for_tile_priority = gfx::ScaleToEnclosingRect( viewport_rect_for_tile_priority_in_content_space_, max_contents_scale); size_t missing_tile_count = 0u; size_t on_demand_missing_tile_count = 0u; only_used_low_res_last_append_quads_ = true; gfx::Rect scaled_recorded_viewport = gfx::ScaleToEnclosingRect( raster_source_->RecordedViewport(), max_contents_scale); for (PictureLayerTilingSet::CoverageIterator iter( tilings_.get(), max_contents_scale, shared_quad_state->visible_quad_layer_rect, ideal_contents_scale_); iter; ++iter) { gfx::Rect geometry_rect = iter.geometry_rect(); gfx::Rect visible_geometry_rect = scaled_occlusion.GetUnoccludedContentRect(geometry_rect); gfx::Rect offset_geometry_rect = geometry_rect; offset_geometry_rect.Offset(quad_offset); gfx::Rect offset_visible_geometry_rect = visible_geometry_rect; offset_visible_geometry_rect.Offset(quad_offset); bool needs_blending = !contents_opaque(); if (visible_geometry_rect.IsEmpty()) continue; int64_t visible_geometry_area = static_cast<int64_t>(visible_geometry_rect.width()) * visible_geometry_rect.height(); append_quads_data->visible_layer_area += visible_geometry_area; bool has_draw_quad = false; if (*iter && iter->draw_info().IsReadyToDraw()) { const TileDrawInfo& draw_info = iter->draw_info(); switch (draw_info.mode()) { case TileDrawInfo::RESOURCE_MODE: { gfx::RectF texture_rect = iter.texture_rect(); // The raster_contents_scale_ is the best scale that the layer is // trying to produce, even though it may not be ideal. Since that's // the best the layer can promise in the future, consider those as // complete. But if a tile is ideal scale, we don't want to consider // it incomplete and trying to replace it with a tile at a worse // scale. if (iter->contents_scale_key() != raster_contents_scale_ && iter->contents_scale_key() != ideal_contents_scale_ && geometry_rect.Intersects(scaled_viewport_for_tile_priority)) { append_quads_data->num_incomplete_tiles++; } auto* quad = render_pass->CreateAndAppendDrawQuad<viz::TileDrawQuad>(); quad->SetNew( shared_quad_state, offset_geometry_rect, offset_visible_geometry_rect, needs_blending, draw_info.resource_id_for_export(), texture_rect, draw_info.resource_size(), draw_info.contents_swizzled(), draw_info.is_premultiplied(), nearest_neighbor_, !layer_tree_impl()->settings().enable_edge_anti_aliasing); ValidateQuadResources(quad); has_draw_quad = true; break; } case TileDrawInfo::SOLID_COLOR_MODE: { float alpha = (SkColorGetA(draw_info.solid_color()) * (1.0f / 255.0f)) * shared_quad_state->opacity; if (mask_type_ == Layer::LayerMaskType::MULTI_TEXTURE_MASK || alpha >= std::numeric_limits<float>::epsilon()) { auto* quad = render_pass->CreateAndAppendDrawQuad<viz::SolidColorDrawQuad>(); quad->SetNew( shared_quad_state, offset_geometry_rect, offset_visible_geometry_rect, draw_info.solid_color(), !layer_tree_impl()->settings().enable_edge_anti_aliasing); ValidateQuadResources(quad); } has_draw_quad = true; break; } case TileDrawInfo::OOM_MODE: break; // Checkerboard. } } if (!has_draw_quad) { // Checkerboard. SkColor color = SafeOpaqueBackgroundColor(); if (ShowDebugBorders(DebugBorderType::LAYER)) { // Fill the whole tile with the missing tile color. color = DebugColors::OOMTileBorderColor(); } auto* quad = render_pass->CreateAndAppendDrawQuad<viz::SolidColorDrawQuad>(); quad->SetNew(shared_quad_state, offset_geometry_rect, offset_visible_geometry_rect, color, false); ValidateQuadResources(quad); if (geometry_rect.Intersects(scaled_viewport_for_tile_priority)) { append_quads_data->num_missing_tiles++; ++missing_tile_count; } append_quads_data->checkerboarded_visible_content_area += visible_geometry_area; // Intersect checkerboard rect with interest rect to generate rect where // we checkerboarded and has recording. The area where we don't have // recording is not necessarily a Rect, and its area is calculated using // subtraction. gfx::Rect visible_rect_has_recording = visible_geometry_rect; visible_rect_has_recording.Intersect(scaled_recorded_viewport); int64_t checkerboarded_has_recording_area = static_cast<int64_t>(visible_rect_has_recording.width()) * visible_rect_has_recording.height(); append_quads_data->checkerboarded_needs_raster_content_area += checkerboarded_has_recording_area; append_quads_data->checkerboarded_no_recording_content_area += visible_geometry_area - checkerboarded_has_recording_area; continue; } if (iter.resolution() != HIGH_RESOLUTION) { append_quads_data->approximated_visible_content_area += visible_geometry_area; } // If we have a draw quad, but it's not low resolution, then // mark that we've used something other than low res to draw. if (iter.resolution() != LOW_RESOLUTION) only_used_low_res_last_append_quads_ = false; if (last_append_quads_tilings_.empty() || last_append_quads_tilings_.back() != iter.CurrentTiling()) { last_append_quads_tilings_.push_back(iter.CurrentTiling()); } } // Adjust shared_quad_state with the quad_offset, since we've adjusted each // quad we've appended by it. shared_quad_state->quad_to_target_transform.Translate(-quad_offset); shared_quad_state->quad_layer_rect.Offset(quad_offset); shared_quad_state->visible_quad_layer_rect.Offset(quad_offset); if (missing_tile_count) { TRACE_EVENT_INSTANT2("cc", "PictureLayerImpl::AppendQuads checkerboard", TRACE_EVENT_SCOPE_THREAD, "missing_tile_count", missing_tile_count, "on_demand_missing_tile_count", on_demand_missing_tile_count); } // Aggressively remove any tilings that are not seen to save memory. Note // that this is at the expense of doing cause more frequent re-painting. A // better scheme would be to maintain a tighter visible_layer_rect for the // finer tilings. CleanUpTilingsOnActiveLayer(last_append_quads_tilings_); } bool PictureLayerImpl::UpdateTiles() { if (!CanHaveTilings()) { ideal_page_scale_ = 0.f; ideal_device_scale_ = 0.f; ideal_contents_scale_ = 0.f; ideal_source_scale_ = 0.f; SanityCheckTilingState(); return false; } // Remove any non-ideal tilings that were not used last time we generated // quads to save memory and processing time. Note that pending tree should // only have one or two tilings (high and low res), so only clean up the // active layer. This cleans it up here in case AppendQuads didn't run. // If it did run, this would not remove any additional tilings. if (layer_tree_impl()->IsActiveTree()) CleanUpTilingsOnActiveLayer(last_append_quads_tilings_); UpdateIdealScales(); if (!raster_contents_scale_ || ShouldAdjustRasterScale()) { RecalculateRasterScales(); AddTilingsForRasterScale(); } if (layer_tree_impl()->IsActiveTree()) AddLowResolutionTilingIfNeeded(); DCHECK(raster_page_scale_); DCHECK(raster_device_scale_); DCHECK(raster_source_scale_); DCHECK(raster_contents_scale_); DCHECK(low_res_raster_contents_scale_); was_screen_space_transform_animating_ = draw_properties().screen_space_transform_is_animating; double current_frame_time_in_seconds = (layer_tree_impl()->CurrentBeginFrameArgs().frame_time - base::TimeTicks()).InSecondsF(); UpdateViewportRectForTilePriorityInContentSpace(); // The tiling set can require tiles for activation any of the following // conditions are true: // - This layer produced a high-res or non-ideal-res tile last frame. // - We're in requires high res to draw mode. // - We're not in smoothness takes priority mode. // To put different, the tiling set can't require tiles for activation if // we're in smoothness mode and only used low-res or checkerboard to draw last // frame and we don't need high res to draw. // // The reason for this is that we should be able to activate sooner and get a // more up to date recording, so we don't run out of recording on the active // tree. // A layer must be a drawing layer for it to require tiles for activation. bool can_require_tiles_for_activation = false; if (contributes_to_drawn_render_surface()) { can_require_tiles_for_activation = !only_used_low_res_last_append_quads_ || RequiresHighResToDraw() || !layer_tree_impl()->SmoothnessTakesPriority(); } static const Occlusion kEmptyOcclusion; const Occlusion& occlusion_in_content_space = layer_tree_impl()->settings().use_occlusion_for_tile_prioritization ? draw_properties().occlusion_in_content_space : kEmptyOcclusion; // Pass |occlusion_in_content_space| for |occlusion_in_layer_space| since // they are the same space in picture layer, as contents scale is always 1. bool updated = tilings_->UpdateTilePriorities( viewport_rect_for_tile_priority_in_content_space_, ideal_contents_scale_, current_frame_time_in_seconds, occlusion_in_content_space, can_require_tiles_for_activation); return updated; } void PictureLayerImpl::UpdateViewportRectForTilePriorityInContentSpace() { // If visible_layer_rect() is empty or viewport_rect_for_tile_priority is // set to be different from the device viewport, try to inverse project the // viewport into layer space and use that. Otherwise just use // visible_layer_rect(). gfx::Rect visible_rect_in_content_space = visible_layer_rect(); gfx::Rect viewport_rect_for_tile_priority = layer_tree_impl()->ViewportRectForTilePriority(); if (visible_rect_in_content_space.IsEmpty() || layer_tree_impl()->DeviceViewport() != viewport_rect_for_tile_priority) { gfx::Transform view_to_layer(gfx::Transform::kSkipInitialization); if (ScreenSpaceTransform().GetInverse(&view_to_layer)) { // Transform from view space to content space. visible_rect_in_content_space = MathUtil::ProjectEnclosingClippedRect( view_to_layer, viewport_rect_for_tile_priority); // We have to allow for a viewport that is outside of the layer bounds in // order to compute tile priorities correctly for offscreen content that // is going to make it on screen. However, we also have to limit the // viewport since it can be very large due to screen_space_transforms. As // a heuristic, we clip to bounds padded by skewport_extrapolation_limit * // maximum tiling scale, since this should allow sufficient room for // skewport calculations. gfx::Rect padded_bounds(bounds()); int padding_amount = layer_tree_impl() ->settings() .skewport_extrapolation_limit_in_screen_pixels * MaximumTilingContentsScale(); padded_bounds.Inset(-padding_amount, -padding_amount); visible_rect_in_content_space = SafeIntersectRects(visible_rect_in_content_space, padded_bounds); } } if (layer_tree_impl()->TotalMaxScrollOffset().x() == 0) { if (visible_layer_rect().IsEmpty()) { gfx::Rect visible_rect_in_content = gfx::Rect(visible_rect_in_content_space); // Checking an intersection area on only horizontal level. // Set the y position to 0 for comparison. visible_rect_in_content.set_y(0); gfx::Rect layer_rect = gfx::Rect(bounds()); layer_rect.set_x((int) (position().x())); visible_rect_in_content.Intersect(layer_rect); if (visible_rect_in_content.IsEmpty()) { visible_rect_in_content_space.Intersect(visible_layer_rect()); } } } viewport_rect_for_tile_priority_in_content_space_ = visible_rect_in_content_space; #if defined(OS_ANDROID) // On android, if we're in a scrolling gesture, the pending tree does not // reflect the fact that we may be hiding the top or bottom controls. Thus, // it would believe that the viewport is smaller than it actually is which // can cause activation flickering issues. So, if we're in this situation // adjust the visible rect by the top/bottom controls height. This isn't // ideal since we're not always in this case, but since we should be // prioritizing the active tree anyway, it doesn't cause any serious issues. // https://crbug.com/794456. if (layer_tree_impl()->IsPendingTree() && layer_tree_impl()->IsActivelyScrolling()) { float total_controls_height = layer_tree_impl()->top_controls_height() + layer_tree_impl()->bottom_controls_height(); viewport_rect_for_tile_priority_in_content_space_.Inset( 0, // left 0, // top, 0, // right, -total_controls_height); // bottom } #endif } PictureLayerImpl* PictureLayerImpl::GetPendingOrActiveTwinLayer() const { if (!twin_layer_ || !twin_layer_->IsOnActiveOrPendingTree()) return nullptr; return twin_layer_; } void PictureLayerImpl::UpdateRasterSource( scoped_refptr<RasterSource> raster_source, Region* new_invalidation, const PictureLayerTilingSet* pending_set) { // The bounds and the pile size may differ if the pile wasn't updated (ie. // PictureLayer::Update didn't happen). In that case the pile will be empty. DCHECK(raster_source->GetSize().IsEmpty() || bounds() == raster_source->GetSize()) << " bounds " << bounds().ToString() << " pile " << raster_source->GetSize().ToString(); // We have an updated recording if the DisplayItemList in the new RasterSource // is different. const bool recording_updated = !raster_source_ || raster_source_->GetDisplayItemList() != raster_source->GetDisplayItemList(); // Unregister for all images on the current raster source, if the recording // was updated. if (recording_updated) UnregisterAnimatedImages(); // The |raster_source_| is initially null, so have to check for that for the // first frame. bool could_have_tilings = raster_source_.get() && CanHaveTilings(); raster_source_.swap(raster_source); // Register images from the new raster source, if the recording was updated. // TODO(khushalsagar): UMA the number of animated images in layer? if (recording_updated) RegisterAnimatedImages(); // The |new_invalidation| must be cleared before updating tilings since they // access the invalidation through the PictureLayerTilingClient interface. invalidation_.Clear(); invalidation_.Swap(new_invalidation); bool can_have_tilings = CanHaveTilings(); DCHECK(!pending_set || can_have_tilings == GetPendingOrActiveTwinLayer()->CanHaveTilings()); // Need to call UpdateTiles again if CanHaveTilings changed. if (could_have_tilings != can_have_tilings) layer_tree_impl()->set_needs_update_draw_properties(); if (!can_have_tilings) { RemoveAllTilings(); return; } // We could do this after doing UpdateTiles, which would avoid doing this for // tilings that are going to disappear on the pending tree (if scale changed). // But that would also be more complicated, so we just do it here for now. // // TODO(crbug.com/843787): If the LayerTreeFrameSink is lost, and we activate, // this ends up running with the old LayerTreeFrameSink, or possibly with a // null LayerTreeFrameSink, which can give incorrect results or maybe crash. if (pending_set) { tilings_->UpdateTilingsToCurrentRasterSourceForActivation( raster_source_, pending_set, invalidation_, MinimumContentsScale(), MaximumContentsScale()); } else { tilings_->UpdateTilingsToCurrentRasterSourceForCommit( raster_source_, invalidation_, MinimumContentsScale(), MaximumContentsScale()); // We're in a commit, make sure to update the state of the checker image // tracker with the new async attribute data. layer_tree_impl()->UpdateImageDecodingHints( raster_source_->TakeDecodingModeMap()); } } bool PictureLayerImpl::UpdateCanUseLCDTextAfterCommit() { DCHECK(layer_tree_impl()->IsSyncTree()); // Once we disable lcd text, we don't re-enable it. if (!can_use_lcd_text_) return false; if (can_use_lcd_text_ == CanUseLCDText()) return false; can_use_lcd_text_ = CanUseLCDText(); // Synthetically invalidate everything. gfx::Rect bounds_rect(bounds()); invalidation_ = Region(bounds_rect); tilings_->Invalidate(invalidation_); SetUpdateRect(bounds_rect); return true; } void PictureLayerImpl::NotifyTileStateChanged(const Tile* tile) { if (layer_tree_impl()->IsActiveTree()) AddDamageRect(tile->enclosing_layer_rect()); if (tile->draw_info().NeedsRaster()) { PictureLayerTiling* tiling = tilings_->FindTilingWithScaleKey(tile->contents_scale_key()); if (tiling) tiling->set_all_tiles_done(false); } } void PictureLayerImpl::DidBeginTracing() { raster_source_->DidBeginTracing(); } void PictureLayerImpl::ReleaseResources() { tilings_->ReleaseAllResources(); ResetRasterScale(); } void PictureLayerImpl::ReleaseTileResources() { // All resources are tile resources. ReleaseResources(); } void PictureLayerImpl::RecreateTileResources() { // Recreate tilings with new settings, since some of those might change when // we release resources. tilings_ = CreatePictureLayerTilingSet(); } Region PictureLayerImpl::GetInvalidationRegionForDebugging() { // |invalidation_| gives the invalidation contained in the source frame, but // is not cleared after drawing from the layer. However, update_rect() is // cleared once the invalidation is drawn, which is useful for debugging // visualizations. This method intersects the two to give a more exact // representation of what was invalidated that is cleared after drawing. return IntersectRegions(invalidation_, update_rect()); } std::unique_ptr<Tile> PictureLayerImpl::CreateTile( const Tile::CreateInfo& info) { int flags = 0; // We don't handle solid color masks if mask tiling is disabled, we also don't // handle solid color single texture masks if the flag is enabled, so we // shouldn't bother analyzing those. // Otherwise, always analyze to maximize memory savings. if (mask_type_ != Layer::LayerMaskType::SINGLE_TEXTURE_MASK) flags = Tile::USE_PICTURE_ANALYSIS; if (contents_opaque()) flags |= Tile::IS_OPAQUE; return layer_tree_impl()->tile_manager()->CreateTile( info, id(), layer_tree_impl()->source_frame_number(), flags, can_use_lcd_text_); } const Region* PictureLayerImpl::GetPendingInvalidation() { if (layer_tree_impl()->IsPendingTree()) return &invalidation_; if (layer_tree_impl()->IsRecycleTree()) return nullptr; DCHECK(layer_tree_impl()->IsActiveTree()); if (PictureLayerImpl* twin_layer = GetPendingOrActiveTwinLayer()) return &twin_layer->invalidation_; return nullptr; } const PictureLayerTiling* PictureLayerImpl::GetPendingOrActiveTwinTiling( const PictureLayerTiling* tiling) const { PictureLayerImpl* twin_layer = GetPendingOrActiveTwinLayer(); if (!twin_layer) return nullptr; const PictureLayerTiling* twin_tiling = twin_layer->tilings_->FindTilingWithScaleKey( tiling->contents_scale_key()); if (twin_tiling && twin_tiling->raster_transform() == tiling->raster_transform()) return twin_tiling; return nullptr; } bool PictureLayerImpl::RequiresHighResToDraw() const { return layer_tree_impl()->RequiresHighResToDraw(); } gfx::Rect PictureLayerImpl::GetEnclosingRectInTargetSpace() const { return GetScaledEnclosingRectInTargetSpace(MaximumTilingContentsScale()); } bool PictureLayerImpl::ShouldAnimate(PaintImage::Id paint_image_id) const { // If we are registered with the animation controller, which queries whether // the image should be animated, then we must have recordings with this image. DCHECK(raster_source_); DCHECK(raster_source_->GetDisplayItemList()); DCHECK( !raster_source_->GetDisplayItemList()->discardable_image_map().empty()); // Only animate images for layers which HasValidTilePriorities. This check is // important for 2 reasons: // 1) It avoids doing additional work for layers we don't plan to rasterize // and/or draw. The updated state will be pulled by the animation system // if the draw properties change. // 2) It eliminates considering layers on the recycle tree. Once the pending // tree is activated, the layers on the recycle tree remain registered as // animation drivers, but should not drive animations since they don't have // updated draw properties. // // Additionally only animate images which are on-screen, animations are // paused once they are not visible. if (!HasValidTilePriorities()) return false; const auto& rects = raster_source_->GetDisplayItemList() ->discardable_image_map() .GetRectsForImage(paint_image_id); for (const auto& r : rects.container()) { if (r.Intersects(visible_layer_rect())) return true; } return false; } gfx::Size PictureLayerImpl::CalculateTileSize( const gfx::Size& content_bounds) const { int max_texture_size = layer_tree_impl()->max_texture_size(); if (mask_type_ == Layer::LayerMaskType::SINGLE_TEXTURE_MASK) { // Masks are not tiled, so if we can't cover the whole mask with one tile, // we shouldn't have such a tiling at all. DCHECK_LE(content_bounds.width(), max_texture_size); DCHECK_LE(content_bounds.height(), max_texture_size); return content_bounds; } int default_tile_width = 0; int default_tile_height = 0; if (layer_tree_impl()->use_gpu_rasterization()) { gfx::Size max_tile_size = layer_tree_impl()->settings().max_gpu_raster_tile_size; // Calculate |base_tile_size based| on |gpu_raster_max_texture_size_|, // adjusting for ceil operations that may occur due to DSF. gfx::Size base_tile_size = ApplyDsfAdjustment( gpu_raster_max_texture_size_, layer_tree_impl()->device_scale_factor()); // Set our initial size assuming a |base_tile_size| equal to our // |viewport_size|. gfx::Size default_tile_size = CalculateGpuTileSize(base_tile_size, content_bounds, max_tile_size); // Use half-width GPU tiles when the content_width is greater than our // calculated tile size. if (content_bounds.width() > default_tile_size.width()) { // Divide width by 2 and round up. base_tile_size.set_width((base_tile_size.width() + 1) / 2); default_tile_size = CalculateGpuTileSize(base_tile_size, content_bounds, max_tile_size); } default_tile_width = default_tile_size.width(); default_tile_height = default_tile_size.height(); } else { // For CPU rasterization we use tile-size settings. const LayerTreeSettings& settings = layer_tree_impl()->settings(); int max_untiled_content_width = settings.max_untiled_layer_size.width(); int max_untiled_content_height = settings.max_untiled_layer_size.height(); default_tile_width = settings.default_tile_size.width(); default_tile_height = settings.default_tile_size.height(); // If the content width is small, increase tile size vertically. // If the content height is small, increase tile size horizontally. // If both are less than the untiled-size, use a single tile. if (content_bounds.width() < default_tile_width) default_tile_height = max_untiled_content_height; if (content_bounds.height() < default_tile_height) default_tile_width = max_untiled_content_width; if (content_bounds.width() < max_untiled_content_width && content_bounds.height() < max_untiled_content_height) { default_tile_height = max_untiled_content_height; default_tile_width = max_untiled_content_width; } } int tile_width = default_tile_width; int tile_height = default_tile_height; // Clamp the tile width/height to the content width/height to save space. if (content_bounds.width() < default_tile_width) { tile_width = std::min(tile_width, content_bounds.width()); tile_width = MathUtil::UncheckedRoundUp(tile_width, kTileRoundUp); tile_width = std::min(tile_width, default_tile_width); } if (content_bounds.height() < default_tile_height) { tile_height = std::min(tile_height, content_bounds.height()); tile_height = MathUtil::UncheckedRoundUp(tile_height, kTileRoundUp); tile_height = std::min(tile_height, default_tile_height); } // Ensure that tile width and height are properly aligned. tile_width = MathUtil::UncheckedRoundUp(tile_width, kTileMinimalAlignment); tile_height = MathUtil::UncheckedRoundUp(tile_height, kTileMinimalAlignment); // Under no circumstance should we be larger than the max texture size. tile_width = std::min(tile_width, max_texture_size); tile_height = std::min(tile_height, max_texture_size); return gfx::Size(tile_width, tile_height); } void PictureLayerImpl::GetContentsResourceId( viz::ResourceId* resource_id, gfx::Size* resource_size, gfx::SizeF* resource_uv_size) const { // The bounds and the pile size may differ if the pile wasn't updated (ie. // PictureLayer::Update didn't happen). In that case the pile will be empty. DCHECK(raster_source_->GetSize().IsEmpty() || bounds() == raster_source_->GetSize()) << " bounds " << bounds().ToString() << " pile " << raster_source_->GetSize().ToString(); float dest_scale = MaximumTilingContentsScale(); gfx::Rect content_rect = gfx::ScaleToEnclosingRect(gfx::Rect(bounds()), dest_scale); PictureLayerTilingSet::CoverageIterator iter( tilings_.get(), dest_scale, content_rect, ideal_contents_scale_); // Mask resource not ready yet. if (!iter || !*iter) { *resource_id = 0; return; } // Masks only supported if they fit on exactly one tile. DCHECK(iter.geometry_rect() == content_rect) << "iter rect " << iter.geometry_rect().ToString() << " content rect " << content_rect.ToString(); const TileDrawInfo& draw_info = iter->draw_info(); if (!draw_info.IsReadyToDraw() || draw_info.mode() != TileDrawInfo::RESOURCE_MODE) { *resource_id = 0; return; } *resource_id = draw_info.resource_id_for_export(); *resource_size = draw_info.resource_size(); // |resource_uv_size| represents the range of UV coordinates that map to the // content being drawn. Typically, we draw to the entire texture, so these // coordinates are (1.0f, 1.0f). However, if we are rasterizing to an // over-large texture, this size will be smaller, mapping to the subset of the // texture being used. gfx::SizeF requested_tile_size = gfx::SizeF(iter->tiling()->tiling_data()->tiling_size()); DCHECK_LE(requested_tile_size.width(), draw_info.resource_size().width()); DCHECK_LE(requested_tile_size.height(), draw_info.resource_size().height()); *resource_uv_size = gfx::SizeF( requested_tile_size.width() / draw_info.resource_size().width(), requested_tile_size.height() / draw_info.resource_size().height()); } void PictureLayerImpl::SetNearestNeighbor(bool nearest_neighbor) { if (nearest_neighbor_ == nearest_neighbor) return; nearest_neighbor_ = nearest_neighbor; NoteLayerPropertyChanged(); } void PictureLayerImpl::SetUseTransformedRasterization(bool use) { if (use_transformed_rasterization_ == use) return; use_transformed_rasterization_ = use; NoteLayerPropertyChanged(); } PictureLayerTiling* PictureLayerImpl::AddTiling( const gfx::AxisTransform2d& contents_transform) { DCHECK(CanHaveTilings()); DCHECK_GE(contents_transform.scale(), MinimumContentsScale()); DCHECK_LE(contents_transform.scale(), MaximumContentsScale()); DCHECK(raster_source_->HasRecordings()); return tilings_->AddTiling(contents_transform, raster_source_); } void PictureLayerImpl::RemoveAllTilings() { tilings_->RemoveAllTilings(); // If there are no tilings, then raster scales are no longer meaningful. ResetRasterScale(); } void PictureLayerImpl::AddTilingsForRasterScale() { // Reset all resolution enums on tilings, we'll be setting new values in this // function. tilings_->MarkAllTilingsNonIdeal(); PictureLayerTiling* high_res = tilings_->FindTilingWithScaleKey(raster_contents_scale_); // Note: This function is always invoked when raster scale is recomputed, // but not necessarily changed. This means raster translation update is also // always done when there are significant changes that triggered raster scale // recomputation. gfx::Vector2dF raster_translation = CalculateRasterTranslation(raster_contents_scale_); if (high_res && high_res->raster_transform().translation() != raster_translation) { tilings_->Remove(high_res); high_res = nullptr; } if (!high_res) { // We always need a high res tiling, so create one if it doesn't exist. high_res = AddTiling( gfx::AxisTransform2d(raster_contents_scale_, raster_translation)); } else if (high_res->may_contain_low_resolution_tiles()) { // If the tiling we find here was LOW_RESOLUTION previously, it may not be // fully rastered, so destroy the old tiles. high_res->Reset(); // Reset the flag now that we'll make it high res, it will have fully // rastered content. high_res->reset_may_contain_low_resolution_tiles(); } high_res->set_resolution(HIGH_RESOLUTION); if (layer_tree_impl()->IsPendingTree()) { // On the pending tree, drop any tilings that are non-ideal since we don't // need them to activate anyway. tilings_->RemoveNonIdealTilings(); } SanityCheckTilingState(); } bool PictureLayerImpl::ShouldAdjustRasterScale() const { if (is_directly_composited_image_) { float max_scale = std::max(1.f, MinimumContentsScale()); if (raster_source_scale_ < std::min(ideal_source_scale_, max_scale)) return true; if (raster_source_scale_ > 4 * ideal_source_scale_) return true; return false; } if (was_screen_space_transform_animating_ != draw_properties().screen_space_transform_is_animating) return true; bool is_pinching = layer_tree_impl()->PinchGestureActive(); bool is_scaling = layer_tree_impl()->PageScaleAnimationActive(); if ((is_pinching || is_scaling) && raster_page_scale_) { #if defined(S_TERRACE_SUPPORT) // Don't adjust raster scale during pinch-in for zoom performance(FPS). // This is same concept with SBrowser5.x. However, // as default return value of this function is changed to true from false // on opensource, we should return false in here. if (ideal_page_scale_ > raster_page_scale_) return false; #endif // We change our raster scale when it is: // - Higher than ideal (need a lower-res tiling available) // - Too far from ideal (need a higher-res tiling available) if (raster_page_scale_ > ideal_page_scale_) return true; #if !defined(OS_ANDROID) float ratio = ideal_page_scale_ / raster_page_scale_; if (ratio > kMaxScaleRatioDuringPinch) return true; #endif } if (!is_pinching) { // When not pinching, match the ideal page scale factor. if (raster_page_scale_ != ideal_page_scale_) return true; } // Always match the ideal device scale factor. if (raster_device_scale_ != ideal_device_scale_) return true; if (raster_contents_scale_ > MaximumContentsScale()) return true; if (raster_contents_scale_ < MinimumContentsScale()) return true; // Don't change the raster scale if any of the following are true: // - We have an animating transform. // - The raster scale is already ideal. if (draw_properties().screen_space_transform_is_animating || raster_source_scale_ == ideal_source_scale_) { return false; } // Don't update will-change: transform layers if the raster contents scale is // at least the native scale (otherwise, we'd need to clamp it). if (has_will_change_transform_hint() && raster_contents_scale_ >= raster_page_scale_ * raster_device_scale_) { return false; } // Match the raster scale in all other cases. return true; } void PictureLayerImpl::AddLowResolutionTilingIfNeeded() { DCHECK(layer_tree_impl()->IsActiveTree()); if (!layer_tree_impl()->create_low_res_tiling()) return; // We should have a high resolution tiling at raster_contents_scale, so if the // low res one is the same then we shouldn't try to override this tiling by // marking it as a low res. if (raster_contents_scale_ == low_res_raster_contents_scale_) return; PictureLayerTiling* low_res = tilings_->FindTilingWithScaleKey(low_res_raster_contents_scale_); DCHECK(!low_res || low_res->resolution() != HIGH_RESOLUTION); // Only create new low res tilings when the transform is static. This // prevents wastefully creating a paired low res tiling for every new high // res tiling during a pinch or a CSS animation. bool is_pinching = layer_tree_impl()->PinchGestureActive(); bool is_animating = draw_properties().screen_space_transform_is_animating; bool is_scaling = layer_tree_impl()->PageScaleAnimationActive(); if (!is_pinching && !is_animating && !is_scaling) { if (!low_res) low_res = AddTiling(gfx::AxisTransform2d(low_res_raster_contents_scale_, gfx::Vector2dF())); low_res->set_resolution(LOW_RESOLUTION); } } void PictureLayerImpl::RecalculateRasterScales() { if (is_directly_composited_image_) { if (!raster_source_scale_) raster_source_scale_ = 1.f; float min_scale = MinimumContentsScale(); float max_scale = std::max(1.f, MinimumContentsScale()); float clamped_ideal_source_scale_ = std::max(min_scale, std::min(ideal_source_scale_, max_scale)); while (raster_source_scale_ < clamped_ideal_source_scale_) raster_source_scale_ *= 2.f; while (raster_source_scale_ > 4 * clamped_ideal_source_scale_) raster_source_scale_ /= 2.f; raster_source_scale_ = std::max(min_scale, std::min(raster_source_scale_, max_scale)); raster_page_scale_ = 1.f; raster_device_scale_ = 1.f; raster_contents_scale_ = raster_source_scale_; low_res_raster_contents_scale_ = raster_contents_scale_; return; } float old_raster_contents_scale = raster_contents_scale_; float old_raster_page_scale = raster_page_scale_; raster_device_scale_ = ideal_device_scale_; raster_page_scale_ = ideal_page_scale_; raster_source_scale_ = ideal_source_scale_; raster_contents_scale_ = ideal_contents_scale_; // During pinch we completely ignore the current ideal scale, and just use // a multiple of the previous scale. bool is_pinching = layer_tree_impl()->PinchGestureActive(); bool is_scaling = layer_tree_impl()->PageScaleAnimationActive(); if ((is_pinching || is_scaling) && old_raster_contents_scale) { // See ShouldAdjustRasterScale: // - When zooming out, preemptively create new tiling at lower resolution. // - When zooming in, approximate ideal using multiple of kMaxScaleRatio. bool zooming_out = old_raster_page_scale > ideal_page_scale_; float desired_contents_scale = old_raster_contents_scale; if (zooming_out) { while (desired_contents_scale > ideal_contents_scale_) desired_contents_scale /= kMaxScaleRatioDuringPinch; } else { while (desired_contents_scale < ideal_contents_scale_) desired_contents_scale *= kMaxScaleRatioDuringPinch; } raster_contents_scale_ = tilings_->GetSnappedContentsScaleKey( desired_contents_scale, kSnapToExistingTilingRatio); raster_page_scale_ = raster_contents_scale_ / raster_device_scale_ / raster_source_scale_; } // We rasterize at the maximum scale that will occur during the animation, if // the maximum scale is known. However we want to avoid excessive memory use. // If the scale is smaller than what we would choose otherwise, then it's // always better off for us memory-wise. But otherwise, we don't choose a // scale at which this layer's rastered content would become larger than the // viewport. if (draw_properties().screen_space_transform_is_animating) { bool can_raster_at_maximum_scale = false; bool should_raster_at_starting_scale = false; CombinedAnimationScale animation_scales = layer_tree_impl()->property_trees()->GetAnimationScales( transform_tree_index(), layer_tree_impl()); float maximum_scale = animation_scales.maximum_animation_scale; float starting_scale = animation_scales.starting_animation_scale; if (maximum_scale) { gfx::Size bounds_at_maximum_scale = gfx::ScaleToCeiledSize(raster_source_->GetSize(), maximum_scale); int64_t maximum_area = static_cast<int64_t>(bounds_at_maximum_scale.width()) * static_cast<int64_t>(bounds_at_maximum_scale.height()); gfx::Size viewport = layer_tree_impl()->device_viewport_size(); // Use the square of the maximum viewport dimension direction, to // compensate for viewports with different aspect ratios. int64_t max_viewport_dimension = std::max(static_cast<int64_t>(viewport.width()), static_cast<int64_t>(viewport.height())); int64_t squared_viewport_area = max_viewport_dimension * max_viewport_dimension; if (maximum_area <= squared_viewport_area) can_raster_at_maximum_scale = true; } if (starting_scale && starting_scale > maximum_scale) { gfx::Size bounds_at_starting_scale = gfx::ScaleToCeiledSize(raster_source_->GetSize(), starting_scale); int64_t start_area = static_cast<int64_t>(bounds_at_starting_scale.width()) * static_cast<int64_t>(bounds_at_starting_scale.height()); gfx::Size viewport = layer_tree_impl()->device_viewport_size(); int64_t viewport_area = static_cast<int64_t>(viewport.width()) * static_cast<int64_t>(viewport.height()); if (start_area <= viewport_area) should_raster_at_starting_scale = true; } // Use the computed scales for the raster scale directly, do not try to use // the ideal scale here. The current ideal scale may be way too large in the // case of an animation with scale, and will be constantly changing. if (should_raster_at_starting_scale) raster_contents_scale_ = starting_scale; else if (can_raster_at_maximum_scale) raster_contents_scale_ = maximum_scale; else raster_contents_scale_ = 1.f * ideal_page_scale_ * ideal_device_scale_; } // Clamp will-change: transform layers to be at least the native scale. if (has_will_change_transform_hint()) { float min_desired_scale = raster_device_scale_ * raster_page_scale_; if (raster_contents_scale_ < min_desired_scale) { raster_contents_scale_ = min_desired_scale; raster_page_scale_ = 1.f; } } raster_contents_scale_ = std::max(raster_contents_scale_, MinimumContentsScale()); raster_contents_scale_ = std::min(raster_contents_scale_, MaximumContentsScale()); DCHECK_GE(raster_contents_scale_, MinimumContentsScale()); DCHECK_LE(raster_contents_scale_, MaximumContentsScale()); // If this layer would create zero or one tiles at this content scale, // don't create a low res tiling. gfx::Size raster_bounds = gfx::ScaleToCeiledSize(raster_source_->GetSize(), raster_contents_scale_); gfx::Size tile_size = CalculateTileSize(raster_bounds); bool tile_covers_bounds = tile_size.width() >= raster_bounds.width() && tile_size.height() >= raster_bounds.height(); if (tile_size.IsEmpty() || tile_covers_bounds) { low_res_raster_contents_scale_ = raster_contents_scale_; return; } float low_res_factor = layer_tree_impl()->settings().low_res_contents_scale_factor; low_res_raster_contents_scale_ = std::max(raster_contents_scale_ * low_res_factor, MinimumContentsScale()); DCHECK_LE(low_res_raster_contents_scale_, raster_contents_scale_); DCHECK_GE(low_res_raster_contents_scale_, MinimumContentsScale()); DCHECK_LE(low_res_raster_contents_scale_, MaximumContentsScale()); } void PictureLayerImpl::CleanUpTilingsOnActiveLayer( const std::vector<PictureLayerTiling*>& used_tilings) { DCHECK(layer_tree_impl()->IsActiveTree()); if (tilings_->num_tilings() == 0) return; float min_acceptable_high_res_scale = std::min( raster_contents_scale_, ideal_contents_scale_); float max_acceptable_high_res_scale = std::max( raster_contents_scale_, ideal_contents_scale_); PictureLayerImpl* twin = GetPendingOrActiveTwinLayer(); if (twin && twin->CanHaveTilings()) { min_acceptable_high_res_scale = std::min( min_acceptable_high_res_scale, std::min(twin->raster_contents_scale_, twin->ideal_contents_scale_)); max_acceptable_high_res_scale = std::max( max_acceptable_high_res_scale, std::max(twin->raster_contents_scale_, twin->ideal_contents_scale_)); } PictureLayerTilingSet* twin_set = twin ? twin->tilings_.get() : nullptr; tilings_->CleanUpTilings(min_acceptable_high_res_scale, max_acceptable_high_res_scale, used_tilings, twin_set); DCHECK_GT(tilings_->num_tilings(), 0u); SanityCheckTilingState(); } gfx::Vector2dF PictureLayerImpl::CalculateRasterTranslation( float raster_scale) { if (!use_transformed_rasterization_) return gfx::Vector2dF(); DCHECK(!draw_properties().screen_space_transform_is_animating); gfx::Transform draw_transform = DrawTransform(); DCHECK(draw_transform.IsScaleOrTranslation()); // It is only useful to align the content space to the target space if their // relative pixel ratio is some small rational number. Currently we only // align if the relative pixel ratio is 1:1. // Good match if the maximum alignment error on a layer of size 10000px // does not exceed 0.001px. static constexpr float kErrorThreshold = 0.0000001f; if (std::abs(draw_transform.matrix().getFloat(0, 0) - raster_scale) > kErrorThreshold || std::abs(draw_transform.matrix().getFloat(1, 1) - raster_scale) > kErrorThreshold) return gfx::Vector2dF(); // Extract the fractional part of layer origin in the target space. float origin_x = draw_transform.matrix().getFloat(0, 3); float origin_y = draw_transform.matrix().getFloat(1, 3); return gfx::Vector2dF(origin_x - floorf(origin_x), origin_y - floorf(origin_y)); } float PictureLayerImpl::MinimumContentsScale() const { float setting_min = layer_tree_impl()->settings().minimum_contents_scale; // If the contents scale is less than 1 / width (also for height), // then it will end up having less than one pixel of content in that // dimension. Bump the minimum contents scale up in this case to prevent // this from happening. int min_dimension = std::min(raster_source_->GetSize().width(), raster_source_->GetSize().height()); if (!min_dimension) return setting_min; return std::max(1.f / min_dimension, setting_min); } float PictureLayerImpl::MaximumContentsScale() const { // When mask tiling is disabled or the mask is single textured, masks can not // have tilings that would become larger than the max_texture_size since they // use a single tile for the entire tiling. Other layers can have tilings such // that dimension * scale does not overflow. float max_dimension = static_cast<float>(mask_type_ == Layer::LayerMaskType::SINGLE_TEXTURE_MASK ? layer_tree_impl()->max_texture_size() : std::numeric_limits<int>::max()); float max_scale_width = max_dimension / bounds().width(); float max_scale_height = max_dimension / bounds().height(); float max_scale = std::min(max_scale_width, max_scale_height); // We require that multiplying the layer size by the contents scale and // ceiling produces a value <= |max_dimension|. Because for large layer // sizes floating point ambiguity may crop up, making the result larger or // smaller than expected, we use a slightly smaller floating point value for // the scale, to help ensure that the resulting content bounds will never end // up larger than |max_dimension|. return nextafterf(max_scale, 0.f); } void PictureLayerImpl::ResetRasterScale() { raster_page_scale_ = 0.f; raster_device_scale_ = 0.f; raster_source_scale_ = 0.f; raster_contents_scale_ = 0.f; low_res_raster_contents_scale_ = 0.f; } bool PictureLayerImpl::CanHaveTilings() const { if (raster_source_->IsSolidColor()) return false; if (!DrawsContent()) return false; if (!raster_source_->HasRecordings()) return false; // If the |raster_source_| has a recording it should have non-empty bounds. DCHECK(!raster_source_->GetSize().IsEmpty()); if (MaximumContentsScale() < MinimumContentsScale()) return false; return true; } void PictureLayerImpl::SanityCheckTilingState() const { #if DCHECK_IS_ON() if (!CanHaveTilings()) { DCHECK_EQ(0u, tilings_->num_tilings()); return; } if (tilings_->num_tilings() == 0) return; // We should only have one high res tiling. DCHECK_EQ(1, tilings_->NumHighResTilings()); #endif } float PictureLayerImpl::MaximumTilingContentsScale() const { float max_contents_scale = tilings_->GetMaximumContentsScale(); return std::max(max_contents_scale, MinimumContentsScale()); } std::unique_ptr<PictureLayerTilingSet> PictureLayerImpl::CreatePictureLayerTilingSet() { const LayerTreeSettings& settings = layer_tree_impl()->settings(); return PictureLayerTilingSet::Create( IsActive() ? ACTIVE_TREE : PENDING_TREE, this, settings.tiling_interest_area_padding, layer_tree_impl()->use_gpu_rasterization() ? settings.gpu_rasterization_skewport_target_time_in_seconds : settings.skewport_target_time_in_seconds, settings.skewport_extrapolation_limit_in_screen_pixels, settings.max_preraster_distance_in_screen_pixels); } void PictureLayerImpl::UpdateIdealScales() { DCHECK(CanHaveTilings()); float min_contents_scale = MinimumContentsScale(); DCHECK_GT(min_contents_scale, 0.f); ideal_page_scale_ = IsAffectedByPageScale() ? layer_tree_impl()->current_page_scale_factor() : 1.f; ideal_device_scale_ = layer_tree_impl()->device_scale_factor(); ideal_contents_scale_ = std::min(kMaxIdealContentsScale, std::max(GetIdealContentsScale(), min_contents_scale)); ideal_source_scale_ = ideal_contents_scale_ / ideal_page_scale_ / ideal_device_scale_; } void PictureLayerImpl::GetDebugBorderProperties( SkColor* color, float* width) const { float device_scale_factor = layer_tree_impl() ? layer_tree_impl()->device_scale_factor() : 1; if (is_directly_composited_image_) { *color = DebugColors::ImageLayerBorderColor(); *width = DebugColors::ImageLayerBorderWidth(device_scale_factor); } else { *color = DebugColors::TiledContentLayerBorderColor(); *width = DebugColors::TiledContentLayerBorderWidth(device_scale_factor); } } void PictureLayerImpl::GetAllPrioritizedTilesForTracing( std::vector<PrioritizedTile>* prioritized_tiles) const { if (!tilings_) return; tilings_->GetAllPrioritizedTilesForTracing(prioritized_tiles); } void PictureLayerImpl::AsValueInto( base::trace_event::TracedValue* state) const { LayerImpl::AsValueInto(state); state->SetDouble("ideal_contents_scale", ideal_contents_scale_); state->SetDouble("geometry_contents_scale", MaximumTilingContentsScale()); state->BeginArray("tilings"); tilings_->AsValueInto(state); state->EndArray(); MathUtil::AddToTracedValue("tile_priority_rect", viewport_rect_for_tile_priority_in_content_space_, state); MathUtil::AddToTracedValue("visible_rect", visible_layer_rect(), state); state->BeginArray("pictures"); raster_source_->AsValueInto(state); state->EndArray(); state->BeginArray("invalidation"); invalidation_.AsValueInto(state); state->EndArray(); state->BeginArray("coverage_tiles"); for (PictureLayerTilingSet::CoverageIterator iter( tilings_.get(), MaximumTilingContentsScale(), gfx::Rect(raster_source_->GetSize()), ideal_contents_scale_); iter; ++iter) { state->BeginDictionary(); MathUtil::AddToTracedValue("geometry_rect", iter.geometry_rect(), state); if (*iter) viz::TracedValue::SetIDRef(*iter, state, "tile"); state->EndDictionary(); } state->EndArray(); state->BeginDictionary("can_have_tilings_state"); state->SetBoolean("can_have_tilings", CanHaveTilings()); state->SetBoolean("raster_source_solid_color", raster_source_->IsSolidColor()); state->SetBoolean("draws_content", DrawsContent()); state->SetBoolean("raster_source_has_recordings", raster_source_->HasRecordings()); state->SetDouble("max_contents_scale", MaximumTilingContentsScale()); state->SetDouble("min_contents_scale", MinimumContentsScale()); state->EndDictionary(); state->BeginDictionary("raster_scales"); state->SetDouble("page_scale", raster_page_scale_); state->SetDouble("device_scale", raster_device_scale_); state->SetDouble("source_scale", raster_source_scale_); state->SetDouble("contents_scale", raster_contents_scale_); state->SetDouble("low_res_contents_scale", low_res_raster_contents_scale_); state->EndDictionary(); state->BeginDictionary("ideal_scales"); state->SetDouble("page_scale", ideal_page_scale_); state->SetDouble("device_scale", ideal_device_scale_); state->SetDouble("source_scale", ideal_source_scale_); state->SetDouble("contents_scale", ideal_contents_scale_); state->EndDictionary(); } size_t PictureLayerImpl::GPUMemoryUsageInBytes() const { return tilings_->GPUMemoryUsageInBytes(); } void PictureLayerImpl::RunMicroBenchmark(MicroBenchmarkImpl* benchmark) { benchmark->RunOnLayer(this); } bool PictureLayerImpl::IsOnActiveOrPendingTree() const { return !layer_tree_impl()->IsRecycleTree(); } bool PictureLayerImpl::HasValidTilePriorities() const { return IsOnActiveOrPendingTree() && (contributes_to_drawn_render_surface() || raster_even_if_not_drawn()); } PictureLayerImpl::ImageInvalidationResult PictureLayerImpl::InvalidateRegionForImages( const PaintImageIdFlatSet& images_to_invalidate) { if (!raster_source_ || !raster_source_->GetDisplayItemList() || raster_source_->GetDisplayItemList()->discardable_image_map().empty()) { return ImageInvalidationResult::kNoImages; } InvalidationRegion image_invalidation; for (auto image_id : images_to_invalidate) { const auto& rects = raster_source_->GetDisplayItemList() ->discardable_image_map() .GetRectsForImage(image_id); for (const auto& r : rects.container()) image_invalidation.Union(r); } Region invalidation; image_invalidation.Swap(&invalidation); if (invalidation.IsEmpty()) return ImageInvalidationResult::kNoInvalidation; // Make sure to union the rect from this invalidation with the update_rect // instead of over-writing it. We don't want to reset the update that came // from the main thread. // Note: We can use a rect here since this is only used to track damage for a // frame and not raster invalidation. gfx::Rect new_update_rect = invalidation.bounds(); new_update_rect.Union(update_rect()); SetUpdateRect(new_update_rect); invalidation_.Union(invalidation); tilings_->Invalidate(invalidation); SetNeedsPushProperties(); return ImageInvalidationResult::kInvalidated; } void PictureLayerImpl::RegisterAnimatedImages() { if (!raster_source_ || !raster_source_->GetDisplayItemList()) return; auto* controller = layer_tree_impl()->image_animation_controller(); const auto& metadata = raster_source_->GetDisplayItemList() ->discardable_image_map() .animated_images_metadata(); for (const auto& data : metadata) { // Only update the metadata from updated recordings received from a commit. if (layer_tree_impl()->IsSyncTree()) controller->UpdateAnimatedImage(data); controller->RegisterAnimationDriver(data.paint_image_id, this); } } void PictureLayerImpl::UnregisterAnimatedImages() { if (!raster_source_ || !raster_source_->GetDisplayItemList()) return; auto* controller = layer_tree_impl()->image_animation_controller(); const auto& metadata = raster_source_->GetDisplayItemList() ->discardable_image_map() .animated_images_metadata(); for (const auto& data : metadata) controller->UnregisterAnimationDriver(data.paint_image_id, this); } } // namespace cc
[ "arnaud@geometry.ee" ]
arnaud@geometry.ee
41f14514088540ddd90ff23c4e4e61eeaa2ba490
ff94156d976d0c0f1d0f5daa4fab6c374dadf223
/RFdriver/Calibration.ino
a13eefcd14ac2daac61e91a8c64de7f03d971a55
[]
no_license
GordonAnderson/RFdriver
a8750469cc8b842e2d1400981849a73d5128a59d
488128bd2f0e1c4e8bb0d7d6ae7e9c7a5c6a4b5f
refs/heads/master
2021-07-25T15:19:17.957324
2021-06-01T14:36:03
2021-06-01T14:36:03
250,842,030
0
0
null
null
null
null
UTF-8
C++
false
false
2,066
ino
// // Need to add calibration function for Vrf readback value. // Need to add calibration function for Vrf to drive level, this requires // no user interaction to perform. // void CalibrateLoop(void) { ProcessSerial(false); control.run(); } int Calibrate5592point(uint8_t SPIcs, DACchan *dacchan, ADCchan *adcchan, float *V) { char *Token; String sToken; // Set value and ask for user to enter actual value read if(dacchan !=NULL) AD5592writeDAC(SPIcs, dacchan->Chan, Value2Counts(*V,dacchan)); serial->print("Enter actual value: "); while((Token = GetToken(true)) == NULL) CalibrateLoop(); sToken = Token; serial->println(Token); *V = sToken.toFloat(); while((Token = GetToken(true)) != NULL) CalibrateLoop(); if(adcchan != NULL) return AD5592readADC(SPIcs, adcchan->Chan, 10); return 0; } // This function is used to calibrate ADC/DAC AD5592 channels. void Calibrate5592(uint8_t SPIcs, DACchan *dacchan, ADCchan *adcchan, float V1, float V2) { float val1,val2,m,b; int adcV1, adcV2; int dacV1, dacV2; serial->println("Enter values when prompted."); // Set to first voltage and ask for user to enter actual voltage val1 = V1; adcV1 = Calibrate5592point(SPIcs, dacchan, adcchan, &val1); // Set to second voltage and ask for user to enter actual voltage val2 = V2; adcV2 = Calibrate5592point(SPIcs, dacchan, adcchan, &val2); // Calculate calibration parameters and apply dacV1 = Value2Counts(V1, dacchan); dacV2 = Value2Counts(V2, dacchan); m = (float)(dacV2-dacV1) / (val2-val1); b = (float)dacV1 - val1 * m; serial->println("DAC channel calibration parameters."); serial->print("m = "); serial->println(m); serial->print("b = "); serial->println(b); dacchan->m = m; dacchan->b = b; if(adcchan == NULL) return; m = (float)(adcV2-adcV1) / (val2-val1); b = (float)adcV1 - val1 * m; serial->println("ADC channel calibration parameters."); serial->print("m = "); serial->println(m); serial->print("b = "); serial->println(b); adcchan->m = m; adcchan->b = b; }
[ "gaa@owt.com" ]
gaa@owt.com
57d56c491c8b605ed318f918a4760b81f685e102
61f2f84b98181743e4a1cadf5bd77697eee49133
/Rover/cpp/ICSL/SystemModel/ISystemModel.h
f3bf6d69cf9d8bf5141165b3fe9e96eb1c4b3c91
[]
no_license
ryan0270/quadrover
f18bd3687009269d256e8350db346a9f5066631a
0efb483003b9d2ee6eaa0681ace19b227e697a3f
refs/heads/master
2020-03-29T15:19:05.539105
2013-12-09T04:45:54
2013-12-09T04:45:54
32,518,670
0
0
null
null
null
null
UTF-8
C++
false
false
3,974
h
#ifndef CLASS_SYSTEMMODEL #define CLASS_SYSTEMMODEL #include <string> #include "toadlet/egg/Mutex.h" #include "TNT/tnt.h" #include "TNT_Utils.h" /* Abstract class to define objects that represent system models (standard dynamics, SVR, GPR, etc) */ namespace ICSL { using namespace std; using namespace TNT; class ISystemModel { public: explicit ISystemModel(){}; ISystemModel(int numStates, int numAct) : mCurState(numStates,1,0.0), mCurActuator(numAct,1,0.0){}; virtual ~ISystemModel(){}; virtual void setCurState(Array2D<double> state){mMutex_DataAccess.lock(); mCurState = state.copy(); mMutex_DataAccess.unlock();} virtual void setCurActuation(Array2D<double> control) { mMutex_DataAccess.lock(); mCurActuator = control.copy(); mMutex_DataAccess.unlock(); }; virtual void setName(string s){mName = s;} virtual double getMass(){return mMass;} virtual int getNumStates(){return mNumStates;} virtual int getNumInputs(){return mNumInputs;} virtual int getNumOutputs(){return mNumOutputs;} virtual string getName(){return mName;}; virtual Array2D<double> getCurState() { mMutex_DataAccess.lock(); Array2D<double> temp = mCurState.copy(); mMutex_DataAccess.unlock(); return temp; }; virtual Array2D<double> const getCurActuator(){return mCurActuator;}; /*! \param curState \param curActuation \return the system state derivative evaluated at curState and curActuation */ virtual Array2D<double> calcStateDerivative(Array2D<double> const &curState, Array2D<double> const &curActuation)=0; /*! * \return The state after dt seconds */ virtual const Array2D<double> simulateEuler(Array2D<double> const &curActuation, double dt) { Array2D<double> dx(mNumStates,1); mMutex_DataAccess.lock(); dx.inject(calcStateDerivative(mCurState, curActuation)); mCurState += dt*dx; Array2D<double> tempState = mCurState.copy(); mMutex_DataAccess.unlock(); return tempState; } virtual const Array2D<double> simulateRK2(Array2D<double> const &curActuation, double dt) { mMutex_DataAccess.lock(); Array2D<double> dx1(mNumStates,1), dx2(mNumStates,1); dx1.inject(dt*calcStateDerivative(mCurState, curActuation)); dx2.inject(dt*calcStateDerivative(mCurState+0.5*dx1, curActuation)); mCurState = dx2; Array2D<double> tempState = mCurState.copy(); mMutex_DataAccess.unlock(); return tempState; } virtual const Array2D<double> simulateRK3(Array2D<double> const &curActuation, double dt) { mMutex_DataAccess.lock(); Array2D<double> dx1(mNumStates,1), dx2(mNumStates,1), dx3(mNumStates,1); dx1.inject(dt*calcStateDerivative(mCurState, curActuation)); dx2.inject(dt*calcStateDerivative(mCurState+0.5*dx1, curActuation)); dx3.inject(dt*calcStateDerivative(mCurState-dx1+2*dx2, curActuation)); mCurState += 1.0/6.0*(dx1+4.0*dx2+dx3); Array2D<double> tempState = mCurState.copy(); mMutex_DataAccess.unlock(); return tempState; } virtual const Array2D<double> simulateRK4(Array2D<double> const &curActuation, double dt) { mMutex_DataAccess.lock(); Array2D<double> dx1(mNumStates,1), dx2(mNumStates,1), dx3(mNumStates,1), dx4(mNumStates,1); dx1.inject(dt*calcStateDerivative(mCurState, curActuation)); dx2.inject(dt*calcStateDerivative(mCurState+0.5*dx1, curActuation)); dx3.inject(dt*calcStateDerivative(mCurState+0.5*dx2, curActuation)); dx4.inject(dt*calcStateDerivative(mCurState+dx3, curActuation)); mCurState += 1.0/6.0*(dx1+2.0*dx2+2.0*dx3+dx4); Array2D<double> tempState = mCurState.copy(); mMutex_DataAccess.unlock(); return tempState; } virtual void reset() { mMutex_DataAccess.lock(); for(int i=0; i<mCurState.dim1(); i++) mCurState[i][0] = 0; for(int i=0; i<mCurActuator.dim1(); i++) mCurActuator[i][0] = 0; mMutex_DataAccess.unlock(); } protected: int mNumStates, mNumInputs, mNumOutputs; double mMass; string mName; Array2D<double> mCurState, mCurActuator;//, mLastStateDeriv; toadlet::egg::Mutex mMutex_DataAccess; }; } #endif
[ "Tyler Lab Linux@localhost" ]
Tyler Lab Linux@localhost
3b902b9801f89651b4f0172898043ed577d76b81
c76e78581983830158b2a6f56b807e37132f4bba
/DMOJ-contest/TLE/src/tle17c2p2.cpp
c5052a7e6017c443394c434e8cb9f5ca266a9df5
[]
no_license
itslinotlie/competitive-programming-solutions
7f72e27bbc53046174a95246598c3c9c2096b965
b639ebe3c060bb3c0b304080152cc9d958e52bfb
refs/heads/master
2021-07-17T17:48:42.639357
2021-05-29T03:07:47
2021-05-29T03:07:47
249,599,291
2
1
null
null
null
null
UTF-8
C++
false
false
382
cpp
// 07/19/2020 // https://dmoj.ca/problem/tle17c2p2 #include<bits/stdc++.h> using namespace std; const int mxn = 1e6+2; int n, q, x, psa[mxn]; int main() { cin >> n; for (int i=1;i<=n;i++) { cin >> x; psa[x]--; } for (int i=1;i<=mxn;i++) psa[i]+=psa[i-1]; cin >> q; for (int i=1;i<=q;i++) { cin >> x; cout << psa[x]+x << endl; } }
[ "michael.li.web@gmail.com" ]
michael.li.web@gmail.com
b92941d72da2b6c1f507b2e0a6f5f35736d8fa0c
f06d9b671187f13eaa27b1ea272d11a9588ac546
/玩转算法面试/9-12-309-Best Time to Buy and Sell Stock with Cooldown/main.cpp
16e946972a4209c2d9247e85ecb52132e19d2e99
[]
no_license
Rani-Zz/skill-tutorials
49eb3d18d69e2d92b7b34b4c5d8a3db21a4b9749
da50fa072fab2bf49cca6c534472b26bd182ae33
refs/heads/master
2020-05-01T07:57:26.497704
2019-09-11T02:58:57
2019-09-11T02:58:57
177,365,049
0
0
null
null
null
null
GB18030
C++
false
false
1,003
cpp
class Solution { public: /** *画状体图 *每一天会有三种状态:hold,rest,sold *hold[i] rest[i] sold[i]分别表示这三种状态下可获得的最大值 *状态转移: *hold[i] :max(hold[i-1], res[i-1] - price[i]) *sold[i] :hold[i-1] + price[i] *rest[i] :max(rest[i-1], sold[i-1]) *初始化:rest[0] = 0, sold[0] = 0,hold[0] = INT_MIN *结果 max(rest[i],sold[i]) *时间复杂度 O(n) *空间复杂度 O(n) */ int maxProfit(vector<int>& prices) { int n = prices.size(); if(n==0) return 0; vector<int> rest(n+1,-1); vector<int> sold(n+1,-1); vector<int> hold(n+1,-1); rest[0] = 0; sold[0] = 0; hold[0] = INT_MIN; for(int i = 0;i<n;i++) { hold[i+1] = max(hold[i],rest[i]-prices[i]); sold[i+1] = hold[i]+prices[i]; rest[i+1] = max(rest[i],sold[i]); } return max(rest[n],sold[n]); } };
[ "850150293@qq.com" ]
850150293@qq.com
f7d7a9348f0cb81bf790db7915ca8feeeee66e51
17aae4aa45dbdca8c12f01ea37ac08007cd8500d
/AlgoToolbox/Week 2/fibonacci_last_digit.cpp
8559de6031feb9c4a19e15d2edeaae0977b4b38d
[]
no_license
pablomarcel/Algorithms-and-Data-Structures-Coursera
0405c3a9b1e4a5ecb779d7704fa68576361b30c5
4e91e320717aa2f7417f00a7ae8a610286241da9
refs/heads/master
2023-03-17T05:06:48.157832
2019-11-18T08:35:51
2019-11-18T08:35:51
null
0
0
null
null
null
null
UTF-8
C++
false
false
360
cpp
#include <iostream> #include<vector> using namespace std; long long int get_fibonacci_last(long long int n) { vector<long long int> dp(n+1,0); dp[1]=1; for (int i = 2; i <=n ; ++i) { dp[i]=(dp[i-1]+dp[i-2])%10; } return dp[n]%10; } int main() { int n; cin >> n; int c = get_fibonacci_last(n); cout << c << '\n'; }
[ "kartikdutt@live.in" ]
kartikdutt@live.in
02e15e89803bfdf0687407223bd724e1b80678d5
c7ccf5be40781b3681d0bf7047e51424d72fe240
/regstartwnd.h
486003602234545736a014da14314aac4dd5afdd
[]
no_license
heartquake7/DatabaseApp1
e54fad1731cec4bd2956ae46baac3eb1cd468f0c
6caab38a5965d3d337759328d6a5917abcd5acab
refs/heads/master
2020-03-19T07:07:57.134994
2018-06-04T22:14:28
2018-06-04T22:14:28
136,088,425
0
0
null
null
null
null
UTF-8
C++
false
false
1,165
h
#ifndef REGSTARTWND_H #define REGSTARTWND_H #include <QWidget> #include <QSqlRelationalTableModel> #include <QSqlRelationalDelegate> #include <QSqlRelation> #include <QSqlRecord> #include <QMenu> #include "database.h" #include "addregdialog.h" namespace Ui { class RegStartWnd; } class RegStartWnd : public QWidget { Q_OBJECT public: explicit RegStartWnd(QWidget *parent = 0, database* = 0, access = guest); ~RegStartWnd(); void setupModel(const QStringList &headers); void createUI(); private slots: void on_btn_back_clicked(); void slotEditRecord(); void slotDeleteRecord(); void oncloseDlg(); void slotCustomMenuReq(QPoint pos); void on_btn_add_clicked(); void on_btn_showsearch_clicked(); void on_btn_search_clicked(); void on_btn_reset_clicked(); void on_tableView_doubleClicked(const QModelIndex &index); void on_btn_showfilter_clicked(); void on_btn_resetfilter_clicked(); void on_btn_applyfilter_clicked(); private: Ui::RegStartWnd *ui; database* db; QSqlQuery query; QSqlQueryModel* model; QWidget* Parent; access Acc; }; #endif // REGSTARTWND_H
[ "noobjkee11@mail.ru" ]
noobjkee11@mail.ru
261d323e3f785ec8e8d065457b1784ce9482eb96
e78ac26c42920ddb75b0f86f03f96b18c0c2c83c
/src/private/Sample.cpp
418cc7061c8dae5a50efe1952523b3cbe241bfe9
[]
no_license
WangShengyu/ConanProjectSample
124b78321f9cc4fd0e7e878f92f0b302543f6295
1c75b7618d6bc8566c60cc36582585f5f50a5b68
refs/heads/master
2020-03-09T23:40:18.408324
2018-07-11T02:55:27
2018-07-11T02:55:40
129,063,334
0
0
null
null
null
null
UTF-8
C++
false
false
105
cpp
#include "Sample.h" int StrangeSum(int a, int b) { if (b == 0) return a; return a / b * b + b; }
[ "wangshengyu@51hitech.com" ]
wangshengyu@51hitech.com
c916742418e05652e0063ad22544aa217d2ec682
15941552709ce55740187848bf6477fbdaa85cc0
/ds-algo/chaining.cpp
b7a72a29e88c556ec069ff6500c206f109af9191
[]
no_license
akgupta-47/Progrm-Basics
b66e1351dddc62201482f0a682a483c0f3c23ac3
04b904abe5fa249dcf8d0fa3af588f125517d2a2
refs/heads/master
2023-06-14T09:10:08.843249
2021-07-12T12:07:44
2021-07-12T12:07:44
296,837,785
0
0
null
null
null
null
UTF-8
C++
false
false
918
cpp
#include <iostream> using namespace std; class Node { public: int data; Node *next; }; void SortedInsert(Node **H, int x) { Node *t, *q = NULL, *p = *H; t = new Node; t->data = x; t->next = NULL; if (*H == NULL) *H = t; else { while (p && p->data < x) { q = p; p = p->next; } } } int hashFun(int key) { return key % 10; } // i am currently stuck at problem of inserting in chain and inserting at first or last position in chain // use vs code to debug every step void InsertChain(Node *H[], int key) { int index = hashFun(key); Node *t, *q = NULL, *p = H[index]; t = new Node; t->data = key; t->next = NULL; if (H[index] == NULL) H[index] = t; else { } } int main() { Node *HT[10]; int i; for (i = 0; i < 10; i++) HT[i] = NULL; return 0; }
[ "akshatgupta3214@gmail.com" ]
akshatgupta3214@gmail.com
a185f6d7cd6936d2dccf6b0ac617321ac7a09ee1
bfb67347a686c6f4da31cf6af4ad8ee847df1468
/Source/WebKit/UIProcess/WebAuthentication/Mock/MockHidConnection.cpp
26c996601cf499a87bb0c761a12daa4c3a392f55
[]
no_license
applejian/webkit
5365d5e23aa3dc08219497ac6e73431f0a641654
5d6858971a7669ab73e0fd4d360e5d68f49dc26b
refs/heads/master
2023-02-21T16:16:16.443185
2018-12-05T14:56:33
2018-12-05T14:56:33
160,545,859
2
0
null
2018-12-05T16:19:47
2018-12-05T16:19:46
null
UTF-8
C++
false
false
10,775
cpp
/* * Copyright (C) 2018 Apple Inc. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS 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 APPLE INC. OR ITS CONTRIBUTORS * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF * THE POSSIBILITY OF SUCH DAMAGE. */ #include "config.h" #include "MockHidConnection.h" #if ENABLE(WEB_AUTHN) && PLATFORM(MAC) #include <WebCore/AuthenticatorGetInfoResponse.h> #include <WebCore/CBORReader.h> #include <WebCore/FidoConstants.h> #include <wtf/BlockPtr.h> #include <wtf/CryptographicallyRandomNumber.h> #include <wtf/RunLoop.h> #include <wtf/text/Base64.h> namespace WebKit { using Mock = MockWebAuthenticationConfiguration::Hid; using namespace WebCore; using namespace cbor; using namespace fido; namespace MockHidConnectionInternal { // https://fidoalliance.org/specs/fido-v2.0-ps-20170927/fido-client-to-authenticator-protocol-v2.0-ps-20170927.html#mandatory-commands const size_t CtapChannelIdSize = 4; const uint8_t CtapKeepAliveStatusProcessing = 1; // https://fidoalliance.org/specs/fido-v2.0-ps-20170927/fido-client-to-authenticator-protocol-v2.0-ps-20170927.html#commands const int64_t CtapMakeCredentialRequestOptionsKey = 7; const int64_t CtapGetAssertionRequestOptionsKey = 5; } MockHidConnection::MockHidConnection(IOHIDDeviceRef device, const MockWebAuthenticationConfiguration& configuration) : HidConnection(device) , m_configuration(configuration) { } void MockHidConnection::initialize() { m_initialized = true; } void MockHidConnection::terminate() { m_terminated = true; } void MockHidConnection::send(Vector<uint8_t>&& data, DataSentCallback&& callback) { ASSERT(m_initialized); auto task = BlockPtr<void()>::fromCallable([weakThis = makeWeakPtr(*this), data = WTFMove(data), callback = WTFMove(callback)]() mutable { ASSERT(!RunLoop::isMain()); RunLoop::main().dispatch([weakThis, data = WTFMove(data), callback = WTFMove(callback)]() mutable { if (!weakThis) { callback(DataSent::No); return; } weakThis->assembleRequest(WTFMove(data)); auto sent = DataSent::Yes; if (weakThis->stagesMatch() && weakThis->m_configuration.hid->error == Mock::Error::DataNotSent) sent = DataSent::No; callback(sent); }); }); dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), task.get()); } void MockHidConnection::registerDataReceivedCallbackInternal() { if (stagesMatch() && m_configuration.hid->error == Mock::Error::EmptyReport) { receiveReport({ }); shouldContinueFeedReports(); return; } if (!m_configuration.hid->fastDataArrival) feedReports(); } void MockHidConnection::assembleRequest(Vector<uint8_t>&& data) { if (!m_requestMessage) { m_requestMessage = FidoHidMessage::createFromSerializedData(data); ASSERT(m_requestMessage); } else { auto status = m_requestMessage->addContinuationPacket(data); ASSERT_UNUSED(status, status); } if (m_requestMessage->messageComplete()) parseRequest(); } void MockHidConnection::parseRequest() { using namespace MockHidConnectionInternal; ASSERT(m_requestMessage); // Set stages. if (m_requestMessage->cmd() == FidoHidDeviceCommand::kInit) { auto previousSubStage = m_subStage; m_subStage = Mock::SubStage::Init; if (previousSubStage == Mock::SubStage::Msg) m_stage = Mock::Stage::Request; } if (m_requestMessage->cmd() == FidoHidDeviceCommand::kCbor) m_subStage = Mock::SubStage::Msg; // Set options. if (m_stage == Mock::Stage::Request && m_subStage == Mock::SubStage::Msg) { m_requireResidentKey = false; m_requireUserVerification = false; auto payload = m_requestMessage->getMessagePayload(); ASSERT(payload.size()); auto cmd = static_cast<CtapRequestCommand>(payload[0]); payload.remove(0); auto requestMap = CBORReader::read(payload); ASSERT(requestMap); if (cmd == CtapRequestCommand::kAuthenticatorMakeCredential) { auto it = requestMap->getMap().find(CBORValue(CtapMakeCredentialRequestOptionsKey)); // Find options. if (it != requestMap->getMap().end()) { auto& optionMap = it->second.getMap(); auto itr = optionMap.find(CBORValue(kResidentKeyMapKey)); if (itr != optionMap.end()) m_requireResidentKey = itr->second.getBool(); itr = optionMap.find(CBORValue(kUserVerificationMapKey)); if (itr != optionMap.end()) m_requireUserVerification = itr->second.getBool(); } } if (cmd == CtapRequestCommand::kAuthenticatorGetAssertion) { auto it = requestMap->getMap().find(CBORValue(CtapGetAssertionRequestOptionsKey)); // Find options. if (it != requestMap->getMap().end()) { auto& optionMap = it->second.getMap(); auto itr = optionMap.find(CBORValue(kUserVerificationMapKey)); if (itr != optionMap.end()) m_requireUserVerification = itr->second.getBool(); } } } // Store nonce. if (m_subStage == Mock::SubStage::Init) { m_nonce = m_requestMessage->getMessagePayload(); ASSERT(m_nonce.size() == kHidInitNonceLength); } m_currentChannel = m_requestMessage->channelId(); m_requestMessage = std::nullopt; if (m_configuration.hid->fastDataArrival) feedReports(); } void MockHidConnection::feedReports() { using namespace MockHidConnectionInternal; if (m_subStage == Mock::SubStage::Init) { Vector<uint8_t> payload; payload.reserveInitialCapacity(kHidInitResponseSize); payload.appendVector(m_nonce); if (stagesMatch() && m_configuration.hid->error == Mock::Error::WrongNonce) payload[0]--; payload.grow(kHidInitResponseSize); cryptographicallyRandomValues(payload.data() + payload.size(), CtapChannelIdSize); auto channel = kHidBroadcastChannel; if (stagesMatch() && m_configuration.hid->error == Mock::Error::WrongChannelId) channel--; FidoHidInitPacket initPacket(channel, FidoHidDeviceCommand::kInit, WTFMove(payload), payload.size()); receiveReport(initPacket.getSerializedData()); shouldContinueFeedReports(); return; } std::optional<FidoHidMessage> message; if (m_stage == Mock::Stage::Info && m_subStage == Mock::SubStage::Msg) { auto infoData = encodeAsCBOR(AuthenticatorGetInfoResponse({ ProtocolVersion::kCtap }, Vector<uint8_t>(kAaguidLength, 0u))); infoData.insert(0, static_cast<uint8_t>(CtapDeviceResponseCode::kSuccess)); // Prepend status code. if (stagesMatch() && m_configuration.hid->error == Mock::Error::WrongChannelId) message = FidoHidMessage::create(m_currentChannel - 1, FidoHidDeviceCommand::kCbor, infoData); else message = FidoHidMessage::create(m_currentChannel, FidoHidDeviceCommand::kCbor, infoData); } if (m_stage == Mock::Stage::Request && m_subStage == Mock::SubStage::Msg) { if (m_configuration.hid->keepAlive) { m_configuration.hid->keepAlive = false; FidoHidInitPacket initPacket(m_currentChannel, FidoHidDeviceCommand::kKeepAlive, { CtapKeepAliveStatusProcessing }, 1); receiveReport(initPacket.getSerializedData()); continueFeedReports(); return; } if (stagesMatch() && m_configuration.hid->error == Mock::Error::UnsupportedOptions && (m_requireResidentKey || m_requireUserVerification)) message = FidoHidMessage::create(m_currentChannel, FidoHidDeviceCommand::kCbor, { static_cast<uint8_t>(CtapDeviceResponseCode::kCtap2ErrUnsupportedOption) }); else { Vector<uint8_t> payload; auto status = base64Decode(m_configuration.hid->payloadBase64, payload); ASSERT_UNUSED(status, status); message = FidoHidMessage::create(m_currentChannel, FidoHidDeviceCommand::kCbor, payload); } } ASSERT(message); bool isFirst = true; while (message->numPackets()) { auto report = message->popNextPacket(); if (!isFirst && stagesMatch() && m_configuration.hid->error == Mock::Error::WrongChannelId) report = FidoHidContinuationPacket(m_currentChannel - 1, 0, { }).getSerializedData(); // Packets are feed asynchronously to mimic actual data transmission. RunLoop::main().dispatch([report = WTFMove(report), weakThis = makeWeakPtr(*this)]() mutable { if (!weakThis) return; weakThis->receiveReport(WTFMove(report)); }); isFirst = false; } } bool MockHidConnection::stagesMatch() const { return m_configuration.hid->stage == m_stage && m_configuration.hid->subStage == m_subStage; } void MockHidConnection::shouldContinueFeedReports() { if (!m_configuration.hid->continueAfterErrorData) return; m_configuration.hid->continueAfterErrorData = false; m_configuration.hid->error = Mock::Error::Success; continueFeedReports(); } void MockHidConnection::continueFeedReports() { // Send actual response for the next run. RunLoop::main().dispatch([weakThis = makeWeakPtr(*this)]() mutable { if (!weakThis) return; weakThis->feedReports(); }); } } // namespace WebKit #endif // ENABLE(WEB_AUTHN) && PLATFORM(MAC)
[ "jiewen_tan@apple.com@268f45cc-cd09-0410-ab3c-d52691b4dbfc" ]
jiewen_tan@apple.com@268f45cc-cd09-0410-ab3c-d52691b4dbfc
1cfc1247a1372cf0e0053c340fa95e61e0b7a3ed
38be118d186851d3b11e517d03f072f7daafc44f
/Chap14/Lab14_2/node.h
31f06632277df8638a10e6b81df72c32e81979a9
[]
no_license
Lanova/sjcc-cpp-course
7477e373c2296032449a5ece3881c0434cd82129
29034bc3143eff95c6775b0e7d72009a2b835754
refs/heads/master
2022-09-01T03:16:24.562514
2020-05-22T20:18:41
2020-05-22T20:18:41
255,234,483
0
0
null
null
null
null
UTF-8
C++
false
false
734
h
//DISPLAY 13.13 Interface File for a Node Class // This is the header file for Node.h. This is the interface for // a node class that behaves similarly to the struct defined // in Display 13.4 #ifndef NODE_H #define NODE_H class Node { public: Node( ); Node(int value, Node *next); // Constructors to initialize a node int getData( ) const; // Retrieve value for this node Node *getLink( ) const; // Retrieve next Node in the list void setData(int value); // Use to modify the value stored in the list void setLink(Node *next); // Use to change the reference to the next node private: int data; Node *link; }; typedef Node* NodePtr; // node.h #endif
[ "Lanovafuria@gmail.com" ]
Lanovafuria@gmail.com
1dd3e3a7c572f562fbc46f8422fb4b0bbbc20219
a7b670687a192cffcc9355691549478ff22d1fa3
/frc-cpp-sim/WPILib-2012/AnalogChannel.h
d57184a1e80332b004ab9fd63b8ece99443d21c0
[]
no_license
anidev/frc-simulator
f226d9af0bcb4fc25f33ad3a28dceb0fbadac109
3c60daa84acbabdcde5aa9de6935e1950b48e4c3
refs/heads/master
2020-12-24T17:35:21.255684
2014-02-04T04:45:21
2014-02-04T04:45:21
7,597,042
0
1
null
null
null
null
UTF-8
C++
false
false
2,582
h
/*----------------------------------------------------------------------------*/ /* Copyright (c) FIRST 2008. All Rights Reserved. */ /* Open Source Software - may be modified and shared by FRC teams. The code */ /* must be accompanied by the FIRST BSD license file in $(WIND_BASE)/WPILib. */ /*----------------------------------------------------------------------------*/ #ifndef ANALOG_CHANNEL_H_ #define ANALOG_CHANNEL_H_ #include "ChipObject.h" #include "SensorBase.h" #include "PIDSource.h" class AnalogModule; /** * Analog channel class. * * Each analog channel is read from hardware as a 12-bit number representing -10V to 10V. * * Connected to each analog channel is an averaging and oversampling engine. This engine accumulates * the specified ( by SetAverageBits() and SetOversampleBits() ) number of samples before returning a new * value. This is not a sliding window average. The only difference between the oversampled samples and * the averaged samples is that the oversampled samples are simply accumulated effectively increasing the * resolution, while the averaged samples are divided by the number of samples to retain the resolution, * but get more stable values. */ class AnalogChannel : public SensorBase, public PIDSource { public: static const UINT8 kAccumulatorModuleNumber = 1; static const UINT32 kAccumulatorNumChannels = 2; static const UINT32 kAccumulatorChannels[kAccumulatorNumChannels]; AnalogChannel(UINT8 moduleNumber, UINT32 channel); explicit AnalogChannel(UINT32 channel); virtual ~AnalogChannel(); AnalogModule *GetModule(); INT16 GetValue(); INT32 GetAverageValue(); float GetVoltage(); float GetAverageVoltage(); UINT8 GetModuleNumber(); UINT32 GetChannel(); void SetAverageBits(UINT32 bits); UINT32 GetAverageBits(); void SetOversampleBits(UINT32 bits); UINT32 GetOversampleBits(); UINT32 GetLSBWeight(); INT32 GetOffset(); bool IsAccumulatorChannel(); void InitAccumulator(); void SetAccumulatorInitialValue(INT64 value); void ResetAccumulator(); void SetAccumulatorCenter(INT32 center); void SetAccumulatorDeadband(INT32 deadband); INT64 GetAccumulatorValue(); UINT32 GetAccumulatorCount(); void GetAccumulatorOutput(INT64 *value, UINT32 *count); double PIDGet(); private: void InitChannel(UINT8 moduleNumber, UINT32 channel); UINT32 m_channel; AnalogModule *m_module; tAccumulator *m_accumulator; INT64 m_accumulatorOffset; }; #endif
[ "anidev.aelico@gmail.com" ]
anidev.aelico@gmail.com
87863a33ad5e011aaa6455a89c7752f43331f5fd
19f039b593be9401d479b15f97ecb191ef478f46
/RSA-SW/PSME/common/configuration/src/schema_validator.cpp
be823bdc9a22d75cdd5cf2f048a3c6070e7d85ea
[ "MIT", "BSD-3-Clause", "Apache-2.0" ]
permissive
isabella232/IntelRackScaleArchitecture
9a28e34a7f7cdc21402791f24dad842ac74d07b6
1206d2316e1bd1889b10a1c4f4a39f71bdfa88d3
refs/heads/master
2021-06-04T08:33:27.191735
2016-09-29T09:18:10
2016-09-29T09:18:10
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,709
cpp
/*! * @section LICENSE * * @copyright * Copyright (c) 2015 Intel Corporation * * @copyright * 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 * * @copyright * http://www.apache.org/licenses/LICENSE-2.0 * * @copyright * 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. * * @section DESCRIPTION * * @file schema_validator.cpp * * @brief SchemaValidator implementation * */ #include "configuration/schema_validator.hpp" #include "configuration/schema_property.hpp" #include "configuration/json_path.hpp" #include "configuration/utils.hpp" #include "json/json.hpp" using namespace configuration; class SchemaValidator::Impl { public: void add_property(const SchemaProperty& property) { m_properties.push_back(property); } void validate(const json::Value& json, SchemaErrors& errors) { for (auto it = json.cbegin(); it != json.cend(); it++) { m_json_path.push_key(it.key()); // if there is no validator for module check global property if (!check_property(m_json_path.get_path(), *it, errors)) { check_property(it.key(), *it, errors); } validate(*it, errors); m_json_path.pop_key(); } } bool check_property(const std::string& name, const json::Value& value, SchemaErrors& errors) { for (auto& property : m_properties) { if (property.get_name() == name) { auto error = property.validate(value); if (error.count()) { error.set_path(m_json_path.get_path()); error.set_value(json_value_to_string(value)); errors.add_error(error); } return true; } } return false; } using property_t = std::vector<SchemaProperty>; property_t m_properties{}; JsonPath m_json_path{}; }; SchemaValidator::SchemaValidator() : m_impl{new SchemaValidator::Impl} {} SchemaValidator::~SchemaValidator() {} void SchemaValidator::add_property(const SchemaProperty& property) { m_impl->add_property(property); } void SchemaValidator::validate(const json::Value& json, SchemaErrors& errors) { m_impl->validate(json, errors); }
[ "chester.kuo@gmail.com" ]
chester.kuo@gmail.com
6b9f9c1d46be456d5497c4e3cd369c0d7a021df0
43a4fe17b5c0879a0d5fcda969e688d6ba145442
/Cosmic/vendor/imgui/ImGuizmo.cpp
b93928c8625716de64a56b7f13bb81dc363ebb5e
[ "MIT" ]
permissive
Decstar77/Cosmic
1f0b8950e2561363dac631f238649f7e99f57064
3b5068cf798c1706f3c6a615eb45f2d71862f1b7
refs/heads/main
2021-06-25T21:51:30.664234
2021-01-03T19:21:15
2021-01-03T19:21:15
208,612,184
2
0
null
null
null
null
UTF-8
C++
false
false
98,058
cpp
// The MIT License(MIT) // // Copyright(c) 2016 Cedric Guillemet // // 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 "imgui.h" #ifndef IMGUI_DEFINE_MATH_OPERATORS #define IMGUI_DEFINE_MATH_OPERATORS #endif #include "imgui_internal.h" #include "ImGuizmo.h" #if !defined(_WIN32) #define _malloca(x) alloca(x) #else #include <malloc.h> #endif // includes patches for multiview from // https://github.com/CedricGuillemet/ImGuizmo/issues/15 namespace ImGuizmo { static const float ZPI = 3.14159265358979323846f; static const float RAD2DEG = (180.f / ZPI); static const float DEG2RAD = (ZPI / 180.f); static float gGizmoSizeClipSpace = 0.1f; const float screenRotateSize = 0.06f; /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // utility and math void FPU_MatrixF_x_MatrixF(const float* a, const float* b, float* r) { r[0] = a[0] * b[0] + a[1] * b[4] + a[2] * b[8] + a[3] * b[12]; r[1] = a[0] * b[1] + a[1] * b[5] + a[2] * b[9] + a[3] * b[13]; r[2] = a[0] * b[2] + a[1] * b[6] + a[2] * b[10] + a[3] * b[14]; r[3] = a[0] * b[3] + a[1] * b[7] + a[2] * b[11] + a[3] * b[15]; r[4] = a[4] * b[0] + a[5] * b[4] + a[6] * b[8] + a[7] * b[12]; r[5] = a[4] * b[1] + a[5] * b[5] + a[6] * b[9] + a[7] * b[13]; r[6] = a[4] * b[2] + a[5] * b[6] + a[6] * b[10] + a[7] * b[14]; r[7] = a[4] * b[3] + a[5] * b[7] + a[6] * b[11] + a[7] * b[15]; r[8] = a[8] * b[0] + a[9] * b[4] + a[10] * b[8] + a[11] * b[12]; r[9] = a[8] * b[1] + a[9] * b[5] + a[10] * b[9] + a[11] * b[13]; r[10] = a[8] * b[2] + a[9] * b[6] + a[10] * b[10] + a[11] * b[14]; r[11] = a[8] * b[3] + a[9] * b[7] + a[10] * b[11] + a[11] * b[15]; r[12] = a[12] * b[0] + a[13] * b[4] + a[14] * b[8] + a[15] * b[12]; r[13] = a[12] * b[1] + a[13] * b[5] + a[14] * b[9] + a[15] * b[13]; r[14] = a[12] * b[2] + a[13] * b[6] + a[14] * b[10] + a[15] * b[14]; r[15] = a[12] * b[3] + a[13] * b[7] + a[14] * b[11] + a[15] * b[15]; } void Frustum(float left, float right, float bottom, float top, float znear, float zfar, float* m16) { float temp, temp2, temp3, temp4; temp = 2.0f * znear; temp2 = right - left; temp3 = top - bottom; temp4 = zfar - znear; m16[0] = temp / temp2; m16[1] = 0.0; m16[2] = 0.0; m16[3] = 0.0; m16[4] = 0.0; m16[5] = temp / temp3; m16[6] = 0.0; m16[7] = 0.0; m16[8] = (right + left) / temp2; m16[9] = (top + bottom) / temp3; m16[10] = (-zfar - znear) / temp4; m16[11] = -1.0f; m16[12] = 0.0; m16[13] = 0.0; m16[14] = (-temp * zfar) / temp4; m16[15] = 0.0; } void Perspective(float fovyInDegrees, float aspectRatio, float znear, float zfar, float* m16) { float ymax, xmax; ymax = znear * tanf(fovyInDegrees * DEG2RAD); xmax = ymax * aspectRatio; Frustum(-xmax, xmax, -ymax, ymax, znear, zfar, m16); } void Cross(const float* a, const float* b, float* r) { r[0] = a[1] * b[2] - a[2] * b[1]; r[1] = a[2] * b[0] - a[0] * b[2]; r[2] = a[0] * b[1] - a[1] * b[0]; } float Dot(const float* a, const float* b) { return a[0] * b[0] + a[1] * b[1] + a[2] * b[2]; } void Normalize(const float* a, float* r) { float il = 1.f / (sqrtf(Dot(a, a)) + FLT_EPSILON); r[0] = a[0] * il; r[1] = a[1] * il; r[2] = a[2] * il; } void LookAt(const float* eye, const float* at, const float* up, float* m16) { float X[3], Y[3], Z[3], tmp[3]; tmp[0] = eye[0] - at[0]; tmp[1] = eye[1] - at[1]; tmp[2] = eye[2] - at[2]; Normalize(tmp, Z); Normalize(up, Y); Cross(Y, Z, tmp); Normalize(tmp, X); Cross(Z, X, tmp); Normalize(tmp, Y); m16[0] = X[0]; m16[1] = Y[0]; m16[2] = Z[0]; m16[3] = 0.0f; m16[4] = X[1]; m16[5] = Y[1]; m16[6] = Z[1]; m16[7] = 0.0f; m16[8] = X[2]; m16[9] = Y[2]; m16[10] = Z[2]; m16[11] = 0.0f; m16[12] = -Dot(X, eye); m16[13] = -Dot(Y, eye); m16[14] = -Dot(Z, eye); m16[15] = 1.0f; } template <typename T> T Clamp(T x, T y, T z) { return ((x < y) ? y : ((x > z) ? z : x)); } template <typename T> T max(T x, T y) { return (x > y) ? x : y; } template <typename T> T min(T x, T y) { return (x < y) ? x : y; } template <typename T> bool IsWithin(T x, T y, T z) { return (x >= y) && (x <= z); } struct matrix_t; struct vec_t { public: float x, y, z, w; void Lerp(const vec_t& v, float t) { x += (v.x - x) * t; y += (v.y - y) * t; z += (v.z - z) * t; w += (v.w - w) * t; } void Set(float v) { x = y = z = w = v; } void Set(float _x, float _y, float _z = 0.f, float _w = 0.f) { x = _x; y = _y; z = _z; w = _w; } vec_t& operator -= (const vec_t& v) { x -= v.x; y -= v.y; z -= v.z; w -= v.w; return *this; } vec_t& operator += (const vec_t& v) { x += v.x; y += v.y; z += v.z; w += v.w; return *this; } vec_t& operator *= (const vec_t& v) { x *= v.x; y *= v.y; z *= v.z; w *= v.w; return *this; } vec_t& operator *= (float v) { x *= v; y *= v; z *= v; w *= v; return *this; } vec_t operator * (float f) const; vec_t operator - () const; vec_t operator - (const vec_t& v) const; vec_t operator + (const vec_t& v) const; vec_t operator * (const vec_t& v) const; const vec_t& operator + () const { return (*this); } float Length() const { return sqrtf(x * x + y * y + z * z); }; float LengthSq() const { return (x * x + y * y + z * z); }; vec_t Normalize() { (*this) *= (1.f / Length()); return (*this); } vec_t Normalize(const vec_t& v) { this->Set(v.x, v.y, v.z, v.w); this->Normalize(); return (*this); } vec_t Abs() const; void Cross(const vec_t& v) { vec_t res; res.x = y * v.z - z * v.y; res.y = z * v.x - x * v.z; res.z = x * v.y - y * v.x; x = res.x; y = res.y; z = res.z; w = 0.f; } void Cross(const vec_t& v1, const vec_t& v2) { x = v1.y * v2.z - v1.z * v2.y; y = v1.z * v2.x - v1.x * v2.z; z = v1.x * v2.y - v1.y * v2.x; w = 0.f; } float Dot(const vec_t& v) const { return (x * v.x) + (y * v.y) + (z * v.z) + (w * v.w); } float Dot3(const vec_t& v) const { return (x * v.x) + (y * v.y) + (z * v.z); } void Transform(const matrix_t& matrix); void Transform(const vec_t& s, const matrix_t& matrix); void TransformVector(const matrix_t& matrix); void TransformPoint(const matrix_t& matrix); void TransformVector(const vec_t& v, const matrix_t& matrix) { (*this) = v; this->TransformVector(matrix); } void TransformPoint(const vec_t& v, const matrix_t& matrix) { (*this) = v; this->TransformPoint(matrix); } float& operator [] (size_t index) { return ((float*)&x)[index]; } const float& operator [] (size_t index) const { return ((float*)&x)[index]; } bool operator!=(const vec_t& other) const { return memcmp(this, &other, sizeof(vec_t)); } }; vec_t makeVect(float _x, float _y, float _z = 0.f, float _w = 0.f) { vec_t res; res.x = _x; res.y = _y; res.z = _z; res.w = _w; return res; } vec_t makeVect(ImVec2 v) { vec_t res; res.x = v.x; res.y = v.y; res.z = 0.f; res.w = 0.f; return res; } vec_t vec_t::operator * (float f) const { return makeVect(x * f, y * f, z * f, w * f); } vec_t vec_t::operator - () const { return makeVect(-x, -y, -z, -w); } vec_t vec_t::operator - (const vec_t& v) const { return makeVect(x - v.x, y - v.y, z - v.z, w - v.w); } vec_t vec_t::operator + (const vec_t& v) const { return makeVect(x + v.x, y + v.y, z + v.z, w + v.w); } vec_t vec_t::operator * (const vec_t& v) const { return makeVect(x * v.x, y * v.y, z * v.z, w * v.w); } vec_t vec_t::Abs() const { return makeVect(fabsf(x), fabsf(y), fabsf(z)); } vec_t Normalized(const vec_t& v) { vec_t res; res = v; res.Normalize(); return res; } vec_t Cross(const vec_t& v1, const vec_t& v2) { vec_t res; res.x = v1.y * v2.z - v1.z * v2.y; res.y = v1.z * v2.x - v1.x * v2.z; res.z = v1.x * v2.y - v1.y * v2.x; res.w = 0.f; return res; } float Dot(const vec_t& v1, const vec_t& v2) { return (v1.x * v2.x) + (v1.y * v2.y) + (v1.z * v2.z); } vec_t BuildPlan(const vec_t& p_point1, const vec_t& p_normal) { vec_t normal, res; normal.Normalize(p_normal); res.w = normal.Dot(p_point1); res.x = normal.x; res.y = normal.y; res.z = normal.z; return res; } struct matrix_t { public: union { float m[4][4]; float m16[16]; struct { vec_t right, up, dir, position; } v; vec_t component[4]; }; matrix_t(const matrix_t& other) { memcpy(&m16[0], &other.m16[0], sizeof(float) * 16); } matrix_t() {} operator float* () { return m16; } operator const float* () const { return m16; } void Translation(float _x, float _y, float _z) { this->Translation(makeVect(_x, _y, _z)); } void Translation(const vec_t& vt) { v.right.Set(1.f, 0.f, 0.f, 0.f); v.up.Set(0.f, 1.f, 0.f, 0.f); v.dir.Set(0.f, 0.f, 1.f, 0.f); v.position.Set(vt.x, vt.y, vt.z, 1.f); } void Scale(float _x, float _y, float _z) { v.right.Set(_x, 0.f, 0.f, 0.f); v.up.Set(0.f, _y, 0.f, 0.f); v.dir.Set(0.f, 0.f, _z, 0.f); v.position.Set(0.f, 0.f, 0.f, 1.f); } void Scale(const vec_t& s) { Scale(s.x, s.y, s.z); } matrix_t& operator *= (const matrix_t& mat) { matrix_t tmpMat; tmpMat = *this; tmpMat.Multiply(mat); *this = tmpMat; return *this; } matrix_t operator * (const matrix_t& mat) const { matrix_t matT; matT.Multiply(*this, mat); return matT; } void Multiply(const matrix_t& matrix) { matrix_t tmp; tmp = *this; FPU_MatrixF_x_MatrixF((float*)&tmp, (float*)&matrix, (float*)this); } void Multiply(const matrix_t& m1, const matrix_t& m2) { FPU_MatrixF_x_MatrixF((float*)&m1, (float*)&m2, (float*)this); } float GetDeterminant() const { return m[0][0] * m[1][1] * m[2][2] + m[0][1] * m[1][2] * m[2][0] + m[0][2] * m[1][0] * m[2][1] - m[0][2] * m[1][1] * m[2][0] - m[0][1] * m[1][0] * m[2][2] - m[0][0] * m[1][2] * m[2][1]; } float Inverse(const matrix_t& srcMatrix, bool affine = false); void SetToIdentity() { v.right.Set(1.f, 0.f, 0.f, 0.f); v.up.Set(0.f, 1.f, 0.f, 0.f); v.dir.Set(0.f, 0.f, 1.f, 0.f); v.position.Set(0.f, 0.f, 0.f, 1.f); } void Transpose() { matrix_t tmpm; for (int l = 0; l < 4; l++) { for (int c = 0; c < 4; c++) { tmpm.m[l][c] = m[c][l]; } } (*this) = tmpm; } void RotationAxis(const vec_t& axis, float angle); void OrthoNormalize() { v.right.Normalize(); v.up.Normalize(); v.dir.Normalize(); } }; void vec_t::Transform(const matrix_t& matrix) { vec_t out; out.x = x * matrix.m[0][0] + y * matrix.m[1][0] + z * matrix.m[2][0] + w * matrix.m[3][0]; out.y = x * matrix.m[0][1] + y * matrix.m[1][1] + z * matrix.m[2][1] + w * matrix.m[3][1]; out.z = x * matrix.m[0][2] + y * matrix.m[1][2] + z * matrix.m[2][2] + w * matrix.m[3][2]; out.w = x * matrix.m[0][3] + y * matrix.m[1][3] + z * matrix.m[2][3] + w * matrix.m[3][3]; x = out.x; y = out.y; z = out.z; w = out.w; } void vec_t::Transform(const vec_t& s, const matrix_t& matrix) { *this = s; Transform(matrix); } void vec_t::TransformPoint(const matrix_t& matrix) { vec_t out; out.x = x * matrix.m[0][0] + y * matrix.m[1][0] + z * matrix.m[2][0] + matrix.m[3][0]; out.y = x * matrix.m[0][1] + y * matrix.m[1][1] + z * matrix.m[2][1] + matrix.m[3][1]; out.z = x * matrix.m[0][2] + y * matrix.m[1][2] + z * matrix.m[2][2] + matrix.m[3][2]; out.w = x * matrix.m[0][3] + y * matrix.m[1][3] + z * matrix.m[2][3] + matrix.m[3][3]; x = out.x; y = out.y; z = out.z; w = out.w; } void vec_t::TransformVector(const matrix_t& matrix) { vec_t out; out.x = x * matrix.m[0][0] + y * matrix.m[1][0] + z * matrix.m[2][0]; out.y = x * matrix.m[0][1] + y * matrix.m[1][1] + z * matrix.m[2][1]; out.z = x * matrix.m[0][2] + y * matrix.m[1][2] + z * matrix.m[2][2]; out.w = x * matrix.m[0][3] + y * matrix.m[1][3] + z * matrix.m[2][3]; x = out.x; y = out.y; z = out.z; w = out.w; } float matrix_t::Inverse(const matrix_t& srcMatrix, bool affine) { float det = 0; if (affine) { det = GetDeterminant(); float s = 1 / det; m[0][0] = (srcMatrix.m[1][1] * srcMatrix.m[2][2] - srcMatrix.m[1][2] * srcMatrix.m[2][1]) * s; m[0][1] = (srcMatrix.m[2][1] * srcMatrix.m[0][2] - srcMatrix.m[2][2] * srcMatrix.m[0][1]) * s; m[0][2] = (srcMatrix.m[0][1] * srcMatrix.m[1][2] - srcMatrix.m[0][2] * srcMatrix.m[1][1]) * s; m[1][0] = (srcMatrix.m[1][2] * srcMatrix.m[2][0] - srcMatrix.m[1][0] * srcMatrix.m[2][2]) * s; m[1][1] = (srcMatrix.m[2][2] * srcMatrix.m[0][0] - srcMatrix.m[2][0] * srcMatrix.m[0][2]) * s; m[1][2] = (srcMatrix.m[0][2] * srcMatrix.m[1][0] - srcMatrix.m[0][0] * srcMatrix.m[1][2]) * s; m[2][0] = (srcMatrix.m[1][0] * srcMatrix.m[2][1] - srcMatrix.m[1][1] * srcMatrix.m[2][0]) * s; m[2][1] = (srcMatrix.m[2][0] * srcMatrix.m[0][1] - srcMatrix.m[2][1] * srcMatrix.m[0][0]) * s; m[2][2] = (srcMatrix.m[0][0] * srcMatrix.m[1][1] - srcMatrix.m[0][1] * srcMatrix.m[1][0]) * s; m[3][0] = -(m[0][0] * srcMatrix.m[3][0] + m[1][0] * srcMatrix.m[3][1] + m[2][0] * srcMatrix.m[3][2]); m[3][1] = -(m[0][1] * srcMatrix.m[3][0] + m[1][1] * srcMatrix.m[3][1] + m[2][1] * srcMatrix.m[3][2]); m[3][2] = -(m[0][2] * srcMatrix.m[3][0] + m[1][2] * srcMatrix.m[3][1] + m[2][2] * srcMatrix.m[3][2]); } else { // transpose matrix float src[16]; for (int i = 0; i < 4; ++i) { src[i] = srcMatrix.m16[i * 4]; src[i + 4] = srcMatrix.m16[i * 4 + 1]; src[i + 8] = srcMatrix.m16[i * 4 + 2]; src[i + 12] = srcMatrix.m16[i * 4 + 3]; } // calculate pairs for first 8 elements (cofactors) float tmp[12]; // temp array for pairs tmp[0] = src[10] * src[15]; tmp[1] = src[11] * src[14]; tmp[2] = src[9] * src[15]; tmp[3] = src[11] * src[13]; tmp[4] = src[9] * src[14]; tmp[5] = src[10] * src[13]; tmp[6] = src[8] * src[15]; tmp[7] = src[11] * src[12]; tmp[8] = src[8] * src[14]; tmp[9] = src[10] * src[12]; tmp[10] = src[8] * src[13]; tmp[11] = src[9] * src[12]; // calculate first 8 elements (cofactors) m16[0] = (tmp[0] * src[5] + tmp[3] * src[6] + tmp[4] * src[7]) - (tmp[1] * src[5] + tmp[2] * src[6] + tmp[5] * src[7]); m16[1] = (tmp[1] * src[4] + tmp[6] * src[6] + tmp[9] * src[7]) - (tmp[0] * src[4] + tmp[7] * src[6] + tmp[8] * src[7]); m16[2] = (tmp[2] * src[4] + tmp[7] * src[5] + tmp[10] * src[7]) - (tmp[3] * src[4] + tmp[6] * src[5] + tmp[11] * src[7]); m16[3] = (tmp[5] * src[4] + tmp[8] * src[5] + tmp[11] * src[6]) - (tmp[4] * src[4] + tmp[9] * src[5] + tmp[10] * src[6]); m16[4] = (tmp[1] * src[1] + tmp[2] * src[2] + tmp[5] * src[3]) - (tmp[0] * src[1] + tmp[3] * src[2] + tmp[4] * src[3]); m16[5] = (tmp[0] * src[0] + tmp[7] * src[2] + tmp[8] * src[3]) - (tmp[1] * src[0] + tmp[6] * src[2] + tmp[9] * src[3]); m16[6] = (tmp[3] * src[0] + tmp[6] * src[1] + tmp[11] * src[3]) - (tmp[2] * src[0] + tmp[7] * src[1] + tmp[10] * src[3]); m16[7] = (tmp[4] * src[0] + tmp[9] * src[1] + tmp[10] * src[2]) - (tmp[5] * src[0] + tmp[8] * src[1] + tmp[11] * src[2]); // calculate pairs for second 8 elements (cofactors) tmp[0] = src[2] * src[7]; tmp[1] = src[3] * src[6]; tmp[2] = src[1] * src[7]; tmp[3] = src[3] * src[5]; tmp[4] = src[1] * src[6]; tmp[5] = src[2] * src[5]; tmp[6] = src[0] * src[7]; tmp[7] = src[3] * src[4]; tmp[8] = src[0] * src[6]; tmp[9] = src[2] * src[4]; tmp[10] = src[0] * src[5]; tmp[11] = src[1] * src[4]; // calculate second 8 elements (cofactors) m16[8] = (tmp[0] * src[13] + tmp[3] * src[14] + tmp[4] * src[15]) - (tmp[1] * src[13] + tmp[2] * src[14] + tmp[5] * src[15]); m16[9] = (tmp[1] * src[12] + tmp[6] * src[14] + tmp[9] * src[15]) - (tmp[0] * src[12] + tmp[7] * src[14] + tmp[8] * src[15]); m16[10] = (tmp[2] * src[12] + tmp[7] * src[13] + tmp[10] * src[15]) - (tmp[3] * src[12] + tmp[6] * src[13] + tmp[11] * src[15]); m16[11] = (tmp[5] * src[12] + tmp[8] * src[13] + tmp[11] * src[14]) - (tmp[4] * src[12] + tmp[9] * src[13] + tmp[10] * src[14]); m16[12] = (tmp[2] * src[10] + tmp[5] * src[11] + tmp[1] * src[9]) - (tmp[4] * src[11] + tmp[0] * src[9] + tmp[3] * src[10]); m16[13] = (tmp[8] * src[11] + tmp[0] * src[8] + tmp[7] * src[10]) - (tmp[6] * src[10] + tmp[9] * src[11] + tmp[1] * src[8]); m16[14] = (tmp[6] * src[9] + tmp[11] * src[11] + tmp[3] * src[8]) - (tmp[10] * src[11] + tmp[2] * src[8] + tmp[7] * src[9]); m16[15] = (tmp[10] * src[10] + tmp[4] * src[8] + tmp[9] * src[9]) - (tmp[8] * src[9] + tmp[11] * src[10] + tmp[5] * src[8]); // calculate determinant det = src[0] * m16[0] + src[1] * m16[1] + src[2] * m16[2] + src[3] * m16[3]; // calculate matrix inverse float invdet = 1 / det; for (int j = 0; j < 16; ++j) { m16[j] *= invdet; } } return det; } void matrix_t::RotationAxis(const vec_t& axis, float angle) { float length2 = axis.LengthSq(); if (length2 < FLT_EPSILON) { SetToIdentity(); return; } vec_t n = axis * (1.f / sqrtf(length2)); float s = sinf(angle); float c = cosf(angle); float k = 1.f - c; float xx = n.x * n.x * k + c; float yy = n.y * n.y * k + c; float zz = n.z * n.z * k + c; float xy = n.x * n.y * k; float yz = n.y * n.z * k; float zx = n.z * n.x * k; float xs = n.x * s; float ys = n.y * s; float zs = n.z * s; m[0][0] = xx; m[0][1] = xy + zs; m[0][2] = zx - ys; m[0][3] = 0.f; m[1][0] = xy - zs; m[1][1] = yy; m[1][2] = yz + xs; m[1][3] = 0.f; m[2][0] = zx + ys; m[2][1] = yz - xs; m[2][2] = zz; m[2][3] = 0.f; m[3][0] = 0.f; m[3][1] = 0.f; m[3][2] = 0.f; m[3][3] = 1.f; } /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // enum MOVETYPE { NONE, MOVE_X, MOVE_Y, MOVE_Z, MOVE_YZ, MOVE_ZX, MOVE_XY, MOVE_SCREEN, ROTATE_X, ROTATE_Y, ROTATE_Z, ROTATE_SCREEN, SCALE_X, SCALE_Y, SCALE_Z, SCALE_XYZ }; struct Context { Context() : mbUsing(false), mbEnable(true), mbUsingBounds(false) { } ImDrawList* mDrawList; MODE mMode; matrix_t mViewMat; matrix_t mProjectionMat; matrix_t mModel; matrix_t mModelInverse; matrix_t mModelSource; matrix_t mModelSourceInverse; matrix_t mMVP; matrix_t mViewProjection; vec_t mModelScaleOrigin; vec_t mCameraEye; vec_t mCameraRight; vec_t mCameraDir; vec_t mCameraUp; vec_t mRayOrigin; vec_t mRayVector; float mRadiusSquareCenter; ImVec2 mScreenSquareCenter; ImVec2 mScreenSquareMin; ImVec2 mScreenSquareMax; float mScreenFactor; vec_t mRelativeOrigin; bool mbUsing; bool mbEnable; // translation vec_t mTranslationPlan; vec_t mTranslationPlanOrigin; vec_t mMatrixOrigin; vec_t mTranslationLastDelta; // rotation vec_t mRotationVectorSource; float mRotationAngle; float mRotationAngleOrigin; //vec_t mWorldToLocalAxis; // scale vec_t mScale; vec_t mScaleValueOrigin; vec_t mScaleLast; float mSaveMousePosx; // save axis factor when using gizmo bool mBelowAxisLimit[3]; bool mBelowPlaneLimit[3]; float mAxisFactor[3]; // bounds stretching vec_t mBoundsPivot; vec_t mBoundsAnchor; vec_t mBoundsPlan; vec_t mBoundsLocalPivot; int mBoundsBestAxis; int mBoundsAxis[2]; bool mbUsingBounds; matrix_t mBoundsMatrix; // int mCurrentOperation; float mX = 0.f; float mY = 0.f; float mWidth = 0.f; float mHeight = 0.f; float mXMax = 0.f; float mYMax = 0.f; float mDisplayRatio = 1.f; bool mIsOrthographic = false; int mActualID = -1; int mEditingID = -1; OPERATION mOperation = OPERATION(-1); }; static Context gContext; static const float angleLimit = 0.96f; static const float planeLimit = 0.2f; static const vec_t directionUnary[3] = { makeVect(1.f, 0.f, 0.f), makeVect(0.f, 1.f, 0.f), makeVect(0.f, 0.f, 1.f) }; static const ImU32 directionColor[3] = { 0xFF0000AA, 0xFF00AA00, 0xFFAA0000 }; // Alpha: 100%: FF, 87%: DE, 70%: B3, 54%: 8A, 50%: 80, 38%: 61, 12%: 1F static const ImU32 planeColor[3] = { 0x610000AA, 0x6100AA00, 0x61AA0000 }; static const ImU32 selectionColor = 0x8A1080FF; static const ImU32 inactiveColor = 0x99999999; static const ImU32 translationLineColor = 0xAAAAAAAA; static const char* translationInfoMask[] = { "X : %5.3f", "Y : %5.3f", "Z : %5.3f", "Y : %5.3f Z : %5.3f", "X : %5.3f Z : %5.3f", "X : %5.3f Y : %5.3f", "X : %5.3f Y : %5.3f Z : %5.3f" }; static const char* scaleInfoMask[] = { "X : %5.2f", "Y : %5.2f", "Z : %5.2f", "XYZ : %5.2f" }; static const char* rotationInfoMask[] = { "X : %5.2f deg %5.2f rad", "Y : %5.2f deg %5.2f rad", "Z : %5.2f deg %5.2f rad", "Screen : %5.2f deg %5.2f rad" }; static const int translationInfoIndex[] = { 0,0,0, 1,0,0, 2,0,0, 1,2,0, 0,2,0, 0,1,0, 0,1,2 }; static const float quadMin = 0.5f; static const float quadMax = 0.8f; static const float quadUV[8] = { quadMin, quadMin, quadMin, quadMax, quadMax, quadMax, quadMax, quadMin }; static const int halfCircleSegmentCount = 64; static const float snapTension = 0.5f; /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // static int GetMoveType(vec_t* gizmoHitProportion); static int GetRotateType(); static int GetScaleType(); static ImVec2 worldToPos(const vec_t& worldPos, const matrix_t& mat, ImVec2 position = ImVec2(gContext.mX, gContext.mY), ImVec2 size = ImVec2(gContext.mWidth, gContext.mHeight)) { vec_t trans; trans.TransformPoint(worldPos, mat); trans *= 0.5f / trans.w; trans += makeVect(0.5f, 0.5f); trans.y = 1.f - trans.y; trans.x *= size.x; trans.y *= size.y; trans.x += position.x; trans.y += position.y; return ImVec2(trans.x, trans.y); } static void ComputeCameraRay(vec_t& rayOrigin, vec_t& rayDir, ImVec2 position = ImVec2(gContext.mX, gContext.mY), ImVec2 size = ImVec2(gContext.mWidth, gContext.mHeight)) { ImGuiIO& io = ImGui::GetIO(); matrix_t mViewProjInverse; mViewProjInverse.Inverse(gContext.mViewMat * gContext.mProjectionMat); float mox = ((io.MousePos.x - position.x) / size.x) * 2.f - 1.f; float moy = (1.f - ((io.MousePos.y - position.y) / size.y)) * 2.f - 1.f; rayOrigin.Transform(makeVect(mox, moy, 0.f, 1.f), mViewProjInverse); rayOrigin *= 1.f / rayOrigin.w; vec_t rayEnd; rayEnd.Transform(makeVect(mox, moy, 1.f - FLT_EPSILON, 1.f), mViewProjInverse); rayEnd *= 1.f / rayEnd.w; rayDir = Normalized(rayEnd - rayOrigin); } static float GetSegmentLengthClipSpace(const vec_t& start, const vec_t& end) { vec_t startOfSegment = start; startOfSegment.TransformPoint(gContext.mMVP); if (fabsf(startOfSegment.w) > FLT_EPSILON) // check for axis aligned with camera direction { startOfSegment *= 1.f / startOfSegment.w; } vec_t endOfSegment = end; endOfSegment.TransformPoint(gContext.mMVP); if (fabsf(endOfSegment.w) > FLT_EPSILON) // check for axis aligned with camera direction { endOfSegment *= 1.f / endOfSegment.w; } vec_t clipSpaceAxis = endOfSegment - startOfSegment; clipSpaceAxis.y /= gContext.mDisplayRatio; float segmentLengthInClipSpace = sqrtf(clipSpaceAxis.x * clipSpaceAxis.x + clipSpaceAxis.y * clipSpaceAxis.y); return segmentLengthInClipSpace; } static float GetParallelogram(const vec_t& ptO, const vec_t& ptA, const vec_t& ptB) { vec_t pts[] = { ptO, ptA, ptB }; for (unsigned int i = 0; i < 3; i++) { pts[i].TransformPoint(gContext.mMVP); if (fabsf(pts[i].w) > FLT_EPSILON) // check for axis aligned with camera direction { pts[i] *= 1.f / pts[i].w; } } vec_t segA = pts[1] - pts[0]; vec_t segB = pts[2] - pts[0]; segA.y /= gContext.mDisplayRatio; segB.y /= gContext.mDisplayRatio; vec_t segAOrtho = makeVect(-segA.y, segA.x); segAOrtho.Normalize(); float dt = segAOrtho.Dot3(segB); float surface = sqrtf(segA.x * segA.x + segA.y * segA.y) * fabsf(dt); return surface; } inline vec_t PointOnSegment(const vec_t& point, const vec_t& vertPos1, const vec_t& vertPos2) { vec_t c = point - vertPos1; vec_t V; V.Normalize(vertPos2 - vertPos1); float d = (vertPos2 - vertPos1).Length(); float t = V.Dot3(c); if (t < 0.f) { return vertPos1; } if (t > d) { return vertPos2; } return vertPos1 + V * t; } static float IntersectRayPlane(const vec_t& rOrigin, const vec_t& rVector, const vec_t& plan) { float numer = plan.Dot3(rOrigin) - plan.w; float denom = plan.Dot3(rVector); if (fabsf(denom) < FLT_EPSILON) // normal is orthogonal to vector, cant intersect { return -1.0f; } return -(numer / denom); } static float DistanceToPlane(const vec_t& point, const vec_t& plan) { return plan.Dot3(point) + plan.w; } static bool IsInContextRect(ImVec2 p) { return IsWithin(p.x, gContext.mX, gContext.mXMax) && IsWithin(p.y, gContext.mY, gContext.mYMax); } void SetRect(float x, float y, float width, float height) { gContext.mX = x; gContext.mY = y; gContext.mWidth = width; gContext.mHeight = height; gContext.mXMax = gContext.mX + gContext.mWidth; gContext.mYMax = gContext.mY + gContext.mXMax; gContext.mDisplayRatio = width / height; } void SetOrthographic(bool isOrthographic) { gContext.mIsOrthographic = isOrthographic; } void SetDrawlist(ImDrawList* drawlist) { gContext.mDrawList = drawlist ? drawlist : ImGui::GetWindowDrawList(); } void BeginFrame() { ImGuiIO& io = ImGui::GetIO(); const ImU32 flags = ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoScrollbar | ImGuiWindowFlags_NoInputs | ImGuiWindowFlags_NoSavedSettings | ImGuiWindowFlags_NoFocusOnAppearing | ImGuiWindowFlags_NoBringToFrontOnFocus; #ifdef IMGUI_HAS_VIEWPORT ImGui::SetNextWindowSize(ImGui::GetMainViewport()->Size); ImGui::SetNextWindowPos(ImGui::GetMainViewport()->Pos); #else ImGui::SetNextWindowSize(io.DisplaySize); ImGui::SetNextWindowPos(ImVec2(0, 0)); #endif ImGui::PushStyleColor(ImGuiCol_WindowBg, 0); ImGui::PushStyleColor(ImGuiCol_Border, 0); ImGui::PushStyleVar(ImGuiStyleVar_WindowRounding, 0.0f); ImGui::Begin("gizmo", NULL, flags); gContext.mDrawList = ImGui::GetWindowDrawList(); ImGui::End(); ImGui::PopStyleVar(); ImGui::PopStyleColor(2); } bool IsUsing() { return gContext.mbUsing || gContext.mbUsingBounds; } bool IsOver() { return (gContext.mOperation == TRANSLATE && GetMoveType(NULL) != NONE) || (gContext.mOperation == ROTATE && GetRotateType() != NONE) || (gContext.mOperation == SCALE && GetScaleType() != NONE) || IsUsing(); } bool IsOver(OPERATION op) { switch (op) { case SCALE: return GetScaleType() != NONE || IsUsing(); case ROTATE: return GetRotateType() != NONE || IsUsing(); case TRANSLATE: return GetMoveType(NULL) != NONE || IsUsing(); } return false; } void Enable(bool enable) { gContext.mbEnable = enable; if (!enable) { gContext.mbUsing = false; gContext.mbUsingBounds = false; } } static float GetUniform(const vec_t& position, const matrix_t& mat) { vec_t trf = makeVect(position.x, position.y, position.z, 1.f); trf.Transform(mat); return trf.w; } static void ComputeContext(const float* view, const float* projection, float* matrix, MODE mode) { gContext.mMode = mode; gContext.mViewMat = *(matrix_t*)view; gContext.mProjectionMat = *(matrix_t*)projection; if (mode == LOCAL) { gContext.mModel = *(matrix_t*)matrix; gContext.mModel.OrthoNormalize(); } else { gContext.mModel.Translation(((matrix_t*)matrix)->v.position); } gContext.mModelSource = *(matrix_t*)matrix; gContext.mModelScaleOrigin.Set(gContext.mModelSource.v.right.Length(), gContext.mModelSource.v.up.Length(), gContext.mModelSource.v.dir.Length()); gContext.mModelInverse.Inverse(gContext.mModel); gContext.mModelSourceInverse.Inverse(gContext.mModelSource); gContext.mViewProjection = gContext.mViewMat * gContext.mProjectionMat; gContext.mMVP = gContext.mModel * gContext.mViewProjection; matrix_t viewInverse; viewInverse.Inverse(gContext.mViewMat); gContext.mCameraDir = viewInverse.v.dir; gContext.mCameraEye = viewInverse.v.position; gContext.mCameraRight = viewInverse.v.right; gContext.mCameraUp = viewInverse.v.up; // compute scale from the size of camera right vector projected on screen at the matrix position vec_t pointRight = viewInverse.v.right; pointRight.TransformPoint(gContext.mViewProjection); gContext.mScreenFactor = gGizmoSizeClipSpace / (pointRight.x / pointRight.w - gContext.mMVP.v.position.x / gContext.mMVP.v.position.w); vec_t rightViewInverse = viewInverse.v.right; rightViewInverse.TransformVector(gContext.mModelInverse); float rightLength = GetSegmentLengthClipSpace(makeVect(0.f, 0.f), rightViewInverse); gContext.mScreenFactor = gGizmoSizeClipSpace / rightLength; ImVec2 centerSSpace = worldToPos(makeVect(0.f, 0.f), gContext.mMVP); gContext.mScreenSquareCenter = centerSSpace; gContext.mScreenSquareMin = ImVec2(centerSSpace.x - 10.f, centerSSpace.y - 10.f); gContext.mScreenSquareMax = ImVec2(centerSSpace.x + 10.f, centerSSpace.y + 10.f); ComputeCameraRay(gContext.mRayOrigin, gContext.mRayVector); } static void ComputeColors(ImU32* colors, int type, OPERATION operation) { if (gContext.mbEnable) { switch (operation) { case TRANSLATE: colors[0] = (type == MOVE_SCREEN) ? selectionColor : 0xFFFFFFFF; for (int i = 0; i < 3; i++) { colors[i + 1] = (type == (int)(MOVE_X + i)) ? selectionColor : directionColor[i]; colors[i + 4] = (type == (int)(MOVE_YZ + i)) ? selectionColor : planeColor[i]; colors[i + 4] = (type == MOVE_SCREEN) ? selectionColor : colors[i + 4]; } break; case ROTATE: colors[0] = (type == ROTATE_SCREEN) ? selectionColor : 0xFFFFFFFF; for (int i = 0; i < 3; i++) { colors[i + 1] = (type == (int)(ROTATE_X + i)) ? selectionColor : directionColor[i]; } break; case SCALE: colors[0] = (type == SCALE_XYZ) ? selectionColor : 0xFFFFFFFF; for (int i = 0; i < 3; i++) { colors[i + 1] = (type == (int)(SCALE_X + i)) ? selectionColor : directionColor[i]; } break; case BOUNDS: break; } } else { for (int i = 0; i < 7; i++) { colors[i] = inactiveColor; } } } static void ComputeTripodAxisAndVisibility(int axisIndex, vec_t& dirAxis, vec_t& dirPlaneX, vec_t& dirPlaneY, bool& belowAxisLimit, bool& belowPlaneLimit) { dirAxis = directionUnary[axisIndex]; dirPlaneX = directionUnary[(axisIndex + 1) % 3]; dirPlaneY = directionUnary[(axisIndex + 2) % 3]; if (gContext.mbUsing && (gContext.mActualID == -1 || gContext.mActualID == gContext.mEditingID)) { // when using, use stored factors so the gizmo doesn't flip when we translate belowAxisLimit = gContext.mBelowAxisLimit[axisIndex]; belowPlaneLimit = gContext.mBelowPlaneLimit[axisIndex]; dirAxis *= gContext.mAxisFactor[axisIndex]; dirPlaneX *= gContext.mAxisFactor[(axisIndex + 1) % 3]; dirPlaneY *= gContext.mAxisFactor[(axisIndex + 2) % 3]; } else { // new method float lenDir = GetSegmentLengthClipSpace(makeVect(0.f, 0.f, 0.f), dirAxis); float lenDirMinus = GetSegmentLengthClipSpace(makeVect(0.f, 0.f, 0.f), -dirAxis); float lenDirPlaneX = GetSegmentLengthClipSpace(makeVect(0.f, 0.f, 0.f), dirPlaneX); float lenDirMinusPlaneX = GetSegmentLengthClipSpace(makeVect(0.f, 0.f, 0.f), -dirPlaneX); float lenDirPlaneY = GetSegmentLengthClipSpace(makeVect(0.f, 0.f, 0.f), dirPlaneY); float lenDirMinusPlaneY = GetSegmentLengthClipSpace(makeVect(0.f, 0.f, 0.f), -dirPlaneY); float mulAxis = (lenDir < lenDirMinus && fabsf(lenDir - lenDirMinus) > FLT_EPSILON) ? -1.f : 1.f; float mulAxisX = (lenDirPlaneX < lenDirMinusPlaneX && fabsf(lenDirPlaneX - lenDirMinusPlaneX) > FLT_EPSILON) ? -1.f : 1.f; float mulAxisY = (lenDirPlaneY < lenDirMinusPlaneY && fabsf(lenDirPlaneY - lenDirMinusPlaneY) > FLT_EPSILON) ? -1.f : 1.f; dirAxis *= mulAxis; dirPlaneX *= mulAxisX; dirPlaneY *= mulAxisY; // for axis float axisLengthInClipSpace = GetSegmentLengthClipSpace(makeVect(0.f, 0.f, 0.f), dirAxis * gContext.mScreenFactor); float paraSurf = GetParallelogram(makeVect(0.f, 0.f, 0.f), dirPlaneX * gContext.mScreenFactor, dirPlaneY * gContext.mScreenFactor); belowPlaneLimit = (paraSurf > 0.0025f); belowAxisLimit = (axisLengthInClipSpace > 0.02f); // and store values gContext.mAxisFactor[axisIndex] = mulAxis; gContext.mAxisFactor[(axisIndex + 1) % 3] = mulAxisX; gContext.mAxisFactor[(axisIndex + 2) % 3] = mulAxisY; gContext.mBelowAxisLimit[axisIndex] = belowAxisLimit; gContext.mBelowPlaneLimit[axisIndex] = belowPlaneLimit; } } static void ComputeSnap(float* value, float snap) { if (snap <= FLT_EPSILON) { return; } float modulo = fmodf(*value, snap); float moduloRatio = fabsf(modulo) / snap; if (moduloRatio < snapTension) { *value -= modulo; } else if (moduloRatio > (1.f - snapTension)) { *value = *value - modulo + snap * ((*value < 0.f) ? -1.f : 1.f); } } static void ComputeSnap(vec_t& value, float* snap) { for (int i = 0; i < 3; i++) { ComputeSnap(&value[i], snap[i]); } } static float ComputeAngleOnPlan() { const float len = IntersectRayPlane(gContext.mRayOrigin, gContext.mRayVector, gContext.mTranslationPlan); vec_t localPos = Normalized(gContext.mRayOrigin + gContext.mRayVector * len - gContext.mModel.v.position); vec_t perpendicularVector; perpendicularVector.Cross(gContext.mRotationVectorSource, gContext.mTranslationPlan); perpendicularVector.Normalize(); float acosAngle = Clamp(Dot(localPos, gContext.mRotationVectorSource), -1.f, 1.f); float angle = acosf(acosAngle); angle *= (Dot(localPos, perpendicularVector) < 0.f) ? 1.f : -1.f; return angle; } static void DrawRotationGizmo(int type) { ImDrawList* drawList = gContext.mDrawList; // colors ImU32 colors[7]; ComputeColors(colors, type, ROTATE); vec_t cameraToModelNormalized; if (gContext.mIsOrthographic) { matrix_t viewInverse; viewInverse.Inverse(*(matrix_t*)&gContext.mViewMat); cameraToModelNormalized = viewInverse.v.dir; } else { cameraToModelNormalized = Normalized(gContext.mModel.v.position - gContext.mCameraEye); } cameraToModelNormalized.TransformVector(gContext.mModelInverse); gContext.mRadiusSquareCenter = screenRotateSize * gContext.mHeight; for (int axis = 0; axis < 3; axis++) { ImVec2 circlePos[halfCircleSegmentCount]; float angleStart = atan2f(cameraToModelNormalized[(4 - axis) % 3], cameraToModelNormalized[(3 - axis) % 3]) + ZPI * 0.5f; for (unsigned int i = 0; i < halfCircleSegmentCount; i++) { float ng = angleStart + ZPI * ((float)i / (float)halfCircleSegmentCount); vec_t axisPos = makeVect(cosf(ng), sinf(ng), 0.f); vec_t pos = makeVect(axisPos[axis], axisPos[(axis + 1) % 3], axisPos[(axis + 2) % 3]) * gContext.mScreenFactor; circlePos[i] = worldToPos(pos, gContext.mMVP); } float radiusAxis = sqrtf((ImLengthSqr(worldToPos(gContext.mModel.v.position, gContext.mViewProjection) - circlePos[0]))); if (radiusAxis > gContext.mRadiusSquareCenter) { gContext.mRadiusSquareCenter = radiusAxis; } drawList->AddPolyline(circlePos, halfCircleSegmentCount, colors[3 - axis], false, 2); } drawList->AddCircle(worldToPos(gContext.mModel.v.position, gContext.mViewProjection), gContext.mRadiusSquareCenter, colors[0], 64, 3.f); if (gContext.mbUsing && (gContext.mActualID == -1 || gContext.mActualID == gContext.mEditingID)) { ImVec2 circlePos[halfCircleSegmentCount + 1]; circlePos[0] = worldToPos(gContext.mModel.v.position, gContext.mViewProjection); for (unsigned int i = 1; i < halfCircleSegmentCount; i++) { float ng = gContext.mRotationAngle * ((float)(i - 1) / (float)(halfCircleSegmentCount - 1)); matrix_t rotateVectorMatrix; rotateVectorMatrix.RotationAxis(gContext.mTranslationPlan, ng); vec_t pos; pos.TransformPoint(gContext.mRotationVectorSource, rotateVectorMatrix); pos *= gContext.mScreenFactor; circlePos[i] = worldToPos(pos + gContext.mModel.v.position, gContext.mViewProjection); } drawList->AddConvexPolyFilled(circlePos, halfCircleSegmentCount, 0x801080FF); drawList->AddPolyline(circlePos, halfCircleSegmentCount, 0xFF1080FF, true, 2); ImVec2 destinationPosOnScreen = circlePos[1]; char tmps[512]; ImFormatString(tmps, sizeof(tmps), rotationInfoMask[type - ROTATE_X], (gContext.mRotationAngle / ZPI) * 180.f, gContext.mRotationAngle); drawList->AddText(ImVec2(destinationPosOnScreen.x + 15, destinationPosOnScreen.y + 15), 0xFF000000, tmps); drawList->AddText(ImVec2(destinationPosOnScreen.x + 14, destinationPosOnScreen.y + 14), 0xFFFFFFFF, tmps); } } static void DrawHatchedAxis(const vec_t& axis) { for (int j = 1; j < 10; j++) { ImVec2 baseSSpace2 = worldToPos(axis * 0.05f * (float)(j * 2) * gContext.mScreenFactor, gContext.mMVP); ImVec2 worldDirSSpace2 = worldToPos(axis * 0.05f * (float)(j * 2 + 1) * gContext.mScreenFactor, gContext.mMVP); gContext.mDrawList->AddLine(baseSSpace2, worldDirSSpace2, 0x80000000, 6.f); } } static void DrawScaleGizmo(int type) { ImDrawList* drawList = gContext.mDrawList; // colors ImU32 colors[7]; ComputeColors(colors, type, SCALE); // draw vec_t scaleDisplay = { 1.f, 1.f, 1.f, 1.f }; if (gContext.mbUsing && (gContext.mActualID == -1 || gContext.mActualID == gContext.mEditingID)) { scaleDisplay = gContext.mScale; } for (unsigned int i = 0; i < 3; i++) { vec_t dirPlaneX, dirPlaneY, dirAxis; bool belowAxisLimit, belowPlaneLimit; ComputeTripodAxisAndVisibility(i, dirAxis, dirPlaneX, dirPlaneY, belowAxisLimit, belowPlaneLimit); // draw axis if (belowAxisLimit) { ImVec2 baseSSpace = worldToPos(dirAxis * 0.1f * gContext.mScreenFactor, gContext.mMVP); ImVec2 worldDirSSpaceNoScale = worldToPos(dirAxis * gContext.mScreenFactor, gContext.mMVP); ImVec2 worldDirSSpace = worldToPos((dirAxis * scaleDisplay[i]) * gContext.mScreenFactor, gContext.mMVP); if (gContext.mbUsing && (gContext.mActualID == -1 || gContext.mActualID == gContext.mEditingID)) { drawList->AddLine(baseSSpace, worldDirSSpaceNoScale, 0xFF404040, 3.f); drawList->AddCircleFilled(worldDirSSpaceNoScale, 6.f, 0xFF404040); } drawList->AddLine(baseSSpace, worldDirSSpace, colors[i + 1], 3.f); drawList->AddCircleFilled(worldDirSSpace, 6.f, colors[i + 1]); if (gContext.mAxisFactor[i] < 0.f) { DrawHatchedAxis(dirAxis * scaleDisplay[i]); } } } // draw screen cirle drawList->AddCircleFilled(gContext.mScreenSquareCenter, 6.f, colors[0], 32); if (gContext.mbUsing && (gContext.mActualID == -1 || gContext.mActualID == gContext.mEditingID)) { //ImVec2 sourcePosOnScreen = worldToPos(gContext.mMatrixOrigin, gContext.mViewProjection); ImVec2 destinationPosOnScreen = worldToPos(gContext.mModel.v.position, gContext.mViewProjection); /*vec_t dif(destinationPosOnScreen.x - sourcePosOnScreen.x, destinationPosOnScreen.y - sourcePosOnScreen.y); dif.Normalize(); dif *= 5.f; drawList->AddCircle(sourcePosOnScreen, 6.f, translationLineColor); drawList->AddCircle(destinationPosOnScreen, 6.f, translationLineColor); drawList->AddLine(ImVec2(sourcePosOnScreen.x + dif.x, sourcePosOnScreen.y + dif.y), ImVec2(destinationPosOnScreen.x - dif.x, destinationPosOnScreen.y - dif.y), translationLineColor, 2.f); */ char tmps[512]; //vec_t deltaInfo = gContext.mModel.v.position - gContext.mMatrixOrigin; int componentInfoIndex = (type - SCALE_X) * 3; ImFormatString(tmps, sizeof(tmps), scaleInfoMask[type - SCALE_X], scaleDisplay[translationInfoIndex[componentInfoIndex]]); drawList->AddText(ImVec2(destinationPosOnScreen.x + 15, destinationPosOnScreen.y + 15), 0xFF000000, tmps); drawList->AddText(ImVec2(destinationPosOnScreen.x + 14, destinationPosOnScreen.y + 14), 0xFFFFFFFF, tmps); } } static void DrawTranslationGizmo(int type) { ImDrawList* drawList = gContext.mDrawList; if (!drawList) { return; } // colors ImU32 colors[7]; ComputeColors(colors, type, TRANSLATE); const ImVec2 origin = worldToPos(gContext.mModel.v.position, gContext.mViewProjection); // draw bool belowAxisLimit = false; bool belowPlaneLimit = false; for (unsigned int i = 0; i < 3; ++i) { vec_t dirPlaneX, dirPlaneY, dirAxis; ComputeTripodAxisAndVisibility(i, dirAxis, dirPlaneX, dirPlaneY, belowAxisLimit, belowPlaneLimit); // draw axis if (belowAxisLimit) { ImVec2 baseSSpace = worldToPos(dirAxis * 0.1f * gContext.mScreenFactor, gContext.mMVP); ImVec2 worldDirSSpace = worldToPos(dirAxis * gContext.mScreenFactor, gContext.mMVP); drawList->AddLine(baseSSpace, worldDirSSpace, colors[i + 1], 3.f); // Arrow head begin ImVec2 dir(origin - worldDirSSpace); float d = sqrtf(ImLengthSqr(dir)); dir /= d; // Normalize dir *= 6.0f; ImVec2 ortogonalDir(dir.y, -dir.x); // Perpendicular vector ImVec2 a(worldDirSSpace + dir); drawList->AddTriangleFilled(worldDirSSpace - dir, a + ortogonalDir, a - ortogonalDir, colors[i + 1]); // Arrow head end if (gContext.mAxisFactor[i] < 0.f) { DrawHatchedAxis(dirAxis); } } // draw plane if (belowPlaneLimit) { ImVec2 screenQuadPts[4]; for (int j = 0; j < 4; ++j) { vec_t cornerWorldPos = (dirPlaneX * quadUV[j * 2] + dirPlaneY * quadUV[j * 2 + 1]) * gContext.mScreenFactor; screenQuadPts[j] = worldToPos(cornerWorldPos, gContext.mMVP); } drawList->AddPolyline(screenQuadPts, 4, directionColor[i], true, 1.0f); drawList->AddConvexPolyFilled(screenQuadPts, 4, colors[i + 4]); } } drawList->AddCircleFilled(gContext.mScreenSquareCenter, 6.f, colors[0], 32); if (gContext.mbUsing && (gContext.mActualID == -1 || gContext.mActualID == gContext.mEditingID)) { ImVec2 sourcePosOnScreen = worldToPos(gContext.mMatrixOrigin, gContext.mViewProjection); ImVec2 destinationPosOnScreen = worldToPos(gContext.mModel.v.position, gContext.mViewProjection); vec_t dif = { destinationPosOnScreen.x - sourcePosOnScreen.x, destinationPosOnScreen.y - sourcePosOnScreen.y, 0.f, 0.f }; dif.Normalize(); dif *= 5.f; drawList->AddCircle(sourcePosOnScreen, 6.f, translationLineColor); drawList->AddCircle(destinationPosOnScreen, 6.f, translationLineColor); drawList->AddLine(ImVec2(sourcePosOnScreen.x + dif.x, sourcePosOnScreen.y + dif.y), ImVec2(destinationPosOnScreen.x - dif.x, destinationPosOnScreen.y - dif.y), translationLineColor, 2.f); char tmps[512]; vec_t deltaInfo = gContext.mModel.v.position - gContext.mMatrixOrigin; int componentInfoIndex = (type - MOVE_X) * 3; ImFormatString(tmps, sizeof(tmps), translationInfoMask[type - MOVE_X], deltaInfo[translationInfoIndex[componentInfoIndex]], deltaInfo[translationInfoIndex[componentInfoIndex + 1]], deltaInfo[translationInfoIndex[componentInfoIndex + 2]]); drawList->AddText(ImVec2(destinationPosOnScreen.x + 15, destinationPosOnScreen.y + 15), 0xFF000000, tmps); drawList->AddText(ImVec2(destinationPosOnScreen.x + 14, destinationPosOnScreen.y + 14), 0xFFFFFFFF, tmps); } } static bool CanActivate() { if (ImGui::IsMouseClicked(0) && !ImGui::IsAnyItemHovered() && !ImGui::IsAnyItemActive()) { return true; } return false; } static void HandleAndDrawLocalBounds(float* bounds, matrix_t* matrix, float* snapValues, OPERATION operation) { ImGuiIO& io = ImGui::GetIO(); ImDrawList* drawList = gContext.mDrawList; // compute best projection axis vec_t axesWorldDirections[3]; vec_t bestAxisWorldDirection = { 0.0f, 0.0f, 0.0f, 0.0f }; int axes[3]; unsigned int numAxes = 1; axes[0] = gContext.mBoundsBestAxis; int bestAxis = axes[0]; if (!gContext.mbUsingBounds) { numAxes = 0; float bestDot = 0.f; for (unsigned int i = 0; i < 3; i++) { vec_t dirPlaneNormalWorld; dirPlaneNormalWorld.TransformVector(directionUnary[i], gContext.mModelSource); dirPlaneNormalWorld.Normalize(); float dt = fabsf(Dot(Normalized(gContext.mCameraEye - gContext.mModelSource.v.position), dirPlaneNormalWorld)); if (dt >= bestDot) { bestDot = dt; bestAxis = i; bestAxisWorldDirection = dirPlaneNormalWorld; } if (dt >= 0.1f) { axes[numAxes] = i; axesWorldDirections[numAxes] = dirPlaneNormalWorld; ++numAxes; } } } if (numAxes == 0) { axes[0] = bestAxis; axesWorldDirections[0] = bestAxisWorldDirection; numAxes = 1; } else if (bestAxis != axes[0]) { unsigned int bestIndex = 0; for (unsigned int i = 0; i < numAxes; i++) { if (axes[i] == bestAxis) { bestIndex = i; break; } } int tempAxis = axes[0]; axes[0] = axes[bestIndex]; axes[bestIndex] = tempAxis; vec_t tempDirection = axesWorldDirections[0]; axesWorldDirections[0] = axesWorldDirections[bestIndex]; axesWorldDirections[bestIndex] = tempDirection; } for (unsigned int axisIndex = 0; axisIndex < numAxes; ++axisIndex) { bestAxis = axes[axisIndex]; bestAxisWorldDirection = axesWorldDirections[axisIndex]; // corners vec_t aabb[4]; int secondAxis = (bestAxis + 1) % 3; int thirdAxis = (bestAxis + 2) % 3; for (int i = 0; i < 4; i++) { aabb[i][3] = aabb[i][bestAxis] = 0.f; aabb[i][secondAxis] = bounds[secondAxis + 3 * (i >> 1)]; aabb[i][thirdAxis] = bounds[thirdAxis + 3 * ((i >> 1) ^ (i & 1))]; } // draw bounds unsigned int anchorAlpha = gContext.mbEnable ? 0xFF000000 : 0x80000000; matrix_t boundsMVP = gContext.mModelSource * gContext.mViewProjection; for (int i = 0; i < 4; i++) { ImVec2 worldBound1 = worldToPos(aabb[i], boundsMVP); ImVec2 worldBound2 = worldToPos(aabb[(i + 1) % 4], boundsMVP); if (!IsInContextRect(worldBound1) || !IsInContextRect(worldBound2)) { continue; } float boundDistance = sqrtf(ImLengthSqr(worldBound1 - worldBound2)); int stepCount = (int)(boundDistance / 10.f); stepCount = min(stepCount, 1000); float stepLength = 1.f / (float)stepCount; for (int j = 0; j < stepCount; j++) { float t1 = (float)j * stepLength; float t2 = (float)j * stepLength + stepLength * 0.5f; ImVec2 worldBoundSS1 = ImLerp(worldBound1, worldBound2, ImVec2(t1, t1)); ImVec2 worldBoundSS2 = ImLerp(worldBound1, worldBound2, ImVec2(t2, t2)); //drawList->AddLine(worldBoundSS1, worldBoundSS2, 0x000000 + anchorAlpha, 3.f); drawList->AddLine(worldBoundSS1, worldBoundSS2, 0xAAAAAA + anchorAlpha, 2.f); } vec_t midPoint = (aabb[i] + aabb[(i + 1) % 4]) * 0.5f; ImVec2 midBound = worldToPos(midPoint, boundsMVP); static const float AnchorBigRadius = 8.f; static const float AnchorSmallRadius = 6.f; bool overBigAnchor = ImLengthSqr(worldBound1 - io.MousePos) <= (AnchorBigRadius * AnchorBigRadius); bool overSmallAnchor = ImLengthSqr(midBound - io.MousePos) <= (AnchorBigRadius * AnchorBigRadius); int type = NONE; vec_t gizmoHitProportion; switch (operation) { case TRANSLATE: type = GetMoveType(&gizmoHitProportion); break; case ROTATE: type = GetRotateType(); break; case SCALE: type = GetScaleType(); break; case BOUNDS: break; } if (type != NONE) { overBigAnchor = false; overSmallAnchor = false; } unsigned int bigAnchorColor = overBigAnchor ? selectionColor : (0xAAAAAA + anchorAlpha); unsigned int smallAnchorColor = overSmallAnchor ? selectionColor : (0xAAAAAA + anchorAlpha); drawList->AddCircleFilled(worldBound1, AnchorBigRadius, 0xFF000000); drawList->AddCircleFilled(worldBound1, AnchorBigRadius - 1.2f, bigAnchorColor); drawList->AddCircleFilled(midBound, AnchorSmallRadius, 0xFF000000); drawList->AddCircleFilled(midBound, AnchorSmallRadius - 1.2f, smallAnchorColor); int oppositeIndex = (i + 2) % 4; // big anchor on corners if (!gContext.mbUsingBounds && gContext.mbEnable && overBigAnchor && CanActivate()) { gContext.mBoundsPivot.TransformPoint(aabb[(i + 2) % 4], gContext.mModelSource); gContext.mBoundsAnchor.TransformPoint(aabb[i], gContext.mModelSource); gContext.mBoundsPlan = BuildPlan(gContext.mBoundsAnchor, bestAxisWorldDirection); gContext.mBoundsBestAxis = bestAxis; gContext.mBoundsAxis[0] = secondAxis; gContext.mBoundsAxis[1] = thirdAxis; gContext.mBoundsLocalPivot.Set(0.f); gContext.mBoundsLocalPivot[secondAxis] = aabb[oppositeIndex][secondAxis]; gContext.mBoundsLocalPivot[thirdAxis] = aabb[oppositeIndex][thirdAxis]; gContext.mbUsingBounds = true; gContext.mEditingID = gContext.mActualID; gContext.mBoundsMatrix = gContext.mModelSource; } // small anchor on middle of segment if (!gContext.mbUsingBounds && gContext.mbEnable && overSmallAnchor && CanActivate()) { vec_t midPointOpposite = (aabb[(i + 2) % 4] + aabb[(i + 3) % 4]) * 0.5f; gContext.mBoundsPivot.TransformPoint(midPointOpposite, gContext.mModelSource); gContext.mBoundsAnchor.TransformPoint(midPoint, gContext.mModelSource); gContext.mBoundsPlan = BuildPlan(gContext.mBoundsAnchor, bestAxisWorldDirection); gContext.mBoundsBestAxis = bestAxis; int indices[] = { secondAxis , thirdAxis }; gContext.mBoundsAxis[0] = indices[i % 2]; gContext.mBoundsAxis[1] = -1; gContext.mBoundsLocalPivot.Set(0.f); gContext.mBoundsLocalPivot[gContext.mBoundsAxis[0]] = aabb[oppositeIndex][indices[i % 2]];// bounds[gContext.mBoundsAxis[0]] * (((i + 1) & 2) ? 1.f : -1.f); gContext.mbUsingBounds = true; gContext.mEditingID = gContext.mActualID; gContext.mBoundsMatrix = gContext.mModelSource; } } if (gContext.mbUsingBounds && (gContext.mActualID == -1 || gContext.mActualID == gContext.mEditingID)) { matrix_t scale; scale.SetToIdentity(); // compute projected mouse position on plan const float len = IntersectRayPlane(gContext.mRayOrigin, gContext.mRayVector, gContext.mBoundsPlan); vec_t newPos = gContext.mRayOrigin + gContext.mRayVector * len; // compute a reference and delta vectors base on mouse move vec_t deltaVector = (newPos - gContext.mBoundsPivot).Abs(); vec_t referenceVector = (gContext.mBoundsAnchor - gContext.mBoundsPivot).Abs(); // for 1 or 2 axes, compute a ratio that's used for scale and snap it based on resulting length for (int i = 0; i < 2; i++) { int axisIndex1 = gContext.mBoundsAxis[i]; if (axisIndex1 == -1) { continue; } float ratioAxis = 1.f; vec_t axisDir = gContext.mBoundsMatrix.component[axisIndex1].Abs(); float dtAxis = axisDir.Dot(referenceVector); float boundSize = bounds[axisIndex1 + 3] - bounds[axisIndex1]; if (dtAxis > FLT_EPSILON) { ratioAxis = axisDir.Dot(deltaVector) / dtAxis; } if (snapValues) { float length = boundSize * ratioAxis; ComputeSnap(&length, snapValues[axisIndex1]); if (boundSize > FLT_EPSILON) { ratioAxis = length / boundSize; } } scale.component[axisIndex1] *= ratioAxis; } // transform matrix matrix_t preScale, postScale; preScale.Translation(-gContext.mBoundsLocalPivot); postScale.Translation(gContext.mBoundsLocalPivot); matrix_t res = preScale * scale * postScale * gContext.mBoundsMatrix; *matrix = res; // info text char tmps[512]; ImVec2 destinationPosOnScreen = worldToPos(gContext.mModel.v.position, gContext.mViewProjection); ImFormatString(tmps, sizeof(tmps), "X: %.2f Y: %.2f Z:%.2f" , (bounds[3] - bounds[0]) * gContext.mBoundsMatrix.component[0].Length() * scale.component[0].Length() , (bounds[4] - bounds[1]) * gContext.mBoundsMatrix.component[1].Length() * scale.component[1].Length() , (bounds[5] - bounds[2]) * gContext.mBoundsMatrix.component[2].Length() * scale.component[2].Length() ); drawList->AddText(ImVec2(destinationPosOnScreen.x + 15, destinationPosOnScreen.y + 15), 0xFF000000, tmps); drawList->AddText(ImVec2(destinationPosOnScreen.x + 14, destinationPosOnScreen.y + 14), 0xFFFFFFFF, tmps); } if (!io.MouseDown[0]) { gContext.mbUsingBounds = false; gContext.mEditingID = -1; } if (gContext.mbUsingBounds) { break; } } } /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // static int GetScaleType() { ImGuiIO& io = ImGui::GetIO(); int type = NONE; // screen if (io.MousePos.x >= gContext.mScreenSquareMin.x && io.MousePos.x <= gContext.mScreenSquareMax.x && io.MousePos.y >= gContext.mScreenSquareMin.y && io.MousePos.y <= gContext.mScreenSquareMax.y) { type = SCALE_XYZ; } // compute for (unsigned int i = 0; i < 3 && type == NONE; i++) { vec_t dirPlaneX, dirPlaneY, dirAxis; bool belowAxisLimit, belowPlaneLimit; ComputeTripodAxisAndVisibility(i, dirAxis, dirPlaneX, dirPlaneY, belowAxisLimit, belowPlaneLimit); dirAxis.TransformVector(gContext.mModel); dirPlaneX.TransformVector(gContext.mModel); dirPlaneY.TransformVector(gContext.mModel); const float len = IntersectRayPlane(gContext.mRayOrigin, gContext.mRayVector, BuildPlan(gContext.mModel.v.position, dirAxis)); vec_t posOnPlan = gContext.mRayOrigin + gContext.mRayVector * len; const ImVec2 posOnPlanScreen = worldToPos(posOnPlan, gContext.mViewProjection); const ImVec2 axisStartOnScreen = worldToPos(gContext.mModel.v.position + dirAxis * gContext.mScreenFactor * 0.1f, gContext.mViewProjection); const ImVec2 axisEndOnScreen = worldToPos(gContext.mModel.v.position + dirAxis * gContext.mScreenFactor, gContext.mViewProjection); vec_t closestPointOnAxis = PointOnSegment(makeVect(posOnPlanScreen), makeVect(axisStartOnScreen), makeVect(axisEndOnScreen)); if ((closestPointOnAxis - makeVect(posOnPlanScreen)).Length() < 12.f) // pixel size { type = SCALE_X + i; } } return type; } static int GetRotateType() { ImGuiIO& io = ImGui::GetIO(); int type = NONE; vec_t deltaScreen = { io.MousePos.x - gContext.mScreenSquareCenter.x, io.MousePos.y - gContext.mScreenSquareCenter.y, 0.f, 0.f }; float dist = deltaScreen.Length(); if (dist >= (gContext.mRadiusSquareCenter - 1.0f) && dist < (gContext.mRadiusSquareCenter + 1.0f)) { type = ROTATE_SCREEN; } const vec_t planNormals[] = { gContext.mModel.v.right, gContext.mModel.v.up, gContext.mModel.v.dir }; for (unsigned int i = 0; i < 3 && type == NONE; i++) { // pickup plan vec_t pickupPlan = BuildPlan(gContext.mModel.v.position, planNormals[i]); const float len = IntersectRayPlane(gContext.mRayOrigin, gContext.mRayVector, pickupPlan); vec_t localPos = gContext.mRayOrigin + gContext.mRayVector * len - gContext.mModel.v.position; if (Dot(Normalized(localPos), gContext.mRayVector) > FLT_EPSILON) { continue; } vec_t idealPosOnCircle = Normalized(localPos); idealPosOnCircle.TransformVector(gContext.mModelInverse); ImVec2 idealPosOnCircleScreen = worldToPos(idealPosOnCircle * gContext.mScreenFactor, gContext.mMVP); //gContext.mDrawList->AddCircle(idealPosOnCircleScreen, 5.f, 0xFFFFFFFF); ImVec2 distanceOnScreen = idealPosOnCircleScreen - io.MousePos; float distance = makeVect(distanceOnScreen).Length(); if (distance < 8.f) // pixel size { type = ROTATE_X + i; } } return type; } static int GetMoveType(vec_t* gizmoHitProportion) { ImGuiIO& io = ImGui::GetIO(); int type = NONE; // screen if (io.MousePos.x >= gContext.mScreenSquareMin.x && io.MousePos.x <= gContext.mScreenSquareMax.x && io.MousePos.y >= gContext.mScreenSquareMin.y && io.MousePos.y <= gContext.mScreenSquareMax.y) { type = MOVE_SCREEN; } // compute for (unsigned int i = 0; i < 3 && type == NONE; i++) { vec_t dirPlaneX, dirPlaneY, dirAxis; bool belowAxisLimit, belowPlaneLimit; ComputeTripodAxisAndVisibility(i, dirAxis, dirPlaneX, dirPlaneY, belowAxisLimit, belowPlaneLimit); dirAxis.TransformVector(gContext.mModel); dirPlaneX.TransformVector(gContext.mModel); dirPlaneY.TransformVector(gContext.mModel); const float len = IntersectRayPlane(gContext.mRayOrigin, gContext.mRayVector, BuildPlan(gContext.mModel.v.position, dirAxis)); vec_t posOnPlan = gContext.mRayOrigin + gContext.mRayVector * len; const ImVec2 posOnPlanScreen = worldToPos(posOnPlan, gContext.mViewProjection); const ImVec2 axisStartOnScreen = worldToPos(gContext.mModel.v.position + dirAxis * gContext.mScreenFactor * 0.1f, gContext.mViewProjection); const ImVec2 axisEndOnScreen = worldToPos(gContext.mModel.v.position + dirAxis * gContext.mScreenFactor, gContext.mViewProjection); vec_t closestPointOnAxis = PointOnSegment(makeVect(posOnPlanScreen), makeVect(axisStartOnScreen), makeVect(axisEndOnScreen)); if ((closestPointOnAxis - makeVect(posOnPlanScreen)).Length() < 12.f) // pixel size { type = MOVE_X + i; } const float dx = dirPlaneX.Dot3((posOnPlan - gContext.mModel.v.position) * (1.f / gContext.mScreenFactor)); const float dy = dirPlaneY.Dot3((posOnPlan - gContext.mModel.v.position) * (1.f / gContext.mScreenFactor)); if (belowPlaneLimit && dx >= quadUV[0] && dx <= quadUV[4] && dy >= quadUV[1] && dy <= quadUV[3]) { type = MOVE_YZ + i; } if (gizmoHitProportion) { *gizmoHitProportion = makeVect(dx, dy, 0.f); } } return type; } static bool HandleTranslation(float* matrix, float* deltaMatrix, int& type, float* snap) { ImGuiIO& io = ImGui::GetIO(); bool applyRotationLocaly = gContext.mMode == LOCAL || type == MOVE_SCREEN; bool modified = false; // move if (gContext.mbUsing && (gContext.mActualID == -1 || gContext.mActualID == gContext.mEditingID)) { ImGui::CaptureMouseFromApp(); const float len = fabsf(IntersectRayPlane(gContext.mRayOrigin, gContext.mRayVector, gContext.mTranslationPlan)); // near plan vec_t newPos = gContext.mRayOrigin + gContext.mRayVector * len; // compute delta vec_t newOrigin = newPos - gContext.mRelativeOrigin * gContext.mScreenFactor; vec_t delta = newOrigin - gContext.mModel.v.position; // 1 axis constraint if (gContext.mCurrentOperation >= MOVE_X && gContext.mCurrentOperation <= MOVE_Z) { int axisIndex = gContext.mCurrentOperation - MOVE_X; const vec_t& axisValue = *(vec_t*)&gContext.mModel.m[axisIndex]; float lengthOnAxis = Dot(axisValue, delta); delta = axisValue * lengthOnAxis; } // snap if (snap) { vec_t cumulativeDelta = gContext.mModel.v.position + delta - gContext.mMatrixOrigin; if (applyRotationLocaly) { matrix_t modelSourceNormalized = gContext.mModelSource; modelSourceNormalized.OrthoNormalize(); matrix_t modelSourceNormalizedInverse; modelSourceNormalizedInverse.Inverse(modelSourceNormalized); cumulativeDelta.TransformVector(modelSourceNormalizedInverse); ComputeSnap(cumulativeDelta, snap); cumulativeDelta.TransformVector(modelSourceNormalized); } else { ComputeSnap(cumulativeDelta, snap); } delta = gContext.mMatrixOrigin + cumulativeDelta - gContext.mModel.v.position; } if(delta != gContext.mTranslationLastDelta) { modified = true; } gContext.mTranslationLastDelta = delta; // compute matrix & delta matrix_t deltaMatrixTranslation; deltaMatrixTranslation.Translation(delta); if (deltaMatrix) { memcpy(deltaMatrix, deltaMatrixTranslation.m16, sizeof(float) * 16); } matrix_t res = gContext.mModelSource * deltaMatrixTranslation; *(matrix_t*)matrix = res; if (!io.MouseDown[0]) { gContext.mbUsing = false; } type = gContext.mCurrentOperation; } else { // find new possible way to move vec_t gizmoHitProportion; type = GetMoveType(&gizmoHitProportion); if (type != NONE) { ImGui::CaptureMouseFromApp(); } if (CanActivate() && type != NONE) { gContext.mbUsing = true; gContext.mEditingID = gContext.mActualID; gContext.mCurrentOperation = type; vec_t movePlanNormal[] = { gContext.mModel.v.right, gContext.mModel.v.up, gContext.mModel.v.dir, gContext.mModel.v.right, gContext.mModel.v.up, gContext.mModel.v.dir, -gContext.mCameraDir }; vec_t cameraToModelNormalized = Normalized(gContext.mModel.v.position - gContext.mCameraEye); for (unsigned int i = 0; i < 3; i++) { vec_t orthoVector = Cross(movePlanNormal[i], cameraToModelNormalized); movePlanNormal[i].Cross(orthoVector); movePlanNormal[i].Normalize(); } // pickup plan gContext.mTranslationPlan = BuildPlan(gContext.mModel.v.position, movePlanNormal[type - MOVE_X]); const float len = IntersectRayPlane(gContext.mRayOrigin, gContext.mRayVector, gContext.mTranslationPlan); gContext.mTranslationPlanOrigin = gContext.mRayOrigin + gContext.mRayVector * len; gContext.mMatrixOrigin = gContext.mModel.v.position; gContext.mRelativeOrigin = (gContext.mTranslationPlanOrigin - gContext.mModel.v.position) * (1.f / gContext.mScreenFactor); } } return modified; } static bool HandleScale(float* matrix, float* deltaMatrix, int& type, float* snap) { ImGuiIO& io = ImGui::GetIO(); bool modified = false; if (!gContext.mbUsing) { // find new possible way to scale type = GetScaleType(); if (type != NONE) { ImGui::CaptureMouseFromApp(); } if (CanActivate() && type != NONE) { gContext.mbUsing = true; gContext.mEditingID = gContext.mActualID; gContext.mCurrentOperation = type; const vec_t movePlanNormal[] = { gContext.mModel.v.up, gContext.mModel.v.dir, gContext.mModel.v.right, gContext.mModel.v.dir, gContext.mModel.v.up, gContext.mModel.v.right, -gContext.mCameraDir }; // pickup plan gContext.mTranslationPlan = BuildPlan(gContext.mModel.v.position, movePlanNormal[type - SCALE_X]); const float len = IntersectRayPlane(gContext.mRayOrigin, gContext.mRayVector, gContext.mTranslationPlan); gContext.mTranslationPlanOrigin = gContext.mRayOrigin + gContext.mRayVector * len; gContext.mMatrixOrigin = gContext.mModel.v.position; gContext.mScale.Set(1.f, 1.f, 1.f); gContext.mRelativeOrigin = (gContext.mTranslationPlanOrigin - gContext.mModel.v.position) * (1.f / gContext.mScreenFactor); gContext.mScaleValueOrigin = makeVect(gContext.mModelSource.v.right.Length(), gContext.mModelSource.v.up.Length(), gContext.mModelSource.v.dir.Length()); gContext.mSaveMousePosx = io.MousePos.x; } } // scale if (gContext.mbUsing && (gContext.mActualID == -1 || gContext.mActualID == gContext.mEditingID)) { ImGui::CaptureMouseFromApp(); const float len = IntersectRayPlane(gContext.mRayOrigin, gContext.mRayVector, gContext.mTranslationPlan); vec_t newPos = gContext.mRayOrigin + gContext.mRayVector * len; vec_t newOrigin = newPos - gContext.mRelativeOrigin * gContext.mScreenFactor; vec_t delta = newOrigin - gContext.mModel.v.position; // 1 axis constraint if (gContext.mCurrentOperation >= SCALE_X && gContext.mCurrentOperation <= SCALE_Z) { int axisIndex = gContext.mCurrentOperation - SCALE_X; const vec_t& axisValue = *(vec_t*)&gContext.mModel.m[axisIndex]; float lengthOnAxis = Dot(axisValue, delta); delta = axisValue * lengthOnAxis; vec_t baseVector = gContext.mTranslationPlanOrigin - gContext.mModel.v.position; float ratio = Dot(axisValue, baseVector + delta) / Dot(axisValue, baseVector); gContext.mScale[axisIndex] = max(ratio, 0.001f); } else { float scaleDelta = (io.MousePos.x - gContext.mSaveMousePosx) * 0.01f; gContext.mScale.Set(max(1.f + scaleDelta, 0.001f)); } // snap if (snap) { float scaleSnap[] = { snap[0], snap[0], snap[0] }; ComputeSnap(gContext.mScale, scaleSnap); } // no 0 allowed for (int i = 0; i < 3; i++) gContext.mScale[i] = max(gContext.mScale[i], 0.001f); if(gContext.mScaleLast != gContext.mScale) { modified = true; } gContext.mScaleLast = gContext.mScale; // compute matrix & delta matrix_t deltaMatrixScale; deltaMatrixScale.Scale(gContext.mScale * gContext.mScaleValueOrigin); matrix_t res = deltaMatrixScale * gContext.mModel; *(matrix_t*)matrix = res; if (deltaMatrix) { deltaMatrixScale.Scale(gContext.mScale); memcpy(deltaMatrix, deltaMatrixScale.m16, sizeof(float) * 16); } if (!io.MouseDown[0]) gContext.mbUsing = false; type = gContext.mCurrentOperation; } return modified; } static bool HandleRotation(float* matrix, float* deltaMatrix, int& type, float* snap) { ImGuiIO& io = ImGui::GetIO(); bool applyRotationLocaly = gContext.mMode == LOCAL; bool modified = false; if (!gContext.mbUsing) { type = GetRotateType(); if (type != NONE) { ImGui::CaptureMouseFromApp(); } if (type == ROTATE_SCREEN) { applyRotationLocaly = true; } if (CanActivate() && type != NONE) { gContext.mbUsing = true; gContext.mEditingID = gContext.mActualID; gContext.mCurrentOperation = type; const vec_t rotatePlanNormal[] = { gContext.mModel.v.right, gContext.mModel.v.up, gContext.mModel.v.dir, -gContext.mCameraDir }; // pickup plan if (applyRotationLocaly) { gContext.mTranslationPlan = BuildPlan(gContext.mModel.v.position, rotatePlanNormal[type - ROTATE_X]); } else { gContext.mTranslationPlan = BuildPlan(gContext.mModelSource.v.position, directionUnary[type - ROTATE_X]); } const float len = IntersectRayPlane(gContext.mRayOrigin, gContext.mRayVector, gContext.mTranslationPlan); vec_t localPos = gContext.mRayOrigin + gContext.mRayVector * len - gContext.mModel.v.position; gContext.mRotationVectorSource = Normalized(localPos); gContext.mRotationAngleOrigin = ComputeAngleOnPlan(); } } // rotation if (gContext.mbUsing && (gContext.mActualID == -1 || gContext.mActualID == gContext.mEditingID)) { ImGui::CaptureMouseFromApp(); gContext.mRotationAngle = ComputeAngleOnPlan(); if (snap) { float snapInRadian = snap[0] * DEG2RAD; ComputeSnap(&gContext.mRotationAngle, snapInRadian); } vec_t rotationAxisLocalSpace; rotationAxisLocalSpace.TransformVector(makeVect(gContext.mTranslationPlan.x, gContext.mTranslationPlan.y, gContext.mTranslationPlan.z, 0.f), gContext.mModelInverse); rotationAxisLocalSpace.Normalize(); matrix_t deltaRotation; deltaRotation.RotationAxis(rotationAxisLocalSpace, gContext.mRotationAngle - gContext.mRotationAngleOrigin); if(gContext.mRotationAngle != gContext.mRotationAngleOrigin) { modified = true; } gContext.mRotationAngleOrigin = gContext.mRotationAngle; matrix_t scaleOrigin; scaleOrigin.Scale(gContext.mModelScaleOrigin); if (applyRotationLocaly) { *(matrix_t*)matrix = scaleOrigin * deltaRotation * gContext.mModel; } else { matrix_t res = gContext.mModelSource; res.v.position.Set(0.f); *(matrix_t*)matrix = res * deltaRotation; ((matrix_t*)matrix)->v.position = gContext.mModelSource.v.position; } if (deltaMatrix) { *(matrix_t*)deltaMatrix = gContext.mModelInverse * deltaRotation * gContext.mModel; } if (!io.MouseDown[0]) { gContext.mbUsing = false; gContext.mEditingID = -1; } type = gContext.mCurrentOperation; } return modified; } void DecomposeMatrixToComponents(const float* matrix, float* translation, float* rotation, float* scale) { matrix_t mat = *(matrix_t*)matrix; scale[0] = mat.v.right.Length(); scale[1] = mat.v.up.Length(); scale[2] = mat.v.dir.Length(); mat.OrthoNormalize(); rotation[0] = RAD2DEG * atan2f(mat.m[1][2], mat.m[2][2]); rotation[1] = RAD2DEG * atan2f(-mat.m[0][2], sqrtf(mat.m[1][2] * mat.m[1][2] + mat.m[2][2] * mat.m[2][2])); rotation[2] = RAD2DEG * atan2f(mat.m[0][1], mat.m[0][0]); translation[0] = mat.v.position.x; translation[1] = mat.v.position.y; translation[2] = mat.v.position.z; } void RecomposeMatrixFromComponents(const float* translation, const float* rotation, const float* scale, float* matrix) { matrix_t& mat = *(matrix_t*)matrix; matrix_t rot[3]; for (int i = 0; i < 3; i++) { rot[i].RotationAxis(directionUnary[i], rotation[i] * DEG2RAD); } mat = rot[0] * rot[1] * rot[2]; float validScale[3]; for (int i = 0; i < 3; i++) { if (fabsf(scale[i]) < FLT_EPSILON) { validScale[i] = 0.001f; } else { validScale[i] = scale[i]; } } mat.v.right *= validScale[0]; mat.v.up *= validScale[1]; mat.v.dir *= validScale[2]; mat.v.position.Set(translation[0], translation[1], translation[2], 1.f); } void SetID(int id) { gContext.mActualID = id; } bool Manipulate(const float* view, const float* projection, OPERATION operation, MODE mode, float* matrix, float* deltaMatrix, float* snap, float* localBounds, float* boundsSnap) { ComputeContext(view, projection, matrix, mode); // set delta to identity if (deltaMatrix) { ((matrix_t*)deltaMatrix)->SetToIdentity(); } // behind camera vec_t camSpacePosition; camSpacePosition.TransformPoint(makeVect(0.f, 0.f, 0.f), gContext.mMVP); if (!gContext.mIsOrthographic && camSpacePosition.z < 0.001f) { return false; } // -- int type = NONE; bool manipulated = false; if (gContext.mbEnable) { if (!gContext.mbUsingBounds) { switch (operation) { case ROTATE: manipulated = HandleRotation(matrix, deltaMatrix, type, snap); break; case TRANSLATE: manipulated = HandleTranslation(matrix, deltaMatrix, type, snap); break; case SCALE: manipulated = HandleScale(matrix, deltaMatrix, type, snap); break; case BOUNDS: break; } } } if (localBounds && !gContext.mbUsing) { HandleAndDrawLocalBounds(localBounds, (matrix_t*)matrix, boundsSnap, operation); } gContext.mOperation = operation; if (!gContext.mbUsingBounds) { switch (operation) { case ROTATE: DrawRotationGizmo(type); break; case TRANSLATE: DrawTranslationGizmo(type); break; case SCALE: DrawScaleGizmo(type); break; case BOUNDS: break; } } return manipulated; } void SetGizmoSizeClipSpace(float value) { gGizmoSizeClipSpace = value; } /////////////////////////////////////////////////////////////////////////////////////////////////// void ComputeFrustumPlanes(vec_t* frustum, const float* clip) { frustum[0].x = clip[3] - clip[0]; frustum[0].y = clip[7] - clip[4]; frustum[0].z = clip[11] - clip[8]; frustum[0].w = clip[15] - clip[12]; frustum[1].x = clip[3] + clip[0]; frustum[1].y = clip[7] + clip[4]; frustum[1].z = clip[11] + clip[8]; frustum[1].w = clip[15] + clip[12]; frustum[2].x = clip[3] + clip[1]; frustum[2].y = clip[7] + clip[5]; frustum[2].z = clip[11] + clip[9]; frustum[2].w = clip[15] + clip[13]; frustum[3].x = clip[3] - clip[1]; frustum[3].y = clip[7] - clip[5]; frustum[3].z = clip[11] - clip[9]; frustum[3].w = clip[15] - clip[13]; frustum[4].x = clip[3] - clip[2]; frustum[4].y = clip[7] - clip[6]; frustum[4].z = clip[11] - clip[10]; frustum[4].w = clip[15] - clip[14]; frustum[5].x = clip[3] + clip[2]; frustum[5].y = clip[7] + clip[6]; frustum[5].z = clip[11] + clip[10]; frustum[5].w = clip[15] + clip[14]; for (int i = 0; i < 6; i++) { frustum[i].Normalize(); } } void DrawCubes(const float* view, const float* projection, const float* matrices, int matrixCount) { matrix_t viewInverse; viewInverse.Inverse(*(matrix_t*)view); struct CubeFace { float z; ImVec2 faceCoordsScreen[4]; ImU32 color; }; CubeFace* faces = (CubeFace*)_malloca(sizeof(CubeFace) * matrixCount * 6); if (!faces) { return; } vec_t frustum[6]; matrix_t viewProjection = *(matrix_t*)view * *(matrix_t*)projection; ComputeFrustumPlanes(frustum, viewProjection.m16); int cubeFaceCount = 0; for (int cube = 0; cube < matrixCount; cube++) { const float* matrix = &matrices[cube * 16]; const matrix_t& model = *(matrix_t*)matrix; matrix_t res = *(matrix_t*)matrix * *(matrix_t*)view * *(matrix_t*)projection; matrix_t modelView = *(matrix_t*)matrix * *(matrix_t*)view; for (int iFace = 0; iFace < 6; iFace++) { const int normalIndex = (iFace % 3); const int perpXIndex = (normalIndex + 1) % 3; const int perpYIndex = (normalIndex + 2) % 3; const float invert = (iFace > 2) ? -1.f : 1.f; const vec_t faceCoords[4] = { directionUnary[normalIndex] + directionUnary[perpXIndex] + directionUnary[perpYIndex], directionUnary[normalIndex] + directionUnary[perpXIndex] - directionUnary[perpYIndex], directionUnary[normalIndex] - directionUnary[perpXIndex] - directionUnary[perpYIndex], directionUnary[normalIndex] - directionUnary[perpXIndex] + directionUnary[perpYIndex], }; // clipping /* bool skipFace = false; for (unsigned int iCoord = 0; iCoord < 4; iCoord++) { vec_t camSpacePosition; camSpacePosition.TransformPoint(faceCoords[iCoord] * 0.5f * invert, res); if (camSpacePosition.z < 0.001f) { skipFace = true; break; } } if (skipFace) { continue; } */ vec_t centerPosition, centerPositionVP; centerPosition.TransformPoint(directionUnary[normalIndex] * 0.5f * invert, *(matrix_t*)matrix); centerPositionVP.TransformPoint(directionUnary[normalIndex] * 0.5f * invert, res); bool inFrustum = true; for (int iFrustum = 0; iFrustum < 6; iFrustum++) { float dist = DistanceToPlane(centerPosition, frustum[iFrustum]); if (dist < 0.f) { inFrustum = false; break; } } if (!inFrustum) { continue; } CubeFace& cubeFace = faces[cubeFaceCount]; // 3D->2D //ImVec2 faceCoordsScreen[4]; for (unsigned int iCoord = 0; iCoord < 4; iCoord++) { cubeFace.faceCoordsScreen[iCoord] = worldToPos(faceCoords[iCoord] * 0.5f * invert, res); } cubeFace.color = directionColor[normalIndex] | 0x808080; cubeFace.z = centerPositionVP.z / centerPositionVP.w; cubeFaceCount++; } } qsort(faces, cubeFaceCount, sizeof(CubeFace), [](void const* _a, void const* _b){ CubeFace* a = (CubeFace*)_a; CubeFace* b = (CubeFace*)_b; if (a->z < b->z) { return 1; } return -1; }); // draw face with lighter color for (int iFace = 0; iFace < cubeFaceCount; iFace++) { const CubeFace& cubeFace = faces[iFace]; gContext.mDrawList->AddConvexPolyFilled(cubeFace.faceCoordsScreen, 4, cubeFace.color); } } void DrawGrid(const float* view, const float* projection, const float* matrix, const float gridSize) { matrix_t viewProjection = *(matrix_t*)view * *(matrix_t*)projection; vec_t frustum[6]; ComputeFrustumPlanes(frustum, viewProjection.m16); matrix_t res = *(matrix_t*)matrix * viewProjection; for (float f = -gridSize; f <= gridSize; f += 1.f) { for (int dir = 0; dir < 2; dir++) { vec_t ptA = makeVect(dir ? -gridSize : f, 0.f, dir ? f : -gridSize); vec_t ptB = makeVect(dir ? gridSize : f, 0.f, dir ? f : gridSize); bool visible = true; for (int i = 0; i < 6; i++) { float dA = DistanceToPlane(ptA, frustum[i]); float dB = DistanceToPlane(ptB, frustum[i]); if (dA < 0.f && dB < 0.f) { visible = false; break; } if (dA > 0.f && dB > 0.f) { continue; } if (dA < 0.f) { float len = fabsf(dA - dB); float t = fabsf(dA) / len; ptA.Lerp(ptB, t); } if (dB < 0.f) { float len = fabsf(dB - dA); float t = fabsf(dB) / len; ptB.Lerp(ptA, t); } } if (visible) { ImU32 col = 0xFF808080; col = (fmodf(fabsf(f), 10.f) < FLT_EPSILON) ? 0xFF909090 : col; col = (fabsf(f) < FLT_EPSILON) ? 0xFF404040 : col; float thickness = 1.f; thickness = (fmodf(fabsf(f), 10.f) < FLT_EPSILON) ? 1.5f : thickness; thickness = (fabsf(f) < FLT_EPSILON) ? 2.3f : thickness; gContext.mDrawList->AddLine(worldToPos(ptA, res), worldToPos(ptB, res), col, thickness); } } } } void ViewManipulate(float* view, float length, ImVec2 position, ImVec2 size, ImU32 backgroundColor) { static bool isDraging = false; static bool isClicking = false; static bool isInside = false; static vec_t interpolationUp; static vec_t interpolationDir; static int interpolationFrames = 0; const vec_t referenceUp = makeVect(0.f, 1.f, 0.f); matrix_t svgView, svgProjection; svgView = gContext.mViewMat; svgProjection = gContext.mProjectionMat; ImGuiIO& io = ImGui::GetIO(); gContext.mDrawList->AddRectFilled(position, position + size, backgroundColor); matrix_t viewInverse; viewInverse.Inverse(*(matrix_t*)view); const vec_t camTarget = viewInverse.v.position - viewInverse.v.dir * length; // view/projection matrices const float distance = 3.f; matrix_t cubeProjection, cubeView; float fov = acosf(distance / (sqrtf(distance * distance + 3.f))) * RAD2DEG; Perspective(fov / sqrtf(2.f), size.x / size.y, 0.01f, 1000.f, cubeProjection.m16); vec_t dir = makeVect(viewInverse.m[2][0], viewInverse.m[2][1], viewInverse.m[2][2]); vec_t up = makeVect(viewInverse.m[1][0], viewInverse.m[1][1], viewInverse.m[1][2]); vec_t eye = dir * distance; vec_t zero = makeVect(0.f, 0.f); LookAt(&eye.x, &zero.x, &up.x, cubeView.m16); // set context gContext.mViewMat = cubeView; gContext.mProjectionMat = cubeProjection; ComputeCameraRay(gContext.mRayOrigin, gContext.mRayVector, position, size); const matrix_t res = cubeView * cubeProjection; // panels static const ImVec2 panelPosition[9] = { ImVec2(0.75f,0.75f), ImVec2(0.25f, 0.75f), ImVec2(0.f, 0.75f), ImVec2(0.75f, 0.25f), ImVec2(0.25f, 0.25f), ImVec2(0.f, 0.25f), ImVec2(0.75f, 0.f), ImVec2(0.25f, 0.f), ImVec2(0.f, 0.f) }; static const ImVec2 panelSize[9] = { ImVec2(0.25f,0.25f), ImVec2(0.5f, 0.25f), ImVec2(0.25f, 0.25f), ImVec2(0.25f, 0.5f), ImVec2(0.5f, 0.5f), ImVec2(0.25f, 0.5f), ImVec2(0.25f, 0.25f), ImVec2(0.5f, 0.25f), ImVec2(0.25f, 0.25f) }; // tag faces bool boxes[27]{}; for (int iPass = 0; iPass < 2; iPass++) { for (int iFace = 0; iFace < 6; iFace++) { const int normalIndex = (iFace % 3); const int perpXIndex = (normalIndex + 1) % 3; const int perpYIndex = (normalIndex + 2) % 3; const float invert = (iFace > 2) ? -1.f : 1.f; const vec_t indexVectorX = directionUnary[perpXIndex] * invert; const vec_t indexVectorY = directionUnary[perpYIndex] * invert; const vec_t boxOrigin = directionUnary[normalIndex] * -invert - indexVectorX - indexVectorY; const vec_t faceCoords[4] = { directionUnary[normalIndex] + directionUnary[perpXIndex] + directionUnary[perpYIndex], directionUnary[normalIndex] + directionUnary[perpXIndex] - directionUnary[perpYIndex], directionUnary[normalIndex] - directionUnary[perpXIndex] - directionUnary[perpYIndex], directionUnary[normalIndex] - directionUnary[perpXIndex] + directionUnary[perpYIndex] }; // plan local space const vec_t n = directionUnary[normalIndex] * invert; vec_t viewSpaceNormal = n; vec_t viewSpacePoint = n * 0.5f; viewSpaceNormal.TransformVector(cubeView); viewSpaceNormal.Normalize(); viewSpacePoint.TransformPoint(cubeView); const vec_t viewSpaceFacePlan = BuildPlan(viewSpacePoint, viewSpaceNormal); // back face culling if (viewSpaceFacePlan.w > 0.f) { continue; } const vec_t facePlan = BuildPlan(n * 0.5f, n); const float len = IntersectRayPlane(gContext.mRayOrigin, gContext.mRayVector, facePlan); vec_t posOnPlan = gContext.mRayOrigin + gContext.mRayVector * len - (n * 0.5f); float localx = Dot(directionUnary[perpXIndex], posOnPlan) * invert + 0.5f; float localy = Dot(directionUnary[perpYIndex], posOnPlan) * invert + 0.5f; // panels const vec_t dx = directionUnary[perpXIndex]; const vec_t dy = directionUnary[perpYIndex]; const vec_t origin = directionUnary[normalIndex] - dx - dy; for (int iPanel = 0; iPanel < 9; iPanel++) { vec_t boxCoord = boxOrigin + indexVectorX * float(iPanel % 3) + indexVectorY * float(iPanel / 3) + makeVect(1.f, 1.f, 1.f); const ImVec2 p = panelPosition[iPanel] * 2.f; const ImVec2 s = panelSize[iPanel] * 2.f; ImVec2 faceCoordsScreen[4]; vec_t panelPos[4] = { dx * p.x + dy * p.y, dx * p.x + dy * (p.y + s.y), dx * (p.x + s.x) + dy * (p.y + s.y), dx * (p.x + s.x) + dy * p.y }; for (unsigned int iCoord = 0; iCoord < 4; iCoord++) { faceCoordsScreen[iCoord] = worldToPos((panelPos[iCoord] + origin) * 0.5f * invert, res, position, size); } const ImVec2 panelCorners[2] = { panelPosition[iPanel], panelPosition[iPanel] + panelSize[iPanel] }; bool insidePanel = localx > panelCorners[0].x&& localx < panelCorners[1].x && localy > panelCorners[0].y&& localy < panelCorners[1].y; int boxCoordInt = int(boxCoord.x * 9.f + boxCoord.y * 3.f + boxCoord.z); assert(boxCoordInt < 27); boxes[boxCoordInt] |= insidePanel && (!isDraging); // draw face with lighter color if (iPass) { gContext.mDrawList->AddConvexPolyFilled(faceCoordsScreen, 4, (directionColor[normalIndex] | 0x80808080) | (isInside ? 0x080808 : 0)); if (boxes[boxCoordInt]) { gContext.mDrawList->AddConvexPolyFilled(faceCoordsScreen, 4, 0x8060A0F0); if (!io.MouseDown[0] && !isDraging && isClicking) { // apply new view direction int cx = boxCoordInt / 9; int cy = (boxCoordInt - cx * 9) / 3; int cz = boxCoordInt % 3; interpolationDir = makeVect(1.f - cx, 1.f - cy, 1.f - cz); interpolationDir.Normalize(); if (fabsf(Dot(interpolationDir, referenceUp)) > 1.0f - 0.01f) { vec_t right = viewInverse.v.right; if (fabsf(right.x) > fabsf(right.z)) { right.z = 0.f; } else { right.x = 0.f; } right.Normalize(); interpolationUp = Cross(interpolationDir, right); interpolationUp.Normalize(); } else { interpolationUp = referenceUp; } interpolationFrames = 40; isClicking = false; } if (io.MouseDown[0] && !isDraging) { isClicking = true; } } } } } } if (interpolationFrames) { interpolationFrames--; vec_t newDir = viewInverse.v.dir; newDir.Lerp(interpolationDir, 0.2f); newDir.Normalize(); vec_t newUp = viewInverse.v.up; newUp.Lerp(interpolationUp, 0.3f); newUp.Normalize(); newUp = interpolationUp; vec_t newEye = camTarget + newDir * length; LookAt(&newEye.x, &camTarget.x, &newUp.x, view); } isInside = ImRect(position, position + size).Contains(io.MousePos); // drag view if (!isDraging && io.MouseDown[0] && isInside && (fabsf(io.MouseDelta.x) > 0.f || fabsf(io.MouseDelta.y) > 0.f)) { isDraging = true; isClicking = false; } else if (isDraging && !io.MouseDown[0]) { isDraging = false; } if (isDraging) { matrix_t rx, ry, roll; rx.RotationAxis(referenceUp, -io.MouseDelta.x * 0.01f); ry.RotationAxis(viewInverse.v.right, -io.MouseDelta.y * 0.01f); roll = rx * ry; vec_t newDir = viewInverse.v.dir; newDir.TransformVector(roll); newDir.Normalize(); // clamp vec_t planDir = Cross(viewInverse.v.right, referenceUp); planDir.y = 0.f; planDir.Normalize(); float dt = Dot(planDir, newDir); if (dt < 0.0f) { newDir += planDir * dt; newDir.Normalize(); } vec_t newEye = camTarget + newDir * length; LookAt(&newEye.x, &camTarget.x, &referenceUp.x, view); } // restore view/projection because it was used to compute ray ComputeContext(svgView.m16, svgProjection.m16, gContext.mModelSource.m16, gContext.mMode); } };
[ "porter.declan@gmail.com" ]
porter.declan@gmail.com
b4287b3db5cb3135af91dd0707aa1bf2e5f3f3db
9ec079af787c290035ca26e86e89940210cfa662
/pixel.h
8f10e8622942fee3c8e84f0e241a8c6d51a78b24
[]
no_license
chasecolford/KeyboardGUI
2533dc632dbe904849622ec41184b558735c295d
3610539c84cd99447a8ec6e3142c1bed76e27aad
refs/heads/master
2022-11-26T13:06:49.155785
2020-08-02T22:57:54
2020-08-02T22:57:54
null
0
0
null
null
null
null
UTF-8
C++
false
false
151
h
#ifndef PIXEL_H #define PIXEL_H #include <QWidget> class Pixel : public QWidget { public: explicit Pixel(QWidget* parent); }; #endif // PIXEL_H
[ "56804717+ChaseSinify@users.noreply.github.com" ]
56804717+ChaseSinify@users.noreply.github.com
981d2b36daf4294d41ac3b0807c104943089c55e
8319097d116501d562c0d1cbaafe3fcdebebb119
/interface/sources/PreviewMaskWidget.h
cbfe9020a31f00f2deb97ed9f5849e0a2535dca1
[]
no_license
GiantClam/jubangktv
e6d596d33b4193e2c891e1f69021142b5078f811
51dd618ce38b9628669e5973c75cf3f1344b0bbf
refs/heads/master
2020-05-20T11:09:02.341186
2012-09-16T17:19:42
2012-09-16T17:19:42
null
0
0
null
null
null
null
UTF-8
C++
false
false
492
h
#ifndef PREVIEW_MASKWIDGET_H #define PREVIEW_MASKWIDGET_H #include "MaskWidget.h" #include "FilterSubject.h" #include "PreviewWidget.h" #include <QPropertyAnimation> class PreviewMaskWidget : public QObject { Q_OBJECT public: PreviewMaskWidget(QWidget *_parent); ~PreviewMaskWidget(); void showSong(int _songID); private: void setAnimationParam(const QPoint &_showPoint); private: MaskWidget maskWidget; PreviewWidget previewWidget; QPropertyAnimation animation; }; #endif
[ "liulanggoukk@gmail.com" ]
liulanggoukk@gmail.com
8e6464082012f2ff4a68925fc327aa132a6a238d
67b7a7085447b7561208ed6df95dd3133df580e2
/may03/blow/unified_lod_3/framework/priority_queue.cpp
35cb11ae8695dfa62e9ef7c4becf4b84802782c0
[]
no_license
dwilliamson/GDMagArchive
81fd5b708417697bfb2caf8a983dd3ad7decdaf7
701948bbd74b7ae765be8cdaf4ae0f875e2bbf8e
refs/heads/master
2021-06-07T23:41:08.343776
2016-10-31T14:42:20
2016-10-31T14:42:20
72,441,821
74
4
null
null
null
null
UTF-8
C++
false
false
3,474
cpp
#include "../framework.h" #include "priority_queue.h" #include <math.h> Priority_Queue::Priority_Queue(int num_expected_items, double _search_log_factor) { assert(num_expected_items > 0); search_log_factor = _search_log_factor; max_node_height = (int)(log(num_expected_items) / log(search_log_factor)) + 1; assert(max_node_height > 0); float population = 100; int i; for (i = 0; i < max_node_height; i++) { int size_in_bytes = sizeof(Priority_Queue_Node) + i * sizeof(Priority_Queue_Node *); population /= search_log_factor; if (population < 20) population = 20; // @Cleanup arbitrary constant. } init_sentinel(); num_items = 0; } Priority_Queue::~Priority_Queue() { } void Priority_Queue::init_sentinel() { // Set up the sentinel node. sentinel = make_node(max_node_height); sentinel->priority = -1; sentinel->data = NULL; int i; for (i = 0; i < max_node_height; i++) sentinel->next[i] = NULL; } void Priority_Queue::reset() { num_items = 0; init_sentinel(); } Priority_Queue_Node *Priority_Queue::make_node(int height) { assert(height >= 1); assert(height <= max_node_height); Priority_Queue_Node *node = (Priority_Queue_Node *)(new char[sizeof(Priority_Queue_Node) + (height - 1) * sizeof(Priority_Queue_Node *)]); return node; } Priority_Queue_Node *Priority_Queue::make_node(int *height_result) { int height = 1; const int RAND_QUANTUM = 1 << 24; double factor = 1; // @Warning: 'die_roll' uses rand() which is a no-no for // serious software development. int die_roll = rand() % RAND_QUANTUM; // @Improvement we can probably compute the below thingy // in closed form... why don't we do that? while (height < max_node_height) { factor *= (1.0 / search_log_factor); int number_to_beat = (int)(factor * RAND_QUANTUM); if (die_roll >= number_to_beat) break; height++; } assert(height <= max_node_height); *height_result = height; return make_node(height); } void Priority_Queue::add(float priority, void *data) { int node_height; Priority_Queue_Node *node = make_node(&node_height); node->priority = priority; node->data = data; Priority_Queue_Node *cursor = sentinel; int i; for (i = max_node_height - 1; i >= 0; i--) { while (1) { Priority_Queue_Node *next = cursor->next[i]; if (next == NULL) break; if (next->priority > node->priority) break; cursor = next; } if (i < node_height) { node->next[i] = cursor->next[i]; cursor->next[i] = node; } } num_items++; } void *Priority_Queue::remove_head(float *priority_result, bool *success_result) { Priority_Queue_Node *first_node = sentinel->next[0]; if (!first_node) { *success_result = false; assert(num_items == 0); return NULL; } // Unlink the head from the list. assert(num_items > 0); int i; for (i = 0; i < max_node_height; i++) { if (sentinel->next[i] == first_node) { sentinel->next[i] = first_node->next[i]; } } *priority_result = first_node->priority; *success_result = true; void *return_value = first_node->data; delete [] ((char *)first_node); num_items--; return return_value; }
[ "dwilliamson_coder@hotmail.com" ]
dwilliamson_coder@hotmail.com
45eae74148e3209981475854f6e06f3d841aa05b
dc97aa3ddd1648c4c5528e97e316dd02091fc5ed
/main.cpp
0afe990dad32844061fe4638bce7f3efedaa7eca
[]
no_license
wutaoo/markov_localization_learn
a2791cee60ca2791b33bb8417ee592823c7fff20
af63d00ae0c67f87a5ab1dd0518dcc93d355dc88
refs/heads/master
2020-05-29T19:50:19.395568
2017-09-19T12:31:07
2017-09-19T12:31:07
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,777
cpp
#include <iostream> #include <vector> #include <fstream> #include <sstream> #include <string> #include "measurement_package.h" #include "map.h" #include "help_functions.h" #include "bayesianFilter.h" using namespace std; int main() { /****************************************************************************** * declaration: *****************************************************************************/ //define example: 01, 02, 03, 04 string example_string = "03"; //declare map: map map_1d; //declare measurement list: std::vector<MeasurementPackage> measurement_pack_list; //declare helpers: help_functions helper; //define file names: char in_file_name_ctr[1024]; char in_file_name_obs[1024]; char in_file_name_gt[1024]; /****************************************************************************** * read map and measurements: * *****************************************************************************/ //read map: helper.read_map_data("data/map_1d.txt", map_1d); //define file name of controls: sprintf(in_file_name_ctr, "data/example%s/control_data.txt", example_string.c_str()); //define file name of observations: sprintf(in_file_name_obs, "data/example%s/observations/", example_string.c_str()); //read in data to measurement package list: helper.read_measurement_data(in_file_name_ctr, in_file_name_obs, measurement_pack_list); /******************************************************************************* * start 1d_bayesian filter * *******************************************************************************/ //create instance of 1d_bayesian localization filter: bayesianFilter localization_1d_bayesian; //define number of time steps: size_t T = measurement_pack_list.size(); //cycle: for (size_t t = 0; t < T; ++t) { //Call 1d_bayesian filter: localization_1d_bayesian.process_measurement(measurement_pack_list[t], map_1d, helper); } /******************************************************************************* * print/compare results: * ********************************************************************************/ //define file name of gt data: sprintf(in_file_name_gt, "data/example%s/gt_example%s.txt", example_string.c_str(), example_string.c_str()); ///compare gt data with results: helper.compare_data(in_file_name_gt, localization_1d_bayesian.bel_x); return 0; }
[ "shenzb12@lzu.edu.cn" ]
shenzb12@lzu.edu.cn
172ac56c207ef85dc6f29afeaaa02b66e3e2417b
c808b0ab75a24d3a72331349202fa803706914cc
/src/animaControll.h
fc173ef8f080de8028e8cfd557ce5b6edd6f60a3
[ "MIT" ]
permissive
Miantang/Ege-Butter-Fly
83f4ee875f2a2be82b7bd7a9e97a7d2baa29fcc1
fac166c9ceb41ed3953e42547aed27caa8c55dd5
refs/heads/master
2021-05-02T06:22:50.860662
2018-07-11T04:02:34
2018-07-11T04:02:34
34,900,553
5
1
null
2015-05-04T14:50:13
2015-05-01T11:46:33
C++
UTF-8
C++
false
false
2,674
h
/*************************************************************************** Copyright (c) 2015- MianTang https://github.com/Miantang/Ege-Butter-Fly Taking part in the mooc class in NetEase of C++ introduction <http://mooc.study.163.com/course/BUPT-1000003015#/info> Related to a competition about creating EGE Draws or Animations . Image code was edited by Adobe Illustrator from source paintings *.jpg(fetched from Baidu Tieba) to SVG Vector , then convert them to the Cpp code for this software via a software made myself.(Based on Flash Actionscript) <https://github.com/Miantang/AsToEge> This software is released under the MIT License <http://www.opensource.org/licenses/mit-license.php> ****************************************************************************/ #pragma once #include <graphics.h> // Preset mode for animation controlling for each Image or Text. const int LEFT = 1; const int RIGHT = 2; const int ALPHA = 3; const int HOLD = 4; const int LEFTALPHA = 5; const int RIGHTALPHA = 6; const int ALPHAHOLD = 7; // Combine setcolor and setlinewidth to a single function , for easier converting of Flash code. void lineStyle(float, color_t, PIMAGE); /** * @brief Init screen of EGE. */ class Screen { private : int width; int height; public : Screen(int, int) ; ~Screen() ; int getWidth() ; int getHeight() ; }; /** * @brief Base class for Picture and Text . */ class Image { public : Image(); ~Image(); void draw(); void animation(); void render(); PIMAGE img; float x, y; float dx, dy; int alpha, da; int animaPreset; bool isCleared; }; /** * @brief Text element to display on the screen , extend Image . */ class Text : public Image { public : int txtWidth; int txtHeight; LPCTSTR textstring; Text(int, int, LPCTSTR, int); //convert the anchor to the cneter of text, for operating easier. inline int toCenterX(int); inline int toCenterY(int); }; /** * @brief Attach timeline to the Image[or its child class] for displaying in its Composition */ class Layer { public : float inTime, outTime; Image* source; Layer(); Layer(float, float, Image*); void init(float, float, Image*); }; /** * @brief Display the Layer(s) contained ,foreach currentTime to present the elements in proper time on the screen. */ class Composition { public : Composition(int, Layer*); Layer* layers; int numOfLayers; void present(float); // void setLayer(int, Layer); };
[ "antisaber@gmail.com" ]
antisaber@gmail.com
b98ca7942b4960f0a4e2ad5cb91fe749748671a9
0a9410ef6897bec58a5c5d2a080aad5bc75bb386
/benchmark/point-correlation/dual-tree/src/util.cpp
fc447f0513c6fa05288bff5e113c6f2f4252f8f3
[]
no_license
kirshanthans/twisted-interchanger
47e24ea945b993e006ae1a32a6f290a66896d0b2
4219af25ab3e5978df31ccffef6560c9bce45ebd
refs/heads/master
2021-05-01T12:38:55.762960
2017-01-21T04:06:49
2017-01-21T04:06:49
79,527,532
5
1
null
null
null
null
UTF-8
C++
false
false
3,038
cpp
/* Copyright (c) 2017, Kirshanthan Sundararajah, Laith Sakka and Milind Kulkarni All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the Purdue University 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 <COPYRIGHT HOLDER> BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "util.h" #include "common.h" float max(float a, float b) { return a > b ? a : b; } float min(float a, float b) { return a < b ? a : b; } void readInput(int argc, char **argv) { FILE *in; if(argc != 5 && argc != 4) { fprintf(stderr, "usage: pointcorr <DIM> <rad> <npoints> [input_file]\n"); exit(1); } dim = atoi(argv[1]); if(dim <= 0) { fprintf(stderr, "Invalid DIM\n"); exit(1); } rad = atof(argv[2]); npoints = atol(argv[3]); if(npoints <= 0) { fprintf(stderr, "Not enough points.\n"); exit(1); } inPoints = new Point[npoints]; if(argc == 5) { in = fopen(argv[4], "r"); if(in == NULL) { fprintf(stderr, "Could not open %s\n", argv[4]); exit(1); } for(int i = 0; i < npoints; i++) { readPoint(in, &inPoints[i]); } fclose(in); } else { srand(0); for(int i = 0; i < npoints; i++) { for(int j = 0; j < dim; j++) { inPoints[i].coord[j] = (float)rand() / RAND_MAX; } } } } void readPoint(FILE *in, Point *p) { int dummy; if(fscanf(in, "%d", &dummy) != 1) { fprintf(stderr, "Input file not large enough.\n"); exit(1); } for(int j = 0; j < dim; j++) { if(fscanf(in, "%f", &p->coord[j]) != 1) { fprintf(stderr, "Input file not large enough.\n"); exit(1); } } } #ifdef PERF void handleError(int retval) { cout << "PAPI Error " << retval << ": " << PAPI_strerror(retval) << endl; exit(1); } #endif
[ "kirshanthans.14@cse.mrt.ac.lk" ]
kirshanthans.14@cse.mrt.ac.lk
93fd0481115a3b565a111e0e896da3f63cb9e408
0bb056d5ec33b47d2f7f0c26fdc5e8b892def498
/Blackjack/main.cpp
ee4b92d6e970741f1ada7d457e3580688c124369
[]
no_license
arniyu/Forritun-Upprifjunarn-mskei-
523bd6734f3ee126afbc58999cf81c52874fc77d
927bdd6269aa2d39016fe6965d4d0cbfd358d93d
refs/heads/master
2020-12-24T06:28:05.512334
2016-11-11T13:27:04
2016-11-11T13:27:04
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,333
cpp
#include <iostream> #include "Card.h" using namespace std; const int MAXSIZE = 5; const int MINSIZE = 2; bool evaluateHandSize(int handSize) { return handSize <= MAXSIZE && handSize >= MINSIZE; } void prompt() { cout << "Scoring a blackjack hand" << endl; cout << "------------------------" << endl; cout << "Number of cards (min 2, max 5): " << endl; } int main() { char again = 'y'; while(again == 'y' || again == 'Y') { char cardInput; int handSize; vector<Card> cards; prompt(); cin >> handSize; if(!evaluateHandSize(handSize)) { cout << "Invalid number of cards!" << endl; } else { for(int i = 1; i <= handSize; i++) { cout << "Card no. " << i << ": "; cin >> cardInput; Card card; card.setCardValue(cardInput); cards.push_back(card); } Card card; int score = card.evaluateHand(cards); cout << "The score of the hand is: " << score << endl; if(card.checkIfBusted(score)) { cout << "Busted!" << endl; } } cout << "Score again?" << endl; cin >> again; } return 0; }
[ "kari@lsretail.com" ]
kari@lsretail.com
bd03d382e1f7af5d468a986b60afe226b844d658
b220e8dc2bc7e7f3b445c00294c5353a33c5a67f
/Source/WinSandbox/PlayerControllerSystem.cpp
7229c6c0afc73fd5def771357f5b1a8479c487e6
[ "MIT" ]
permissive
wradley/Freight
374d2e8dc0277d7caa5f1d7c10b042f6115af9dc
91eda2ca0af64036202309f6adbf2d80c406e031
refs/heads/master
2023-07-07T21:03:49.120549
2020-05-24T04:07:22
2020-05-24T04:07:22
182,446,073
0
0
null
null
null
null
UTF-8
C++
false
false
4,924
cpp
#include "PlayerControllerSystem.hpp" #include "Freight.hpp" #include <glfw3.h> PlayerControllerSystem::PlayerControllerSystem() : mPlayerID(0), mHasPlayer(false), mInitLastXY(false), mXPixelsMoved(0.0), mYPixelsMoved(0.0), mPitch(0.0), mYaw(0.0) { } PlayerControllerSystem::~PlayerControllerSystem() { } void PlayerControllerSystem::start() { auto &em = fr::EventManager::Instance(); em.on<AddEntityEvent>([this](std::shared_ptr<const AddEntityEvent> e) { for (auto &tag : e->tags) { if (tag == "player") { mHasPlayer = true; mPlayerID = e->entity; mPlayerTform = e->transform; } } }); em.on<InputEvent>([this](std::shared_ptr<const InputEvent> e) { for (auto &key : e->keys) { // key down if (key.openglKey == GLFW_KEY_W && key.openglAction == GLFW_PRESS) mController.lVertical += 1.0; else if (key.openglKey == GLFW_KEY_S && key.openglAction == GLFW_PRESS) mController.lVertical -= 1.0; else if (key.openglKey == GLFW_KEY_A && key.openglAction == GLFW_PRESS) mController.lHorizontal -= 1.0; else if (key.openglKey == GLFW_KEY_D && key.openglAction == GLFW_PRESS) mController.lHorizontal += 1.0; // key up else if (key.openglKey == GLFW_KEY_W && key.openglAction == GLFW_RELEASE) mController.lVertical -= 1.0; else if (key.openglKey == GLFW_KEY_S && key.openglAction == GLFW_RELEASE) mController.lVertical += 1.0; else if (key.openglKey == GLFW_KEY_A && key.openglAction == GLFW_RELEASE) mController.lHorizontal += 1.0; else if (key.openglKey == GLFW_KEY_D && key.openglAction == GLFW_RELEASE) mController.lHorizontal -= 1.0; // esc -> quit else if (key.openglKey == GLFW_KEY_ESCAPE && key.openglAction == GLFW_PRESS) { auto ae = new ApplicationExitEvent; fr::EventManager::Instance().post(std::shared_ptr<const ApplicationExitEvent>(ae)); } } for (auto &move : e->mouseMoves) { if (!mInitLastXY) { mInitLastXY = true; mLastX = move.xpos; mLastY = move.ypos; } mXPixelsMoved += move.xpos - mLastX; mYPixelsMoved += move.ypos - mLastY; mLastX = move.xpos; mLastY = move.ypos; } }); } void PlayerControllerSystem::update() { // convert mouse pixels moved to analog stick range mController.rHorizontal = mXPixelsMoved / X_MAX_PIXELS; mController.rVertical = mYPixelsMoved / Y_MAX_PIXELS; mXPixelsMoved = 0; mYPixelsMoved = 0; // remove errors if (mController.lVertical > 1.0) mController.lVertical = 1.0; if (mController.lVertical < -1.0) mController.lVertical = -1.0; if (mController.lVertical < 0.01 && mController.lVertical > -0.01) mController.lVertical = 0.0; if (mController.lHorizontal > 1.0) mController.lHorizontal = 1.0; if (mController.lHorizontal < -1.0) mController.lHorizontal = -1.0; if (mController.lHorizontal < 0.01 && mController.lHorizontal > -0.01) mController.lHorizontal = 0.0; if (mController.rVertical > 1.0) mController.rVertical = 1.0; if (mController.rVertical < -1.0) mController.rVertical = -1.0; if (mController.rVertical < 0.01 && mController.rVertical > -0.01) mController.rVertical = 0.0; if (mController.rHorizontal > 1.0) mController.rHorizontal = 1.0; if (mController.rHorizontal < -1.0) mController.rHorizontal = -1.0; if (mController.rHorizontal < 0.01 && mController.rHorizontal > -0.01) mController.rHorizontal = 0.0; // calculate player movement if (!mHasPlayer) return; if (mController.lVertical == 0.0 && mController.lHorizontal == 0.0 && mController.rVertical == 0.0 && mController.rHorizontal == 0.0 ) return; fr::Vec3 move{mController.lHorizontal, 0, -mController.lVertical}; mPitch += fr::ToRad(-mController.rVertical * ROT_SPEED_Y); mYaw += fr::ToRad(-mController.rHorizontal * ROT_SPEED_X); fr::Quat pitch = fr::AxisAngleToQuat({1,0,0}, mPitch); fr::Quat yaw = fr::AxisAngleToQuat({0,1,0}, mYaw); mPlayerTform.rotation = yaw * pitch; mPlayerTform.position += mPlayerTform.rotation * fr::Normal(move) * MOVE_SPEED; TransformEntitiesEvent::EntityTransform entTform; entTform.entity = mPlayerID; entTform.transform = mPlayerTform; auto te = new TransformEntitiesEvent; te->transforms.push_back(entTform); auto &em = fr::EventManager::Instance(); em.post<TransformEntitiesEvent>(std::shared_ptr<const TransformEntitiesEvent>(te)); } void PlayerControllerSystem::stop() { }
[ "wcallahan@wi.rr.com" ]
wcallahan@wi.rr.com
61502320821d4797f41653c9467d8be1c438c121
6a2f91a2aded2360e0330b10f2b13568f3047416
/exportSMOKEY/release/windows/obj/src/DFJKOption.cpp
21f21ece4b0aaf69525aaa0affa64f85ce76ea74
[ "Apache-2.0" ]
permissive
ThatCraftyOne/FNF-Vs-Smokey-Mod
7dc59c71c82f1e5a49176eadc2cf8dc1a57fc89c
9278a44cc6f2fb5892d694af1fe84465fb75c25f
refs/heads/main
2023-06-20T06:52:16.012255
2021-07-19T14:47:26
2021-07-19T14:47:26
387,495,580
0
0
null
null
null
null
UTF-8
C++
false
true
6,207
cpp
// Generated by Haxe 4.2.2 #include <hxcpp.h> #ifndef INCLUDED_Controls #include <Controls.h> #endif #ifndef INCLUDED_DFJKOption #include <DFJKOption.h> #endif #ifndef INCLUDED_KeyBindMenu #include <KeyBindMenu.h> #endif #ifndef INCLUDED_MusicBeatState #include <MusicBeatState.h> #endif #ifndef INCLUDED_Option #include <Option.h> #endif #ifndef INCLUDED_OptionsMenu #include <OptionsMenu.h> #endif #ifndef INCLUDED_flixel_FlxBasic #include <flixel/FlxBasic.h> #endif #ifndef INCLUDED_flixel_FlxState #include <flixel/FlxState.h> #endif #ifndef INCLUDED_flixel_FlxSubState #include <flixel/FlxSubState.h> #endif #ifndef INCLUDED_flixel_addons_transition_FlxTransitionableState #include <flixel/addons/transition/FlxTransitionableState.h> #endif #ifndef INCLUDED_flixel_addons_ui_FlxUIState #include <flixel/addons/ui/FlxUIState.h> #endif #ifndef INCLUDED_flixel_addons_ui_interfaces_IEventGetter #include <flixel/addons/ui/interfaces/IEventGetter.h> #endif #ifndef INCLUDED_flixel_addons_ui_interfaces_IFlxUIState #include <flixel/addons/ui/interfaces/IFlxUIState.h> #endif #ifndef INCLUDED_flixel_group_FlxTypedGroup #include <flixel/group/FlxTypedGroup.h> #endif #ifndef INCLUDED_flixel_input_actions_FlxActionSet #include <flixel/input/actions/FlxActionSet.h> #endif #ifndef INCLUDED_flixel_util_IFlxDestroyable #include <flixel/util/IFlxDestroyable.h> #endif HX_DEFINE_STACK_FRAME(_hx_pos_c83b011b1ca270a7_82_new,"DFJKOption","new",0xfb5a698a,"DFJKOption.new","Options.hx",82,0x9d9a0240) HX_LOCAL_STACK_FRAME(_hx_pos_c83b011b1ca270a7_88_press,"DFJKOption","press",0x85470b2d,"DFJKOption.press","Options.hx",88,0x9d9a0240) HX_LOCAL_STACK_FRAME(_hx_pos_c83b011b1ca270a7_95_updateDisplay,"DFJKOption","updateDisplay",0xd7d600e3,"DFJKOption.updateDisplay","Options.hx",95,0x9d9a0240) void DFJKOption_obj::__construct( ::Controls controls){ HX_STACKFRAME(&_hx_pos_c83b011b1ca270a7_82_new) HXLINE( 83) super::__construct(); HXLINE( 84) this->controls = controls; } Dynamic DFJKOption_obj::__CreateEmpty() { return new DFJKOption_obj; } void *DFJKOption_obj::_hx_vtable = 0; Dynamic DFJKOption_obj::__Create(::hx::DynamicArray inArgs) { ::hx::ObjectPtr< DFJKOption_obj > _hx_result = new DFJKOption_obj(); _hx_result->__construct(inArgs[0]); return _hx_result; } bool DFJKOption_obj::_hx_isInstanceOf(int inClassId) { if (inClassId<=(int)0x27a70eb9) { return inClassId==(int)0x00000001 || inClassId==(int)0x27a70eb9; } else { return inClassId==(int)0x302cc5bc; } } bool DFJKOption_obj::press(){ HX_GC_STACKFRAME(&_hx_pos_c83b011b1ca270a7_88_press) HXLINE( 89) ::OptionsMenu _hx_tmp = ::OptionsMenu_obj::instance; HXDLIN( 89) _hx_tmp->openSubState( ::KeyBindMenu_obj::__alloc( HX_CTX ,null())); HXLINE( 90) return false; } ::String DFJKOption_obj::updateDisplay(){ HX_STACKFRAME(&_hx_pos_c83b011b1ca270a7_95_updateDisplay) HXDLIN( 95) return HX_("Key Bindings",6f,44,93,fe); } ::hx::ObjectPtr< DFJKOption_obj > DFJKOption_obj::__new( ::Controls controls) { ::hx::ObjectPtr< DFJKOption_obj > __this = new DFJKOption_obj(); __this->__construct(controls); return __this; } ::hx::ObjectPtr< DFJKOption_obj > DFJKOption_obj::__alloc(::hx::Ctx *_hx_ctx, ::Controls controls) { DFJKOption_obj *__this = (DFJKOption_obj*)(::hx::Ctx::alloc(_hx_ctx, sizeof(DFJKOption_obj), true, "DFJKOption")); *(void **)__this = DFJKOption_obj::_hx_vtable; __this->__construct(controls); return __this; } DFJKOption_obj::DFJKOption_obj() { } void DFJKOption_obj::__Mark(HX_MARK_PARAMS) { HX_MARK_BEGIN_CLASS(DFJKOption); HX_MARK_MEMBER_NAME(controls,"controls"); ::Option_obj::__Mark(HX_MARK_ARG); HX_MARK_END_CLASS(); } void DFJKOption_obj::__Visit(HX_VISIT_PARAMS) { HX_VISIT_MEMBER_NAME(controls,"controls"); ::Option_obj::__Visit(HX_VISIT_ARG); } ::hx::Val DFJKOption_obj::__Field(const ::String &inName,::hx::PropertyAccess inCallProp) { switch(inName.length) { case 5: if (HX_FIELD_EQ(inName,"press") ) { return ::hx::Val( press_dyn() ); } break; case 8: if (HX_FIELD_EQ(inName,"controls") ) { return ::hx::Val( controls ); } break; case 13: if (HX_FIELD_EQ(inName,"updateDisplay") ) { return ::hx::Val( updateDisplay_dyn() ); } } return super::__Field(inName,inCallProp); } ::hx::Val DFJKOption_obj::__SetField(const ::String &inName,const ::hx::Val &inValue,::hx::PropertyAccess inCallProp) { switch(inName.length) { case 8: if (HX_FIELD_EQ(inName,"controls") ) { controls=inValue.Cast< ::Controls >(); return inValue; } } return super::__SetField(inName,inValue,inCallProp); } void DFJKOption_obj::__GetFields(Array< ::String> &outFields) { outFields->push(HX_("controls",76,86,bc,37)); super::__GetFields(outFields); }; #ifdef HXCPP_SCRIPTABLE static ::hx::StorageInfo DFJKOption_obj_sMemberStorageInfo[] = { {::hx::fsObject /* ::Controls */ ,(int)offsetof(DFJKOption_obj,controls),HX_("controls",76,86,bc,37)}, { ::hx::fsUnknown, 0, null()} }; static ::hx::StaticInfo *DFJKOption_obj_sStaticStorageInfo = 0; #endif static ::String DFJKOption_obj_sMemberFields[] = { HX_("controls",76,86,bc,37), HX_("press",83,53,88,c8), HX_("updateDisplay",39,8f,b8,86), ::String(null()) }; ::hx::Class DFJKOption_obj::__mClass; void DFJKOption_obj::__register() { DFJKOption_obj _hx_dummy; DFJKOption_obj::_hx_vtable = *(void **)&_hx_dummy; ::hx::Static(__mClass) = new ::hx::Class_obj(); __mClass->mName = HX_("DFJKOption",98,9c,38,d9); __mClass->mSuper = &super::__SGetClass(); __mClass->mConstructEmpty = &__CreateEmpty; __mClass->mConstructArgs = &__Create; __mClass->mGetStaticField = &::hx::Class_obj::GetNoStaticField; __mClass->mSetStaticField = &::hx::Class_obj::SetNoStaticField; __mClass->mStatics = ::hx::Class_obj::dupFunctions(0 /* sStaticFields */); __mClass->mMembers = ::hx::Class_obj::dupFunctions(DFJKOption_obj_sMemberFields); __mClass->mCanCast = ::hx::TCanCast< DFJKOption_obj >; #ifdef HXCPP_SCRIPTABLE __mClass->mMemberStorageInfo = DFJKOption_obj_sMemberStorageInfo; #endif #ifdef HXCPP_SCRIPTABLE __mClass->mStaticStorageInfo = DFJKOption_obj_sStaticStorageInfo; #endif ::hx::_hx_RegisterClass(__mClass->mName, __mClass); }
[ "craftyg425@gmail.com" ]
craftyg425@gmail.com
073a3ea89d45dfa38e1b513a51a81a23d1769fed
a915cc8ca72a714920fa57fed0b8374b26e7970d
/cudahook.h
80e132e41fee6529eacae2adc34c3cf7d65f3b1b
[]
no_license
rafaelfschmid/cudahook-dynamic
cdf3cbc4cd2215a80be7be5d7d1c3060571b1dde
9351689899ab698df577896982968f921aaadfba
refs/heads/master
2020-05-25T16:36:13.940171
2019-06-06T19:17:12
2019-06-06T19:17:12
187,890,620
1
0
null
null
null
null
UTF-8
C++
false
false
1,568
h
#include <stdio.h> #include <dlfcn.h> #include <cassert> #include <list> #include <cuda.h> #include <vector_types.h> #include <vector> #include <boost/interprocess/managed_shared_memory.hpp> #include <boost/interprocess/containers/map.hpp> namespace bip = boost::interprocess; typedef struct { const char* entry; int id = -1; //dim3 gridDim; //dim3 blockDim; int numOfBlocks; int numOfThreads; int numOfRegisters; int sharedDynamicMemory; int sharedStaticMemory; //int computationalTime; cudaStream_t stream; bool start = false; bool finished = false; //std::list<void *> args; } kernelInfo_t; kernelInfo_t &kernelInfo() { static kernelInfo_t _kernelInfo; return _kernelInfo; } /*std::vector<kernelInfo_t> &kernels() { static std::vector<kernelInfo_t> _kernels; return _kernels; }*/ typedef struct { int numOfSMs; int numOfRegister; // register per SM int maxThreads; // max threads per SM int sharedMemory; // sharedMemory per SM } deviceInfo_t; deviceInfo_t &deviceInfo() { static deviceInfo_t _deviceInfo; return _deviceInfo; } std::vector<deviceInfo_t> &devices() { static std::vector<deviceInfo_t> _devices; return _devices; } typedef int KeyType; typedef kernelInfo_t MappedType; typedef std::pair<const int, kernelInfo_t> ValueType; //allocator of for the map. typedef bip::allocator<ValueType, bip::managed_shared_memory::segment_manager> ShmemAllocator; //third parameter argument is the ordering function is used to compare the keys. typedef bip::map<int, kernelInfo_t, std::less<int>, ShmemAllocator> SharedMap;
[ "rafaelfschmid@gmail.com" ]
rafaelfschmid@gmail.com
8b2431e4de308e09fa2458b14768b2d1e5c26bdc
ff7e21977af6d6820f397cc65ed87d6cfe5372a4
/src/test/Test_Annotation_Coco.cpp
5b00b059dc495105221141db4d6131c058a96171
[ "MIT" ]
permissive
Yannick-ll/mask_to_coco
ae7661d72db0c51f9a6cf5239b640fa8a8615734
fb8c6751cfb97bbdc323ca5bcb846c7f7b716218
refs/heads/master
2023-07-09T06:55:12.812590
2021-08-12T13:16:54
2021-08-12T13:16:54
395,322,788
0
0
null
null
null
null
UTF-8
C++
false
false
15,529
cpp
/* * Copyright (C) 2021 Yannick Lufimpu Luviya - All Rights Reserved */ using namespace std; #include "Annotation.h" using namespace RSRCH::COCO; int main(int argc, char** argv) { RSRCH::COCO::Annotation annotation; std::string version = "4.5.6"; RSRCH::COCO::Flags flags; std::vector<RSRCH::COCO::Shape> shapes; std::string imagePath = "..\\butterfly (1).jpg"; std::string imageData = "/9j/4AAQSkZJRgABAQAAAQABAAD/2wBDAAgGBgcGBQgHBwcJCQgKDBQNDAsLDBkSEw8UHRofHh0aHBwgJC4nICIsIxwcKDcpLDAxNDQ0Hyc5PTgyPC4zNDL/2wBDAQkJCQwLDBgNDRgyIRwhMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjL/wAARCAC+AQkDASIAAhEBAxEB/8QAHwAAAQUBAQEBAQEAAAAAAAAAAAECAwQFBgcICQoL/8QAtRAAAgEDAwIEAwUFBAQAAAF9AQIDAAQRBRIhMUEGE1FhByJxFDKBkaEII0KxwRVS0fAkM2JyggkKFhcYGRolJicoKSo0NTY3ODk6Q0RFRkdISUpTVFVWV1hZWmNkZWZnaGlqc3R1dnd4eXqDhIWGh4iJipKTlJWWl5iZmqKjpKWmp6ipqrKztLW2t7i5usLDxMXGx8jJytLT1NXW19jZ2uHi4+Tl5ufo6erx8vP09fb3+Pn6/8QAHwEAAwEBAQEBAQEBAQAAAAAAAAECAwQFBgcICQoL/8QAtREAAgECBAQDBAcFBAQAAQJ3AAECAxEEBSExBhJBUQdhcRMiMoEIFEKRobHBCSMzUvAVYnLRChYkNOEl8RcYGRomJygpKjU2Nzg5OkNERUZHSElKU1RVVldYWVpjZGVmZ2hpanN0dXZ3eHl6goOEhYaHiImKkpOUlZaXmJmaoqOkpaanqKmqsrO0tba3uLm6wsPExcbHyMnK0tPU1dbX2Nna4uPk5ebn6Onq8vP09fb3+Pn6/9oADAMBAAIRAxEAPwB+aTFPxRivojwBmKSpMU3FAhjLSYp5pKAG0uKWlxQA3FLilxS4oASlxTgKMUDG4p1KBRigQlFLiigBKWlooASjFLRigBKMU6koATFKBRSgUAOUU7FNFOFSMTbS7aeKWgCPbQVqQUGgCDFKBTsUYoATFLtWnUZoGQYpKfimtVCEpDTaKBCGjFLinUANxRinYpaAEpcUUtACUtFLigYlFOxRigBuKXFOxS4pMQylxTsUYpANxRin4o20ANxRipMUYoAjxS4qTFGKAGAU7FPUUpFK5VhlLQRRQIKKKKAEopcUUwExRiloxQBCaaacTTDTQDaMU7FGKYCUuKMUuKAExRilxS4oATFGKdijFIBKXFLilxTEIBS4p2KXFADMU7FOxRiiwriYoxTsUoFOwrjcUuKdijFKwXG4oxTsUYoHcbijFOxRSsMSlpcUlIBDSYp1JigBMUUtGKQxKKWloAbRTqKAKhoxS4oqgEApcUtGKLgJilxS4pcUgG0uKXFOxQAzFLinAUuKAEApQKXFLTEJilxUbXMaXtva7l+1TZ8qFWG58AkkD0ABJJ4HeqdpqUuqSSxWFu8jqxCtFGbkbgcYJh3KB776yqYilS+NmtLD1avwI0cUuKzodP1vWNPlvbS9Vfsbn7ZartErBRllWJVdgxH3csOozXK386+MvEelafol82kW9wCPMkvJGVyQxyQWJGAmAMDk8kZzXM8yp/ZTZ0rLan2mkd5tb+5RtrzvxyYtNgt9EgvdI1d7dNk+oWlp5bxuOAGkBwxPf5j0JIqzDo93pUEX9l+I4rG3uERnhv4onm84g5QYB3AYwOmcnis55rGHxL8f+Aawyqc/hf4f8E77a9NIrzCLQr22uZY7PV5bm4hYebDDpc8uwkZwdyHHT07/AFroINN12zhtZJdXWK0mfYWt9JneaABTlpFKKw5AGRu5IPI5qo5pB/Z/r7iZZXOP2l/XzOvoxVSw8N31/ay3+jfECyvLeFT58c1oG2YGTu+YMpxnggdKwvE+seIvC3m6deWtjJqip50f2PfKrQbSTLtI4AK4O4jucECtoZhRlpsYTwFWO2p1GKi8/f8ALAnm/wC0vCj6t/hkivLdR8TaxeWupLb39s0MckMXmQzspyVdmKZCbtxQg5H90DOcn0fRI2m0a1ka4nZ2Tdukb5hkkhSv3QVHynjqD0rWliFWk1FbGdXDOjHmmy3snf70vlf7Ma5P/fTdfyFMFmqTJIrz71z/AMt3IORjBUkj3/Cpis6fddZf+unyn/voAj9KbFcrNNLbsjRSxqHZW7qcgMCOCMgj145AyK2supjd9B+KTFSEUYosK5HilxT8UYqRjMUYp+KMUhjMUuKdilxQOxSApadijFMQ3FGKfijFAxMUYp2KMUhCYoxTsUYoASlxRSigBAKq6ncNZ2XmK6q7SxxeY2Pk3uF3YYgHGc4JA45I61cqC9sbbUrKW0u0823kxvXcRnBBHI5HIFKak4tR3HBxU05bHM+F7W2bV/FUX9vWMthNL9muJmRri5ntgSXZGAAVdgZWcAr0x/C1es6W8et6HF/ZfmaX4dVNsDRqIpZkHGQCP3ceAfm++eo28E+Wl4tE8R2mo6pLo29W2RfabXCXKZUEsqsFj8tQNoVCCRnliMNs9Vu30mwXUJdS1DT2ZtumfZXitfs5UpHMzKrZjDDG07j0OCevzGIpT5rS3R9NTnCSvAuavqmsfD6z1i/0m3g/sPW2WK2mkLs4O05lXJywIY/MxGTtIyB83IeC9U1nwlpl94mtvDmn3Nqqx28d3dgAxyFjgpzk5/iA7bTkDr2Pim78ZXHgP7PFLaXnhmVvs8U1sCbmdRnagBGSu5dudu7Cknjkw6daQap4s8EzeHFtrWzaGWY+Zieb5AUMkwOUDnGEHOzHsFFx92OpM3zSNTQvDjeJ/HOqa7balY6laqqxy6jLZqwa6CjIgjJKhVG35mBOc4znNbcPwqtrHxN/wky+Ib3+1Fcy/aJvIK7mBHK7AoGDgAdO2MCtK08EaRoOmPHPqmoQWrStM7Sai9urM3JPyMijpnA4rJvrv4e20DzwaRFr0u4RjybZrzc5OAvmtuXJPA+bPPGay55Sd1crlSViGWbVPAN7q+ut4h0vVW1Fw8lnMv2eWZ1XCiEoXyxGBjbg8dK2LDx/4m1GzWeL4e6urtjCyyog/N9pxnvt96Twp4Okh8USeLNU0zTNIna2ENrptkqkwDOS0jABTKfu5UdOPpr+KPHVl4bdbMxyXOq3HFpYWuHnlJ6EjGEHXk56HGcYpuz03ZBw/jmw1+5sH8Q6hZWXh3yYdl80Oo+bPdQEqTFtCBGPUDcSMnHQ5rzrxJrja3eNfz6950Ud4LdJbu1eG4lhdAsnEeMopHKA5ySf4sV6ve6DqGpQW9x4v8ifUr5zDpmiRsTa2zFSWlk5/eFF3MxJwMELyy15d4rsktPDsWoreyz6pJPcxXkk212nTz2VXZWJw2EXDKB0A7A1cGluLlctjK8PQW02v6UWTT7S3tVW4dknVnbMIyzMSf44yxU4KmQgcYx6vE9t+6vY7hfs9xhvl5EhI+Vh6EnHPcfQY4Lwp4dsrvRv7bXTlki35WznferqqhZGBOAGLAsM8cbTx8w7600O2ubI3Ftcf6BMRL5K/wADhg25RjK8jDL6kn5TkN3VsXHAYOVSpJRb2736aHHCisVi4xs3FO0u1uv5jpbtYXlVkbbG8cX1L4A/U/pVtYN7pH915EaVWbptU4OfxI/Ktd9OsZt7NErfcl2rk7ipDLnHvUOqeRN5TKi+auVaNf7g5wRnpuGfcDFfN0+LL01CN+bu9Vu3/l+R60snoTq3S01/JL9H82ZbRts3f5//AFf4Gm4q3dMrzfun3RLhE2+g6fjzk+5qArX3eFquvRjV76/Lp+G/mfI4mHsqrp9v6f4kWKMVJikxWrRCYzFGKdijFQ0WmNpaXFLtpDTKVLilxRigYYopaKBBiilxRigBKMUuKXFAxMUUuKXFAhKUUYp+KYivdWVtfw+Td28U8X92RQw+vPesC68IMmn3Vvo2qXdil0qpPHv3JIoztVmILAc+pA9K6ilFTOjCppJXLhWnT+FnHabH/YmuLf3dvF4fihaJIriy3TRxqDiSXD7h5hVtoyvTd8pya2fAfhm5udfmVWudKurH975ibGubmO4w6szYKKoVcYQZBLDI73dU0+2v7Lbc2v2tYXEy2+4gTMvIU47N90/WuO0u61/wbc6hcwrqayyWNrcwSRyfaobKyZiQJVIydikhcYwQ38JOfGxmG9k+WPU9nB4j2sby3PUNbj8LeHNTiWewn1zX5FzFb/Nd3OCcbi0hIjXJ6kgY6dK5jUda8XW3inSNc1jw35tvJvt9K0a2vlLxzspzIw2ncdoYFsYUHt37zS4NL0XRpdRW4VopIzd3WoyNueZQMmVm7kjoOg6AAACqWi2ly9zceJtbZra4mRhFC2B9gtF+bbnn5iPmc9zx0WvNjNb2O2UXsc54s17xxbaH5zpZaDPcSpb2VnDi6u55WI+UucIoxzkAkflnp/DnhfSfAmjT67rU/n6mIDLqOqXDGR3PVgpPO3OAAOWwKxPAWkat4n8St401+LZb7MaPayYIgjY53YycMRjnqdxPpiPxRc/8LB8e/wDCLxS/8U7ojCbVJFbiaYZxET6DBBHqG7gVpdWt0W5lZtinX7qPw/qfxB1KNo57uDydHsmb/UW5I29P4pG2ljzwF7cDzXSdNl1qz8y7haaz0xIklj3N84X5nwF6sQzHnPccFs11XjXVG8TeKE09Dt06wwx25xv28D04X07s3pSW9pGieTBEsar821emf8964KmZQw9ROUb9bbeh9BhsldbDXcuVvyvp16rc6CWTTbDTPJaLbbsmxI4VGCpHQL0AwazX1yKJ/wDQNsDMuJYZsHeu4emcMATg98AH1GXLtRPk/wBazYTd0z6/QDJqK4RbZFhtt3mt1b+In3ry8divr1d1prfZXukv8j18uySjhaCoXbeuu3za1O1kuYE/cx/Nu37tzcDGz7v5/pVCfULR4fmuNryL8jSMASM9yOhz0+tc3DqjWezcFZIckyNyMnsPWo7aaw13HljdFwnyuw+6enB4615sMJye8727m31FwdpPQ6W01JbidCrr9lbd8yr99i4CMPbaGz+vatDFcqyb9qx7oHjl3xeXgBCCDgL0HAC/QVtf25abPuz7/u7VQHp+NfY8P5jRw8JUakko7q/49D5PiHI69eUauHg3LZ2t8i+RTcVQt9f0+5fy/NaJ/wC7IhBrRG103L8yN/EtfV0cVRr/AMKSZ8hisuxeDf8AtFNx9Vp95HijFSYoxVs5kR4oxT8UYqSyjRS4oxQXsFFLinYoCwzFGKfilxQIZijFPxRigBMUooxS0AIKdRS0CEpaWimmIBXC6v4du9K/tfVbLUdV+23v7qL7O42LHIdrJKuMlACcEH5cLx3Hd0orOtRjVjZmtCtKk7o88sNQk8PWr6ZNqNst14flFxcwzaq8ltqiB1aNYEPyhlABGOchcg8he81jx1peu6ALW2g1Jre6ZDfSfZXUQ2IcCSTcQMqwOCQSQGY9qwL7wnaPbS2vlLLps119puY1RftIwuNsUhUsOgG3pjjjJNYEkF7c6fZ2kfiHVNP1LzpLDTodRxFCmnMMYlcDg8KCG/2QF6EeHWwzhL3ke1SxEZx91nuviHXodB8H3V/Zp5s0aeTarHz5kztsRR6jcR+ANcHolm3hXw1LZJuu79l+1X8zPnzrmQhVjDE8lmIUE9eCfvVyMFw32K1mtNK1e20iGVbexaw1BLmGPUQxXfGshJKNkAAnADMRyc1V1XxJNfeR4dd7tZTdfaNWWZIlUyIAQilCxKgjHLdl75riqU2o2b03Z6GEj7SqoxXvPRfM2JlSzRLaKVZYlYl51/5eZicyS/Qk4Uf3QD/EafDfKkH3vmYn+dZjT/aYUjVtrckfUYIH5VkzXscO+YvtXk//AFhXgTpuvJuW5+kUcJTpUuSTskb3ny3N7tjVdykhV/HJOew6flVXUNV0/RUZru6824bsvX6CuEm1a+leXy7qWJJP+ebEfyrDuI3WTdI+7d/F1r0KWWJtc8tOy/zPn8bnvs1ahC67v+rmxrHie51I+XF+5tx0Vev41u/D27jh+1Rs2HjlSX22nIb8uK4Gug8LQX0mswi0tbmZXPlP5SFsA9zj04P4V6NbCRlQdKmjwMJmdSWOjWxEtNn5Jnqd3Pse68v+GQOPzBP8zTLuVtksi/fZUmH16VjtdM7srfKpwrfgOf5VBrOq/ZrZ2X72wIv8z/T8q+chh25KK/rY/Qp040Yc83otX+BtmWC/tt06+m2RfvJ6HI6imW2uXWi3Pl3L7om6Sfwt6Zx0P+1+eaoXFnc6LP8AZZfm2rlG6B0Pt/T1BqrPJ51s0Mnvj6en9a6o06mFrWTs0/uMlQo43DKStKEl12/r+tz0uxvoL+DzIP8AdZe4Pof8as4ryfwzrz6VqEQkfdbt8jf7vofp1H/169ZFfbYDFuvT9/4lv/mfkmeZZDA11Kl8EtvLuv8AJ9mNxRinYortPFKOKMU6uosreF7LQWECh2umy3PZgfXnO3v74xWdSfIrm8Ic7scu8TI+2VGV/wC6y4P5GkxXXeItEu7m6e+3ptZ0t0VvvHJCgnjHLH8qZrOi2GlaO48pvtCsiJMznMjHlvl6AAf59c44iLS7sqWHkm+yLXhjQ7C80dLq5tVlkZ227iegOAMdO1ZeqadaTaBa6vaWv2Z5G2tDuJHJIBGfoPwNdP4caK28KQSyNtjVZHZvQbmOfyqp4ji8q20iygi/0X7Sibt3TAwB75BJz7VyqpL2rV+p0ypr2Sduhn+IfDlpY21rNbb1/eLFLyTuz/Fz0PH05qPX9M0/Qrmzmig81JN2+F3ODgDBz1HWtzxj/wAgMf8AXdP61leOzmWxX/Zk/pTozlLlTfcVaEY8zS7FnVxpunaNBc/2NbM1xhduANmVLfexnjHtVXwnFYX6PbzadAzwqCZm+YvknqD0q343+TTLKP8A6a/yUj+tQ+BV/wCP9v8AcH/oVC/3dy6jt+/Uehh6g8Go6zFb21nFafvfJ/d9/mwGxgAGrOrWGiWE0tqst99ojX+6hUkgEeh7ioNGX7R4ptz/AHp2f8st/Sn+KP8AkY73/gH/AKCK6F8agnbQ5nbkc7dS9HpWjpplg139pW4vI/l8vLc8Z4A9xxVKz0z7N4oisbtFlTfhvRwVJB/ka6iG4+weFbS9W1WeWG3XHYgEDJzjp0J+lc7o13JqPi+3uJ9paRmPy9BhDgD8hWUJzam3tqazhBOC66FjxE1tpt19lg0yz2yRAiRkO5ckj19qreGdJttUubhblWZI0G3axHJPB4+hrW8T6Nf6hfxTWsAkRYgrfMoOck45PvS+CI8Q3kv95lX8gT/WhVLYe6eoezviLSWhz6acv9v/ANnNu2ef5W7vjPX8q0F8O2LeIZdKvE8+3aIum7Gfx4x0yKbav5vjbc3/AD9P+mQP5V0AiZ/GrSfwx2o/U4H8z+VVVqyWjf2fxJpUovW32vwPOI/D2l2F/uiso1lt2aJG5JQZ2kDJ4GBjArxG0la01yXz/v75Ek+uTn9a+hNQ/wCQnd/9d3/9CNcW3w80+bxHLqc8rS28khla1ZeGdiSct/dyc4/pUYzCuvTioL+mdeUZlHBYh1KrvazXXZ7HGR3X7k3P/LJX2eZ23Yzj64yfwPpXPaoy+e3ltlWO78e9ew6J4NttHfUrX5bnSr3aywzZLRlc5XPccjDcEYHXrWLrXwutnhT+xJfLlVjuW5kJDgnj5gOCPpzXmrKKlP346+R9LW4up4uPsaqtro/LzPLYLWe5d1giaR1jZ22rnCqCST7AA1nXf8P41734M8H/APCOQyzXLxS6hN8rNHkqiZ+6CQCc4BP0Hpz5J8QIbK28ZXtrp8CQW8O1dqdMlQTgduSePatpYSVKCnLfsePPMYV5yowV0upylfQ3w3s5LPwPYLIPmm3TfgWJH6YP414Jp1lJqOp2tlH9+4lWJfxIH9a+o7e3itrWK3iTbFGgRV9AowP5V25fD3nI8nMp2godzznx9YSaPdJqcMW+0uG2y7f4JOufowz+OfUVxdhbT+JvEVrZ7W8pnG5fRM5Zj+Gf0r3W/sLbUtPlsruLzIJl2sv45BB7EEA/hVDR/DOl+HzM9hBteXhpWYs2P7oJ6D6VnUyuLxHtI6J7np0uJa/1H6tVk21ov0u/IreKdM+36TLJHFuuLdS6bepA+8B9QPzArxqTV2f7n94/lX0Ca5268EeHbud5pNOVHZtzeXI6g568A459sU8bl0a8/aR3FlHEVbBUPq8m+W915f1/meKwyiGdfM/1W4b8+meele+2ELQ6fbwt8vlxKnc4wMDk8njHXmuE8W+Bmm1a3k0uDbFeP5UqxrxCe7cdFxk/Ue4FejEUsDh5Upy5vT1IzfGwxNKnyPTfzQyjFPxRXpHhFCu28OW32vRtPbcqra3bu35HA/NhXFVoaRbNfX8Vi8siQzMfMVW64Unp0zxWFePNDex00Zcs9rnU3Ot2g+2/aZW3294GSFerhAAAD6bgSfxrOv8AVNNuL/8AtNrqS78pf3Fm0RARsdWPQjPPHt6VW1/w5/ZECTQytJAx2YYDKnBI6dRwawaypUaclzRZpVqzT5ZI7m9nb/hBPMZvnmjXd7lmBP8AM0y8l/4o3Tbif70bwv8AkeP0q/e6ZDN4bitZ52hihRC0nX7o5yKmgTSta0xbeNfOtYSEH3l5CjHoehrlU4pX8zpcZN28hniaD7TpKx/3p4l/NwP61g+OG/4mFqv92It+Z/8ArVrXviOw064axltp2MO3bgKRwAQcls+nNchq+pSapqD3DJt+Xai9cKM/ryfzrXDQndNrTX8TLEzjZpPXT8DpPHIzBZf77fyFHgb/AFN7/vJ/I1p63o/9t20Hl3Cx+XllbbkEED3qPw9o8+j/AGrz5I2WTbtZWPbPXI9xWftI/V+S+v8AwTT2cvb89tDmvCcW/wARo3/PNHb9Mf1qx4n1G2e6urNbCDzVK7rrjfwAfTPt1qp4fvINO1syTvtiZWTd2XJBGfbirWv6YrvPqsd7bSxSONqq2TzgcY4NdLS9veXbQ5ot+waj31NY3KWmlaG0v+qkRY5V7bWTv7A4P4Vm6Vp76b4xS3YfKu9kb1UqcH+n1Bpur3MNz4X02OOWJpY9quqsMrhSDkdR0pNN1/fqdrNfsqrDE0XmKCSc4wTj6frWahLkbXW9zSU486T6WJvGm77fb4ZhuiI49j/9etPwfHs0Zm/56SsfyAH9DWD4m1C21G/ia2bzFjTG7aRzknv+FdF4Xlhm0BIFb5l3B1XqMsSP0qaiaw6THTaeIbRxlrJM+pxSW3zTtLuT3Ocgc13Wn3iXN/cK9nJBeKiiXdgjAzjBB56muevLOw0XVbJobpmMco85X5IHB3cD0roJNS022huNQjnjleRR8qsMtgHAA69z+dPESU0uVb7Cw8eRvme2/wBxxF4f+Jhcf9dX/wDQjTFphO99zffb5mp616MdFY82Su7kgp9Rin1VyeUWvl7Xb3+0vEF/ehtwnuHdfoWOP0xX0V4n1D+y/C2pXm/a8ds3l/7xGF/UivmOvPx872ienl8LKUjufhZpv2/xnFMy/JZxNP7ZxgD9c/hXvVeZ/BzTfJ0m91Fl+a4lCL/ur/8AXJ/KvTlWt8GuWl6nPjHz1fQFXfS3L2lgm67l2/7PVvpjt+vuBS3dx9gh2xf8fDf+OZ/r/wDq7HPIazI1npl1qMqyyvDEXb14Ge9clfN8NTq+ylLXyNYZVi50vaUofeTXvxG8PWF1LbYlZ48b2+bA78lcY9sjrT9K8e6NrEzx/ZbmDoU8xcb1z1G4tkZPYd/evFdTe8N1KI0ZrWNCzeVuaMnozFsYY7jgsRjPHAqHT4Ps11bLPa3OLhC8eFAJGCQ8ZJHIIH1wR7Uvr8L3tp6mn9n1eW19fTT9PzPpKJYLxN1pKsv+z39Rx3/Dn24qBlrA0v5rO1ureXd5kSkSL0cEA/lXTxTfb4XZvluF5b39W+uBz6gHuOShmuGrVPZwlr5inluKpU/aVY2XlsVsUYpxFGK9I40jPxW/4Pi3a/u/55xM/wDIf1rBArq/BEX+mXcn92NV/Mn/AArHEO1Jm1BXqI2PFoX/AIR6XP8AfTH/AH0P6ZrzzFd54yk2aTEv96cZ/BSf8K4u1h869t4f+ejqn5kCssJpSuaYrWpY2brxDqH9mvp97a7XkTasjKyHHqQRz+lbfgsf8SaX/ruf/QVq14qgWXQJ227mjKsvtyAf0JqPwimzQk/2nb+eP6VzzlGVBtK2pvGMo1km76HOeLV2a+zf3o1b+Y/pWGa6/wAQ6JqF/qfnW0SvFsVfvgdM8cn3rnhp81vqcVrcRNGzOq7Wx0LYyMda66NSPIlfoclanL2jdup1PiWBYvC9vD2jaNfyUiuI2rXeeMP+QMn/AF2X+RrhqnCO9O/mVi/4lvISjFdFo2gQTWbahfuywKpYKvGQOrE9ccGi90S2S/01bTzPs95ztPVRwTj8D+lX7eHNymfsJ8vMc7ilxXY6loun/wBq6baxwCPzt+/y+OAuc/nWU+hLN4il0+2ZlijwzM3OBtBP1OTSjiISV/K5UqE4u2+tjDrtPD0LW/h15F+/cS4Vu4BYJn8OTVe80HS0tbxbZpftFnFvZmbIPBIB7dB2x1Fattcx6d4Xt7hh92BSF9WIyB+ZrCvVVSCUe5vRpOnNuXY5PxFKr6/dMv8ACwX8lAP65rPktp4UVpIJYkb7rMhGfpnrXQeG9PW+uZdQuvmWNt3zd3PJJ+nX8a0tZuZBoFwbtVVp32wx91GRjPvgEn64rT23JJU1r0M/Y88XUl1OLFSrTAKeK6zkHilpBRTCxi+L9KXWPDMtpJcNFEzpuZcZODuxz7gV86XVrJbXstq3zPG5Tp154wPevo3xPefZtPSPf/CW/Pj+n615X4b0tdd+IUDMv7q1/wBIl/4Cflz/AMCK/gDXzX1mdfH1Ka+FWS9VuevRSpUlf1PW/DGlLonhzT7D+KOIb/dzyx/Mmt+1Hz7v7v8AkA+xYqPxNVKCa+i5fd5UeZf3uZmn9gS4Pms33v71SN4e85HVotyMpVl25BB6iqWot+5stqKvmQb5NvG45I5/Kk1E7Law2oqs0G87VAyckZP4AV8S+EnUnzyxDu2+i/zPe/tqcVyxjZK3X/gHMav4DPhnwD4hMkoa1gsp/se37wV23bXz3Vs4I6huxHNCD4Zt4v8ABfhq/srlYmls7dLhnOTCkYckx4/iZiBz0xXfpYW1+t6k8VsrL5AWSSJeMjnHHU4//VWTNbKl75MVlFbSqwRVVFDZ6DLADJPr0r2KeVU1HlUve79b237HPLHzte2hrW/hpbCzit4otsUMYRfYAYFDWS23zRsu/wDzj9cVBqNrss4po4pYljYwvuyN+OQ/P94Z/KluIfJs4plt1ktZIBtmVjkSY5DHP97jB4x05ryKXCzp1I1YYh3Tvst9+50yzecouE4aW7/8Aq3K7Jvl+VONvsCAQPwBA/CocVGDT91faLQ8HRlPFdl4JjxbXUv951X8gT/WuPxXe+EY9mh7v+ekrN+WF/pWGLdqRthVeoUPG0nyWUX95nP5YH9TXO6Qn/E5sv8Arun6MDW34zk/4mFrH/diLfmf/rVlaDHv1yyX/b3fkCf6UqOlD5MK2tf5o7PxN/yL91/wH/0IUzwsP+Kft/8Aef8A9CNL4n/5Fy7/AOAf+hil8ND/AIp60/4F/wChGuP/AJcfP9Dt/wCX/wAv1MfxLql/Y6kkdtcNHE0Qbaqjrk56j2rI0ySa/wBftZJ5WlbzVO5vbn+laHjH/kJwf9cB/wChGqnhlN2vwH+7ub/x0j+tdcElQ5ra2OOo269m9LnZ6nYW+o23k3DMqbg2VYA5H1+tcRrlhZWEyx2U/mbgd+5gdh7dP88V0XjE/wDEst1/6bj9A1cXipwkHy819OxeKkubltr3O68QBLPwu0Ef3dqRL9Mj+grL0J7vUdSivLllW3s49i9hkjH545J+lLZ63ZXekmx1Pcu1QN6qTkDoeOQRgVBNcx33kaLpSstuzfPI3Vu5J/LP4dqiMJRi4Na9/IqU1KSknp28zqfsm7V/trdFhESL7liSfyx+tVtGgcXOo3UqMjzXBVc90XhT/OnwQW2i2Ezq7N5a/MzuTkgZAA6Dr0Fc9Y+J7lLtnu8yRN8u1ABs9wP8/pWUKc5p8prOcYNc2jKkl5ezXt7Z23/L5OVb14JGM9hjr7Ct7xBbtD4Zihxu8ny1b8Bj+eKpSalo9pNLfWStLdSZwrAhVJ6nkfy/SqVnr8kMDw3cSXcEjEssnqTk9iMZ5xiujllJqUVa1vmYJxinGTvf8Df8L2zW+jb2/wCWzGVV9sAD88Z/GsVo73xFq372J4YI+G3dIx3HPc/54FVp9cu3v/tULeTtXYkY5AX0I70Xeu393D5ckqqrfeWNcZ+p6040qik5aXf4ClVpuKjrZfiRao9o15tso1WCNdi7f48dWJ7/AF9hVQCkAp1dcVyqxyyd3cKUCimXE32a1lm/uqdv16D+dRXqqjTlUlslccIc0lE8/wDHmq/PLt+4vC/QdKtfC/SWttCl1Wf/AI+NRfcu7r5YyB+ZyfxFcVrYn8Q+J7TSIG+a4lCblbOAeS34AE/hXtdtbxWdrFbwJtihQIi+iqMAflXh5Jh2outPd6/Nndip2jZdfyJaaacTTRt/i/z719CeeX7g21zDZL9qVfLi2SfI57k8cc9ainuYnRI2iWVI8rEzMwO3JIDAHnrTJ4V2eZGnyf3euD1x/h6jB9asXNrbQp/wP7rN2GM/XqfyrmktrPubq7vdFY3Mnk3EbbdszDf8vp0x6AZpz3077GZImeFNisyndggjkg88H8KdGYN/91Nqt97uSAR+GT+VPP2Z03Sy/PuPp0wOePftms7O+/4en6FaW2K9rN9mS4hZPNSZNrLux0OQR7g0201bT0n1K1trrzf3ASW3VW+R2GRk425HJ65xj1qWOG2fe3zfKm/7393JZSO2Rj6GsvS/D2m6P9quILdonu2LPuldstknPLHoWJP1A6nioqXV37hdW2t2JhTsUny76fXQc6RVr0Tw1t/sG12/7X57jmvPcVYgvLuzjzbXEka43bVYgZ+nSsq9J1I2TNaFRU5XZ3WoaBa6ldLcTvNuVQu1WAGASfT3rAsLBdL8Xwws3y4ZomPcEED8eo/CsWW8u3Z5Xupyx/6aGom3v8zNu/3uaiFGaTi5aFzrQcuZR1O58Un/AIkUq/3nVf8Ax4H+lTeHnjfQ7UKyttXn2OTmvPgKXFJ4X3OS/Ur6z7/PbobfiqRJdZ2q27y4lRvY5Jx+RFV/D8622s27SNtVspu+oIH64rOxRitlTSp8hg6l5853PiHTbjUbWJbbbvjfdtY4zxXHXunXOnOkdyu3cuV2sD/Kp7XVtQs0Cx3TbT/C3zD9en4VDe39xqM/mXDhnA2rgYAFZ0adSHu6WNKs4VPe6lbFTWdzJYXMVxH9+P8AvdOmCD+BqKlrdq6szBaO6NPVNdn1REh2rHF1ZVbOT7n09qy8UuKMUowUFaJUpOTuxMUU7FFMkbSgUtOAoAQClxS4pcVQBXN+NdTWw0ny9/zyZZvp0H9a6YCvHPiVqct1fvAnygNsH0yB2ryM3m3CNBfbf4LX/I6sLG8nLsX/AIXaV9r1K/8AEMifKrG3t/qfvH8sD8TXqZqhoOkxaLodppkH3YUClv7zfxH8Tk/jWiwr0cPTVOmooyqy55shNGaUikIrcysSRzMibd/3v8//AF6d5e9GZXX9BnHPGf5dfaocU1j5f3aylFPcpSaJ5ra5h37k+78rN26kdfrkUq2l2/8AC3f6cAk4+mD+VQGaXZt3fL/d7f55NKbmeT70rf55qPZJdF9xXP5v7xzrs+Zn/wBpW4OPpjjP0J/CoZJWfZ/s4X8vYdO/5n1pCaSrjGMVoS3KTHAUtNT79TbapsSTZ//Z"; int imageHeight = 190; int imageWidth = 265; RSRCH::COCO::Shape shape; std::string label = "butterfly"; std::vector< std::vector <float> > points; std::string shape_type = "polygon"; //RSRCH::COCO::Flags flags; std::vector <float> pts1, pts2; pts1.push_back(151.29718875502007);pts1.push_back(112.44979919678714); pts2.push_back(155.714859437751);pts2.push_back(109.03614457831324); points.push_back(pts1); points.push_back(pts2); shape.set_label(label); shape.set_points(points); shape.set_shape_type(shape_type); shape.set_flags(flags); shapes.push_back(shape); annotation.set_version(version); annotation.set_shapes(shapes); annotation.set_imagePath(imagePath); annotation.set_imageData(imageData); annotation.set_imageHeight(imageHeight); annotation.set_imageWidth(imageWidth); nlohmann::json json_annotation_coco = annotation; std::cout << " \n\n\n\n" << json_annotation_coco.dump(4); std::ofstream json_file("/home/deploy/app/tests/jarvis/mask_to_coco/data/json_annotation_coco.json"); json_file << json_annotation_coco.dump(4); return 0; }
[ "yannick.lufimpu.luviya@gmail.com" ]
yannick.lufimpu.luviya@gmail.com
751766e103a7a4d7b8d94c2c372038a556075fe5
a1e801e87a59dc3a1d7fb3a270f7c6767079dda0
/src/ofxCeres/Models/StructuralAnalysis/System.inl
1985f7a32c0b2bc0ed54761530074c1c4864d188
[ "MIT" ]
permissive
n1ckfg/ofxCeres
b39b242b535b8259ac0c8d136c0baabc4fa48f3e
dc24a5d64a8290c88946f03b3b291e0182845f96
refs/heads/master
2022-03-02T01:07:12.569220
2019-11-13T13:29:59
2019-11-13T13:29:59
null
0
0
null
null
null
null
UTF-8
C++
false
false
4,355
inl
#include "System.h" #include "DrawProperties.h" template<int jointConnectionCount, int groundSupportCount> struct SolverError { SolverError(const ofxCeres::Models::StructuralAnalysis::System & system) : referenceSystem(system) { } template<typename T> bool operator() (const T * const parameters , T * residuals) const { auto system = ofxCeres::Models::StructuralAnalysis::TSystem<T>(this->referenceSystem); system.updateStateParameters(parameters); auto & residual = residuals[0]; residual = (T) 0; for (const auto & bodyIt : system.bodies) { residual += bodyIt.second->getForceError(); residual += bodyIt.second->getTorqueError(); } for (const auto & groundSupport : system.groundSupports) { residual += glm::length2(groundSupport.force) * 1e-8; } return true; } static ceres::CostFunction * Create(const ofxCeres::Models::StructuralAnalysis::System & referenceSystem) { return new ceres::AutoDiffCostFunction<SolverError, 1, (jointConnectionCount + groundSupportCount) * 3>( new SolverError(referenceSystem) ); } const ofxCeres::Models::StructuralAnalysis::System & referenceSystem; }; namespace ofxCeres { namespace Models { namespace StructuralAnalysis { //---------- template<typename T> std::string TSystem<T>::JointAddress::toString() const { return this->bodyName + "." + this->jointName; } //---------- template<typename T> TSystem<T>::Body::Body() { } //---------- template<typename T> T TSystem<T>::Body::getForceError() const { glm::tvec3<T> total; for (const auto & loadIt : this->loads) { total += loadIt.second.force; } for (const auto & jointIt : this->joints) { total += jointIt.second.force; } return glm::dot(total, total); } //---------- template<typename T> T TSystem<T>::Body::getTorqueError() const { glm::tvec3<T> total; for (const auto & loadIt : this->loads) { total += glm::cross(loadIt.second.position, loadIt.second.force); } for (const auto & jointIt : this->joints) { total += glm::cross((glm::tvec3<T>) jointIt.second.position, jointIt.second.force); } return glm::dot(total, total); } //---------- template<typename T> void TSystem<T>::setJointForce(const JointAddress & jointAddress , const glm::tvec3<T> & force , bool inverse) { auto & body = this->bodies[jointAddress.bodyName]; auto & joint = body->joints[jointAddress.jointName]; auto bodyInverseRotation = glm::inverse(body->getGlobalOrientation()); joint.force = (glm::tquat<T>) bodyInverseRotation * force * (T) (inverse ? -1.0 : 1.0); } //---------- template<int jointConnectionCount, int groundSupportCount> bool System::solve(const SolverSettings & solverSettings) { if (this->jointConnections.size() != jointConnectionCount) { throw(ofxCeres::Exception("Number of joint constraints does not match templated constant jointConnectionCount")); } if (this->groundSupports.size() != groundSupportCount) { throw(ofxCeres::Exception("Number of ground supports does not match templated constant groundSupportCount")); } this->throwIfBadJointConnection(); double systemState[(jointConnectionCount + groundSupportCount) * 3]; //take the state from current system { auto movingOutput = (glm::tvec3<double> *) systemState; for (const auto & jointConnection : this->jointConnections) { *movingOutput++ = (glm::tvec3<double>) jointConnection.force; } for (const auto & groundSupport : this->groundSupports) { *movingOutput++ = (glm::tvec3<double>) groundSupport.force; } } ceres::Problem problem; auto costFunction = SolverError<jointConnectionCount, groundSupportCount>::Create(*this); problem.AddResidualBlock(costFunction , NULL , systemState); ceres::Solver::Summary summary; ceres::Solve(solverSettings.options, &problem, &summary); if (solverSettings.printReport) { cout << summary.FullReport() << endl; } this->updateStateParameters(systemState); return summary.termination_type == ceres::TerminationType::CONVERGENCE; } } } }
[ "elliot@kimchiandchips.com" ]
elliot@kimchiandchips.com