text
stringlengths
65
6.05M
lang
stringclasses
8 values
type
stringclasses
2 values
id
stringlengths
64
64
/*! * \file OxCalculatorT2Truncation_test.cpp * \author Konrad Werys * \date 2019/11/01 */ #include "gtest/gtest.h" #include "OxTestData.h" #include "CmakeConfigForTomato.h" #ifdef USE_PRIVATE_NR2 #include "OxModelT2TwoParamScale.h" #include "OxFitterAmoebaVnl.h" #include "OxFitterLevenbergMarquardtVnl.h" #include "OxStartPointCalculatorBasic.h" #include "OxCalculatorT2Truncation.h" #ifdef USE_VNL TEST(OxCalculatorT2Truncation, highR2_lowT2) { typedef double TYPE; TYPE signal[] = {110, 75, 49, 35, 25, 18, 11, 8}; TYPE echoTimes[] = {3, 6, 9, 12, 15, 18, 21, 24}; int nSamples = 8; double tolerance = 1e-4; double correctT2 = 7.9055; double correctR2 = 0.9990; double correctFe = 3.6119; double correctNSamplesUsed = 8; double correctExitCondition = 1; // init the necessary objects Ox::ModelT2TwoParamScale<TYPE> model; Ox::FitterLevenbergMarquardtVnl<TYPE> fitter; Ox::CalculatorT2Truncation<TYPE> calculator; // configure calculator.setModel(&model); calculator.setFitter(&fitter); // set the data calculator.setNSamples(nSamples); calculator.setEchoTimes(echoTimes); calculator.setSigMag(signal); calculator.calculate(); EXPECT_NEAR(calculator.getResults()["T2"], correctT2, tolerance); EXPECT_NEAR(calculator.getResults()["R2"], correctR2, tolerance); EXPECT_NEAR(calculator.getResults()["Fe"], correctFe, tolerance); EXPECT_NEAR(calculator.getResults()["nSamplesUsed"], correctNSamplesUsed, tolerance); EXPECT_NEAR(calculator.getResults()["exitCondition"], correctExitCondition, tolerance); } TEST(OxCalculatorT2Truncation, highR2_highT2) { typedef double TYPE; TYPE signal[] = {106, 94, 84, 74, 66, 58, 52, 46}; TYPE echoTimes[] = {3, 6, 9, 12, 15, 18, 21, 24}; int nSamples = 8; double tolerance = 1e-4; double correctT2 = 25.1418; double correctR2 = 0.9998; double correctFe = 0.8805; double correctNSamplesUsed = 8; double correctExitCondition = 1; // init the necessary objects Ox::ModelT2TwoParamScale<TYPE> model; Ox::FitterAmoebaVnl<TYPE> fitter; Ox::CalculatorT2Truncation<TYPE> calculator; // configure calculator.setModel(&model); calculator.setFitter(&fitter); // set the data calculator.setNSamples(nSamples); calculator.setEchoTimes(echoTimes); calculator.setSigMag(signal); calculator.calculate(); EXPECT_NEAR(calculator.getResults()["T2"], correctT2, tolerance); EXPECT_NEAR(calculator.getResults()["R2"], correctR2, tolerance); EXPECT_NEAR(calculator.getResults()["Fe"], correctFe, tolerance); EXPECT_NEAR(calculator.getResults()["nSamplesUsed"], correctNSamplesUsed, tolerance); EXPECT_NEAR(calculator.getResults()["exitCondition"], correctExitCondition, tolerance); } TEST(OxCalculatorT2Truncation, truncationInWork) { typedef double TYPE; TYPE signal[] = {110, 75, 49, 35, 24, 25, 26, 25}; TYPE echoTimes[] = {3, 6, 9, 12, 15, 18, 21, 24}; int nSamples = 8; double tolerance = 1e-4; double correctB = 162.6716; double correctDeltaB = 2.9064; double correctT2 = 7.6755; double correctDeltaT2 = 0.1864; double correctR2 = 0.9991; double correctFe = 3.7444; double correctDeltaFe = 0.1109; double correctNSamplesUsed = 4; double correctExitCondition = 3; // init the necessary objects Ox::ModelT2TwoParamScale<TYPE> model; Ox::FitterAmoebaVnl<TYPE> fitter; Ox::CalculatorT2Truncation<TYPE> calculator; // configure calculator.setModel(&model); calculator.setFitter(&fitter); // set the data calculator.setNSamples(nSamples); calculator.setEchoTimes(echoTimes); calculator.setSigMag(signal); calculator.calculate(); EXPECT_NEAR(calculator.getResults()["B"], correctB, tolerance); EXPECT_NEAR(calculator.getResults()["deltaB"], correctDeltaB, tolerance); EXPECT_NEAR(calculator.getResults()["T2"], correctT2, tolerance); EXPECT_NEAR(calculator.getResults()["deltaT2"], correctDeltaT2, tolerance); EXPECT_NEAR(calculator.getResults()["R2"], correctR2, tolerance); EXPECT_NEAR(calculator.getResults()["Fe"], correctFe, tolerance); EXPECT_NEAR(calculator.getResults()["deltaFe"], correctDeltaFe, tolerance); EXPECT_NEAR(calculator.getResults()["nSamplesUsed"], correctNSamplesUsed, tolerance); EXPECT_NEAR(calculator.getResults()["exitCondition"], correctExitCondition, tolerance); } TEST(OxCalculatorT2Truncation, lowR2_highT2) { typedef double TYPE; TYPE signal[] = {109, 93, 86, 72, 64, 60, 52, 49}; TYPE echoTimes[] = {3, 6, 9, 12, 15, 18, 21, 24}; int nSamples = 8; double tolerance = 1e-4; double correctT2 = 25.1101; double correctR2 = 0.9897; double correctFe = 0.8818; double correctNSamplesUsed = 8; double correctExitCondition = 4; // init the necessary objects Ox::ModelT2TwoParamScale<TYPE> model; Ox::FitterAmoebaVnl<TYPE> fitter; Ox::CalculatorT2Truncation<TYPE> calculator; // configure calculator.setModel(&model); calculator.setFitter(&fitter); // set the data calculator.setNSamples(nSamples); calculator.setEchoTimes(echoTimes); calculator.setSigMag(signal); calculator.calculate(); EXPECT_NEAR(calculator.getResults()["T2"], correctT2, tolerance); EXPECT_NEAR(calculator.getResults()["R2"], correctR2, tolerance); EXPECT_NEAR(calculator.getResults()["Fe"], correctFe, tolerance); EXPECT_NEAR(calculator.getResults()["nSamplesUsed"], correctNSamplesUsed, tolerance); EXPECT_NEAR(calculator.getResults()["exitCondition"], correctExitCondition, tolerance); } TEST(OxCalculatorT2Truncation, calculateFitError) { typedef double TYPE; TYPE signal[] = {109, 93, 86, 72, 64, 60, 52, 49}; TYPE echoTimes[] = {3, 6, 9, 12, 15, 18, 21, 24}; int nSamples = 8; double tolerance = 1e-4; double correctDeltaB = 2.4428; double correctDeltaT2 = 1.0852; double correctDeltaFe = 0.0465; // init the necessary objects Ox::ModelT2TwoParamScale<TYPE> model; Ox::FitterAmoebaVnl<TYPE> fitter; Ox::CalculatorT2Truncation<TYPE> calculator; // configure calculator.setModel(&model); calculator.setFitter(&fitter); // set the data calculator.setNSamples(nSamples); calculator.setEchoTimes(echoTimes); calculator.setSigMag(signal); calculator.calculate(); EXPECT_NEAR(calculator.getResults()["deltaB"], correctDeltaB, tolerance); EXPECT_NEAR(calculator.getResults()["deltaT2"], correctDeltaT2, tolerance); EXPECT_NEAR(calculator.getResults()["deltaFe"], correctDeltaFe, tolerance); } TEST(OxCalculatorT2Truncation, startPointCalculator) { typedef double TYPE; TYPE signal[] = {109, 93, 86, 72, 64, 60, 52, 49}; TYPE echoTimes[] = {3, 6, 9, 12, 15, 18, 21, 24}; int nSamples = 8; double tolerance = 1e-4; double correctDeltaB = 2.4428; double correctDeltaT2 = 1.0852; double correctDeltaFe = 0.0465; // init the necessary objects Ox::ModelT2TwoParamScale<TYPE> model; Ox::FitterAmoebaVnl<TYPE> fitter; Ox::StartPointCalculatorBasic<TYPE> startPointCalculator; Ox::CalculatorT2Truncation<TYPE> calculator; // configure calculator.setModel(&model); calculator.setFitter(&fitter); calculator.setStartPointCalculator(&startPointCalculator); // set the data calculator.setNSamples(nSamples); calculator.setEchoTimes(echoTimes); calculator.setSigMag(signal); calculator.calculate(); EXPECT_NEAR(calculator.getResults()["deltaB"], correctDeltaB, tolerance); EXPECT_NEAR(calculator.getResults()["deltaT2"], correctDeltaT2, tolerance); EXPECT_NEAR(calculator.getResults()["deltaFe"], correctDeltaFe, tolerance); } TEST(OxCalculatorT2Truncation, copyConstructor) { typedef double TYPE; TYPE signal[] = {109, 93, 86, 72, 64, 60, 52, 49}; TYPE echoTimes[] = {3, 6, 9, 12, 15, 18, 21, 24}; int nSamples = 8; // init the necessary objects Ox::ModelT2TwoParamScale<TYPE> model; Ox::FitterAmoebaVnl<TYPE> fitterAmoebaVnl; Ox::CalculatorT2Truncation<TYPE> calculator; // configure calculator.setModel(&model); calculator.setFitter(&fitterAmoebaVnl); // set the data calculator.setNSamples(nSamples); calculator.setEchoTimes(echoTimes); calculator.setSigMag(signal); calculator.setMeanCutOff(123); Ox::CalculatorT2Truncation<TYPE> calculatorCopy = calculator; EXPECT_EQ(calculator.getMeanCutOff(), calculatorCopy.getMeanCutOff()); EXPECT_EQ(calculator.getNSamples(), calculatorCopy.getNSamples()); EXPECT_EQ(calculator.getNDims(), calculatorCopy.getNDims()); // empty object pointers EXPECT_THROW(calculatorCopy.getModel(), std::runtime_error); EXPECT_THROW(calculatorCopy.getFitter(), std::runtime_error); // empty array pointers EXPECT_THROW(calculatorCopy.getEchoTimes(), std::runtime_error); EXPECT_FALSE(calculatorCopy.getRepTimes()); EXPECT_FALSE(calculatorCopy.getRelAcqTimes()); EXPECT_THROW(calculatorCopy.getSigMag(), std::runtime_error); EXPECT_FALSE(calculatorCopy.getSigPha()); // non-empty pointers of internal arrays EXPECT_TRUE(calculatorCopy.getSignal()); EXPECT_TRUE(calculatorCopy.getSigns()); EXPECT_TRUE(calculatorCopy.getStartPoint()); } #endif // USE_VNL #endif // USE_PRIVATE_NR2
C++
CL
ec91042479423302de5357b21d28203125c4e5eb34af28b6ede77126f143ddd6
// Fill out your copyright notice in the Description page of Project Settings. #pragma once #include "CoreMinimal.h" /// <summary> /// Singleton instance containing all game information /// </summary> class DWELLERS_API GameEncapsulator { public: GameEncapsulator(); ~GameEncapsulator(); /// <summary> /// Creates a map with parameters /// </summary> /// <param Name="Mapsize">The width and Height of the map</param> /// <param Name="Chunksize">The Size of a Chunk</param> /// <param Name="Cellsize">The Size of a cell</param> /// <param Name="Cellheight">The scale for one unit upwards between cells</param> static void CreateGame(int Mapsize, int Chunksize, int Cellsize, float Cellheight); /// <summary> /// Get the Singleton instance of the game /// </summary> /// <returns>The game instane</returns> static GameEncapsulator* GetGame(); /// <summary> /// The map used for world spawning and navigation /// </summary> class WorldMap* Map; //Culling distances int MinCull = 10000; int MaxCull = 15000; private: //The game instance static GameEncapsulator* gameencapsulator; };
C++
CL
30f1e22c53a5bb321ab79ed9914395f875a0a4df5d23fd9d5ece7670bfe58217
//! \file //! \brief //! //! Primary Author: Nathan Myers //! Contributing Authors: Matt Edlefsen, Maduna #ifndef AUTONOMY_GUI_HPP #define AUTONOMY_GUI_HPP #include <SDL/SDL.h> #include <SDL/SDL_mixer.h> #include <SDL/SDL_image.h> #include <SDL/SDL_gfxPrimitives.h> #include <SDL/SDL_ttf.h> #include <autonomy/viewport.hpp> #include <autonomy/entity/drone.hpp> #include <autonomy/entity/asteroid.hpp> #include <autonomy/entity/base_station.hpp> #include <autonomy/entity/scripted_drone.hpp> #include <autonomy/location_module.hpp> #include <autonomy/util/serialization.hpp> #include <boost/thread/thread.hpp> #include <boost/thread/mutex.hpp> #include <boost/tuple/tuple.hpp> #include <vector> #include <typeinfo> #include <string> #include <boost/lexical_cast.hpp> namespace autonomy { // state keeps track of where the gui is at enum state { SPLASH, //Winner's don't use drugs TITLE, //title screen GAME, //main game screenv MENU //main menu }; template <typename parent_type> class gui { friend class boost::serialization::access; public: //! Gui Constructor //! Starts the gui_thread with the gui_frame function and initializes done to false gui(); //! Gui Destructor //! Sets done to true and then joins gui_thread ~gui(); //! run() //! This is the main loop of the gui void run(); //! forces the gui to update it's information void do_update(); parent_type& parent() { return *static_cast<parent_type*>(this); } const parent_type& parent() const { return *static_cast<const parent_type*>(this); } private: //private empty copy constructor needed because threads are noncopyable gui(const gui&) {} //! fetches and stores void get_entities(); void display_world(); void display_HUD(); void display_menu(); void resolve_mouse_click(int x, int y,int button); void print_debug(); bool init(); SDL_Surface* load_image( std::string filename ); void apply_surface( int x, int y, SDL_Surface* source, SDL_Surface* destination ); void clean_up(); void display_entity(int color, int x, int y); void display_grid(); int gui_trunc(double n); bool done; boost::mutex update_mutex; bool _do_update; //TODO Add local variables like list of location,entity type pairs to display entity_id_t selected_object; typename location_module<parent_type>::view_ptr_t _entities; boost::thread gui_thread; SDL_Event update_event; SDL_Event event; state gui_state; ui::viewport viewport; SDL_Surface *title_screen; SDL_Surface *dont_do_drugs; SDL_Surface *screen; SDL_Surface *text_buffer; Mix_Music *music; TTF_Font *FONT; bool debug; bool paused; bool gridded; int SCREEN_BPP; int HUD_SIZE; int TICK_DELAY; template < class Archive > void serialize( Archive & ar, const unsigned int version ) { } }; } #include <autonomy/gui.inc.cpp> #endif
C++
CL
e673f0d8fcabeca5e6b3b80decff6d86d8da851c52b04ebe1a151f50259d5036
#ifndef CMOVE_TO_TARGET_COMPONENT_H #define CMOVE_TO_TARGET_COMPONENT_H #include "CComponent.h" #include "CMoverComponent.h" #include "CPositionComponent.h" class CMoveToTargetComponent : public CComponent{ public: //Constructor CMoveToTargetComponent(float sightRadius); //Destructor ~CMoveToTargetComponent(){}; //onExecute - executes the component void onExecute(); //onComponentAdded - informs component another component was added to entity void onComponentAdded(CComponent* component); //setSpeed - sets speed to given value void setTarget(Collider* target){m_target = target;} protected: float m_sightRadius; Collider* m_target; CMoverComponent* m_mover; CPositionComponent* m_position; CColliderComponent* m_collider; }; #endif // CMOVE_TO_TARGET_COMPONENT_H
C++
CL
e32cd42833ea5094d43cf4e11b9993fc7423ed0afdc01a92b313391ffa5e2878
#ifndef REQUESTBUILDER_H #define REQUESTBUILDER_H #include <QObject> #include <QString> #include <QBuffer> #include <QDataStream> #include <QTcpSocket> #include <QQueue> #include <QMutex> #include <QMutexLocker> #include <QWaitCondition> #include <QMessageBox> #include <common.h> #include <clientsideproxy.h> class ClientSideProxy; class RequestBuilder : public QObject { Q_OBJECT public: explicit RequestBuilder(QObject *parent = 0); QTcpSocket::SocketState state(); bool tryConnect(); void disconnectFromHost(); UserInfo user; signals: void loggedIn(bool succes); void loadDomains(QList<DomainInfo> domains); void loadDomainById(DomainInfo domain); void loadTermsByDomain(QList<TermInfo> terms); void loadTerms(QList<TermInfo> terms); void loadConcept(ConceptInfo ci); void loadConceptText(QString text); void loadSearch(QList<quint32> results); void loadTerm(TermInfo term); void termAdded(TermInfo term); void termEditionCompleted(TermInfo term); public slots: void startTransaction(); QByteArray endTransaction(); void login(QString user, QString password); void getAllDomains(); void getDomainById(quint32 domainId); void getAllTermsByDomain(quint32 domainId); void getConcept(quint32 conceptId); void getConceptText(quint32 conceptId); void getAllTerms(quint32 start, quint32 length); void getTerm(quint32 termId); void search(QString search); void addTerm(QString term); void addTermToExisting(QString term, quint32 anotherTermId); void editTerm(quint32 termId,QString term,QStringList keywords, QString text); void on_responseReady(PacketHeader header, QBufferPtr data); void on_getAllDomains(PacketHeader header, QByteArray data); void on_getAllTerms(PacketHeader header, QByteArray data); void on_getConcept(PacketHeader header, QByteArray data); void on_getConceptText(PacketHeader header, QByteArray data); void on_getDomainById(PacketHeader header, QByteArray data); void on_getTerm(PacketHeader header, QByteArray data); void on_getTermsByDomain(PacketHeader header, QByteArray data); void on_getUserById(PacketHeader header, QByteArray data); void on_search(PacketHeader header, QByteArray data); void on_addTerm(PacketHeader header, QByteArray data); void on_editTerm(PacketHeader header, QByteArray data); void on_login(PacketHeader header, QByteArray data); void on_error(PacketHeader header, QByteArray data); void on_forbidden(PacketHeader header, QByteArray data); void on_notFound(PacketHeader header, QByteArray data); void on_timeout(PacketHeader header, QByteArray data); private: void terminateTransaction(); void log(QString text); ClientSideProxy * m_proxy; QBuffer m_transaction; QQueue<quint32> m_queue; bool m_is_transaction; QMap<quint32,QString> m_methods; QMutex m_mutex,m_start_mutex; QWaitCondition m_transactionClosed; QWaitCondition m_activeTransaction; }; #endif // REQUESTBUILDER_H
C++
CL
d647bf9962c196974935a93b41bd626f84417e25fc0fd5a732f79387c9ac1f00
#include "PointOperation.h" Mat MyPO::quantization(const Mat &img, int bpx) //bit(s) per pixel { int range = pow(2, 8 - bpx); vector<Mat> channels; channels.clear(); split(img, channels); Mat res = Mat(img.size(), CV_8U); for (int c = 0, num_channel = channels.size(); c < num_channel; ++c) { channels[c] = (channels[c] - range/2) / range; //opencv always round to nearest number channels[c] = range * channels[c] + range - 1; } merge(channels, res); return res; } Mat MyPO::linearChange(const Mat &img, double alpha, double beta) { Mat imgF, res; img.convertTo(imgF, CV_32F); imgF = imgF * alpha + beta; imgF.convertTo(res, CV_8U); return res; } Mat MyPO::powerChange(const Mat &img, double gamma) { gamma = (gamma + 1) / 10; //advoid division by zero Mat imgF, res; img.convertTo(imgF, CV_32F); pow(imgF, 1/gamma, imgF); normalize(imgF, imgF, 0, 255, CV_MINMAX); imgF.convertTo(res, CV_8U); return res; } Mat MyPO::sigmoid(const Mat& img, double gain, double cutoff) { Mat res, imgF; img.convertTo(imgF, CV_32F); normalize(imgF, imgF, 0, 1, CV_MINMAX); exp(gain * (cutoff - imgF), imgF); imgF += 1; imgF = 1 / imgF; normalize(imgF, imgF, 0, 255, CV_MINMAX); imgF.convertTo(res, CV_8U); return res; } Mat MyPO::applyThreshold(const Mat &img, int threshold){ Mat gray; if (img.channels() == 1) gray = img.clone(); else gray = MyCvtClr::convert_RGB2GRAY(img); for (int i = 0, row = gray.rows; i < row; ++i) for (int j = 0, col = gray.cols; j < col; ++j) if (gray.at<uint8_t>(i, j) > threshold) gray.at<uint8_t>(i, j) = 255; else gray.at<uint8_t>(i, j) = 0; return gray; } int MyPO::OtsuThreshold(const Mat &img) { if (img.channels() != 1) return -1; double His[MAX_SIZE]; double mean_level[MAX_SIZE]; double P[MAX_SIZE]; double sum[MAX_SIZE]; int row = img.rows; int col = img.cols; int deltaHis = 1; int L = MAX_SIZE; for (int i = 0; i < L; ++i) His[i] = 0; for (int i = 0; i < row; ++i) for (int j = 0; j< col; ++j) ++His[img.at<uint8_t>(i, j)]; sum[0] = His[0]; mean_level[0] = 0; His[0] /= (row * col * deltaHis); for (int i = 1; i < L; ++i) { His[i] /= (row * col * deltaHis); sum[i] = sum[i - 1] + His[i]; mean_level[i] = mean_level[i - 1] + i * His[i]; } double variance = -1; int res = 0; for (int i = 1; i < L - 1; ++i) { P[i] = sum[i] / sum[L - 1]; double tu = mean_level[L - 1] * P[i] - mean_level[i]; double mau = P[i] * (1 - P[i]); if (variance < tu / mau * tu) { variance = tu / mau * tu; res = i; } } return res; } Mat MyPO::adaptiveThreshold(const Mat &img) { Mat gray, res; if (img.channels() == 1) gray = img.clone(); else gray = MyCvtClr::convert_RGB2GRAY(img); int threshold = OtsuThreshold(gray); return applyThreshold(gray, threshold); } Mat MyPO::constrastStretching(const Mat &img, int in_low, int in_high, int out_low, int out_high) { in_low += (in_low == 0); if (in_high - in_low == 0) { if (in_low < 254) ++in_high; else --in_low; } Mat res = Mat(img.size(), CV_8UC1); for (int i = 0, row = img.rows; i < row; ++i) for (int j = 0, col = img.cols; j < col; ++j) { int t = img.at<uint8_t>(i, j); if (t <= in_low) t = float(out_low)/in_low * t; else { if (t > in_high) t = (float(255 - out_high)/(255 - in_high)) * (t - in_high) + out_high; else t = (float(out_high - out_low)/(in_high - in_low))*(t - in_low) + out_low; } res.at<uint8_t>(i, j)= t; } return res; }
C++
CL
d2f4007f2b2c9206fb1a7d2a9e830e26e2ecbfd9ce939d1d68ec0e0679b15dec
/* * File: DirectBlockFile.cpp * Author: timboldt * * Created on February 17, 2013, 6:33 PM */ #include <errno.h> #include <exception> #include <fcntl.h> #include <sstream> #include <stdexcept> #include "DirectBlockFile.h" DirectBlockFile::DirectBlockFile() { } DirectBlockFile::~DirectBlockFile() { } void DirectBlockFile::openFile(std::string nameOfFileToOpen, bool createNew) { fileName = nameOfFileToOpen; int fileFlags = O_RDWR; if (createNew) { fileFlags |= O_CREAT; } // TODO: Make this code portable to Linux by using O_DIRECT on Linux platforms fileId = open(fileName.c_str(), fileFlags); if (fileId <= 0) { fileId = 0; throw std::runtime_error(getFileErrorMessage("Failed to open file.", errno)); } int res = fcntl(fileId, F_NOCACHE, 1); if (res < 0) { throw std::runtime_error(getFileErrorMessage("fcntl failed.", errno)); } } void DirectBlockFile::closeFile() { if (fileId > 0) { int res = close(fileId); fileId = 0; if (res < 0) { throw std::runtime_error(getFileErrorMessage("Failed to close file.", errno)); } } } Byte * DirectBlockFile::getBlock(BlockId_t blockId) { Byte * data = NULL; off_t offset = lseek(fileId, blockId * BLOCK_SIZE, SEEK_SET); if (offset < 0) { throw std::runtime_error(getFileErrorMessage("Seek failed.", errno)); } data = new Byte[BLOCK_SIZE]; ssize_t bytesRead = read(fileId, data, BLOCK_SIZE); if (bytesRead <= 0) { delete [] data; data = NULL; throw std::runtime_error(getFileErrorMessage("Read failed.", errno)); } return data; } void DirectBlockFile::updateBlock(BlockId_t blockId, const Byte * data) { off_t offset = lseek(fileId, blockId * BLOCK_SIZE, SEEK_SET); if (offset < 0) { throw std::runtime_error(getFileErrorMessage("Seek failed.", errno)); } //TODO: write } BlockId_t DirectBlockFile::appendBlock(const Byte * data) { off_t offset = lseek(fileId, 0, SEEK_END); if (offset < 0) { throw std::runtime_error(getFileErrorMessage("Seek failed.", errno)); } ssize_t written = write(fileId, data, BLOCK_SIZE); if (written < 0) { throw std::runtime_error(getFileErrorMessage("Write (append) failed.", errno)); } return offset / BLOCK_SIZE; } std::string DirectBlockFile::getFileErrorMessage(const char * message, int errNumber) { std::ostringstream stringStream; stringStream << message << " Filename: " << this->fileName << " Error: " << strerror(errNumber); //************ std::string s = stringStream.str().c_str(); //************ return std::string(stringStream.str()); }
C++
CL
77e5c1cf1ba60d65629e92b50df94049940e7f1fae2e8953e8bddc74e12f9a6e
#include <iostream> #include <map> #include <CGAL/Exact_predicates_inexact_constructions_kernel.h> #include <CGAL/Delaunay_triangulation_2.h> #include <CGAL/Triangulation_face_base_with_info_2.h> typedef CGAL::Exact_predicates_inexact_constructions_kernel K; typedef CGAL::Triangulation_vertex_base_2<K> Vb; typedef CGAL::Triangulation_face_base_with_info_2<int,K> Fb; typedef CGAL::Triangulation_data_structure_2<Vb,Fb> Tds; typedef CGAL::Delaunay_triangulation_2<K,Tds> Triangulation; typedef Triangulation::Finite_faces_iterator Face_iterator; typedef Triangulation::All_faces_iterator All_face_iterator; typedef Triangulation::Face_handle Face; struct InvLong { long value; InvLong() {} InvLong(long v) : value(v) {} }; bool operator < (const InvLong& e1, const InvLong& e2) { return (e1.value > e2.value); } bool operator > (const InvLong& e1, const InvLong& e2) { return (e1.value < e2.value); } bool operator <= (const InvLong& e1, const InvLong& e2) { return (e1.value >= e2.value); } bool operator >= (const InvLong& e1, const InvLong& e2) { return (e1.value <= e2.value); } struct Edge { int u,v; Edge(int u, int v) : u(u),v(v) {} }; bool operator < (const Edge& e1, const Edge& e2) { return (e1.u < e2.u or (e1.u == e2.u and e1.v < e2.v)); } #include <boost/graph/kruskal_min_spanning_tree.hpp> #include <boost/graph/adjacency_list.hpp> typedef boost::adjacency_list<boost::vecS, boost::vecS, boost::undirectedS, boost::no_property, boost::property<boost::edge_weight_t, InvLong> > weighted_graph; typedef boost::graph_traits<weighted_graph>::edge_descriptor edge_desc; typedef boost::property_map<weighted_graph, boost::edge_weight_t>::type weight_map; typedef boost::graph_traits<weighted_graph>::out_edge_iterator out_edge_it; int main() { std::ios_base::sync_with_stdio(false); while(true) { int n,m; std::cin >> n; if(n==0) {break;} std::vector<K::Point_2> pts; pts.reserve(n); std::map<K::Point_2,int> ptoi; std::vector<long> xx; std::vector<long> yy; xx.reserve(n); yy.reserve(n); for(int i=0; i<n; i++) { int x,y; std::cin >> x >> y; pts.push_back(K::Point_2(x,y)); ptoi[pts[i]] = i; xx.push_back(x); yy.push_back(y); } Triangulation t; t.insert(pts.begin(),pts.end()); // label faces: long big = 1l << 60; int cnt = 1; for (All_face_iterator f = t.all_faces_begin(); f != t.all_faces_end(); ++f) { //std::cout << t.triangle(f) << "\n"; if(t.is_infinite(f)) { f->info() = big; } else { f->info() = cnt++; } } //std::cout << "cnt " << cnt << std::endl; weighted_graph G(cnt); weight_map weights = boost::get(boost::edge_weight, G); edge_desc e; std::vector<long> critical(cnt,0); for (All_face_iterator f = t.all_faces_begin(); f != t.all_faces_end(); ++f) { int i = f->info(); //std::cout << t.triangle(f) << "\n"; if(t.is_infinite(f)) { critical[i] = big; } else { // add edges for(int nn=0; nn<3; nn++) { Face nei = f->neighbor(nn); int ni = nei->info(); K::Point_2 &p0 = f->vertex((nn+1) % 3)->point(); K::Point_2 &p1 = f->vertex((nn+2) % 3)->point(); int i0 = ptoi[p0]; int i1 = ptoi[p1]; long dx = xx[i0] - xx[i1]; long dy = yy[i0] - yy[i1]; long dd = dx*dx+dy*dy; //std::cout << "insert " << i << " " << ni << " " << dd << std::endl; e = boost::add_edge(i, ni, G).first; weights[e]=InvLong(dd); } } } weighted_graph G2(cnt); std::map<Edge,long> emap; std::vector<edge_desc> mst; boost::kruskal_minimum_spanning_tree(G, std::back_inserter(mst)); for (std::vector<edge_desc>::iterator it = mst.begin(); it != mst.end(); ++it) { int u = boost::source(*it, G); int v = boost::target(*it, G); //std::cout << boost::source(*it, G) << " " << boost::target(*it, G) << "\n"; e = boost::add_edge(u,v, G2).first; long dd = weights[*it].value; //std::cout << "mst: " << u << " " << v << " " << dd << std::endl; emap[Edge(u,v)] = dd; emap[Edge(v,u)] = dd; } std::vector<bool> visited(cnt,false); std::vector<int> queue; queue.reserve(n); int qIndex = 0; queue.push_back(0); visited[0] = true; while(queue.size() > qIndex) { int v = queue[qIndex++]; out_edge_it oe_beg, oe_end; for (boost::tie(oe_beg, oe_end) = boost::out_edges(v, G2); oe_beg != oe_end; ++oe_beg) { assert(boost::source(*oe_beg, G) == v); int u = boost::target(*oe_beg, G); //std::cout << v << " " << u << " " << emap[Edge(u,v)] << std::endl; if(!visited[u]) { visited[u] = true; queue.push_back(u); critical[u] = std::min(emap[Edge(u,v)], critical[v]); //std::cout << "set: " << u << " " << v << " " << emap[Edge(u,v)] << " " << critical[v] << std::endl; } } } // queries: std::cin >> m; for(int i=0; i<m; i++) { int x,y; long d; std::cin >> x >> y >> d; K::Point_2 q(x,y); Face f = t.locate(q); //std::cout << "q" << i << " " << f->info() << std::endl; // check that not too close to any point: bool canStart = true; for(int v=0; v<3; v++) { auto vv = f->vertex(v); if(!t.is_infinite(vv)) { if(CGAL::squared_distance(vv->point(),q) < d) { canStart = false; //std::cout << " " << vv->point() << " " << CGAL::squared_distance(vv->point(),q) << std::endl; } } else { //std::cout << "inf-pass" << std::endl; } } //std::cout << "start " << canStart << std::endl; if(!canStart) { std::cout << "n"; //std::cout << "n start " << x << " " << y << " " << d << std::endl; continue; } if(CGAL::squared_distance(t.nearest_vertex(q)->point(),q) < d) { std::cout << "n"; //std::cout << "n point " << x << " " << y << " " << d << std::endl; continue; } // check if path out exists: int ii = f->info(); //std::cout << "critical: " << critical[ii] << " " << d << std::endl; if(critical[ii]>=d*4) { std::cout << "y"; //std::cout << "y " << x << " " << y << " " << d << " " << critical[ii] << " " << t.is_infinite(f) << std::endl; //if(t.is_infinite(f)) { // std::cout << " "<< t.triangle(f) << std::endl; //} } else { std::cout << "n"; //std::cout << "n " << x << " " << y << " " << d << std::endl; } } std::cout << std::endl; } }
C++
CL
5204325c2d597dbf7fe6cde99fbcb79960fcdddbdc825ac21fccc50e2ca89d97
/* vim:set ts=3 sw=3 sts=3 et: */ /** * Copyright © 2008-2013 Last.fm Limited * * This file is part of libmoost. * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation * files (the "Software"), to deal in the Software without restriction, * including without limitation the rights to use, copy, modify, merge, * publish, distribute, sublicense, and/or sell copies of the Software, * and to permit persons to whom the Software is furnished to do so, * subject to the following conditions: * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR * OTHER DEALINGS IN THE SOFTWARE. */ /** * @file uri_encoder.hpp * @brief Encodes Uris in accordence with RFC-2396 * @author Ricky Cormier * @version 0.0.0.1 * @date 2011-10-17 * */ #ifndef FM_LAST_MOOST_MURCL_URI_ENCODER_HPP__ #define FM_LAST_MOOST_MURCL_URI_ENCODER_HPP__ #include <string> #include <curl/curl.h> #include "../utils/scope_exit.hpp" #include <boost/cast.hpp> namespace moost { namespace murcl { /** * @brief This class can be used to uri encode a string representing a uri */ struct uri_encoder { typedef moost::utils::scope_exit::type<char *> ::call_free_function_with_val encoded_t; /** * @brief Encode a string that represents a uri * * @param uri * The string representation of a uri to be encoded * * @return * A uri encoded string */ static std::string encode(std::string const & uri) { std::string encoded_uri; if(!uri.empty()) { encoded_t encoded( curl_escape(uri.c_str(), boost::numeric_cast<int>(uri.size())), curl_free); encoded_uri = encoded->get(); } return encoded_uri; } }; }} #endif // FM_LAST_MOOST_MURCL_URI_ENCODER_HPP__
C++
CL
392e3b9d5f6b75e21fc2deb26ab8846fca110c955406b6969496000c2dd28dc8
// // Created by alex on 30/03/15. // #ifndef _VH2015_VSIMPLELIST_H_ #define _VH2015_VSIMPLELIST_H_ #include <stddef.h> #include <iostream> #include "../libs/vheaplib.h" #include "vNumber.h" template <class T> class vSimpleNode{ vRef<vSimpleNode<T>> next; vRef<T> data; public: vSimpleNode(); vSimpleNode(T); vSimpleNode(const vSimpleNode<T>&); T operator !(); //get Data vRef<vSimpleNode<T>> operator ++(); //get Next void operator *=(T); //assign void operator +(vRef<vSimpleNode<T>>); //add }; template <class T> vSimpleNode<T>::vSimpleNode(){ next = 0; } template <class T> vSimpleNode<T>::vSimpleNode(T param){ data = vMalloc((unsigned int) sizeof(T)); vPlacement(data,param); next = 0; } template <class T> vSimpleNode<T>::vSimpleNode(const vSimpleNode<T>& other){ } template <class T> T vSimpleNode<T>::operator !(){ return **data; } template <class T> vRef<vSimpleNode<T>> vSimpleNode<T>::operator ++(){ return next; } template <class T> void vSimpleNode<T>::operator *=(T d){ if(!data != 0){ vPlacement(data,d); }else{ data = vMalloc((unsigned int) sizeof(T)); vPlacement(data,d); } } template <class T> void vSimpleNode<T>::operator +(vRef<vSimpleNode> vR){ next=vR; } //SIMPLE LIST template <class T> class vSimpleList { private: int m_len; vRef<vSimpleNode<T>> m_head; public: vSimpleList(); void operator +(T); //add void operator -(T); //delete void operator --(); //delete all T operator [](int); //getPos void setPos(int, T); //setPos int len(); }; /**@brief: Constructor */ template <class T> vSimpleList<T>::vSimpleList(){ m_len = 0; m_head = 0; } /**@brief: Agrega un dato * @oaram T data: elemento a insertar */ template <class T> void vSimpleList<T>::operator +(T data){ if(!m_head != 0){ vRef<vSimpleNode<T>> tmp = m_head; for(int i=1; i < m_len; i++){ tmp = ++(**tmp); } (**tmp) + (vMalloc(sizeof(vSimpleNode<T>))); vPlacement(++(**tmp),vSimpleNode<T>(data)); (m_len)++; }else{ m_head = vMalloc(sizeof(vSimpleNode<T>)); vPlacement(m_head,vSimpleNode<T>(data)); (m_len)++; } } /**@brief: Borra un dato * @oaram T data: elemento a borrar */ template <class T> void vSimpleList<T>::operator -(T data){ if(!**m_head != data){ vRef<vSimpleNode<T>> tmp = m_head; vRef<vSimpleNode<T>> toDelete = ++(**m_head); for(int i=1; i<m_len; i+=1){ if(!**toDelete == data){ (**tmp) + ++(**toDelete); vFree(toDelete); m_len -= 1; break; } tmp = toDelete; toDelete = ++(**toDelete); } }else{ if(m_len>1){ vRef<vSimpleNode<T>> tmp = ++(**m_head); vFree(m_head); m_head = tmp; }else{ vFree(m_head); } m_len = 0; } } /**@brief: devuelve el dato de la posicion indicada * @param int pos: posicion */ template <class T> T vSimpleList<T>::operator [](int pos){ vRef<vSimpleNode<T>> tmp = m_head; if(pos < m_len){ for(int i=0; i<pos; i+=1){ tmp = ++(**tmp); } } return !**tmp; } /**@brief inserta un dato en la posicion indicada * @param int pos: posicion * @param T data: dato a insertar */ template <class T> void vSimpleList<T>:: setPos(int pos, T data){ if(pos < m_len){ vRef<vSimpleNode<T>> tmp = m_head; for(int i=0; i<pos; i+=1){ tmp = ++(**tmp); } (**tmp) *= data; } } /**@brief: elimina todos los datos */ template <class T> void vSimpleList<T>::operator --(){ while(!m_head != 0) { vRef<vSimpleNode<T>> tmp = m_head; m_head = ++(**m_head); vFree(tmp); } m_len = 0; } /**@brief: Devuelve la longitud * @return int */ template <class T> int vSimpleList<T>::len(){ return m_len; } #endif //_VH2015_VSIMPLELIST_H_
C++
CL
6383cfbd0e241aa719b6696544b2dbb591857fac8e5b71ed53c3f1fe523b31b3
/** * @file procbase_interface.h * @brief Declarations for IProcBase class * @author Nicu Tofan <[email protected]> * @copyright Copyright 2016 piles contributors. All rights reserved. * This file is released under the * [MIT License](http://opensource.org/licenses/mit-license.html) */ #ifndef GUARD_PROCSCHEDULER_INTERFACE_INCLUDE #define GUARD_PROCSCHEDULER_INTERFACE_INCLUDE #include <procscheduler/procscheduler-config.h> #include <QString> #include <QList> #include <QObject> class ProcScheduler; class IProcInvok; class IProcJob; //! Interface for base item in the scheduler. class PROCSCHEDULER_EXPORT IProcBase : public QObject { Q_OBJECT public: //! Types of items. enum Status { PreparingStatus, /**< the instance was created but not run (initial state) */ StartingStatus, /**< in the process of starting the process */ EnqueuedStatus, /**< added to a queue before starting */ ExecutingStatus, /** in process */ CompletedOkStatus, /**< the run was completed OK */ CompletedFailStatus /**< the run was completed with an error */ }; //! State of the item. enum BaseType { InvocationType, /**< an IProcJob instance */ JobType /**< an IProcInvok instance */ }; public: //! Default constructor. IProcBase ( ProcScheduler * mng); //! Destructor. virtual ~IProcBase (); //! The manager where this instance is rooted. ProcScheduler * manager () const { return mng_; } //! Append a definition inside this node. bool appendKid ( IProcBase * pdef) { return insertKid (-1, pdef); } //! Find a kid definition by its label. IProcBase * findKid ( const QString & s_label) const; //! Cast to invocation if this is the right kind. IProcInvok * toInvok (); //! Cast to job if this is the right kind. IProcJob * toJob (); protected: //! Set the manager where this instance is rooted. void setManager ( ProcScheduler * mng) { mng_ = mng; } /* == == == == == == == == == == == == == == == == == */ /** @name IProcBase interface */ ///@{ public: //! The kind of this instance. virtual BaseType baseType () const = 0; //! Execute this item. virtual void execute () = 0; //! The state of the instance. virtual Status execState () const = 0; //! Change the state of the instance. virtual bool setExecState ( Status /* new_state */) { return false; } //! The user label (short string) of this item. virtual QString label () const = 0; //! Change the label (short string) of the item. virtual bool setLabel ( const QString &/*label*/) { return false; } //! The parent item. virtual IProcBase * parent () const { return NULL; } //! Change the parent. virtual bool setParent (IProcBase *) { return false; } //! The list of kids. virtual QList<IProcBase *> kids () const { return QList<IProcBase *>(); } //! A kid at a particular index. virtual IProcBase * kids ( int idx) const { return kids ().at (idx); } //! Number of kids in this item. virtual int kidsCount () const { return kids ().count (); } //! Tell if this instance is a node or a leaf. virtual bool isNode () const { return kidsCount () == 0; } //! Tell if this instance is at the top level or is part of a node. virtual bool isVarTopLevel () const { return parent () == NULL; } //! The index of an item inside this node. virtual int kidIndex ( IProcBase * pdef) const { return kids ().indexOf (pdef); } //! Tell if an item is part of this node. virtual bool isKid ( IProcBase * pdef) const { return kidIndex (pdef) != -1; } //! Insert an item inside this node. virtual bool insertKid ( int /* position */, IProcBase * /* pdef */) { return false; } //! Remove an item from inside this node and delete it. virtual bool removeKid ( int /* position */ = -1, IProcBase * /* pdef */ = NULL) { return false; } //! Remove an item inside this node and return it to the caller. virtual IProcBase * takeKid ( int /* position */ = -1, IProcBase * /* pdef */ = NULL) { return NULL; } public slots: //! Informed that the state of a dependency has changed to completed. virtual void dependencyDone () = 0; ///@} /* == == == == == == == == == == == == == == == == == */ signals: //! The item reached the final status. void done ( bool state_ok); private: ProcScheduler * mng_; }; // class IProcBase #endif // GUARD_PROCSCHEDULER_INTERFACE_INCLUDE
C++
CL
7b2f79af20a2945c32a513ebeb814b26c27c105f497b620b5592014bf4e8b692
// Copyright 2015 XLGAMES Inc. // // Distributed under the MIT License (See // accompanying file "LICENSE" or the website // http://www.opensource.org/licenses/mit-license.php) #include "Font.h" #include "FontRendering.h" #include "../RenderCore/RenderUtils.h" #include "../Assets/Assets.h" #include "../Utility/MemoryUtils.h" #include "../Utility/StringUtils.h" #include "../Utility/PtrUtils.h" #include "../Math/Vector.h" #include "../Core/Exceptions.h" #include <initializer_list> #include <tuple> // We can't use variadic template parameters, or initializer_lists, so use tr1 tuples :( #include <assert.h> #include <algorithm> #include "../RenderCore/Metal/Buffer.h" #include "../RenderCore/Metal/Shader.h" #include "../RenderCore/Metal/Buffer.h" #include "../RenderCore/Metal/DeviceContext.h" #include "../RenderCore/Metal/DeviceContextImpl.h" #include "../RenderCore/Metal/ShaderResource.h" #include "../RenderCore/Metal/State.h" #include "../RenderCore/Metal/InputLayout.h" #include "../RenderCore/Techniques/CommonResources.h" #include "../RenderCore/Techniques/ResourceBox.h" #include "../RenderCore/DX11/Metal/IncludeDX11.h" namespace RenderOverlays { class WorkingVertexSetPCT { public: struct Vertex { Float3 p; unsigned c; Float2 t; Vertex() {} Vertex(Float3 ip, unsigned ic, Float2 it) : p(ip), c(ic), t(it) {} }; static const int VertexSize = sizeof(Vertex); bool PushQuad(const Quad& positions, unsigned color, const Quad& textureCoords, float depth, bool snap=true); void Reset(); size_t VertexCount() const; RenderCore::Metal::VertexBuffer CreateBuffer() const; WorkingVertexSetPCT(); private: Vertex _vertices[512]; Vertex * _currentIterator; }; bool WorkingVertexSetPCT::PushQuad(const Quad& positions, unsigned color, const Quad& textureCoords, float depth, bool snap) { if ((_currentIterator + 6) > &_vertices[dimof(_vertices)]) { return false; // no more space! } float x0 = positions.min[0]; float x1 = positions.max[0]; float y0 = positions.min[1]; float y1 = positions.max[1]; Float3 p0(x0, y0, depth); Float3 p1(x1, y0, depth); Float3 p2(x0, y1, depth); Float3 p3(x1, y1, depth); if (snap) { p0[0] = (float)(int)(0.5f + p0[0]); p1[0] = (float)(int)(0.5f + p1[0]); p2[0] = (float)(int)(0.5f + p2[0]); p3[0] = (float)(int)(0.5f + p3[0]); p0[1] = (float)(int)(0.5f + p0[1]); p1[1] = (float)(int)(0.5f + p1[1]); p2[1] = (float)(int)(0.5f + p2[1]); p3[1] = (float)(int)(0.5f + p3[1]); } // // Following behaviour from DrawQuad in Archeage display_list.cpp // *_currentIterator++ = Vertex(p0, color, Float2( textureCoords.min[0], textureCoords.min[1] )); *_currentIterator++ = Vertex(p2, color, Float2( textureCoords.min[0], textureCoords.max[1] )); *_currentIterator++ = Vertex(p1, color, Float2( textureCoords.max[0], textureCoords.min[1] )); *_currentIterator++ = Vertex(p1, color, Float2( textureCoords.max[0], textureCoords.min[1] )); *_currentIterator++ = Vertex(p2, color, Float2( textureCoords.min[0], textureCoords.max[1] )); *_currentIterator++ = Vertex(p3, color, Float2( textureCoords.max[0], textureCoords.max[1] )); return true; } RenderCore::Metal::VertexBuffer WorkingVertexSetPCT::CreateBuffer() const { return RenderCore::Metal::VertexBuffer(_vertices, size_t(_currentIterator) - size_t(_vertices)); } size_t WorkingVertexSetPCT::VertexCount() const { return _currentIterator - _vertices; } void WorkingVertexSetPCT::Reset() { _currentIterator = _vertices; } WorkingVertexSetPCT::WorkingVertexSetPCT() { _currentIterator = _vertices; } static void Flush(RenderCore::Metal::DeviceContext& renderer, WorkingVertexSetPCT& vertices) { using namespace RenderCore; using namespace RenderCore::Metal; if (vertices.VertexCount()) { auto vertexBuffer = vertices.CreateBuffer(); renderer.Bind(MakeResourceList(vertexBuffer), WorkingVertexSetPCT::VertexSize, 0); renderer.Draw((unsigned)vertices.VertexCount(), 0); vertices.Reset(); } } static unsigned RGBA8(const Color4& color) { return (unsigned(Clamp(color.a, 0.f, 1.f) * 255.f) << 24) | (unsigned(Clamp(color.b, 0.f, 1.f) * 255.f) << 16) | (unsigned(Clamp(color.g, 0.f, 1.f) * 255.f) << 8) | (unsigned(Clamp(color.r, 0.f, 1.f) * 255.f) ) ; } static unsigned ToDigitValue(ucs4 chr, unsigned base) { if (chr >= '0' && chr <= '9') { return chr - '0'; } else if (chr >= 'a' && chr < ('a'+base-10)) { return 0xa + chr - 'a'; } else if (chr >= 'A' && chr < ('a'+base-10)) { return 0xa + chr - 'A'; } return 0xff; } static unsigned ParseColorValue(const ucs4 text[], unsigned* colorOverride) { assert(text && colorOverride); unsigned digitCharacters = 0; while ( (text[digitCharacters] >= '0' && text[digitCharacters] <= '9') || (text[digitCharacters] >= 'A' && text[digitCharacters] <= 'F') || (text[digitCharacters] >= 'a' && text[digitCharacters] <= 'f')) { ++digitCharacters; } if (digitCharacters == 6 || digitCharacters == 8) { unsigned result = (digitCharacters == 6)?0xff000000:0x0; for (unsigned c=0; c<digitCharacters; ++c) { result |= ToDigitValue(text[c], 16) << ((digitCharacters-c-1)*4); } *colorOverride = result; return digitCharacters; } return 0; } class TextStyleResources { public: class Desc {}; const RenderCore::Metal::ShaderProgram* _shaderProgram; RenderCore::Metal::BoundInputLayout _boundInputLayout; RenderCore::Metal::BoundUniforms _boundUniforms; TextStyleResources(const Desc& desc); ~TextStyleResources(); const std::shared_ptr<Assets::DependencyValidation>& GetDependencyValidation() const { return _validationCallback; } private: std::shared_ptr<Assets::DependencyValidation> _validationCallback; }; struct ReciprocalViewportDimensions { public: float _reciprocalWidth, _reciprocalHeight; float _pad[2]; }; TextStyleResources::TextStyleResources(const Desc& desc) { const char vertexShaderSource[] = "game/xleres/basic2D.vsh:P2CT:" VS_DefShaderModel; const char pixelShaderSource[] = "game/xleres/basic.psh:PCT_Text:" PS_DefShaderModel; using namespace RenderCore::Metal; const auto& shaderProgram = Assets::GetAssetDep<ShaderProgram>(vertexShaderSource, pixelShaderSource); BoundInputLayout boundInputLayout(GlobalInputLayouts::PCT, shaderProgram); ConstantBufferLayoutElement elements[] = { { "ReciprocalViewportDimensions", NativeFormat::R32G32_FLOAT, offsetof(ReciprocalViewportDimensions, _reciprocalWidth), 0 } }; BoundUniforms boundUniforms(shaderProgram); boundUniforms.BindConstantBuffer(Hash64("ReciprocalViewportDimensions"), 0, 1, elements, dimof(elements)); auto validationCallback = std::make_shared<Assets::DependencyValidation>(); Assets::RegisterAssetDependency(validationCallback, shaderProgram.GetDependencyValidation()); _shaderProgram = &shaderProgram; _boundInputLayout = std::move(boundInputLayout); _boundUniforms = std::move(boundUniforms); _validationCallback = std::move(validationCallback); } TextStyleResources::~TextStyleResources() {} float TextStyle::Draw( RenderCore::Metal::DeviceContext* renderer, float x, float y, const ucs4 text[], int maxLen, float spaceExtra, float scale, float mx, float depth, unsigned colorARGB, UI_TEXT_STATE textState, bool applyDescender, Quad* q) const { if (!_font) { return 0.f; } TRY { using namespace RenderCore::Metal; int prevGlyph = 0; float xScale = scale; float yScale = scale; if (_options.snap) { x = xScale * (int)(0.5f + x / xScale); y = yScale * (int)(0.5f + y / yScale); } float width = _font->StringWidth(text, maxLen, spaceExtra, _options.outline); float height = _font->LineHeight() * yScale; if (textState != UI_TEXT_STATE_NORMAL) { const float magicGap = 3.0f; Quad reverseBox; reverseBox.min[0] = x; reverseBox.min[1] = y - height + magicGap * yScale; reverseBox.max[0] = x + width; reverseBox.max[1] = y + magicGap * xScale; if(_options.outline) { reverseBox.min[0] -= xScale; reverseBox.min[1] -= yScale; reverseBox.max[0] -= xScale; reverseBox.max[1] -= yScale; } if(mx > 0.0f) { reverseBox.max[0] = std::min(reverseBox.max[0], mx); } // ITexture* backTex = NULL; // if (textState == UI_TEXT_STATE_REVERSE) { // backTex = desktop.greyTex; // } // else if( textState == UI_TEXT_STATE_INACTIVE_REVERSE) { // backTex = desktop.greyTex; // } // if (backTex) { // DrawQuad(list, reverseBox, Quad::MinMax(0,0,1,1), Color4::Create(1,1,1,1), backTex, true, false); // } } // VertexShader& vshader = GetResource<VertexShader>(vertexShaderSource); // PixelShader& pshader = GetResource<PixelShader>(pixelShaderSource); auto& res = RenderCore::Techniques::FindCachedBoxDep<TextStyleResources>(TextStyleResources::Desc()); renderer->Bind(res._boundInputLayout); // have to bind a standard P2CT input layout renderer->Bind(*res._shaderProgram); renderer->Bind(Topology::TriangleList); renderer->Bind(RenderCore::Techniques::CommonResources()._dssDisable); renderer->Bind(RenderCore::Techniques::CommonResources()._cullDisable); { ViewportDesc viewportDesc(*renderer); ReciprocalViewportDimensions reciprocalViewportDimensions = { 1.f / float(viewportDesc.Width), 1.f / float(viewportDesc.Height), 0.f, 0.f }; // ConstantBuffer constantBuffer(&reciprocalViewportDimensions, sizeof(reciprocalViewportDimensions)); // std::shared_ptr<std::vector<uint8>> packet = constantBuffer.GetUnderlying(); auto packet = RenderCore::MakeSharedPkt( (const uint8*)&reciprocalViewportDimensions, (const uint8*)PtrAdd(&reciprocalViewportDimensions, sizeof(reciprocalViewportDimensions))); res._boundUniforms.Apply(*renderer, UniformsStream(), UniformsStream(&packet, nullptr, 1)); // renderer->BindVS(boundLayout, constantBuffer); // renderer.BindVS(ResourceList<ConstantBuffer, 1>(std::make_tuple())); } const FontTexture2D * currentBoundTexture = nullptr; WorkingVertexSetPCT workingVertices; // bool batchFont = _font->GetTexKind() == FTK_IMAGETEXT ? false : true; float descent = 0.0f; if (applyDescender) { descent = _font->Descent(); } float opacity = (colorARGB >> 24) / float(0xff); unsigned colorOverride = 0x0; for (uint32 i = 0; i < (uint32)maxLen; ++i) { ucs4 ch = text[i]; if (!ch) break; if (ch == '\n' || ch == '\r' || ch == '\0') continue; if (mx > 0.0f && x > mx) { return x; } if (!XlComparePrefixI((ucs4*)"{\0\0\0C\0\0\0o\0\0\0l\0\0\0o\0\0\0r\0\0\0:\0\0\0", &text[i], 7)) { unsigned newColorOverride = 0; unsigned parseLength = ParseColorValue(&text[i+7], &newColorOverride); if (parseLength) { colorOverride = newColorOverride; i += 7 + parseLength; while (i<(uint32)maxLen && text[i] && text[i] != '}') ++i; continue; } } int curGlyph; Float2 v = _font->GetKerning(prevGlyph, ch, &curGlyph); x += xScale * v[0]; y += yScale * v[1]; prevGlyph = curGlyph; std::pair<const FontChar*, const FontTexture2D*> charAndTexture = _font->GetChar(ch); const FontChar* fc = charAndTexture.first; const FontTexture2D* tex = charAndTexture.second; if(!fc) continue; // Set the new texture if needed (changing state requires flushing completed work) if (tex != currentBoundTexture) { Flush(*renderer, workingVertices); ShaderResourceView::UnderlyingResource sourceTexture = (ShaderResourceView::UnderlyingResource)tex->GetUnderlying(); if (!sourceTexture) { throw ::Assets::Exceptions::PendingAsset("", "Pending background upload of font texture"); } ShaderResourceView shadRes(sourceTexture); renderer->BindPS(RenderCore::MakeResourceList(shadRes)); currentBoundTexture = tex; } _font->TouchFontChar(fc); float baseX = x + fc->left * xScale; float baseY = y - (fc->top + descent) * yScale; if (_options.snap) { baseX = xScale * (int)(0.5f + baseX / xScale); baseY = yScale * (int)(0.5f + baseY / yScale); } Quad pos = Quad::MinMax(baseX, baseY, baseX + fc->width * xScale, baseY + fc->height * yScale); Quad tc = Quad::MinMax(fc->u0, fc->v0, fc->u1, fc->v1); if (_options.outline) { Quad shadowPos; unsigned shadowColor = RGBA8(Color4::Create(0, 0, 0, opacity)); shadowPos = pos; shadowPos.min[0] -= xScale; shadowPos.max[0] -= xScale; shadowPos.min[1] -= yScale; shadowPos.max[1] -= yScale; if (!workingVertices.PushQuad(shadowPos, shadowColor, tc, depth)) { Flush(*renderer, workingVertices); workingVertices.PushQuad(shadowPos, shadowColor, tc, depth); } shadowPos = pos; shadowPos.min[1] -= yScale; shadowPos.max[1] -= yScale; if (!workingVertices.PushQuad(shadowPos, shadowColor, tc, depth)) { Flush(*renderer, workingVertices); workingVertices.PushQuad(shadowPos, shadowColor, tc, depth); } shadowPos = pos; shadowPos.min[0] += xScale; shadowPos.max[0] += xScale; shadowPos.min[1] -= yScale; shadowPos.max[1] -= yScale; if (!workingVertices.PushQuad(shadowPos, shadowColor, tc, depth)) { Flush(*renderer, workingVertices); workingVertices.PushQuad(shadowPos, shadowColor, tc, depth); } shadowPos = pos; shadowPos.min[0] -= xScale; shadowPos.max[0] -= xScale; if (!workingVertices.PushQuad(shadowPos, shadowColor, tc, depth)) { Flush(*renderer, workingVertices); workingVertices.PushQuad(shadowPos, shadowColor, tc, depth); } shadowPos = pos; shadowPos.min[0] += xScale; shadowPos.max[0] += xScale; if (!workingVertices.PushQuad(shadowPos, shadowColor, tc, depth)) { Flush(*renderer, workingVertices); workingVertices.PushQuad(shadowPos, shadowColor, tc, depth); } shadowPos = pos; shadowPos.min[0] -= xScale; shadowPos.max[0] -= xScale; shadowPos.min[1] += yScale; shadowPos.max[1] += yScale; if (!workingVertices.PushQuad(shadowPos, shadowColor, tc, depth)) { Flush(*renderer, workingVertices); workingVertices.PushQuad(shadowPos, shadowColor, tc, depth); } shadowPos = pos; shadowPos.min[1] += yScale; shadowPos.max[1] += yScale; if (!workingVertices.PushQuad(shadowPos, shadowColor, tc, depth)) { Flush(*renderer, workingVertices); workingVertices.PushQuad(shadowPos, shadowColor, tc, depth); } shadowPos = pos; shadowPos.min[0] += xScale; shadowPos.max[0] += xScale; shadowPos.min[1] += yScale; shadowPos.max[1] += yScale; if (!workingVertices.PushQuad(shadowPos, shadowColor, tc, depth)) { Flush(*renderer, workingVertices); workingVertices.PushQuad(shadowPos, shadowColor, tc, depth); } } if (_options.shadow) { Quad shadowPos = pos; shadowPos.min[0] += xScale; shadowPos.max[0] += xScale; shadowPos.min[1] += yScale; shadowPos.max[1] += yScale; if (!workingVertices.PushQuad(shadowPos, RGBA8(Color4::Create(0,0,0,opacity)), tc, depth)) { Flush(*renderer, workingVertices); workingVertices.PushQuad(shadowPos, RGBA8(Color4::Create(0,0,0,opacity)), tc, depth); } } if (!workingVertices.PushQuad(pos, RenderCore::ARGBtoABGR(colorOverride?colorOverride:colorARGB), tc, depth)) { Flush(*renderer, workingVertices); workingVertices.PushQuad(pos, RenderCore::ARGBtoABGR(colorOverride?colorOverride:colorARGB), tc, depth); } x += fc->xAdvance * xScale; if (_options.outline) { x += 2 * xScale; } if (ch == ' ') { x += spaceExtra; } if (q) { if (i == 0) { *q = pos; } else { if (q->min[0] > pos.min[0]) { q->min[0] = pos.min[0]; } if (q->min[1] > pos.min[1]) { q->min[1] = pos.min[1]; } if (q->max[0] < pos.max[0]) { q->max[0] = pos.max[0]; } if (q->max[1] < pos.max[1]) { q->max[1] = pos.max[1]; } } } } Flush(*renderer, workingVertices); } CATCH(...) { // OutputDebugString("Suppressed exception while drawing text"); } CATCH_END return x; } static Float2 GetAlignPos(const Quad& q, const Float2& extent, UiAlign align) { Float2 pos; pos[0] = q.min[0]; pos[1] = q.min[1]; switch (align) { case UIALIGN_TOP_LEFT: pos[0] = q.min[0]; pos[1] = q.min[1]; break; case UIALIGN_TOP: pos[0] = 0.5f * (q.min[0] + q.max[0] - extent[0]); pos[1] = q.min[1]; break; case UIALIGN_TOP_RIGHT: pos[0] = q.max[0] - extent[0]; pos[1] = q.min[1]; break; case UIALIGN_LEFT: pos[0] = q.min[0]; pos[1] = 0.5f * (q.min[1] + q.max[1] - extent[1]); break; case UIALIGN_CENTER: pos[0] = 0.5f * (q.min[0] + q.max[0] - extent[0]); pos[1] = 0.5f * (q.min[1] + q.max[1] - extent[1]); break; case UIALIGN_RIGHT: pos[0] = q.max[0] - extent[0]; pos[1] = 0.5f * (q.min[1] + q.max[1] - extent[1]); break; case UIALIGN_BOTTOM_LEFT: pos[0] = q.min[0]; pos[1] = q.max[1] - extent[1]; break; case UIALIGN_BOTTOM: pos[0] = 0.5f * (q.min[0] + q.max[0] - extent[0]); pos[1] = q.max[1] - extent[1]; break; case UIALIGN_BOTTOM_RIGHT: pos[0] = q.max[0] - extent[0]; pos[1] = q.max[1] - extent[1]; break; } return pos; } static Float2 AlignText(const Quad& q, Font* font, float stringWidth, float indent, UiAlign align) { Float2 extent = Float2(stringWidth, font->Ascent(false)); Float2 pos = GetAlignPos(q, extent, align); pos[0] += indent; pos[1] += extent[1]; switch (align) { case UIALIGN_TOP_LEFT: case UIALIGN_TOP: case UIALIGN_TOP_RIGHT: pos[1] += font->Ascent(true) - extent[1]; break; case UIALIGN_BOTTOM_LEFT: case UIALIGN_BOTTOM: case UIALIGN_BOTTOM_RIGHT: pos[1] -= font->Descent(); break; } return pos; } Float2 TextStyle::AlignText(const Quad& q, UiAlign align, const ucs4* text, int maxLen /*= -1*/) { assert(_font); return RenderOverlays::AlignText(q, _font.get(), _font->StringWidth(text, maxLen), 0, align); } Float2 TextStyle::AlignText(const Quad& q, UiAlign align, float width, float indent) { assert(_font); return RenderOverlays::AlignText(q, _font.get(), width, indent, align); } float TextStyle::StringWidth(const ucs4* text, int maxlen) { return _font->StringWidth(text, maxlen); } int TextStyle::CharCountFromWidth(const ucs4* text, float width) { return _font->CharCountFromWidth(text, width); } float TextStyle::SetStringEllipis(const ucs4* inText, ucs4* outText, size_t outTextSize, float width) { return _font->StringEllipsis(inText, outText, outTextSize, width); } float TextStyle::CharWidth(ucs4 ch, ucs4 prev) { return _font->CharWidth(ch, prev); } TextStyle::TextStyle(Font& font, const DrawTextOptions& options) : _font(&font), _options(options) { } TextStyle::~TextStyle() { } }
C++
CL
0965fd9cd09ed98979be3e519146d10a8245208f6119b3f810882a7211e27467
#pragma once #include "Screengrab.h" #include <Windows.h> #include "Log.h" #include <atlbase.h> #include "Cleanup.h" namespace { bool g_WIC2 = false; bool _IsWIC2() { return g_WIC2; } IWICImagingFactory *_GetWIC() { static INIT_ONCE s_initOnce = INIT_ONCE_STATIC_INIT; IWICImagingFactory *factory = nullptr; InitOnceExecuteOnce(&s_initOnce, [](PINIT_ONCE, PVOID, PVOID *factory) -> BOOL { #if (_WIN32_WINNT >= _WIN32_WINNT_WIN8) || defined(_WIN7_PLATFORM_UPDATE) HRESULT hr = CoCreateInstance( CLSID_WICImagingFactory2, nullptr, CLSCTX_INPROC_SERVER, __uuidof(IWICImagingFactory2), factory ); if (SUCCEEDED(hr)) { // WIC2 is available on Windows 10, Windows 8.x, and Windows 7 SP1 with KB 2670838 installed g_WIC2 = true; return TRUE; } else { hr = CoCreateInstance( CLSID_WICImagingFactory1, nullptr, CLSCTX_INPROC_SERVER, __uuidof(IWICImagingFactory), factory ); return SUCCEEDED(hr) ? TRUE : FALSE; } #else return SUCCEEDED(CoCreateInstance( CLSID_WICImagingFactory, nullptr, CLSCTX_INPROC_SERVER, __uuidof(IWICImagingFactory), factory)) ? TRUE : FALSE; #endif }, nullptr, reinterpret_cast<LPVOID *>(&factory)); return factory; } inline DXGI_FORMAT EnsureNotTypeless(DXGI_FORMAT fmt) { // Assumes UNORM or FLOAT; doesn't use UINT or SINT switch (fmt) { case DXGI_FORMAT_R32G32B32A32_TYPELESS: return DXGI_FORMAT_R32G32B32A32_FLOAT; case DXGI_FORMAT_R32G32B32_TYPELESS: return DXGI_FORMAT_R32G32B32_FLOAT; case DXGI_FORMAT_R16G16B16A16_TYPELESS: return DXGI_FORMAT_R16G16B16A16_UNORM; case DXGI_FORMAT_R32G32_TYPELESS: return DXGI_FORMAT_R32G32_FLOAT; case DXGI_FORMAT_R10G10B10A2_TYPELESS: return DXGI_FORMAT_R10G10B10A2_UNORM; case DXGI_FORMAT_R8G8B8A8_TYPELESS: return DXGI_FORMAT_R8G8B8A8_UNORM; case DXGI_FORMAT_R16G16_TYPELESS: return DXGI_FORMAT_R16G16_UNORM; case DXGI_FORMAT_R32_TYPELESS: return DXGI_FORMAT_R32_FLOAT; case DXGI_FORMAT_R8G8_TYPELESS: return DXGI_FORMAT_R8G8_UNORM; case DXGI_FORMAT_R16_TYPELESS: return DXGI_FORMAT_R16_UNORM; case DXGI_FORMAT_R8_TYPELESS: return DXGI_FORMAT_R8_UNORM; case DXGI_FORMAT_BC1_TYPELESS: return DXGI_FORMAT_BC1_UNORM; case DXGI_FORMAT_BC2_TYPELESS: return DXGI_FORMAT_BC2_UNORM; case DXGI_FORMAT_BC3_TYPELESS: return DXGI_FORMAT_BC3_UNORM; case DXGI_FORMAT_BC4_TYPELESS: return DXGI_FORMAT_BC4_UNORM; case DXGI_FORMAT_BC5_TYPELESS: return DXGI_FORMAT_BC5_UNORM; case DXGI_FORMAT_B8G8R8A8_TYPELESS: return DXGI_FORMAT_B8G8R8A8_UNORM; case DXGI_FORMAT_B8G8R8X8_TYPELESS: return DXGI_FORMAT_B8G8R8X8_UNORM; case DXGI_FORMAT_BC7_TYPELESS: return DXGI_FORMAT_BC7_UNORM; default: return fmt; } } //-------------------------------------------------------------------------------------- HRESULT CaptureTexture(_In_ ID3D11DeviceContext *pContext, _In_ ID3D11Resource *pSource, D3D11_TEXTURE2D_DESC &desc, CComPtr<ID3D11Texture2D> &pStaging) { if (!pContext || !pSource) return E_INVALIDARG; D3D11_RESOURCE_DIMENSION resType = D3D11_RESOURCE_DIMENSION_UNKNOWN; pSource->GetType(&resType); if (resType != D3D11_RESOURCE_DIMENSION_TEXTURE2D) return HRESULT_FROM_WIN32(ERROR_NOT_SUPPORTED); CComPtr<ID3D11Texture2D> pTexture; HRESULT hr = pSource->QueryInterface(IID_PPV_ARGS(&pTexture)); if (FAILED(hr)) return hr; assert(pTexture); pTexture->GetDesc(&desc); CComPtr<ID3D11Device> d3dDevice; pContext->GetDevice(&d3dDevice); if (desc.SampleDesc.Count > 1) { // MSAA content must be resolved before being copied to a staging texture desc.SampleDesc.Count = 1; desc.SampleDesc.Quality = 0; CComPtr<ID3D11Texture2D> pTemp; hr = d3dDevice->CreateTexture2D(&desc, 0, &pTemp); if (FAILED(hr)) return hr; assert(pTemp); DXGI_FORMAT fmt = EnsureNotTypeless(desc.Format); UINT support = 0; hr = d3dDevice->CheckFormatSupport(fmt, &support); if (FAILED(hr)) return hr; if (!(support & D3D11_FORMAT_SUPPORT_MULTISAMPLE_RESOLVE)) return E_FAIL; for (UINT item = 0; item < desc.ArraySize; ++item) { for (UINT level = 0; level < desc.MipLevels; ++level) { UINT index = D3D11CalcSubresource(level, item, desc.MipLevels); pContext->ResolveSubresource(pTemp, index, pSource, index, fmt); } } desc.BindFlags = 0; desc.MiscFlags &= D3D11_RESOURCE_MISC_TEXTURECUBE; desc.CPUAccessFlags = D3D11_CPU_ACCESS_READ; desc.Usage = D3D11_USAGE_STAGING; hr = d3dDevice->CreateTexture2D(&desc, 0, &pStaging); if (FAILED(hr)) return hr; assert(pStaging); pContext->CopyResource(pStaging, pTemp); } else if ((desc.Usage == D3D11_USAGE_STAGING) && (desc.CPUAccessFlags & D3D11_CPU_ACCESS_READ)) { // Handle case where the source is already a staging texture we can use directly pStaging = pTexture; } else { // Otherwise, create a staging texture from the non-MSAA source desc.BindFlags = 0; desc.MiscFlags &= D3D11_RESOURCE_MISC_TEXTURECUBE; desc.CPUAccessFlags = D3D11_CPU_ACCESS_READ; desc.Usage = D3D11_USAGE_STAGING; hr = d3dDevice->CreateTexture2D(&desc, 0, &pStaging); if (FAILED(hr)) return hr; assert(pStaging); pContext->CopyResource(pStaging, pSource); } return S_OK; } } // anonymous namespace HRESULT __cdecl SaveWICTextureToFile( _In_ ID3D11DeviceContext *pContext, _In_ ID3D11Resource *pSource, _In_ REFGUID guidContainerFormat, _In_z_ const wchar_t *filePath, _In_opt_ const std::optional<SIZE> destSize, _In_opt_ const GUID *targetFormat, _In_opt_ std::function<void(IPropertyBag2 *)> setCustomProps) { if (!filePath) return E_INVALIDARG; CComPtr<IWICImagingFactory> pWIC = _GetWIC(); if (!pWIC) return E_NOINTERFACE; CComPtr<IWICStream> wicStream; HRESULT hr = pWIC->CreateStream(&wicStream); if (FAILED(hr)) return hr; hr = wicStream->InitializeFromFilename(filePath, GENERIC_WRITE); if (FAILED(hr)) return hr; hr = SaveWICTextureToWicStream(pContext, pSource, guidContainerFormat, wicStream, destSize, targetFormat, setCustomProps); if (FAILED(hr)) { wicStream.Release(); DeleteFileW(filePath); } return hr; } HRESULT __cdecl SaveWICTextureToStream( _In_ ID3D11DeviceContext *pContext, _In_ ID3D11Resource *pSource, _In_ REFGUID guidContainerFormat, _In_ IStream *pStream, _In_opt_ const std::optional<SIZE> destSize, _In_opt_ const GUID *targetFormat, _In_opt_ std::function<void(IPropertyBag2 *)> setCustomProps) { if (!pStream) return E_INVALIDARG; CComPtr<IWICImagingFactory> pWIC = _GetWIC(); if (!pWIC) return E_NOINTERFACE; CComPtr<IWICStream> wicStream; HRESULT hr = pWIC->CreateStream(&wicStream); if (FAILED(hr)) return hr; hr = wicStream->InitializeFromIStream(pStream); if (FAILED(hr)) return hr; hr = SaveWICTextureToWicStream(pContext, pSource, guidContainerFormat, wicStream, destSize, targetFormat, setCustomProps); if (FAILED(hr)) { wicStream.Release(); } return hr; } HRESULT __cdecl SaveWICTextureToWicStream( _In_ ID3D11DeviceContext *pContext, _In_ ID3D11Resource *pSource, _In_ REFGUID guidContainerFormat, _Inout_ IWICStream *pStream, _In_opt_ const std::optional<SIZE> destSize, _In_opt_ const GUID *targetFormat, _In_opt_ std::function<void(IPropertyBag2 *)> setCustomProps) { if (!pStream) return E_INVALIDARG; D3D11_TEXTURE2D_DESC desc = {}; CComPtr<ID3D11Texture2D> pStaging; HRESULT hr = CaptureTexture(pContext, pSource, desc, pStaging); if (FAILED(hr)) return hr; // Determine source format's WIC equivalent WICPixelFormatGUID pfGuid; bool sRGB = false; switch (desc.Format) { case DXGI_FORMAT_R32G32B32A32_FLOAT: pfGuid = GUID_WICPixelFormat128bppRGBAFloat; break; case DXGI_FORMAT_R16G16B16A16_FLOAT: pfGuid = GUID_WICPixelFormat64bppRGBAHalf; break; case DXGI_FORMAT_R16G16B16A16_UNORM: pfGuid = GUID_WICPixelFormat64bppRGBA; break; case DXGI_FORMAT_R10G10B10_XR_BIAS_A2_UNORM: pfGuid = GUID_WICPixelFormat32bppRGBA1010102XR; break; // DXGI 1.1 case DXGI_FORMAT_R10G10B10A2_UNORM: pfGuid = GUID_WICPixelFormat32bppRGBA1010102; break; case DXGI_FORMAT_B5G5R5A1_UNORM: pfGuid = GUID_WICPixelFormat16bppBGRA5551; break; case DXGI_FORMAT_B5G6R5_UNORM: pfGuid = GUID_WICPixelFormat16bppBGR565; break; case DXGI_FORMAT_R32_FLOAT: pfGuid = GUID_WICPixelFormat32bppGrayFloat; break; case DXGI_FORMAT_R16_FLOAT: pfGuid = GUID_WICPixelFormat16bppGrayHalf; break; case DXGI_FORMAT_R16_UNORM: pfGuid = GUID_WICPixelFormat16bppGray; break; case DXGI_FORMAT_R8_UNORM: pfGuid = GUID_WICPixelFormat8bppGray; break; case DXGI_FORMAT_A8_UNORM: pfGuid = GUID_WICPixelFormat8bppAlpha; break; case DXGI_FORMAT_R8G8B8A8_UNORM: pfGuid = GUID_WICPixelFormat32bppRGBA; break; case DXGI_FORMAT_R8G8B8A8_UNORM_SRGB: pfGuid = GUID_WICPixelFormat32bppRGBA; sRGB = true; break; case DXGI_FORMAT_B8G8R8A8_UNORM: // DXGI 1.1 pfGuid = GUID_WICPixelFormat32bppBGRA; break; case DXGI_FORMAT_B8G8R8A8_UNORM_SRGB: // DXGI 1.1 pfGuid = GUID_WICPixelFormat32bppBGRA; sRGB = true; break; case DXGI_FORMAT_B8G8R8X8_UNORM: // DXGI 1.1 pfGuid = GUID_WICPixelFormat32bppBGR; break; case DXGI_FORMAT_B8G8R8X8_UNORM_SRGB: // DXGI 1.1 pfGuid = GUID_WICPixelFormat32bppBGR; sRGB = true; break; default: return HRESULT_FROM_WIN32(ERROR_NOT_SUPPORTED); } CComPtr<IWICImagingFactory> pWIC = _GetWIC(); if (!pWIC) return E_NOINTERFACE; CComPtr<IWICBitmapEncoder> encoder; hr = pWIC->CreateEncoder(guidContainerFormat, 0, &encoder); if (FAILED(hr)) return hr; hr = encoder->Initialize(pStream, WICBitmapEncoderNoCache); if (FAILED(hr)) return hr; CComPtr<IWICBitmapFrameEncode> frame; CComPtr<IPropertyBag2> props; hr = encoder->CreateNewFrame(&frame, &props); if (FAILED(hr)) return hr; if (targetFormat && memcmp(&guidContainerFormat, &GUID_ContainerFormatBmp, sizeof(WICPixelFormatGUID)) == 0 && _IsWIC2()) { // Opt-in to the WIC2 support for writing 32-bit Windows BMP files with an alpha channel PROPBAG2 option = {}; option.pstrName = const_cast<wchar_t *>(L"EnableV5Header32bppBGRA"); VARIANT varValue; varValue.vt = VT_BOOL; varValue.boolVal = VARIANT_TRUE; (void)props->Write(1, &option, &varValue); } if (setCustomProps) { setCustomProps(props); } hr = frame->Initialize(props); if (FAILED(hr)) return hr; int outputWidth = desc.Width; int outputHeight = desc.Height; if (destSize.has_value()) { outputWidth = destSize.value().cx; outputHeight = destSize.value().cy; } hr = frame->SetSize(outputWidth, outputHeight); if (FAILED(hr)) return hr; hr = frame->SetResolution(72, 72); if (FAILED(hr)) return hr; // Pick a target format WICPixelFormatGUID targetGuid; if (targetFormat) { targetGuid = *targetFormat; } else { // Screenshots donít typically include the alpha channel of the render target switch (desc.Format) { #if (_WIN32_WINNT >= _WIN32_WINNT_WIN8) || defined(_WIN7_PLATFORM_UPDATE) case DXGI_FORMAT_R32G32B32A32_FLOAT: case DXGI_FORMAT_R16G16B16A16_FLOAT: if (_IsWIC2()) { targetGuid = GUID_WICPixelFormat96bppRGBFloat; } else { targetGuid = GUID_WICPixelFormat24bppBGR; } break; #endif case DXGI_FORMAT_R16G16B16A16_UNORM: targetGuid = GUID_WICPixelFormat48bppBGR; break; case DXGI_FORMAT_B5G5R5A1_UNORM: targetGuid = GUID_WICPixelFormat16bppBGR555; break; case DXGI_FORMAT_B5G6R5_UNORM: targetGuid = GUID_WICPixelFormat16bppBGR565; break; case DXGI_FORMAT_R32_FLOAT: case DXGI_FORMAT_R16_FLOAT: case DXGI_FORMAT_R16_UNORM: case DXGI_FORMAT_R8_UNORM: case DXGI_FORMAT_A8_UNORM: targetGuid = GUID_WICPixelFormat8bppGray; break; default: targetGuid = GUID_WICPixelFormat24bppBGR; break; } } hr = frame->SetPixelFormat(&targetGuid); if (FAILED(hr)) return hr; if (targetFormat && memcmp(targetFormat, &targetGuid, sizeof(WICPixelFormatGUID)) != 0) { // Requested output pixel format is not supported by the WIC codec return E_FAIL; } // Encode WIC metadata CComPtr<IWICMetadataQueryWriter> metawriter; if (SUCCEEDED(frame->GetMetadataQueryWriter(&metawriter))) { PROPVARIANT value; PropVariantInit(&value); value.vt = VT_LPSTR; value.pszVal = const_cast<char *>("DirectXTK"); if (memcmp(&guidContainerFormat, &GUID_ContainerFormatPng, sizeof(GUID)) == 0) { // Set Software name (void)metawriter->SetMetadataByName(L"/tEXt/{str=Software}", &value); // Set sRGB chunk if (sRGB) { value.vt = VT_UI1; value.bVal = 0; (void)metawriter->SetMetadataByName(L"/sRGB/RenderingIntent", &value); } } else { // Set Software name (void)metawriter->SetMetadataByName(L"System.ApplicationName", &value); if (sRGB) { // Set EXIF Colorspace of sRGB value.vt = VT_UI2; value.uiVal = 1; (void)metawriter->SetMetadataByName(L"System.Image.ColorSpace", &value); } } } D3D11_MAPPED_SUBRESOURCE mapped; hr = pContext->Map(pStaging, 0, D3D11_MAP_READ, 0, &mapped); if (FAILED(hr)) return hr; CComPtr<IWICBitmap> source; hr = pWIC->CreateBitmapFromMemory(desc.Width, desc.Height, pfGuid, mapped.RowPitch, mapped.RowPitch * desc.Height, reinterpret_cast<BYTE *>(mapped.pData), &source); if (FAILED(hr)) { pContext->Unmap(pStaging, 0); return hr; } CComPtr<IWICBitmapScaler> bitmapScaler; hr = pWIC->CreateBitmapScaler(&bitmapScaler); if (FAILED(hr)) return hr; CComPtr<IWICBitmapSource> imageSource; if (outputWidth != desc.Width || outputHeight != desc.Height) { bitmapScaler->Initialize(source, outputWidth, outputHeight, WICBitmapInterpolationMode::WICBitmapInterpolationModeNearestNeighbor); imageSource = bitmapScaler; } else { imageSource = source; } if (memcmp(&targetGuid, &pfGuid, sizeof(WICPixelFormatGUID)) != 0) { // Conversion required to write CComPtr<IWICFormatConverter> FC; hr = pWIC->CreateFormatConverter(&FC); if (FAILED(hr)) { pContext->Unmap(pStaging, 0); return hr; } BOOL canConvert = FALSE; hr = FC->CanConvert(pfGuid, targetGuid, &canConvert); if (FAILED(hr) || !canConvert) { return E_UNEXPECTED; } hr = FC->Initialize(imageSource, targetGuid, WICBitmapDitherTypeNone, 0, 0, WICBitmapPaletteTypeMedianCut); if (FAILED(hr)) { pContext->Unmap(pStaging, 0); return hr; } imageSource.Release(); imageSource = FC; } hr = frame->WriteSource(imageSource, NULL); pContext->Unmap(pStaging, 0); if (FAILED(hr)) return hr; hr = frame->Commit(); if (FAILED(hr)) return hr; hr = encoder->Commit(); if (FAILED(hr)) return hr; return S_OK; } HRESULT CreateWICBitmapFromFile(_In_z_ const wchar_t *filePath, _In_ const GUID targetFormat, _Outptr_ IWICBitmapSource **ppIWICBitmapSource) { HRESULT hr = S_OK; if (ppIWICBitmapSource) { *ppIWICBitmapSource = nullptr; } if (!filePath) return E_INVALIDARG; // Step 1: Decode the source image auto pWIC = _GetWIC(); if (!pWIC) return E_NOINTERFACE; // Create a decoder CComPtr<IWICBitmapDecoder> pDecoder = NULL; RETURN_ON_BAD_HR(hr = pWIC->CreateDecoderFromFilename( filePath, // Image to be decoded NULL, // Do not prefer a particular vendor GENERIC_READ, // Desired read access to the file WICDecodeMetadataCacheOnDemand, // Cache metadata when needed &pDecoder // Pointer to the decoder )); CComPtr<IWICBitmapFrameDecode> pFrame = NULL; RETURN_ON_BAD_HR(hr = pDecoder->GetFrame(0, &pFrame)); WICPixelFormatGUID sourcePixelFormat; RETURN_ON_BAD_HR(hr = pFrame->GetPixelFormat(&sourcePixelFormat)); // Convert to 32bpp RGBA for easier processing. CComPtr<IWICBitmapSource> pConvertedFrame = NULL; RETURN_ON_BAD_HR(hr = WICConvertBitmapSource(targetFormat, pFrame, &pConvertedFrame)); if (SUCCEEDED(hr)) { if (ppIWICBitmapSource) { *ppIWICBitmapSource = pConvertedFrame; (*ppIWICBitmapSource)->AddRef(); } } return hr; }
C++
CL
88706043c52e308d8f1b4bc92adeae0e22dd0fc7bd011a16756e83300a9dd023
#include <iostream> #include <QPointF> // This file exists to define print overrides for catch error types // Qt does not natively support writing outputs to ostream. // This file should only be used for debug test strings, do not use // this in production code. inline std::ostream &operator<<(std::ostream &os, const QPointF &value) { return os << '(' << value.x() << ',' << value.y() << ')'; }
C++
CL
6f851288ccddbd2d32eafc49b0245fc8555324d6b1bce24ec2c37950446b6ca0
/* * File: encoder_layer.h * Project: transformer * Author: koth (Koth Chen) * ----- * Last Modified: 2019-09-16 6:14:37 * Modified By: koth ([email protected]) * ----- * Copyright 2020 - 2019 */ #pragma once #include <cstddef> #include <vector> #include "torch/nn/cloneable.h" #include "torch/nn/module.h" #include "torch/nn/modules/container/any.h" #include "torch/nn/pimpl.h" #include "torch/types.h" #include "radish/transformer/multihead_attention.h" namespace radish { using Tensor = torch::Tensor; /// Options for the `EncoderLayer` module. struct TORCH_API EncoderLayerOptions { EncoderLayerOptions(int64_t d_model, int64_t d_inner, int64_t n_head, int64_t d_k, int64_t d_v, double dropout = 0.1); TORCH_ARG(int64_t, d_model); TORCH_ARG(int64_t, d_inner); TORCH_ARG(int64_t, n_head); TORCH_ARG(int64_t, d_k); TORCH_ARG(int64_t, d_v); TORCH_ARG(double, dropout) = 0.1; }; class TORCH_API EncoderLayerImpl : public ::torch::nn::Cloneable<EncoderLayerImpl> { public: EncoderLayerImpl(int64_t d_model, int64_t d_inner, int64_t n_head, int64_t d_k, int64_t d_v, double dropout = 0.1) : EncoderLayerImpl( EncoderLayerOptions(d_model, d_inner, n_head, d_k, d_v, dropout)) {} explicit EncoderLayerImpl(EncoderLayerOptions options); void reset() override; /// Pretty prints the `Linear` module into the given `stream`. void pretty_print(std::ostream& stream) const override; std::vector<Tensor> forward(const Tensor& enc_input, const Tensor& non_pad_mask = {}, const Tensor& slf_attn_mask = {}); /// The options used to configure this module. EncoderLayerOptions options; radish::MultiheadAttention slf_attn = nullptr; torch::nn::AnyModule pos_ffn; }; /// A `ModuleHolder` subclass for `EncoderLayerImpl`. /// See the documentation for `EncoderLayerImpl` class to learn what /// methods it provides, or the documentation for `ModuleHolder` to learn about /// PyTorch's module storage semantics. TORCH_MODULE(EncoderLayer); } // namespace radish
C++
CL
84e94fa77af35719c50f61b267d0dcc7c3e0f36f65f9a927b8f4cc9da1c419f7
#pragma once #ifndef cpp_util_h_ #define cpp_util_h_ #ifndef __cplusplus #error "Do NOT include this file in C source!" #else #ifdef EXTERN_C } #endif #include <cstddef> #include <utility> #include <type_traits> #include <vector> #include <memory> #include <string> // use this to ensure a type is C-safe #define ASSERT_IS_POD(TYPE) static_assert(std::is_pod< TYPE >::value, #TYPE " must be POD to be C-safe!") // utility function providing std::vector<thing> => thing* functionality template<typename T> typename std::enable_if<std::is_pod<T>::value, size_t>::type memcpy_from_vector(T *&dest, const std::vector<typename std::remove_const<T>::type> &vec) { dest = static_cast<T*>(malloc(sizeof(T)*vec.size())); memcpy(const_cast<typename std::remove_const<T>::type*>(dest), vec.data(), sizeof(T)*vec.size()); return vec.size(); } // assume ownership, instantiate a std::string, and free the memory used std::string strcpy_and_free(char *src) noexcept; #ifdef EXTERN_C extern "C" { #endif #endif #endif
C++
CL
08643e24b9d981b9189f479dca36060fb6ecca9604e61d0eae36ea080f1ddb40
#include <OneWire.h> #include <DallasTemperature.h> #include <ESP8266WiFi.h> #include <ESP8266WiFiMulti.h> #include <InfluxDb.h> // -------- Settings -------- #define WIFI_SSID "" #define WIFI_PASS "" #define INFLUXDB_HOST "" #define INFLUXDB_PORT "8086" #define INFLUXDB_DB "" #define INFLUXDB_USER "" #define INFLUXDB_PASS "" #define ESP_LED_PIN D4 // Status LED of wemos d1 mini lite board, An solange aktiv, low=an #define ONE_WIRE_BUS D4 // Data pin of ds18b20 uint32_t sleep_time = 10; //in s, 470R zwischen D0 und RST! #define DS18B20_POWERPIN D2 // io as vcc, comment out to disable, use 100n cap on sensor when doing this! // also see "influxdb measurement and tags" in setup() // -------- -------- // 9 bits: increments of 0.5C, 93.75ms to measure temperature; // 10 bits: increments of 0.25C, 187.5ms to measure temperature; // 11 bits: increments of 0.125C, 375ms to measure temperature; // 12 bits: increments of 0.0625C, 750ms to measure temperature. #define SENSOR_RESOLUTION 12 // Setup a oneWire instance to communicate with any OneWire devices (not just Maxim/Dallas temperature ICs) OneWire oneWire(ONE_WIRE_BUS); // Pass our oneWire reference to Dallas Temperature. DallasTemperature sensors(&oneWire); DeviceAddress sensorDeviceAddress; ESP8266WiFiMulti WiFiMulti; Influxdb influx(INFLUXDB_HOST); void wifi_connect(){ Serial.print("WLAN: connecting to \"" + (String)WIFI_SSID + "\""); WiFi.begin(WIFI_SSID, WIFI_PASS); uint16_t tries=0; while (tries < 30 && WiFi.status() != WL_CONNECTED) { delay(500); Serial.print('.'); tries++; } Serial.println(""); if(WiFi.status() != WL_CONNECTED){ Serial.println("WLAN: Fehler: keine WLAN Verbindung moeglich"); }else{ Serial.print("WLAN: connected, IP address: "); Serial.println(WiFi.localIP()); } } void wifi_disconnect(){ Serial.println("WLAN: disconnected"); WiFi.disconnect(); } void go_to_sleep(uint32_t seconds){ wifi_disconnect(); if(seconds == 0){ Serial.println("Going to Sleep FOREVER!!!"); }else{ Serial.println("Going to Sleep for " + (String)seconds + 's'); } Serial.println(""); //`ESP.deepSleep(microseconds, mode)` will put the chip into deep sleep. `mode` is one of `WAKE_RF_DEFAULT`, `WAKE_RFCAL`, `WAKE_NO_RFCAL`, `WAKE_RF_DISABLED`. (GPIO16 needs to be tied to RST to wake from deepSleep.) // digitalWrite(ESP_LED_PIN, HIGH); //statusled aus ESP.deepSleep(seconds*1000000, WAKE_RF_DEFAULT); //delay(seconds*1000); } void setup() { pinMode(ESP_LED_PIN, OUTPUT); digitalWrite(ESP_LED_PIN, LOW); //statusled an #ifdef DS18B20_POWERPIN pinMode(DS18B20_POWERPIN, OUTPUT); digitalWrite(DS18B20_POWERPIN, HIGH); //artificial vcc #endif Serial.begin(9600); Serial.println(""); Serial.println("### Start ###"); if(WiFi.status() != WL_CONNECTED)wifi_connect(); if(WiFi.status() != WL_CONNECTED)wifi_connect(); if(WiFi.status() != WL_CONNECTED)wifi_connect(); if(WiFi.status() != WL_CONNECTED)wifi_connect(); if(WiFi.status() != WL_CONNECTED)wifi_connect(); if(WiFi.status() != WL_CONNECTED){ Serial.println("WLAN nicht verbindbar, sleep 5 min."); go_to_sleep(300); //0=forever } Serial.println("Init Sensor..."); delay(100); sensors.begin(); sensors.getAddress(sensorDeviceAddress, 0); sensors.setResolution(sensorDeviceAddress, SENSOR_RESOLUTION); Serial.print("Requesting temperatures..."); sensors.requestTemperatures(); // Send the command to get temperatures float temp = sensors.getTempCByIndex(0); Serial.println(" DONE"); Serial.print("Temperature for the device 1 (index 0) is: "); Serial.println(temp); influx.setDbAuth(INFLUXDB_DB, INFLUXDB_USER, INFLUXDB_PASS); // -------- influxdb measurement and tags -------- InfluxData row("temperatur"); // measurement (table) row.addTag("standort", "test"); row.addTag("board", "esp8266"); row.addTag("sensor", "ds18b20"); row.addValue("temperatur", temp); // -------- influxdb -------- influx.write(row); // delay(sleep_time); go_to_sleep(sleep_time); //0=forever } void loop() {}
C++
CL
bad0823b12ce6b82363649704ba78ac9f76b4d6bf1d26efeee54230db1bcf30a
#pragma once #include "../../Plugins/IPlugins.h" #include "IPluginsWindow.h" #include <trview.common/Windows/IShell.h> namespace trview { class PluginsWindow final : public IPluginsWindow { public: struct Names { static inline const std::string plugins_list = "Plugins"; }; explicit PluginsWindow(const std::weak_ptr<IPlugins>& plugins, const std::shared_ptr<IShell>& shell); virtual ~PluginsWindow() = default; void render() override; void set_number(int32_t number) override; void update(float dt) override; private: bool render_plugins_window(); std::string _id{ "Plugins 0" }; std::weak_ptr<IPlugins> _plugins; std::shared_ptr<IShell> _shell; }; }
C++
CL
99fb14bd36948da43964b9e86ddc6ce744228479a1012c0fbfa10b9c83a2e3b9
/////////////////////////////////////////////////////////////////////////////// // Tokenizer.cpp // ============= // General purpose string tokenizer (C++ string version) // // The default delimiters are space(" "), tab(\t, \v), newline(\n), // carriage return(\r), and form feed(\f). // If you want to use different delimiters, then use setDelimiter() to override // the delimiters. Note that the delimiter string can hold multiple characters. // // AUTHOR: Song Ho Ahn ([email protected]) // CREATED: 2005-05-25 // UPDATED: 2011-03-08 /////////////////////////////////////////////////////////////////////////////// #include "Tokenizer.h" #include <iostream> using namespace std; /////////////////////////////////////////////////////////////////////////////// // constructor /////////////////////////////////////////////////////////////////////////////// Tokenizer::Tokenizer() : buffer(""), token(""), delimiter(DEFAULT_DELIMITER) { currPos = buffer.begin(); } Tokenizer::Tokenizer(const std::string& str, const std::string& delimiter) : buffer(str), token(""), delimiter(delimiter) { currPos = buffer.begin(); } /////////////////////////////////////////////////////////////////////////////// // destructor /////////////////////////////////////////////////////////////////////////////// Tokenizer::~Tokenizer() { } /////////////////////////////////////////////////////////////////////////////// // reset string buffer, delimiter and the currsor position /////////////////////////////////////////////////////////////////////////////// void Tokenizer::set(const std::string& str, const std::string& delimiter) { this->buffer = str; this->delimiter = delimiter; this->currPos = buffer.begin(); } void Tokenizer::setString(const std::string& str) { this->buffer = str; this->currPos = buffer.begin(); } void Tokenizer::setDelimiter(const std::string& delimiter) { this->delimiter = delimiter; this->currPos = buffer.begin(); } /////////////////////////////////////////////////////////////////////////////// // return the next token // If cannot find a token anymore, return "". /////////////////////////////////////////////////////////////////////////////// std::string Tokenizer::next() { if(buffer.size() <= 0) return ""; // skip if buffer is empty token.clear(); // reset token string this->skipDelimiter(); // skip leading delimiters // append each char to token string until it meets delimiter while(currPos != buffer.end() && !isDelimiter(*currPos)) { token += *currPos; ++currPos; } return token; } /////////////////////////////////////////////////////////////////////////////// // skip ang leading delimiters /////////////////////////////////////////////////////////////////////////////// void Tokenizer::skipDelimiter() { while(currPos != buffer.end() && isDelimiter(*currPos)) ++currPos; } /////////////////////////////////////////////////////////////////////////////// // return true if the current character is delimiter /////////////////////////////////////////////////////////////////////////////// bool Tokenizer::isDelimiter(char c) { return (delimiter.find(c) != std::string::npos); } /////////////////////////////////////////////////////////////////////////////// // split the input string into multiple tokens // This function scans tokens from the current cursor position. /////////////////////////////////////////////////////////////////////////////// std::vector<std::string> Tokenizer::split() { std::vector<std::string> tokens; std::string token; while((token = this->next()) != "") { tokens.push_back(token); } return tokens; } /* * Method: Tokenizer::sort_tokens * Params: * Returns: std::vector<std::string> * Effects: */ std::vector<std::string> Tokenizer::sort_tokens() { std::vector<std::string> dummy; cerr << "Tokenizer::sort_tokens()" << endl; return dummy; } /* * Method: Tokenizer::set_of_tokens * Params: * Returns: std::set<std::string> * Effects: */ std::set<std::string> Tokenizer::set_of_tokens() { std::set<std::string> dummy; cerr << "Tokenizer::set_of_tokens()" << endl; return dummy; } /* * Method: Tokenizer::longest_token * Params: * Returns: std::string * Effects: */ std::string Tokenizer::longest_token() { std::string dummy; cerr << "Tokenizer::longest_token()" << endl; return dummy; } /* * Method: Tokenizer::find_token * Params: unsigned int n * Returns: std::string * Effects: */ std::string Tokenizer::find_token(unsigned int n) { std::string dummy; cerr << "Tokenizer::find_token()" << endl; return dummy; } /* * Method: Tokenizer::check_for_duplicates * Params: * Returns: bool * Effects: */ bool Tokenizer::check_for_duplicates() { bool dummy; cerr << "Tokenizer::check_for_duplicates()" << endl; return dummy; } std::map<int, string> Tokenizer::build_map() { std::map<int, string> dummy; cerr << "Tokenizer::build_map()" << endl; return dummy; }
C++
CL
93ba8c205296108944deb5c2fb3f48b7b3d6db005794ab379f7d6a4a0e0688ac
#include "messagesignalreceivedblock.h" #include "../../executionhandler.h" #include "../../statementblock.h" #include "../../programmodel.h" #include "../../intmessage.h" #include <QDebug> MessageSignalReceivedBlock::~MessageSignalReceivedBlock() { if(_message != NULL) delete _message; delete _signalQueue; } QList<Block::ParamType> MessageSignalReceivedBlock::getParamTypes() const { QList<Block::ParamType> params; params.append(Block::STRING_EXPRESSION); return params; } void MessageSignalReceivedBlock::sendSignal(const Signal& signal, Sprite* sprite) { //check pointer and type of signal if(sprite == NULL || signal.getType() != Signal::MESSAGE) return; //add signal to queue _signalQueue->enqueue(signal); //run statements sprite->getProgramModel()->getExecutionHandler()->addExecutionThread(this, sprite->getVarTable(), sprite); } void MessageSignalReceivedBlock::executeNextStep(ExecutionThread &executionThread) const { //check if block is valid for execution if(_message == NULL) { //take signal from queue if(_signalQueue->size() > 0) _signalQueue->dequeue(); executionThread.endExecution(NULL); return; } //get message IntMessage* m = (IntMessage*)executionThread.getMessage(); if(m == NULL) { m = new IntMessage(0); executionThread.setMessage(m); } //evaluate message if(m->getValue() == 0) { executionThread.setNextBlock(_message); m->setValue(1); return; } if(m->getValue() == 1) { Value* message = executionThread.getReturnValue(); if(message == NULL || message->getDataType() != Value::STRING) { //take signal from queue if(_signalQueue->size() > 0) _signalQueue->dequeue(); executionThread.endExecution(NULL); return; } //if no signal, end execution if(_signalQueue->isEmpty()) { executionThread.endExecution(NULL); return; } //if message does not equal the signal message, end execution if(message->toString() != _signalQueue->dequeue().getMessage()) { executionThread.endExecution(NULL); return; } //message equals the signal message -> start execution executionThread.setNextBlock(getStatement()); m->setValue(2); return; } executionThread.endExecution(NULL); } bool MessageSignalReceivedBlock::addParameter(Block *parameter, int index) { if(parameter == NULL || index != 0) return false; if(parameter->getReturnType() == Block::STRING_EXPRESSION || parameter->getReturnType() == Block::STRING_VAR) { _message = (ExpressionBlock*)parameter; return true; } return false; }
C++
CL
724338f1ae5bd7e69513daffc07c6fe473a29407360fd5a0ef50b711b409a327
 #include "ProxyTester.h" // при отладки переопределяем функцию чтения/записи usb-порта int ProxyTester::UpdateTesterState(void) { #ifndef DEBUG RT.UpdateTesterState(); #else // прибор не подключен, никакие данные в порт не посылаем Sleep(3); // имитируем задержку реакции на команду return 0; // возвращаем безошибочное состояние USB-порта #endif } void ProxyTester::SetAltitude(double alt){ #ifndef DEBUG RT.SetAltitude(alt); #else Tester::cve.SetAltitude(alt); // прибор не подключен, никакие данные в порт не посылаем // имитируем выдачу команды на заданной высоте и ослаблении if ( (RT.GetAltitude() >= 12) & (RT.GetAltitude() <= 15) & (RT.GetAttenuation() <= 100) ) RT.SetVK(TRUE); #endif } void ProxyTester::SetAttenuation(double att){ #ifndef DEBUG RT.SetAttenuation(att); #else Tester::cve.SetAttenuation(att); // прибор не подключен, никакие данные в порт не посылаем // имитируем выдачу команды на заданной высоте и ослаблении if ( (RT.GetAltitude() >= 12) & (RT.GetAltitude() <= 15) & (RT.GetAttenuation() <= 100) ) RT.SetVK(TRUE); #endif } int ProxyTester::GetError(void){ #ifndef DEBUG RT.GetError(att); #else // имитируем отсутсвие ошибок return 0; #endif } bool ProxyTester::GetVK(void){ #ifndef DEBUG RT.GetVK(); #else // читаем команду непосредстенно с объекта экземпляра RD return Tester::rd.GetVK(); #endif } ProxyTester::ProxyTester(void) { } ProxyTester::~ProxyTester(void) { }
C++
CL
0df63fc478d53af7d752e989ac1249f8acd0180782631d59cf0db898f2c2e8e6
#include <stdlib.h> #include "linalg.h" #include "fractals.h" namespace Aloschil { using namespace std; //---------------------------------------------------------------------------- // This is a public API. Refer to fractals.h for details. //---------------------------------------------------------------------------- SimpleGeometricFractal::SimpleGeometricFractal() { deletionType = DeletePrevious; overallPolicy= DontMirrorOverallPolicy; onIterationPolicy= DontMirrorOnIterationPolicy; onSegmentNumberPolicy= DontMirrorOnSegmentNumberPolicy; } //---------------------------------------------------------------------------- // This is a public API. Refer to fractals.h for details. //---------------------------------------------------------------------------- void SimpleGeometricFractal::calculate(const list<Segment> &_iterator,const list<Segment> &_initializer,unsigned int numberOfIterations,double delta) { iterator=_iterator; iterations.clear(); iterations.push_back(_initializer); double overallYScaleSign = (overallPolicy==DontMirrorOverallPolicy) ? 1 : -1; for(unsigned int i=0;i<numberOfIterations;++i) { list<Segment> currIterationSegments; list<Segment>::iterator curSegment = iterations[i].begin(); list<Segment>::iterator endSegment = iterations[i].end(); double onIterationScaleSign; switch(onIterationPolicy) { case MirrorOnEvenOnIterationPolicy: onIterationScaleSign = (i%2==0) ? -1 : 1; break; case MirrorOnOddOnIterationPolicy: onIterationScaleSign = (i%2!=0) ? -1 : 1; break; case DontMirrorOnIterationPolicy: onIterationScaleSign = 1; break; } unsigned int segmentNumber=0; for(;curSegment!=endSegment;++curSegment,++segmentNumber) { double onSegmentNumberScaleSign; switch(onSegmentNumberPolicy) { case MirrorOnEvenOnSegmentNumberPolicy: onSegmentNumberScaleSign = (segmentNumber%2==0) ? -1 : 1; break; case MirrorOnOddOnSegmentNumberPolicy: onSegmentNumberScaleSign = (segmentNumber%2!=0) ? -1 : 1; break; case DontMirrorOnSegmentNumberPolicy: onSegmentNumberScaleSign = 1; break; } double curSign = onSegmentNumberScaleSign*onIterationScaleSign*overallYScaleSign; double curSegmentLength = (*curSegment).getLength(); if(curSegmentLength>delta) { Matrix curSegmentVector = (*curSegment).getVector(); Matrix &curFirstVertex = (*curSegment).p1; Matrix transformation = translate(curFirstVertex[0], curFirstVertex[1], curFirstVertex[2])* rotateZ(ang(Vector(1.0,0.0),Vector(curSegmentVector[0],curSegmentVector[1])))* scale(curSegmentLength,curSign*curSegmentLength,curSegmentLength); list<Segment>::iterator curIteratorSegment = iterator.begin(); list<Segment>::iterator endIteratorSegment = iterator.end(); for(;curIteratorSegment!=endIteratorSegment ;++curIteratorSegment) { Matrix tmp1 = transformation*(*curIteratorSegment).p1; Matrix tmp2 = transformation*(*curIteratorSegment).p2; Segment tmp; tmp.p1 = tmp1; tmp.p2 = tmp2; currIterationSegments.push_back(tmp); } switch(deletionType) { case KeepPrevious: currIterationSegments.push_back(*curSegment); break; case DeletePrevious: break; case DeleteOnEvenIterations: if(i%2) currIterationSegments.push_back(*curSegment); break; case RandomDeletion: if(rand()>RAND_MAX/2.0) currIterationSegments.push_back(*curSegment); break; } } else { currIterationSegments.push_back(*curSegment); } } iterations.push_back(currIterationSegments); } } void IterableFunctionsSystemFractal::calculate( const vector<Matrix> &baseVertex, const vector<Matrix> &transformationTriples, unsigned int numberOfIterations) { iterations.clear(); // Calculating transformation matrices vector<Matrix> transformationMatrices; if(baseVertex.empty()) return; Matrix baseTrianlgeMatrix = baseVertex[0]; baseTrianlgeMatrix = augment(baseTrianlgeMatrix, baseVertex[1]); baseTrianlgeMatrix = augment(baseTrianlgeMatrix, baseVertex[2]); Matrix inverseBaseTriangleMatrix = (!baseTrianlgeMatrix); unsigned int numberOfTransformations = transformationTriples.size()/3; for(unsigned int i=0;i<numberOfTransformations;++i) { Matrix endTrianlgeMatrix = transformationTriples[i*3]; endTrianlgeMatrix = augment(endTrianlgeMatrix, transformationTriples[i*3+1]); endTrianlgeMatrix = augment(endTrianlgeMatrix, transformationTriples[i*3+2]); transformationMatrices.push_back(endTrianlgeMatrix*inverseBaseTriangleMatrix); } iterations.push_back(transformationTriples); for(unsigned int i=1;i<numberOfIterations;++i) { vector<Matrix> currentIterationVertices; unsigned int numberOfVerticesInPrIt = iterations[i-1].size(); for(unsigned int curVertex=0;curVertex<numberOfVerticesInPrIt;++curVertex) { unsigned int numberOfTransformations = transformationMatrices.size(); for(unsigned int curTransform=0;curTransform<numberOfTransformations;++curTransform) currentIterationVertices.push_back(transformationMatrices[curTransform]*iterations[i-1][curVertex]); } iterations.push_back(currentIterationVertices); } } }
C++
CL
722b5f9113adb726fc2b4ba26371baa1066f6fa1e3a165d6029ddcd9d3f47fb7
/* * Name: SalesMgr.h * * Description: The SalesMgr object is responsible for collecting and reporting * sales information for the Ecommerce simulation. * */ #ifndef SALESMGR_H #define SALESMGR_H #include <iostream> #include <string> #include <sstream> #include "ProductT.h" #include "Queue.h" #include "Message.h" //std::string productType[] { "jacket", "pants", "shorts", "shirt", "socks" }; class SalesMgr { public: SalesMgr(); // constructor explicit SalesMgr(Queue<Message>* smq); // constructor ~SalesMgr(); // destructor SalesMgr(const SalesMgr& copySource); // copy constructor void SalesMgrMonitor(); // sales monitor void operator () (); void UpdateSalesCounters(const Message); void OutputSalesCounters(); Queue<Message>* GetMsgQueuePtr(); // friend std::ostream& operator<< (std::ostream& os, const Message& sm); private: struct ApparelCtr { int itemType{0}; int itemSizeS{0}; // Small counter int itemSizeM{0}; // Medium counter int itemSizeL{0}; // Large counter int itemColorBR{0}; // Brown counter int itemColorRD{0}; // Red counter int itemColorWH{0}; // White counter int itemColorGR{0}; // Green counter int itemColorBK{0}; // Black counter int itemColorBL{0}; // Blue counter double itemCost{0.0}; }; double totalSales{0.0}; ApparelCtr* menProdCtr[PRODUCT_CT]{nullptr,nullptr,nullptr,nullptr,nullptr}; ApparelCtr* womenProdCtr[PRODUCT_CT]{nullptr,nullptr,nullptr,nullptr,nullptr}; Queue<Message>* salesMsgQueuePtr{nullptr};; // apparel, M or F, size, color }; #endif
C++
CL
1f376c1fd9d771a1d540983cd88da3dd91ffd73e95ec1f2dcb1b45e83097f111
#include "DockerClient.h" #include "DockerExceptions.h" #include "HTTPCommon.h" #include <fmt/format.h> #include <chrono> #include <future> #include <thread> namespace Sphinx { namespace Docker { namespace v2 { using json = nlohmann::json; namespace fs = boost::filesystem; template <typename T> ResultJSON DockerSocketClient<T>::list_images() { auto response = client->get("/images/json?all=1"); auto images = json::parse(response.data()); return {DockerStatus::NoError, images}; } template <typename T> ResultJSON DockerSocketClient<T>::list_containers() { auto response = client->get("/containers/json?all=1&size=1"); auto containers = json::parse(response.data()); return {DockerStatus::NoError, containers}; } template <typename T> ResultJSON DockerSocketClient<T>::get_info() { auto response = client->get("/info"); auto info = json::parse(response.data()); auto status = DockerStatus::NoError; if (response.status() == HTTPStatus::SERVER_ERROR) { status = DockerStatus::ServerError; } return {status, info}; } template <typename T> ResultJSON DockerSocketClient<T>::create_container( const std::string &image_name, const std::vector<std::string> &commands, const fs::path &working_dir, const std::vector<std::pair<fs::path, fs::path>> &mounting_points) { std::vector<std::string> binds; std::transform(std::begin(mounting_points), std::end(mounting_points), std::back_inserter(binds), [](const auto &p) { return fmt::format("{0}:{1}", p.first.string(), p.second.string()); }); json container = {{"Hostname", ""}, {"User", ""}, {"Memory", 0}, {"MemorySwap", 0}, {"AttachStdin", true}, {"AttachStdout", true}, {"AttachStderr", true}, {"Tty", false}, {"OpenStdin", true}, {"StdinOnce", true}, {"Cmd", commands}, {"Image", image_name}, {"HostConfig", {{"Binds", binds}}}, {"WorkingDir", working_dir.string()}}; const auto request_data = container.dump(); logger->debug("Container creation JSON: {}", container.dump(4)); auto response = client->post("/containers/create", request_data); logger->debug("Create container: {0}", response.dump()); auto status = translate_status<DockerOperation::CreateContainer>(response.status()); return {status, json::parse(response.data())}; } template <typename T> ResultJSON DockerSocketClient<T>::wait_container(const Container &container) { auto request = fmt::format("/containers/{0}/wait", container.id); auto response = client->post(request); logger->debug("Waiting for the container: {0}", response.dump()); auto status = translate_status<DockerOperation::WaitContainer>(response.status()); return {status, json::parse(response.data())}; } template <typename T> ResultJSON DockerSocketClient<T>::start_container(const Container &container) { auto request = fmt::format("/containers/{0}/start", container.id); auto response = client->post(request); logger->debug("Start container: {0}", response.dump()); auto status = translate_status<DockerOperation::StartContainer>(response.status()); if (response.data().empty()) { return {status, json{}}; } return {status, json::parse(response.data())}; } template <typename T> ResultJSON DockerSocketClient<T>::attach_container(const Container &container, IOBuffers &io_buffers) { auto request = fmt::format( "/containers/{0}/attach?stream=1&logs=1&stdout=1&stderr=1&stdin=1", container.id); client->set_output_stream(&io_buffers.output); client->set_error_stream(&io_buffers.error); client->set_input_stream(&io_buffers.input); client->use_output_streams(true); client->use_input_stream(true); auto response = client->post(request, "", {{"Upgrade", "tcp"}}); client->use_output_streams(false); client->use_input_stream(false); auto status = translate_status<DockerOperation::AttachContainer>(response.status()); return {status, {}}; } template <typename T> ResultJSON DockerSocketClient<T>::inspect_container(const Container &container) { auto query_path = fmt::format("/containers/{0}/json", container.id); auto response = client->get(query_path); logger->debug("Inspect container: {0}", response.data()); auto status = translate_status<DockerOperation::InspectContainer>(response.status()); return {status, json::parse(response.data())}; } template <typename T> ResultJSON DockerSocketClient<T>::remove_container(const Container &container) { auto query_path = fmt::format("/containers/{0}", container.id); auto response = client->request(HTTPMethod::DELETE, query_path); logger->debug("Remove container: {0}", container.id); auto status = translate_status<DockerOperation::RemoveContainer>(response.status()); if (response.data().empty()) { return {status, json{}}; } return {status, json::parse(response.data())}; } template <typename T> ResultJSON DockerSocketClient<T>::stop_container(const Container &container, unsigned int wait_time) { auto query_path = fmt::format("/containers/{0}/stop?t={1}", container.id, wait_time); auto response = client->post(query_path); logger->debug("Stop container: {0}", container.id); auto status = translate_status<DockerOperation::StopContainer>(response.status()); if (response.data().empty()) { return {status, json{}}; } return {status, json::parse(response.data())}; } template <typename T> int DockerSocketClient<T>::run_command_in_mounted_dir( const std::vector<std::string> &cmd, const fs::path &mount_dir, IOBuffers &io_buffers) { auto working_dir = fs::path("/home/sandbox"); auto create_result = create_container( image_name, cmd, working_dir, {std::make_pair(mount_dir, working_dir)}); throw_if_error(create_result); Container container{std::get<1>(create_result).at("Id")}; SCOPE_EXIT(throw_if_error(remove_container(container))); auto start_result = start_container(container); throw_if_error(start_result); auto attach_result = attach_container(container, io_buffers); throw_if_error(attach_result); auto wait_result = wait_container(container); throw_if_error(wait_result); int exit_code = std::get<1>(wait_result).at("StatusCode"); return exit_code; } template <typename T> std::tuple<std::string, std::string, int> DockerSocketClient<T>::run_command_in_mounted_dir( const std::vector<std::string> &cmd, const fs::path &mount_dir, const std::string &stdin) { IOBuffers io_buffers; std::ostream stdin_stream(&io_buffers.input); stdin_stream << stdin; auto exit_code = run_command_in_mounted_dir(cmd, mount_dir, io_buffers); std::string data_error{std::istreambuf_iterator<char>(&io_buffers.error), {}}; std::string data{std::istreambuf_iterator<char>(&io_buffers.output), {}}; return {data, data_error, exit_code}; } template <typename T> template <typename U> std::string DockerSocketClient<T>::get_message_error(const U & /*data*/) { return {}; } template <typename T> std::string DockerSocketClient<T>::get_message_error(const nlohmann::json &data) { return data["message"]; } template <typename T> template <typename... U> bool DockerSocketClient<T>::throw_if_error(const Result<U...> &result) { if (const auto &status = std::get<0>(result); status != DockerStatus::NoError) { std::string message = get_message_error(std::get<1>(result)); logger->error("Status code: {}, Error message: {}", static_cast<int>(status), message); throw docker_exception{message}; } return false; } template <typename T> template <typename... U> bool DockerSocketClient<T>::is_error(const Result<U...> &result) { if (const auto &status = std::get<0>(result); status != DockerStatus::NoError) { logger->error("Status code: {}, Error message: {}", static_cast<int>(status), get_message_error(std::get<1>(result))); return true; } return false; } #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wweak-template-vtables" template class DockerSocketClient<UnixSocket>; template class DockerSocketClient<TCPSocket>; #pragma clang diagnostic pop } // namespace v2 } // namespace Docker } // namespace Sphinx
C++
CL
c8b71b0483cc2fe742c49d9d3fd43eb44ca53331cd55c9273d0306f428bfd642
#include <iostream> #include "ProjectUility.hpp" #include "DimensionUtility.hpp" #include "Geometry.hpp" //#include "Domain.hpp" //#include "Solver.hpp" #include "GeometryDataProcessor.hpp" #include "Dof.hpp" #include "GeometryLoader.hpp" #include "DofUnit.hpp" //void DemoDataArray(); //void DemoDataTable(); int main() { auto proj_1 = ArtProject::create("TestProj").setRunPath(".").setDivideSlash("/").setInitialFolderName("Init").build(); auto quadMeshForIntgration = Geometry<Dim2D, MeshTypeMethod>::create("Test2D_BLM").setSourceFormat(GeometrySourceFormat::File) .load(proj_1).preprocess().build(); auto blmMeshForApproximation = Geometry<Dim2D, FEM>::create("Test2D_Quad").load(proj_1).preprocess().build(); // //// auto geoSetting = Geometry<Dim2D, FEM>::create("Test2D_BLM").setSourceFormat(GeometrySourceFormat::File); //// auto geoLoading = geoSetting.load(proj_1); //// auto geoPreProcess = geoLoading.preprocess(); //// auto blmMeshForApproximation = geoPreProcess.build(); // // std::cout << "---- Int Mesh ----" << std::endl; std::cout << *(quadMeshForIntgration->xNode) << std::endl; std::cout << *(quadMeshForIntgration->cElement30) << std::endl; std::cout << "---- Approxi Mesh ----" << std::endl; std::cout << *(blmMeshForApproximation->xNode) << std::endl; std::cout << *(blmMeshForApproximation->cElement30) << std::endl; std::cout << "---- Test FemElement ----" << std::endl; std::cout << *blmMeshForApproximation->femElement[2]->getVolume() << std::endl; std::cout << "---- Test Dof ----" << std::endl; Dof<Dim2D, DofVector> coord("Dof_Coord", *(quadMeshForIntgration->xNode)); std::cout << coord << std::endl; Dof<Dim2D, DofScalar> temp("T", quadMeshForIntgration->xNode->size()); std::cout << temp << std::endl; // GeometryDataProcessor<Dim2D, Geometry<Dim2D, MeshTypeMethod>::GeoType> a(quadMeshForIntgration); // a.process(); // auto one2Dpoint = blmMeshForApproximation->xNode->getPoint(1); // one2Dpoint->x(); one2Dpoint->y(); // // auto eleConnect = blmMeshForApproximation->cElement30->getElementConnectivity(3); // eleConnect->getVertex()[1]->x(); // // ArtCFD project // ProjectArt proj("TestProj"); // // // Geometry set up // auto pGeo = std::make_shared<Geometry<Dim2D,FEM>>(); // // // FEM Geometry Read // IO_FileReader IO_Reader(proj); // pGeo->getGeoData()->readFile(IO_Reader); // pGeo->getGeoData()->DataProcessor(); // // // DOF create // auto dof = std::make_shared<DOF<Dim2D, ScalarDOF>>("T", pGeo->getGeoData()->xNode->getSize()); // // // System create // auto sys = std::make_shared<System<Dim2D, FEM, ScalarDOF>>(pGeo, dof); // // // Domain create (and add system) // auto domain = std::make_shared<Domain<Dim2D, FEM>>(); // domain->addSystem(std::static_pointer_cast<SystemBase<Dim2D, FEM>>(sys)); // // // Problem solve // auto solver = std::make_shared<Solver<Dim2D, FEM>>(domain); // solver->solve(); // // // Output DOF // IO_FileWriter IO_writer(proj); // dof->writeFile(IO_writer, pGeo->getGeoData()->xNode); // DemoDataArray(); // DemoDataTable(); return 0; } //void DemoDataArray(){ // // DataArray Demo // std::cout<< "======== Start to Demo DataArray ========" <<std::endl; // // Two kind of data source will be created // std::shared_ptr<std::vector<double>> data1 = std::make_shared<std::vector<double>>(5,5.5); // std::vector<int> data2{1,2,3,4,5,6,7,8,9}; // // // Influence data builder construct memory-safe pointer with 1-D array // auto dataArrayOut1 = DataArray<double>::create("Array1").dataFrom(data1).build(); // auto dataArrayOut2 = DataArray<int>::create("Array2").dataFrom(data2).build(); // // // Show array results // std::cout<< (*dataArrayOut1) <<std::endl; // std::cout<< (*dataArrayOut2) <<std::endl; // // // Copy (Constructor & Assignment) // DataArray<double> testCopyArray1{}; // testCopyArray1 = (*dataArrayOut1); // testCopyArray1.setName("testCopyArray1"); // // DataArray<int> testCopyArray2(*dataArrayOut2); // testCopyArray2.setName("testCopyArray2"); // // std::cout<< testCopyArray1 <<std::endl; // std::cout<< testCopyArray2 <<std::endl; // // // Move (Constructor & Assignment) // decltype(testCopyArray1) testMoveArray1; // testMoveArray1 = std::move(testCopyArray1); // testMoveArray1.setName("testCopyArray1(Move)"); // // std::cout << "After Move:" << std::endl; // std::cout<< testMoveArray1 <<std::endl; // std::cout << "Original Data:" << std::endl; // std::cout<< testCopyArray1 <<std::endl; // // decltype(testCopyArray2) testMoveArray2(std::move(testCopyArray2)); // testMoveArray2.setName("testCopyArray2(Move)"); // std::cout << "After Move:" << std::endl; // std::cout<< testMoveArray2 <<std::endl; // std::cout << "Original Data:" << std::endl; // std::cout<< testCopyArray2 <<std::endl; // // // Access element // size_t pos = 3; // std::cout<<testMoveArray1.at(pos)<<std::endl; // std::cout<<testMoveArray2(5)<<std::endl; // // // Iterator // std::cout<< "Iterator Access testMoveArray1" << std::endl; // for (auto i = testMoveArray1.begin(); i != testMoveArray1.end(); ++i) { // std::cout<< *i << std::endl; // } // // std::cout<< "Const Iterator Access testMoveArray2" << std::endl; // for (auto i = testMoveArray2.cbegin(); i != testMoveArray2.cend(); ++i) { // std::cout<< *i << std::endl; // } // // // Error // try { // std::cout<<testMoveArray2(100)<<std::endl; // } // catch(std::exception &err){ // std::cout << err.what() <<std::endl; // } //} // //void DemoDataTable(){ // // DataTable Demo // std::cout<< "======== Start to Demo DataTable ========" <<std::endl; // // Two kind of data source will be created // std::shared_ptr<StdVectorTensor2D<int>> data1 = std::make_shared<StdVectorTensor2D<int>>(); // (*data1).emplace_back(std::vector<int>{1,2,3}); // (*data1).emplace_back(std::vector<int>{4,5,6}); // (*data1).emplace_back(std::vector<int>{7,8,9}); // // StdVectorTensor2D<double> data2{}; // data2.emplace_back(std::vector<double>{1.1,1.2,1.3}); // data2.emplace_back(std::vector<double>{2.1,2.2,2.3,2.4,2.5,2.6,2.7}); // data2.emplace_back(std::vector<double>{3.1,3.2}); // data2.emplace_back(std::vector<double>{4e-1,5e-1,6e-1}); // // // Influence data builder construct memory-safe pointer with 2-D table // auto dataTableOut1 = DataTable<int>::create("Table1").dataFrom(data1).build(); // auto dataTableOut2 = DataTable<double>::create("Table2").dataFrom(data2).build(); // // // Show table results // std::cout<< (*dataTableOut1) <<std::endl; // std::cout<< (*dataTableOut2) <<std::endl; // // // Access element // std::cout<< "Access dataTableOut1(2,0)" << std::endl; // std::cout<< (*dataTableOut1).at(2, 0) <<std::endl; // std::cout<< "Access dataTableOut2(3,1)" << std::endl; // std::cout<< (*dataTableOut2)(3,1) <<std::endl; // std::cout<< "Access dataTableOut2(3,1)" << std::endl; // std::cout<< (*dataTableOut2).row(3).col(2) << std::endl; // // // Copy (Constructor & Assignment) // DataTable<int> testCopyTable1{}; // testCopyTable1 = (*dataTableOut1); // testCopyTable1.setName("testCopyTable1"); // // DataTable<double> testCopyTable2(*dataTableOut2); // testCopyTable2.setName("testCopyTable2"); // // std::cout<< testCopyTable1 <<std::endl; // std::cout<< testCopyTable2 <<std::endl; // // // Move (Constructor & Assignment) // decltype(testCopyTable1) testMoveTable1; // testMoveTable1 = std::move(testCopyTable1); // testMoveTable1.setName("testCopyTable1(Move)"); // // std::cout << "After Move:" << std::endl; // std::cout<< testMoveTable1 <<std::endl; // std::cout << "Original Data:" << std::endl; // std::cout<< testCopyTable1 <<std::endl; // // decltype(testCopyTable2) testMoveTable2(std::move(testCopyTable2)); // testMoveTable2.setName("testCopyTable2(Move)"); // std::cout << "After Move:" << std::endl; // std::cout<< testMoveTable2 <<std::endl; // std::cout << "Original Data:" << std::endl; // std::cout<< testCopyTable2 <<std::endl; // // // Iterator // std::cout<< "Iterator Access row 1 in testMoveTable1" << std::endl; // for (auto i = testMoveTable1.row(1).begin(); i != testMoveTable1.row(1).end(); ++i) { // std::cout<< *i << std::endl; // } // // std::cout<< "Iterator Access row 1 in testMoveTable2" << std::endl; // for (auto i = testMoveTable2.row(1).cbegin(); i != testMoveTable2.row(1).cend(); ++i) { // std::cout<< *i << std::endl; // } // // // Isolated column // auto TableOut2_C0 = (*dataTableOut2).row(0); // auto TableOut2_C1 = (*dataTableOut2).row(1); // auto TableOut2_C2 = (*dataTableOut2).row(2); // // std::cout << TableOut2_C0 << std::endl; // std::cout << TableOut2_C1 << std::endl; // std::cout << TableOut2_C2 << std::endl; // // // Error // try { // std::cout<< "Try access testMoveTable1(100,1)"<<std::endl; // std::cout<<testMoveTable1(100,1)<<std::endl; // } // catch(std::exception &err){ // std::cout << err.what() <<std::endl; // } // // try { // std::cout<< "Try access testMoveTable2(1,100)"<<std::endl; // std::cout<<testMoveTable2(1,100)<<std::endl; // } // catch(std::exception &err){ // std::cout << err.what() <<std::endl; // } // // try { // std::cout<< "Try access testMoveTable2(100,100)"<<std::endl; // std::cout<<testMoveTable2(100,100)<<std::endl; // } // catch(std::exception &err){ // std::cout << err.what() <<std::endl; // } // //}
C++
CL
61944238848803b38c625aaa729cc694fce4e5727aa03b66962f1da704922b25
#include <Arduino.h> #define DEBUG_MSG //#define USED_BUZZER // Interpreteur #define START_STOP "s" #define PAUSE_NOPAUSE "p" #define FLASH_ONOFF "f" #define CONFIG_MODE "c={" // c={VAR1=var1value|VAR2=var2value...} #define BAUD_RATE (57600) #define BAUD_RATE_VAR "BAUD_RATE" #define INPUTSTRING_SIZE (40) #define OUTPUTSTRING_SIZE (20) // definition des ports. // #define FLASH_PIN 11 //sortie pwm eclairage #define CAM_PIN 9 //sortie commande photo aux cameras (toujours LOW, mais INPUT pour haute impedance et OUTPUT pour mettre a la masse) //#define STARTCAM_PIN 4 //entree debut serie de photos //#define READYCAM_PIN 5 //Cam prête #define RUN_LED 6 //run arduino #ifdef USED_BUZZER #define BUZZER_PIN 5 //buzzer #endif // definitions flash #define MAX_FLASHLEVEL 255 // Niveau eclairement max (ie flash). #define MIN_FLASHLEVEL 5 // Niveau eclairement eco. #define FLASH_OFFLEVEL 0 // default FLASH ON. #define STAB_FLASH_DELAY 2 #define FLASH_DELAY 10 // Extinction du flash apres prise de photo. // definitions cam #define TIME_ACQUISITION_VAR "TIME_ACQUISITION" // Temps acquisition photo. #define CAM_WRITE_DELAY 1 // delay apres ecriture sur pin de camlight #ifdef USED_BUZZER #define BUZZER_ON 255 // Buzzer on . #define BUZZER_OFF 0 // buzzer off. #endif // Serial unsigned int baud_rate = BAUD_RATE; String inputString = String(""); // a string to hold incoming data. String outputString = String(""); // A string to hold IS+TimeStamp of current pics boolean stringComplete = false; // whether the string is complete. // Cam & pics int num_pics; // number of pics. unsigned long prevShot_ms; // prev time pics in ms. unsigned long currentShot_ms ; // current time pics in ms. unsigned long beginWork_ms ; // debut chantier en ms unsigned int time_acquisition_delay=15; // Time acquisition of a photo. This value is embedded on SD card unsigned int time_between_pics=900; // Time between two pics in ms. unsigned int delay_correction=time_acquisition_delay+FLASH_DELAY+STAB_FLASH_DELAY+CAM_WRITE_DELAY; // correction des temps pour obtenir un intervalle de temps entre photos correct unsigned int time_between_pics_revised=time_between_pics-delay_correction ; // temps corrigé // states boolean start_state ; boolean pause_state ; boolean flash_state ; void initSerial() { String msg = String("") ; inputString.reserve(INPUTSTRING_SIZE) ; outputString.reserve(OUTPUTSTRING_SIZE) ; //Initialize serial and wait for port to open: Serial.begin(baud_rate) ; while (!Serial) { ; } msg="Serial communication ready at "+String(baud_rate)+" baud!" ; Serial.println(msg) ; return ; } void configurePorts() { pinMode(FLASH_PIN, OUTPUT); pinMode(CAM_PIN, INPUT); //pinMode(STARTCAM_PIN, INPUT); pinMode(RUN_LED, OUTPUT); #ifdef USED_BUZZER pinMode(BUZZER_PIN, OUTPUT); #endif return ; } void serialEvent() { while (Serial.available()) { char inChar = (char)Serial.read(); //get new byte if (inChar != '\n') { inputString += inChar; } // TODO warn not ctr sur lenght else { stringComplete = true; } } return ; } void parseConfig(String is) { String msg = String("") ; String temp = String(""); int index=0; while( is.length()!=0 ) { index=is.indexOf("|") ; if(index==-1) { temp=is.substring(0,is.length()) ; is="" ; } else { temp=is.substring(0, index) ; is=is.substring(index+1,is.length()) ; } #ifdef DEBUG_MSG msg="temp=["+temp+"]" ; Serial.println(msg) ; msg="is=["+is+"]" ; Serial.println(msg) ; #endif if( temp.substring( 0,temp.indexOf("=") )==BAUD_RATE_VAR) { baud_rate=temp.substring(temp.indexOf("=")+1, temp.length()).toInt() ; } else if (temp.substring(0,temp.indexOf("="))==TIME_ACQUISITION_VAR) { time_acquisition_delay=temp.substring( temp.indexOf("=")+1, temp.length()).toInt() ; } else { msg="WARNING: "+temp.substring( 0,temp.indexOf("="))+" variable unknown!" ; Serial.println(msg) ; } } return ; } void toggleSTART() { String msg = String(""); if(start_state) { num_pics=0; // init number of pics. prevShot_ms=millis(); // init current time pics in ms. beginWork_ms=prevShot_ms ; currentShot_ms=0; msg=String("BEGIN-")+String(0)+"HH:"+String(0)+"MM:"+String(0)+"SS"; } else { unsigned long duration=millis()-beginWork_ms ; Serial.println ( duration ) ; int hh=floor( (duration/3600000) ) ; int mm=floor( ((duration-(3600000*hh))/60000) ); int ss=floor( ( (duration-(3600000*hh)-(60000*mm))/1000)) ; beginWork_ms=0; msg=String("END-")+String(hh)+"HH:"+String(mm)+"MM:"+String(ss)+"SS"; } Serial.println ( msg ); //Serial.println ( (start_state==true? "START On":"START Off") ); return ; } void togglePAUSE() { Serial.println ( (pause_state==true? "PAUSE On":"PAUSE Off") ); return ; } void toggleFLASH() { analogWrite(FLASH_PIN, (flash_state==true? MIN_FLASHLEVEL : FLASH_OFFLEVEL) ); delay(STAB_FLASH_DELAY); time_between_pics_revised=time_between_pics-(flash_state==true? time_acquisition_delay+FLASH_DELAY+STAB_FLASH_DELAY+CAM_WRITE_DELAY: time_acquisition_delay+CAM_WRITE_DELAY); Serial.println ( (flash_state==true? "FLASH On":"FLASH Off") ); return ; } void execCommand() { if (inputString==START_STOP) { if(!pause_state) { start_state=!start_state; toggleSTART() ; } else { Serial.println ("Can't START On/Off, System PAUSE ON"); } } else if (inputString==PAUSE_NOPAUSE) { if (start_state) { pause_state=!pause_state; togglePAUSE(); } else { Serial.println ("Can't PAUSE On/Off, System STOPPED"); } } else if (inputString==FLASH_ONOFF) { flash_state=!flash_state ; toggleFLASH(); } else if (inputString.startsWith(CONFIG_MODE)&&inputString.endsWith("}") ) { String is = String(""); int from = inputString.indexOf("{")+1 ; int to = inputString.length()-1; Serial.println ("Enter config mode") ; is=inputString.substring(from, to) ; parseConfig(is) ; } else { String msg ="WARNING: "+inputString+" Unknown command."; Serial.println(msg) ; } inputString=""; stringComplete=false ; return ; } void take_pic() { if(flash_state) { analogWrite(FLASH_PIN, MAX_FLASHLEVEL); delay(STAB_FLASH_DELAY); // on attend la stabilisation de l'eclairage à sa valeur max. } #ifdef USED_BUZZER // start buzzer. analogWrite(BUZZER_PIN, BUZZER_ON); #endif pinMode(CAM_PIN, OUTPUT); digitalWrite(CAM_PIN,LOW); delay(CAM_WRITE_DELAY); //1ms pinMode(CAM_PIN, INPUT); digitalWrite(CAM_PIN,LOW); currentShot_ms=millis(); num_pics++; if(flash_state) { delay(time_acquisition_delay+FLASH_DELAY); // attente de : temps acquisition de la prise de photo+ delais constant de 10ms avant de // couper les LED. analogWrite(FLASH_PIN, MIN_FLASHLEVEL); //Led niveau bas } #ifdef DEBUG_MSG // Serial.print("Pics number [") ; // Serial.print(num_pics) ; // Serial.print("-") ; // Serial.print(lastShot_ms) ; // Serial.println("]") ; #endif #ifdef USED_BUZZER //stop buzzer anogWrite(BUZZER_PIN, BUZZER_OFF); #endif long delta = currentShot_ms-prevShot_ms ; outputString=String(num_pics)+"-"+String(currentShot_ms)+"-"+String(delta) ; Serial.println(outputString) ; outputString=""; prevShot_ms=currentShot_ms; return ; } void setup() { initSerial(); configurePorts(); start_state=false; // stat run, ie take pics pause_state=false; // stat pause, false flash_state=true; // flash activate analogWrite(FLASH_PIN, MIN_FLASHLEVEL); //Led niveau bas return ; } void loop() { if (stringComplete) { execCommand(); } if(!pause_state && start_state) { take_pic(); } delay(time_between_pics_revised) ; // Temps entre deux photos corrigé du temps passé dans la fonction take_pics(). }
C++
CL
1ad35b4f8e4603536350b56d74bce4ff3a751b2cdc8ac32b90f319ec331e8547
// OculusFPS.cpp : Defines the entry point for the application. // #include "framework.h" #include "OculusFPS.h" #include <shellapi.h> #include <stdlib.h> #include <string> #include <time.h> #include "OculusPerfInfo.h" #define MAX_LOADSTRING 100 const int TITLE_HEIGHT = 12; const int DATA_HEIGHT = 72; const int CELL_WIDTH = 100; const int PADDING = 4; const int CLIENT_WIDTH = PADDING * 2 + CELL_WIDTH * 3; const int CLIENT_HEIGHT = PADDING * 3 + TITLE_HEIGHT + DATA_HEIGHT; const COLORREF WINDOW_BACKGROUND = RGB(64, 64, 64); const COLORREF TITLE_COLOR = RGB(148, 148, 148); const COLORREF DATA_COLOR[4] = { RGB(0, 255, 0), RGB(128, 204, 0), RGB(255, 128, 64), RGB(255, 0, 0) }; const COLORREF AWS_LABEL_COLOR = RGB(255, 128, 0); const WCHAR STR_NO_INIT[] = L"Unable to initialize Oculus Library"; const WCHAR STR_NO_HMD[] = L"Headset Inactive"; const WCHAR STR_FPS_TITLE[] = L"FPS"; const WCHAR STR_AWS_IND[] = L"[AWS]"; const WCHAR STR_LATENCY_TITLE[] = L"Latency (ms)"; const WCHAR STR_DROPPED_FRAMES_TITLE[] = L"Dropped frames"; // Global Variables: HINSTANCE _hInst; // current instance WCHAR _szTitle[MAX_LOADSTRING]; // The title bar text WCHAR _szWindowClass[MAX_LOADSTRING]; // the main window class name UINT_PTR _idTimer = 0; HWND _hPerfInfoWnd; OculusPerfInfo* _perfInfoClass; // Command line args bool _fTestMode; // Perf data bool _fPerfInfoInitialized; opi_PerfInfo _perfInfo; // Forward declarations of functions included in this code module: ATOM MyRegisterClass(HINSTANCE hInstance); BOOL InitInstance(HINSTANCE, int); LRESULT CALLBACK WndProc(HWND, UINT, WPARAM, LPARAM); INT_PTR CALLBACK About(HWND, UINT, WPARAM, LPARAM); BOOL InitializeTimer(HWND); void UpdatePerfData(opi_PerfInfo&); void DisplayPerfData(HDC); VOID CALLBACK TimerCallback(HWND, UINT, UINT, DWORD); int APIENTRY wWinMain(_In_ HINSTANCE hInstance, _In_opt_ HINSTANCE hPrevInstance, _In_ LPWSTR lpCmdLine, _In_ int nCmdShow) { UNREFERENCED_PARAMETER(hPrevInstance); LPWSTR* szArglist; int nArgs; szArglist = CommandLineToArgvW(lpCmdLine, &nArgs); if (NULL != szArglist) { for (int i = 0; i < nArgs; i++) { LPWSTR szArg = szArglist[i]; int nArgLen = wcslen(szArg); if (nArgLen > 0) { _wcslwr_s(szArg, nArgLen + 1); if (0 == wcscmp(szArg, L"-d")) { _fTestMode = true; } } } LocalFree(szArglist); } // Initialize global strings LoadStringW(hInstance, IDS_APP_TITLE, _szTitle, MAX_LOADSTRING); LoadStringW(hInstance, IDC_OCULUSFPS, _szWindowClass, MAX_LOADSTRING); MyRegisterClass(hInstance); // Perform application initialization: if (!InitInstance (hInstance, nCmdShow)) { return FALSE; } HACCEL hAccelTable = LoadAccelerators(hInstance, MAKEINTRESOURCE(IDC_OCULUSFPS)); MSG msg; // Main message loop: while (GetMessage(&msg, nullptr, 0, 0)) { if (!TranslateAccelerator(msg.hwnd, hAccelTable, &msg)) { TranslateMessage(&msg); DispatchMessage(&msg); } } delete(_perfInfoClass); return (int) msg.wParam; } // // FUNCTION: MyRegisterClass() // // PURPOSE: Registers the window class. // ATOM MyRegisterClass(HINSTANCE hInstance) { WNDCLASSEXW wcex; wcex.cbSize = sizeof(WNDCLASSEX); wcex.style = CS_HREDRAW | CS_VREDRAW; wcex.lpfnWndProc = WndProc; wcex.cbClsExtra = 0; wcex.cbWndExtra = 0; wcex.hInstance = hInstance; wcex.lpszMenuName = NULL; wcex.hIcon = LoadIcon(hInstance, MAKEINTRESOURCE(IDI_OCULUSFPS)); wcex.hCursor = LoadCursor(nullptr, IDC_ARROW); wcex.hbrBackground = CreateSolidBrush(WINDOW_BACKGROUND); wcex.lpszClassName = _szWindowClass; wcex.hIconSm = LoadIcon(wcex.hInstance, MAKEINTRESOURCE(IDI_OCULUSFPS)); return RegisterClassExW(&wcex); } // // FUNCTION: InitInstance(HINSTANCE, int) // // PURPOSE: Saves instance handle and creates main window // // COMMENTS: // // In this function, we save the instance handle in a global variable and // create and display the main program window. // BOOL InitInstance(HINSTANCE hInstance, int nCmdShow) { _hInst = hInstance; // Store instance handle in our global variable const DWORD dwStyle = WS_DLGFRAME | WS_SYSMENU; RECT rcWindow = { 0, 0, CLIENT_WIDTH, CLIENT_HEIGHT}; AdjustWindowRect(&rcWindow, dwStyle, TRUE); HWND hWnd = CreateWindowW(_szWindowClass, _szTitle, dwStyle, CW_USEDEFAULT, 0, rcWindow.right - rcWindow.left, rcWindow.bottom - rcWindow.top, nullptr, nullptr, hInstance, nullptr); if (!hWnd) { return FALSE; } ShowWindow(hWnd, nCmdShow); UpdateWindow(hWnd); _perfInfoClass = new OculusPerfInfo(); if (!_fTestMode) { _fPerfInfoInitialized = _perfInfoClass->init(); } else { _fPerfInfoInitialized = _perfInfoClass->initTestMode(); } _perfInfoClass->setCallback(UpdatePerfData); return TRUE; } // // FUNCTION: WndProc(HWND, UINT, WPARAM, LPARAM) // // PURPOSE: Processes messages for the main window. // // WM_COMMAND - process the application menu // WM_PAINT - Paint the main window // WM_DESTROY - post a quit message and return // // LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam) { switch (message) { case WM_CREATE: _hPerfInfoWnd = hWnd; break; case WM_COMMAND: { int wmId = LOWORD(wParam); // Parse the menu selections: switch (wmId) { case IDM_ABOUT: DialogBox(_hInst, MAKEINTRESOURCE(IDD_ABOUTBOX), hWnd, About); break; default: return DefWindowProc(hWnd, message, wParam, lParam); } } break; case WM_PAINT: case WM_DISPLAYCHANGE: { PAINTSTRUCT ps; HDC hdc = BeginPaint(hWnd, &ps); DisplayPerfData(hdc); EndPaint(hWnd, &ps); } break; case WM_DESTROY: PostQuitMessage(0); break; default: return DefWindowProc(hWnd, message, wParam, lParam); } return 0; } // Message handler for about box. INT_PTR CALLBACK About(HWND hDlg, UINT message, WPARAM wParam, LPARAM lParam) { UNREFERENCED_PARAMETER(lParam); switch (message) { case WM_INITDIALOG: return (INT_PTR)TRUE; case WM_COMMAND: if (LOWORD(wParam) == IDOK || LOWORD(wParam) == IDCANCEL) { EndDialog(hDlg, LOWORD(wParam)); return (INT_PTR)TRUE; } break; } return (INT_PTR)FALSE; } void UpdatePerfData(opi_PerfInfo& newPerfInfo) { _perfInfo = newPerfInfo; if (_hPerfInfoWnd != NULL) { InvalidateRect(_hPerfInfoWnd, NULL, TRUE); } } void DisplayPerfData(HDC hdc) { HFONT hTitleFont, hDataFont, hOldFont; SetMapMode(hdc, MM_TEXT); // Retrieve a handle to the variable stock font. hTitleFont = CreateFont(TITLE_HEIGHT, 0, 0, 0, FW_DONTCARE, FALSE, FALSE, FALSE, DEFAULT_CHARSET, OUT_OUTLINE_PRECIS, CLIP_DEFAULT_PRECIS, CLEARTYPE_QUALITY, VARIABLE_PITCH, TEXT("Arial")); hDataFont = CreateFont(DATA_HEIGHT, 0, 0, 0, FW_DONTCARE, FALSE, FALSE, FALSE, DEFAULT_CHARSET, OUT_OUTLINE_PRECIS, CLIP_DEFAULT_PRECIS, CLEARTYPE_QUALITY, VARIABLE_PITCH, TEXT("Arial")); // Select the variable stock font into the specified device context. if (hOldFont = (HFONT)SelectObject(hdc, hTitleFont)) { SetTextAlign(hdc, TA_TOP | TA_CENTER); SetTextColor(hdc, TITLE_COLOR); SetBkColor(hdc, WINDOW_BACKGROUND); if (!_fPerfInfoInitialized) { int x = CLIENT_WIDTH / 2; int y = (CLIENT_HEIGHT - TITLE_HEIGHT) / 2; TextOut(hdc, x, y, STR_NO_INIT, wcslen(STR_NO_INIT)); } else if (!_perfInfo.fHeadsetActive) { int x = CLIENT_WIDTH / 2; int y = (CLIENT_HEIGHT - TITLE_HEIGHT) / 2; TextOut(hdc, x, y, STR_NO_HMD, wcslen(STR_NO_HMD)); } else { std::wstring strFps = std::to_wstring(_perfInfo.nAppFps); std::wstring strLatency = std::to_wstring(_perfInfo.nLatencyMs); std::wstring strDroppedFrames = std::to_wstring(_perfInfo.nDroppedFrames); int nOkFps = _perfInfo.fAwsActive ? 30 : 60; int nBadFps = _perfInfo.nMaxAppFps / 2; int iFpsColor = 0, iLatencyColor = 0, iDroppedFramesColor = 0; if (_perfInfo.nAppFps < nBadFps) { iFpsColor = 3; } else if (_perfInfo.nAppFps < nOkFps) { iFpsColor = 2; } else if (_perfInfo.nAppFps < _perfInfo.nMaxAppFps) { iFpsColor = 1; } if (_perfInfo.nLatencyMs > 30) { iLatencyColor = 2; } else if (_perfInfo.nLatencyMs > 60) { iLatencyColor = 3; } if (_perfInfo.nDroppedFrames > 0) { iDroppedFramesColor = 2; } int y = PADDING; int x = PADDING + CELL_WIDTH / 2; // Display the text string. TextOut(hdc, x, y, STR_FPS_TITLE, wcslen(STR_FPS_TITLE)); TextOut(hdc, x + CELL_WIDTH, y, STR_LATENCY_TITLE, wcslen(STR_LATENCY_TITLE)); TextOut(hdc, x + CELL_WIDTH * 2, y, STR_DROPPED_FRAMES_TITLE, wcslen(STR_DROPPED_FRAMES_TITLE)); y += TITLE_HEIGHT; SelectObject(hdc, hDataFont); SetTextColor(hdc, DATA_COLOR[iFpsColor]); TextOut(hdc, x, y, strFps.c_str(), strFps.length()); SetTextColor(hdc, DATA_COLOR[iLatencyColor]); TextOut(hdc, x + CELL_WIDTH, y, strLatency.c_str(), strLatency.length()); SetTextColor(hdc, DATA_COLOR[iDroppedFramesColor]); TextOut(hdc, x + CELL_WIDTH * 2, y, strDroppedFrames.c_str(), strDroppedFrames.length()); if (_perfInfo.fAwsActive) { SetTextAlign(hdc, TA_TOP | TA_LEFT); SelectObject(hdc, hTitleFont); SetTextColor(hdc, WINDOW_BACKGROUND); SetBkColor(hdc, AWS_LABEL_COLOR); TextOut(hdc, PADDING, PADDING, STR_AWS_IND, wcslen(STR_AWS_IND)); } } // Restore the original font. SelectObject(hdc, hOldFont); } }
C++
CL
caa8167a7f61abf58cd16fa194c1e223f0a6a5c51eeaaff6167cbb3d8426c9fe
#include "xbus_wrapper.h" /* shared lib build up */ #ifdef __cplusplus extern "C" { /* char str to long int */ long int dpi_hexstr_2_longint(char* st) { std::stringstream ss; unsigned long x; ss << std::hex << st; ss >> x; return x; } /* longint 2 str */ char* dpi_longint_2_hexstr(long int i){ std::stringstream ss; string x; ss << std::hex << i; ss >> x; return const_cast<char*>(x.c_str()); } /* new XBUS_Transfer */ void* dpi_xbus_new_xbus_transfer() { XBUS_Transfer* tt = new XBUS_Transfer(); assert(tt!=NULL && "UVM_ERROR: DPI_XBUS, new XBUS_Transfer fail"); return reinterpret_cast<void*>(tt); } /* new XBUS_MailBox */ void* dpi_xbus_new_xbus_maxbusox(char* inst_name) { XBUS_MailBox* ft = new XBUS_MailBox(inst_name); assert(ft!=NULL && "UVM_ERROR: DPI_XBUS, new XBUS_MailBox fail"); return reinterpret_cast<void*>(ft); } /* set begin time */ void dpi_xbus_set_xbus_transfer_begin_time(void* ip, char* begin_time) { XBUS_Transfer* tt = reinterpret_cast<XBUS_Transfer*>(ip); assert(tt!=NULL && "UVM_ERROR: DPI_XBUS, set XBUS_Transfer begin_time fail"); tt->begin_time = dpi_hexstr_2_longint(begin_time); } /* get begin time */ char* dpi_xbus_get_xbus_transfer_begin_time(void* ip) { XBUS_Transfer* tt = reinterpret_cast<XBUS_Transfer*>(ip); assert(tt!=NULL && "UVM_ERROR: DPI_XBUS, get XBUS_Transfer begin_time fail"); return dpi_longint_2_hexstr(tt->begin_time); } /* set end time */ void dpi_xbus_set_xbus_transfer_end_time(void* ip, char* end_time) { XBUS_Transfer* tt = reinterpret_cast<XBUS_Transfer*>(ip); assert(tt!=NULL && "UVM_ERROR: DPI_XBUS, set XBUS_Transfer end_time fail"); tt->end_time = dpi_hexstr_2_longint(end_time); } /* get end time */ char* dpi_xbus_get_xbus_transfer_end_time(void* ip) { XBUS_Transfer* tt = reinterpret_cast<XBUS_Transfer*>(ip); assert(tt!=NULL && "UVM_ERRORL DPI_XBUS, get_XBUS_Transfer end time fail"); return dpi_longint_2_hexstr(tt->end_time); } /* set begin_cycle */ void dpi_xbus_set_xbus_transfer_begin_cycle(void* ip, char* begin_cycle) { XBUS_Transfer* tt = reinterpret_cast<XBUS_Transfer*>(ip); assert(tt!=NULL && "UVM_ERROR DPI_XBUS, set_XBUS_Transfer begin cycle fail"); tt->begin_cycle = dpi_hexstr_2_longint(begin_cycle); } /* get begin cycle */ char* dpi_xbus_get_xbus_transfer_begin_cycle(void* ip) { XBUS_Transfer* tt = reinterpret_cast<XBUS_Transfer*>(ip); assert(tt!=NULL && "UVM_ERROR DPI_XBUS, get_XBUS_Transfer begin cycle fail"); return dpi_longint_2_hexstr(tt->begin_cycle); } /* set end_cycle */ void dpi_xbus_set_xbus_transfer_end_cycle(void* ip, char* end_cycle) { XBUS_Transfer* tt = reinterpret_cast<XBUS_Transfer*>(ip); assert(tt!=NULL && "UVM_ERROR DPI_XBUS, set_XBUS_Transfer end cycle fail"); tt->end_cycle = dpi_hexstr_2_longint(end_cycle); } /* get end cycle */ char* dpi_xbus_get_xbus_transfer_end_cycle(void* ip) { XBUS_Transfer* tt = reinterpret_cast<XBUS_Transfer*>(ip); assert(tt!=NULL && "UVM_ERROR DPI_XBUS, get_XBUS_Transfer end cycle fail"); return dpi_longint_2_hexstr(tt->end_cycle); } /* set rw */ void dpi_xbus_set_xbus_transfer_rw(void* ip, char* rw) { XBUS_Transfer* tt = reinterpret_cast<XBUS_Transfer*>(ip); assert(tt!=NULL && "UVM_ERROR DPI_XBUS, set_XBUS_Transfer rw fail"); tt->rw = rw; } /* get rw */ char* dpi_xbus_get_xbus_transfer_rw(void* ip) { XBUS_Transfer* tt = reinterpret_cast<XBUS_Transfer*>(ip); assert(tt!=NULL && "UVM_ERROR DPI_XBUS, get_XBUS_Transfer rw fail"); char *cstr = new char[tt->rw.length() + 1]; strcpy(cstr, tt->rw.c_str()); return cstr; } /* set addr */ void dpi_xbus_set_xbus_transfer_addr(void* ip, char* addr) { XBUS_Transfer* tt = reinterpret_cast<XBUS_Transfer*>(ip); assert(tt!=NULL && "UVM_ERROR DPI_XBUS, set_XBUS_Transfer addr fail"); tt->addr = dpi_hexstr_2_longint(addr); } /* get addr */ char* dpi_xbus_get_xbus_transfer_addr(void* ip) { XBUS_Transfer* tt = reinterpret_cast<XBUS_Transfer*>(ip); assert(tt!=NULL && "UVM_ERROR DPI_XBUS, get_XBUS_Transfer addr fail"); return dpi_longint_2_hexstr(tt->addr); } /* set data */ void dpi_xbus_set_xbus_transfer_data(void* ip, char* data) { XBUS_Transfer* tt = reinterpret_cast<XBUS_Transfer*>(ip); assert(tt!=NULL && "UVM_ERROR DPI_XBUS, set_XBUS_Transfer data fail"); tt->data = dpi_hexstr_2_longint(data); } /* get data */ char* dpi_xbus_get_xbus_transfer_data(void* ip) { XBUS_Transfer* tt = reinterpret_cast<XBUS_Transfer*>(ip); assert(tt!=NULL && "UVM_ERROR DPI_XBUS, get_XBUS_Transfer data fail"); return dpi_longint_2_hexstr(tt->data); } /* set byten */ void dpi_xbus_set_xbus_transfer_byten(void* ip, char* data) { XBUS_Transfer* tt = reinterpret_cast<XBUS_Transfer*>(ip); assert(tt!=NULL && "UVM_ERROR DPI_XBUS, set_XBUS_Transfer byten fail"); tt->byten = dpi_hexstr_2_longint(data); } /* get byten */ char* dpi_xbus_get_xbus_transfer_byten(void* ip) { XBUS_Transfer* tt = reinterpret_cast<XBUS_Transfer*>(ip); assert(tt!=NULL && "UVM_ERROR DPI_XBUS, get_XBUS_Transfer byten fail"); return dpi_longint_2_hexstr(tt->byten); } /* dpi register xbus transfer 2 xbus maxbusox */ void dpi_xbus_register_xbus_transfer(void* it, void* ip) { XBUS_Transfer* tt = reinterpret_cast<XBUS_Transfer*>(ip); XBUS_MailBox* ft = reinterpret_cast<XBUS_MailBox*>(it); assert(tt!=NULL && ft!=NULL && "UVM_ERROR: DPI_XBUS, register XBUS_Transfer is fail"); ft->push(tt); } /* dpi get xbus_transfer if the maxbusox queue is not empty */ void* dpi_xbus_next_xbus_transfer(void* it) { XBUS_MailBox* ft = reinterpret_cast<XBUS_MailBox*>(it); assert(ft!=NULL && "UVM_ERROR: DPI_XBUS, next XBUS_Transfer is fial"); XBUS_Transfer* tt = ft->next(); return reinterpret_cast<void*>(tt); } } #endif
C++
CL
576b799c3dd970dbb8dd077189a19259ccc4bde2fd2e34e972b3e5dc77be8ec8
#pragma once /* Contains classes that deal with geometry */ #include <initializer_list> #include <algorithm> // std::min(), std::max() #include <cstdlib> // abs(), rand() #include "vector2.hpp" // 'Vector2d' type used in 'dRect' template<typename T> constexpr int sign(T val) { // standard 'sign()' function (x<0 => -1, x==0 => 0, x>0 => 1) return (T(0) < val) - (val < T(0)); } // # Side # // - Represents sides of a rectangle and directions enum class Side { NONE = 0, LEFT = 1, RIGHT = 2, TOP = 3, BOTTOM = 4 }; constexpr int sign(Side side) { switch (side) { case Side::LEFT: return -1; case Side::RIGHT: return 1; case Side::TOP: return -1; case Side::BOTTOM: return 1; default: return 0; } } constexpr Side invert(Side side) { switch (side) { case Side::LEFT: return Side::RIGHT; case Side::RIGHT: return Side::LEFT; case Side::TOP: return Side::BOTTOM; case Side::BOTTOM: return Side::TOP; default: return Side::NONE; } } // # Orientation # // - Like side but only LEFT/RIGHT // - Mostly used by creatures enum class Orientation { LEFT = -1, RIGHT = 1 }; constexpr int sign(Orientation orientation) { return static_cast<int>(orientation); } constexpr Orientation invert(Orientation orientation) { return static_cast<Orientation>(-static_cast<int>(orientation)); } // # srcRect # // - Rect with int dimensions, used as a source rect when handling texture sheets struct srcRect { int x, y; int w, h; }; constexpr srcRect make_srcRect(const Vector2 &point, const Vector2 &size, bool initializeAsCentered = false) { if (initializeAsCentered) { return srcRect{ point.x - size.x / 2, point.y - size.y / 2, size.x, size.y }; } else { return srcRect{ point.x, point.y, size.x, size.y }; } } constexpr srcRect make_srcRect(int x, int y, int width, int height, bool initializeAsCentered = false) { if (initializeAsCentered) { return srcRect{ x - width / 2, y - height / 2, width, height }; } else { return srcRect{ x, y, width, height }; } } // # dstRect # // - Rect with double dimensions, used during rendering to allow proper texture scaling struct dstRect { double x, y; double w, h; constexpr bool containsPoint(const Vector2d &point) { return (this->x < point.x&& point.x < this->x + this->w) && (this->y < point.y&& point.y < this->y + this->h); } }; constexpr dstRect make_dstRect(const Vector2d &point, const Vector2d &size, bool initializeAsCentered = false) { if (initializeAsCentered) { return dstRect{ point.x - size.x / 2, point.y - size.y / 2, size.x, size.y }; } else { return dstRect{ point.x, point.y, size.x, size.y }; } } constexpr dstRect make_dstRect(double x, double y, double width, double height, bool initializeAsCentered = false) { if (initializeAsCentered) { return dstRect{ x - width / 2, y - height / 2, width, height }; } else { return dstRect{ x, y, width, height }; } } // helpers:: // - Small helper functions namespace helpers { constexpr int roundUp32(int val) { // round value UP to a multiple of 32 constexpr int POWER_OF_TWO = 32; return (val + POWER_OF_TWO - 1) & -POWER_OF_TWO; // bithacks allow ~4X faster rounding for powers of 2 } // Methods for getting cell index from position constexpr Vector2 divide32(const Vector2d &position) { return (position / 32.).toVector2(); // returns floor(position / 32) } constexpr Vector2 divide32(const Vector2 &position) { return position / 32; } constexpr int divide32(double value) { return static_cast<int>(value / 32.); // sometimes we only need 1 coordinate } } // # dRect # // - Represents 'float' rectangle // - Used for physics, hitboxes, etc class dRect { public: constexpr dRect() = default; // inits point1 and point2 as (0, 0) constexpr dRect(const Vector2d &point, const Vector2d &size, bool initializeAsCentered = false) { // 'point' is either a top left corner or a center depending on 'initializeAsCentered' value if (initializeAsCentered) { this->point1 = point - size / 2.; this->point2 = point + size / 2.; } else { this->point1 = point; this->point2 = point + size; } } constexpr dRect(double pointX, double pointY, double sizeX, double sizeY, bool initializeAsCentered = false) : dRect(Vector2d(pointX, pointY), Vector2d(sizeX, sizeY), initializeAsCentered) {} // Move methods constexpr dRect& moveCornerTo(const Vector2d &newPoint1) { // moves 'point1' (top-left corner) TO the 'newPoint1' without changing size const auto size = this->getSize(); this->point1 = newPoint1; this->point2 = newPoint1 + size; return *this; } constexpr dRect& moveCornerTo(double newPoint1X, double newPoint1Y) { return this->moveCornerTo(Vector2d(newPoint1X, newPoint1Y)); } constexpr dRect& moveCenterTo(const Vector2d &newCenter) { // move center point TO the 'newCenter' without changing dimensions const auto size = this->getSize(); this->point1 = newCenter - size / 2.; this->point2 = newCenter + size / 2.; return *this; } constexpr dRect& moveCenterTo(double newCenterX, double newCenterY) { return this->moveCenterTo(Vector2d(newCenterX, newCenterY)); } constexpr dRect& moveBy(const Vector2d &movement) { // move rectangle point BY <movement> without changing dimensions this->point1 += movement; this->point2 += movement; return *this; } constexpr dRect& moveBy(double movementX, double movementY) { this->point1.x += movementX; this->point2.x += movementX; this->point1.y += movementY; this->point2.y += movementY; return *this; } constexpr dRect& moveByX(double movementX) { this->point1.x += movementX; this->point2.x += movementX; return *this; } constexpr dRect& moveByY(double movementY) { this->point1.y += movementY; this->point2.y += movementY; return *this; } constexpr dRect& moveSideTo(Side side, double newValue) { // move rectangle side to the 'newValue' without changing dimensions const auto size = this->getSize(); switch (side) { case Side::LEFT: this->point1.x = newValue; this->point2.x = newValue + size.x; break; case Side::RIGHT: this->point2.x = newValue; this->point1.x = newValue - size.x; break; case Side::TOP: this->point1.y = newValue; this->point2.y = newValue + size.y; break; case Side::BOTTOM: this->point2.y = newValue; this->point1.y = newValue - size.y; break; case Side::NONE: break; } return *this; } constexpr dRect& moveLeftTo(double newValue) { const auto sizeX = this->getSizeX(); this->point1.x = newValue; this->point2.x = newValue + sizeX; return *this; } constexpr dRect& moveRightTo(double newValue) { const auto sizeX = this->getSizeX(); this->point1.x = newValue - sizeX; this->point2.x = newValue; return *this; } constexpr dRect& moveTopTo(double newValue) { const auto sizeY = this->getSizeY(); this->point1.y = newValue; this->point2.y = newValue + sizeY; return *this; } constexpr dRect& moveBottomTo(double newValue) { const auto sizeY = this->getSizeY(); this->point1.y = newValue - sizeY; this->point2.y = newValue; return *this; } // Scale methods constexpr dRect& scaleInPlaceTo(const Vector2d &newSize) { // set new size without changing center position const auto center = this->getCenter(); *this = dRect(center, newSize, true); return *this; } constexpr dRect& scaleInPlaceBy(double scale) { // scale rectangle without changing center position const auto center = this->getCenter(); const auto size = this->getSize(); *this = dRect(center, size * scale, true); return *this; } // Corner getters constexpr Vector2d getCornerTopLeft() const { return this->point1; } constexpr Vector2d getCornerTopRight() const { return Vector2d(this->point2.x, this->point1.y); } constexpr Vector2d getCornerBottomLeft() const { return Vector2d(this->point1.x, this->point2.y); } constexpr Vector2d getCornerBottomRight() const { return this->point2; } // Center getters constexpr Vector2d getCenter() const { return (this->point1 + this->point2) / 2.; } constexpr double getCenterX() const { return (this->point1.x + this->point2.x) / 2.; } constexpr double getCenterY() const { return (this->point1.y + this->point2.y) / 2.; } // Size getters constexpr Vector2d getSize() const { return this->point2 - this->point1; } constexpr double getSizeX() const { return this->point2.x - this->point1.x; } constexpr double getSizeY() const { return this->point2.y - this->point1.y; } // Side getters constexpr double getSide(Side side) const { switch (side) { case Side::BOTTOM: return this->point2.y; case Side::TOP: return this->point1.y; case Side::LEFT: return this->point1.x; case Side::RIGHT: return this->point2.x; default: return -1.; } } constexpr double getLeft() const { return this->point1.x; } constexpr double getRight() const { return this->point2.x; } constexpr double getTop() const { return this->point1.y; } constexpr double getBottom() const { return this->point2.y; } // Side middlepoint getters constexpr Vector2d getSideMiddlepoint(Side side) const { switch (side) { case Side::LEFT: return this->getLeftMiddlepoint(); case Side::RIGHT: return this->getRightMiddlepoint(); case Side::TOP: return this->getTopMiddlepoint(); case Side::BOTTOM: return this->getBottomMiddlepoint(); default: return Vector2(); } } constexpr Vector2d getLeftMiddlepoint() const { return Vector2d(this->point1.x, (this->point1.y + this->point2.y) / 2.); } constexpr Vector2d getRightMiddlepoint() const { return Vector2d(this->point2.x, (this->point1.y + this->point2.y) / 2.); } constexpr Vector2d getTopMiddlepoint() const { return Vector2d((this->point1.x + this->point2.x) / 2., this->point1.y); } constexpr Vector2d getBottomMiddlepoint() const { return Vector2d((this->point1.x + this->point2.x) / 2., this->point2.y); } // Intersection methods struct CollisionInfo { double overlap_x; double overlap_y; double overlap_area; // == 0 => rects don't collide }; constexpr CollisionInfo collideWithRect(const dRect &other) const { const double overlapX = std::max( 0., std::min(this->point2.x, other.point2.x) - std::max(this->point1.x, other.point1.x) ); const double overlapY = std::max( 0., std::min(this->point2.y, other.point2.y) - std::max(this->point1.y, other.point1.y) ); return dRect::CollisionInfo{ overlapX, overlapY, overlapX * overlapY }; // provides collision info for 2 rects } constexpr bool overlapsWithRect(const dRect &other) const { // faster than colliding but only gives bool result return !(other.point1.x >= this->point2.x || this->point1.x >= other.point2.x || this->point1.y >= other.point2.y || other.point1.y >= this->point2.y); // true if intersection is impossible => invert it to get the result } constexpr bool containsPoint(const Vector2d &point) const { return (this->getLeft() < point.x) && (this->getRight() > point.x) && (this->getTop() < point.y) && (this->getBottom() > point.y); } // Convertions constexpr dstRect to_dstRect() const { return dstRect{ this->point1.x, this->point1.y, this->getSizeX(), this->getSizeY() }; } private: Vector2d point1; // top-left corner Vector2d point2; // bottom-right corner }; // Random functions bool rand_bool(); int rand_int(int min, int max); // random int in [min, max] range double rand_double(); // random double in (0, 1] range double rand_double(double min, double max); // random double in (min, max] range template<class T> T rand_linear_combination(const T& A, const T& B) { // random linear combination of 2 colors/vectors/etc const auto coef = rand_double(); return A * coef + B * (1. - coef); } template<class T> const T& rand_choise(std::initializer_list<T> objects) { return objects.begin()[rand_int(0, objects.size() - 1)]; }
C++
CL
af5d3cca489f8388cd0c26a11b0850d5fc1df706b3d717544534f181c477dfe7
// // Created by y on 1/3/21. // #ifndef UDACITYCAPSTONE_AES256_AES256_H #define UDACITYCAPSTONE_AES256_AES256_H #include <vector> #include<cstdint> #include "lookup_tables.h" #include "cli.h" #include <memory> #define KEY_SIZE 32 #define BLOCK_SIZE 16 #define NUMBER_OF_ROUNDS 14 #define STATE_SIZE [4][4] #define STATE_ROW_SIZE 4 #define STATE_COLUMN_SIZE 4 #define WORD_SIZE 4 #define NUMBER_OF_ROUNDS_KEYS 15 #endif //UDACITYCAPSTONE_AES256_AES256_H class AES256 { public: void Encrypt(const ByteAVector &plain, const ByteAVector &key_in, ByteAVector &cipher); void Decrypt(const ByteAVector &cipher, const ByteAVector &key_in, ByteAVector &plain); private: unsigned char state STATE_SIZE; unsigned char key STATE_SIZE; unsigned char round_key[NUMBER_OF_ROUNDS_KEYS][BLOCK_SIZE]; void State(const ByteAVector &input, unsigned char out STATE_SIZE); void KeyState(int round); void SubBytes(); void ShiftRows(); void MixColumns(); void MixMul(unsigned char state_column[WORD_SIZE][1], int column); void AddRoundKey(); void InvSubBytes(); void InvShiftRows(); void InvMixColumns(); void InvMixMul(unsigned char state_column[WORD_SIZE][1], int column); void KeyExpansion(const ByteAVector &key_in); void WordKeyExpansion(unsigned char temp_word[WORD_SIZE], int round); void RotWord(unsigned char temp_word[WORD_SIZE], int round); void SubWord(unsigned char temp_word[WORD_SIZE], int round); void Rcon(unsigned char temp_word[WORD_SIZE], int round); void PrintState(); void State2Block(ByteAVector &block); };
C++
CL
92cd495c0c271d82e791b995ba3ae7b9d734c360587ef877a642ce17f2aa9035
#include "engine.h" #include <glm/gtc/matrix_transform.hpp> #include <glad/glad.h> #include <GLFW/glfw3.h> #include <iostream> #include <random> #include <thread> #include <strstream> #include <iomanip> ButtonEvent makeButtonEventFromGLFWkeypress(int key, int action, int mods) { return { {keyboard, key}, action, bool( mods & GLFW_MOD_SHIFT), bool(mods & GLFW_MOD_CONTROL), bool(mods & GLFW_MOD_ALT) }; } ButtonEvent makeButtonEventFromGLFWmousepress(int key, int action, int mods) { return { {mouseButton, key}, action, bool(mods & GLFW_MOD_SHIFT), bool(mods & GLFW_MOD_CONTROL), bool(mods & GLFW_MOD_ALT) }; } // Called by glfw api when a key is pressed. Adds input to a queue which is consumed on engine update void keyActionCallback(GLFWwindow* window, int key, int scancode, int action, int mods) { Engine* engine = static_cast<Engine*>(glfwGetWindowUserPointer(window)); ButtonInputSystem& buttonInputSystem = ( engine )->buttonInputSystem; buttonInputSystem.pushButtonAction(makeButtonEventFromGLFWkeypress(key, action, mods)); engine->keyMap[key].store(action); } void mouseButtonActionCallback(GLFWwindow* window, int key, int action, int mods) { ButtonInputSystem& buttonInputSystem = (static_cast<Engine*>(glfwGetWindowUserPointer(window)))->buttonInputSystem; buttonInputSystem.pushButtonAction(makeButtonEventFromGLFWmousepress(key, action, mods)); } void framebufferSizeCallback(GLFWwindow* window, int width, int height) { GraphicsSystem& graphicsSystem = (static_cast<Engine*>(glfwGetWindowUserPointer(window)))->graphicsSystem; graphicsSystem.resolution = glm::uvec2(width, height); graphicsSystem.camera.aspectRatio = double(width) / double(height); graphicsSystem.onResizeFramebuffer(); //glViewport(0, 0, width, height); } void updateForever(Engine* engine) { double timeStamp=0.; double timeAcumulator = 0; // engine->physicsTimestep; double dt = 0; while (true) { timeAcumulator += dt; timeStamp = glfwGetTime(); timeAcumulator -= engine->physicsTimestep; engine->update(); while ((dt = glfwGetTime() - timeStamp) - timeAcumulator < engine->physicsTimestep); // spin until physics timestep has passed } } WindowWrapper::WindowWrapper(unsigned int winWidth, unsigned int winHeight) { glfwInit(); glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 4); glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 6); glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE); //glfwWindowHint(GLFW_SAMPLES, 8); window = glfwCreateWindow(winWidth, winHeight, "Game engine test", NULL, NULL); if (window == NULL) { std::cerr << "Failed to create GLFW window" << std::endl; glfwTerminate(); } glfwMakeContextCurrent(window); if (!gladLoadGLLoader((GLADloadproc)glfwGetProcAddress)) { std::cerr << "Failed to initialize GLAD" << std::endl; glfwTerminate(); } } // Creates OpenGL context, registers callback functions, and calls each system's constructor Engine::Engine(unsigned int winWidth, unsigned int winHeight) : windowWrapper(winWidth, winHeight) { windowWrapper.window; glEnable(GL_DEPTH_TEST); glViewport(0, 0, winWidth, winHeight); glfwSetWindowUserPointer(windowWrapper.window, this); glfwSetKeyCallback(windowWrapper.window, keyActionCallback); glfwSetMouseButtonCallback(windowWrapper.window, mouseButtonActionCallback); glfwSetFramebufferSizeCallback(windowWrapper.window, framebufferSizeCallback); // graphics system // load resources // TODO: initialize systems graphicsSystem.camera.position = glm::vec3(0., 0., 14.); graphicsSystem.camera.lookAt (glm::vec3(0)); framebufferSizeCallback(windowWrapper.window, winWidth, winHeight); glfwSetTime(0.); } Engine::~Engine() { glfwTerminate(); } // runs on secondary thread void Engine::update() { double newTime = glfwGetTime(); double dt = newTime - lastUpdateTime; lastUpdateTime = newTime; glm::dvec2 newMousePos; glfwGetCursorPos(windowWrapper.window, &(newMousePos.x), &(newMousePos.y)); newMousePos.x *= 2. / graphicsSystem.resolution.x; newMousePos.x -= 1.; newMousePos.y *= -2. / graphicsSystem.resolution.y; newMousePos.y += 1.; glm::dvec2 deltaMouse = newMousePos - lastMousePos; lastMousePos = newMousePos; // debug #ifdef DEBUG_CAMERA graphicsSystem.camera.rotate(-1 * 2 * deltaMouse.x, 2* deltaMouse.y); if (checkButtonState( KEY_RIGHT )) { graphicsSystem.camera.walk(glm::vec3(10, 0, 0) * float(dt)); } if (checkButtonState(KEY_LEFT)) { graphicsSystem.camera.walk(glm::vec3(-10, 0, 0) * float(dt)); } if (checkButtonState(KEY_UP)) { graphicsSystem.camera.walk(glm::vec3(0, 0, 20) * float(dt)); } if (checkButtonState(KEY_DOWN)) { graphicsSystem.camera.walk(glm::vec3(0, 0, -10) * float(dt)); } if (checkButtonState(KEY_PAGE_UP)) { graphicsSystem.camera.walk(glm::vec3(0, 10, 0) * float(dt)); } if (checkButtonState(KEY_PAGE_DOWN)) { graphicsSystem.camera.walk(glm::vec3(0, -10, 0) * float(dt)); } #endif if (dt > physicsTimestep) { dt = physicsTimestep; } // makes sure that the main thread isnt deleting entities std::lock_guard guard(entityDeletionMutex); buttonInputSystem.update(*this, dt); physicsSystem.update(*this, dt); fighterSystem.update(*this, dt); healthSystem.update(*this, dt); } // must run on main thread void Engine::draw() { // locks physics thread while entities are deleted if (!destructionQueue.empty()) { std::lock_guard guard(entityDeletionMutex); while (!destructionQueue.empty()) { destroyEntity(destructionQueue.front()); destructionQueue.pop(); } } double newTime = glfwGetTime(); double dt = newTime - lastDrawTime; lastDrawTime = newTime; fpsCounter.update(newTime); std::stringstream titleStream; titleStream << "Engine - FPS: " << std::fixed << std::setprecision(2) << fpsCounter.getFPS(); glfwSetWindowTitle(windowWrapper.window, (titleStream.str()).c_str()); graphicsSystem.draw(*this, dt); } void Engine::doLoopForever() { glfwSetTime(0.); lastUpdateTime = 0.; lastDrawTime = 0.; std::thread updateThread(updateForever, this); // launches physics / game logic thread while (true) { //update(); draw(); glfwSwapBuffers(windowWrapper.window); updateJoySticks(); glfwPollEvents(); } } void Engine::updateJoySticks() { GLFWgamepadstate state; if (glfwJoystickIsGamepad(GLFW_JOYSTICK_1) && glfwGetGamepadState(GLFW_JOYSTICK_1, &state)) { for (int i = 0; i < LAST_GAMEPAD; ++i) { int buttonState = state.buttons[i]; if (gamepad1Map[i] != buttonState) { gamepad1Map[i] = buttonState; buttonInputSystem.pushButtonAction(ButtonEvent{ Button(gamepad1, i), buttonState, false, false, false }); } } } } double Engine::getTime() { return glfwGetTime(); } bool Engine::checkButtonState(Button button) { if (button.inputType == keyboard) { if (button.key > LAST_KEY) return false; return keyMap[button.key].load(); } else if (button.inputType == gamepad1) { if (button.key > LAST_GAMEPAD) return false; return gamepad1Map[button.key].load(); } return false; } Entity& Engine::makeEntity(unsigned int catagories) { Entity newentity; newentity.catagory = catagories; handle<Entity> ID = entities.add(std::move(newentity)); return *entities.find(ID); } void Engine::destroyEntity(handle<Entity> ID) { Entity* entityptr = getEntity(ID); if (entityptr) { auto& entity = *entityptr; if (entity.constraintHandle != INVALID_HANDLE) { destroyComponent(entity.constraintHandle); entity.constraintHandle = handle<ConstraintComponent>(INVALID_HANDLE); } if (entity.physicsHandle != INVALID_HANDLE) { destroyComponent(entity.physicsHandle); entity.physicsHandle = handle<PhysicsComponent>(INVALID_HANDLE); } if (entity.spriteHandle != INVALID_HANDLE) { destroyComponent(entity.spriteHandle); entity.spriteHandle = handle<SpriteComponent>(INVALID_HANDLE); } if (entity.lightHandle != INVALID_HANDLE) { destroyComponent(entity.lightHandle); entity.lightHandle = handle<LightComponent>(INVALID_HANDLE); } if (entity.modelHandle != INVALID_HANDLE) { destroyComponent(entity.modelHandle); entity.modelHandle = handle<ModelComponent>(INVALID_HANDLE); } if (entity.healthHandle != INVALID_HANDLE) { destroyComponent(entity.healthHandle); entity.healthHandle = handle<HealthComponent>(INVALID_HANDLE); } if (entity.damageHandle != INVALID_HANDLE) { destroyComponent(entity.damageHandle); entity.damageHandle = handle<DamageComponent>(INVALID_HANDLE); } if (entity.fighterHandle != INVALID_HANDLE) { destroyComponent(entity.fighterHandle); entity.fighterHandle = handle<FighterComponent>(INVALID_HANDLE); } entities.remove(ID); } }
C++
CL
7ed746594195089aa335280b84532a6d9439f34bf16d6f721aa9e7d1f8517b8a
#ifndef OIL_OILLOOP_H #define OIL_OILLOOP_H #include <OIL/IOilStatement.h> #include <OIL/IOilLoop.h> #include <string> #include <Tokenization/SourceRef.h> class OilStatementBody; class OilLoop : public virtual IOilStatement, public virtual IOilLoop { public: OilLoop ( const SourceRef & Ref, OilStatementBody * StatementBody ); OilLoop ( const SourceRef & Ref, OilStatementBody * StatementBody, const std :: u32string & LoopLabel ); ~OilLoop (); bool HasLoopLabel () const; const std :: u32string & GetLoopLabel () const; const OilStatementBody * GetStatementBody () const; OilStatementBody * GetStatementBody (); StatementType GetStatementType () const; const SourceRef & GetSourceRef () const; private: OilStatementBody * StatementBody; const std :: u32string LoopLabel; SourceRef Ref; }; #endif
C++
CL
f45d7f2f18529e137d89da296e79daf2105183133658e2d349f765040e4b4c7c
//----------------------------------------------------------------------------- // File: HStackedLayout.h //----------------------------------------------------------------------------- // Project: Kactus 2 // Author: Joni-Matti Määttä // Date: 22.4.2011 // // Description: // Horizontal stacked layout. //----------------------------------------------------------------------------- #ifndef HSTACKEDLAYOUT_H #define HSTACKEDLAYOUT_H #include "IHGraphicsLayout.h" #include <designEditors/common/DiagramUtil.h> //----------------------------------------------------------------------------- //! Horizontal stacked layout. //----------------------------------------------------------------------------- template <class T> class HStackedLayout : public IHGraphicsLayout<T> { public: /*! * Constructor. * * @param [in] spacing The spacing. */ HStackedLayout(qreal spacing); /*! * Destructor. */ ~HStackedLayout(); /*! * Updates the horizontal stacking of the items when one item is being moved. * * @param [in] items The list of items. * @param [in] item The item that is being moved. * @param [in] minX The minimum x coordinate. * * @remarks The list of items is assumed to initially have correct left-right ordering and * positioning. */ void updateItemMove(QList<T*>& items, T* item, qreal minX = 0.0); /*! * Sets the position of an item based on its index in the list using horizontal stacking. * * @param [in] items The list of items. Assumed to be already in correct order. * @param [in] item The item to position. * @param [in] y The y coordinate for the item's position. * @param [in] minX The minimum x coordinate. */ void setItemPos(QList<T*> const& items, T* item, qreal y, qreal minX = 0.0); /*! * Updates the positions of all items using horizontal stacking. * * @param [in] items The list of items. * @param [in] x The y coordinate for the items. * @param [in] minX The minimum x coordinate. */ void updateItemPositions(QList<T*>& items, qreal y, qreal minX = 0.0); private: //----------------------------------------------------------------------------- // Data. //----------------------------------------------------------------------------- //! The spacing between items. qreal spacing_; }; //----------------------------------------------------------------------------- #include "HStackedLayout.inl" #endif // HSTACKEDLAYOUT_H
C++
CL
70fe5cbec8984ddce9026eac6c6d9f5e6ae7c3cc1e7787f9340341482a77bb42
#include "CEntity.h" #include "CPlayer.h" #include "CCycler_Fix.h" // memdbgon must be the last include file in a .cpp file!!! #include "tier0/memdbgon.h" abstract_class CE_Temp_NPC : public CE_Cycler_Fix { public: CE_DECLARE_CLASS(CE_Temp_NPC, CE_Cycler_Fix); virtual void Spawn() { Precache(); BaseClass::Spawn(); SetModel(STRING(GetModelName())); SetHullType(HULL_HUMAN); SetHullSizeNormal(); SetSolid( SOLID_BBOX ); AddSolidFlags( FSOLID_NOT_STANDABLE ); SetMoveType( MOVETYPE_STEP ); SetBloodColor( DONT_BLEED ); m_NPCState = NPC_STATE_NONE; SetImpactEnergyScale( 0.0f ); CapabilitiesClear(); NPCInit(); } virtual Class_T Classify ( void ) { return CLASS_PLAYER_ALLY_VITAL; } virtual int OnTakeDamage(const CTakeDamageInfo& info) { return 0; } virtual float MaxYawSpeed( void ) { return 0.0f; } virtual bool CanBeAnEnemyOf( CBaseEntity *pEnemy ) { return false; } };
C++
CL
7b3fbd77d4ad9eeb3ef84d474df6dd542b170eb324b22faada015de847f5df66
#include "auv_guidance/test_node.hpp" int main(int argc, char **argv) { ros::init(argc, argv, "pose_edkf"); auv_guidance::TestNode testNode; ros::spin(); } namespace auv_guidance { TestNode::TestNode() : nh("~") { // Ceres stuff min jerk time solver ///////////////////// ceres::Problem problemMinJerkTime_; ceres::Solver::Options optionsMinJerkTime_; ceres::Solver::Summary summaryMinJerkTime_; double x0, v0, a0, j0, xf, vf, af, jf; nh.getParam("x0", x0); nh.getParam("v0", v0); nh.getParam("a0", a0); nh.getParam("j0", j0); nh.getParam("xf", xf); nh.getParam("vf", vf); nh.getParam("af", af); nh.getParam("jf", jf); Eigen::Vector4d start = Eigen::Vector4d::Zero(); Eigen::Vector4d end = Eigen::Vector4d::Zero(); start(0) = x0; start(1) = v0; start(2) = a0; start(3) = j0; end(0) = xf; end(1) = vf; end(2) = af; end(3) = jf; double minTime_ = 0; problemMinJerkTime_.AddResidualBlock(new ceres::AutoDiffCostFunction<MonotonicTrajectoryTimeSolver, 1, 1>(new MonotonicTrajectoryTimeSolver(start, end)), NULL, &minTime_); problemMinJerkTime_.SetParameterLowerBound(&minTime_, 0, 0.0); optionsMinJerkTime_.max_num_iterations = 100; optionsMinJerkTime_.linear_solver_type = ceres::DENSE_QR; ceres::Solve(optionsMinJerkTime_, &problemMinJerkTime_, &summaryMinJerkTime_); cout << "Min Jerk time: " << minTime_ << endl; } } // namespace auv_guidance
C++
CL
0b8c524d9379305aafc3864762c83d7b5a2fbfc2ab3a0b8f70dc94e1b344dc5e
#ifdef _MSC_VER #include <windows.h> #include <tchar.h> #ifdef UNICODE #define _tcscpy wcscpy #define _tcslen wcslen #define _tcscat wcscat #else #define _tcscpy strcpy #define _tcslen strlen #define _tcscat strcat #endif // 获取系统实际支持的指令集: // 使用FMA/AVX参数依次运行runtime_check.exe, 若输出中包含"true", 则表示支持该指令集 #include"string" using namespace std; static bool runtime_check(bool *fma, bool *avx) { if (!fma || !avx) { return false; } *fma = false; *avx = false; #ifdef UNICODE wchar_t exe[] = _T("runtime_check.exe "); wchar_t arg[2][4] = {_T("FMA"), _T("AVX")}; #else char exe[] = "runtime_check.exe "; char arg[2][4] = {"FMA", "AVX"}; #endif PROCESS_INFORMATION pi; STARTUPINFO si; memset(&pi, 0, sizeof(PROCESS_INFORMATION)); memset(&si, 0, sizeof(STARTUPINFO)); si.cb = sizeof(STARTUPINFO); si.dwFlags |= STARTF_USESTDHANDLES; // STARTF_USESTDHANDLES is Required. si.dwFlags |= STARTF_USESHOWWINDOW; si.wShowWindow = SW_HIDE; int i; for (i = 0; i < 2; i++) { SECURITY_ATTRIBUTES saAttr; saAttr.nLength = sizeof(SECURITY_ATTRIBUTES); saAttr.bInheritHandle = TRUE; saAttr.lpSecurityDescriptor = NULL; HANDLE hChildStdoutRd = NULL; // Read-side, used in calls to ReadFile() to get child's stdout output. HANDLE hChildStdoutWr = NULL; // Write-side, given to child process using si struct. // Create a pipe to get results from child's stdout. if (!CreatePipe(&hChildStdoutRd, &hChildStdoutWr, &saAttr, 0)) { printf("cannot create pipe\n"); return false; } // Ensure the read handle to the pipe for STDOUT is not inherited. if (!SetHandleInformation(hChildStdoutRd, HANDLE_FLAG_INHERIT, 0)) { printf("Stdout SetHandleInformation"); return false; } si.hStdOutput = hChildStdoutWr; // Requires STARTF_USESTDHANDLES in dwFlags. si.hStdError = hChildStdoutWr; // Requires STARTF_USESTDHANDLES in dwFlags. #ifdef UNICODE wchar_t *cmd = new wchar_t[_tcslen(exe) + _tcslen(arg[i]) + 1]; #else char *cmd = new char[_tcslen(exe) + _tcslen(arg[i]) + 1]; #endif _tcscpy(cmd, exe); _tcscat(cmd, arg[i]); BOOL bSuccess = CreateProcess( NULL, // No module name (use command line) cmd, // Command line NULL, // Process handle not inheritable NULL, // Thread handle not inheritable TRUE, // Set handle inheritance to TRUE 0, // No creation flags NULL, // Use parent's environment block NULL, // Use parent's starting directory &si, // Pointer to STARTUPINFO structure &pi); // Pointer to PROCESS_INFORMATION structure delete[] cmd; if (bSuccess) { WaitForSingleObject(pi.hProcess, INFINITE); // Close the write end of the pipe before reading from the read end of the pipe. if (!CloseHandle(hChildStdoutWr)) { printf("cannot close handle"); return false; } std::string strResult; // Read output from the child process. for (;;) { DWORD dwRead; char chBuf[64]; // Read from pipe that is the standard output for child process. bSuccess = ReadFile(hChildStdoutRd, chBuf, 64, &dwRead, NULL); if (!bSuccess || 0 == dwRead) { break; } strResult += std::string(chBuf, dwRead); } if (strResult.length() > 0) { std::size_t pos = strResult.find(":"); strResult = strResult.substr(pos + 2, 4); if (strResult == "true") { if (0 == i) *fma = true; if (1 == i) *avx = true; } } CloseHandle(hChildStdoutRd); CloseHandle(pi.hProcess); CloseHandle(pi.hThread); } else { printf("CreateProcess failed: %d\n", GetLastError()); return false; } } return true; } #endif // _MSC_VER
C++
CL
b15044404ed34cfd902c60b4e646fa492e7d475b8dd8e1c0884773c2508f7d29
#define GLM_SWIZZLE #include "glew-2.0.0\include\GL\glew.h" #include "glfw-3.2.1.bin.WIN64\include\GLFW\glfw3.h" #include "glm\glm\gtx\transform.hpp" #include "glm\glm\gtc\matrix_transform.hpp" #include "glm\glm\gtc\quaternion.hpp" #include "glm\glm\gtx\quaternion.hpp" #include <iostream> #include "glm\glm\glm.hpp" #include <string> #include <fstream> #include "LoadShaders\include\LoadShaders.h" #include <vector> #include <time.h> #include <conio.h> #include <vector> #include <chrono> #include "windows.h" #include "glm\glm\glm.hpp" #include "camera.h" #include "HeightMapGenerator.h" using namespace glm; using namespace std; //GENERATE HEIGHTMAP BENCHMARK class Benchmark { GLFWwindow *window; mat4 ProjectionMatrix; mat4 ViewMatrix; //Common buffers// GLuint VBO; vector<vec4> vertices; GLuint HeightMap; GLuint PerFrameBuffer; GLuint ConstantBuffer; GLuint ElementBuffer; GLuint RenderProgram; GLuint Polygonizator; GLuint VertexPolygonizator; ////Tests objects//// GLuint ComputeShader; GLuint VertexShader; GLuint heightMapIndexBuffer; vector<vec2> heightMapIndex; //////////////////// GLuint VertexProgram, IndexBuffer; struct perFrameData { mat4 ViewMatrix; float time; vec3 seed; } *perFrameData; struct constantData { mat4 ProjectionMatrix; } *constantData; double loopTotalTime = 0; double testTime = 35; double frames = 0; int heightMapSize = 10; int octaves =64; Camera camera; enum Test { VertexTest, ComputeTest, CPUTest }; #define Compute Test::ComputeTest #define Vertex Test::VertexTest #define CPU Test::CPUTest Test test;// = Compute; public: Benchmark(); void draw(GLuint drawMode); int init(int width = 800, int height = 600, int test = 0, int heightMapSize=100); void initBuffers(); double launchLoop(); void updateBuffers(); void generateHeightmapComputeShader(); void generateHeightmapVertexShader(); void setOctaves(int _octaves) { octaves = _octaves; }; void generateHeigtmapCpu(); void polygonise(); void polygoniseVertex(); ~Benchmark(); };
C++
CL
9515c1f79d3ee1b7d9f7b8002404b96a6fe7357a927f3a36122095cbd261d166
// CreateRemoteThreadInsertDlg.cpp : 实现文件 // #include "stdafx.h" #include "CreateRemoteThreadInsert.h" #include "CreateRemoteThreadInsertDlg.h" #include "afxdialogex.h" #include "ThreadInsert.h" #ifdef _DEBUG #define new DEBUG_NEW #endif // CCreateRemoteThreadInsertDlg 对话框 CCreateRemoteThreadInsertDlg::CCreateRemoteThreadInsertDlg(CWnd* pParent /*=NULL*/) : CDialogEx(CCreateRemoteThreadInsertDlg::IDD, pParent) { m_hIcon = AfxGetApp()->LoadIcon(IDR_MAINFRAME); } void CCreateRemoteThreadInsertDlg::DoDataExchange(CDataExchange* pDX) { CDialogEx::DoDataExchange(pDX); } BEGIN_MESSAGE_MAP(CCreateRemoteThreadInsertDlg, CDialogEx) ON_WM_PAINT() ON_WM_QUERYDRAGICON() ON_BN_CLICKED(IDC_INSERT, &CCreateRemoteThreadInsertDlg::OnBnClickedInsert) END_MESSAGE_MAP() // CCreateRemoteThreadInsertDlg 消息处理程序 BOOL CCreateRemoteThreadInsertDlg::OnInitDialog() { CDialogEx::OnInitDialog(); // 设置此对话框的图标。当应用程序主窗口不是对话框时,框架将自动 // 执行此操作 SetIcon(m_hIcon, TRUE); // 设置大图标 SetIcon(m_hIcon, FALSE); // 设置小图标 // TODO: 在此添加额外的初始化代码 return TRUE; // 除非将焦点设置到控件,否则返回 TRUE } // 如果向对话框添加最小化按钮,则需要下面的代码 // 来绘制该图标。对于使用文档/视图模型的 MFC 应用程序, // 这将由框架自动完成。 void CCreateRemoteThreadInsertDlg::OnPaint() { if (IsIconic()) { CPaintDC dc(this); // 用于绘制的设备上下文 SendMessage(WM_ICONERASEBKGND, reinterpret_cast<WPARAM>(dc.GetSafeHdc()), 0); // 使图标在工作区矩形中居中 int cxIcon = GetSystemMetrics(SM_CXICON); int cyIcon = GetSystemMetrics(SM_CYICON); CRect rect; GetClientRect(&rect); int x = (rect.Width() - cxIcon + 1) / 2; int y = (rect.Height() - cyIcon + 1) / 2; // 绘制图标 dc.DrawIcon(x, y, m_hIcon); } else { CDialogEx::OnPaint(); } } //当用户拖动最小化窗口时系统调用此函数取得光标 //显示。 HCURSOR CCreateRemoteThreadInsertDlg::OnQueryDragIcon() { return static_cast<HCURSOR>(m_hIcon); } void CCreateRemoteThreadInsertDlg::OnBnClickedInsert() { // TODO: 在此添加控件通知处理程序代码 //HWND hwnd;//目标进程窗口句柄 DWORD hpid;//目标进程pid HANDLE htargetprocess;//目标进程句柄 LPVOID lpAddr;//目标线程申请内存空间的指针 // LPVOID lpBuffer;//dll地址 AdjustProcessTokenPrivilege(); ////查找目标进程窗口 //hwnd=::FindWindow(TEXT("Edit"),NULL); //if(hwnd==NULL) //{ // OutputDebugString(L"查找窗口失败"); // MessageBox(L"注入失败",L"提示",MB_OK); // return; //} //GetWindowThreadProcessId(hwnd,&hpid); hpid=GetProcessIDByName(L"Calculator.exe"); if(hpid==0) { OutputDebugString(L"获取窗口进程PID失败"); MessageBox(L"注入失败",L"提示",MB_OK); return; } htargetprocess=OpenTargetProcess(hpid); if(htargetprocess==NULL) { MessageBox(L"注入失败",L"提示",MB_OK); return; } if(TagetAlloc(htargetprocess, lpAddr) == FALSE) { MessageBox(L"注入失败",L"提示",MB_OK); return; } if(WriteDLLToTarget(htargetprocess, lpAddr , TEXT("C:\\Users\\10178\\Desktop\\InjectDllFile.dll") )== FALSE ) { MessageBox(L"注入失败",L"提示",MB_OK); return; } PTHREAD_START_ROUTINE pnfStartAddr ; pnfStartAddr=(PTHREAD_START_ROUTINE)GetProcAddress(GetModuleHandle(TEXT("Kernel32")), "LoadLibraryW"); if(pnfStartAddr==NULL) { OutputDebugString(L"获取LoadLibrary地址失败"); MessageBox(L"注入失败",L"提示",MB_OK); return; } if( CreateThreadInTarget(htargetprocess,pnfStartAddr,lpAddr) == FALSE) { MessageBox(L"注入失败",L"提示",MB_OK); return; } }
C++
CL
bdf94c6871947d31501bbe8b83d2d0fbdea0f6b200b93605d63114c1744d6dc1
// ______ _____ _ ________ // / ____/___ / ___/(_)___ ___ / _/ __ | // / / / __ \\__ \/ / __ `__ \ / // / / / // / /___/ /_/ /__/ / / / / / / // // /_/ / // \____/\____/____/_/_/ /_/ /_/___/\____/ // Kratos CoSimulationApplication // // License: BSD License, see license.txt // // Main authors: Philipp Bucher (https://github.com/philbucher) // // System includes #include <thread> #include <system_error> // Project includes #include "includes/communication/communication.hpp" #include "includes/file_serializer.hpp" #include "includes/utilities.hpp" #include "includes/version.hpp" namespace CoSimIO { namespace Internals { void AddFilePermissions(const fs::path& rPath) { CO_SIM_IO_TRY fs::permissions(rPath, fs::perms::owner_read | fs::perms::owner_write | fs::perms::group_read | fs::perms::group_write | fs::perms::others_read | fs::perms::others_write, fs::perm_options::add); CO_SIM_IO_CATCH } Communication::Communication( const Info& I_Settings, std::shared_ptr<DataCommunicator> I_DataComm) : mpDataComm(I_DataComm), mMyName(I_Settings.Get<std::string>("my_name")), mConnectTo(I_Settings.Get<std::string>("connect_to")), mAlwaysUseSerializer(I_Settings.Get<bool>("always_use_serializer", false)), mWorkingDirectory(I_Settings.Get<std::string>("working_directory", fs::relative(fs::current_path()).string())), mEchoLevel(I_Settings.Get<int>("echo_level", 0)), mPrintTiming(I_Settings.Get<bool>("print_timing", false)) { CO_SIM_IO_TRY if (I_Settings.Has("is_primary_connection")) { mIsPrimaryConnection = I_Settings.Get<bool>("is_primary_connection"); mPrimaryWasExplicitlySpecified = true; } else { // automatically determine the primary connection in case the user didn't specify it mIsPrimaryConnection = mMyName < mConnectTo; mPrimaryWasExplicitlySpecified = false; } mConnectionName = Utilities::CreateConnectionName(mMyName, mConnectTo); CO_SIM_IO_ERROR_IF_NOT(fs::exists(mWorkingDirectory)) << "The working directory " << mWorkingDirectory << " does not exist!" << std::endl; if (I_Settings.Has("serializer_trace_type")) { mSerializerTraceType = Serializer::StringToTraceType(I_Settings.Get<std::string>("serializer_trace_type")); } mCommInFolder = I_Settings.Get<bool>("use_folder_for_communication", true); mCommFolder = GetWorkingDirectory(); if (mCommInFolder) { mCommFolder /= ".CoSimIOComm_" + GetConnectionName(); } CO_SIM_IO_CATCH } Info Communication::Connect(const Info& I_Info) { CO_SIM_IO_TRY CO_SIM_IO_INFO_IF("CoSimIO", GetEchoLevel()>0 && mpDataComm->Rank() == 0) << "Establishing connection for \"" << mConnectionName << "\"\n from: \"" << mMyName << "\"\n to: \"" << mConnectTo << "\"\n as " << (mIsPrimaryConnection ? "PRIMARY" : "SECONDARY") << " connection; working directory: " << mWorkingDirectory << " ..." << std::endl; CO_SIM_IO_ERROR_IF(mIsConnected) << "A connection was already established!" << std::endl; BaseConnectDetail(I_Info); PrepareConnection(I_Info); HandShake(I_Info); Info connect_detail_info = ConnectDetail(I_Info); mIsConnected = true; connect_detail_info.Set<bool>("is_connected", true); connect_detail_info.Set<int>("connection_status", ConnectionStatus::Connected); connect_detail_info.Set<std::string>("working_directory", mWorkingDirectory.string()); CO_SIM_IO_ERROR_IF_NOT(mIsConnected) << "Connection was not successful!" << std::endl; CO_SIM_IO_INFO_IF("CoSimIO", GetEchoLevel()>0 && mpDataComm->Rank() == 0) << "Connection established" << std::endl; return connect_detail_info; CO_SIM_IO_CATCH } Info Communication::Disconnect(const Info& I_Info) { CO_SIM_IO_TRY CO_SIM_IO_INFO_IF("CoSimIO", GetEchoLevel()>0 && mpDataComm->Rank() == 0) << "Disconnecting \"" << mConnectionName << "\" ..." << std::endl; if (mIsConnected) { Info disconnect_detail_info = DisconnectDetail(I_Info); mIsConnected = false; disconnect_detail_info.Set<bool>("is_connected", false); BaseDisconnectDetail(I_Info); if (mIsConnected) { CO_SIM_IO_INFO("CoSimIO") << "Warning: Disconnect was not successful!" << std::endl; disconnect_detail_info.Set<int>("connection_status", ConnectionStatus::DisconnectionError); } else { CO_SIM_IO_INFO_IF("CoSimIO", GetEchoLevel()>0 && mpDataComm->Rank() == 0) << "Disconnecting successful" << std::endl; disconnect_detail_info.Set<int>("connection_status", ConnectionStatus::Disconnected); } return disconnect_detail_info; } else { CO_SIM_IO_INFO("CoSimIO") << "Warning: Calling Disconnect but there was no active connection!" << std::endl; Info disconnect_info; disconnect_info.Set<bool>("is_connected", false); disconnect_info.Set<int>("connection_status", ConnectionStatus::DisconnectionError); return disconnect_info; } CO_SIM_IO_CATCH } void Communication::BaseConnectDetail(const Info& I_Info) { CO_SIM_IO_TRY if (mCommInFolder && GetIsPrimaryConnection() && mpDataComm->Rank() == 0) { // delete and recreate directory to remove potential leftovers std::error_code ec; fs::remove_all(mCommFolder, ec); CO_SIM_IO_INFO_IF("CoSimIO", ec) << "Warning, communication directory (" << mCommFolder << ") could not be deleted!\nError code: " << ec.message() << std::endl; if (!fs::exists(mCommFolder)) { fs::create_directory(mCommFolder); AddFilePermissions(mCommFolder); // otherwise the process with lower rights cannot delete files in it } } SynchronizeAll("conn"); CO_SIM_IO_CATCH } void Communication::BaseDisconnectDetail(const Info& I_Info) { CO_SIM_IO_TRY SynchronizeAll("disconn"); if (mCommInFolder && GetIsPrimaryConnection() && mpDataComm->Rank() == 0) { // delete directory to remove potential leftovers std::error_code ec; fs::remove_all(mCommFolder, ec); if (ec) { CO_SIM_IO_INFO("CoSimIO") << "Warning, communication directory (" << mCommFolder << ") could not be deleted!\nError code: " << ec.message() << std::endl; } } CO_SIM_IO_CATCH } Info Communication::ImportInfoImpl(const Info& I_Info) { CO_SIM_IO_TRY Info imported_info; Info rec_info = ReceiveObjectWithStreamSerializer(I_Info, imported_info); imported_info.Set<double>("elapsed_time", rec_info.Get<double>("elapsed_time")); imported_info.Set<double>("elapsed_time_ipc", rec_info.Get<double>("elapsed_time_ipc")); imported_info.Set<double>("elapsed_time_serializer", rec_info.Get<double>("elapsed_time_serializer")); imported_info.Set<std::size_t>("memory_usage_ipc", rec_info.Get<std::size_t>("memory_usage_ipc")); return imported_info; CO_SIM_IO_CATCH } Info Communication::ExportInfoImpl(const Info& I_Info) { CO_SIM_IO_TRY return SendObjectWithStreamSerializer(I_Info, I_Info); CO_SIM_IO_CATCH } Info Communication::ImportDataImpl( const Info& I_Info, Internals::DataContainer<double>& rData) { CO_SIM_IO_TRY if (mAlwaysUseSerializer) { return ReceiveObjectWithStreamSerializer(I_Info, rData); } else { Info info; const double elapsed_time = ReceiveDataContainer(I_Info, rData); info.Set<double>("elapsed_time", elapsed_time); info.Set<std::size_t>("memory_usage_ipc", rData.size()*sizeof(double)); return info; } CO_SIM_IO_CATCH } Info Communication::ExportDataImpl( const Info& I_Info, const Internals::DataContainer<double>& rData) { CO_SIM_IO_TRY if (mAlwaysUseSerializer) { return SendObjectWithStreamSerializer(I_Info, rData); } else { Info info; const double elapsed_time = SendDataContainer(I_Info, rData); info.Set<double>("elapsed_time", elapsed_time); info.Set<std::size_t>("memory_usage_ipc", rData.size()*sizeof(double)); return info; } CO_SIM_IO_CATCH } Info Communication::ImportMeshImpl( const Info& I_Info, ModelPart& O_ModelPart) { CO_SIM_IO_TRY return ReceiveObjectWithStreamSerializer(I_Info, O_ModelPart); CO_SIM_IO_CATCH } Info Communication::ExportMeshImpl( const Info& I_Info, const ModelPart& I_ModelPart) { CO_SIM_IO_TRY return SendObjectWithStreamSerializer(I_Info, I_ModelPart); CO_SIM_IO_CATCH } void Communication::CheckConnection(const Info& I_Info) { CO_SIM_IO_ERROR_IF_NOT(mIsConnected) << "No active connection exists!" << std::endl; CO_SIM_IO_ERROR_IF_NOT(I_Info.Has("identifier")) << "\"identifier\" must be specified!" << std::endl; Utilities::CheckEntry(I_Info.Get<std::string>("identifier"), "identifier"); } void Communication::PostChecks(const Info& I_Info) { CO_SIM_IO_ERROR_IF_NOT(I_Info.Has("elapsed_time")) << "\"elapsed_time\" must be specified!" << std::endl; CO_SIM_IO_ERROR_IF_NOT(I_Info.Has("memory_usage_ipc")) << "\"memory_usage_ipc\" must be specified!" << std::endl; } fs::path Communication::GetTempFileName( const fs::path& rPath, const bool UseAuxFileForFileAvailability) const { CO_SIM_IO_TRY if (!UseAuxFileForFileAvailability) { if (mCommInFolder) { return rPath.string().insert(mCommFolder.string().length()+1, "."); } else { return "." + rPath.string(); } } else { return rPath; } CO_SIM_IO_CATCH } fs::path Communication::GetFileName(const fs::path& rPath, const std::string& rExtension) const { CO_SIM_IO_TRY fs::path local_copy(rPath); local_copy += "." + rExtension; if (mCommInFolder) { return mCommFolder / local_copy; } else { return local_copy; } CO_SIM_IO_CATCH } fs::path Communication::GetFileName(const fs::path& rPath, const int Rank, const std::string& rExtension) const { CO_SIM_IO_TRY fs::path local_copy(rPath); local_copy += "_s" + std::to_string(mpDataComm->Rank()) + "_d" + std::to_string(Rank); return GetFileName(local_copy, rExtension); CO_SIM_IO_CATCH } void Communication::WaitForPath( const fs::path& rPath, const bool UseAuxFileForFileAvailability, const int PrintEchoLevel) const { CO_SIM_IO_TRY CO_SIM_IO_INFO_IF("CoSimIO", GetEchoLevel()>=PrintEchoLevel) << "Waiting for: " << rPath << std::endl; if (!UseAuxFileForFileAvailability) { Utilities::WaitUntilPathExists(rPath); } else { fs::path avail_file = fs::path(rPath.string()+".avail"); Utilities::WaitUntilPathExists(avail_file); // once the file exists it means that the real file was written, hence it can be removed RemovePath(avail_file); } CO_SIM_IO_INFO_IF("CoSimIO", GetEchoLevel()>=PrintEchoLevel) << "Found: " << rPath << std::endl; CO_SIM_IO_CATCH } void Communication::WaitUntilFileIsRemoved( const fs::path& rPath, const int PrintEchoLevel) const { CO_SIM_IO_TRY std::error_code ec; if (fs::exists(rPath, ec)) { // only issue the wating message if the file exists initially CO_SIM_IO_INFO_IF("CoSimIO", GetEchoLevel()>=PrintEchoLevel) << "Waiting for: " << rPath << " to be removed" << std::endl; while(fs::exists(rPath, ec)) { std::this_thread::sleep_for(std::chrono::microseconds(10)); // wait 0.001s before next check } CO_SIM_IO_INFO_IF("CoSimIO", GetEchoLevel()>=PrintEchoLevel) << rPath << " was removed" << std::endl; } CO_SIM_IO_CATCH } void Communication::MakeFileVisible( const fs::path& rPath, const bool UseAuxFileForFileAvailability) const { CO_SIM_IO_TRY if (!UseAuxFileForFileAvailability) { const fs::path tmp_file_name = GetTempFileName(rPath, UseAuxFileForFileAvailability); AddFilePermissions(tmp_file_name); std::error_code ec; fs::rename(tmp_file_name, rPath, ec); CO_SIM_IO_ERROR_IF(ec) << rPath << " could not be made visible!\nError code: " << ec.message() << std::endl; } else { AddFilePermissions(rPath); std::ofstream avail_file; avail_file.open(rPath.string() + ".avail"); avail_file.close(); } CO_SIM_IO_CATCH } void Communication::RemovePath(const fs::path& rPath) const { CO_SIM_IO_TRY // In windows the file cannot be removed if another file handle is using it // this can be the case here if the partner checks if the file (still) exists // hence we try multiple times to delete it std::error_code ec; for (std::size_t i=0; i<5; ++i) { if (fs::remove(rPath, ec)) { return; // if file could be removed succesfully then return } } CO_SIM_IO_ERROR << rPath << " could not be deleted!\nError code: " << ec.message() << std::endl; CO_SIM_IO_CATCH } void Communication::SynchronizeAll(const std::string& rTag) const { CO_SIM_IO_TRY // first synchronize among the partitions mpDataComm->Barrier(); // then synchronize among the partners if (mpDataComm->Rank() == 0) { const fs::path file_name_primary(GetFileName("CoSimIO_primary_" + GetConnectionName() + "_" + rTag, "sync")); const fs::path file_name_secondary(GetFileName("CoSimIO_secondary_" + GetConnectionName() + "_" + rTag, "sync")); if (GetIsPrimaryConnection()) { std::ofstream sync_file; sync_file.open(GetTempFileName(file_name_primary)); sync_file.close(); CO_SIM_IO_ERROR_IF_NOT(fs::exists(GetTempFileName(file_name_primary))) << "Primary sync file " << file_name_primary << " could not be created!" << std::endl; MakeFileVisible(file_name_primary); WaitForPath(file_name_secondary, true, 2); RemovePath(file_name_secondary); WaitUntilFileIsRemoved(file_name_primary, 2); } else { WaitForPath(file_name_primary, true, 2); RemovePath(file_name_primary); std::ofstream sync_file; sync_file.open(GetTempFileName(file_name_secondary)); sync_file.close(); CO_SIM_IO_ERROR_IF_NOT(fs::exists(GetTempFileName(file_name_secondary))) << "Secondary sync file " << file_name_secondary << " could not be created!" << std::endl; MakeFileVisible(file_name_secondary); WaitUntilFileIsRemoved(file_name_secondary, 2); } } // and finally synchronize again among the partitions mpDataComm->Barrier(); CO_SIM_IO_CATCH } Info Communication::GetMyInfo() const { CoSimIO::Info my_info; my_info.Set<int>("version_major", GetMajorVersion()); my_info.Set<int>("version_minor", GetMinorVersion()); my_info.Set<std::string>("version_patch", GetPatchVersion()); my_info.Set<bool>("primary_was_explicitly_specified", mPrimaryWasExplicitlySpecified); my_info.Set<std::string>("communication_format", GetCommunicationName()); my_info.Set<std::string>("operating_system", GetOsName()); my_info.Set<int>("num_processes", GetDataCommunicator().Size()); my_info.Set<bool>("is_big_endian", Utilities::IsBigEndian()); my_info.Set<bool>("always_use_serializer", mAlwaysUseSerializer); my_info.Set<std::string>("serializer_trace_type", Serializer::TraceTypeToString(mSerializerTraceType)); my_info.Set<Info>("communication_settings", GetCommunicationSettings()); return my_info; } void Communication::HandShake(const Info& I_Info) { CO_SIM_IO_TRY if (mpDataComm->Rank() == 0) { const fs::path file_name_p2s(GetFileName("CoSimIO_" + GetConnectionName() + "_compatibility_check_primary_to_secondary", "dat")); const fs::path file_name_s2p(GetFileName("CoSimIO_" + GetConnectionName() + "_compatibility_check_secondary_to_primary", "dat")); auto exchange_data_for_handshake = [this]( const fs::path& rMyFileName, const fs::path& rOtherFileName){ // first export my info WaitUntilFileIsRemoved(rMyFileName,1); // in case of leftovers { // necessary as FileSerializer releases resources on destruction! FileSerializer serializer_save(GetTempFileName(rMyFileName).string(), mSerializerTraceType); serializer_save.save("info", GetMyInfo()); } MakeFileVisible(rMyFileName); // now get the info from the other WaitForPath(rOtherFileName, true, 1); { // necessary as FileSerializer releases resources on destruction! FileSerializer serializer_load(rOtherFileName.string(), mSerializerTraceType); serializer_load.load("info", mPartnerInfo); } RemovePath(rOtherFileName); }; if (GetIsPrimaryConnection()) { exchange_data_for_handshake(file_name_p2s, file_name_s2p); } else { exchange_data_for_handshake(file_name_s2p, file_name_p2s); } // perform checks for compatibility CO_SIM_IO_ERROR_IF(GetMajorVersion() != mPartnerInfo.Get<int>("version_major")) << "Major version mismatch! My version: " << GetMajorVersion() << "; partner version: " << mPartnerInfo.Get<int>("version_major") << std::endl; CO_SIM_IO_ERROR_IF(GetMinorVersion() != mPartnerInfo.Get<int>("version_minor")) << "Minor version mismatch! My version: " << GetMinorVersion() << "; partner version: " << mPartnerInfo.Get<int>("version_minor") << std::endl; CO_SIM_IO_ERROR_IF(mPrimaryWasExplicitlySpecified != mPartnerInfo.Get<bool>("primary_was_explicitly_specified")) << std::boolalpha << "Mismatch in how the primary connection was specified!\nPrimary connection was explicitly specified for me: " << mPrimaryWasExplicitlySpecified << "\nPrimary connection was explicitly specified for partner: " << mPartnerInfo.Get<bool>("primary_was_explicitly_specified") << std::noboolalpha << std::endl; CO_SIM_IO_ERROR_IF(GetCommunicationName() != mPartnerInfo.Get<std::string>("communication_format")) << "Mismatch in communication_format!\nMy communication_format: " << GetCommunicationName() << "\nPartner communication_format: " << mPartnerInfo.Get<std::string>("communication_format") << std::endl; CO_SIM_IO_ERROR_IF(GetDataCommunicator().Size() != mPartnerInfo.Get<int>("num_processes")) << "Mismatch in num_processes!\nMy num_processes: " << GetDataCommunicator().Size() << "\nPartner num_processes: " << mPartnerInfo.Get<int>("num_processes") << std::endl; CO_SIM_IO_ERROR_IF(mAlwaysUseSerializer != mPartnerInfo.Get<bool>("always_use_serializer")) << std::boolalpha << "Mismatch in always_use_serializer!\nMy always_use_serializer: " << mAlwaysUseSerializer << "\nPartner always_use_serializer: " << mPartnerInfo.Get<bool>("always_use_serializer") << std::noboolalpha << std::endl; CO_SIM_IO_ERROR_IF(Serializer::TraceTypeToString(mSerializerTraceType) != mPartnerInfo.Get<std::string>("serializer_trace_type")) << "Mismatch in serializer_trace_type!\nMy serializer_trace_type: " << Serializer::TraceTypeToString(mSerializerTraceType) << "\nPartner serializer_trace_type: " << mPartnerInfo.Get<std::string>("serializer_trace_type") << std::endl; auto print_endianness = [](const bool IsBigEndian){return IsBigEndian ? "big endian" : "small endian";}; CO_SIM_IO_INFO_IF("CoSimIO", Utilities::IsBigEndian() != mPartnerInfo.Get<bool>("is_big_endian")) << "WARNING: Parnters have different endianness, check results carefully! It is recommended to use serialized ascii commuication.\n My endianness: " << print_endianness(Utilities::IsBigEndian()) << "\n Partner endianness: " << print_endianness(mPartnerInfo.Get<bool>("is_big_endian")) << std::endl; // more things can be done in derived class if necessary DerivedHandShake(); } // sync the partner info among the partitions mpDataComm->Broadcast(mPartnerInfo, 0); CO_SIM_IO_CATCH } void Communication::PrintElapsedTime( const Info& I_Info, const Info& O_Info, const std::string& rLabel) { const std::string identifier =I_Info.Get<std::string>("identifier"); const double dur = O_Info.Get<double>("elapsed_time"); CO_SIM_IO_INFO_IF("CoSimIO-Timing", GetPrintTiming() && GetDataCommunicator().Rank()==0) << rLabel << " \"" << identifier << "\" took " << dur << " [s]" << std::endl; } } // namespace Internals } // namespace CoSimIO
C++
CL
d9de7e950caef7e8d6663dda77865302b2583e68dce4045f2ef24ca5bb54294e
/* * FeedStatLogAdapter.h * * Created on: Nov 1, 2011 * Author: qun.liu */ #ifndef FEEDSTATLOGADAPTER_H_ #define FEEDSTATLOGADAPTER_H_ #include "Singleton.h" #include "AdapterI.h" #include "FeedStatLog.h" namespace xce { namespace feed { using namespace MyUtil; class FeedStatLogAdapter: public MyUtil::AdapterI, public MyUtil::AdapterISingleton<MyUtil::XceFeedChannel, FeedStatLogAdapter> { public: FeedStatLogAdapter() { } void AddLog(MyUtil::StrSeq category, string log); protected: virtual string name() { return "FeedStatLog0"; } virtual string endpoints() { return "@FeedStatLog0"; } virtual size_t cluster() { return 0; } FeedStatLogPrx getManager(); FeedStatLogPrx getManagerOneway(); }; }; }; #endif /* FEEDSTATLOGADAPTER_H_ */
C++
CL
87ec441ea959a6f14db85d6ede76b0924e2ccbb368ffdb41f08f16a6b8b2f2b5
#include "stdafx.h" #include <comutil.h> #include "UploadSelect.h" #include "SelectFolderDialog.h" //20080612 해시값 추출 클래스 추가, jyh #include "MD5_Client.h" void UploadSelect::ShowDlgFile() { DWORD dFlag = OFN_HIDEREADONLY | OFN_OVERWRITEPROMPT | /*OFN_ALLOWMULTISELECT | */OFN_FILEMUSTEXIST | OFN_NONETWORKBUTTON; CFileDialog pWindow(TRUE, NULL, NULL, dFlag); CFileStatus statusFile; int nSelectedCount = 0; CString pSelectedPath; CString pSelectedSize; POSITION startPosition; char pFileName[10000] = {0}; CMD5 pMD5; //20080612 해시값 추출 클래스, jyh CString strMD5CheckSum; //20080612 해시값 저장 변수, jyh DWORD dwErrorCode = NO_ERROR; pWindow.m_ofn.lpstrFile = pFileName; pWindow.m_ofn.nMaxFile = sizeof(pFileName); pWindow.m_ofn.lpstrInitialDir = m_pRegPath; pWindow.m_ofn.lpstrTitle = "업로드 하실 파일을 선택해주세요"; if(IDOK == pWindow.DoModal()) { startPosition = pWindow.GetStartPosition(); while(startPosition) { pSelectedPath = pWindow.GetNextPathName(startPosition); CFileFind mFind; if(mFind.FindFile(pSelectedPath)) { mFind.FindNextFile(); pSelectedSize.Format("%I64d", mFind.GetLength()); //20080612 해시값 추출, jyh strMD5CheckSum = pMD5.GetString(mFind.GetFilePath(), dwErrorCode); //m_pMain->SelectComplete(_bstr_t(pSelectedPath), _bstr_t(pSelectedSize), _bstr_t("-1")); m_pMain->SelectComplete(_bstr_t(pSelectedPath), _bstr_t(pSelectedSize), _bstr_t("-1"), _bstr_t(strMD5CheckSum)); } mFind.Close(); if(nSelectedCount == 0) { m_pRegPath.Format("%s", pSelectedPath); //20071217 레지스트리에 저작권 등록시 선택하는 파일 경로를 저장한다, jyh m_pReg.SaveKey(CLIENT_REG_PATH, "strCopyrightPath", pSelectedPath); ::PathRemoveFileSpec((LPTSTR)(LPCTSTR)m_pRegPath); m_pReg.SaveKey(CLIENT_REG_PATH, "strWebPath", m_pRegPath); } nSelectedCount ++; } } } //20071112 오픈 자료실 파일 열기 대화상자, jyh void UploadSelect::ShowDlgOpenFile() { DWORD dFlag = OFN_HIDEREADONLY | OFN_OVERWRITEPROMPT | /*OFN_ALLOWMULTISELECT | */OFN_FILEMUSTEXIST | OFN_NONETWORKBUTTON; CFileDialog pWindow(TRUE, NULL, NULL, dFlag); CFileStatus statusFile; int nSelectedCount = 0; CString pSelectedPath; CString pSelectedSize; POSITION startPosition; char pFileName[10000] = {0}; pWindow.m_ofn.lpstrFile = pFileName; pWindow.m_ofn.nMaxFile = sizeof(pFileName); pWindow.m_ofn.lpstrInitialDir = m_pRegPath; pWindow.m_ofn.lpstrTitle = "업로드 하실 파일을 선택해주세요"; if(IDOK == pWindow.DoModal()) { startPosition = pWindow.GetStartPosition(); while(startPosition) { pSelectedPath = pWindow.GetNextPathName(startPosition); CFileFind mFind; if(mFind.FindFile(pSelectedPath)) { mFind.FindNextFile(); //파일 사이즈가 50MB 이상은 업로드 금지 if(mFind.GetLength() > 52428800) { AfxMessageBox("50MB 이상은 업로드 할 수 없습니다!"); return; } pSelectedSize.Format("%I64d", mFind.GetLength()); m_pMain->SelectComplete(_bstr_t(pSelectedPath), _bstr_t(pSelectedSize), _bstr_t("-1"), _bstr_t("-1")); } mFind.Close(); if(nSelectedCount == 0) { m_pRegPath.Format("%s", pSelectedPath); ::PathRemoveFileSpec((LPTSTR)(LPCTSTR)m_pRegPath); m_pReg.SaveKey(CLIENT_REG_PATH, "strWebPath", m_pRegPath); } nSelectedCount ++; } } } void UploadSelect::ShowDlgFolder() { CString pSelectedPath; DWORD wFlag = OFN_HIDEREADONLY | OFN_OVERWRITEPROMPT | OFN_PATHMUSTEXIST; CSelectFolderDialog pSelectDialog(FALSE, m_pRegPath, wFlag, NULL, NULL, "업로드 하실 폴더를 선택해주세요"); if(pSelectDialog.DoModal() == IDOK) { pSelectedPath = pSelectDialog.GetSelectedPath(); //20090324 드라이브는 선택되지 않게 한다, jyh int nCnt = 0, nPos = 0; while((nPos = pSelectedPath.Find("\\", nPos)) > 0) { nPos++; nCnt++; } if(nCnt == 1) { AfxMessageBox("드라이브는 선택할 수 없습니다!"); return; } m_pReg.SaveKey(CLIENT_REG_PATH, "strWebPath", pSelectedPath); //20071217 레지스트리에 저작권 등록시 선택하는 파일 경로를 저장한다, jyh m_pReg.SaveKey(CLIENT_REG_PATH, "strCopyrightPath", pSelectedPath); if(pSelectedPath.Right(1) == '\\') pSelectedPath = pSelectedPath.Left(pSelectedPath.GetLength() -1); m_pMain->SelectComplete(_bstr_t(pSelectedPath), _bstr_t("-1"), _bstr_t("-1"), _bstr_t("-1")); FolderSubInfo(pSelectedPath, pSelectedPath); } } //20071112 오픈 자료실 폴더 열기 대화상자, jyh void UploadSelect::ShowDlgOpenFolder() { CString pSelectedPath; DWORD wFlag = OFN_HIDEREADONLY | OFN_OVERWRITEPROMPT | OFN_PATHMUSTEXIST; CSelectFolderDialog pSelectDialog(FALSE, m_pRegPath, wFlag, NULL, NULL, "업로드 하실 폴더를 선택해주세요"); if(pSelectDialog.DoModal() == IDOK) { pSelectedPath = pSelectDialog.GetSelectedPath(); m_pReg.SaveKey(CLIENT_REG_PATH, "strWebPath", pSelectedPath); if(pSelectedPath.Right(1) == '\\') pSelectedPath = pSelectedPath.Left(pSelectedPath.GetLength() -1); ULONGLONG nFolderSize = 0; nFolderSize = pSelectDialog.GetFolderSize(pSelectedPath); //폴더 사이즈가 50MB 이상은 업로드 금지 if(nFolderSize > 52428800) { AfxMessageBox("50MB 이상은 업로드 할 수 없습니다!"); return; } m_pMain->SelectComplete(_bstr_t(pSelectedPath), _bstr_t("-1"), _bstr_t("-1"), _bstr_t("-1")); FolderSubInfo(pSelectedPath, pSelectedPath); } } void UploadSelect::FolderSubInfo(CString strTargetFolder, CString strRoot) { CFileFind mFind; CString pCheckPath; CString pSize; CFileStatus statusFile; CMD5 pMD5; //20080612 해시값 추출 클래스, jyh CString strMD5CheckSum; //20080612 해시값 저장 변수, jyh DWORD dwErrorCode = NO_ERROR; if(strTargetFolder.Right(1) != "\\") strTargetFolder += "\\"; pCheckPath = strTargetFolder + "*.*"; BOOL bFind = mFind.FindFile(pCheckPath); while(bFind) { bFind = mFind.FindNextFile(); if(mFind.IsDots()) continue; if(!mFind.IsHidden() && mFind.IsDirectory()) { m_pMain->SelectComplete(_bstr_t(mFind.GetFilePath()), _bstr_t("-1"), _bstr_t(strRoot), _bstr_t("-1")); FolderSubInfo(mFind.GetFilePath(), strRoot); } } mFind.Close(); bFind = mFind.FindFile(pCheckPath); while(bFind) { bFind = mFind.FindNextFile(); if(mFind.IsDots()) continue; if(!mFind.IsHidden() && !mFind.IsSystem() && !mFind.IsDirectory()) { //20080612 해시값을 추출, jyh strMD5CheckSum = pMD5.GetString(mFind.GetFilePath(), dwErrorCode); pSize.Format("%I64d", mFind.GetLength()); m_pMain->SelectComplete(_bstr_t(mFind.GetFilePath()), _bstr_t(pSize), _bstr_t(strRoot), _bstr_t(strMD5CheckSum)); } } mFind.Close(); }
C++
CL
4ac9060478ad143046db74db5e0269d2476362afdd8fef55dad76e0f5527f28f
#ifndef PWM_MOTOR_CONTROL_NODE_H #define PWM_MOTOR_CONTROL_NODE_H #include <ros/ros.h> #include <std_msgs/Int8.h> #include <motor_control.h> class PwmMotorControlNode { public: PwmMotorControlNode() = delete; PwmMotorControlNode(ros::NodeHandle* node_handle, std::unique_ptr<PwmMotorControl> motor_control); ~PwmMotorControlNode(); private: void MotorSpeedCallback(const std_msgs::Int8::ConstPtr& msg); void OutputTimerCallback(const ros::TimerEvent& event); void SaveMotorSpeed(const int& motor_speed); void ResetMotorSpeedAfterDataSilence(); std::unique_ptr<PwmMotorControl> motor_control_; std::int8_t current_motor_speed_{0}; ros::Time time_last_motor_speed_received_{0.0F}; ros::NodeHandle nh_; ros::Subscriber motor_speed_sub_; ros::Timer output_timer_; const ros::Duration motor_speed_silence_timout_{1.0F}; const ros::Duration pwm_output_period_{0.1F}; }; #endif
C++
CL
79ae9f7f5fe71c40bceead4ce77ae59b9275bbedd905fc903f9c22b792371e2e
/*--------------------------------*- C++ -*----------------------------------*\ ========= | \\ / F ield | OpenFOAM: The Open Source CFD Toolbox \\ / O peration | Website: https://openfoam.org \\ / A nd | Version: 7 \\/ M anipulation | \*---------------------------------------------------------------------------*/ FoamFile { version 2.0; format ascii; class volVectorField; location "70"; object U; } // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // dimensions [0 1 -1 0 0 0 0]; internalField nonuniform List<vector> 928 ( (0.356418 -0.00131398 5.73984e-23) (0.3603 -0.00130034 -2.10408e-22) (0.364143 -0.00128683 -2.83849e-23) (0.367948 -0.00127346 1.68328e-22) (0.371716 -0.00126021 -8.47883e-23) (0.357247 -0.00393903 -1.70403e-21) (0.361121 -0.00389816 7.27866e-22) (0.364956 -0.00385767 8.61369e-23) (0.368753 -0.00381758 -4.52224e-22) (0.372513 -0.00377789 8.50241e-22) (0.358903 -0.0065554 2.03402e-24) (0.36276 -0.0064874 1.18405e-21) (0.366579 -0.00642006 -1.10122e-21) (0.370361 -0.00635337 7.33933e-22) (0.374105 -0.00628735 1.68012e-22) (0.361379 -0.00915732 -1.17095e-21) (0.365212 -0.0090624 8.58863e-23) (0.369007 -0.0089684 2.12751e-21) (0.372765 -0.00887531 -1.3858e-21) (0.376485 -0.00878314 4.86025e-22) (0.364666 -0.0117391 -1.92814e-21) (0.368467 -0.0116176 4.41234e-22) (0.37223 -0.0114972 -8.22764e-22) (0.375956 -0.0113779 1.99396e-21) (0.379646 -0.0112599 5.81714e-22) (0.368753 -0.0142952 -3.20208e-22) (0.372514 -0.0141474 2.15718e-21) (0.376238 -0.0140009 -5.37931e-23) (0.379925 -0.0138559 1.29705e-22) (0.383575 -0.0137123 -9.48091e-22) (0.373625 -0.0168202 -2.967e-21) (0.377338 -0.0166465 4.07604e-21) (0.381015 -0.0164744 -3.28736e-21) (0.384655 -0.016304 4.0907e-21) (0.38826 -0.0161353 -1.42172e-21) (0.379264 -0.0193086 4.78511e-22) (0.382922 -0.0191096 9.72697e-22) (0.386544 -0.0189124 2.45378e-21) (0.390131 -0.0187171 -6.38722e-21) (0.393683 -0.0185238 4.69593e-21) (0.385651 -0.0217555 3.93233e-23) (0.389247 -0.0215317 3.29487e-22) (0.392807 -0.0213099 -1.11167e-21) (0.396333 -0.0210903 3.53488e-22) (0.399825 -0.0208729 2.42717e-21) (0.392763 -0.0241559 4.32521e-21) (0.396289 -0.0239079 2.31631e-21) (0.399782 -0.0236622 -3.95327e-21) (0.40324 -0.0234189 -2.55538e-21) (0.406665 -0.023178 -4.91748e-22) (0.400575 -0.026505 -2.93576e-22) (0.404026 -0.0262335 -8.63541e-22) (0.407443 -0.0259647 1.66567e-21) (0.410827 -0.0256983 -4.76401e-22) (0.41418 -0.0254345 -2.6671e-21) (0.417499 -0.0251733 1.80813e-21) (0.409061 -0.0287984 3.97535e-21) (0.412429 -0.0285043 -4.65004e-21) (0.415765 -0.0282129 -8.1454e-22) (0.419069 -0.0279243 4.78442e-21) (0.422342 -0.0276384 -2.14943e-21) (0.425584 -0.0273553 -3.61325e-21) (0.42147 -0.0307159 3.25245e-23) (0.424719 -0.0304029 -1.95743e-21) (0.427938 -0.0300927 -5.4544e-21) (0.431126 -0.0297856 1.18602e-20) (0.434284 -0.0294814 -5.84625e-21) (0.431119 -0.0328645 4.3285e-21) (0.434275 -0.0325307 -1.09768e-20) (0.437402 -0.0321999 1.18942e-20) (0.4405 -0.0318723 -2.78793e-21) (0.44357 -0.0315478 -4.85699e-21) (0.441342 -0.0349466 -3.09463e-21) (0.444401 -0.0345929 5.99305e-21) (0.447432 -0.0342424 3.35509e-21) (0.450435 -0.0338951 -1.93418e-21) (0.45341 -0.0335512 -7.76385e-22) (0.452108 -0.0369588 -1.36941e-20) (0.455064 -0.0365862 3.02971e-21) (0.457994 -0.0362168 7.29013e-21) (0.460897 -0.0358509 -5.23867e-22) (0.463774 -0.0354884 -7.07754e-21) (0.463379 -0.0388982 8.44317e-21) (0.466229 -0.0385076 -1.79649e-21) (0.469053 -0.0381204 -1.96242e-21) (0.471853 -0.0377368 2.01044e-21) (0.474627 -0.0373567 -7.15541e-21) (0.475121 -0.0407622 -2.65517e-21) (0.47786 -0.0403546 2.74767e-21) (0.480575 -0.0399506 8.86425e-21) (0.483267 -0.0395502 -6.77456e-21) (0.485935 -0.0391536 -8.22565e-21) (0.488579 -0.0387606 6.72214e-21) (0.489921 -0.0421248 3.26021e-21) (0.492524 -0.0417051 4.59932e-21) (0.495104 -0.041289 1.39679e-21) (0.497662 -0.0408767 -1.44085e-21) (0.500199 -0.0404682 3.55294e-21) (0.502375 -0.0438164 6.36059e-22) (0.504862 -0.0433819 -2.12389e-21) (0.507328 -0.0429511 -1.18348e-20) (0.509774 -0.0425242 2.38605e-21) (0.512199 -0.0421012 -1.69271e-21) (0.515184 -0.0454277 8.47756e-21) (0.517552 -0.0449794 6.36399e-22) (0.519902 -0.0445351 -2.70327e-21) (0.522232 -0.0440946 -6.89319e-21) (0.524544 -0.0436581 -4.4904e-21) (0.528309 -0.0469573 -8.7147e-21) (0.530557 -0.0464965 5.68915e-21) (0.532788 -0.0460396 -6.87162e-21) (0.535001 -0.0455866 -1.22671e-21) (0.537197 -0.0451376 3.41289e-21) (0.541713 -0.0484044 -9.98305e-22) (0.543839 -0.0479321 -2.3615e-21) (0.545949 -0.0474637 -5.6318e-21) (0.548044 -0.0469992 -5.73836e-21) (0.550122 -0.0465387 7.26334e-21) (0.552185 -0.0460823 2.28817e-21) (0.55736 -0.0492856 -1.85493e-21) (0.559349 -0.0488067 6.31825e-22) (0.561323 -0.0483319 1.24289e-20) (0.563283 -0.047861 -3.85701e-21) (0.565229 -0.0473942 -1.42762e-21) (0.571084 -0.0505568 4.2731e-21) (0.57295 -0.0500686 -1.2601e-20) (0.574803 -0.0495843 8.37294e-21) (0.576644 -0.0491041 -2.32696e-21) (0.578472 -0.0486279 5.09019e-21) (0.584973 -0.0517456 -5.04067e-21) (0.586715 -0.0512491 5.37226e-21) (0.588447 -0.0507566 2.80793e-21) (0.590168 -0.050268 -8.0522e-21) (0.591878 -0.0497834 8.34367e-22) (0.60061 -0.0523474 8.76206e-22) (0.602221 -0.0518475 -6.55544e-21) (0.603822 -0.0513516 1.10614e-20) (0.605413 -0.0508597 -9.08035e-21) (0.606995 -0.0503718 5.11846e-21) (0.614599 -0.0533641 9.15003e-22) (0.616088 -0.052858 1.03036e-20) (0.617569 -0.0523558 -7.1233e-21) (0.619043 -0.0518575 5.9772e-21) (0.620509 -0.0513632 5.05938e-21) (0.628647 -0.0543132 6.46478e-21) (0.630015 -0.0538016 -1.86405e-21) (0.631378 -0.0532938 -7.09449e-21) (0.632734 -0.0527898 6.48034e-22) (0.634084 -0.0522898 -1.43094e-21) (0.642721 -0.0552034 5.85201e-21) (0.643971 -0.0546869 5.52748e-22) (0.645215 -0.054174 -6.36336e-21) (0.646455 -0.0536649 8.01924e-21) (0.64769 -0.0531597 -1.51075e-21) (0.665668 -0.0564073 0) (0.666745 -0.0558882 0) (0.667819 -0.0553725 0) (0.668891 -0.0548602 0) (0.66996 -0.0543516 0) (0.671025 -0.0538467 0) (0.700168 -0.057194 0) (0.700992 -0.056677 0) (0.701817 -0.0561632 0) (0.702641 -0.0556528 0) (0.703465 -0.0551457 0) (0.733965 -0.0581866 0) (0.73454 -0.0576722 0) (0.735118 -0.0571607 0) (0.7357 -0.0566521 0) (0.736284 -0.0561466 0) (0.767831 -0.0588247 0) (0.768163 -0.0583174 0) (0.7685 -0.0578124 0) (0.768844 -0.0573099 0) (0.769193 -0.0568101 0) (0.801478 -0.0591177 0) (0.801574 -0.0586216 0) (0.801679 -0.0581273 0) (0.801793 -0.0576349 0) (0.801914 -0.0571446 0) (0.834629 -0.0590827 0) (0.834501 -0.0586016 0) (0.834385 -0.0581217 0) (0.834279 -0.0576431 0) (0.834185 -0.0571661 0) (0.867027 -0.058738 0) (0.86669 -0.0582755 0) (0.866366 -0.0578134 0) (0.866056 -0.057352 0) (0.865759 -0.0568916 0) (0.89844 -0.0581059 0) (0.89791 -0.057665 0) (0.897396 -0.0572238 0) (0.896897 -0.0567827 0) (0.896413 -0.0563418 0) (0.92866 -0.057212 0) (0.927956 -0.0567952 0) (0.927269 -0.0563775 0) (0.926599 -0.0559592 0) (0.925946 -0.0555404 0) (0.957507 -0.0560841 0) (0.956649 -0.0556936 0) (0.95581 -0.0553015 0) (0.954989 -0.0549079 0) (0.954185 -0.0545132 0) (0.984833 -0.0547519 0) (0.983842 -0.0543893 0) (0.982871 -0.0540242 0) (0.981919 -0.053657 0) (0.980985 -0.0532879 0) (1.01052 -0.0532459 0) (1.00942 -0.0529121 0) (1.00834 -0.0525751 0) (1.00727 -0.0522353 0) (1.00623 -0.0518929 0) (1.03448 -0.0515969 0) (1.03329 -0.0512924 0) (1.03212 -0.050984 0) (1.03096 -0.0506721 0) (1.02983 -0.0503569 0) (1.05666 -0.0498352 0) (1.0554 -0.04956 0) (1.05416 -0.0492801 0) (1.05294 -0.0489961 0) (1.05173 -0.0487082 0) (1.07704 -0.0479899 0) (1.07573 -0.0477433 0) (1.07443 -0.0474916 0) (1.07316 -0.0472351 0) (1.07191 -0.0469742 0) (1.0956 -0.0460882 0) (1.09426 -0.0458695 0) (1.09294 -0.0456451 0) (1.09163 -0.0454153 0) (1.09035 -0.0451805 0) (1.11239 -0.0441554 0) (1.11104 -0.0439633 0) (1.1097 -0.043765 0) (1.10837 -0.0435609 0) (1.10707 -0.0433513 0) (1.12745 -0.0422141 0) (1.12609 -0.0420472 0) (1.12475 -0.0418735 0) (1.12343 -0.0416937 0) (1.12212 -0.041508 0) (1.14084 -0.0402842 0) (1.1395 -0.0401407 0) (1.13817 -0.0399902 0) (1.13686 -0.0398331 0) (1.13556 -0.0396697 0) (1.15265 -0.0383825 0) (1.15133 -0.0382607 0) (1.15003 -0.0381316 0) (1.14874 -0.0379955 0) (1.14746 -0.037853 0) (1.16297 -0.0365232 0) (1.16169 -0.0364212 0) (1.16041 -0.0363116 0) (1.15915 -0.0361949 0) (1.15791 -0.0360715 0) (1.17191 -0.0347173 0) (1.17066 -0.0346333 0) (1.16943 -0.0345415 0) (1.16821 -0.0344424 0) (1.167 -0.0343363 0) (1.17957 -0.0329734 0) (1.17837 -0.0329054 0) (1.17718 -0.0328296 0) (1.176 -0.0327464 0) (1.17483 -0.0326561 0) (1.18607 -0.0312973 0) (1.18491 -0.0312437 0) (1.18377 -0.0311822 0) (1.18264 -0.0311132 0) (1.18151 -0.031037 0) (1.19151 -0.0296928 0) (1.1904 -0.0296519 0) (1.18931 -0.0296031 0) (1.18823 -0.0295467 0) (1.18715 -0.0294832 0) (1.196 -0.0281615 0) (1.19495 -0.0281319 0) (1.19391 -0.0280943 0) (1.19287 -0.0280492 0) (1.19184 -0.0279968 0) (1.19966 -0.0267038 0) (1.19866 -0.026684 0) (1.19767 -0.0266562 0) (1.19668 -0.026621 0) (1.1957 -0.0265785 0) (1.20257 -0.0253182 0) (1.20162 -0.025307 0) (1.20068 -0.0252879 0) (1.19974 -0.0252613 0) (1.19881 -0.0252276 0) (1.20484 -0.0240026 0) (1.20394 -0.0239988 0) (1.20304 -0.0239873 0) (1.20215 -0.0239683 0) (1.20126 -0.0239422 0) (1.20655 -0.0227538 0) (1.2057 -0.0227564 0) (1.20484 -0.0227514 0) (1.204 -0.0227391 0) (1.20315 -0.0227198 0) (1.20778 -0.0215681 0) (1.20697 -0.0215763 0) (1.20616 -0.021577 0) (1.20535 -0.0215705 0) (1.20455 -0.0215571 0) (1.2086 -0.0204415 0) (1.20783 -0.0204546 0) (1.20706 -0.0204602 0) (1.20629 -0.0204587 0) (1.20553 -0.0204505 0) (1.20908 -0.0193698 0) (1.20834 -0.019387 0) (1.20761 -0.0193969 0) (1.20688 -0.0193999 0) (1.20615 -0.0193962 0) (1.20927 -0.0183488 0) (1.20857 -0.0183695 0) (1.20787 -0.0183831 0) (1.20717 -0.0183899 0) (1.20648 -0.0183902 0) (1.20923 -0.0173743 0) (1.20856 -0.017398 0) (1.20789 -0.0174148 0) (1.20722 -0.0174249 0) (1.20655 -0.0174286 0) (1.20899 -0.0164422 0) (1.20835 -0.0164684 0) (1.20771 -0.0164879 0) (1.20707 -0.0165009 0) (1.20643 -0.0165076 0) (1.2086 -0.0155488 0) (1.20798 -0.0155771 0) (1.20737 -0.0155988 0) (1.20675 -0.0156142 0) (1.20614 -0.0156236 0) (1.20809 -0.0146905 0) (1.2075 -0.0147204 0) (1.20691 -0.014744 0) (1.20631 -0.0147615 0) (1.20572 -0.0147732 0) (1.20749 -0.0138639 0) (1.20692 -0.0138952 0) (1.20635 -0.0139203 0) (1.20578 -0.0139396 0) (1.20521 -0.0139531 0) (1.20683 -0.0130662 0) (1.20627 -0.0130984 0) (1.20572 -0.0131247 0) (1.20517 -0.0131453 0) (1.20462 -0.0131605 0) (1.20611 -0.0122945 0) (1.20558 -0.0123273 0) (1.20504 -0.0123545 0) (1.2045 -0.0123762 0) (1.20397 -0.0123926 0) (1.20537 -0.0115463 0) (1.20485 -0.0115795 0) (1.20433 -0.0116072 0) (1.20381 -0.0116297 0) (1.20329 -0.0116471 0) (1.20461 -0.0108195 0) (1.20411 -0.0108527 0) (1.2036 -0.0108807 0) (1.2031 -0.0109037 0) (1.20259 -0.0109218 0) (1.20386 -0.0101119 0) (1.20336 -0.0101448 0) (1.20287 -0.0101728 0) (1.20238 -0.0101961 0) (1.20188 -0.0102147 0) (1.20311 -0.00942175 0) (1.20263 -0.00945417 0) (1.20215 -0.00948191 0) (1.20166 -0.00950514 0) (1.20118 -0.00952401 0) (1.20238 -0.00874741 0) (1.20191 -0.00877905 0) (1.20144 -0.00880627 0) (1.20097 -0.00882923 0) (1.20049 -0.00884809 0) (1.20168 -0.00808735 0) (1.20121 -0.00811796 0) (1.20075 -0.00814442 0) (1.20029 -0.00816689 0) (1.19983 -0.00818551 0) (1.201 -0.00744021 0) (1.20055 -0.00746954 0) (1.2001 -0.00749502 0) (1.19964 -0.00751677 0) (1.19919 -0.00753493 0) (1.20037 -0.0068047 0) (1.19992 -0.00683254 0) (1.19948 -0.00685681 0) (1.19903 -0.00687764 0) (1.19858 -0.00689514 0) (1.19977 -0.00617966 0) (1.19934 -0.0062058 0) (1.1989 -0.00622867 0) (1.19846 -0.00624837 0) (1.19801 -0.00626503 0) (1.19922 -0.00556398 0) (1.19879 -0.00558823 0) (1.19836 -0.00560951 0) (1.19792 -0.00562791 0) (1.19749 -0.00564353 0) (1.19872 -0.00495664 0) (1.1983 -0.00497882 0) (1.19787 -0.00499833 0) (1.19744 -0.00501526 0) (1.19701 -0.00502969 0) (1.19827 -0.00435664 0) (1.19785 -0.0043766 0) (1.19743 -0.00439419 0) (1.197 -0.00440949 0) (1.19657 -0.00442258 0) (1.19787 -0.00376304 0) (1.19745 -0.00378063 0) (1.19703 -0.00379617 0) (1.19661 -0.00380971 0) (1.19619 -0.00382133 0) (1.19753 -0.00317494 0) (1.19711 -0.00319004 0) (1.1967 -0.00320339 0) (1.19628 -0.00321505 0) (1.19586 -0.00322509 0) (1.19724 -0.00259146 0) (1.19683 -0.00260395 0) (1.19641 -0.00261502 0) (1.196 -0.0026247 0) (1.19558 -0.00263305 0) (1.197 -0.00201172 0) (1.1966 -0.00202153 0) (1.19619 -0.00203022 0) (1.19577 -0.00203784 0) (1.19536 -0.00204442 0) (1.19683 -0.00143488 0) (1.19642 -0.00144193 0) (1.19601 -0.00144819 0) (1.1956 -0.00145368 0) (1.19519 -0.00145842 0) (1.19671 -0.000860099 0) (1.19631 -0.000864354 0) (1.1959 -0.000868129 0) (1.19549 -0.000871441 0) (1.19508 -0.000874305 0) (1.19665 -0.00028656 0) (1.19625 -0.000287982 0) (1.19584 -0.000289244 0) (1.19543 -0.000290351 0) (1.19502 -0.000291309 0) (0.665668 0.0564073 0) (0.699345 0.0577141 0) (0.733393 0.0587036 0) (0.767507 0.0593341 0) (0.801392 0.0596155 0) (0.834769 0.0595648 0) (0.867379 0.0592009 0) (0.898987 0.0585464 0) (0.929382 0.0576275 0) (0.958385 0.0564725 0) (0.985845 0.0551117 0) (1.01164 0.0535761 0) (1.0357 0.0518972 0) (1.05795 0.0501055 0) (1.07837 0.0482308 0) (1.09697 0.0463007 0) (1.11377 0.0443408 0) (1.12882 0.042374 0) (1.1422 0.0404202 0) (1.15399 0.0384966 0) (1.16427 0.0366173 0) (1.17317 0.0347933 0) (1.18078 0.0330331 0) (1.18723 0.0313426 0) (1.19262 0.0297253 0) (1.19706 0.0281829 0) (1.20066 0.0267153 0) (1.20353 0.0253213 0) (1.20575 0.0239983 0) (1.20741 0.0227431 0) (1.2086 0.021552 0) (1.20938 0.0204207 0) (1.20982 0.0193451 0) (1.20998 0.0183207 0) (1.2099 0.0173434 0) (1.20964 0.016409 0) (1.20922 0.0155137 0) (1.20869 0.0146539 0) (1.20807 0.0138263 0) (1.20738 0.0130278 0) (1.20665 0.0122557 0) (1.20589 0.0115075 0) (1.20512 0.0107808 0) (1.20435 0.0100738 0) (1.20359 0.00938446 0) (1.20285 0.00871119 0) (1.20214 0.00805246 0) (1.20146 0.00740688 0) (1.20081 0.00677316 0) (1.20021 0.00615012 0) (1.19965 0.00553665 0) (1.19915 0.00493168 0) (1.19869 0.00433423 0) (1.19829 0.00374332 0) (1.19794 0.00315804 0) (1.19765 0.00257747 0) (1.19741 0.00200075 0) (1.19723 0.00142699 0) (1.19712 0.000855349 0) (1.19706 0.000284973 0) (0.666745 0.0558882 0) (0.700168 0.057194 0) (0.733965 0.0581866 0) (0.767831 0.0588247 0) (0.801478 0.0591177 0) (0.834629 0.0590827 0) (0.867027 0.058738 0) (0.89844 0.0581059 0) (0.92866 0.057212 0) (0.957507 0.0560841 0) (0.984833 0.0547519 0) (1.01052 0.0532459 0) (1.03448 0.0515969 0) (1.05666 0.0498352 0) (1.07704 0.0479899 0) (1.0956 0.0460882 0) (1.11239 0.0441554 0) (1.12745 0.0422141 0) (1.14084 0.0402842 0) (1.15265 0.0383825 0) (1.16297 0.0365232 0) (1.17191 0.0347173 0) (1.17957 0.0329734 0) (1.18607 0.0312973 0) (1.19151 0.0296928 0) (1.196 0.0281615 0) (1.19966 0.0267038 0) (1.20257 0.0253182 0) (1.20484 0.0240026 0) (1.20655 0.0227538 0) (1.20778 0.0215681 0) (1.2086 0.0204415 0) (1.20908 0.0193698 0) (1.20927 0.0183488 0) (1.20923 0.0173743 0) (1.20899 0.0164422 0) (1.2086 0.0155488 0) (1.20809 0.0146905 0) (1.20749 0.0138639 0) (1.20683 0.0130662 0) (1.20611 0.0122945 0) (1.20537 0.0115463 0) (1.20461 0.0108195 0) (1.20386 0.0101119 0) (1.20311 0.00942175 0) (1.20238 0.00874741 0) (1.20168 0.00808735 0) (1.201 0.00744021 0) (1.20037 0.0068047 0) (1.19977 0.00617966 0) (1.19922 0.00556398 0) (1.19872 0.00495664 0) (1.19827 0.00435664 0) (1.19787 0.00376304 0) (1.19753 0.00317494 0) (1.19724 0.00259146 0) (1.197 0.00201172 0) (1.19683 0.00143488 0) (1.19671 0.000860099 0) (1.19665 0.00028656 0) (0.667819 0.0553725 0) (0.700992 0.056677 0) (0.73454 0.0576722 0) (0.768163 0.0583174 0) (0.801574 0.0586216 0) (0.834501 0.0586016 0) (0.86669 0.0582755 0) (0.89791 0.057665 0) (0.927956 0.0567952 0) (0.956649 0.0556936 0) (0.983842 0.0543893 0) (1.00942 0.0529121 0) (1.03329 0.0512924 0) (1.0554 0.04956 0) (1.07573 0.0477433 0) (1.09426 0.0458695 0) (1.11104 0.0439633 0) (1.12609 0.0420472 0) (1.1395 0.0401407 0) (1.15133 0.0382607 0) (1.16169 0.0364212 0) (1.17066 0.0346333 0) (1.17837 0.0329054 0) (1.18491 0.0312437 0) (1.1904 0.0296519 0) (1.19495 0.0281319 0) (1.19866 0.026684 0) (1.20162 0.025307 0) (1.20394 0.0239988 0) (1.2057 0.0227564 0) (1.20697 0.0215763 0) (1.20783 0.0204545 0) (1.20834 0.019387 0) (1.20857 0.0183695 0) (1.20856 0.017398 0) (1.20835 0.0164684 0) (1.20798 0.0155771 0) (1.2075 0.0147204 0) (1.20692 0.0138952 0) (1.20627 0.0130984 0) (1.20558 0.0123273 0) (1.20485 0.0115795 0) (1.20411 0.0108527 0) (1.20336 0.0101448 0) (1.20263 0.00945417 0) (1.20191 0.00877905 0) (1.20121 0.00811796 0) (1.20055 0.00746954 0) (1.19992 0.00683254 0) (1.19934 0.0062058 0) (1.19879 0.00558823 0) (1.1983 0.00497882 0) (1.19785 0.0043766 0) (1.19745 0.00378063 0) (1.19711 0.00319004 0) (1.19683 0.00260395 0) (1.1966 0.00202153 0) (1.19642 0.00144193 0) (1.19631 0.000864354 0) (1.19625 0.000287982 0) (0.668891 0.0548602 0) (0.701817 0.0561632 0) (0.735118 0.0571607 0) (0.7685 0.0578124 0) (0.801679 0.0581273 0) (0.834385 0.0581217 0) (0.866366 0.0578134 0) (0.897396 0.0572238 0) (0.927269 0.0563775 0) (0.95581 0.0553015 0) (0.982871 0.0540242 0) (1.00834 0.0525751 0) (1.03212 0.050984 0) (1.05416 0.0492801 0) (1.07443 0.0474916 0) (1.09294 0.0456451 0) (1.1097 0.043765 0) (1.12475 0.0418735 0) (1.13817 0.0399902 0) (1.15003 0.0381316 0) (1.16041 0.0363116 0) (1.16943 0.0345415 0) (1.17718 0.0328296 0) (1.18377 0.0311822 0) (1.18931 0.0296031 0) (1.19391 0.0280943 0) (1.19767 0.0266562 0) (1.20068 0.0252879 0) (1.20304 0.0239873 0) (1.20484 0.0227514 0) (1.20616 0.021577 0) (1.20706 0.0204602 0) (1.20761 0.0193969 0) (1.20787 0.0183831 0) (1.20789 0.0174148 0) (1.20771 0.0164879 0) (1.20737 0.0155988 0) (1.20691 0.014744 0) (1.20635 0.0139203 0) (1.20572 0.0131247 0) (1.20504 0.0123545 0) (1.20433 0.0116072 0) (1.2036 0.0108807 0) (1.20287 0.0101728 0) (1.20215 0.00948191 0) (1.20144 0.00880627 0) (1.20075 0.00814442 0) (1.2001 0.00749501 0) (1.19948 0.00685681 0) (1.1989 0.00622867 0) (1.19836 0.00560951 0) (1.19787 0.00499833 0) (1.19743 0.00439419 0) (1.19703 0.00379617 0) (1.1967 0.00320339 0) (1.19641 0.00261502 0) (1.19619 0.00203022 0) (1.19601 0.00144819 0) (1.1959 0.000868129 0) (1.19584 0.000289244 0) (0.66996 0.0543516 0) (0.702641 0.0556528 0) (0.7357 0.0566521 0) (0.768844 0.0573099 0) (0.801792 0.0576349 0) (0.834279 0.0576431 0) (0.866056 0.057352 0) (0.896897 0.0567827 0) (0.926599 0.0559592 0) (0.954989 0.0549079 0) (0.981919 0.053657 0) (1.00727 0.0522353 0) (1.03096 0.0506721 0) (1.05294 0.0489961 0) (1.07316 0.0472351 0) (1.09163 0.0454153 0) (1.10837 0.0435609 0) (1.12343 0.0416937 0) (1.13686 0.0398331 0) (1.14874 0.0379955 0) (1.15915 0.0361949 0) (1.16821 0.0344424 0) (1.176 0.0327464 0) (1.18264 0.0311132 0) (1.18823 0.0295467 0) (1.19287 0.0280492 0) (1.19668 0.026621 0) (1.19974 0.0252613 0) (1.20215 0.0239683 0) (1.204 0.0227391 0) (1.20535 0.0215705 0) (1.20629 0.0204587 0) (1.20688 0.0193999 0) (1.20717 0.0183899 0) (1.20722 0.0174249 0) (1.20707 0.0165009 0) (1.20675 0.0156142 0) (1.20631 0.0147615 0) (1.20578 0.0139395 0) (1.20517 0.0131453 0) (1.2045 0.0123762 0) (1.20381 0.0116297 0) (1.2031 0.0109037 0) (1.20238 0.0101961 0) (1.20166 0.00950514 0) (1.20097 0.00882923 0) (1.20029 0.00816689 0) (1.19964 0.00751677 0) (1.19903 0.00687764 0) (1.19846 0.00624837 0) (1.19792 0.00562791 0) (1.19744 0.00501526 0) (1.197 0.00440949 0) (1.19661 0.00380971 0) (1.19628 0.00321505 0) (1.196 0.0026247 0) (1.19577 0.00203784 0) (1.1956 0.00145368 0) (1.19549 0.000871441 0) (1.19543 0.000290351 0) (0.671025 0.0538467 0) (0.703465 0.0551457 0) (0.736284 0.0561466 0) (0.769193 0.0568101 0) (0.801914 0.0571446 0) (0.834185 0.0571661 0) (0.865759 0.0568916 0) (0.896413 0.0563418 0) (0.925946 0.0555404 0) (0.954185 0.0545132 0) (0.980985 0.0532879 0) (1.00623 0.0518929 0) (1.02983 0.0503569 0) (1.05173 0.0487082 0) (1.07191 0.0469742 0) (1.09035 0.0451805 0) (1.10707 0.0433513 0) (1.12212 0.041508 0) (1.13556 0.0396697 0) (0.642721 0.0552034 -5.79597e-21) (0.643971 0.0546869 -5.59041e-22) (0.645215 0.054174 6.43158e-21) (0.646455 0.0536649 -8.03147e-21) (0.64769 0.0531597 1.56235e-21) (0.628647 0.0543132 -6.45536e-21) (0.630015 0.0538016 1.86121e-21) (0.631378 0.0532938 7.06592e-21) (0.632734 0.0527898 -5.90959e-22) (0.634084 0.0522898 1.4384e-21) (0.614599 0.0533641 -1.16428e-21) (0.616088 0.052858 -1.04463e-20) (0.617569 0.0523558 6.88218e-21) (0.619043 0.0518575 -6.16814e-21) (0.620509 0.0513632 -5.31294e-21) (0.59899 0.052851 3.81138e-21) (0.60061 0.0523474 1.58031e-21) (0.602221 0.0518475 6.76837e-21) (0.603822 0.0513516 -1.06031e-20) (0.605413 0.0508597 9.33718e-21) (0.606995 0.0503718 -4.91987e-21) (0.584973 0.0517456 5.05091e-21) (0.586715 0.0512491 -5.16561e-21) (0.588447 0.0507566 -2.7981e-21) (0.590168 0.050268 7.88345e-21) (0.591878 0.0497834 -9.05706e-22) (0.571084 0.0505568 -4.21064e-21) (0.57295 0.0500686 1.26639e-20) (0.574803 0.0495843 -8.37145e-21) (0.576644 0.0491041 2.34898e-21) (0.578472 0.0486279 -5.00655e-21) (0.55736 0.0492856 2.04071e-21) (0.559349 0.0488067 -1.17119e-21) (0.561323 0.0483319 -1.21923e-20) (0.563283 0.047861 3.29169e-21) (0.565229 0.0473942 1.64569e-21) (0.541713 0.0484044 5.34512e-22) (0.543839 0.0479321 1.60716e-21) (0.545949 0.0474637 5.61937e-21) (0.548044 0.0469992 5.01425e-21) (0.550122 0.0465387 -7.23002e-21) (0.552185 0.0460823 -2.629e-21) (0.528309 0.0469573 8.80413e-21) (0.530557 0.0464965 -5.03667e-21) (0.532788 0.0460396 7.79886e-21) (0.535001 0.0455866 1.87267e-21) (0.537197 0.0451376 -2.77887e-21) (0.515184 0.0454277 -8.47818e-21) (0.517552 0.0449794 -8.95038e-22) (0.519902 0.0445351 1.86335e-21) (0.522232 0.0440946 6.36683e-21) (0.524544 0.0436581 3.87531e-21) (0.502375 0.0438164 -3.16787e-22) (0.504862 0.0433819 2.00639e-21) (0.507328 0.0429511 1.26484e-20) (0.509774 0.0425242 -2.14088e-21) (0.512199 0.0421012 1.83385e-21) (0.489921 0.0421248 -2.98667e-21) (0.492524 0.0417051 -4.85259e-21) (0.495104 0.041289 -1.96052e-21) (0.497662 0.0408767 1.09777e-21) (0.500199 0.0404682 -3.08389e-21) (0.475121 0.0407622 2.31127e-21) (0.47786 0.0403546 -2.50163e-21) (0.480575 0.0399506 -8.23366e-21) (0.483267 0.0395502 6.76264e-21) (0.485935 0.0391536 9.05638e-21) (0.488579 0.0387606 -6.92555e-21) (0.463379 0.0388982 -8.48289e-21) (0.466229 0.0385076 1.08033e-21) (0.469053 0.0381204 1.67297e-21) (0.471853 0.0377368 -1.41235e-21) (0.474627 0.0373567 6.65273e-21) (0.452108 0.0369588 1.41155e-20) (0.455064 0.0365862 -2.80465e-21) (0.457994 0.0362168 -7.01368e-21) (0.460897 0.0358509 5.50753e-23) (0.463774 0.0354884 7.11837e-21) (0.441342 0.0349466 3.54537e-21) (0.444401 0.0345929 -6.04745e-21) (0.447432 0.0342424 -3.59251e-21) (0.450435 0.0338951 2.15966e-21) (0.45341 0.0335512 4.83176e-22) (0.431119 0.0328645 -5.16687e-21) (0.434275 0.0325307 1.0561e-20) (0.437402 0.0321999 -1.18978e-20) (0.4405 0.0318723 2.78644e-21) (0.44357 0.0315478 4.7071e-21) (0.42147 0.0307159 2.84094e-22) (0.424719 0.0304029 2.05386e-21) (0.427938 0.0300927 5.49081e-21) (0.431126 0.0297856 -1.21223e-20) (0.434284 0.0294814 6.43226e-21) (0.409061 0.0287984 -3.58709e-21) (0.412429 0.0285043 4.8295e-21) (0.415765 0.0282129 7.22191e-22) (0.419069 0.0279243 -4.75053e-21) (0.422342 0.0276384 2.53766e-21) (0.425584 0.0273553 3.62193e-21) (0.400575 0.026505 -2.26723e-22) (0.404026 0.0262335 9.31203e-22) (0.407443 0.0259647 -9.45916e-22) (0.410827 0.0256983 5.69321e-22) (0.41418 0.0254345 2.20312e-21) (0.392763 0.0241559 -4.27779e-21) (0.396289 0.0239079 -2.70268e-21) (0.399782 0.0236622 3.67957e-21) (0.40324 0.0234189 2.18742e-21) (0.406665 0.023178 4.36283e-22) (0.385651 0.0217555 -5.15866e-23) (0.389247 0.0215317 -7.27123e-23) (0.392807 0.0213099 1.02011e-21) (0.396333 0.0210903 -3.49484e-23) (0.399825 0.0208729 -2.35542e-21) (0.379264 0.0193086 -5.89922e-22) (0.382922 0.0191096 -9.92622e-22) (0.386544 0.0189124 -2.27709e-21) (0.390131 0.0187171 6.25812e-21) (0.393683 0.0185238 -4.46154e-21) (0.373625 0.0168202 3.27311e-21) (0.377338 0.0166465 -4.26763e-21) (0.381015 0.0164744 3.32006e-21) (0.384655 0.016304 -4.06393e-21) (0.38826 0.0161353 1.34915e-21) (0.368753 0.0142952 2.82656e-22) (0.372514 0.0141474 -1.92592e-21) (0.376238 0.0140009 -2.68669e-22) (0.379925 0.0138559 -3.45266e-22) (0.383575 0.0137123 7.55229e-22) (0.364666 0.0117391 1.75709e-21) (0.368467 0.0116176 -5.8157e-22) (0.37223 0.0114972 1.11978e-21) (0.375956 0.0113779 -1.86396e-21) (0.379646 0.0112599 -4.3622e-22) (0.361379 0.00915732 1.2881e-21) (0.365212 0.0090624 8.43148e-24) (0.369007 0.0089684 -2.2709e-21) (0.372765 0.00887531 1.49751e-21) (0.376485 0.00878314 -5.81712e-22) (0.358903 0.0065554 6.82425e-24) (0.36276 0.0064874 -1.21221e-21) (0.366579 0.00642006 1.14705e-21) (0.370361 0.00635337 -7.13886e-22) (0.374105 0.00628735 -1.43078e-22) (0.357247 0.00393903 1.68115e-21) (0.361121 0.00389816 -7.54025e-22) (0.364956 0.00385767 -1.96637e-23) (0.368753 0.00381758 4.18971e-22) (0.372513 0.00377789 -7.99941e-22) (0.356418 0.00131398 -4.96949e-23) (0.3603 0.00130034 2.05954e-22) (0.364143 0.00128683 9.89416e-24) (0.367948 0.00127346 -1.61074e-22) (0.371716 0.00126021 8.0593e-23) ) ; boundaryField { inlet { type uniformFixedValue; uniformValue constant (1 0 0); value nonuniform 0(); } outlet { type pressureInletOutletVelocity; value nonuniform 0(); } cylinder { type fixedValue; value nonuniform 0(); } top { type symmetryPlane; } bottom { type symmetryPlane; } defaultFaces { type empty; } procBoundary35to34 { type processor; value nonuniform List<vector> 189 ( (0.352497 -0.00132775 1.08512e-23) (0.353334 -0.0039803 -9.29469e-22) (0.355006 -0.00662404 9.56991e-22) (0.357507 -0.00925313 2.35603e-21) (0.360827 -0.0118618 -3.40416e-21) (0.364955 -0.0144445 3.43358e-21) (0.369875 -0.0169955 -2.26206e-21) (0.37557 -0.0195096 -2.62347e-22) (0.38202 -0.0219814 1.32138e-21) (0.389203 -0.0244061 4.82543e-21) (0.397092 -0.0267789 7.16572e-22) (0.40566 -0.0290951 2.08375e-21) (0.41819 -0.0310318 -7.77335e-21) (0.41819 -0.0310318 -7.77335e-21) (0.427932 -0.0332014 7.18681e-21) (0.438255 -0.0353036 -2.08992e-22) (0.449124 -0.0373349 -3.89147e-21) (0.460504 -0.0392924 1.59135e-21) (0.472358 -0.0411733 2.91988e-21) (0.487297 -0.0425483 1.27542e-20) (0.487297 -0.0425483 1.27542e-20) (0.499868 -0.0442547 -2.07707e-21) (0.512796 -0.0458797 -1.1528e-21) (0.526043 -0.0474219 6.06112e-22) (0.539571 -0.0488805 -7.26354e-21) (0.555358 -0.0497683 3.67077e-21) (0.555358 -0.0497683 3.67077e-21) (0.569205 -0.0510488 -5.61785e-21) (0.583219 -0.0522459 3.25903e-21) (0.59899 -0.052851 6.3652e-21) (0.59899 -0.052851 6.3652e-21) (0.613102 -0.0538739 4.9802e-21) (0.627272 -0.0548284 2.01325e-21) (0.641468 -0.0557235 1.89355e-21) (0.664588 -0.0569298 0) (0.699345 -0.0577141 0) (0.699345 -0.0577141 0) (0.733393 -0.0587036 0) (0.767507 -0.0593341 0) (0.801392 -0.0596155 0) (0.834769 -0.0595648 0) (0.867379 -0.0592009 0) (0.898987 -0.0585464 0) (0.929382 -0.0576275 0) (0.958385 -0.0564725 0) (0.985845 -0.0551117 0) (1.01164 -0.0535761 0) (1.0357 -0.0518972 0) (1.05795 -0.0501055 0) (1.07837 -0.0482308 0) (1.09697 -0.0463007 0) (1.11377 -0.0443408 0) (1.12882 -0.042374 0) (1.1422 -0.0404202 0) (1.15399 -0.0384966 0) (1.16427 -0.0366173 0) (1.17317 -0.0347933 0) (1.18078 -0.0330331 0) (1.18723 -0.0313426 0) (1.19262 -0.0297253 0) (1.19706 -0.0281829 0) (1.20066 -0.0267153 0) (1.20353 -0.0253213 0) (1.20575 -0.0239983 0) (1.20741 -0.0227431 0) (1.2086 -0.021552 0) (1.20938 -0.0204207 0) (1.20982 -0.0193451 0) (1.20998 -0.0183207 0) (1.2099 -0.0173434 0) (1.20964 -0.016409 0) (1.20922 -0.0155137 0) (1.20869 -0.0146539 0) (1.20807 -0.0138263 0) (1.20738 -0.0130278 0) (1.20665 -0.0122557 0) (1.20589 -0.0115075 0) (1.20512 -0.0107808 0) (1.20435 -0.0100738 0) (1.20359 -0.00938446 0) (1.20285 -0.00871119 0) (1.20214 -0.00805246 0) (1.20146 -0.00740688 0) (1.20081 -0.00677316 0) (1.20021 -0.00615012 0) (1.19965 -0.00553665 0) (1.19915 -0.00493168 0) (1.19869 -0.00433423 0) (1.19829 -0.00374332 0) (1.19794 -0.00315804 0) (1.19765 -0.00257747 0) (1.19741 -0.00200075 0) (1.19723 -0.00142699 0) (1.19712 -0.000855349 0) (1.19706 -0.000284973 0) (0.664588 0.0569298 0) (0.698522 0.0582372 0) (0.732826 0.0592231 0) (0.767189 0.0598456 0) (0.801315 0.0601146 0) (0.834921 0.0600476 0) (0.867746 0.0596637 -2.35559e-11) (0.89955 0.0589862 -2.36704e-11) (0.930123 0.0580414 0) (0.959282 0.0568586 0) (0.986877 0.0554683 0) (1.01279 0.0539024 -2.41035e-11) (1.03693 0.0521927 -2.42017e-11) (1.05925 0.0503705 0) (1.07972 0.0484658 0) (1.09835 0.0465067 0) (1.11516 0.0445192 0) (1.13022 0.0425264 0) (1.14358 0.0405484 0) (1.15533 0.0386026 0) (1.16559 0.036703 0) (1.17444 0.0348607 0) (1.18201 0.0330842 0) (1.1884 0.0313791 0) (1.19374 0.029749 0) (1.19813 0.0281955 0) (1.20168 0.0267182 0) (1.20449 0.0253157 0) (1.20666 0.0239855 0) (1.20828 0.0227241 0) (1.20942 0.0215276 0) (1.21016 0.0203919 0) (1.21056 0.0193124 0) (1.21068 0.0182849 0) (1.21058 0.017305 0) (1.21028 0.0163685 0) (1.20984 0.0154715 0) (1.20928 0.0146105 0) (1.20864 0.013782 0) (1.20793 0.0129831 0) (1.20718 0.0122108 0) (1.20641 0.0114628 0) (1.20563 0.0107366 0) (1.20484 0.0100304 0) (1.20407 0.00934214 0) (1.20332 0.00867023 0) (1.2026 0.00801312 0) (1.20191 0.00736941 0) (1.20125 0.0067378 0) (1.20065 0.00611708 0) (1.20008 0.00550612 0) (1.19957 0.00490387 0) (1.19911 0.00430928 0) (1.1987 0.0037214 0) (1.19835 0.00313927 0) (1.19805 0.00256196 0) (1.19782 0.00198859 0) (1.19764 0.00141826 0) (1.19752 0.000850086 0) (1.19746 0.000283215 0) (0.641468 0.0557235 -1.89286e-21) (0.627272 0.0548284 -1.97801e-21) (0.613102 0.0538739 -5.20159e-21) (0.613102 0.0538739 -5.20159e-21) (0.597361 0.0533585 1.07531e-20) (0.583219 0.0522459 -2.92489e-21) (0.569205 0.0510488 5.60433e-21) (0.555358 0.0497683 -3.74574e-21) (0.555358 0.0497683 -3.74574e-21) (0.539571 0.0488805 7.32296e-21) (0.526043 0.0474219 3.57476e-22) (0.512796 0.0458797 2.4869e-22) (0.499868 0.0442547 2.95299e-21) (0.487297 0.0425483 -1.32383e-20) (0.487297 0.0425483 -1.32383e-20) (0.472358 0.0411733 -2.98259e-21) (0.460504 0.0392924 -1.6659e-21) (0.449124 0.0373349 3.18984e-21) (0.438255 0.0353036 6.65528e-22) (0.427932 0.0332014 -7.42032e-21) (0.41819 0.0310318 8.0888e-21) (0.41819 0.0310318 8.0888e-21) (0.40566 0.0290951 -1.84057e-21) (0.397092 0.0267789 -6.80711e-22) (0.389203 0.0244061 -5.00305e-21) (0.38202 0.0219814 -1.29987e-21) (0.37557 0.0195096 3.33555e-22) (0.369875 0.0169955 2.28111e-21) (0.364955 0.0144445 -3.87529e-21) (0.360827 0.0118618 3.63e-21) (0.357507 0.00925313 -2.39763e-21) (0.355006 0.00662404 -9.13328e-22) (0.353334 0.0039803 9.92181e-22) (0.352497 0.00132775 -3.86971e-23) ) ; } procBoundary35to36 { type processor; value nonuniform List<vector> 191 ( (0.375445 -0.0012471 -5.31252e-23) (0.376235 -0.0037386 1.3952e-22) (0.377811 -0.00622199 5.20305e-22) (0.380169 -0.0086919 -2.32528e-22) (0.383299 -0.011143 -3.85893e-22) (0.38719 -0.0135702 -2.02742e-22) (0.391829 -0.0159683 3.46134e-21) (0.3972 -0.0183323 3.15667e-22) (0.403283 -0.0206576 4.93485e-21) (0.410057 -0.0229394 -5.47266e-21) (0.410057 -0.0229394 -5.47266e-21) (0.420787 -0.0249147 -1.38789e-22) (0.428795 -0.027075 -2.24785e-21) (0.437412 -0.0291801 -3.23034e-21) (0.44661 -0.0312264 -4.99807e-21) (0.456358 -0.0332105 5.84406e-22) (0.466625 -0.0351294 -1.59965e-21) (0.477376 -0.0369803 1.13393e-21) (0.477376 -0.0369803 1.13393e-21) (0.4912 -0.0383713 -6.26635e-22) (0.502713 -0.0400635 9.34569e-21) (0.514603 -0.041682 -9.91407e-21) (0.526836 -0.0432255 -8.18222e-21) (0.539375 -0.0446926 1.17961e-21) (0.539375 -0.0446926 1.17961e-21) (0.554232 -0.04563 7.5956e-21) (0.567161 -0.0469315 -9.20292e-22) (0.580287 -0.0481558 5.34394e-21) (0.593577 -0.0493029 1.2775e-21) (0.593577 -0.0493029 1.2775e-21) (0.608568 -0.049888 -3.8219e-21) (0.621966 -0.050873 -2.47553e-22) (0.635427 -0.0517938 -7.50691e-22) (0.64892 -0.0526584 2.86236e-21) (0.64892 -0.0526584 2.86236e-21) (0.672088 -0.0533456 0) (0.704289 -0.0546423 0) (0.73687 -0.0556443 0) (0.769547 -0.056313 0) (0.802044 -0.0566567 0) (0.834101 -0.0566908 0) (0.865475 -0.0564323 0) (0.895944 -0.0559014 0) (0.925309 -0.0551214 0) (0.953399 -0.0541177 0) (0.98007 -0.0529174 0) (1.00521 -0.0515483 0) (1.02872 -0.0500389 0) (1.05055 -0.0484169 0) (1.07067 -0.0467091 0) (1.08908 -0.0449412 0) (1.10578 -0.0431366 0) (1.12083 -0.0413168 0) (1.13428 -0.0395006 0) (1.1462 -0.0377043 0) (1.15667 -0.0359417 0) (1.1658 -0.0342237 0) (1.17367 -0.0325591 0) (1.1804 -0.030954 0) (1.18608 -0.0294128 0) (1.19082 -0.0279376 0) (1.19472 -0.0265292 0) (1.19788 -0.025187 0) (1.20038 -0.0239093 0) (1.20231 -0.0226937 0) (1.20375 -0.021537 0) (1.20477 -0.0204357 0) (1.20543 -0.0193861 0) (1.20578 -0.0183842 0) (1.20589 -0.0174262 0) (1.20579 -0.0165084 0) (1.20553 -0.0156272 0) (1.20514 -0.0147792 0) (1.20464 -0.0139612 0) (1.20407 -0.0131703 0) (1.20344 -0.012404 0) (1.20277 -0.0116597 0) (1.20209 -0.0109354 0) (1.20139 -0.0102289 0) (1.2007 -0.00953869 0) (1.20002 -0.00886299 0) (1.19936 -0.00820042 0) (1.19873 -0.00754963 0) (1.19813 -0.00690944 0) (1.19757 -0.00627873 0) (1.19705 -0.00565648 0) (1.19658 -0.00504172 0) (1.19615 -0.00443354 0) (1.19577 -0.00383109 0) (1.19544 -0.00323354 0) (1.19517 -0.0026401 0) (1.19494 -0.00204999 0) (1.19478 -0.00146245 0) (1.19467 -0.000876736 0) (1.19461 -0.000292123 0) (1.14746 0.037853 0) (1.15791 0.0360715 0) (1.167 0.0343363 0) (1.17483 0.0326561 0) (1.18151 0.031037 0) (1.18715 0.0294832 0) (1.19184 0.0279968 0) (1.1957 0.0265785 0) (1.19881 0.0252276 0) (1.20126 0.0239422 0) (1.20315 0.0227198 0) (1.20455 0.0215571 0) (1.20553 0.0204505 0) (1.20615 0.0193962 0) (1.20648 0.0183902 0) (1.20655 0.0174286 0) (1.20643 0.0165076 0) (1.20614 0.0156236 0) (1.20572 0.0147732 0) (1.20521 0.0139531 0) (1.20462 0.0131605 0) (1.20397 0.0123926 0) (1.20329 0.0116471 0) (1.20259 0.0109218 0) (1.20188 0.0102147 0) (1.20118 0.00952401 0) (1.20049 0.00884809 0) (1.19983 0.00818551 0) (1.19919 0.00753493 0) (1.19858 0.00689514 0) (1.19801 0.00626502 0) (1.19749 0.00564353 0) (1.19701 0.00502969 0) (1.19657 0.00442258 0) (1.19619 0.00382133 0) (1.19586 0.00322509 0) (1.19558 0.00263305 0) (1.19536 0.00204442 0) (1.19519 0.00145842 0) (1.19508 0.000874305 0) (1.19502 0.000291309 0) (0.672088 0.0533456 0) (0.64892 0.0526584 -2.8741e-21) (0.704289 0.0546423 0) (0.73687 0.0556443 0) (0.769547 0.056313 0) (0.802044 0.0566567 0) (0.834101 0.0566908 0) (0.865475 0.0564323 0) (0.895944 0.0559014 0) (0.925309 0.0551214 0) (0.953399 0.0541177 0) (0.98007 0.0529174 0) (1.00521 0.0515483 0) (1.02872 0.0500389 0) (1.05055 0.0484169 0) (1.07067 0.0467091 0) (1.08908 0.0449412 0) (1.10578 0.0431366 0) (1.12083 0.0413168 0) (1.14746 0.037853 0) (1.13428 0.0395006 0) (0.64892 0.0526584 -2.8741e-21) (0.635427 0.0517938 7.93086e-22) (0.621966 0.050873 7.66331e-23) (0.608568 0.049888 4.00362e-21) (0.593577 0.0493029 -1.21002e-21) (0.593577 0.0493029 -1.21002e-21) (0.580287 0.0481558 -5.31168e-21) (0.567161 0.0469315 1.11211e-21) (0.554232 0.04563 -7.97164e-21) (0.539375 0.0446926 -7.24962e-22) (0.539375 0.0446926 -7.24962e-22) (0.526836 0.0432255 7.75609e-21) (0.514603 0.041682 9.83914e-21) (0.502713 0.0400635 -9.67522e-21) (0.4912 0.0383713 9.54612e-22) (0.477376 0.0369803 -1.36506e-21) (0.477376 0.0369803 -1.36506e-21) (0.466625 0.0351294 1.80728e-21) (0.456358 0.0332105 -8.37771e-22) (0.44661 0.0312264 5.23681e-21) (0.437412 0.0291801 3.23842e-21) (0.428795 0.027075 2.31302e-21) (0.417499 0.0251733 3.34579e-21) (0.417499 0.0251733 3.34579e-21) (0.410057 0.0229394 5.26052e-21) (0.403283 0.0206576 -4.81558e-21) (0.3972 0.0183323 -4.97777e-22) (0.391829 0.0159683 -3.18144e-21) (0.38719 0.0135702 2.40392e-22) (0.383299 0.011143 7.02906e-23) (0.380169 0.0086919 2.45739e-22) (0.377811 0.00622198 -4.149e-22) (0.376235 0.0037386 -1.72444e-22) (0.375445 0.0012471 6.90265e-23) ) ; } } // ************************************************************************* //
C++
CL
2a4a68bcb1f8c5bda84ff1dc465729d223aa058c949152b2ee41d09d4befd62e
/* * Gpio.h * * Created on: 28-okt.-2016 * Author: lieven2 */ #ifndef GPIO_H_ #define GPIO_H_ #include <stdint.h> #define PA(x) (0x10000+(x)) #define PB(x) (0x20000+(x)) #define PC(x) (0x30000+(x)) #define PORT(x) ((x & 0x30000)>>16) #define PIN(x) (x & 0xFFFF) class Gpio { public: typedef void (*InterruptHandler)(void); typedef enum { GPIO_OUTPUT, GPIO_INPUT } Mode; typedef enum { GPIO_EDGE_RISING, GPIO_EDGE_FALLING, GPIO_EDGE_BOTH } Edge; Gpio(uint32_t pin); virtual ~Gpio(); void setMode(Mode mode); void setInterrupt(Edge edge, InterruptHandler func); void setup(); void write(uint8_t bit); uint8_t read(); InterruptHandler _handler; private: uint32_t _port; uint16_t _pin; Mode _mode; Edge _edge; }; #endif /* GPIO_H_ */
C++
CL
64b9b30d9b5146963a0fa62ece3c389892223b621ce4bdd8f64a508c143d2ab0
#ifndef GARBAGE_COLLECTION_H #define GARBAGE_COLLECTION_H 10000 #include <sys/types.h> #include "ssd.hh" #include "ftl.hh" #include "common.hh" STATE find_victim_block( ssd_info *ssd,local * location); STATE greedy_algorithm(ssd_info * ssd, local * location); STATE fifo_algorithm(ssd_info * ssd, local * location); STATE windowed_algorithm(ssd_info * ssd, local * location); STATE RGA_algorithm(ssd_info * ssd, local * location); STATE RANDOM_algorithm(ssd_info * ssd, local * location); STATE RANDOM_p_algorithm(ssd_info * ssd, local * location); STATE RANDOM_pp_algorithm(ssd_info * ssd, local * location); unsigned int best_cost( ssd_info * ssd, plane_info * the_plane, int active_block , int cold_active_block); int64_t compute_moving_cost(ssd_info * ssd, const local * location, const local * twin_location, int approach); int erase_block(ssd_info * ssd,const local * location); bool update_priority(ssd_info * ssd, unsigned int channel, unsigned int lun); STATE move_page(ssd_info * ssd, const local * location, gc_operation * gc_node); STATE add_gc_node(ssd_info * ssd, gc_operation * gc_node); int plane_emergency_state(ssd_info * ssd, const local * location); void update_subreq_state(ssd_info * ssd, const local * location, int64_t next_state_time); sub_request * create_gc_sub_request( ssd_info * ssd, const local * location, int operation, gc_operation * gc_node); bool Schedule_GC(ssd_info * ssd, sub_request * sub); void pre_process_gc(ssd_info * ssd, const local * location); STATE delete_gc_node(ssd_info * ssd, gc_operation * gc_node); #endif
C++
CL
7e7a00aa6e1e5bb5c2f8ec62dd9dd24421acb2b2aec00017f87ad4858b982ac7
/* * Copyright 1999-2004 The Apache Software Foundation. * * 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. */ #if !defined(ATTRIBUTEVECTORENTRYEXTENDED_HEADER_GUARD_1357924680) #define ATTRIBUTEVECTORENTRYEXTENDED_HEADER_GUARD_1357924680 // Base include file. Must be first. #include <xalanc/PlatformSupport/PlatformSupportDefinitions.hpp> #include <xalanc/PlatformSupport/AttributeVectorEntry.hpp> XALAN_CPP_NAMESPACE_BEGIN class XALAN_PLATFORMSUPPORT_EXPORT AttributeVectorEntryExtended : public AttributeVectorEntry { public: AttributeVectorEntryExtended( const XMLChVectorType& theName, const XMLChVectorType& theValue, const XMLChVectorType& theType, const XMLChVectorType& theURI = XMLChVectorType(), const XMLChVectorType& theLocalName = XMLChVectorType()) : AttributeVectorEntry(theName, theValue, theType), m_uri(theURI), m_localName(theLocalName) { } AttributeVectorEntryExtended( const XMLCh* theName, const XMLCh* theValue, const XMLCh* theType, const XMLCh* theURI, const XMLCh* theLocalName) : AttributeVectorEntry(theName, theValue, theType), m_uri(theURI, theURI + length(theURI) + 1), m_localName(theLocalName, theLocalName + length(theLocalName) + 1) { } AttributeVectorEntryExtended( const XMLCh* theName, const XMLCh* theValue, const XMLCh* theType) : AttributeVectorEntry(theName, theValue, theType), m_uri(), m_localName() { } AttributeVectorEntryExtended() : AttributeVectorEntry(), m_uri(), m_localName() { } virtual ~AttributeVectorEntryExtended() { } void clear() { AttributeVectorEntry::clear(); m_uri.clear(); m_localName.clear(); } XMLChVectorType m_uri; XMLChVectorType m_localName; }; XALAN_CPP_NAMESPACE_END #endif // ATTRIBUTEVECTORENTRY_HEADER_GUARD_1357924680
C++
CL
28f9f878364c4dd68bd6af6a589eafc43432cc882dc02edc12ac4d9529b67808
// This file is part of the Acts project. // // Copyright (C) 2017 CERN for the benefit of the Acts project // // This Source Code Form is subject to the terms of the Mozilla Public // License, v. 2.0. If a copy of the MPL was not distributed with this // file, You can obtain one at http://mozilla.org/MPL/2.0/. #pragma once #include "Acts/MagneticField/InterpolatedBFieldMap.hpp" #include "Acts/Utilities/Logger.hpp" #include "Acts/Utilities/Units.hpp" #include "Acts/Utilities/detail/Axis.hpp" #include "Acts/Utilities/detail/Grid.hpp" namespace FW { namespace BField { namespace txt { /// Method to setup the FieldMapper /// @param localToGlobalBin Function mapping the local bins of r,z to the /// global /// bin of the map magnetic field value e.g.: we have small grid with the /// values: r={2,3}, z ={4,5}, the corresponding indices are i(r) and j(z), /// the /// globalIndex is M and the field map is: ///|| r | i || z | j || |B(r,z)| || M || /// ----------------------------------- ///|| 2 | 0 || 4 | 0 || 2.323 || 0 || ///|| 2 | 0 || 5 | 1 || 2.334 || 1 || ///|| 3 | 1 || 4 | 0 || 2.325 || 2 || ///|| 3 | 1 || 5 | 1 || 2.331 || 3 || /// /// @code /// In this case the function would look like: /// [](std::array<size_t, 2> binsRZ, std::array<size_t, 2> nBinsRZ) { /// return (binsRZ.at(0) * nBinsRZ.at(1) + binsRZ.at(1)); /// } /// @endcode /// @param[in] fieldMapFile Path to file containing field map in txt format /// @param[in] lengthUnit The unit of the grid points /// @param[in] BFieldUnit The unit of the magnetic field /// @param[in] nPoints Extimate of number of grid points in field map needed /// for allocation /// @note This information is only used as a hint for the required size of /// the internal vectors. A correct value is not needed, but will help /// to speed up the field map initialization process. /// @param[in] firstOctant Flag if set to true indicating that only the /// first /// quadrant of the grid points and the BField values has been given and /// that /// the BFieldMap should be created symmetrically for all quadrants. /// e.g. we have the grid values r={0,1} with BFieldValues={2,3} on the r /// axis. /// If the flag is set to true the r-axis grid values will be set to /// {-1,0,1} /// and the BFieldValues will be set to {3,2,3}. Acts::InterpolatedBFieldMapper< Acts::detail::Grid<Acts::Vector2D, Acts::detail::EquidistantAxis, Acts::detail::EquidistantAxis>> fieldMapperRZ( std::function<size_t(std::array<size_t, 2> binsRZ, std::array<size_t, 2> nBinsRZ)> localToGlobalBin, std::string fieldMapFile = "", double lengthUnit = Acts::units::_mm, double BFieldUnit = Acts::units::_T, size_t nPoints = 1000, bool firstOctant = false); /// Method to setup the FieldMapper /// @param localToGlobalBin Function mapping the local bins of x,y,z to the /// global bin of the map magnetic field value e.g.: we have small grid with /// the /// values: x={2,3}, y={3,4}, z ={4,5}, the corresponding indices are i(x), /// j(y) /// and z(k), the globalIndex is M and the field map is: ///|| x | i || y | j || z | k || |B(x,y,z)| || M || /// -------------------------------------------- ///|| 2 | 0 || 3 | 0 || 4 | 0 || 2.323 || 0 || ///|| 2 | 0 || 3 | 0 || 5 | 1 || 2.334 || 1 || ///|| 2 | 0 || 4 | 1 || 4 | 0 || 2.325 || 2 || ///|| 2 | 0 || 4 | 1 || 5 | 1 || 2.331 || 3 || ///|| 3 | 1 || 3 | 0 || 4 | 0 || 2.323 || 4 || ///|| 3 | 1 || 3 | 0 || 5 | 1 || 2.334 || 5 || ///|| 3 | 1 || 4 | 1 || 4 | 0 || 2.325 || 6 || ///|| 3 | 1 || 4 | 1 || 5 | 1 || 2.331 || 7 || /// /// @code /// In this case the function would look like: /// [](std::array<size_t, 3> binsXYZ, std::array<size_t, 3> nBinsXYZ) { /// return (binsXYZ.at(0) * (nBinsXYZ.at(1) * nBinsXYZ.at(2)) /// + binsXYZ.at(1) * nBinsXYZ.at(2) /// + binsXYZ.at(2)); /// } /// @endcode /// @param[in] fieldMapFile Path to file containing field map in txt format /// @param[in] lengthUnit The unit of the grid points /// @param[in] BFieldUnit The unit of the magnetic field /// @param[in] nPoints Extimate of number of grid points in field map needed /// for allocation /// @note This information is only used as a hint for the required size of /// the internal vectors. A correct value is not needed, but will help /// to speed up the field map initialization process. /// @param[in] firstOctant Flag if set to true indicating that only the /// first /// octant of the grid points and the BField values has been given and that /// the BFieldMap should be created symmetrically for all quadrants. /// e.g. we have the grid values z={0,1} with BFieldValues={2,3} on the r /// axis. /// If the flag is set to true the z-axis grid values will be set to /// {-1,0,1} /// and the BFieldValues will be set to {3,2,3}. Acts::InterpolatedBFieldMapper< Acts::detail::Grid<Acts::Vector3D, Acts::detail::EquidistantAxis, Acts::detail::EquidistantAxis, Acts::detail::EquidistantAxis>> fieldMapperXYZ( std::function<size_t(std::array<size_t, 3> binsXYZ, std::array<size_t, 3> nBinsXYZ)> localToGlobalBin, std::string fieldMapFile = "", double lengthUnit = Acts::units::_mm, double BFieldUnit = Acts::units::_T, size_t nPoints = 1000, bool firstOctant = false); } // namespace txt namespace root { /// Method to setup the FieldMapper /// @param localToGlobalBin Function mapping the local bins of r,z to the /// global /// bin of the map magnetic field value e.g.: we have small grid with the /// values: r={2,3}, z ={4,5}, the corresponding indices are i(r) and j(z), /// the /// globalIndex is M and the field map is: ///|| r | i || z | j || |B(r,z)| || M || /// ----------------------------------- ///|| 2 | 0 || 4 | 0 || 2.323 || 0 || ///|| 2 | 0 || 5 | 1 || 2.334 || 1 || ///|| 3 | 1 || 4 | 0 || 2.325 || 2 || ///|| 3 | 1 || 5 | 1 || 2.331 || 3 || /// /// @code /// In this case the function would look like: /// [](std::array<size_t, 2> binsRZ, std::array<size_t, 2> nBinsRZ) { /// return (binsRZ.at(0) * nBinsRZ.at(1) + binsRZ.at(1)); /// } /// @endcode /// @param[in] fieldMapFile Path to file containing field map in txt format /// @param[in] treeName The name of the root tree /// @param[in] lengthUnit The unit of the grid points /// @param[in] BFieldUnit The unit of the magnetic field /// @param[in] firstQuadrant Flag if set to true indicating that only the /// first /// quadrant of the grid points and the BField values has been given and /// that /// the BFieldMap should be created symmetrically for all quadrants. /// e.g. we have the grid values r={0,1} with BFieldValues={2,3} on the r /// axis. /// If the flag is set to true the r-axis grid values will be set to /// {-1,0,1} /// and the BFieldValues will be set to {3,2,3}. Acts::InterpolatedBFieldMapper< Acts::detail::Grid<Acts::Vector2D, Acts::detail::EquidistantAxis, Acts::detail::EquidistantAxis>> fieldMapperRZ( std::function<size_t(std::array<size_t, 2> binsRZ, std::array<size_t, 2> nBinsRZ)> localToGlobalBin, std::string fieldMapFile = "", std::string treeName = "", double lengthUnit = Acts::units::_mm, double BFieldUnit = Acts::units::_T, bool firstOctant = false); /// Method to setup the FieldMapper /// @param localToGlobalBin Function mapping the local bins of x,y,z to the /// global bin of the map magnetic field value e.g.: we have small grid with /// the /// values: x={2,3}, y={3,4}, z ={4,5}, the corresponding indices are i(x), /// j(y) /// and z(k), the globalIndex is M and the field map is: ///|| x | i || y | j || z | k || |B(x,y,z)| || M || /// -------------------------------------------- ///|| 2 | 0 || 3 | 0 || 4 | 0 || 2.323 || 0 || ///|| 2 | 0 || 3 | 0 || 5 | 1 || 2.334 || 1 || ///|| 2 | 0 || 4 | 1 || 4 | 0 || 2.325 || 2 || ///|| 2 | 0 || 4 | 1 || 5 | 1 || 2.331 || 3 || ///|| 3 | 1 || 3 | 0 || 4 | 0 || 2.323 || 4 || ///|| 3 | 1 || 3 | 0 || 5 | 1 || 2.334 || 5 || ///|| 3 | 1 || 4 | 1 || 4 | 0 || 2.325 || 6 || ///|| 3 | 1 || 4 | 1 || 5 | 1 || 2.331 || 7 || /// /// @code /// In this case the function would look like: /// [](std::array<size_t, 3> binsXYZ, std::array<size_t, 3> nBinsXYZ) { /// return (binsXYZ.at(0) * (nBinsXYZ.at(1) * nBinsXYZ.at(2)) /// + binsXYZ.at(1) * nBinsXYZ.at(2) /// + binsXYZ.at(2)); /// } /// @endcode /// @param[in] fieldMapFile Path to file containing field map in txt format /// @param[in] treeName The name of the root tree /// @param[in] lengthUnit The unit of the grid points /// @param[in] BFieldUnit The unit of the magnetic field /// @param[in] firstOctant Flag if set to true indicating that only the /// first /// octant of the grid points and the BField values has been given and that /// the BFieldMap should be created symmetrically for all quadrants. /// e.g. we have the grid values z={0,1} with BFieldValues={2,3} on the r /// axis. /// If the flag is set to true the z-axis grid values will be set to /// {-1,0,1} /// and the BFieldValues will be set to {3,2,3}. Acts::InterpolatedBFieldMapper< Acts::detail::Grid<Acts::Vector3D, Acts::detail::EquidistantAxis, Acts::detail::EquidistantAxis, Acts::detail::EquidistantAxis>> fieldMapperXYZ( std::function<size_t(std::array<size_t, 3> binsXYZ, std::array<size_t, 3> nBinsXYZ)> localToGlobalBin, std::string fieldMapFile = "", std::string treeName = "", double lengthUnit = Acts::units::_mm, double BFieldUnit = Acts::units::_T, bool firstOctant = false); } // namespace root } // namespace BField } // namespace FW
C++
CL
22a7049407c760a7c2c246f7c647db8d54107db10189a285bf1dec67e7b3f35d
// CtlBd_Function.cpp: implementation of the CCtlBd_Function class. // ////////////////////////////////////////////////////////////////////// #include "stdafx.h" #include "handler.h" #include "CtlBd_Function.h" #include "Cmmsdk.h" #include "CmmsdkDef.h" #include "CtlBd_Variable.h" #include "ComizoaPublic.h" #include "FastechPublic_IO.h" //#include "FAS_HSSI.h" #include "math.h" #include "PublicFunction.h" #include "Variable.h" #include "AlgMemory.h" #ifdef _DEBUG #undef THIS_FILE static char THIS_FILE[]=__FILE__; #define new DEBUG_NEW #endif ////////////////////////////////////////////////////////////////////// // Construction/Destruction ////////////////////////////////////////////////////////////////////// CCtlBd_Function CtlBdFunc; CCtlBd_Function::CCtlBd_Function() { } CCtlBd_Function::~CCtlBd_Function() { //st_ctlbd.n_TotalMotBoard_Number } int CCtlBd_Function::Board_Initialize(int n_mode) { int nRet = 0; /////////////////////////////////////////////////////////////////////////////////////////////////////// //Motor Board Initialize /////////////////////////////////////////////////////////////////////////////////////////////////////// /* if(CTLBD_MOTBD_TYPE == 0) //0:파스텍 보드를 사용하는 장비이면, 1:커미조아 모터를 사용하는 장비 { // st_ctlbd.n_TotalMotBoard_Number = 3; //모터보드가 3개 있다 // st_ctlbd.n_TotalMotorAxis_Number= 18; //모터의 총 수량은 18개이다 // st_ctlbd.n_MotorAxis_Number[0] = 8; //0번 모터보드는 8축용 보드이다 // st_ctlbd.n_MotorAxis_Number[1] = 6; //1번 모터보드는 6축용 보드이다 // st_ctlbd.n_MotorAxis_Number[2] = 4; //2번 모터보드는 4축용 보드이다 } else if(CTLBD_MOTBD_TYPE == 1) //1:커미조아 보드를 사용하는 장비이면, 1:커미조아 모터를 사용하는 장비 { }*/ return RET_GOOD; } int CCtlBd_Function::Robot_Clash_Safety_Check(int n_Mode, int n_SourceAxis, int n_ReferenceAxis, double d_Safety_Gap, double d_TargetPos) {//d_Safety_Gap = 300; //300mm 이상 떨어져 있어야 한다 //DC Loading 사이트 //n_Mode => 0: 모터 이동전 순수하게 체크만 하는 상태, 1: 모터가 이동중일때 체크하는 상태 int nRet = RET_ERROR; return nRet; } //////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Inposition 생략 및 거리별 속도를 관리한다 //////////////////////////////////////////////////////////////////////////////////////////////////////////////// int CCtlBd_Function::MotorSpeed_Control(int n_Axis, double d_CurrentPos, double d_TargetPos, double * dp_Speed) { double dCurrentPos = 0, dTargetPos = 0, dVal =0, d_abs_val = 0, dAccDecTime=0; // if(n_Axis == M_DCLDRBT_Z || n_Axis == M_DCULDRBT_Z || n_Axis == M_ULDRBT_Z) // { // dCurrentPos = COMI.Get_MotCurrentPos(n_Axis); // // //목표위치 계산 방법은 ==> 현재위치 - 목표이동 위치 이다 // dVal = dCurrentPos - d_TargetPos; // if(st_motor[n_Axis].d_pos[0] >= d_TargetPos) //P_DCLDRBT_Z_SAFETY == 0 ,목표 지점이 안전위치와 같으면 정해진 속도로 이동 // { // dp_Speed[0] = st_motor[n_Axis].d_spd_vel[0]; dp_Speed[1] = st_motor[n_Axis].d_spd_vel[1]; dp_Speed[2] = st_motor[n_Axis].d_spd_vel[2]; //가속 펄수 값은 9,000,000 이다 // //UP할때는 Inposition를 보자 말자 // COMI.Set_Motor_IO_Property(n_Axis, cmINP_EN, cmFALSE); //cmINP_EN=9 //cmFALSE = 0 INP 비활성, cmTRUE = 1 INP 활성 // } // else if(dVal > 0) //먼 위치에서 가까운 위치(홈 위치) 로 이동했을때는 + 값 발생 , 모터가 UP 할 때 발생 // { // //원래 셋팅되어있는 값 사용 // //650,000 13,000,000 13,000,000 ==> 16mm 이동하는데 65ms 소요 // //300,000 9,000000 9,000000 ==> 16mm 이동하는데 80ms 소요 // dp_Speed[0] = st_motor[n_Axis].d_spd_vel[0]; dp_Speed[1] = st_motor[n_Axis].d_spd_vel[1]; dp_Speed[2] = st_motor[n_Axis].d_spd_vel[2]; //가속 펄수 값은 9,000,000 이다 // // //UP할때 또는 정확한 목표지점으로 가지 않아도 되는 조건이면 Inposition를 보지 말자 // COMI.Set_Motor_IO_Property(n_Axis, cmINP_EN, cmFALSE); //cmINP_EN=9 //cmFALSE = 0 INP 비활성, cmTRUE = 1 INP 활성 // } //12mm 이하로 내려갈 때 // else // {/* // if(n_Axis == M_DCLDRBT_Z || n_Axis == M_DCULDRBT_Z ) // { // if(dVal > -12) //-1 ~ -19 DC로디로봇이 DC 소켓에 놓을때 - 값 발생 //홈 위치에서 증가 방향으로 이동하려면 - 값이 발생한다 // {//dAccPPS = (d_work - st_motor[n_Axis].d_initial_speed) / (d_accel_time / 1000); // //dAccDecTime = (d_work - st_motor[n_Axis].d_initial_speed) / (dAccPPS / 1000); // dAccDecTime = (300000 - st_motor[n_Axis].d_initial_speed) / (5000000 / 1000); //60ms // dp_Speed[0] = 300000; dp_Speed[1] = dAccDecTime; dp_Speed[2] = dAccDecTime; //가속 펄수 값은 9,000,000 이다 // // COMI.Set_Motor_IO_Property(n_Axis, cmINP_EN, cmTRUE); //cmINP_EN=9 //cmFALSE = 0 INP 비활성, cmTRUE = 1 INP 활성 // } // //20mm 이하로 내려갈 때 // else if(dVal > -38) //-1 ~ -19 DC로디로봇이 DC 소켓에 놓을때 - 값 발생 //홈 위치에서 증가 방향으로 이동하려면 - 값이 발생한다 // {//dAccPPS = (d_work - st_motor[n_Axis].d_initial_speed) / (d_accel_time / 1000); // //dAccDecTime = (d_work - st_motor[n_Axis].d_initial_speed) / (dAccPPS / 1000); // dAccDecTime = (300000 - st_motor[n_Axis].d_initial_speed) / (9000000 / 1000); //dAccDecTime = 33 ms // dp_Speed[0] = 300000; dp_Speed[1] = dAccDecTime; dp_Speed[2] = dAccDecTime; //가속 펄수 값은 9,000,000 이다 // // COMI.Set_Motor_IO_Property(n_Axis, cmINP_EN, cmTRUE); //cmINP_EN=9 //cmFALSE = 0 INP 비활성, cmTRUE = 1 INP 활성 // } //20mm이상 내려갈때 // else //if(dVal < -38) //-20 이하 로딩로봇이 트레이에서 집을때, 언로딩 로봇이 인서트 버퍼 bottom에 놓을때 발생 // { // //dAccDecTime = (650000 - st_motor[n_Axis].d_initial_speed) / (12000000 / 1000); //dAccDecTime = 300 ms // //dp_Speed[0] = 650000; dp_Speed[1] = dAccDecTime; dp_Speed[2] = dAccDecTime; //가속 펄수 값은 9,000,000 이다 // dAccDecTime = (st_motor[n_Axis].d_spd_vel[0] - st_motor[n_Axis].d_initial_speed) / (12000000 / 1000); //dAccDecTime = 300 ms // dp_Speed[0] = st_motor[n_Axis].d_spd_vel[0]; dp_Speed[1] = dAccDecTime; dp_Speed[2] = dAccDecTime; //가속 펄수 값은 9,000,000 이다 // // COMI.Set_Motor_IO_Property(n_Axis, cmINP_EN, cmTRUE); //cmINP_EN=9 //cmFALSE = 0 INP 비활성, cmTRUE = 1 INP 활성 // } // } // */ // if(n_Axis == M_DCLDRBT_Z) // { // if(d_TargetPos == st_motor[M_DCLDRBT_Z].d_pos[P_DCLDRBT_Z_LDPLATE_PICK]) // { // //091012 dp_Speed[0] = 650000; dp_Speed[1] = 50; dp_Speed[2] = 100; // // dp_Speed[0] = 450000; dp_Speed[1] = 100; dp_Speed[2] = 50; // // } // else if(d_TargetPos == st_motor[M_DCLDRBT_Z].d_pos[P_DCLDRBT_Z_DCBUFF_PICK]) // { // dp_Speed[0] = 650000; dp_Speed[1] = 50; dp_Speed[2] = 100; // // } // else if(d_TargetPos == st_motor[M_DCLDRBT_Z].d_pos[P_DCLDRBT_Z_DCTEST_PICK]) // { // dp_Speed[0] = 450000; dp_Speed[1] = 50; dp_Speed[2] = 50; // // } // else if(d_TargetPos == st_motor[M_DCLDRBT_Z].d_pos[P_DCLDRBT_Z_LDPLATE_PLACE]) // { // dp_Speed[0] = 650000; dp_Speed[1] = 50; dp_Speed[2] = 100; // // } // else if(d_TargetPos == st_motor[M_DCLDRBT_Z].d_pos[P_DCLDRBT_Z_LDBUFF_PLACE]) // { // dp_Speed[0] = 650000; dp_Speed[1] = 50; dp_Speed[2] = 100; // // } // else if(d_TargetPos == st_motor[M_DCLDRBT_Z].d_pos[P_DCLDRBT_Z_DCTEST_PLACE]) // { // //dp_Speed[0] = 450000; dp_Speed[1] = 50; dp_Speed[2] = 50; // // //091012 dp_Speed[0] = 380000; dp_Speed[1] = 50; dp_Speed[2] = 50; // // dp_Speed[0] = 380000; dp_Speed[1] = 50; dp_Speed[2] = 50; // // } // else // { // dp_Speed[0] = st_motor[n_Axis].d_spd_vel[0]; dp_Speed[1] = st_motor[n_Axis].d_spd_vel[1]; dp_Speed[2] = st_motor[n_Axis].d_spd_vel[2]; //가속 펄수 값은 9,000,000 이다 // } // COMI.Set_Motor_IO_Property(n_Axis, cmINP_EN, cmTRUE); //cmINP_EN=9 //cmFALSE = 0 INP 비활성, cmTRUE = 1 INP 활성 // } // else if(n_Axis == M_DCULDRBT_Z) // { // if(d_TargetPos == st_motor[M_DCULDRBT_Z].d_pos[P_DCULDRBT_Z_DCTEST_PICK]) // { // dp_Speed[0] = 550000; dp_Speed[1] = 50; dp_Speed[2] = 100; // // } // else if(d_TargetPos == st_motor[M_DCULDRBT_Z].d_pos[P_DCULDRBT_Z_DCBUFF_PICK]) // { // dp_Speed[0] = 400000; dp_Speed[1] = 50; dp_Speed[2] = 50; // // } // else if(d_TargetPos == st_motor[M_DCULDRBT_Z].d_pos[P_DCULDRBT_Z_INSERTBUFF_TOP_PICK]) // { // dp_Speed[0] = 400000; dp_Speed[1] = 50; dp_Speed[2] = 50; // // } // else if(d_TargetPos == st_motor[M_DCULDRBT_Z].d_pos[P_DCULDRBT_Z_INSERTBUFF_BOTTOM_PICK]) // { // dp_Speed[0] = 550000; dp_Speed[1] = 50; dp_Speed[2] = 100; // // } // else if(d_TargetPos == st_motor[M_DCULDRBT_Z].d_pos[P_DCULDRBT_Z_DCTEST_PLACE]) // { // dp_Speed[0] = 550000; dp_Speed[1] = 50; dp_Speed[2] = 100; // // } // else if(d_TargetPos == st_motor[M_DCULDRBT_Z].d_pos[P_DCULDRBT_Z_DCBUFF_PLACE]) // { // dp_Speed[0] = 400000; dp_Speed[1] = 50; dp_Speed[2] = 50; // // } // else if(d_TargetPos == st_motor[M_DCULDRBT_Z].d_pos[P_DCULDRBT_Z_INSERTBUFF_TOP_PLACE]) // { // //dp_Speed[0] = 400000; dp_Speed[1] = 50; dp_Speed[2] = 50; // // dp_Speed[0] = 400000; dp_Speed[1] = 50; dp_Speed[2] = 100; // // } // else if(d_TargetPos == st_motor[M_DCULDRBT_Z].d_pos[P_DCULDRBT_Z_INSERTBUFF_BOTTOM_PLACE]) // { // //dp_Speed[0] = 550000; dp_Speed[1] = 50; dp_Speed[2] = 100; // // dp_Speed[0] = 550000; dp_Speed[1] = 50; dp_Speed[2] = 100; // // } // else // { // dp_Speed[0] = st_motor[n_Axis].d_spd_vel[0]; dp_Speed[1] = st_motor[n_Axis].d_spd_vel[1]; dp_Speed[2] = st_motor[n_Axis].d_spd_vel[2]; //가속 펄수 값은 9,000,000 이다 // } // COMI.Set_Motor_IO_Property(n_Axis, cmINP_EN, cmTRUE); //cmINP_EN=9 //cmFALSE = 0 INP 비활성, cmTRUE = 1 INP 활성 // } // else// if(n_Axis == M_ULDRBT_Z) // {//090909 // if(d_TargetPos == st_motor[M_ULDRBT_Z].d_pos[P_ULDRBT_Z_REMOVEBUFF_TOP_PICK]) // { // dp_Speed[0] = 400000; dp_Speed[1] = 100; dp_Speed[2] = 150; // // } // else if(d_TargetPos == st_motor[M_ULDRBT_Z].d_pos[P_ULDRBT_Z_REMOVEBUFF_MIDDLE_PICK]) // { // dp_Speed[0] = 500000; dp_Speed[1] = 100; dp_Speed[2] = 150; // // } // else if(d_TargetPos == st_motor[M_ULDRBT_Z].d_pos[P_ULDRBT_Z_REMOVEBUFF_BOTTOM_PICK]) // { // dp_Speed[0] = 400000; dp_Speed[1] = 80; dp_Speed[2] = 150; // // } // else if(d_TargetPos == st_motor[M_ULDRBT_Z].d_pos[P_ULDRBT_Z_MANUALBUFF_PICK]) // { // dp_Speed[0] = 500000; dp_Speed[1] = 100; dp_Speed[2] = 150; // // } // else if(d_TargetPos == st_motor[M_ULDRBT_Z].d_pos[P_ULDRBT_Z_MANUALBUFF_PLACE]) // { // dp_Speed[0] = 400000; dp_Speed[1] = 100; dp_Speed[2] = 150; // // } // else if(d_TargetPos == st_motor[M_ULDRBT_Z].d_pos[P_ULDRBT_Z_ULDPLATE_PLACE]) // { // dp_Speed[0] = 400000; dp_Speed[1] = 80; dp_Speed[2] = 150; // // } // else // { // dp_Speed[0] = st_motor[n_Axis].d_spd_vel[0]; dp_Speed[1] = st_motor[n_Axis].d_spd_vel[1]; dp_Speed[2] = st_motor[n_Axis].d_spd_vel[2]; //가속 펄수 값은 9,000,000 이다 // } // COMI.Set_Motor_IO_Property(n_Axis, cmINP_EN, cmTRUE); //cmINP_EN=9 //cmFALSE = 0 INP 비활성, cmTRUE = 1 INP 활성 // } // } // } // else if(n_Axis == M_SORTBUFFRBT_Z || n_Axis == M_INSERTRBT_Z || n_Axis == M_REMOVERBT_Z) // { // dCurrentPos = COMI.Get_MotCurrentPos(n_Axis); // // //목표위치 계산 방법은 ==> 현재위치 - 목표이동 위치 이다 // dVal = dCurrentPos - d_TargetPos; // if(dVal > 0) //먼 위치에서 가까운 위치(홈 위치) 로 이동했을때는 + 값 발생 , 모터가 UP 할 때 발생 // { // dp_Speed[0] = st_motor[n_Axis].d_spd_vel[0]; dp_Speed[1] = st_motor[n_Axis].d_spd_vel[1]; dp_Speed[2] = st_motor[n_Axis].d_spd_vel[2]; //가속 펄수 값은 9,000,000 이다 // //UP할때 또는 정확한 목표지점으로 가지 않아도 되는 조건이면 Inposition를 보지 말자 // COMI.Set_Motor_IO_Property(n_Axis, cmINP_EN, cmFALSE); //cmINP_EN=9 //cmFALSE = 0 INP 비활성, cmTRUE = 1 INP 활성 // } // else //motor 가 다운 할때 발생 // { // dp_Speed[0] = st_motor[n_Axis].d_spd_vel[0]; dp_Speed[1] = st_motor[n_Axis].d_spd_vel[1]; dp_Speed[2] = st_motor[n_Axis].d_spd_vel[2]; //가속 펄수 값은 9,000,000 이다 // COMI.Set_Motor_IO_Property(n_Axis, cmINP_EN, cmTRUE); //cmINP_EN=9 //cmFALSE = 0 INP 비활성, cmTRUE = 1 INP 활성 // } // } // /* // else if(n_Axis == M_DCLDRBT_X || n_Axis == M_DCULDRBT_X) //아직 사용안함 // {//로보트 X 스크류 모터는 정해진 속도로 게속 이동하여 굳이 필요없음. // dAccDecTime = (st_motor[n_Axis].d_spd_vel[0] - st_motor[n_Axis].d_initial_speed) / (9750000 / 1000); //dAccDecTime = 66.6 ms //이동구간 시간 : 289ms // dp_Speed[0] = st_motor[n_Axis].d_spd_vel[0]; dp_Speed[1] = dAccDecTime; dp_Speed[2] = dAccDecTime; //가속 펄수 값은 9,000,000 이다 // }*/ // else if(n_Axis == M_DCLDRBT_Y || n_Axis == M_DCULDRBT_Y)// || n_Axis == M_ULDRBT_Y) // { // dCurrentPos = COMI.Get_MotCurrentPos(n_Axis); // d_abs_val = fabs(dCurrentPos - d_TargetPos); // dVal = dCurrentPos - d_TargetPos; //090830 fabs(dCurrentPos - d_TargetPos); // if(d_abs_val < st_size.d_tray_dcld_mm_y + 1) //피치 Y + 2 mm 보다 작으면 정속도를 다운한다 , 진동 문제로 // { // dp_Speed[0] = 200000; dp_Speed[1] = 100; dp_Speed[2] = 100; //가속 펄수 값은 9,000,000 이다 // } // else if(n_Axis == M_DCLDRBT_Y && st_motor[M_DCLDRBT_Y].d_pos[P_DCLDRBT_DCSAFETY_POS] == d_TargetPos && dVal < 0) //모터가 증가 방향이면 // { // dp_Speed[0] = 100000; dp_Speed[1] = 100; dp_Speed[2] = 100; //가속 펄수 값은 9,000,000 이다 // } // else if(n_Axis == M_DCULDRBT_Y && st_motor[M_DCULDRBT_Y].d_pos[P_DCULDRBT_DCSAFETY_POS] == d_TargetPos && dVal < 0) //모터가 증가 방향이면 // { // dp_Speed[0] = 100000; dp_Speed[1] = 100; dp_Speed[2] = 100; //가속 펄수 값은 9,000,000 이다 // } // else // { // dp_Speed[0] = st_motor[n_Axis].d_spd_vel[0]; dp_Speed[1] = st_motor[n_Axis].d_spd_vel[1]; dp_Speed[2] = st_motor[n_Axis].d_spd_vel[2]; // } // } // else if(n_Axis == M_REMOVERBT_Y) // {//090907 // dCurrentPos = COMI.Get_MotCurrentPos(n_Axis); // d_abs_val = fabs(dCurrentPos - d_TargetPos); // dVal = dCurrentPos - d_TargetPos; //090830 fabs(dCurrentPos - d_TargetPos); // if(n_Axis == M_REMOVERBT_Y && st_motor[M_REMOVERBT_Y].d_pos[P_REMOVERBT_BIBTABLE_SAFETY_POS] == d_TargetPos && dVal < 0) //모터가 증가 방향이면 // { // dp_Speed[0] = 10000; dp_Speed[1] = 100; dp_Speed[2] = 100; //가속 펄수 값은 9,000,000 이다 // } // else // { // dp_Speed[0] = st_motor[n_Axis].d_spd_vel[0]; dp_Speed[1] = st_motor[n_Axis].d_spd_vel[1]; dp_Speed[2] = st_motor[n_Axis].d_spd_vel[2]; // } // } // else if(n_Axis == M_ULDRBT_Y)//보간 속도 율 // { // dCurrentPos = COMI.Get_MotCurrentPos(n_Axis); // dVal = fabs(dCurrentPos - d_TargetPos); // if(dVal < 50) // { // dp_Speed[0] = 50; dp_Speed[1] = 50; dp_Speed[2] = 50; //speed rate를 50%로 변경 한다 // } // else if(dVal < 100) //100mm이하 위치 // { // dp_Speed[0] = 60; dp_Speed[1] = 60; dp_Speed[2] = 60; //speed rate를 50%로 변경 한다 // } // else if(dVal < 200) //100mm이하 위치 // { // dp_Speed[0] = 70; dp_Speed[1] = 70; dp_Speed[2] = 70; //speed rate를 50%로 변경 한다 // } // else // { // dp_Speed[0] = 100; dp_Speed[1] = 100; dp_Speed[2] = 100; //speed rate를 100%로 변경 한다 // } // } // else if(n_Axis == M_ULDRBT_X) //보간 속도 율 // { // dCurrentPos = COMI.Get_MotCurrentPos(n_Axis); // dVal = fabs(dCurrentPos - d_TargetPos); // if(dVal > 400) // { // dp_Speed[0] = 50; dp_Speed[1] = 50; dp_Speed[2] = 50; //speed rate를 50%로 변경 한다 // } // else // { // dp_Speed[0] = 100; dp_Speed[1] = 100; dp_Speed[2] = 100; //speed rate를 100%로 변경 한다 // } // } // /* // else if(n_Axis == M_DCLDRBT_X || n_Axis == M_DCULDRBT_X || n_Axis == M_ULDRBT_X) // { // dCurrentPos = COMI.Get_MotCurrentPos(n_Axis); // dVal = fabs(dCurrentPos - d_TargetPos); // if(dVal < st_size.d_tray_dcld_mm_x + 1) //피치 Y + 2 mm 보다 작으면 정속도를 다운한다 , 진동 문제로 // { // dp_Speed[0] = 10000; dp_Speed[1] = 200; dp_Speed[2] = 200; //가속 펄수 값은 9,000,000 이다 // } // else // { // dp_Speed[0] = st_motor[n_Axis].d_spd_vel[0]; dp_Speed[1] = st_motor[n_Axis].d_spd_vel[1]; dp_Speed[2] = st_motor[n_Axis].d_spd_vel[2]; // } // }*/ // else // { // dp_Speed[0] = st_motor[n_Axis].d_spd_vel[0]; dp_Speed[1] = st_motor[n_Axis].d_spd_vel[1]; dp_Speed[2] = st_motor[n_Axis].d_spd_vel[2]; // } return RET_GOOD; } int CCtlBd_Function::Alarm_Error_Occurrence(int n_Count, int n_Type, int n_Status, CString s_JamCode) { CString strMsg; st_alarm_info.nCountMode = n_Count; st_alarm_info.nTypeMode = n_Type; st_alarm_info.strCode = s_JamCode; // st_handler_info.nRunStatus = n_Status; // MyJamData.On_Alarm_Info_Set_to_Variable(alarm.str_code); if (st_handler_info.cWndList != NULL) // 리스트 바 화면 존재 { if(n_Count == MOT_DEBUG) { strMsg.Format(_T("[MOT SAFETY CHECK]=> [%s] [%s]"), st_alarm_info.strCode, st_alarm_info.strCurrMsg); //wsprintfA(st_other_info.cAbnormalMsg, "%S", strMsg); if (st_handler_info.cWndList != NULL) { //clsFunc.OnStringToChar(strMsg, st_other_info.cAbnormalMsg); clsMem.OnAbNormalMessagWrite(strMsg); //st_handler_info.cWndList->SendMessage(WM_LIST_DATA, 0, ABNORMAL_MSG); // 동작 실패 출력 요청 } } else { strMsg.Format(_T("[%s] [%s]"), st_alarm_info.strCode, st_alarm_info.strCurrMsg); //wsprintfA(st_other_info.cAbnormalMsg, "%S", strMsg); //clsFunc.OnStringToChar(strMsg, st_other_info.cAbnormalMsg); if (st_handler_info.cWndList != NULL) { clsMem.OnAbNormalMessagWrite(strMsg); //st_handler_info.cWndList->SendMessage(WM_LIST_DATA, 0, ABNORMAL_MSG); // 동작 실패 출력 요청 } } } return RET_GOOD; } int CCtlBd_Function::Send_Error_Message(int n_Mode, int n_Axis, CString s_JamCode, CString s_JamMsg) { // long lErrorCode; // short int nErrorParseAxis; // short int nErrorParseReason; char cErrorMsg[200]; CString sMsg, sTemp; memset(&cErrorMsg, 0, sizeof(cErrorMsg)); // 데이터 저장 변수 초기화 /* if(n_Mode == MOT_ERR_MSG) {//문자 메세지를 받아 리스트 화면에 디스플레이 한다 if (st_handler.cwnd_list != NULL) // 리스트 바 화면 존재 { st_other.str_abnormal_msg = s_JamMsg; st_handler.cwnd_list->PostMessage(WM_LIST_DATA, 0, ABNORMAL_MSG); // 동작 실패 출력 요청 } } else if(n_Mode == MOT_ERR_CODE) {//jamcode 설정 if (st_handler.cwnd_list != NULL) // 리스트 바 화면 존재 { st_other.str_abnormal_msg = s_JamMsg; st_handler.cwnd_list->PostMessage(WM_LIST_DATA, 0, ABNORMAL_MSG); // 동작 실패 출력 요청 } } */ /* if(CTLBD_DEBUG_MODE) { if(CTLBD_MOTBD_TYPE == 0) //파스텍 보드 { } else if(CTLBD_MOTBD_TYPE == 1) //커미조아 보드 { cmmErrGetLastCode(&lErrorCode); //마지막 발생한 에러 코드 확인 nErrorParseAxis = cmmErrParseAxis(lErrorCode); //에러를 발생시킨 축 정보를 가져온다 nErrorParseReason = cmmErrParseReason(lErrorCode); //error code를 받는다 cmmErrGetString(lErrorCode, cErrorMsg, 200); sTemp.Format(_T("Msg=%s"), cErrorMsg); sMsg.Format(_T("Motor Num:%d, Code=%d, Axis=%d, reason=%d, %s"), n_Axis, lErrorCode, nErrorParseAxis, nErrorParseReason, sTemp); if (st_handler_info.cWndList != NULL) // 리스트 바 화면 존재 { wsprintfA(st_other_info.cAbnormalMsg, "%S", sMsg); st_handler_info.cWndList->PostMessage(WM_LIST_DATA, 0, ABNORMAL_MSG); // 동작 실패 출력 요청 if(MOT_DEBUG) clsFunc.OnLogFileAdd(3, sMsg); } sMsg.Format(_T("Index or Axis=%d, %s"), n_Axis, s_JamMsg); if (st_handler_info.cWndList != NULL) // 리스트 바 화면 존재 { // st_other.str_abnormal_msg = sMsg; // sprintf(st_other.c_abnormal_msg, st_other.str_abnormal_msg); wsprintfA(st_other_info.cAbnormalMsg, "%S", sMsg); st_handler_info.cWndList->PostMessage(WM_LIST_DATA, 0, ABNORMAL_MSG); // 동작 실패 출력 요청 if(MOT_DEBUG) clsFunc.OnLogFileAdd(3, sMsg); } } } st_alarm_info.strCode = s_JamCode; //alarm.n_count_mode = 0; alarm.n_type_mode = CTL_dWARNING; */ return YES; } int CCtlBd_Function::OnMotor_SafetyCheck(int n_Mode, int n_Axis, double d_TargetPos) {/* // n_Mode = 0:Home Check, 1:Start, 2:Check, 3:Jog CString strMsg; int nRet = 0, nRet_1 = 0, nRet_2 = 0; double d_CurPos[3] = {0,}; double d_Pos[3] = {0,}; double d_GapCheck[3] = {0,}; int i = 0; int n_SetTime = 50; //091127 20->50으로 변경 100; //500ms 동안 계속 감기되면 그때 비로소 I/O 상태 return // ************************************************************************** // 모터 알람 상태 검사한다 // -> 알람 발생한 경우 알람 해제한다 // ************************************************************************** //software limit 값 셋팅 체크 에러 if(st_handler_info.nRunStatus == dRUN) { nRet = clsFunc.OnDoorOpenCheck(); if(nRet == RET_ERROR) { // 문이 열려있고, 안전장치 가동중이면 에러를 리턴한다. 2K6/06/09/ViboX return RET_ERROR; } } if (COMI.Get_MotAlarmStatus(n_Axis) == RET_ERROR) // 모터 ALARM 상태 검사 함수 { //091216 추가 if(st_motor_info[n_Axis].n_retry_time_flag == NO) { st_motor_info[n_Axis].n_retry_time_flag = YES; st_motor_info[n_Axis].l_retry_time_wait[0] = GetCurrentTime(); COMI.Set_MotAlarmClear(n_Axis); if (st_handler_info.cWndList != NULL) // 리스트 바 화면 존재 { strMsg.Format(_T("[Motor Alarm Reset_1] Axis=%d, Wait:%d"), n_Axis, 500); //wsprintfA(st_other_info.cNormalMsg, "%S", strMsg); //clsFunc.OnStringToChar(strMsg, st_other_info.cNormalMsg); clsMem.OnNormalMessageWrite(strMsg); st_handler_info.cWndList->PostMessage(WM_LIST_DATA, 0, NORMAL_MSG); // 동작 실패 출력 요청 } } st_motor_info[n_Axis].l_retry_time_wait[1] = GetCurrentTime(); st_motor_info[n_Axis].l_retry_time_wait[2] = st_motor_info[n_Axis].l_retry_time_wait[1] - st_motor_info[n_Axis].l_retry_time_wait[0]; if(st_motor_info[n_Axis].l_retry_time_wait[2] < 0) { st_motor_info[n_Axis].n_retry_time_flag = YES; st_motor_info[n_Axis].l_retry_time_wait[0] = GetCurrentTime(); return RET_RETRY; } else if(st_motor_info[n_Axis].l_retry_time_wait[2] < 500) //500ms초 이상이 되었을때 다음조건 체크) { return RET_RETRY; } if (COMI.Set_MotAlarmClear(n_Axis) == RET_GOOD) // 모터 ALARM CLEAR 함수 { st_motor_info[n_Axis].n_retry_time_flag = NO; //091216 //091119 james Sleep(1000); // 일정 시간 후에 상태 확인하기 위해 SLEEP 사용한다 if (st_handler_info.cWndList != NULL) // 리스트 바 화면 존재 { strMsg.Format(_T("[Motor Alarm Reset_2] Axis=%d, Wait:%d"), n_Axis, 500); //wsprintfA(st_other_info.cNormalMsg, "%S", strMsg); //clsFunc.OnStringToChar(strMsg, st_other_info.cNormalMsg); clsMem.OnNormalMessageWrite(strMsg); st_handler_info.cWndList->PostMessage(WM_LIST_DATA, 0, NORMAL_MSG); // 동작 실패 출력 요청 } if (COMI.Get_MotAlarmStatus(n_Axis) == RET_ERROR ) // 모터 ALARM 상태 검사 함수 { if (st_motor_info[n_Axis].n_retry_cnt > MOT_RTY_CNT) { st_alarm_info.strCode.Format(_T("%02d0002"), n_Axis); CtlBdFunc.ms_ErrMsg = _T("[Motor_SafetyCheck_1] Alarm Check Error"); CtlBdFunc.Send_Error_Message(MOT_ERR_CODE, n_Axis, st_alarm_info.strCode, CtlBdFunc.ms_ErrMsg); st_motor_info[n_Axis].n_retry_cnt = 0; // 알람 해제 시도 횟수 return RET_ERROR; } else { st_motor_info[n_Axis].n_retry_cnt++ ; return RET_RETRY; } } } else { st_motor_info[n_Axis].n_retry_time_flag = NO; //091216 if (st_motor_info[n_Axis].n_retry_cnt > MOT_RTY_CNT) { st_alarm_info.strCode.Format(_T("%02d0002"), n_Axis); CtlBdFunc.ms_ErrMsg = _T("[Motor_SafetyCheck_2] Alarm Check Error"); CtlBdFunc.Send_Error_Message(MOT_ERR_CODE, n_Axis, st_alarm_info.strCode, CtlBdFunc.ms_ErrMsg); st_motor_info[n_Axis].n_retry_cnt = 0; // 알람 해제 시도 횟수 return RET_ERROR; } else { st_motor_info[n_Axis].n_retry_cnt++ ; return RET_RETRY; } } } // ************************************************************************** // ************************************************************************** // 모터 파워 상태 검사한다 // -> 모터 POWER OFF 시 POWER ON 상태로 만든다 // ************************************************************************** if (COMI.Get_MotPower(n_Axis) == RET_ERROR ) // 모터 POWER 상태 검사 함수 { //091216 추가 if(st_motor_info[n_Axis].n_retry_time_flag == NO) { st_motor_info[n_Axis].n_retry_time_flag = YES; st_motor_info[n_Axis].l_retry_time_wait[0] = GetCurrentTime(); COMI.Set_MotPower(n_Axis, NO); if (st_handler_info.cWndList != NULL) // 리스트 바 화면 존재 { strMsg.Format(_T("[Motor Power Reset_1] Axis=%d, Wait:%d"), n_Axis, 500); //wsprintfA(st_other_info.cNormalMsg, "%S", strMsg); //clsFunc.OnStringToChar(strMsg, st_other_info.cNormalMsg); clsMem.OnNormalMessageWrite(strMsg); st_handler_info.cWndList->PostMessage(WM_LIST_DATA, 0, NORMAL_MSG); // 동작 실패 출력 요청 } } st_motor_info[n_Axis].l_retry_time_wait[1] = GetCurrentTime(); st_motor_info[n_Axis].l_retry_time_wait[2] = st_motor_info[n_Axis].l_retry_time_wait[1] - st_motor_info[n_Axis].l_retry_time_wait[0]; if(st_motor_info[n_Axis].l_retry_time_wait[2] < 0) { st_motor_info[n_Axis].n_retry_time_flag = YES; st_motor_info[n_Axis].l_retry_time_wait[0] = GetCurrentTime(); return RET_RETRY; } else if(st_motor_info[n_Axis].l_retry_time_wait[2] < 500) //500ms초 이상이 되었을때 다음조건 체크) { return RET_RETRY; } if (COMI.Set_MotPower(n_Axis, NO) == RET_GOOD) // 모터 POWER ON 설정 함수 { st_motor_info[n_Axis].n_retry_time_flag = NO; //091216 //091119 james Sleep(1000); // 일정 시간 후에 상태 확인하기 위해 SLEEP 사용한다 if (st_handler_info.cWndList != NULL) // 리스트 바 화면 존재 { strMsg.Format(_T("[Motor Power Reset_2] Axis=%d, Wait:%d"), n_Axis, 500); //wsprintfA(st_other_info.cNormalMsg, "%S", strMsg); //clsFunc.OnStringToChar(strMsg, st_other_info.cNormalMsg); clsMem.OnNormalMessageWrite(strMsg); st_handler_info.cWndList->PostMessage(WM_LIST_DATA, 0, NORMAL_MSG); // 동작 실패 출력 요청 } if (COMI.Get_MotPower(n_Axis) == RET_ERROR) // 모터 POWER 상태 검사 함수 { if (st_motor_info[n_Axis].n_retry_cnt > (MOT_RTY_CNT)) { st_alarm_info.strCode.Format(_T("%02d0005"), n_Axis); CtlBdFunc.ms_ErrMsg = _T("[Motor_SafetyCheck_1] Power Check Error"); CtlBdFunc.Send_Error_Message(MOT_ERR_CODE, n_Axis, st_alarm_info.strCode, CtlBdFunc.ms_ErrMsg); st_motor_info[n_Axis].n_retry_cnt = 0; return RET_ERROR; } else { st_motor_info[n_Axis].n_retry_cnt++ ; return RET_RETRY; } } } else { st_motor_info[n_Axis].n_retry_time_flag = NO; //091216 if (st_motor_info[n_Axis].n_retry_cnt > MOT_RTY_CNT) { st_alarm_info.strCode.Format(_T("%02d0005"), n_Axis); CtlBdFunc.ms_ErrMsg = _T("[Motor_SafetyCheck_2] Power Check Error"); CtlBdFunc.Send_Error_Message(MOT_ERR_CODE, n_Axis, st_alarm_info.strCode, CtlBdFunc.ms_ErrMsg); st_motor_info[n_Axis].n_retry_cnt = 0; return RET_ERROR; } else { st_motor_info[n_Axis].n_retry_cnt++ ; return RET_RETRY; } } } st_motor_info[n_Axis].n_retry_time_flag = NO;//091216 */ return RET_GOOD; } int CCtlBd_Function::Initialize_FASIO_Board(void) { int m=0, p=0, s=0; int nRet=0; WORD wMaskMap = 0; /* INT nHSSI_speed=0; INT nMasterNo=0, nPortNo =0, nSlaveNo=0; nRet = FAS_IO.Set_IO_BoardOpen(&nMasterNo, START_NOTHING); // I/O 보드 오픈 함수 if (nRet == CTLBD_RET_ERROR) { return CTLBD_RET_ERROR; //IO_BOARD_OPEN_FAILED; } nRet = FAS_IO.Search_IO_Master(&nMasterNo); // PC에 연결된 마스터 보드 갯수 검사 함수 if (nRet == CTLBD_RET_ERROR) { return CTLBD_RET_ERROR; } for(m=0; m<nMasterNo; m++) { nRet = FAS_IO.Search_IO_Port(m, &nPortNo); // 마스터 보드에 연결된 PORT 갯수 검사 함수 if (nRet == CTLBD_RET_ERROR) return CTLBD_RET_ERROR; //PORT_SEARCH_FAILED; for(p=0; p<nPortNo; p++) { nRet = FAS_IO.Set_IO_HSSISpeed(m, p, PORT_SPEED_10); // PORT와 SLAVE I/O 모듈과의 통신 속도 설정 함수 if (nRet == CTLBD_RET_ERROR) return CTLBD_RET_ERROR; //IO_SPEED_SET_FAILED; nRet = FAS_IO.Search_IO_Slave(m, p, &nSlaveNo); // PORT에 연결된 SLAVE 검사 함수 if (nRet == CTLBD_RET_ERROR) return CTLBD_RET_ERROR; //IO_SLAVE_SEARCH_FAILED; for(s=0; s<nSlaveNo; s++) { nRet = FAS_IO.Set_IO_SlaveEnable(m, p, s, CTLBD_YES); // SLAVE I/O 모듈 동작 ENABLE/DISABLE 설정 함수 if (nRet == CTLBD_RET_ERROR) return CTLBD_RET_ERROR; //IO_SLAVE_ENABLE_FAILED; wMaskMap = 0; //clear for(i=0; i<16; i++) //0~15 까지의 Port 16bit 셋팅, 각각의 I/O 상태를 정의한다 { wMaskMap = wMaskMap | (WORD)pow(2, mw_IOMaskMap[m][p][s][i]); } FAS_IO.Set_IO_DefineWord(m, p, s, wMaskMap); // x Master, x포트, x번 슬레이브 , 16bit 셋팅 //FAS_IO.Set_IO_DefineWord(0, 0, 0, 0x0003); // 0번 Master, 0번 포트, 0번 슬레이브 , 16bit 셋팅 //FAS_IO.Set_IO_DefineWord(0, 0, 1, 0x0003); // 0번 Master, 0번 포트, 1번 슬레이브 , 16bit 셋팅 //FAS_IO.Set_IO_DefineWord(0, 1, 0, 0x00ff); // 0번 Master, 1번 포트, 0번 슬레이브 , 16bit 셋팅 } } } */ return RET_GOOD; } int CCtlBd_Function::Initialize_InterruptMask_TriggerConfig(void) { int i, nAxis; // st_motor[0].l_Set_InterruptMask[12] = CTL_YES; // COMI.Set_InterruptMask(0, st_motor[0].l_Set_InterruptMask); // double dRatio[3] = {100,100,100}; //Set_TriggerSet_OneCompareConfig(int n_Axis, int n_Source, int n_Method, double d_ComparePosition) // COMI.Set_TriggerSet_OneCompareConfig(0, 0, 1, 5000); // st_motor[].n_interrupt_flag /* "Normal Stop", // 0 "Succesive start", // 1 "", // 2 "", // 3 "Start of acceleration", //4 "End of acceleration", // 5 "Start of deceleration", // 6 "End of deceleration", // 7 "", // 8 "", // 9 "Position error tolerance exceed", // 10 "General Comparator", // 11 "Compared trigger", // 12 "CLR signal resets the counter value", // 13 "LTC input making counter value latched", // 14 "ORG input signal ON", // 15 "SD input signal ON", // 16 "+DR input changes", // 17 "-DR input changes" // 18 int n_interrupt_source; //인터럽트 처리 조건 //n_Mode : szCompareSource[4][50] = { //0 "COMMAND Counter", //1 "Feedback Counter", //2 "Deviation Counter", //3 "General Counter" int n_interrupt_method; //사용하는 조건 정의 //CHAR szCompareMethod[6][50] = { //0 "Disable", //1 "CMP == COUNTER (No direction)", //2 "CMP == COUNTER (Only when counting up)", //3 "CMP == COUNTER (Only when counting down)", //4 "CMP > COUNTER", //5 "CMP < COUNTER" */ for(i=0; i<5; i++) //for(nAxis=0; nAxis<MOT_MAXMOTOR; nAxis++) { if(i == 0) { nAxis = 0; st_motor_info[nAxis].n_interrupt_flag = YES; //dc load robot Y 무조건 설정 } else if(i == 1) { nAxis = 5; st_motor_info[nAxis].n_interrupt_flag = YES; //dc unload robot Y 무조건 설정 } else if(i == 2) { nAxis = 16; st_motor_info[nAxis].n_interrupt_flag = YES; //insert robot Y 무조건 설정 } else if(i == 3) { nAxis = 19; //2009.5.27 james 소켓 푸쉬 추가 //st_motor[nAxis].n_interrupt_flag = CTL_YES; //소켓 푸쉬 무조건 설정 } else if(i == 4) { nAxis = 20; st_motor_info[nAxis].n_interrupt_flag = YES; //remove robot Y 무조건 설정 } if(st_motor_info[nAxis].n_interrupt_flag == YES) //인터럽트를 사용하는 모터이면 { st_motor_info[nAxis].l_Set_InterruptMask[0] = NO; //"Normal Stop", // 0 st_motor_info[nAxis].l_Set_InterruptMask[1] = NO; //"Succesive start", // 1 st_motor_info[nAxis].l_Set_InterruptMask[2] = NO; //"", // 2 st_motor_info[nAxis].l_Set_InterruptMask[3] = NO; //"", // 3 st_motor_info[nAxis].l_Set_InterruptMask[4] = NO; //"Start of acceleration", //4 st_motor_info[nAxis].l_Set_InterruptMask[5] = NO; //End of acceleration", // 5 st_motor_info[nAxis].l_Set_InterruptMask[6] = NO; //"Start of deceleration", // 6 st_motor_info[nAxis].l_Set_InterruptMask[7] = NO; //"End of deceleration", // 7 st_motor_info[nAxis].l_Set_InterruptMask[8] = NO; //"", // 8 st_motor_info[nAxis].l_Set_InterruptMask[9] = NO; //"", // 9 st_motor_info[nAxis].l_Set_InterruptMask[10] = NO; //"Position error tolerance exceed", // 10 st_motor_info[nAxis].l_Set_InterruptMask[11] = NO; //"General Comparator", // 11 //이것만 우선 사용한다 st_motor_info[nAxis].l_Set_InterruptMask[12] = YES; //"Compared trigger", // 12 st_motor_info[nAxis].l_Set_InterruptMask[13] = NO; //"CLR signal resets the counter value", // 13 st_motor_info[nAxis].l_Set_InterruptMask[14] = NO; //"LTC input making counter value latched", // 14 st_motor_info[nAxis].l_Set_InterruptMask[15] = NO; //"ORG input signal ON", // 15 st_motor_info[nAxis].l_Set_InterruptMask[16] = NO; //"SD input signal ON", // 16 st_motor_info[nAxis].l_Set_InterruptMask[17] = NO; //"+DR input changes", // 17 st_motor_info[nAxis].l_Set_InterruptMask[18] = NO; //"-DR input changes" // 18 //인터럽트 마스키 정보를 셋팅한다 //Set_InterruptMask(int n_Axis, long l_Set_InterruptMask[19]) COMI.Set_InterruptMask(nAxis, st_motor_info[nAxis].l_Set_InterruptMask); //인터럽트 발생 조건 및 구간 설정 //Set_TriggerSet_OneCompareConfig(int n_Axis, int n_Source, int n_Method, double d_ComparePosition) COMI.Set_TriggerSet_OneCompareConfig(nAxis, st_motor_info[nAxis].n_interrupt_source, st_motor_info[nAxis].n_interrupt_method, st_motor_info[nAxis].n_interrupt_position); } } return RET_GOOD; }
C++
CL
eef0542cbbca460a9faf677960a97bfd182430e251a66815a294d7e313fd0c62
#include <fstream> #include <iostream> #include <vector> #include <algorithm> using namespace std; #include <jtflib/mesh/mesh.h> #include "../common/vtk.h" #include "../common/util.h" #include "../common/IO.h" #include <jtflib/mesh/mesh.h> #include "../hexmesh/io.h" using namespace zjucad::matrix; //using namespace jtf::hexmesh; int hex_surf2obj(int argc, char *argv[]) { if(argc != 3 && argc != 4) { cerr << "# [usage] hex_surf2obj hex obj [s2v]" << endl; return __LINE__; } jtf::mesh::meshes hm; matrixst quad; if(jtf::hexmesh::hex_mesh_read_from_wyz(argv[1], hm.mesh_, hm.node_,1)) return __LINE__; cerr << "# hex number " << hm.mesh_.size(2) << endl; cerr << "# hex point " << hm.node_.size(2) << endl; unique_ptr<jtf::mesh::face2hex_adjacent> fa(jtf::mesh::face2hex_adjacent::create(hm.mesh_)); if(!fa.get()){ cerr << "# [error] can not build face2hex_adjacent." << endl; return __LINE__; } jtf::mesh::get_outside_face(*fa, quad); if(argc == 3) remove_extra_node(quad, hm.node_); if(argc == 4){ matrix<size_t> orig2new_mapping; remove_extra_node(quad, hm.node_, &orig2new_mapping); matrix<int> s2v(hm.node_.size(2),1); for(size_t i = 0; i < orig2new_mapping.size(); ++i){ if(orig2new_mapping[i] != -1) s2v[orig2new_mapping[i]] = i; } jtf::mesh::write_matrix(argv[3], s2v); } jtf::mesh::save_obj(argv[2], quad, hm.node_); return 0; }
C++
CL
be754eda0a8771345f2e5b589b8e154f0df6c5c6e6ef2c6f0486253fe2ab917d
/*****************************************************/ // Copyright © 2007-2012 Navico // Confidential and proprietary. All rights reserved. /*****************************************************/ #ifndef GLINDEXBUFFER_H #define GLINDEXBUFFER_H #pragma warning(push, 1) #include <QtGlobal> #pragma warning(pop) #if ! (defined QT_OPENGL_ES || defined Q_WS_QWS) #include "../IndexBuffer.h" #include "OpenGL.h" /** This is the default OpenGL hardware index buffer implementation for systems that do not support vertex buffer objects (ARB_vertex_buffer_object). \note Since this class does not make use of VBOs and is simply an array wrapper, I am inlining all of the methods. */ class tGLBufferObject; class tGLIndexBuffer: public tIndexBuffer { public: tGLIndexBuffer(tHardwareBuffer::eUsage usage, int sizeInBytes); ~tGLIndexBuffer(); //----- Inherited from tIndexBuffer -----// //! \copydoc tIndexBuffer::Bind void Bind(); void UnBind(); unsigned long SizeInBytes() const; //! \copydoc tIndexBuffer::DirectAccessAllowed bool DirectAccessAllowed() const { return false; } unsigned char* GetDataPtr(unsigned long offsetInBytes); private: //----- Inherited from tHardwareBuffer -----// //! \copydoc tHardwareBuffer::ReadData bool ReadFromBufferImpl(unsigned long sourceOffsetInBytes, unsigned long lengthInBytes, void* pDestination); //! \copydoc tHardwareBuffer::WriteData bool WriteToBufferImpl(const void* pSource, unsigned long length, unsigned long destinationOffset); //----- Inherited from tIndexBuffer -----// //! \copydoc tIndexBuffer::LockImpl bool LockImpl(); //! \copydoc tIndexBuffer::UnlockImpl void UnlockImpl(); private: tGLIndexBuffer(); tGLIndexBuffer(const tGLIndexBuffer& buffer); tGLIndexBuffer& operator = (const tGLIndexBuffer& buffer); private: //----- Member Variables (Attributes) -----// boost::shared_ptr<tGLBufferObject> m_xBufferObject; }; #endif // ! (defined QT_OPENGL_ES || defined Q_WS_QWS) #endif // GLDEFAULTINDEXBUFFER_H
C++
CL
ce0b623aa1943a0760a464c3f11f3baa59984f93b51ee12fbee5d6c613e1c07f
#include "tes3/tes3recordfactory.h" #include "tes3/record/tes3recordgeneric.h" #include "tes3/record/tes3recordignore.h" #include "tes3/subrecord/tes3subrecordhedr.h" #include "tes3/subrecord/tes3subrecordsinglestring.h" #include "tes3/subrecord/tes3subrecordsinglefloat.h" #include "tes3/subrecord/tes3subrecordsingleulong.h" #include "tes3/subrecord/tes3subrecordweat.h" #include "tes3/subrecord/tes3subrecordcolorref.h" #include "tes3/subrecord/tes3subrecordsnam.h" #include "tes3/subrecord/tes3subrecorddatacell.h" #include "tes3/subrecord/tes3subrecordintvland.h" #include "tes3/subrecord/tes3subrecordvnml.h" #include "tes3/subrecord/tes3subrecordvhgt.h" #include "tes3/subrecord/tes3subrecordwnam.h" #include "tes3/subrecord/tes3subrecordvtex.h" #include "tes3/record/tes3recordgroup.h" #include "tes3/subrecord/tes3subrecorddatafrmr.h" #include "tes3/subrecord/tes3subrecordflags.h" #include "tes3/subrecord/tes3subrecordambi.h" #include "tes3/subrecord/tes3subrecordignore.h" #include "tes3/subrecord/tes3subrecorddatates3.h" //----------------------------------------------------------------------------- Tes3RecordFactory::Tes3RecordFactory() { registerClasses(); } //----------------------------------------------------------------------------- Tes3RecordFactory::~Tes3RecordFactory() {} //----------------------------------------------------------------------------- void Tes3RecordFactory::registerClasses() { Tes3RecordGeneric::registerClass(_mapKnownRecords); Tes3RecordIgnore::registerClass(_mapKnownRecords); Tes3RecordGroup::registerClass(_mapKnownRecords); Tes3SubRecordHEDR::registerClass(_mapKnownRecords); Tes3SubRecordWEAT::registerClass(_mapKnownRecords); Tes3SubRecordSNAM::registerClass(_mapKnownRecords); Tes3SubRecordVNML::registerClass(_mapKnownRecords); Tes3SubRecordVHGT::registerClass(_mapKnownRecords); Tes3SubRecordWNAM::registerClass(_mapKnownRecords); Tes3SubRecordVTEX::registerClass(_mapKnownRecords); Tes3SubRecordAMBI::registerClass(_mapKnownRecords); Tes3SubRecordSingleString::registerClass(_mapKnownRecords); Tes3SubRecordSingleFloat::registerClass(_mapKnownRecords); Tes3SubRecordSingleULong::registerClass(_mapKnownRecords); Tes3SubRecordColorRef::registerClass(_mapKnownRecords); Tes3SubRecordFlags::registerClass(_mapKnownRecords); Tes3SubRecordIgnore::registerClass(_mapKnownRecords); Tes3SubRecordDATACELL::registerClass(_mapKnownRecords); Tes3SubRecordINTVLAND::registerClass(_mapKnownRecords); Tes3SubRecordDATAFRMR::registerClass(_mapKnownRecords); Tes3SubRecordDATATES3::registerClass(_mapKnownRecords); } //----------------------------------------------------------------------------- TesRecordBase* Tes3RecordFactory::create(string const& token, string const& tokenMain, unsigned char* pBuffer) { // check for Record if (_mapKnownRecords.count(token) > 0) { return _mapKnownRecords[token](pBuffer); } // check for SubRecord if (_mapKnownRecords.count(tokenMain+token) > 0) { return _mapKnownRecords[tokenMain+token](pBuffer); } return nullptr; }
C++
CL
89d650953c58f7d0e2e5c9811cacc2a5e92f9b7e83eff4f16d14349564d74723
#ifndef LIBRARY_H #define LIBRARY_H #include <QDialog> #include "equipment.h" /** * Класс описывающий библиотеку * Возможность добавления/удаления оборудования в/из библиотеки */ namespace Ui { class Library; } class Library : public QDialog { Q_OBJECT public: /* * Добавление в виджеты WidgetsLibrary и WidgetsProject списки оборудований * инициализируются все необходимые данные для работы с библиотекой */ explicit Library(QVector <Equipment*> &equipments_in_library, QVector<Equipment*> &equipments_in_project, QWidget *parent = nullptr); ~Library(); private slots: void on_pushAdd_clicked();// добавить в виджет void on_pushDelete_clicked();// удалить из виджета void on_ListWidgetsLibrary_itemClicked();// реакция на нажатие на объект из виджета 1 void on_ListWidgetsLibrary_itemDoubleClicked();// реакция на двойной клик по объекту из виджета 1 void on_ListWidgetsProject_itemClicked();// реакция на нажатие на объект из виджета 2 void on_ListWidgetsProject_itemDoubleClicked();// реакция на двойной клик по объекту из виджета 1 void on_pushOk_clicked();// завершение работы с библиокой private: Ui::Library *ui; bool library_hasFocus; bool project_hasFocus; QVector<Equipment*> &equipments_in_project; QVector<Equipment*> &equipments_in_library; }; #endif // LIBRARY_H
C++
CL
af13392e522c840051f50768aace708011cc0932e4c4a74aeccb9fa4199f0357
#ifndef _chi_graph_h #define _chi_graph_h #include "../ChiMesh/chi_mesh.h" #include <boost/graph/adjacency_list.hpp> #include <boost/graph/topological_sort.hpp> #include <boost/geometry.hpp> #include <boost/geometry/index/indexable.hpp> /**Cell pointer struct.*/ struct GraphCellInfo { chi_mesh::Cell* cell_ptr; GraphCellInfo() { cell_ptr = nullptr; } GraphCellInfo& operator=(const GraphCellInfo& other) { cell_ptr = other.cell_ptr; return *this; } }; typedef boost::property<boost::vertex_degree_t, int, GraphCellInfo> vertex_deg_prop; typedef boost::property<boost::vertex_color_t, boost::default_color_type, vertex_deg_prop> vertexProperties; typedef boost::adjacency_list< boost::vecS, //Use std::vector for EdgeList boost::vecS, //Use std::vector for VertexList boost::undirectedS, //Graph type selector vertexProperties> CHI_UD_GRAPH; typedef boost::adjacency_list< boost::vecS, //Use std::vector for EdgeList boost::vecS, //Use std::vector for VertexList boost::directedS, //Graph type selector vertexProperties> CHI_D_GRAPH; namespace chi_graph { void CuthillMckee(CHI_UD_GRAPH& in_graph, std::vector<int>* mapping); struct GraphVertex; class DirectedGraph; } #endif
C++
CL
ebf94ea5ada69f5e43fc47d958e6cc61b79c8d0d3415fb126d71bde45dd91061
// // program41.cpp // chapter02 // // Created by chenyijun on 17/2/4. // Copyright (c) 2017年 chenyijun. All rights reserved. // #include <iostream> #include <string> using namespace std; class Sales_data{ //友元函数 friend std::istream& operator >> (std::istream&, Sales_data&); //友元函数 friend std::ostream& operator << (std::ostream&, const Sales_data&); //友元函数 friend bool operator < (const Sales_data &, const Sales_data &); //友元函数 friend bool operator == (const Sales_data &, const Sales_data &); public: //构造函数的3种形式 Sales_data() = default; Sales_data(const std::string &book): bookNo(book) { } Sales_data(std::istream &is) { is >> *this; } public: Sales_data& operator += (const Sales_data&); std::string isbn() const { return bookNo; } private: std::string bookNo; //书籍编号,隐式初始化为空串 unsigned units_sold = 0; //销售量,显示初始化为0 double sellingprice = 0.0; //原始价格,显示初始化为0.0 double saleprice = 0.0; //实售价格,显示初始化为0.0 double discount = 0.0; //折扣,显示初始化为0.0 }; inline bool compareIsbn(const Sales_data &lhs, const Sales_data &rhs) { return lhs.isbn() == rhs.isbn(); } Sales_data operator + (const Sales_data&, const Sales_data&); inline bool operator == (const Sales_data &lhs, const Sales_data &rhs) { return lhs.units_sold == rhs.units_sold && \ lhs.sellingprice == rhs.sellingprice && \ lhs.saleprice == rhs.saleprice && \ lhs.isbn() == rhs.isbn(); } inline bool operator != (const Sales_data &lhs, const Sales_data &rhs) { return !(lhs == rhs); //基于运算符 == 给出 !=的定义 } Sales_data& Sales_data::operator += (const Sales_data& rhs) { units_sold += rhs.units_sold; saleprice = (rhs.saleprice * rhs.units_sold + saleprice * units_sold) \ / (rhs.units_sold + units_sold); if(sellingprice != 0) discount = saleprice / sellingprice; return *this; } Sales_data operator + (const Sales_data& lhs, const Sales_data& rhs) { Sales_data ret(lhs); //把lhs的内容拷贝到临时变量ret中,这种做法便于运算 ret += rhs; //把rhs的内容加入其中 return ret; //返回ret } std::istream& operator >> (std::istream& in, Sales_data& s) { in >> s.bookNo >> s.units_sold >> s.sellingprice >> s.saleprice; if((in && s.sellingprice) != 0) s.discount = s.saleprice / s.sellingprice; else s = Sales_data(); //输入错误,重置输入的数据 return in; } std::ostream& operator << (std::ostream& out, const Sales_data& s) { out << s.isbn() << " " << s.units_sold << " " << s.sellingprice \ << " " << s.saleprice << " " << s.discount; return out; } int main() { Sales_data book; std::cout << "请输入销售记录:" << std::endl; while(std::cin >> book) { std::cout << " ISBN,售出本数,原始价格,实售价格,折扣为" << book << std::endl; } Sales_data trans1, trans2; std::cout << "请输入两条ISBN相同的销售记录:" << std::endl; std::cin >> trans1 >> trans2; if(compareIsbn(trans1, trans2)) std::cout << "汇总信息:ISBN,售出本数,原始价格,实售价格,折扣为" << trans1 + trans2 << std::endl; else std::cout << "两条销售记录的ISBN不同" << std::endl; Sales_data total, trans; std::cout << "请输入几条ISBN相同的销售记录:" << std::endl; if(std::cin >> trans) { while(std::cin >> trans) if(compareIsbn(total, trans)) //ISBN相同 { total = total + trans; } else //ISBN不同 { std::cout << "当前书籍ISBN不同" << std::endl; break; } } else { std::cout << "没有数据" << std::endl; return -1; } int num = 1; //记录当前书籍的销售记录总数 std::cout << "请输入若干销售记录:" << std::endl; if(std::cin >> trans1) { while(std::cin >> trans2) if(compareIsbn(trans1, trans2)) //ISBN相同 { num++; } else //ISBN不同 { std::cout << trans1.isbn() << "共有" << num << "条销售记录" << std::endl; trans1 = trans2; num = 1; } std::cout << trans1.isbn() << "共有" << num << "条销售记录" << std::endl; } else { std::cout << "没有数据" << std::endl; return -1; } return 0; }
C++
CL
9fb55e494d5a5d66db10fb3de32168e8b1c2f6dcbad09c31bfd4864f6cec0dfc
#pragma once #ifndef APP_SRC_EXECUTE_HPP_ #define APP_SRC_EXECUTE_HPP_ #include "message.hpp" #include "write.hpp" #include "read.hpp" #include "spdlog/spdlog.h" #include "fmt/core.h" #include <boost/asio/serial_port.hpp> #include <boost/system/error_code.hpp> #include <boost/asio/streambuf.hpp> #include <string> /* * Utility to synchronously execute specified command */ template< bool isSet, bool isXTest, bool isXRead, bool isXWrite, bool isXExec, typename Body > int execute( std::string const & device, boost::asio::serial_port & sp, Ringbeller::request<isSet, isXTest, isXRead, isXWrite, isXExec, Body> const & command, Ringbeller::response<Ringbeller::string_body, Ringbeller::vector_sequence> & response) { boost::system::error_code ec; // Write to the modem auto const wb = Ringbeller::write(sp, command, ec); if (ec) { spdlog::error("Failed to write to the device {}, Reason: {}", device, ec.message()); return -1; } fmt::print("Sent {} bytes to the modem\n", wb); // Read from the modem boost::asio::streambuf buf; auto rb = Ringbeller::read(sp, buf, response, ec); if (ec) { spdlog::error("Failed to read from the device {}, Reason: {}", device, ec.message()); return -1; } // Present the response fmt::print("Read {} bytes from the modem\n", rb); fmt::print("Response result code: {}\n", response.rc); if (not response.rc_text.empty()) { fmt::print("Response result text: {}\n", response.rc_text); } else { fmt::print("Response result text is empty\n"); } if (response.body.empty()) { fmt::print("Response body is empty\n"); } else for (auto const & line : response.body) { fmt::print("Response body: {}\n", line); } return 0; } #endif /* APP_SRC_EXECUTE_HPP_ */
C++
CL
9aef376551a8e00f20504feed8e6c246d8df96cd9cc472dee6aa488d59c4dd14
//======================================================================================== // // $File: //depot/devtech/16.0.x/plugin/source/private/toolkit/interfaces/IDiagnosticLogger.h $ // // Owner: gxiao // // $Author: pmbuilder $ // // $DateTime: 2020/11/06 13:08:29 $ // // $Revision: #2 $ // // $Change: 1088580 $ // // ADOBE CONFIDENTIAL // // Copyright 1997-2010 Adobe Systems Incorporated. All rights reserved. // // NOTICE: All information contained herein is, and remains // the property of Adobe Systems Incorporated and its suppliers, // if any. The intellectual and technical concepts contained // herein are proprietary to Adobe Systems Incorporated and its // suppliers and may be covered by U.S. and Foreign Patents, // patents in process, and are protected by trade secret or copyright law. // Dissemination of this information or reproduction of this material // is strictly forbidden unless prior written permission is obtained // from Adobe Systems Incorporated. // //======================================================================================== #pragma once #ifndef __IDiagnosticLogger__ #define __IDiagnosticLogger__ #include "IDiagLoggingAPI.h" #include "DiagnosticLogID.h" class ISAXAttributes; #define kDIAGLOGSTRINGBUFFERSIZE 256 #define kDIAGLOGLINEBUFFERSIZE 2048 /** This is logger interface. It implements common logging interface IDiagLoggingAPI. @see IDiagLoggingAPI */ class IDiagnosticLogger : public IDiagLoggingAPI { public: enum { kDefaultIID = IID_IDIAGNOSTICLOGGER }; typedef enum { kUnhandledException, kProtectiveShutdown } AppTerminationState; /** DiagLogStackItem is used by logger manager to store context information */ class DiagLogStackItem { public: DiagLogStackItem() {} DiagLogStackItem(const PMString &context, const clock_t &time) : fContext(context), fTimeStamp(time) {} const PMString &GetContext() const {return fContext;} const clock_t &GetTimeStamp() const {return fTimeStamp;} PMString fContext; clock_t fTimeStamp; }; /** Initialize logger. */ virtual void InitializeLogger() = 0; /** Enable a logger. @param enable boolean flag if to enable logger @return the logger with this name */ virtual void Enable(bool16 enable = kTrue) = 0; /** Return if logger is enabled. @return kTrue if logger is enabled */ virtual bool16 IsEnabled() const = 0; /** Return the logger name. @return PMString the name of logger */ virtual const PMString GetName() const = 0; /** Load logger configuration. @param attrs AttributeList which contains configuration data */ virtual void LoadLoggerConfig(ISAXAttributes * attrs) = 0; /** Generate logger configuration. @param attrs AttributeList which contains configuration data */ virtual void GenerateLoggerConfig(IXMLOutStream::AttributeList& attrs) = 0; /** Handle abnormal application termination. */ virtual void HandleAbnormalAppTermination(AppTerminationState state) = 0; /** Flush logger buffer during idle time. This function will be called from idle task. Logger shouldn't perform any long operation in this function. */ virtual void IdleFlush() = 0; /** Reset logger. Not implemented yet. */ virtual void Reset() = 0; }; #endif // __IDiagnosticLogger__
C++
CL
813db424d524c0203529d197184ca895ce17d08a4105a6996654a92f50ee9954
#include <GL/gl.h> #include <GL/glu.h> #include <GL/glut.h> #include <stdlib.h> #include <math.h> #include "ringue.h" #include "lutador.h" #include "iniciacao.h" #include "menu.h" #include "util.h" #define INC_KEY 1 #define INC_KEYIDLE 0.2 //Key status int keyStatus[256]; Menu menu; Iniciacao iniciacao; Util util; Lutador lutador; Lutador bot; Ringue ringue; // Window dimensions GLint Width; GLint Height; GLint WidthHalf; GLint HeightHalf; GLint pontoCentral; //Pontuacao GLint pontoLutador; GLint pontoBot; //Lutador Socando pow pow pow GLboolean parouDeSocarLutador = true; GLboolean botaoCerto; // Bot socando pow pow pow GLint distanciaSoco = 0; GLint distanciaSocoTotal = 200; GLint braco = 1; GLboolean parouDeSocarBot = true; // Tipo Jogo bool modoTreino; //Util int toggleCam = 0; bool toggleLight = false; bool toggleApagaTudo; int buttonDown = 0; //Texture GLuint texturePlane; GLuint textureBotWins; GLuint texturePlayerWins; GLuint LoadTextureRAW( const char * filename ) { GLuint texture; Image* image = loadBMP(filename); glGenTextures( 1, &texture ); glBindTexture( GL_TEXTURE_2D, texture ); glTexEnvf( GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE,GL_MODULATE ); // glTexEnvf( GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE,GL_REPLACE ); glTexParameterf( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER,GL_LINEAR ); glTexParameterf( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER,GL_LINEAR ); glTexImage2D(GL_TEXTURE_2D, //Always GL_TEXTURE_2D 0, //0 for now GL_RGB, //Format OpenGL uses for image image->width, image->height, //Width and height 0, //The border of the image GL_RGB, //GL_RGB, because pixels are stored in RGB format GL_UNSIGNED_BYTE, //GL_UNSIGNED_BYTE, because pixels are stored //as unsigned numbers image->pixels); //The actual pixel data delete image; return texture; } void changeCamera(int angle, int zNear, int zFar) { glMatrixMode (GL_PROJECTION); glLoadIdentity (); gluPerspective (angle, Width / Height, zNear, zFar); glMatrixMode (GL_MODELVIEW); glutPostRedisplay(); } void orthogonalStart() { glMatrixMode(GL_PROJECTION); // if(!toggleLight){ glDisable(GL_LIGHTING); // } glPushMatrix(); glLoadIdentity(); gluOrtho2D(-500/2, 500/2, -500/2, 500/2); glMatrixMode(GL_MODELVIEW); } void orthogonalEnd() { glMatrixMode(GL_PROJECTION); glEnable(GL_LIGHTING); glPopMatrix(); glMatrixMode(GL_MODELVIEW); } void background(GLuint texture) { orthogonalStart(); // texture width/height const int iw = 500; const int ih = 500; glPushMatrix(); glBindTexture( GL_TEXTURE_2D, texture); glTranslatef( -iw/2, -ih/2, 0 ); glBegin(GL_QUADS); glTexCoord2i(0,0); glVertex2i(0, 0); glTexCoord2i(1,0); glVertex2i(iw, 0); glTexCoord2i(1,1); glVertex2i(iw, ih); glTexCoord2i(0,1); glVertex2i(0, ih); glEnd(); glPopMatrix(); orthogonalEnd(); } void renderScene(void) { glMatrixMode(GL_MODELVIEW); glLoadIdentity(); glClearColor(0.692, 0.852, 0.988, 1.0f); // Black, no opacity(alpha). // glClearColor(0,0,0, 1.0f); // Black, no opacity(alpha). glClear ( GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); if(pontoLutador < 10 && pontoBot < 10) { background(texturePlane); menu.DesenhaMiniMapa(lutador.GetX(), lutador.GetY(), bot.GetX(), bot.GetY()); menu.DesenhaPlacar(pontoLutador, pontoBot); util.ProcessaCamera(toggleCam, lutador); // util.DrawAxes(50); ringue.Desenha(); util.Iluminacao(lutador, bot, toggleLight, ringue, toggleApagaTudo); bot.Desenha(toggleLight); lutador.Desenha(toggleLight); } else if(pontoLutador >= pontoBot) { background(texturePlayerWins); // background(); // menu.DesenhaFinalJogo(true); } else if(pontoBot > pontoLutador) { background(textureBotWins); // background(); // menu.DesenhaFinalJogo(false); } glutSwapBuffers(); // Desenha the new frame of the game. } void keyPress(unsigned char key, int x, int y) { switch (key) { case '+': util.zoom++; break; case '-': util.zoom--; break; case '1': toggleCam = 0; changeCamera(util.GetCamAngle(), 15, 1000); break; case '2': toggleCam = 1; changeCamera(50, 15, 1000); break; case '3': toggleCam = 2; changeCamera(util.GetCamAngle(), 5, 1000); break; case 'n': case 'N': toggleLight = !toggleLight; //Using keyStatus trick break; case 'a': case 'A': keyStatus[(int)('a')] = 1; //Using keyStatus trick break; case 'd': case 'D': keyStatus[(int)('d')] = 1; //Using keyStatus trick break; case 'w': case 'W': keyStatus[(int)('w')] = 1; //Using keyStatus trick break; case 's': case 'S': keyStatus[(int)('s')] = 1; //Using keyStatus trick break; case 'l': case 'L': toggleApagaTudo = !toggleApagaTudo; break; case 27 : exit(0); } glutPostRedisplay(); } void keyup(unsigned char key, int x, int y) { keyStatus[(int)(key)] = 0; glutPostRedisplay(); } void ResetKeyStatus() { int i; //Initialize keyStatus for(i = 0; i < 256; i++) keyStatus[i] = 0; } void init(void) { ResetKeyStatus(); glEnable(GL_TEXTURE_2D); glShadeModel (GL_SMOOTH); // glEnable(GL_LIGHTING); glEnable(GL_DEPTH_TEST); ringue.CarregaTexturas(); lutador.CarregaTexturas(); bot.CarregaTexturas(); texturePlane = LoadTextureRAW( "modelos/ceu.bmp" ); textureBotWins = LoadTextureRAW( "modelos/bot_wins.bmp" ); texturePlayerWins = LoadTextureRAW( "modelos/player_wins.bmp" ); ringue.CalculaAlturaComBaseNoLutador(lutador.altura); } void movimentaBot(double inc) { if(distanciaSoco <= 0) { distanciaSoco = 0; parouDeSocarBot = true; if(braco == 1){ braco = 2; } else if(braco == 2){ braco = 1; } } if(inc < 1){ inc = 1; } if(bot.VerificaSePode(inc, Width, Height, lutador.GetX(), lutador.GetY())){ bot.Anda(inc); } else { //distanciaSoco += inc; bool acertou = bot.Soca(distanciaSocoTotal, distanciaSoco, braco, lutador); if(acertou) { if(parouDeSocarBot) { pontoBot++; parouDeSocarBot = false; } distanciaSoco -= inc; } else { if(parouDeSocarBot) { distanciaSoco += inc; } else { distanciaSoco -= inc; } } } bot.GiraSozinho(inc, lutador.GetX(), lutador.GetY()); } bool VerificaSeEstaAndando() { if(keyStatus[(int)('w')]) { return false; } if(keyStatus[(int)('s')]) { return false; } if(keyStatus[(int)('a')]) { return false; } if(keyStatus[(int)('d')]) { return false; } return true; } void idle(void) { if(pontoLutador < 10 && pontoBot < 10) { static GLdouble previousTime = glutGet(GLUT_ELAPSED_TIME); GLdouble currentTime, timeDiference; currentTime = glutGet(GLUT_ELAPSED_TIME); timeDiference = currentTime - previousTime; previousTime = currentTime; double inc = INC_KEY * timeDiference * INC_KEYIDLE; // for(int i = 0; i < 90000000; i++); if(!modoTreino) { movimentaBot(inc); } //Treat keyPress if(keyStatus[(int)('w')]) { if(lutador.VerificaSePode(inc, Width, Height, bot.GetX(), bot.GetY())) { lutador.ParaDeSocar(); lutador.Anda(inc); } } if(keyStatus[(int)('s')]) { if(lutador.VerificaSePode(-inc, Width, Height, bot.GetX(), bot.GetY())) { lutador.ParaDeSocar(); lutador.Anda(-inc); } } if(keyStatus[(int)('a')]) { lutador.ParaDeSocar(); lutador.Gira(inc); } if(keyStatus[(int)('d')]) { lutador.ParaDeSocar(); lutador.Gira(-inc); } glutPostRedisplay(); } } void mouse(int button, int state, int x, int y) { if(state == 0) { pontoCentral = x; if(button == 0) { botaoCerto = true; } } else { botaoCerto = false; pontoCentral = 0; lutador.ParaDeSocar(); } if (button == GLUT_RIGHT_BUTTON && state == GLUT_DOWN){ util.lastX = x; util.lastY = y; buttonDown = 1; } if (button == GLUT_RIGHT_BUTTON && state == GLUT_UP) { buttonDown = 0; } } void mouseArrasta(int x, int y) { if(botaoCerto) { if(VerificaSeEstaAndando()) { GLfloat distanciaPercorrida = abs(x - pontoCentral); if(distanciaPercorrida > WidthHalf) { distanciaPercorrida = WidthHalf; } if(x > pontoCentral){ // cout << "socando" << endl; bool acertou = lutador.Soca(WidthHalf, distanciaPercorrida, 1, bot); if(acertou) { if(parouDeSocarLutador) { pontoLutador++; parouDeSocarLutador = false; } } else{ parouDeSocarLutador = true; } } else if(x < pontoCentral) { bool acertou = lutador.Soca(WidthHalf, distanciaPercorrida, 2, bot); if(acertou) { if(parouDeSocarLutador) { pontoLutador++; parouDeSocarLutador = false; } } else{ parouDeSocarLutador = true; } } } } else { if (!buttonDown) return; util.camYXAngle += x - util.lastX; util.camYZAngle -= y - util.lastY; util.lastX = x; util.lastY = y; GLfloat s = abs(util.camYXAngle*M_PI/180); GLfloat t = abs(util.camYZAngle*M_PI/180); // cout << "s: " << (util.camYXAngle) << " t: " << (util.camYZAngle) << endl; } glutPostRedisplay(); } void Inicializa(char *caminhoArquivo) { if(!iniciacao.ProcessaArquivo(caminhoArquivo)) { exit(0); } iniciacao.IniciaArena(Width, Height, WidthHalf, HeightHalf, ringue); iniciacao.IniciaLutadores(lutador, bot, ringue); iniciacao.TipoJogo(modoTreino); menu.Iniciacao(Width, Height); // ringue.Iniciacao(Width, Height, 3); } void reshape (int w, int h) { glViewport (0, 0, (GLsizei)w, (GLsizei)h); changeCamera(util.GetCamAngle(), 15, 1000); } int main(int argc, char *argv[]) { // Initialize openGL with Double buffer and RGB color without transparency. // Its interesting to try GLUT_SINGLE instead of GLUT_DOUBLE. glutInit(&argc, argv); glutInitDisplayMode (GLUT_DOUBLE | GLUT_RGB | GLUT_DEPTH); Inicializa(argv[1]); // Create the window. glutInitWindowSize(500, 500); glutInitWindowPosition(150,50); glutCreateWindow("Pow Pow Pow"); // Define callbacks. glutDisplayFunc(renderScene); glutKeyboardFunc(keyPress); glutIdleFunc(idle); glutReshapeFunc (reshape); glutKeyboardUpFunc(keyup); glutMotionFunc(mouseArrasta); glutMouseFunc(mouse); init(); glutMainLoop(); return 0; }
C++
CL
cadd9d5054c46b502868e865545b4404cbb32c1d484b052f986ee6a7280816bd
#pragma once #include<GL/glew.h> #include <glfw3.h> #include <GL/glm/glm.hpp> #include <GL/glm/gtc/matrix_transform.hpp> #include <iostream> #include <assert.h> #include <vendor/imgui/ImguiLib.h> #include "../../Dependencies/Action/Action.h" #define endl '\n' #define pi 3.14159265359 #define null 0 typedef unsigned int uint; typedef unsigned short ushort; typedef unsigned char uchar; #define ASSERT(x) if (!(x)) assert(false) #define gc(x) GLClearError();\ x;\ ASSERT(GLCheckError()) static void GLClearError() { while (glGetError() != GL_NO_ERROR); } template<typename T> inline float Det(const T& a, const T& b) { return a.x * b.y - a.y * b.x; } static bool GLCheckError() { while (GLenum error = glGetError()) { std::cout << "[OpenGL Error] "; switch (error) { case GL_INVALID_ENUM: std::cout << "GL_INVALID_ENUM : An unacceptable value is specified for an enumerated argument."; break; case GL_INVALID_VALUE: std::cout << "GL_INVALID_OPERATION : A numeric argument is out of range."; break; case GL_INVALID_OPERATION: std::cout << "GL_INVALID_OPERATION : The specified operation is not allowed in the current state."; break; case GL_INVALID_FRAMEBUFFER_OPERATION: std::cout << "GL_INVALID_FRAMEBUFFER_OPERATION : The framebuffer object is not complete."; break; case GL_OUT_OF_MEMORY: std::cout << "GL_OUT_OF_MEMORY : There is not enough memory left to execute the command."; break; case GL_STACK_UNDERFLOW: std::cout << "GL_STACK_UNDERFLOW : An attempt has been made to perform an operation that would cause an internal stack to underflow."; break; case GL_STACK_OVERFLOW: std::cout << "GL_STACK_OVERFLOW : An attempt has been made to perform an operation that would cause an internal stack to overflow."; break; default: std::cout << "Unrecognized error" << error; } std::cout << endl; return false; } return true; } struct ARGBColor { ARGBColor() {} ARGBColor(uchar a, uchar r, uchar g, uchar b) :a(a), r(r), b(b), g(g) {} uchar r = 255, g = 255, b = 255, a = 255; }; struct Color { //Constructors Color() {} Color(float r, float g, float b) :rgb(r, g, b) {} Color(glm::vec3 color) :rgb(color) {} //Static funcs static Color Black() { return Color(0, 0, 0); }; static Color White() { return Color(1, 1, 1); }; static Color Red() { return Color(1, 0, 0); }; static Color Green() { return Color(0, 1, 0); }; static Color Blue() { return Color(0, 0, 1); }; static Color Random() { return Color( (float)rand() / (float)RAND_MAX, (float)rand() / (float)RAND_MAX, (float)rand() / (float)RAND_MAX); } //Methods void GammaCorrect() { rgb = sqrt(rgb); } // Operators Color operator*(float f)const { return this->rgb * f; } operator ARGBColor() const { return ARGBColor(255, uchar(rgb.r * 255), uchar(rgb.g * 255), uchar(rgb.b * 255)); } Color operator+(const Color& c)const { return Color(rgb + c.rgb); } Color operator*(const Color& c)const { return { c.rgb * rgb }; } // Public Fields glm::vec3 rgb = glm::vec3(0); };
C++
CL
a0b1ee7030401cbe6d78d34dfbf16b16a29021d7ded3729edf2d3a659ff7a6eb
#include "nan.h" #include "v8-helpers.hh" #include "EGLWindowObject.hh" namespace node_angle { static const auto constAttribute = static_cast<v8::PropertyAttribute>(v8::ReadOnly | v8::DontDelete); #define EXPORT_GL_CONSTANT(target, name) \ do { \ Nan::HandleScope scope; \ Nan::ForceSet( \ target, \ Nan::New(#name).ToLocalChecked(), \ Nan::New(GL_##name), \ constAttribute); \ } while (0) #define ARG_JUST(index, type, name) \ auto name##Maybe = Nan::To<type>(info[index]); \ if (name##Maybe.IsNothing()) { \ return Nan::ThrowTypeError("Arg '"#name"' must be type "#type); \ } \ auto name = name##Maybe.FromJust(); #define ARG_LOCAL(index, type, name) \ auto name##Maybe = Nan::To<type>(info[index]); \ if (name##Maybe.IsEmpty()) { \ return Nan::ThrowTypeError("Arg '"#name"' must be type "#type); \ } \ auto name = name##Maybe.ToLocalChecked(); #define ARG_STRING(index, name) \ ARG_LOCAL(index, v8::String, name##Local) \ auto name = V8StringToUTF8StdString(name##Local); NAN_METHOD(createShader) { ARG_JUST(0, int32_t, type); auto result = glCreateShader(type); info.GetReturnValue().Set(result); } NAN_METHOD(shaderSource) { ARG_JUST(0, int32_t, shader); ARG_STRING(1, source); auto sourceArray = { source.data() }; glShaderSource(shader, std::size(sourceArray), std::data(sourceArray), nullptr); } NAN_METHOD(compileShader) { ARG_JUST(0, int32_t, shader); glCompileShader(shader); } NAN_METHOD(deleteShader) { ARG_JUST(0, int32_t, shader); glDeleteShader(shader); } NAN_METHOD(getShaderParameter) { ARG_JUST(0, int32_t, shader); ARG_JUST(1, int32_t, pname); switch (pname) { default: return Nan::ThrowRangeError("Invalid shader parameter name"); case GL_SHADER_TYPE: case GL_COMPILE_STATUS: break; } GLint value; glGetShaderiv(shader, pname, &value); info.GetReturnValue().Set(value); } NAN_METHOD(getShaderInfoLog) { ARG_JUST(0, int32_t, shader); GLint length = 0; glGetShaderiv(shader, GL_INFO_LOG_LENGTH, &length); if (length <= 1) { return info.GetReturnValue().SetEmptyString(); } std::vector<GLchar> buffer(length); glGetShaderInfoLog(shader, length, nullptr, buffer.data()); info.GetReturnValue().Set(Nan::New(buffer.data()).ToLocalChecked()); } NAN_METHOD(createProgram) { auto result = glCreateProgram(); info.GetReturnValue().Set(result); } NAN_METHOD(attachShader) { ARG_JUST(0, int32_t, program); ARG_JUST(1, int32_t, shader); glAttachShader(program, shader); } NAN_METHOD(linkProgram) { ARG_JUST(0, int32_t, program); glLinkProgram(program); } NAN_METHOD(deleteProgram) { ARG_JUST(0, int32_t, program); glDeleteProgram(program); } NAN_METHOD(useProgram) { ARG_JUST(0, int32_t, program); glUseProgram(program); } NAN_METHOD(getProgramParameter) { ARG_JUST(0, int32_t, program); ARG_JUST(1, int32_t, pname); switch (pname) { default: return Nan::ThrowRangeError("Invalid program parameter name"); case GL_LINK_STATUS: break; } GLint value; glGetProgramiv(program, pname, &value); info.GetReturnValue().Set(value); } NAN_METHOD(getProgramInfoLog) { ARG_JUST(0, int32_t, program); GLint length = 0; glGetProgramiv(program, GL_INFO_LOG_LENGTH, &length); if (length <= 1) { return info.GetReturnValue().SetEmptyString(); } std::vector<GLchar> buffer(length); glGetProgramInfoLog(program, length, nullptr, buffer.data()); info.GetReturnValue().Set(Nan::New(buffer.data()).ToLocalChecked()); } NAN_METHOD(viewport) { ARG_JUST(0, int32_t, x); ARG_JUST(1, int32_t, y); ARG_JUST(2, int32_t, width); ARG_JUST(3, int32_t, height); glViewport(x, y, width, height); } NAN_METHOD(clearColor) { ARG_JUST(0, double, red); ARG_JUST(1, double, green); ARG_JUST(2, double, blue); ARG_JUST(3, double, alpha); glClearColor( static_cast<float>(red), static_cast<float>(green), static_cast<float>(blue), static_cast<float>(alpha)); } NAN_METHOD(clear) { ARG_JUST(0, uint32_t, mask); glClear(mask); } NAN_METHOD(cullFace) { ARG_JUST(0, int32_t, mode); glCullFace(mode); } NAN_METHOD(enable) { ARG_JUST(0, int32_t, cap); glEnable(cap); } NAN_METHOD(disable) { ARG_JUST(0, int32_t, cap); glDisable(cap); } NAN_METHOD(createBuffer) { GLuint buffer; glGenBuffers(1, &buffer); info.GetReturnValue().Set(buffer); } NAN_METHOD(bindBuffer) { ARG_JUST(0, int32_t, target); ARG_JUST(1, uint32_t, buffer); glBindBuffer(target, buffer); } NAN_METHOD(bufferData) { ARG_JUST(0, int32_t, target); ARG_LOCAL(1, v8::Object, bufferData); ARG_JUST(2, int32_t, usage); Nan::TypedArrayContents<uint8_t> contents{ bufferData }; if (!*contents) { return Nan::ThrowTypeError("Arg 'bufferData' must be any ArrayBufferView (e.g. Float32Array)"); } glBufferData(target, contents.length(), *contents, usage); } NAN_METHOD(getAttribLocation) { ARG_JUST(0, int32_t, program); ARG_STRING(1, name); auto location = glGetAttribLocation(program, name.c_str()); info.GetReturnValue().Set(location); } NAN_METHOD(uniformMatrix) { ARG_JUST(0, int32_t, location); ARG_JUST(1, int32_t, count); ARG_JUST(2, bool, transpose); ARG_LOCAL(3, v8::Object, matrix); if (!matrix->IsFloat32Array()) { return Nan::ThrowTypeError("Arg 'matrix' must be Float32Array."); } Nan::TypedArrayContents<float> contents{ matrix }; if (contents.length() != 16) { return Nan::ThrowTypeError("Arg 'matrix' must have length 16."); } glUniformMatrix4fv(location, count, transpose, *contents); } NAN_METHOD(getUniformLocation) { ARG_JUST(0, int32_t, program); ARG_STRING(1, name); auto location = glGetUniformLocation(program, name.c_str()); info.GetReturnValue().Set(location); } NAN_METHOD(enableVertexAttribArray) { ARG_JUST(0, int32_t, location); glEnableVertexAttribArray(location); } NAN_METHOD(vertexAttribPointer) { ARG_JUST(0, int32_t, location); ARG_JUST(1, int32_t, size); ARG_JUST(2, int32_t, type); ARG_JUST(3, bool, normalized); ARG_JUST(4, int32_t, stride); ARG_JUST(5, intptr_t, offset); glVertexAttribPointer( location, size, type, normalized, stride, reinterpret_cast<void*>(offset)); } NAN_METHOD(drawArrays) { ARG_JUST(0, int32_t, mode); ARG_JUST(1, int32_t, first); ARG_JUST(2, int32_t, count); glDrawArrays(mode, first, count); } NAN_METHOD(drawElements) { ARG_JUST(0, int32_t, mode); ARG_JUST(1, int32_t, count); ARG_JUST(2, int32_t, type); ARG_JUST(3, intptr_t, offset); glDrawElements(mode, count, type, reinterpret_cast<void*>(offset)); } NAN_MODULE_INIT(InitAll) { NAN_EXPORT(target, createShader); NAN_EXPORT(target, shaderSource); NAN_EXPORT(target, compileShader); NAN_EXPORT(target, deleteShader); NAN_EXPORT(target, getShaderParameter); NAN_EXPORT(target, getShaderInfoLog); NAN_EXPORT(target, createProgram); NAN_EXPORT(target, attachShader); NAN_EXPORT(target, linkProgram); NAN_EXPORT(target, deleteProgram); NAN_EXPORT(target, useProgram); NAN_EXPORT(target, getProgramParameter); NAN_EXPORT(target, getProgramInfoLog); NAN_EXPORT(target, viewport); NAN_EXPORT(target, clearColor); NAN_EXPORT(target, clear); NAN_EXPORT(target, cullFace); NAN_EXPORT(target, enable); NAN_EXPORT(target, disable); NAN_EXPORT(target, createBuffer); NAN_EXPORT(target, bindBuffer); NAN_EXPORT(target, bufferData); NAN_EXPORT(target, enableVertexAttribArray); NAN_EXPORT(target, vertexAttribPointer); NAN_EXPORT(target, getAttribLocation); NAN_EXPORT(target, uniformMatrix); NAN_EXPORT(target, getUniformLocation); NAN_EXPORT(target, drawArrays); NAN_EXPORT(target, drawElements); EXPORT_GL_CONSTANT(target, VERTEX_SHADER); EXPORT_GL_CONSTANT(target, FRAGMENT_SHADER); EXPORT_GL_CONSTANT(target, COMPILE_STATUS); EXPORT_GL_CONSTANT(target, LINK_STATUS); EXPORT_GL_CONSTANT(target, COLOR_BUFFER_BIT); EXPORT_GL_CONSTANT(target, ARRAY_BUFFER); EXPORT_GL_CONSTANT(target, ELEMENT_ARRAY_BUFFER); EXPORT_GL_CONSTANT(target, STATIC_DRAW); #undef FLOAT EXPORT_GL_CONSTANT(target, FLOAT); EXPORT_GL_CONSTANT(target, UNSIGNED_SHORT); EXPORT_GL_CONSTANT(target, TRIANGLES); EXPORT_GL_CONSTANT(target, BACK); EXPORT_GL_CONSTANT(target, CULL_FACE); EGLWindowObject::Init(target); } NODE_MODULE(angle, InitAll) }
C++
CL
8b7b3eeed269af07d516cf0bedf5a2e940c90a98c29f5c0b8f55ad643533601b
// Copyright 2017-2023 Closed Sum Games, LLC. All Rights Reserved. #pragma once #include "Kismet/KismetSystemLibrary.h" class UWorld; class AActor; namespace NCsDebug { namespace NDraw { struct CSCORE_API FLibrary { static const float DEBUG_IMPACTPOINT_SIZE; /** * Draw a debug line */ static void DrawDebugLine(const UWorld* InWorld, FVector3f const& LineStart, FVector3f const& LineEnd, FColor const& Color, bool bPersistentLines = false, float LifeTime = -1.f, uint8 DepthPriority = 0, float Thickness = 0.f); /** * Draw a debug point */ static void DrawDebugPoint(const UWorld* InWorld, FVector3f const& Position, float Size, FColor const& PointColor, bool bPersistentLines = false, float LifeTime = -1.f, uint8 DepthPriority = 0); /** * Draw directional arrow */ static void DrawDebugDirectionalArrow(const UWorld* InWorld, FVector3f const& LineStart, FVector3f const& LineEnd, float ArrowSize, FColor const& Color, bool bPersistentLines = false, float LifeTime = -1.f, uint8 DepthPriority = 0, float Thickness = 0.f); /** * Draw a debug box */ static void DrawDebugBox(const UWorld* InWorld, FVector3f const& Center, FVector3f const& Extent, FColor const& Color, bool bPersistentLines = false, float LifeTime = -1.f, uint8 DepthPriority = 0, float Thickness = 0.f); /** * Draw a debug box with rotation */ static void DrawDebugBox(const UWorld* InWorld, FVector3f const& Center, FVector3f const& Extent, const FQuat4f& Rotation, FColor const& Color, bool bPersistentLines = false, float LifeTime = -1.f, uint8 DepthPriority = 0, float Thickness = 0.f); /** * Draw Debug Circle */ static void DrawDebugCircle(const UWorld* InWorld, const FMatrix44f& TransformMatrix, float Radius, int32 Segments, const FColor& Color, bool bPersistentLines = false, float LifeTime = -1.f, uint8 DepthPriority = 0, float Thickness = 0.f, bool bDrawAxis = true); /** * Draw Debug Circle */ static void DrawDebugCircle(const UWorld* InWorld, FVector3f Center, float Radius, int32 Segments, const FColor& Color, bool bPersistentLines = false, float LifeTime = -1.f, uint8 DepthPriority = 0, float Thickness = 0.f, FVector3f YAxis = FVector3f(0.f, 1.f, 0.f), FVector3f ZAxis = FVector3f(0.f, 0.f, 1.f), bool bDrawAxis = true); /** * Draw a capsule using the LineBatcher */ static void DrawDebugCapsule(const UWorld* InWorld, FVector3f const& Center, float HalfHeight, float Radius, const FQuat4f& Rotation, FColor const& Color, bool bPersistentLines = false, float LifeTime = -1.f, uint8 DepthPriority = 0, float Thickness = 0); /** * Draw Debug 2D donut */ static void DrawDebug2DDonut(const UWorld* InWorld, const FMatrix44f& TransformMatrix, float InnerRadius, float OuterRadius, int32 Segments, const FColor& Color, bool bPersistentLines = false, float LifeTime = -1.f, uint8 DepthPriority = 0, float Thickness = 0.f); /** * Draw a debug sphere */ static void DrawDebugSphere(const UWorld* InWorld, FVector3f const& Center, float Radius, int32 Segments, FColor const& Color, bool bPersistentLines = false, float LifeTime = -1.f, uint8 DepthPriority = 0, float Thickness = 0.f); /** * Draw a debug cone. AngleWidth and AngleHeight are given in radians */ static void DrawDebugCone(const UWorld* InWorld, FVector3f const& Origin, FVector3f const& Direction, float Length, float AngleWidth, float AngleHeight, int32 NumSides, FColor const& Color, bool bPersistentLines = false, float LifeTime = -1.f, uint8 DepthPriority = 0, float Thickness = 0.f); static void DrawDebugString(const UWorld* InWorld, FVector3f const& TextLocation, const FString& Text, class AActor* TestBaseActor = NULL, FColor const& TextColor = FColor::White, float Duration = -1.000000, bool bDrawShadow = false, float FontScale = 1.f); /** Draw a solid box. Various API's provided for convenience, including ones that use FBox as well as ones that prefer (Center, Extent). **/ /** * Draw a Debug box with optional transform. */ static void DrawDebugSolidBox(const UWorld* InWorld, FBox3f const& Box, FColor const& Color, const FTransform3f& Transform = FTransform3f::Identity, bool bPersistent = false, float LifeTime = -1.f, uint8 DepthPriority = 0); /** * Draw a Debug box from (Center, Extent) with no rotation (axis-aligned) */ static void DrawDebugSolidBox(const UWorld* InWorld, FVector3f const& Center, FVector3f const& Extent, FColor const& Color, bool bPersistent = false, float LifeTime = -1.f, uint8 DepthPriority = 0); /** * Draw a Debug box from (Center, Extent) with specified Rotation */ static void DrawDebugSolidBox(const UWorld* InWorld, FVector3f const& Center, FVector3f const& Extent, FQuat4f const& Rotation, FColor const& Color, bool bPersistent = false, float LifeTime = -1.f, uint8 DepthPriority = 0); static FCollisionQueryParams ConfigureCollisionParams(FName TraceTag, bool bTraceComplex, const TArray<AActor*>& ActorsToIgnore, bool bIgnoreSelf, UObject* WorldContextObject); static FCollisionObjectQueryParams ConfigureCollisionObjectParams(const TArray<TEnumAsByte<EObjectTypeQuery> >& ObjectTypes); static void SweptSphere(const UWorld* InWorld, FVector3f const& Start, FVector3f const& End, float Radius, FColor const& Color, bool bPersistentLines = false, float LifeTime = -1.f, uint8 DepthPriority = 0); static void SweptBox(const UWorld* InWorld, FVector3f const& Start, FVector3f const& End, FRotator3f const& Orientation, FVector3f const& HalfSize, FColor const& Color, bool bPersistentLines = false, float LifeTime = -1.f, uint8 DepthPriority = 0); static void LineTraceSingle(const UWorld* World, const FVector3f& Start, const FVector3f& End, EDrawDebugTrace::Type DrawDebugType, bool bHit, const FHitResult& OutHit, FLinearColor TraceColor, FLinearColor TraceHitColor, float DrawTime); static void LineTraceMulti(const UWorld* World, const FVector3f& Start, const FVector3f& End, EDrawDebugTrace::Type DrawDebugType, bool bHit, const TArray<FHitResult>& OutHits, FLinearColor TraceColor, FLinearColor TraceHitColor, float DrawTime); static void BoxTraceSingle(const UWorld* World, const FVector3f& Start, const FVector3f& End, const FVector3f HalfSize, const FRotator3f Orientation, EDrawDebugTrace::Type DrawDebugType, bool bHit, const FHitResult& OutHit, FLinearColor TraceColor, FLinearColor TraceHitColor, float DrawTime); static void BoxTraceMulti(const UWorld* World, const FVector3f& Start, const FVector3f& End, const FVector3f HalfSize, const FRotator3f Orientation, EDrawDebugTrace::Type DrawDebugType, bool bHit, const TArray<FHitResult>& OutHits, FLinearColor TraceColor, FLinearColor TraceHitColor, float DrawTime); static void SphereTraceSingle(const UWorld* World, const FVector3f& Start, const FVector3f& End, float Radius, EDrawDebugTrace::Type DrawDebugType, bool bHit, const FHitResult& OutHit, FLinearColor TraceColor, FLinearColor TraceHitColor, float DrawTime); static void SphereTraceMulti(const UWorld* World, const FVector3f& Start, const FVector3f& End, float Radius, EDrawDebugTrace::Type DrawDebugType, bool bHit, const TArray<FHitResult>& OutHits, FLinearColor TraceColor, FLinearColor TraceHitColor, float DrawTime); static void CapsuleTraceSingle(const UWorld* World, const FVector3f& Start, const FVector3f& End, float Radius, float HalfHeight, EDrawDebugTrace::Type DrawDebugType, bool bHit, const FHitResult& OutHit, FLinearColor TraceColor, FLinearColor TraceHitColor, float DrawTime); static void CapsuleTraceMulti(const UWorld* World, const FVector3f& Start, const FVector3f& End, float Radius, float HalfHeight, EDrawDebugTrace::Type DrawDebugType, bool bHit, const TArray<FHitResult>& OutHits, FLinearColor TraceColor, FLinearColor TraceHitColor, float DrawTime); static void String(const UWorld* InWorld, FVector3f const& TextLocation, const FString& Text, AActor* TestBaseActor = NULL, FColor const& TextColor = FColor::White, float Duration = -1.000000, bool bDrawShadow = false, float FontScale = 1.f); }; } }
C++
CL
630fc50351a6a9cca54014721804a30e18bd7020b0704b6c8d7dbb0219ed592c
#pragma once #include "InitialDFA.h" #include "RegularDFA.h" #include "GroupState.h" class GroupDFA { public: GroupDFA(); ~GroupDFA(); void createFromInitialDFA(const InitialDFA& initialDfa, RegularDFA &intvertedRegularDfa); bool returnNextState( const std::set<std::size_t> &action, std::size_t &nextStateNumber, std::vector<std::size_t> &groupNumbers); std::size_t getActualState() const { return actualState; } std::size_t getStartState() const { return initialState; } std::size_t getFinalStates() const { return finalState; } std::size_t getSize() const { return states.size(); } void returnToStartPosition() { actualState = initialState; } void returnMovePossibility( const std::size_t &number, std::map<const std::set<std::size_t>, std::size_t> &pNextStates, std::vector<std::size_t> &groupNumbers) const; void print(std::string &output) const; private: void createGroupDfa(const InitialDFA& initialDfa, RegularDFA &regualarDfa); std::vector<GroupState *> states; std::unordered_map<const GroupState *, std::size_t> mapStates; std::map<std::size_t, std::size_t> groupsMap; std::size_t initialState; std::size_t finalState; std::size_t actualState; };
C++
CL
12ae91c1444e86c3c53191f30452ef1c65e266690df5acf84e16bfdcd1390323
/****************************************************************************** * jlp_wxgdev_popup_create.cpp * JLP_wxGDev_Popup class * Purpose: Popup menu for displaying a curve with wxwidgets * * Author: JLP * Version: 12/03/2020 ******************************************************************************/ #include <stdio.h> #include <stdlib.h> #include "jlp_wxgdev_popup.h" #include "jlp_wxgdev_popup_id.h" // ID_INFO, .... /*** #include "jlp_wxgdev_labels.h" #include "jlp_wxgdev_shapes.h" #include "jlp_wx_cursor.h" #include "jlp_itt1.h" ***/ /* #define DEBUG */ /************************************************************* * Delete the previous popup menu * *************************************************************/ void JLP_wxGDev_Popup::DeletePopupMenu() { if(PopupMenu1 != NULL) { if(menuInfo != NULL) delete menuInfo; menuInfo = NULL; /** WARNING: SUBMENUS SHOULD NOT BE DELETED SEPARATELY ... // menuCursor: submenu of menuSetup: should be deleted first ? if(menuCursor != NULL) delete menuCursor; menuCursor = NULL; // menuPen: submenu of menuSetup: should be deleted first ? if(menuPen != NULL) delete menuPen; menuPen = NULL; // menuBackgd: submenu of menuSetup: should be deleted first ? if(menuBackgd != NULL) delete menuBackgd; menuBackgd = NULL; // menuLUT: submenu of menuSetup: should be deleted first ? if(menuLUT != NULL) delete menuLUT; menuLUT = NULL; // menuITT1: submenu of menuSetup: should be deleted first ? if(menuITT1 != NULL) delete menuITT1; menuITT1 = NULL; // menuITT2: submenu of menuSetup: should be deleted first ? if(menuITT2 != NULL) delete menuITT2; menuITT2 = NULL; // menuZoom: submenu of menuSetup: should be deleted first ? if(menuZoom != NULL) delete menuZoom; menuZoom = NULL; ***/ // menuSetup: should also delete all submenus... if(menuSetup != NULL) delete menuSetup; menuSetup = NULL; if(menuGsegraf != NULL) delete menuGsegraf; menuGsegraf = NULL; if(menuFilter != NULL) delete menuFilter; menuFilter = NULL; if(menuProcess != NULL) delete menuProcess; menuProcess = NULL; if(menuLabel != NULL) delete menuLabel; menuLabel = NULL; if(menuShape != NULL) delete menuShape; menuShape = NULL; if(menuBoxType != NULL) delete menuBoxType; menuBoxType = NULL; if(menuBoxLimits != NULL) delete menuBoxLimits; menuBoxLimits = NULL; // PopupMenu1: should be deleted the last // problem here ... // delete PopupMenu1; PopupMenu1 = NULL; } return; } /************************************************************************ * Create the popup menu corresponding to gdev_graphic_type1 * ************************************************************************/ void JLP_wxGDev_Popup::CreatePopupMenu() { bool display_image; if(PopupMenu1 != NULL) DeletePopupMenu(); PopupMenu1 = new wxMenu; #if 0 PopupMenu1.AppendCheckItem(ID_MENU_ToBeChecked, _T("To be &checked")); PopupMenu1.Append(ID_MENU_ToBeGreyed, _T("To be &greyed"), _T("This menu item should be initially greyed out")); PopupMenu1.AppendSeparator(); PopupMenu1.Delete(ID_MENU_ToBeDeleted); PopupMenu1.Check(ID_MENU_ToBeChecked, true); PopupMenu1.Enable(ID_MENU_ToBeGreyed, false); #endif #ifdef DEBUG printf("CreatePopupMenu/ gdev_graphic_type=%d\n", gdev_graphic_type1); #endif // ***************** Info menu ********************************** /* GDevGraphicType: * 1 = jlp_splot_curves * 2 = jlp_splot_images * 3 = wx_scrolled/jlp_splot_images * 4 = gsegraf_2d_curves * 5 = gsegraf_2d_images * 6 = gsegraf_3d_curves * 7 = gsegraf_3d_images * 8 = gsegraf_polar_curve */ if((gdev_graphic_type1 == 2) || (gdev_graphic_type1 == 3) || (gdev_graphic_type1 == 5) || (gdev_graphic_type1 == 7)) { display_image = true; } else { display_image = false; } menuInfo = new wxMenu; if(display_image == true) { menuInfo->Append( ID_INFO_IMAGE, _T("Info. about image")); if((gdev_graphic_type1 == 2) || (gdev_graphic_type1 == 3) || (gdev_graphic_type1 == 5)) { menuInfo->Append( ID_DISPLAY_IMAGE_3D, _T("Display the image in 3D"), _T("Plot to a separate frame")); menuInfo->Append( ID_DISPLAY_IMAGE_CONTOURS, _T("Display the image contours"), _T("Plot to a separate frame")); } } else { menuInfo->Append( ID_INFO_CURVE, _T("Info. about curve(s)")); } menuInfo->AppendSeparator(); // ***************** Clipboard submenu ****************************** if(display_image == true) { menuInfo->Append(wxID_COPY, _T("Copy image\tCtrl-C")); menuInfo->Append(wxID_PASTE, _T("Paste image\tCtrl-V")); } else { menuInfo->Append(wxID_COPY, _T("&Copy curve\tCtrl-C")); } menuInfo->AppendSeparator(); // ***************** Save submenu ****************************** menuInfo->Append(ID_SAVE_TO_PST, _T("Save to postscript"), _T("Save graphic to postscript file")); menuInfo->Append(ID_SAVE, _T("&Save as ..."), _T("Save to bmp, jpg, png, pcx, pnm, tiff, xpm, ico, cur")); if(display_image == true) { PopupMenu1->Append(wxID_ANY, _T("&Image"), menuInfo); } else { PopupMenu1->Append(wxID_ANY, _T("&Curve"), menuInfo); } // ***************** Setup menu ********************************** menuSetup = new wxMenu; // ***************** Colour pen submenu ****************************** menuPen = new wxMenu; menuPen->Append(ID_BLACK_PEN_COLOUR, _T("Black Pen"), _T("Pen colour"), wxITEM_RADIO); menuPen->Append(ID_RED_PEN_COLOUR, _T("Red Pen"), _T("Pen colour"), wxITEM_RADIO); menuPen->Append(ID_GREEN_PEN_COLOUR, _T("Green Pen"), _T("Pen colour"), wxITEM_RADIO); menuPen->Append(ID_BLUE_PEN_COLOUR, _T("Blue Pen"), _T("Pen colour"), wxITEM_RADIO); menuPen->Append(ID_WHITE_PEN_COLOUR, _T("White Pen"), _T("Pen colour"), wxITEM_RADIO); menuSetup->AppendSubMenu(menuPen, _T("Pen"), _T("Select Pen properties")); // Colour background (for curves only) CreateColourBackgroundMenu(); // ***************** Cursor submenu ****************************** menuCursor = new wxMenu; menuCursor->Append(ID_CURSOR_CROSS, _T("Cross"), _T("Cursor shape"), wxITEM_RADIO); menuCursor->Append(ID_CURSOR_BIG_CROSS, _T("BigCross"), _T("Cursor shape"), wxITEM_RADIO); menuCursor->Append(ID_CURSOR_ARROW, _T("Arrow"), _T("Cursor shape"), wxITEM_RADIO); menuCursor->Append(ID_CURSOR_DOWN_ARROW, _T("DownArrow"), _T("Cursor shape"), wxITEM_RADIO); menuCursor->Append(ID_CURSOR_CROSSHAIR, _T("CrossHair"), _T("Cursor shape"), wxITEM_RADIO); menuCursor->Append(ID_CURSOR_CROSSHAIR1, _T("CrossHair with a cross"), _T("Cursor shape"), wxITEM_RADIO); menuSetup->AppendSubMenu(menuCursor, _T("Cursor"), _T("Select the cursor type")); // LUT, ITT, discrete zoom (for jlp_splot/images only) CreateImageMenuForSplot(); PopupMenu1->Append(wxID_ANY, _T("&Setup"), menuSetup); // Filter menu (for jlp_splot/images only) CreateImageMenuFilterForSplot(); CreateSetupMenuForCurves(); // Gsegraf menu CreateGsegrafMenu(); // ***************** Label menu ****************************** menuLabel = new wxMenu; menuLabel->Append(ID_ADD_LABEL, _T("Add a label"), wxT("Label positioned with the mouse")); menuLabel->Append(ID_REM_LABEL, _T("Remove a label"), wxT("Remove a label by clicking on the mouse")); // Scale and orientation for jlp_splot/images only if(display_image == true) { menuLabel->Append(ID_ADD_SCALE, _T("Add the scale"), wxT("Scale positioned with the mouse")); menuLabel->Append(ID_REM_SCALE, _T("Remove the scale"), wxT("Remove the scale (if already entered)")); menuLabel->Append(ID_ADD_NORTH_EAST, wxT("Add the North-East label"), wxT("North-East label positioned with the mouse")); menuLabel->Append(ID_REM_NORTH_EAST, wxT("Remove the North-East label"), wxT("Remove the North-East label (if already entered)")); } // Not available yet for gsegraf: if(gdev_graphic_type1 <= 3) { PopupMenu1->Append(wxID_ANY, _T("Labels"), menuLabel); } // ***************** Shape menu ****************************** CreateShapeMenu(); /* GDevGraphicType: * 1 = jlp_splot_curves * 2 = jlp_splot_images * 3 = wx_scrolled/jlp_splot_images * 4 = gsegraf_2d_curves * 5 = gsegraf_2d_images * 6 = gsegraf_3d_curves * 7 = gsegraf_3d_images * 8 = gsegraf_polar_curve */ // ***************** Image/Curve processing menu ****************************** menuProcess = new wxMenu; if(gdev_graphic_type1 <= 3) { menuProcess->AppendCheckItem( ID_STATISTICS, _T("Statistics in a box"), wxT("Rectangular box selected by the user")); } // Photometry in a circle, for jlp_splot/images only: if(gdev_graphic_type1 == 3) { menuProcess->AppendCheckItem( ID_PHOTOMETRY, _T("Photometry in a circle"), wxT("Circle selected by the user")); menuProcess->AppendCheckItem( ID_ASTROMETRY, _T("Astrometry in a circle"), wxT("Circle selected by the user")); menuProcess->AppendCheckItem( ID_SLICE, _T("Slice along a line"), wxT("Line selected by the user")); // Photometry in a box, for jlp_splot/curves only: } else if(gdev_graphic_type1 == 1) { menuProcess->AppendCheckItem( ID_PHOTOMETRY, _T("Photometry in a box"), wxT("Rectangle selected by the user")); menuProcess->AppendCheckItem( ID_ASTROMETRY, _T("Astrometry in a box"), wxT("Rectangle selected by the user")); } else if(gdev_graphic_type1 == 5) { menuProcess->AppendCheckItem(ID_LABEL_CONTOURS, wxT("Label contours"), wxT("Interactive labelling of contours (if appropriate)")); } menuProcess->AppendCheckItem( ID_GET_COORDINATES, _T("Get list of coordinates"), wxT("Interactive input of a list of coordinates")); PopupMenu1->Append(wxID_ANY, _T("Processing"), menuProcess); return; } /**************************************************************************** * LUT, ITT, discrete zoom, and filter menu * For jlp_splot images ****************************************************************************/ void JLP_wxGDev_Popup::CreateImageMenuForSplot() { /* GDevGraphicType: * 1 = jlp_splot_curves * 2 = jlp_splot_images * 3 = wx_scrolled/jlp_splot_images * 4 = gsegraf_2d_curves * 5 = gsegraf_2d_images * 6 = gsegraf_3d_curves * 7 = gsegraf_3d_images * 8 = gsegraf_polar_curve */ if((gdev_graphic_type1 != 2) && (gdev_graphic_type1 != 3)) return; // ***************** LUT submenu ****************************** /* lut_type: 'l'=log rainbow1 'r'=rainbow2 's'=saw 'g'=gray 'c'=curves * 'p'=pisco * RAIN1, RAIN2, SAW, GRAY, CUR, PISCO, REV */ menuLUT = new wxMenu; menuLUT->Append(ID_LUT_RAIN1, _T("Rainbow1"), wxT("Colour Look Up Table"), wxITEM_RADIO); menuLUT->Append(ID_LUT_RAIN2, _T("Rainbow2"), wxT("Colour Look Up Table"), wxITEM_RADIO); menuLUT->Append(ID_LUT_PISCO, _T("Pisco_like"), wxT("Colour Look Up Table"), wxITEM_RADIO); menuLUT->Append(ID_LUT_CUR, _T("For Curves"), wxT("Colour Look Up Table"), wxITEM_RADIO); menuLUT->Append(ID_LUT_SAW, _T("Gray Saw"), wxT("B&W Look Up Table"), wxITEM_RADIO); menuLUT->Append(ID_LUT_GRAY, _T("Gray Linear"), wxT("B&W Look Up Table"), wxITEM_RADIO); menuLUT->AppendSeparator(); menuLUT->Append(ID_LUT_REV, _T("Reversed LUT"), wxT("Inverse colors"), wxITEM_CHECK); menuSetup->AppendSubMenu(menuLUT, _T("LUT"), wxT("To select a Look Up Table")); // ***************** ITT submenu ****************************** /* * ITT_1: * "Lin" (Linear scale) * LIN, LOG */ menuITT1 = new wxMenu; menuITT1->Append( ID_ITT_LIN, _T("Linear"), _T("Linear scale"), wxITEM_RADIO); menuITT1->Append( ID_ITT_LOG, _T("Logarithmic"), _T("Log. scale"), wxITEM_RADIO); menuSetup->AppendSubMenu(menuITT1, _T("ITT type"), _T("Type of Intensity Transfer Table")); /* "Log" (Linear scale) * "Direct" (Thresholds entered by the user) * "Box" (Automatic: from a rectangular box) * "MinMax" (Automatic scale: Min Max) * "Median" (Automatic scale: Median) * "HC" (Automatic scale: High contrast) * BOX, DIRECT, DIRECT1, AUTO_MINMAX, AUTO_HC, AUTO_VHC, etc * */ menuITT2 = new wxMenu; menuITT2->Append( ID_THR_DIRECT, _T("With fixed thresholds"), _T("Direct input of thresholds"), wxITEM_RADIO); menuITT2->Append( ID_THR_DIRECT1, _T("With new fixed thresholds"), _T("Direct input of thresholds"), wxITEM_RADIO); menuITT2->Append( ID_THR_BOX, _T("Automatic: from box"), _T("Interactive selection from box"), wxITEM_RADIO); menuITT2->Append( ID_THR_AUTO_MINMAX, _T("Automatic: min/max"), _T("Automatic computation"), wxITEM_RADIO); menuITT2->Append( ID_THR_AUTO_MEDIAN, _T("Automatic: median"), _T("Automatic computation with the median"), wxITEM_RADIO); menuITT2->Append( ID_THR_AUTO_HC, _T("Automatic: high contrast"), _T("Automatic computation"), wxITEM_RADIO); menuITT2->Append( ID_THR_AUTO_VHC, _T("Automatic: very high contrast"), _T("Automatic computation"), wxITEM_RADIO); menuSetup->AppendSubMenu(menuITT2, _T("ITT thresholds"), _T("Thresholds of the Intensity Transfer Table")); // No longer used since I fix the maximum size of the image now... // menuSetup->Append( ID_FULL, _T("&Full screen on/off")); // ***************** Discrete Zoom **************************** // Discrete zoom for jlp_splot/images only menuZoom = new wxMenu; menuZoom->Append( ID_ZOOM_C8, _T("/8"), _T("Reduction: /8"), wxITEM_RADIO); menuZoom->Append( ID_ZOOM_C7, _T("/7"), _T("Reduction: /7"), wxITEM_RADIO); menuZoom->Append( ID_ZOOM_C6, _T("/6"), _T("Reduction: /6"), wxITEM_RADIO); menuZoom->Append( ID_ZOOM_C5, _T("/5"), _T("Reduction: /5"), wxITEM_RADIO); menuZoom->Append( ID_ZOOM_C4, _T("/4"), _T("Reduction: /4"), wxITEM_RADIO); menuZoom->Append( ID_ZOOM_C3, _T("/3"), _T("Reduction: /3"), wxITEM_RADIO); menuZoom->Append( ID_ZOOM_C2, _T("/2"), _T("Reduction: /2"), wxITEM_RADIO); menuZoom->Append( ID_ZOOM1, _T("1x"), _T("Magnification: 1x"), wxITEM_RADIO); menuZoom->Append( ID_ZOOM2, _T("2x"), _T("Magnification: 2x"), wxITEM_RADIO); menuZoom->Append( ID_ZOOM3, _T("3x"), _T("Magnification: 3x"), wxITEM_RADIO); menuZoom->Append( ID_ZOOM4, _T("4x"), _T("Magnification: 4x"), wxITEM_RADIO); menuZoom->Append( ID_ZOOM5, _T("5x"), _T("Magnification: 5x"), wxITEM_RADIO); menuZoom->Append( ID_ZOOM6, _T("6x"), _T("Magnification: 6x"), wxITEM_RADIO); menuZoom->Append( ID_ZOOM8, _T("8x"), _T("Magnification: 8x"), wxITEM_RADIO); menuZoom->Append( ID_ZOOM10, _T("10x"), _T("Magnification: 10x"), wxITEM_RADIO); menuZoom->Append( ID_ZOOM15, _T("15x"), _T("Magnification: 15x"), wxITEM_RADIO); menuZoom->Append( ID_ZOOM20, _T("20x"), _T("Magnification: 20x"), wxITEM_RADIO); menuZoom->Append( ID_ZOOM40, _T("40x"), _T("Magnification: 40x"), wxITEM_RADIO); menuSetup->AppendSubMenu(menuZoom, _T("Zoom"), _T("To change the magnification")); return; } /*********************************************************************** * Gsegraf menu ***********************************************************************/ void JLP_wxGDev_Popup::CreateGsegrafMenu() { /* GDevGraphicType: * 1 = jlp_splot_curves * 2 = jlp_splot_images * 3 = wx_scrolled/jlp_splot_images * 4 = gsegraf_2d_curves * 5 = gsegraf_2d_images * 6 = gsegraf_3d_curves * 7 = gsegraf_3d_images * 8 = gsegraf_polar_curve */ if(gdev_graphic_type1 < 4) return; menuGsegraf = new wxMenu; menuGsegraf->Append(ID_GSEG_AXIS_LIMITS, wxT("Change axis limits"), wxT("Display and change the axis limits")); menuGsegraf->Append(ID_GSEG_AXIS_ROTATE, wxT("Axis rotation (if 3d mode)"), wxT("Change the projection angles of the 3d plot")); PopupMenu1->Append(wxID_ANY, _T("Gsegraf"), menuGsegraf); return; } /*********************************************************************** * LUT, ITT, discrete zoom, and filter menu * For jlp_splot images ***********************************************************************/ void JLP_wxGDev_Popup::CreateImageMenuFilterForSplot() { /* GDevGraphicType: * 1 = jlp_splot_curves * 2 = jlp_splot_images * 3 = wx_scrolled/jlp_splot_images * 4 = gsegraf_2d_curves * 5 = gsegraf_2d_images * 6 = gsegraf_3d_curves * 7 = gsegraf_3d_images * 8 = gsegraf_polar_curve */ if((gdev_graphic_type1 != 2) && (gdev_graphic_type1 != 3)) return; // ***************** Filter menu ****************************** // 0=NONE // 1=soft unsharp (UNSH1) 2=medium unsharp (UNSH2) 3=hard unsharp (UNSH3) menuFilter = new wxMenu; menuFilter->Append( ID_FILTER_0, _T("None"), wxT("No filter"), wxITEM_RADIO); menuFilter->Append( ID_FILTER_1, _T("Soft unsharp masking"), wxT("With big square box"), wxITEM_RADIO); menuFilter->Append( ID_FILTER_2, _T("Medium unsharp masking"), wxT("With medium sized square box"), wxITEM_RADIO); menuFilter->Append( ID_FILTER_3, _T("Hard unsharp masking"), wxT("With small square box"), wxITEM_RADIO); /*** * For popup menu (without unresolved modsq): * 4 = VHC1: high contrast version 2008 without unresolved modsq * 5 = VHC2: high contrast version 2015 without unresolved modsq * 6 = VHC3: median profile version 2008 without unresolved modsq * 7 = VHC4: median profile version 2015 without unresolved modsq * 8 = GRAD1 medium gradient * 9 = GRAD2 hard gradient * 10 = CPROF circ. profile * 11 = CIRC1 circ. gradient(rot 10 deg) * 12 = CIRC2 circ. gradient(rot 20 deg) * 13 = CIRC3 circ. gradient(rot 30 deg) ****/ menuFilter->Append( ID_FILTER_4, _T("High contrast for autoc. (VHC1)"), wxT("High contrast without unres. modsq: version 2008"), wxITEM_RADIO); menuFilter->Append( ID_FILTER_5, _T("High contrast for autoc. (VHC2)"), wxT("High contrast without unres. modsq: version 2015"), wxITEM_RADIO); menuFilter->Append( ID_FILTER_6, _T("High contrast for autoc. (VHC3)"), wxT("Median profile without unres. modsq: version 2008"), wxITEM_RADIO); menuFilter->Append( ID_FILTER_7, _T("High contrast for autoc. (VHC4)"), wxT("Median profile without unres. modsq: version 2015"), wxITEM_RADIO); menuFilter->Append( ID_FILTER_8, _T("Laplacian gradient, medium (GRAD1)"), wxT("Medium Laplacian gradient version 2020"), wxITEM_RADIO); menuFilter->Append( ID_FILTER_9, _T("Laplacian gradient, hard (GRAD2)"), wxT("Hard Laplacian gradient version 2020"), wxITEM_RADIO); menuFilter->Append( ID_FILTER_10, _T("Circular profile (CPROF)"), wxT("Circular profile removal, version 2020"), wxITEM_RADIO); menuFilter->Append( ID_FILTER_11, _T("Circular gradient, 10deg (CIRC1)"), wxT("Circular gradient, 10deg, version 2020"), wxITEM_RADIO); menuFilter->Append( ID_FILTER_12, _T("Circular gradient, 20deg (CIRC2)"), wxT("Circular gradient, 20deg, version 2020"), wxITEM_RADIO); menuFilter->Append( ID_FILTER_13, _T("Circular gradient, 30deg (CIRC3)"), wxT("Circular gradient, 30deg, version 2020"), wxITEM_RADIO); PopupMenu1->Append(wxID_ANY, _T("Filter"), menuFilter); return; } /*********************************************************************** * Shape menu (for jlp_splot images) * ***********************************************************************/ void JLP_wxGDev_Popup::CreateShapeMenu() { /* GDevGraphicType: * 1 = jlp_splot_curves * 2 = jlp_splot_images * 3 = wx_scrolled/jlp_splot_images * 4 = gsegraf_2d_curves * 5 = gsegraf_2d_images * 6 = gsegraf_3d_curves * 7 = gsegraf_3d_images * 8 = gsegraf_polar_curve */ if((gdev_graphic_type1 != 2) && (gdev_graphic_type1 != 3)) return; menuShape = new wxMenu; menuShape->Append(ID_ADD_LINE, _T("Add a line"), wxT("Line selected with the mouse")); menuShape->Append(ID_ADD_RECTANGLE, _T("Add a rectangle"), wxT("Rectangle selected with the mouse")); menuShape->Append(ID_ADD_CIRCLE, _T("Add a circle"), wxT("Circle selected with the mouse")); menuShape->Append(ID_ADD_ELLIPSE, _T("Add an ellipse"), wxT("Ellipse selected with the mouse")); menuShape->Append(ID_ADD_RING, _T("Add a ring"), wxT("Ring selected with the mouse")); menuShape->Append(ID_CANCEL_SHAPE, _T("Cancel the last shape"), wxT("Remove the last entered shape")); menuShape->Append(ID_REM_SHAPE, _T("Remove a shape"), wxT("Remove a shape by clicking on it")); menuShape->Append(ID_ROTATE_SHAPE, _T("Rotate a shape"), wxT("Rotate a shape with the mouse")); menuShape->Append(ID_MAGNIFY_SHAPE, _T("Reduce/enlarge a shape"), wxT("Change the size of a shape with the mouse")); menuShape->Append(ID_MOVE_SHAPE, _T("Move a shape"), wxT("Move a shape with the mouse")); menuShape->Append(ID_REM_ALL_SHAPES, _T("Remove all shapes"), wxT("Remove all the shapes")); PopupMenu1->Append(wxID_ANY, _T("Shapes"), menuShape); return; } /**************************************************************************** * Background color (for curves only) *****************************************************************************/ void JLP_wxGDev_Popup::CreateColourBackgroundMenu() { /* GDevGraphicType: * 1 = jlp_splot_curves * 2 = jlp_splot_images * 3 = wx_scrolled/jlp_splot_images * 4 = gsegraf_2d_curves * 5 = gsegraf_2d_images * 6 = gsegraf_3d_curves * 7 = gsegraf_3d_images * 8 = gsegraf_polar_curve */ if((gdev_graphic_type1 == 2) || (gdev_graphic_type1 == 3) || (gdev_graphic_type1 == 5) || (gdev_graphic_type1 == 7)) return; // ***************** Colour background submenu ****************************** menuBackgd = new wxMenu; menuBackgd->Append( ID_BLACK_BACK_COLOUR, _T("Black Background"), _T("Background colour"), wxITEM_RADIO); menuBackgd->Append( ID_YELLOW_BACK_COLOUR, _T("Yellow Background"), _T("Background colour"), wxITEM_RADIO); menuBackgd->Append( ID_GREY_BACK_COLOUR, _T("Grey Background"), _T("Background colour"), wxITEM_RADIO); menuBackgd->Append( ID_WHITE_BACK_COLOUR, _T("White Background"), _T("Background colour"), wxITEM_RADIO); menuSetup->AppendSubMenu(menuBackgd, _T("Background"), _T("Select Background properties")); return; } /************************************************************* * Setup menu for curves * Box type and box limits, for curves/or gsegraf only * *************************************************************/ void JLP_wxGDev_Popup::CreateSetupMenuForCurves() { /* GDevGraphicType: * 1 = jlp_splot_curves * 2 = jlp_splot_images * 3 = wx_scrolled/jlp_splot_images * 4 = gsegraf_2d_curves * 5 = gsegraf_2d_images * 6 = gsegraf_3d_curves * 7 = gsegraf_3d_images * 8 = gsegraf_polar_curve */ // Not available gsegraf 2D image/curves for now (to be done later...) if((gdev_graphic_type1 == 2) || (gdev_graphic_type1 == 3) || (gdev_graphic_type1 > 3)) return; // ***************** Box type submenu ****************************** menuBoxType = new wxMenu; menuBoxType->Append(ID_BOX_TYPE0, _T("BoxType: big steps"), _T("Mongo type"), wxITEM_RADIO); menuBoxType->Append(ID_BOX_TYPE1, _T("BoxType: small steps"), _T("SciSoft type"), wxITEM_RADIO); menuBoxType->Append(ID_BOX_TYPE2, _T("BoxType: round-off limits"), _T("Gsegrafix type"), wxITEM_RADIO); menuBoxType->Append(ID_BOX_TICKS_IN, _T("Axis ticks in"), _T("With axis tiks in"), wxITEM_CHECK); menuBoxType->Append(ID_BOX_XGRID, _T("X grid"), _T("With a grid on the X axis"), wxITEM_CHECK); menuBoxType->Append(ID_BOX_YGRID, _T("Y grid"), _T("With a grid on the Y axis"), wxITEM_CHECK); // For jlp_splot curves only: if(gdev_graphic_type1 == 1) { PopupMenu1->Append(Menu_Popup_Curve, _T("BoxType"), menuBoxType); } // ***************** Box limits menu ********************************** menuBoxLimits = new wxMenu; menuBoxLimits->AppendCheckItem(ID_BOX_LIMITS_WITH_BOX, _T("BoxLimits: with box"), _T("Interactive selection of a rectangular box")); menuBoxLimits->Append(ID_BOX_LIMITS_AUTO, _T("BoxLimits: auto"), _T("Best setup for full plot")); menuBoxLimits->Append(ID_BOX_LIMITS_MANUAL, _T("BoxLimits: manual"), _T("Input of your choice")); if((gdev_graphic_type1 == 1) || (gdev_graphic_type1 == 4) || (gdev_graphic_type1 == 5)) { PopupMenu1->Append(Menu_Popup_Curve, _T("BoxLimits"), menuBoxLimits); } return; }
C++
CL
33a15197e1921cf8da6e407b703432c1f0e85e173ab5eeea47e392282a7285d8
// Nonius - C++ benchmarking tool // // Written in 2014 by Martinho Fernandes <[email protected]> // // To the extent possible under law, the author(s) have dedicated all copyright and related // and neighboring rights to this software to the public domain worldwide. This software is // distributed without any warranty. // // You should have received a copy of the CC0 Public Domain Dedication along with this software. // If not, see <http://creativecommons.org/publicdomain/zero/1.0/> // Tests for parameter related stuff #include <nonius/param.h++> #include <catch.hpp> namespace nonius { namespace { struct x_tag { using type = int; static const char* name() { return "x"; } }; struct y_tag { using type = std::string; static const char* name() { return "y"; } }; } // annon namespace TEST_CASE("param declaration") { SECTION("local") { auto reg = param_registry{}; auto decl = param_declaration<x_tag>{42, reg}; CHECK(decl.registry.defaults().size() == 1); CHECK(global_param_registry().defaults().size() == 0); CHECK(reg.defaults().at("x").as<int>() == 42); } SECTION("global") { auto&& reg = global_param_registry(); { auto decl = scoped_param_declaration<x_tag>{42}; CHECK(reg.defaults().size() == 1); CHECK(reg.defaults().at("x").as<int>() == 42); } // cleanup, for testing CHECK(reg.defaults().size() == 0); } } struct custom_t { int x; std::string y; friend bool operator== (custom_t const& x, custom_t const& y) { return x.x == y.x && x.y == y.y; } friend std::ostream& operator<< (std::ostream& os, custom_t const& x) { os << x.x << " " << x.y; return os; } friend std::istream& operator>> (std::istream& is, custom_t& x) { is.setf(std::ios::skipws); is >> x.x >> x.y; return is; } friend custom_t operator*(custom_t const& lhs, custom_t const& rhs) { return { lhs.x * rhs.x, lhs.y + "*" + rhs.y}; } }; TEST_CASE("parameter types") { SECTION("int") { CHECK(param{42}.as<int>() == 42); CHECK((param{2} + param{3}).as<int>() == 5); CHECK((param{2} * param{3}).as<int>() == 6); } SECTION("float") { CHECK(param{42.0f}.as<float>() == 42.0f); CHECK((param{2.0f} + param{3.5f}).as<float>() == Approx(5.5f)); CHECK((param{2.0f} * param{3.5f}).as<float>() == Approx(7.0f)); } SECTION("string") { CHECK(param{std::string{"foo"}}.as<std::string>() == "foo"); CHECK((param{std::string{"foo"}} + param{std::string{"bar"}}).as<std::string>() == "foobar"); CHECK_THROWS(param{std::string{"foo"}} * param{std::string{"bar"}}); } SECTION("custom") { CHECK((param{custom_t{42, "pepe"}}.as<custom_t>() == custom_t{42, "pepe"})); CHECK_THROWS(param{custom_t{}} + param{custom_t{}}); CHECK(((param{custom_t{42, "pepe"}} * param{custom_t{12, "manolo"}}).as<custom_t>() == custom_t{504, "pepe*manolo"})); } SECTION("types must match") { CHECK_THROWS(param{42}.as<float>()); CHECK_THROWS(param{42.0f}.as<int>()); } } TEST_CASE("parameter maps") { SECTION("get") { auto decl1 = scoped_param_declaration<y_tag>{""}; auto params = parameters{{"y", param{std::string{"foo"}}}}; CHECK(params.get<y_tag>() == "foo"); CHECK_THROWS_AS(params.get<x_tag>(), std::out_of_range); } SECTION("merge") { using str = std::string; auto params = parameters{{"x", str{"foo"}}, {"y", str{"bar"}}}.merged({ {"y", str{"baz"}}, {"z", str{"oof"}}}); CHECK(params.size() == 3); CHECK(params.at("x").as<str>() == "foo"); CHECK(params.at("y").as<str>() == "baz"); CHECK(params.at("z").as<str>() == "oof"); } } } // namespace nonius
C++
CL
e8da9654629821ada549983860bf1dfebdc7e7a1052063cace2f06f32714f666
// (c) MJavad // Fix for rtl languages (for now supports Persian and Arabic with LTR base) #include <base/system.h> #include "rtl_support.h" void CRTLFix::FixString(char *pDst, const char *pSrc, int DstSize, bool FullRTL, int *pCursor, int *pFixedLen) { int Cursor = -1; int Size = 0; int Char; char Buf[4]; CChar Str[MAX_RTL_FIX_SRT_LEN]; // Fill the buffer with pSrc and set the Cursor const char *pTmpSrc = pSrc; while((Char = str_utf8_decode(&pTmpSrc)) && Size < MAX_RTL_FIX_SRT_LEN-1) // max size is MAX_RTL_FIX_SRT_LEN-1 if(Char != -1) { if(Cursor == -1 && pCursor && *pCursor < pTmpSrc-pSrc) Cursor = Size; Str[Size].Type = GetLinkType(Char); Str[Size++].Char = Char; } if(Cursor == -1 && pCursor && *pCursor < pTmpSrc-pSrc) Cursor = Size; // Unusual things if(Size == 0 || DstSize < 2) { if(DstSize > 0) *pDst = 0; return; } if(Size == 1) { int s = str_utf8_encode(Buf, Str[0].Char); if(FullRTL) if(Cursor == 0) *pCursor = s; else *pCursor = 0; else if(Cursor == 0) *pCursor = 0; else *pCursor = s; if(s > DstSize) s = DstSize-1; mem_copy(pDst, Buf, s); pDst[s] = 0; return; } // Process the buffer // Step 1: Skip NO_BREAK chars and set PrevType and NextType Str[0].PrevType = LTR; Str[Size].Type = LTR; int *TypeToFill = 0; int *TypeToFill2 = 0; int *CharToFill = 0; int PrevType; for(int i = 0; i < Size; i++) { int t = Str[i].Type; int c = Str[i].Char; if(c == ARABIC_TATWEEL) { Str[i+1].PrevType = DUAL; Str[i].Type = NONE; } if(t == NO_BREAK) continue; if(CharToFill && Cursor != i) { for(int j = 0; j < ARABIC_ALEF_CHARS_N; j++) if(c == ARABIC_ALEF_CHARS[j]) { *CharToFill = ARABIC_LAMALEF_CHARS[j]; *TypeToFill2 = BEFORE; PrevType = BEFORE; Str[i].Char = 0; break; } CharToFill = 0; } if(!Str[i].Char) continue; if(TypeToFill) { *TypeToFill = t; TypeToFill = 0; Str[i].PrevType = PrevType; } int nt = Str[i+1].Type; if(nt == NO_BREAK || c == ARABIC_LAM) { if(c == ARABIC_LAM) { CharToFill = &Str[i].Char; TypeToFill2 = &Str[i].Type; } TypeToFill = &Str[i].NextType; PrevType = t; } else { Str[i].NextType = nt; Str[i+1].PrevType = t; // i+1 exists because max size is MAX_RTL_FIX_SRT_LEN-1 } } if(TypeToFill) *TypeToFill = 0; // Step 2: Link chars (the HARD part!) and set the Cursor (ALL PARTS have copyright and too much time spent on them) int c; int t; int pt; int nt; int s; int RIndex = 0; int NIndex = 0; int LIndex = 0; int RCursor = -1; int NCursor = -1; int LCursor = -1; const int MaxSize = MAX_RTL_FIX_SRT_LEN*8; // Make sure we never reach the end (4 = max utf8 int char size, 2 = for 2 sides buffers) char RBuf[MaxSize]; // RTL buffer char NBuf[MaxSize]; // NO_DIR buffer (2 sides) char LBuf[MaxSize]; // LTR buffer char *pDstMax = pDst+DstSize-1; char *pOldDst = pDst; for(int i = 0; i < Size; i++) { t = Str[i].Type; c = Str[i].Char; if(!c) continue; if(FullRTL) // i need a rest :) { switch(t) { case LTR: s = str_utf8_encode(Buf, c); if(s > pDstMax-pDst-RIndex-NIndex-LIndex) break; if(NIndex) { if(NCursor != -1) { LCursor = LIndex+NCursor; NCursor = 0; } mem_copy(LBuf+LIndex, NBuf, NIndex); LIndex += NIndex; NIndex = 0; } if(Cursor == i) LCursor = LIndex; mem_copy(LBuf+LIndex, Buf, s); LIndex += s; break; case NUMBER: s = str_utf8_encode(Buf, c); if(s > pDstMax-pDst-RIndex-NIndex-LIndex) break; if(NIndex) { if(NCursor != -1) { LCursor = LIndex+NCursor; NCursor = 0; } mem_copy(LBuf+LIndex, NBuf, NIndex); LIndex += NIndex; NIndex = 0; } if(Cursor == i) LCursor = LIndex; mem_copy(LBuf+LIndex, Buf, s); LIndex += s; break; case NO_DIR: s = str_utf8_encode(Buf, c); if(s > pDstMax-pDst-RIndex-NIndex-LIndex) break; if(LIndex) { if(LCursor != -1) { RCursor = RIndex+LIndex-LCursor; LCursor = 0; } mem_copy(RBuf+MaxSize-RIndex-LIndex, LBuf, LIndex); RIndex += LIndex; LIndex = 0; } if(Cursor == i) RCursor = RIndex; mem_copy(RBuf+MaxSize-RIndex-s, Buf, s); RIndex += s; break; case NONE: c = GetLinked(c); s = str_utf8_encode(Buf, c); if(s > pDstMax-pDst-RIndex-NIndex-LIndex) break; if(LIndex) { if(LCursor != -1) { RCursor = RIndex+LIndex-LCursor; LCursor = 0; } mem_copy(RBuf+MaxSize-RIndex-LIndex, LBuf, LIndex); RIndex += LIndex; LIndex = 0; } if(NIndex) { if(NCursor != -1) { RCursor = RIndex+NCursor; NCursor = 0; } mem_copy(RBuf+MaxSize-RIndex-NIndex, NBuf+MaxSize-NIndex, NIndex); RIndex += NIndex; NIndex = 0; } if(Cursor == i) RCursor = RIndex; mem_copy(RBuf+MaxSize-RIndex-s, Buf, s); RIndex += s; break; case BEFORE: c = GetLinked(c); if(Str[i].PrevType == DUAL) c += FINAL; s = str_utf8_encode(Buf, c); if(s > pDstMax-pDst-RIndex-NIndex-LIndex) break; if(LIndex) { if(LCursor != -1) { RCursor = RIndex+LIndex-LCursor; LCursor = 0; } mem_copy(RBuf+MaxSize-RIndex-LIndex, LBuf, LIndex); RIndex += LIndex; LIndex = 0; } if(NIndex) { if(NCursor != -1) { RCursor = RIndex+NCursor; NCursor = 0; } mem_copy(RBuf+MaxSize-RIndex-NIndex, NBuf+MaxSize-NIndex, NIndex); RIndex += NIndex; NIndex = 0; } if(Cursor == i) RCursor = RIndex; mem_copy(RBuf+MaxSize-RIndex-s, Buf, s); RIndex += s; break; case DUAL: c = GetLinked(c); pt = Str[i].PrevType; nt = Str[i].NextType; if(pt == DUAL) if(nt == BEFORE || nt == DUAL) c += MEDIAL; else c += FINAL; else if(nt == BEFORE || nt == DUAL) c += INITIAL; s = str_utf8_encode(Buf, c); if(s > pDstMax-pDst-RIndex-NIndex-LIndex) break; if(LIndex) { if(LCursor != -1) { RCursor = RIndex+LIndex-LCursor; LCursor = 0; } mem_copy(RBuf+MaxSize-RIndex-LIndex, LBuf, LIndex); RIndex += LIndex; LIndex = 0; } if(NIndex) { if(NCursor != -1) { RCursor = RIndex+NCursor; NCursor = 0; } mem_copy(RBuf+MaxSize-RIndex-NIndex, NBuf+MaxSize-NIndex, NIndex); RIndex += NIndex; NIndex = 0; } if(Cursor == i) RCursor = RIndex; mem_copy(RBuf+MaxSize-RIndex-s, Buf, s); RIndex += s; break; case NO_BREAK: s = str_utf8_encode(Buf, c); if(s > pDstMax-pDst-RIndex-NIndex-LIndex) break; if(LIndex) { if(LCursor != -1) { RCursor = RIndex+LIndex-LCursor; LCursor = 0; } mem_copy(RBuf+MaxSize-RIndex-LIndex, LBuf, LIndex); RIndex += LIndex; LIndex = 0; } if(NIndex) { if(NCursor != -1) { RCursor = RIndex+NCursor; NCursor = 0; } mem_copy(RBuf+MaxSize-RIndex-NIndex, NBuf+MaxSize-NIndex, NIndex); RIndex += NIndex; NIndex = 0; } if(Cursor == i) RCursor = RIndex; mem_copy(RBuf+MaxSize-RIndex-s, Buf, s); RIndex += s; break; } } else { switch(t) { case LTR: if(RIndex) { if(RCursor != -1) { *pCursor = pDst-pOldDst+RIndex-RCursor; RCursor = -1; Cursor = -1; } mem_copy(pDst, RBuf+MaxSize-RIndex, RIndex); pDst += RIndex; RIndex = 0; } if(NIndex) { if(NCursor != -1) { *pCursor = pDst-pOldDst+NCursor; NCursor = -1; Cursor = -1; } mem_copy(pDst, NBuf, NIndex); pDst += NIndex; NIndex = 0; } if(LIndex) { if(LCursor != -1) { *pCursor = pDst-pOldDst+NCursor; LCursor = -1; Cursor = -1; } mem_copy(pDst, LBuf, LIndex); pDst += LIndex; LIndex = 0; } s = str_utf8_encode(Buf, c); if(s > pDstMax-pDst) break; if(Cursor == i) { *pCursor = pDst-pOldDst; Cursor = -1; } mem_copy(pDst, Buf, s); pDst += s; break; case NUMBER: s = str_utf8_encode(Buf, c); if(s > pDstMax-pDst-RIndex-NIndex-LIndex) break; if(RIndex) { if(Cursor == i) LCursor = LIndex; mem_copy(LBuf+LIndex, Buf, s); LIndex += s; } else { if(Cursor == i) { *pCursor = pDst-pOldDst; Cursor = -1; } mem_copy(pDst, Buf, s); pDst += s; } break; case NO_DIR: s = str_utf8_encode(Buf, c); if(s > pDstMax-pDst-RIndex-NIndex-LIndex) break; if(RIndex) { if(LIndex) { if(LCursor != -1) { NCursor = NIndex+LCursor; LCursor = 0; } mem_copy(NBuf+NIndex, LBuf, LIndex); mem_copy(NBuf+MaxSize-NIndex-LIndex, LBuf, LIndex); NIndex += LIndex; LIndex = 0; } if(Cursor == i) NCursor = NIndex; mem_copy(NBuf+NIndex, Buf, s); mem_copy(NBuf+MaxSize-NIndex-s, Buf, s); NIndex += s; } else { if(Cursor == i) { *pCursor = pDst-pOldDst; Cursor = -1; } mem_copy(pDst, Buf, s); pDst += s; } break; case NONE: c = GetLinked(c); s = str_utf8_encode(Buf, c); if(s > pDstMax-pDst-RIndex-NIndex-LIndex) break; if(NIndex) { if(NCursor != -1) { RCursor = RIndex+NCursor; NCursor = 0; } mem_copy(RBuf+MaxSize-RIndex-NIndex, NBuf+MaxSize-NIndex, NIndex); RIndex += NIndex; NIndex = 0; } if(LIndex) { if(LCursor != -1) { RCursor = RIndex+LIndex-LCursor; LCursor = 0; } mem_copy(RBuf+MaxSize-RIndex-LIndex, LBuf, LIndex); RIndex += LIndex; LIndex = 0; } if(Cursor == i) RCursor = RIndex; mem_copy(RBuf+MaxSize-RIndex-s, Buf, s); RIndex += s; break; case BEFORE: c = GetLinked(c); if(Str[i].PrevType == DUAL) c += FINAL; s = str_utf8_encode(Buf, c); if(s > pDstMax-pDst-RIndex-NIndex-LIndex) break; if(NIndex) { if(NCursor != -1) { RCursor = RIndex+NCursor; NCursor = 0; } mem_copy(RBuf+MaxSize-RIndex-NIndex, NBuf+MaxSize-NIndex, NIndex); RIndex += NIndex; NIndex = 0; } if(LIndex) { if(LCursor != -1) { RCursor = RIndex+LIndex-LCursor; LCursor = 0; } mem_copy(RBuf+MaxSize-RIndex-LIndex, LBuf, LIndex); RIndex += LIndex; LIndex = 0; } if(Cursor == i) RCursor = RIndex; mem_copy(RBuf+MaxSize-RIndex-s, Buf, s); RIndex += s; break; case DUAL: c = GetLinked(c); pt = Str[i].PrevType; nt = Str[i].NextType; if(pt == DUAL) if(nt == BEFORE || nt == DUAL) c += MEDIAL; else c += FINAL; else if(nt == BEFORE || nt == DUAL) c += INITIAL; s = str_utf8_encode(Buf, c); if(s > pDstMax-pDst-RIndex-NIndex-LIndex) break; if(NIndex) { if(NCursor != -1) { RCursor = RIndex+NCursor; NCursor = 0; } mem_copy(RBuf+MaxSize-RIndex-NIndex, NBuf+MaxSize-NIndex, NIndex); RIndex += NIndex; NIndex = 0; } if(LIndex) { if(LCursor != -1) { RCursor = RIndex+LIndex-LCursor; LCursor = 0; } mem_copy(RBuf+MaxSize-RIndex-LIndex, LBuf, LIndex); RIndex += LIndex; LIndex = 0; } if(Cursor == i) RCursor = RIndex; mem_copy(RBuf+MaxSize-RIndex-s, Buf, s); RIndex += s; break; case NO_BREAK: s = str_utf8_encode(Buf, c); if(s > pDstMax-pDst-RIndex-NIndex-LIndex) break; if(NIndex) { if(NCursor != -1) { RCursor = RIndex+NCursor; NCursor = 0; } mem_copy(RBuf+MaxSize-RIndex-NIndex, NBuf+MaxSize-NIndex, NIndex); RIndex += NIndex; NIndex = 0; } if(LIndex) { if(LCursor != -1) { RCursor = RIndex+LIndex-LCursor; LCursor = 0; } mem_copy(RBuf+MaxSize-RIndex-LIndex, LBuf, LIndex); RIndex += LIndex; LIndex = 0; } if(Cursor == i) RCursor = RIndex; mem_copy(RBuf+MaxSize-RIndex-s, Buf, s); RIndex += s; break; } } if(s > pDstMax-pDst-RIndex-NIndex-LIndex) break; } if(FullRTL) { if(NIndex) { if(NCursor != -1) { *pCursor = pDst-pOldDst+NIndex-NCursor; Cursor = -1; } mem_copy(pDst, NBuf+MaxSize-NIndex, NIndex); pDst += NIndex; } if(LIndex) { if(LCursor != -1) { *pCursor = pDst-pOldDst+LCursor; Cursor = -1; } mem_copy(pDst, LBuf, LIndex); pDst += LIndex; } if(RIndex) { if(RCursor != -1) { *pCursor = pDst-pOldDst+RIndex-RCursor; Cursor = -1; } mem_copy(pDst, RBuf+MaxSize-RIndex, RIndex); pDst += RIndex; } if(Cursor != -1) *pCursor = 0; } else { if(RIndex) { if(RCursor != -1) { *pCursor = pDst-pOldDst+RIndex-RCursor; Cursor = -1; } mem_copy(pDst, RBuf+MaxSize-RIndex, RIndex); pDst += RIndex; } if(NIndex) { if(NCursor != -1) { *pCursor = pDst-pOldDst+NCursor; Cursor = -1; } mem_copy(pDst, NBuf, NIndex); pDst += NIndex; } if(LIndex) { if(LCursor != -1) { *pCursor = pDst-pOldDst+LCursor; Cursor = -1; } mem_copy(pDst, LBuf, LIndex); pDst += LIndex; } if(Cursor != -1) *pCursor = pDst-pOldDst; } *pDst = 0; // null-terminate the string *pFixedLen = pDst-pOldDst+1; } int CRTLFix::GetLinkType(int Char) { for(int i = 0; i < RTL_RANGE_N*2; i+=2) if(Char >= RTL_RANGE[i] && Char <= RTL_RANGE[i+1]) { // Sorted by usage (better performence) if(Char >= ARABIC_CHARS_RANGE[0] && Char <= ARABIC_CHARS_RANGE[1]) return ARABIC_CHARS_TYPE[Char-ARABIC_CHARS_RANGE[0]]; for(int i = 0; i < PERSIAN_CHARS_N; i++) if(Char == PERSIAN_CHARS[i]) return PERSIAN_CHARS_TYPE[i]; for(int i = 0; i < RTL_CHARS_N; i++) if(Char == RTL_CHARS[i]) return NONE; for(int i = 0; i < RTL_CHARS_RANGE_N*2; i+=2) if(Char >= RTL_CHARS_RANGE[i] && Char <= RTL_CHARS_RANGE[i+1]) return NONE; } for(int i = 0; i < NUMBERS_RANGE_N*2; i+=2) if(Char >= NUMBERS_RANGE[i] && Char <= NUMBERS_RANGE[i+1]) return NUMBER; for(int i = 0; i < NO_DIR_CHARS_RANGE_N*2; i+=2) if(Char >= NO_DIR_CHARS_RANGE[i] && Char <= NO_DIR_CHARS_RANGE[i+1]) return NO_DIR; for(int i = 0; i < NO_DIR_CHARS_N; i++) if(Char == NO_DIR_CHARS[i]) return NO_DIR; for(int i = 0; i < NO_BREAK_CHARS_RANGE_N*2; i+=2) if(Char >= NO_BREAK_CHARS_RANGE[i] && Char <= NO_BREAK_CHARS_RANGE[i+1]) return NO_BREAK; for(int i = 0; i < NO_BREAK_CHARS_N; i++) if(Char == NO_BREAK_CHARS[i]) return NO_BREAK; return LTR; } int CRTLFix::GetLinked(int Char) { if(Char >= ARABIC_CHARS_RANGE[0] && Char <= ARABIC_CHARS_RANGE[1]) return ARABIC_CHARS_LINK[Char-ARABIC_CHARS_RANGE[0]]; for(int i = 0; i < PERSIAN_CHARS_N; i++) if(Char == PERSIAN_CHARS[i]) return PERSIAN_CHARS_LINK[i]; // Retrun others as the same (also LAMALEF) return Char; }
C++
CL
3665eb5fc6e8d13088dbe9d4ed43e550ef90dae1c91164ab4e44f949b37fc64a
// Copyright(c) 2017 POLYGONTEK // // 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 "Precompiled.h" class AdMob { public: class BannerAd; class InterstitialAd; class RewardBasedVideoAd; static void RegisterLuaModule(LuaCpp::State *state); static void Init(const char *appID, const char *testDevices = ""); static void ProcessQueue(); static BannerAd bannerAd; static InterstitialAd interstitialAd; static RewardBasedVideoAd rewardBasedVideoAd; static BE1::StrArray testDeviceList; }; class AdMob::BannerAd { public: void Init(); void Request(const char *unitID, int adWidth, int adHeight); void Show(bool showOnBottomOfScreen, float offsetX, float offsetY); void Hide(); }; class AdMob::InterstitialAd { public: void Init(); void Request(const char *unitID); bool IsReady() const; void Present(); }; class AdMob::RewardBasedVideoAd { public: void Init(); void Request(const char *unitID); bool IsReady() const; void Present(); };
C++
CL
1035ca829e9fc3bb6f6f5108dd3ee9727b6920c0bd0b879198124c3b84f555e2
#ifndef __GPIO_H__ #define __GPIO_H__ #include <chrono> #include <thread> #include <string> #include <fstream> class GPIO { public: enum Direction { Input = 0, Output = 1 }; enum Value { Low = 0, High = 1 }; GPIO(std::string const& _key, Direction _d); GPIO(int _pin, Direction _d); ~GPIO(); void set_value(Value _v); Value get_value() const; void set_direction(Direction _d); Direction get_direction() const { return direction; } int get_pin() const { return pin; } std::string get_key() const { return key; } private: std::string key; int pin; Direction direction; static constexpr const char* gpio_path = "/sys/class/gpio/"; typedef struct pins_t { const char *key; int pin; } pins_t; static const pins_t pins_table[]; static const unsigned int pin_table_len; void write_direction() const; void setup() const; }; #endif
C++
CL
3e94fdc5cf7179daa83f091a7a8bfa581058e9ce73974fefbacc8d74b9e6e084
#include <vbl/io/vbl_io_smart_ptr.h> #include <vsol/vsol_digital_curve_2d_sptr.h> #include <vsol/vsol_digital_curve_2d.h> #include "vsl/vsl_vector_io.hxx" VSL_VECTOR_IO_INSTANTIATE(vsol_digital_curve_2d_sptr);
C++
CL
e600b460dbf3fdf3d8d71f9bf743e8cb5919488dc92413bf2aa87d1c75b42e1a
//============================================================================== // // @@ // // Copyright 2017 Qualcomm Technologies, Inc. All rights reserved. // Confidential & Proprietary - Qualcomm Technologies, Inc. ("QTI") // // The party receiving this software directly from QTI (the "Recipient") // may use this software as reasonably necessary solely for the purposes // set forth in the agreement between the Recipient and QTI (the // "Agreement"). The software may be used in source code form solely by // the Recipient's employees (if any) authorized by the Agreement. Unless // expressly authorized in the Agreement, the Recipient may not sublicense, // assign, transfer or otherwise provide the source code to any third // party. Qualcomm Technologies, Inc. retains all ownership rights in and // to the software // // This notice supersedes any other QTI notices contained within the software // except copyright notices indicating different years of publication for // different portions of the software. This notice does not supersede the // application of any third party copyright notice to that third party's // code. // // @@ // //============================================================================== #include <iostream> #include "CheckRuntime.hpp" #include "android_log.hpp" #include "SNPE/SNPE.hpp" #include "SNPE/SNPEFactory.hpp" #include "DlSystem/DlVersion.hpp" #include "DlSystem/DlEnums.hpp" #include "DlSystem/String.hpp" static const char* TAG = "snpe_jni"; // Command line settings zdl::DlSystem::Runtime_t checkRuntime() { static zdl::DlSystem::Version_t Version = zdl::SNPE::SNPEFactory::getLibraryVersion(); static zdl::DlSystem::Runtime_t Runtime; //std::cout << "SNPE Version: " << Version.asString().c_str() << std::endl; //Print Version number LOGI("%s-%s:line %d >> SNPE Version:%s", __FILE__, __FUNCTION__, __LINE__, Version.asString().c_str()); if (zdl::SNPE::SNPEFactory::isRuntimeAvailable(zdl::DlSystem::Runtime_t::GPU)) { Runtime = zdl::DlSystem::Runtime_t::GPU; LOGI("SNPE backend support GPU"); } if(zdl::SNPE::SNPEFactory::isRuntimeAvailable(zdl::DlSystem::Runtime_t::DSP)) { Runtime = zdl::DlSystem::Runtime_t::DSP; // todo: fix crash while create userbuffer LOGI("SNPE backend support DSP"); } else { Runtime = zdl::DlSystem::Runtime_t::CPU; } Runtime = zdl::DlSystem::Runtime_t::CPU; return Runtime; }
C++
CL
cfe36c8dbaca2689ec103af7a6eb5b1d7c2850153460bc11c829eedfe2842ca0
#include "SparseBayesRRG.hpp" #include "common.h" #include "eigenbayesrkernel.h" #include "raggedbayesrkernel.h" #include "sparsemarker.h" SparseBayesRRG::SparseBayesRRG(const Data *data, const Options *opt) : BayesRBase(data, opt) { } SparseBayesRRG::~SparseBayesRRG() { } std::unique_ptr<Kernel> SparseBayesRRG::kernelForMarker(const ConstMarkerPtr &marker) const { switch (m_opt->preprocessDataType) { case PreprocessDataType::SparseEigen: { const auto eigenSparseMarker = dynamic_pointer_cast<const EigenSparseMarker>(marker); assert(eigenSparseMarker); return std::make_unique<EigenBayesRKernel>(eigenSparseMarker); } case PreprocessDataType::SparseRagged: { const auto raggedSparseMarker = dynamic_pointer_cast<const RaggedSparseMarker>(marker); assert(raggedSparseMarker); return std::make_unique<RaggedBayesRKernel>(raggedSparseMarker); } default: std::cerr << "SparseBayesRRG::kernelForMarker - unsupported type: " << m_opt->preprocessDataType << std::endl; } return {}; } MarkerBuilder *SparseBayesRRG::markerBuilder() const { switch (m_opt->preprocessDataType) { case PreprocessDataType::SparseEigen: // Fall through case PreprocessDataType::SparseRagged: return builderForType(m_opt->preprocessDataType); default: std::cerr << "SparseBayesRRG::markerBuilder - unsupported type: " << m_opt->preprocessDataType << std::endl; } return nullptr; } void SparseBayesRRG::init(int K, unsigned int markerCount, unsigned int individualCount) { BayesRBase::init(K, markerCount, individualCount); m_ones.setOnes(individualCount); } void SparseBayesRRG::prepare(BayesRKernel *kernel) { // Hmmm if (auto* eigenBayesRKernel = dynamic_cast<EigenBayesRKernel*>(kernel)) { eigenBayesRKernel->ones = &m_ones; } } void SparseBayesRRG::readWithSharedLock(BayesRKernel *kernel) { auto* sparseKernel = dynamic_cast<SparseBayesRKernel*>(kernel); assert(sparseKernel); //now we update to the global epsilonSum sparseKernel->epsilonSum = m_epsilonSum; } void SparseBayesRRG::writeWithUniqueLock(BayesRKernel *kernel) { auto* sparseKernel = dynamic_cast<SparseBayesRKernel*>(kernel); assert(sparseKernel); if (m_isAsync) {} //now the global node is in charge of updating m_epsilon else m_epsilonSum += sparseKernel->epsilonSum; } void SparseBayesRRG::updateGlobal(const KernelPtr& kernel, const ConstAsyncResultPtr &result) { BayesRBase::updateGlobal(kernel, result); auto* sparseKernel = dynamic_cast<SparseBayesRKernel*>(kernel.get()); assert(sparseKernel); std::unique_lock lock(m_mutex); m_epsilonSum += sparseKernel->epsilonSum; // now epsilonSum contains only deltaEpsilonSum } void SparseBayesRRG::updateMu(double old_mu,double N) { m_epsilon = m_epsilon.array() + m_mu;// for dense and sparse we substract previous value m_epsilonSum+=old_mu*double(N); //for sparse this is important for dense its ineffectual m_mu = m_dist.norm_rng(m_epsilonSum / N, m_sigmaE / N); //update mu with the sum reduction m_epsilon = m_epsilon.array() - m_mu;// for dense and sparse we substract again now epsilon =Y-mu-X*beta m_epsilonSum-=m_mu*N;//we perform the equivalent update in epsilonSum for sparse this is important, for dense its ineffec. }
C++
CL
61321dac0339f868da138171f882f3bf606fe359d90e89c67f32757945cdf98c
// CPSC 587 Assignment 1 // Albert Chu 10059388 // Adapted and using code originally written by Andrew Owens #include <sstream> #include<iostream> #include<cmath> #include<GL/glew.h> // include BEFORE glut #include<GL/freeglut.h> #include <glm/gtx/string_cast.hpp> #include<glm/glm.hpp> #include <glm/gtc/matrix_transform.hpp> #include <glm/gtc/type_ptr.hpp> #include <glm/gtc/matrix_transform.hpp> #include "ShaderTools.h" #include <math.h> #include <algorithm> // std::max GLuint structProgramID; GLuint vaoStructID; GLuint structVertBufferID; GLuint structColorBufferID; // Could store these in some data structure GLuint trackProgramID; GLuint vaoTrackID; GLuint trackVertBufferID; GLuint trackColorBufferID; float track_max_height; float track_min_height; GLuint vaoCarID; GLuint carProgramID; GLuint carVertBufferID; GLuint carColorBufferID; glm::vec3 carCenter; glm::mat4 trackMVP; glm::mat4 carMVP; glm::mat4 carM; // model matrix glm::mat4 trackM; // model matrix glm::mat4 V; // view matrix glm::mat4 P; // projection matrix can be left alone int curIndex = 0; // The vertex immediately behind the car int delay = 1; float GRAVITY = 9.81f; float car_scale = 1.f; int WIN_WIDTH = 800, WIN_HEIGHT = 600; // function declarations... just to keep things kinda organized. void displayFunc(); void resizeFunc(); void idleFunc(); void init(); void generateIDs(); void deleteIDs(); void setupVAO(); void loadBuffer(); void loadProjectionMatrix(); void loadModelViewMatrix(); void setupModelViewProjectionTransform(); void reloadMVPUniform(); glm::vec3 center(std::vector<glm::vec3> verts); void set_tnb_frame(float speed, glm::mat4 & modelMatrix, std::vector<glm::vec3> & verts, int & index); void moveCarTo(glm::vec3 new_pos); glm::vec3 getMatrixColumn(glm::mat4 matrix, int column); void updateMatrixColumn(glm::mat4 & matrix, int column, glm::vec3 vector); float get_speed(glm::vec3 position); int main( int, char** ); // function declarations std::vector< glm::vec3 > track_verts; std::vector< glm::vec3 > rail_verts; // This is what is going to end up being rendered for the track std::vector< glm::vec3 > struct_verts; // Roller coaster supports std::vector< glm::vec3 > car_verts; bool left_click = false; bool right_click = false; bool translate_bool = true; bool camera_lock = true; float delta_x = 0; float delta_y = 0; float delta_z = 0; int slowdown = 1; // This variable will slow down the roller coaster over time until it stops. int lastTime; //typedef std::vector< Vec3f > VecV3f; void printInfo() { std::cout << "Using GLEW " << glewGetString(GLEW_VERSION) << std::endl; std::cout << "Vendor: " << glGetString(GL_VENDOR) << std::endl; std::cout << "Renderer: " << glGetString(GL_RENDERER) << std::endl; std::cout << "Version: " << glGetString(GL_VERSION) << std::endl; std::cout << "GLSL: " << glGetString(GL_SHADING_LANGUAGE_VERSION) << std::endl; } void render() { if (camera_lock) { updateMatrixColumn(V, 3, glm::vec3(-carCenter.x, -carCenter.y , -carCenter.z - 10)); } else { V = glm::rotate(V, 0.05f, glm::vec3(0.0f, 1.0f, 0.0f)); } setupModelViewProjectionTransform(); // send changes to GPU reloadMVPUniform(); glutPostRedisplay(); } void loadVec3FromFile(std::vector<glm::vec3> & vecs, std::string const & fileName) { std::ifstream file(fileName); if (!file) { throw std::runtime_error("Unable to open file."); } std::string line; size_t index; std::stringstream ss(std::ios_base::in); size_t lineNum = 0; vecs.clear(); while (getline(file, line)) { ++lineNum; // remove comments index = line.find_first_of("#"); if (index != std::string::npos) { line.erase(index, std::string::npos); } // removes leading/tailing junk line.erase(0, line.find_first_not_of(" \t\r\n\v\f")); index = line.find_last_not_of(" \t\r\n\v\f") + 1; if (index != std::string::npos) { line.erase(index, std::string::npos); } if (line.empty()) { continue; // empty or commented out line } ss.str(line); ss.clear(); float x, y, z; if ((ss >> x >> y >> z) && (!ss || !ss.eof() || ss.good())) { throw std::runtime_error("Error read file: " + line + " (line: " + std::to_string(lineNum) + ")"); } else { vecs.push_back(glm::vec3(x,y,z)); } } file.close(); } void displayFunc() { glClear( GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT ); // Draw track glUseProgram(trackProgramID); glBindVertexArray(vaoTrackID); GLfloat width = 5; glLineWidth(width); //glDrawArrays(GL_POINTS, 0, track_verts.size()); glDrawArrays(GL_LINE_LOOP, 0, rail_verts.size()); // Draw Struct glBindVertexArray(vaoStructID); width = 25; glLineWidth(width); glDrawArrays(GL_LINE_LOOP, 0, struct_verts.size()); // Draw car glUseProgram(carProgramID); glBindVertexArray(vaoCarID); //glDrawArrays(GL_POINTS, 0, car_verts.size()); glDrawArrays(GL_TRIANGLES, 0, car_verts.size()); glutSwapBuffers(); } //Keyboard commands for manipulating the enviorment void keyboardFunc(unsigned char key, int x, int y){ if (key == 'o') // Orient view matrix to identity matrix { V = glm::mat4(1.0f); } if (key == 'r') // Rotate Mode translate_bool = false; if (key == 't') // Translate Mode translate_bool = true; if (key == 'l') { V = glm::mat4(1.0f); camera_lock = !camera_lock; if (camera_lock) { V = glm::mat4(1.0f); } else{ V = glm::mat4(1.0f); V = glm::translate(V, glm::vec3(-5, -5, -30)); } } render(); } void mouseMove(int x, int y) { if (left_click) { delta_y -= y; delta_x -= x; if (translate_bool) V = glm::translate(V, glm::vec3(-delta_x / 300, delta_y / 500, 0)); else { V = glm::rotate(V, delta_y / 10, glm::vec3(-1.0f, 0.0f, 0.0f)); V = glm::rotate(V, delta_x / 10, glm::vec3(0.0f, 1.0f, 0.0f)); } delta_x = x; delta_y = y; } if (right_click) { delta_z -= y; V = glm::translate(V, glm::vec3(0, 0, delta_z / 500)); delta_z = y; } render(); } void mouseButton(int button, int state, int x, int y) { switch (button) { case GLUT_LEFT_BUTTON: std::cout << "Left Button" << std::endl; if (state == GLUT_DOWN){ left_click = true; delta_x = x; delta_y = y; } else { left_click = false; } break; case GLUT_MIDDLE_BUTTON: break; case GLUT_RIGHT_BUTTON: if (state == GLUT_DOWN){ right_click = true; delta_z = y; } else { right_click = false; } break; default: std::cerr << "Encountered an error with mouse button : " << button << ", state : " << state << std::endl; } std::cout << "Button: " << button << ", State: " << state << std::endl; printf("Button %s At %d %d\n", (state == GLUT_DOWN) ? "Down" : "Up", x, y); } void resizeFunc( int width, int height ) { WIN_WIDTH = width; WIN_HEIGHT = height; glViewport( 0, 0, width, height ); loadProjectionMatrix(); reloadMVPUniform(); glutPostRedisplay(); } void generateCarID(std::string vsSource, std::string fsSource) { carProgramID = CreateShaderProgram(vsSource, fsSource); // load IDs given from OpenGL glGenVertexArrays(1, &vaoCarID); glGenBuffers(1, &carVertBufferID); glGenBuffers(1, &carColorBufferID); } void generateTrackID(std::string vsSource, std::string fsSource) { trackProgramID = CreateShaderProgram(vsSource, fsSource); // load IDs given from OpenGL glGenVertexArrays(1, &vaoTrackID); glGenBuffers(1, &trackVertBufferID); glGenBuffers(1, &trackColorBufferID); } void generateStructID(std::string vsSource, std::string fsSource) { structProgramID = CreateShaderProgram(vsSource, fsSource); // load IDs given from OpenGL glGenVertexArrays(1, &vaoStructID); glGenBuffers(1, &structVertBufferID); glGenBuffers(1, &structColorBufferID); } void generateIDs() { std::string vsSource = loadShaderStringfromFile("./basic_vs.glsl"); std::string fsSource = loadShaderStringfromFile("./basic_fs.glsl"); generateCarID(vsSource, fsSource); generateTrackID(vsSource, fsSource); generateStructID(vsSource, fsSource); } void deleteIDs() { glDeleteProgram(trackProgramID); glDeleteProgram(carProgramID); glDeleteVertexArrays(1, &vaoTrackID); glDeleteBuffers(1, &trackVertBufferID); glDeleteBuffers(1, &trackColorBufferID); glDeleteVertexArrays(1, &vaoStructID); glDeleteBuffers(1, &structVertBufferID); glDeleteBuffers(1, &structColorBufferID); glDeleteVertexArrays(1, &vaoCarID); glDeleteBuffers(1, &carVertBufferID); glDeleteBuffers(1, &carColorBufferID); } void loadProjectionMatrix() { // Perspective Only P = glm::perspective(60.0f, static_cast<float>(WIN_WIDTH) / WIN_HEIGHT, 0.01f, 1000.f); } void loadModelViewMatrix() { glm::vec3 trackStart = track_verts.at(curIndex); curIndex = 1; carM = glm::scale(carM, glm::vec3(car_scale)); moveCarTo(trackStart); } void setupModelViewProjectionTransform() { trackMVP = P * V * trackM; // transforms vertices from right to left (odd huh?) carMVP = P * V * carM; // transforms vertices from right to left (odd huh?) } void reloadTrackMVPUniform() { GLint mvpID = glGetUniformLocation(trackProgramID, "MVP"); glUseProgram(trackProgramID); glUniformMatrix4fv(mvpID, // ID 1, // only 1 matrix GL_FALSE, // transpose matrix, Mat4f is row major glm::value_ptr(trackMVP) // pointer to data in Mat4f ); } void reloadCarMVPUniform() { GLint mvpID = glGetUniformLocation(carProgramID, "MVP"); glUseProgram(carProgramID); glUniformMatrix4fv(mvpID, // ID 1, // only 1 matrix GL_FALSE, // transpose matrix, Mat4f is row major glm::value_ptr(carMVP) // pointer to data in Mat4f ); } void reloadMVPUniform() { reloadCarMVPUniform(); reloadTrackMVPUniform(); } void setupStructVAO() { glBindVertexArray(vaoStructID); glEnableVertexAttribArray(0); // match layout # in shader glBindBuffer(GL_ARRAY_BUFFER, structVertBufferID); glVertexAttribPointer( 0, // attribute layout # above 3, // # of components (ie XYZ ) GL_FLOAT, // type of components GL_FALSE, // need to be normalized? 0, // stride (void*)0 // array buffer offset ); glEnableVertexAttribArray(1); // match layout # in shader glBindBuffer(GL_ARRAY_BUFFER, structColorBufferID); glVertexAttribPointer( 1, // attribute layout # above 3, // # of components (ie XYZ ) GL_FLOAT, // type of components GL_FALSE, // need to be normalized? 0, // stride (void*)0 // array buffer offset ); glBindVertexArray(0); // reset to default } void setupTrackVAO() { glBindVertexArray(vaoTrackID); glEnableVertexAttribArray(0); // match layout # in shader glBindBuffer(GL_ARRAY_BUFFER, trackVertBufferID); glVertexAttribPointer( 0, // attribute layout # above 3, // # of components (ie XYZ ) GL_FLOAT, // type of components GL_FALSE, // need to be normalized? 0, // stride (void*)0 // array buffer offset ); glEnableVertexAttribArray(1); // match layout # in shader glBindBuffer(GL_ARRAY_BUFFER, trackColorBufferID); glVertexAttribPointer( 1, // attribute layout # above 3, // # of components (ie XYZ ) GL_FLOAT, // type of components GL_FALSE, // need to be normalized? 0, // stride (void*)0 // array buffer offset ); glBindVertexArray(0); // reset to default } void setupCarVAO() { glBindVertexArray(vaoCarID); glEnableVertexAttribArray(0); // match layout # in shader glBindBuffer(GL_ARRAY_BUFFER, carVertBufferID); glVertexAttribPointer( 0, // attribute layout # above 3, // # of components (ie XYZ ) GL_FLOAT, // type of components GL_FALSE, // need to be normalized? 0, // stride (void*)0 // array buffer offset ); glEnableVertexAttribArray(1); // match layout # in shader glBindBuffer(GL_ARRAY_BUFFER, carColorBufferID); glVertexAttribPointer( 1, // attribute layout # above 3, // # of components (ie XYZ ) GL_FLOAT, // type of components GL_FALSE, // need to be normalized? 0, // stride (void*)0 // array buffer offset ); glBindVertexArray(0); // reset to default } // Returns a subdivided vector array that adds another point in between each existing point in vector std::vector< glm::vec3 > subdivide(std::vector< glm::vec3 > verts) { std::vector< glm::vec3 > new_verts; for (int i = 0; i < verts.size(); i++) { glm::vec3 const& v1 = verts[i]; glm::vec3 const& v2 = verts[(i + 1) % verts.size()]; glm::vec3 mid = (v1 + v2) * 0.5f; new_verts.push_back(v1); new_verts.push_back(mid); } return new_verts; } // Returns a subdivided vector array that offsets each existing point in vector halfway to its next neighbor std::vector< glm::vec3 > offset(std::vector< glm::vec3 > verts) { std::vector< glm::vec3 > new_verts; for (int i = 0; i < verts.size(); i++) { glm::vec3 const& v1 = verts[i]; glm::vec3 const& v2 = verts[(i + 1) % verts.size()]; glm::vec3 mid = (v1 + v2) * 0.5f; new_verts.push_back(mid); } return new_verts; } // Returns a subdivided vector array that goes to the specified depth of subdivision std::vector< glm::vec3 > subdivision(std::vector< glm::vec3 > original_verts, int depth) { std::vector< glm::vec3 > new_verts = original_verts; for (int i = 0; i < depth; i++) { new_verts = subdivide(new_verts); new_verts = offset(new_verts); } return new_verts; } float getRandFloat(float low, float high) { return (low + static_cast <float> (rand()) / (static_cast <float> (RAND_MAX / (high - low)))); } // Sets the max and min y from the vector of vec3s void set_max_min_y(std::vector<glm::vec3> verts, float & max, float & min) { for (glm::vec3 vert : verts) { if (vert.y > max) max = vert.y; if (vert.y < min) min = vert.y; } } // Based on some given track, constructs a vector of rail points at some offset void set_track_rails(std::vector<glm::vec3> & track, std::vector<glm::vec3> & rails) { std::vector<glm::vec3> in_rail; //List of inside railling points std::vector<glm::vec3> out_rail; //List of outside railling points //int track_index = 0; float rail_offset = 0.9f; for (int i = 0; i < track.size(); i++) { float speed = get_speed(track[i]) ; glm::mat4 matrix; set_tnb_frame(speed, matrix, track, i); glm::vec3 binormal = getMatrixColumn(matrix, 1); glm::vec3 in_vert = track[i] + (binormal * rail_offset); glm::vec3 out_vert = track[i] - (binormal * rail_offset); in_rail.push_back(in_vert); out_rail.push_back(out_vert); } //Order the verts in a way that will render nicely with gl_line_loop for (int i = 0; i < track.size(); i++) { glm::vec3 in1 = in_rail[i]; glm::vec3 in2 = in_rail[(i + 1) % track.size()]; glm::vec3 out1 = out_rail[i]; glm::vec3 out2 = out_rail[(i + 1) % track.size()]; rails.push_back(in2); rails.push_back(in1); rails.push_back(in1); rails.push_back(out1); rails.push_back(out1); rails.push_back(out2); rails.push_back(out2); rails.push_back(in2); } } // Based on some given track, constructs a vector of rail points at some offset void set_rail_structs(std::vector<glm::vec3> & rails, std::vector<glm::vec3> & structs, int track_min) { int struct_offset = 30; float struct_len = track_min + 15.f; //This is how far the rollercoaster track appears off the ground for (int i = 0; i < rails.size(); i += struct_offset) { glm::vec3 strut_rail = rails[i % rails.size()]; glm::vec3 strut_ground = glm::vec3(strut_rail.x, -struct_len, strut_rail.z); structs.push_back(strut_ground); structs.push_back(strut_rail); structs.push_back(strut_rail); structs.push_back(strut_ground); } } glm::vec3 getMatrixColumn(glm::mat4 matrix, int column) { return glm::vec3(matrix[column][0], matrix[column][1], matrix[column][2]); } // Sets up track vertex buffer from file, subdivide and process vectors to be smooth, Assign colors to the vertex shaders void loadStructBuffer() { set_rail_structs(rail_verts, struct_verts, track_min_height); glBindBuffer(GL_ARRAY_BUFFER, structVertBufferID); glBufferData(GL_ARRAY_BUFFER, sizeof(glm::vec3) * struct_verts.size(), // byte size of Vec3f, 4 of them struct_verts.data(), // pointer (Vec3f*) to contents of verts GL_STATIC_DRAW); // Usage pattern of GPU buffer carCenter = center(car_verts); // RGB values for the vertices std::vector<glm::vec3> colors; for (int i = 0; i < struct_verts.size(); i++) { float r = getRandFloat(0.30, 1.0); float g = getRandFloat(0.60, 1.0); float b = getRandFloat(0.70, 1.0); colors.push_back(glm::vec3(r, g, b)); //colors.push_back(glm::vec3(218, 0, 0)); } glBindBuffer(GL_ARRAY_BUFFER, structColorBufferID); glBufferData(GL_ARRAY_BUFFER, sizeof(glm::vec3)*colors.size(), colors.data(), GL_STATIC_DRAW); } // Sets up track vertex buffer from file, subdivide and process vectors to be smooth, Assign colors to the vertex shaders void loadTrackBuffer(std::string file_path) { loadVec3FromFile(track_verts, file_path); track_verts = subdivision(track_verts, 4); set_max_min_y(track_verts, track_max_height, track_min_height); set_track_rails(track_verts, rail_verts); glBindBuffer(GL_ARRAY_BUFFER, trackVertBufferID); glBufferData(GL_ARRAY_BUFFER, sizeof(glm::vec3) * rail_verts.size(), // byte size of Vec3f, 4 of them rail_verts.data(), // pointer (Vec3f*) to contents of verts GL_STATIC_DRAW); // Usage pattern of GPU buffer // RGB values for the vertices std::vector<glm::vec3> colors; for (int i = 0; i < rail_verts.size(); i++) { //float r = getRandFloat(0.50, 1.0); //float g = getRandFloat(0.50, 1.0); //float b = getRandFloat(0.50, 1.0); //colors.push_back(glm::vec3(r, g, b)); colors.push_back(glm::vec3(218, 0, 0)); } glBindBuffer(GL_ARRAY_BUFFER, trackColorBufferID); glBufferData(GL_ARRAY_BUFFER, sizeof(glm::vec3)*colors.size(), colors.data(), GL_STATIC_DRAW); } glm::vec3 center(std::vector<glm::vec3> verts) { return glm::vec3(0, 0, 0); //Unsure how to get center of object so im going to hack it to start at center } void loadCarBuffer(std::string file_path) { loadVec3FromFile(car_verts, file_path); carCenter = center(car_verts); glBindBuffer(GL_ARRAY_BUFFER, carVertBufferID); glBufferData(GL_ARRAY_BUFFER, sizeof(glm::vec3) * car_verts.size(), // byte size of Vec3f, 4 of them car_verts.data(), // pointer (Vec3f*) to contents of verts GL_STATIC_DRAW); // Usage pattern of GPU buffer // RGB values for the vertices std::vector<glm::vec3> colors; for (int i = 0; i < car_verts.size(); i++) { float r = getRandFloat(0, 1.0); float g = getRandFloat(0.0, 1.0); float b = getRandFloat(1.0, 1.0); colors.push_back(glm::vec3(r, g, b)); } glBindBuffer(GL_ARRAY_BUFFER, carColorBufferID); glBufferData(GL_ARRAY_BUFFER, sizeof(glm::vec3)*colors.size(), colors.data(), GL_STATIC_DRAW); } void init(std::string track_file_path, std::string car_file_path) { glEnable( GL_DEPTH_TEST ); // SETUP SHADERS, BUFFERS, VAOs generateIDs(); setupTrackVAO(); loadTrackBuffer(track_file_path); setupStructVAO(); loadStructBuffer(); setupCarVAO(); loadCarBuffer(car_file_path); loadModelViewMatrix(); loadProjectionMatrix(); setupModelViewProjectionTransform(); reloadMVPUniform(); } void updateMatrixColumn(glm::mat4 & matrix, int column, glm::vec3 vector) { matrix[column][0] = vector.x; matrix[column][1] = vector.y; matrix[column][2] = vector.z; } //Moves a car from whatever its current center position to a new position void moveCarTo(glm::vec3 new_pos) { updateMatrixColumn(carM, 3, new_pos); carCenter = new_pos; render(); } // Returns the next car position along the track given a speed and time glm::vec3 next_car_position(float speed, float delata_time_ms) { float total_distance = speed * (delata_time_ms / 800); // Total distance that must be travelled given the speed and the time passed since last render float distance_travelled = 0; //std::cout << "get_next_car_position: Total distance: " << total_distance << std::endl; // Get to the proper segment glm::vec3 pos, next_pos; pos = carCenter; //pos = track_verts[curIndex % track_verts.size()]; next_pos = track_verts[curIndex % track_verts.size()]; while ((distance_travelled + glm::distance(pos, next_pos)) < total_distance) { //std::cout << "\tWhileLoop: Distance between point[" << (curIndex) << " to " << curIndex + 1 << "] is \n\t" << glm::to_string(pos) << "\n\t and \n\t" << glm::to_string(next_pos) << " is " << glm::distance(pos, next_pos) << std::endl; //std::cout << "\tWhileLoop: Travelled distance: " << distance_travelled << std::endl; distance_travelled += glm::distance(pos, next_pos); pos = track_verts[curIndex % track_verts.size()]; next_pos = track_verts[(curIndex + 1) % track_verts.size()]; curIndex++; } //std::cout << "Found correct segment between [" << curIndex - 1 << " and " << curIndex << "]" << std::endl; //std::cout << "\nDistance between point[" << (curIndex - 1) << " to " << curIndex << "] is \n" << glm::to_string(pos) << "\n\tand \n\t" << glm::to_string(next_pos) << " is " << glm::distance(pos, next_pos) << std::endl; //std::cout << "\tDistance remaining is : \n\t((" << total_distance << " - " << distance_travelled << ") / " << glm::distance(pos, next_pos) << ")" << " = " // << ((total_distance - distance_travelled)) << std::endl; //std::cout << "\tVector is: " << glm::to_string(next_pos - pos) << std::endl; //std::cout << "\tNormalized vector is: " << glm::to_string(glm::normalize(next_pos - pos)) << std::endl; glm::vec3 car_pos = glm::normalize(next_pos - pos) * ((total_distance - distance_travelled)); car_pos = carCenter + car_pos; //std::cout << "\tNew vector is: " << glm::to_string(car_pos) << "\n" << std::endl; curIndex = curIndex % track_verts.size(); return car_pos; } float get_speed(glm::vec3 position) { int speed_scalar = 3; return (glm::sqrt(2 * GRAVITY * (track_max_height - position.y)) + 2) * speed_scalar / slowdown; } // Assumption: curIndex is set at the index immediately in front of where ever carCenter is at. void set_tnb_frame(float speed, glm::mat4 & modelMatrix, std::vector<glm::vec3> & verts, int & index) { glm::vec3 p1 = verts[(index - 1) % verts.size()]; glm::vec3 point = verts[index % verts.size()]; glm::vec3 p3 = verts[(index + 1) % verts.size()]; // Compare the length of segment curIndex - 1 to curIndex, and length of segment curIndex to curIndex + 1 float seg1 = glm::distance(p1, point); float seg2 = glm::distance(point, p3); float max_len = std::min(seg1, seg2); glm::vec3 point_before = point + glm::normalize(p3 - point) * max_len; glm::vec3 point_after = point + glm::normalize(p1 - point) * max_len; float c = glm::length(point_after - point); float h = glm::length((point_after - (point * 2.f) + point_before)); float radius = (pow(c, 2) + (4 * pow(h, 2))) / (8 * h); float speed_squared = (pow(speed,2)); glm::vec3 gravity_vector = glm::vec3(0, 1, 0); glm::vec3 tangent = glm::normalize((point_after - point) * 0.5f); glm::vec3 normal = glm::normalize(((speed_squared / radius) * glm::normalize((point_after - (point * 2.f) + point_before) * 0.25f)) + gravity_vector); glm::vec3 binormal = glm::normalize(glm::cross(tangent, normal)); updateMatrixColumn(modelMatrix, 0, tangent); updateMatrixColumn(modelMatrix, 1, normal); updateMatrixColumn(modelMatrix, 2, binormal); } void timerFunc(int delay) { float speed = get_speed(carCenter); moveCarTo(next_car_position(speed, delay)); set_tnb_frame(speed, carM, track_verts, curIndex); carM = glm::scale(carM, glm::vec3(car_scale)); render(); glutTimerFunc(delay, timerFunc, delay); } int main( int argc, char** argv ) { glutInit( &argc, argv ); // Setup FB configuration glutInitDisplayMode( GLUT_RGB | GLUT_DOUBLE | GLUT_DEPTH ); glutInitWindowSize( WIN_WIDTH, WIN_HEIGHT ); glutInitWindowPosition( 0, 0 ); glutCreateWindow( "Assignment 1: Rollercoaster" ); glewExperimental=true; // Needed in Core Profile // Comment out if you want to us glBeign etc... if( glewInit() != GLEW_OK ) { std::cerr << "Failed to initialize GLEW" << std::endl; return -1; } printInfo(); glutDisplayFunc( displayFunc ); glutReshapeFunc( resizeFunc ); glutTimerFunc(delay, timerFunc, delay); glutMouseFunc(mouseButton); glutMotionFunc(mouseMove); glutKeyboardFunc(keyboardFunc); std::string track("track.txt"); std::string car("car.txt"); init(track, car); // our own initialize stuff func std::cout << "Track Verts total size is: " << track_verts.size() << std::endl; glutMainLoop(); // clean up after loop deleteIDs(); return 0; }
C++
CL
9cefd75fb4d006176363602621c7e4597269fc93007a23f588e766df66eef253
#include "roboteam_tactics/tactics/rtt_bob/old/WeirdTactic.h" #include "roboteam_tactics/treegen/LeafRegister.h" namespace rtt { RTT_REGISTER_TACTIC_F(rtt_bob/old, WeirdTactic); WeirdTactic::WeirdTactic(std::string name, bt::Blackboard::Ptr blackboard) : Tactic(name, blackboard) {} void WeirdTactic::Initialize() { } bt::Node::Status WeirdTactic::Update() { return Status::Failure; } } // rtt
C++
CL
c3f79613d351d76966749660e5361d5455484e4af30a3f622b1bb60bfa14236f
# pragma once # include "String.hpp" # include <DxLib.h> /// <summary>デバッグ情報</summary> class Debug { public: Debug(); public: /// <summary>画面にデバッグ表示する</summary> template <typename ...Args> static void FormatPrint(const String& format, Args&& ...args) { printfDx(format.ToWide().c_str(), std::forward<Args>(args)...); } /// <summary>画面にデバッグ表示したあと改行する</summary> template <typename ...Args> static void FormatPrintln(const String& format, Args&& ...args) { FormatPrint(format.ToWide().c_str(), std::forward<Args>(args)...); printfDx("\n"); } template <typename Type, typename ...Args> static void Print(const Type& value, Args&& ...args) { printfDx(String::Create(value, std::forward<Args>(args)...).ToWide().c_str()); } template <typename Type, typename ...Args> static void Println(const Type& value, Args&& ...args) { FormatPrint(value, std::forward<Args>(args)...); printfDx(L"\n"); } /// <summary>更新処理</summary> static void Update(); /// <summary>毎フレームクリアするかどうかを設定する</summary> static void SetClear(bool isClear); /// <summary>毎フレームクリアするかどうかを返す</summary> static bool IsClear(); /// <summary>デバッグ表示をクリアする</summary> static void Clear(); /// <summary>メッセージボックスを表示する</summary> static void Show(const TCHAR* messsage, const TCHAR* caption, UINT style); /// <summary>フォントサイズを変更する</summary> static void ChangeFontSize(int fontSize); private: bool m_isClear; int m_fontSize; };
C++
CL
0e9c6751325bed6262d4faca393febc28bd2e20ff7a1d65c18e058128412727a
class UnionFind { public: void union_(int u, int v) { if (!id.count(u)) id[u] = u; if (!id.count(v)) id[v] = v; const int i = find(u); const int j = find(v); if (i != j) id[i] = j; } unordered_map<int, vector<int>> getGroupIdToValues() { unordered_map<int, vector<int>> groupIdToValues; for (const auto& [u, _] : id) groupIdToValues[find(u)].push_back(u); return groupIdToValues; } private: unordered_map<int, int> id; int find(int u) { return id[u] == u ? u : id[u] = find(id[u]); } }; class Solution { public: vector<vector<int>> matrixRankTransform(vector<vector<int>>& matrix) { const int m = matrix.size(); const int n = matrix[0].size(); vector<vector<int>> ans(m, vector<int>(n)); // {val: [(i, j)]} map<int, vector<pair<int, int>>> valToGrids; // rank[i] := max rank of the row or column so far vector<int> maxRankSoFar(m + n); for (int i = 0; i < m; ++i) for (int j = 0; j < n; ++j) valToGrids[matrix[i][j]].emplace_back(i, j); for (const auto& [val, grids] : valToGrids) { UnionFind uf; for (const auto& [i, j] : grids) // Union i-th row with j-th col. uf.union_(i, j + m); for (const auto& [groupId, values] : uf.getGroupIdToValues()) { // Get the max rank of all the included rows and cols. int maxRank = 0; for (const int i : values) maxRank = max(maxRank, maxRankSoFar[i]); // Update all the rows and columns to maxRank + 1. for (const int i : values) maxRankSoFar[i] = maxRank + 1; } for (const auto& [i, j] : grids) ans[i][j] = maxRankSoFar[i]; } return ans; } };
C++
CL
4d40fcffcbca51b30dcda6d9a0d53210f89fbbd52acdd62d4ee9bfcecbcde1e0
#include <Arduino.h> // We voegen de Neopixel library toe waarmee we de ledring kunnen aansturen #include <Adafruit_NeoPixel.h> // We voegen de Wifi en de NTPclient libraries toe waarmee we met wifi kunnen verbinden en de tijd kunnen ophalen #include <ESP8266WiFi.h> #include <NTPClient.h> #include <WiFiUdp.h> // We stellen het wifi netwerk en wachtwoord in const char *ssid = "netwerknaam"; const char *password = "wachtwoord"; // We maken een Wifi en NTPclient object aan WiFiUDP ntpUDP; NTPClient timeClient(ntpUDP, "pool.ntp.org"); // We definiëren aan welke pinnen we het knopje, de potentiometer en ledring aangesloten hebben #define POT_PIN A0 #define BTN_PIN D8 #define LED_PIN D4 // Onze ledring heeft 60 ledjes, dit slaan we op en we maken een ledstrip object aan #define LED_COUNT 60 Adafruit_NeoPixel strip(LED_COUNT, LED_PIN, NEO_GRB + NEO_KHZ800); void setup() { // We starten de ledstrip op en zetten hem aan strip.begin(); // We maken de ledstrip rood om aan te geven dat we nog niet met wifi verbonden zijn for (int i = 0; i < strip.numPixels(); i++) { strip.setPixelColor(i, 255, 0, 0); } strip.setBrightness(25); strip.show(); // We maken verbinding met het wifi netwerk WiFi.begin(ssid, password); // Zolang we nog niet met het wifi verbonden zijn updaten we een pixel van de ring naar oranje int status = 0; while (WiFi.status() != WL_CONNECTED) { delay(500); if (status < LED_COUNT) { strip.setPixelColor(status++, 255, 255, 0); strip.show(); } } // We starten de NTPclient op en stellen de tijdszone in op GMT+2 (europese zomertijd) timeClient.begin(); timeClient.setTimeOffset(7200); // We maken de ledstrip blauw om aan te geven dat we succesvol opgestart zijn for (int i = 0; i < strip.numPixels(); i++) { strip.setPixelColor(i, 0, 0, 255); } strip.show(); delay(500); } void loop() { // We updaten de NTPclient met de huidige tijd timeClient.update(); int minuutPixel = timeClient.getMinutes(); int uurPixel = (timeClient.getHours() % 12) * 5; int secondePixel = timeClient.getSeconds(); for (int i = 0; i < strip.numPixels(); i++) { int red = (i == minuutPixel) ? 255 : 0; int green = (i == uurPixel) ? 255 : 0; int blue = (i == secondePixel) ? 255 : 0; if (i % 15 == 0 && !red && !green && !blue) { red = 255; green = 255; blue = 255; } strip.setPixelColor(LED_COUNT - 1 - i, red, green, blue); } // Vervolgens bepalen we hoe fel hij moet zijn door de waarde van de potmeter uit te lezen // Dit is een waarde tussen de 0 en 1024, de brightness moet ingesteld worden tussen 0 en 255, dus delen he het door 4 int brightness = analogRead(POT_PIN) / 4; // We stellen de felheid van de ledring in strip.setBrightness(brightness); // We sturen alle instellingen die we gedaan hebben naar de ledring om weergeven te worden strip.show(); delay(500); }
C++
CL
5db9e36cca9469f9196af56e2df35c93cd39726d1abcc170f9f0c250795bf869
//************************************ bs::framework - Copyright 2018 Marko Pintera **************************************// //*********** Licensed under the MIT license. See LICENSE.md for full terms. This notice is not to be removed. ***********// #pragma once #include "BsCorePrerequisites.h" #include "Resources/BsResource.h" namespace bs { /** @addtogroup Physics * @{ */ /** * Material that controls how two physical objects interact with each other. Materials of both objects are used during * their interaction and their combined values are used. */ class BS_CORE_EXPORT BS_SCRIPT_EXPORT(m:Physics) PhysicsMaterial : public Resource { public: virtual ~PhysicsMaterial() = default; /** * Controls friction when two in-contact objects are not moving lateral to each other (for example how difficult * it is to get an object moving from a static state while it is in contact with other object(s)). */ BS_SCRIPT_EXPORT(n:StaticFriction,pr:setter) virtual void setStaticFriction(float value) = 0; /** @copydoc setStaticFriction() */ BS_SCRIPT_EXPORT(n:StaticFriction,pr:getter) virtual float getStaticFriction() const = 0; /** * Controls friction when two in-contact objects are moving lateral to each other (for example how quickly does an * object slow down when sliding along another object). */ BS_SCRIPT_EXPORT(n:DynamicFriction,pr:setter) virtual void setDynamicFriction(float value) = 0; /** @copydoc setDynamicFriction() */ BS_SCRIPT_EXPORT(n:DynamicFriction,pr:getter) virtual float getDynamicFriction() const = 0; /** * Controls "bounciness" of an object during a collision. Value of 1 means the collision is elastic, and value of 0 * means the value is inelastic. Must be in [0, 1] range. */ BS_SCRIPT_EXPORT(n:Restitution,pr:setter) virtual void setRestitutionCoefficient(float value) = 0; /** @copydoc setRestitutionCoefficient() */ BS_SCRIPT_EXPORT(n:Restitution,pr:getter) virtual float getRestitutionCoefficient() const = 0; /** * Creates a new physics material. * * @param[in] staticFriction Controls friction when two in-contact objects are not moving lateral to each other * (for example how difficult is to get an object moving from a static state while it * is in contact other object(s)). * @param[in] dynamicFriction Sets dynamic friction of the material. Controls friction when two in-contact objects * are moving lateral to each other (for example how quickly does an object slow down * when sliding along another object). * @param[in] restitution Controls "bounciness" of an object during a collision. Value of 1 means the * collision is elastic, and value of 0 means the value is inelastic. Must be in * [0, 1] range. */ BS_SCRIPT_EXPORT(ec:PhysicsMaterial) static HPhysicsMaterial create(float staticFriction = 0.0f, float dynamicFriction = 0.0f, float restitution = 0.0f); /** @name Internal * @{ */ /** * @copydoc create() * * For internal use. Requires manual initialization after creation. */ static SPtr<PhysicsMaterial> _createPtr(float staticFriction = 0.0f, float dynamicFriction = 0.0f, float restitution = 0.0f); /** @} */ /************************************************************************/ /* SERIALIZATION */ /************************************************************************/ public: friend class PhysicsMaterialRTTI; static RTTITypeBase* getRTTIStatic(); RTTITypeBase* getRTTI() const override; }; /** @} */ }
C++
CL
a82d0c522d0420cb7fda714c51851f2655960c99971c008fa8337a2a9cc40004
// Copyright (c) 2020 Hartmut Kaiser // // SPDX-License-Identifier: BSL-1.0 // Distributed under the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) template <typename T> struct test { template <typename T_> test(T_&&) { } }; template <typename T> test(T) -> test<T>; int main() { test t{42}; return 0; }
C++
CL
07a86550ed4ee79bea43d4f005694460f1613ca74111a7983187b4e1026b0a23
/************************************************************************* > File Name: knn_sign_classifier.cpp > Author: Guo Hengkai > Description: KNN sign classifier class implemenation using eigenface or fisherface features > Created Time: Sat 23 May 2015 10:51:47 PM CST ************************************************************************/ #include "knn_sign_classifier.h" #include "dataset.h" #include "extractor.h" #include "eigen_extractor.h" #include "fisher_extractor.h" #include "knn_classifier.h" #include "mat_util.h" #include "math_util.h" #include "file_util.h" #include "test_util.h" #include "timer.h" namespace ghk { KnnSignClassifier::KnnSignClassifier(bool use_fisher, int near_num, int eigen_feat_num, int img_size, bool use_threshold): use_fisher_(use_fisher), eigen_extractor_(eigen_feat_num), knn_classifier_(near_num), img_size_(img_size), threshold_(FLT_MAX), use_threshold_(use_threshold), neg_num_(2000) { if (use_fisher_) { extractor_ = &fisher_extractor_; } else { extractor_ = &eigen_extractor_; } } bool KnnSignClassifier::Save(const string &model_name) const { vector<float> param{Bool2Float(use_fisher_), static_cast<float>(img_size_), threshold_, Bool2Float(use_threshold_)}; if (!SaveMat(model_name + "_para", Mat(), param)) { printf("Fail to save the parameter.\n"); return false; } if (!extractor_->Save(model_name + "_ext")) { printf("Fail to save the extractor.\n"); return false; } if (!knn_classifier_.Save(model_name + "_c")) { printf("Fail to save the classifier.\n"); return false; } return true; } bool KnnSignClassifier::Load(const string &model_name) { vector<float> param; Mat tmp; if (!LoadMat(model_name + "_para", &tmp, &param)) { printf("Fail to load the parameter.\n"); return false; } use_fisher_ = Float2Bool(param[0]); img_size_ = param[1]; threshold_ = param[2]; use_threshold_ = Float2Bool(param[3]); if (use_fisher_) { extractor_ = &fisher_extractor_; } else { extractor_ = &eigen_extractor_; } if (!extractor_->Load(model_name + "_ext")) { printf("Fail to load the extractor.\n"); return false; } if (!knn_classifier_.Load(model_name + "_c")) { printf("Fail to load the classifier.\n"); return false; } return true; } bool KnnSignClassifier::Train(const Dataset &dataset) { // Get training data vector<Mat> images; vector<Mat> neg_images; vector<int> labels; size_t n = dataset.GetClassifyNum(true); Size img_size(img_size_, img_size_); printf("Preparing training data...\n"); for (size_t i = 0; i < n; ++i) { Mat image; dataset.GetClassifyImage(true, i, &image, img_size); cv::cvtColor(image, image, CV_BGR2GRAY); images.push_back(image); labels.push_back(dataset.GetClassifyLabel(true, i)); // Augment using rotation for (int j = 0; j < AUGMENT_TIMES; ++j) { Mat rot_img = image.clone(); RotateImage(rot_img, Random(AUGMENT_ROTATE * 2 + 1) - AUGMENT_ROTATE); images.push_back(rot_img); labels.push_back(labels[labels.size() - 1]); } } if (!use_threshold_) { // Find negative sample srand(time(NULL)); printf("Randomly getting negative samples...\n"); if (!dataset.GetRandomNegImage(neg_num_ / 5, img_size, &neg_images)) { printf("Fail to get negative samples.\n"); return false; } images.insert(images.end(), neg_images.begin(), neg_images.end()); // Negative labels vector<int> neg_labels(neg_images.size(), 0); labels.insert(labels.end(), neg_labels.begin(), neg_labels.end()); } Timer timer; // Train the extractor printf("Training extractor...\n"); timer.Start(); extractor_->Train(images, labels); float t1 = timer.Snapshot(); printf("Time for training extractor: %0.3fs\n", t1); // Feature extraction Mat feats; printf("Extracting features...\n"); extractor_->Extract(images, &feats); float t2 = timer.Snapshot(); printf("Time for extraction: %0.3fs\n", t2 - t1); // Train the KNN classifier printf("Training KNN classifier...\n"); knn_classifier_.Train(feats, labels); float t3 = timer.Snapshot(); printf("Time for training KNN: %0.3fs\n", t3 - t2); if (use_threshold_) { // Train the threshold printf("Training the threshold...\n"); if (!TrainThreshold(dataset)) { printf("Fail to train the threshold.\n"); return false; } } else { labels.erase(labels.begin() + neg_images.size(), labels.end()); feats.resize(labels.size()); } float t4 = timer.Snapshot(); printf("Training done! Total %0.3fs. Now testing...\n", t4); // Test on training vector<int> predict_labels; knn_classifier_.Predict(feats, &predict_labels); float rate, fp; EvaluateClassify(labels, predict_labels, CLASS_NUM, false, &rate, &fp); printf("Test on training rate: %0.2f%%\n", rate * 100); return true; } bool KnnSignClassifier::Test(const Dataset &dataset) { // Get test data vector<Mat> images; vector<int> labels; size_t n = dataset.GetClassifyNum(false); Size img_size(img_size_, img_size_); printf("Preparing testing data...\n"); for (size_t i = 0; i < n; ++i) { Mat image; dataset.GetClassifyImage(false, i, &image, img_size); cv::cvtColor(image, image, CV_BGR2GRAY); images.push_back(image); labels.push_back(dataset.GetClassifyLabel(false, i)); } // Test on test dataset vector<int> predict_labels; Predict(images, &predict_labels); float rate, fp; EvaluateClassify(labels, predict_labels, CLASS_NUM, true, &rate, &fp); printf("Test rate: %0.2f%%\n", rate * 100); return true; } bool KnnSignClassifier::Predict(const vector<Mat> &images, vector<int> *labels) { if (labels == nullptr) { return false; } Timer timer; // Feature extraction Mat feats; printf("Extracting features...\n"); timer.Start(); extractor_->Extract(images, &feats); float t1 = timer.Snapshot(); printf("Time for extraction: %0.3fs\n", t1); // Prediction vector<float> distance; printf("Predicting with KNN...\n"); knn_classifier_.Predict(feats, labels, &distance); float t2 = timer.Snapshot(); printf("Time for classification: %0.3fs\n", t2 - t1); if (use_threshold_) { for (size_t i = 0; i < distance.size(); ++i) { if (distance[i] > threshold_) { (*labels)[i] = 0; } } } float t3 = timer.Snapshot(); printf("Prediction done! Total time for %d images: %0.3fs\n", feats.rows, t3); return true; } bool KnnSignClassifier::FullTest(const Dataset &dataset, const string &dir) { // Backup parameters bool use_fisher_backup = use_fisher_; bool use_threshold_backup = use_threshold_; int img_size_backup = img_size_; // Get training data vector<Mat> images; vector<Mat> neg_images; vector<int> labels; size_t n = dataset.GetClassifyNum(true); Size img_size(img_size_, img_size_); printf("Preparing training data...\n"); Mat rotate_angle(n, AUGMENT_TIMES, CV_32F); for (size_t i = 0; i < n; ++i) { Mat image; dataset.GetClassifyImage(true, i, &image, img_size); cv::cvtColor(image, image, CV_BGR2GRAY); images.push_back(image); labels.push_back(dataset.GetClassifyLabel(true, i)); // Augment using rotation for (int j = 0; j < AUGMENT_TIMES; ++j) { Mat rot_img = image.clone(); rotate_angle.at<float>(i, j) = Random(AUGMENT_ROTATE * 2 + 1) - AUGMENT_ROTATE; RotateImage(rot_img, rotate_angle.at<float>(i, j)); images.push_back(rot_img); labels.push_back(labels[labels.size() - 1]); } } // Find negative sample srand(time(NULL)); printf("Randomly getting negative samples...\n"); if (!dataset.GetRandomNegImage(neg_num_ / 5, img_size, &neg_images)) { printf("Fail to get negative samples.\n"); return false; } vector<int> neg_labels(neg_images.size(), 0); // Get test data vector<Mat> test_images; vector<int> test_labels; size_t test_n = dataset.GetClassifyNum(false); printf("Preparing testing data...\n"); for (size_t i = 0; i < test_n; ++i) { Mat image; dataset.GetClassifyImage(false, i, &image, img_size); cv::cvtColor(image, image, CV_BGR2GRAY); test_images.push_back(image); test_labels.push_back(dataset.GetClassifyLabel(false, i)); } /* // Test of component number for eigen feature (best: 180) set_use_fisher(false); printf("Training for different component number with eigen...\n"); extractor_->Train(images, labels); Mat num_result_eigen(0, 4, CV_32F); const int step = 10; for (int i = step; i <= img_size_ * img_size_; i += step) { printf("%d, ", i); fflush(stdout); Mat feats; extractor_->set_feat_dim(i); extractor_->Extract(images, &feats); knn_classifier_.Train(feats, labels); Mat result_row(1, 4, CV_32F); vector<int> predict_labels; knn_classifier_.Predict(feats, &predict_labels); EvaluateClassify(labels, predict_labels, CLASS_NUM, false, &result_row.at<float>(0, 0), &result_row.at<float>(0, 1)); extractor_->Extract(test_images, &feats); knn_classifier_.Predict(feats, &predict_labels); EvaluateClassify(test_labels, predict_labels, CLASS_NUM, false, &result_row.at<float>(0, 2), &result_row.at<float>(0, 3)); num_result_eigen.push_back(result_row); } printf("\n"); printf("Done! Saving...\n"); SaveMat(dir + "/num_result_eigen", num_result_eigen); // Test of nearest neighbour number for eigen feature (best: 5) set_use_fisher(false); printf("Training for different neighbour number with eigen...\n"); extractor_->Train(images, labels); Mat feats; extractor_->Extract(images, &feats); Mat test_feats; extractor_->Extract(test_images, &test_feats); Mat nearest_result_eigen(0, 4, CV_32F); for (int i = 1; i < 102; i += 2) { printf("%d, ", i); fflush(stdout); knn_classifier_.set_near_num(i); knn_classifier_.Train(feats, labels); Mat result_row(1, 4, CV_32F); vector<int> predict_labels; knn_classifier_.Predict(feats, &predict_labels); EvaluateClassify(labels, predict_labels, CLASS_NUM, false, &result_row.at<float>(0, 0), &result_row.at<float>(0, 1)); knn_classifier_.Predict(test_feats, &predict_labels); EvaluateClassify(test_labels, predict_labels, CLASS_NUM, false, &result_row.at<float>(0, 2), &result_row.at<float>(0, 3)); nearest_result_eigen.push_back(result_row); } printf("\n"); printf("Done! Saving...\n"); SaveMat(dir + "/nearest_result_eigen", nearest_result_eigen); // Test of nearest neighbour number for fisher feature (best: 7) set_use_fisher(true); printf("Training for different neighbour number with fisher...\n"); extractor_->Train(images, labels); extractor_->Extract(images, &feats); extractor_->Extract(test_images, &test_feats); Mat nearest_result_fisher(0, 4, CV_32F); for (int i = 1; i < 102; i += 2) { printf("%d, ", i); fflush(stdout); knn_classifier_.set_near_num(i); knn_classifier_.Train(feats, labels); Mat result_row(1, 4, CV_32F); vector<int> predict_labels; knn_classifier_.Predict(feats, &predict_labels); EvaluateClassify(labels, predict_labels, CLASS_NUM, false, &result_row.at<float>(0, 0), &result_row.at<float>(0, 1)); knn_classifier_.Predict(test_feats, &predict_labels); EvaluateClassify(test_labels, predict_labels, CLASS_NUM, false, &result_row.at<float>(0, 2), &result_row.at<float>(0, 3)); nearest_result_fisher.push_back(result_row); } printf("\n"); printf("Done! Saving...\n"); SaveMat(dir + "/nearest_result_fisher", nearest_result_fisher); // Test of image size printf("Training for different image size..."); vector<Mat> size_train_img; vector<Mat> size_test_img; Mat size_result[2]; for (int size = 10; size <= 150; size += 10) { printf("%d, ", size); fflush(stdout); size_train_img.clear(); size_test_img.clear(); Size img_size(size, size); for (size_t i = 0; i < n; ++i) { Mat image; dataset.GetClassifyImage(true, i, &image, img_size); cv::cvtColor(image, image, CV_BGR2GRAY); size_train_img.push_back(image); // Augment using rotation for (int j = 0; j < AUGMENT_TIMES; ++j) { Mat rot_img = image.clone(); RotateImage(rot_img, rotate_angle.at<float>(i, j)); size_train_img.push_back(rot_img); } } for (size_t i = 0; i < test_n; ++i) { Mat image; dataset.GetClassifyImage(false, i, &image, img_size); cv::cvtColor(image, image, CV_BGR2GRAY); size_test_img.push_back(image); } Mat feats; Mat result_row(1, 4, CV_32F); vector<int> predict_labels; set_use_fisher(false); extractor_->Train(size_train_img, labels); extractor_->Extract(size_train_img, &feats); knn_classifier_.Train(feats, labels); knn_classifier_.Predict(feats, &predict_labels); EvaluateClassify(labels, predict_labels, CLASS_NUM, false, &result_row.at<float>(0, 0), &result_row.at<float>(0, 1)); extractor_->Extract(size_test_img, &feats); knn_classifier_.Predict(feats, &predict_labels); EvaluateClassify(test_labels, predict_labels, CLASS_NUM, false, &result_row.at<float>(0, 2), &result_row.at<float>(0, 3)); size_result[0].push_back(result_row); set_use_fisher(true); extractor_->Train(size_train_img, labels); extractor_->Extract(size_train_img, &feats); knn_classifier_.Train(feats, labels); knn_classifier_.Predict(feats, &predict_labels); EvaluateClassify(labels, predict_labels, CLASS_NUM, false, &result_row.at<float>(0, 0), &result_row.at<float>(0, 1)); extractor_->Extract(size_test_img, &feats); knn_classifier_.Predict(feats, &predict_labels); EvaluateClassify(test_labels, predict_labels, CLASS_NUM, false, &result_row.at<float>(0, 2), &result_row.at<float>(0, 3)); size_result[1].push_back(result_row); } printf("\n"); printf("Done! Saving...\n"); SaveMat(dir + "/size_result_eigen", size_result[0]); SaveMat(dir + "/size_result_fisher", size_result[1]); // Test of open-set methods for eigen feature using threshold Mat th_result_eigen(0, 4, CV_32F); printf("Training for different threshold with eigen...\n"); set_use_fisher(false); extractor_->Train(images, labels); extractor_->Extract(images, &feats); knn_classifier_.Train(feats, labels); Mat neg_feats; extractor_->Extract(neg_images, &neg_feats); vector<float> neg_distance; vector<int> neg_train_labels; knn_classifier_.Predict(neg_feats, &neg_train_labels, &neg_distance); float mean = 0, deviation = 0; for (auto dis: neg_distance) { mean += dis; deviation += dis * dis; } mean /= neg_distance.size(); deviation = sqrt(deviation / neg_distance.size() - mean * mean); extractor_->Extract(test_images, &test_feats); Mat result_row(1, 4, CV_32F); vector<int> predict_labels; vector<float> train_dis; knn_classifier_.Predict(feats, &predict_labels, &train_dis); EvaluateClassify(labels, predict_labels, CLASS_NUM, true, &result_row.at<float>(0, 0), &result_row.at<float>(0, 1)); vector<int> test_predict_labels; vector<float> test_dis; knn_classifier_.Predict(test_feats, &test_predict_labels, &test_dis); EvaluateClassify(test_labels, test_predict_labels, CLASS_NUM, true, &result_row.at<float>(0, 2), &result_row.at<float>(0, 3)); th_result_eigen.push_back(result_row); for (float rate = 0; rate <= 5; rate += 0.5) { printf("%0.1f, ", rate); fflush(stdout); threshold_ = mean + rate * deviation; vector<int> temp_labels; for (size_t i = 0; i < train_dis.size(); ++i) { if (train_dis[i] > threshold_) { temp_labels.push_back(0); } else { temp_labels.push_back(predict_labels[i]); } } EvaluateClassify(labels, temp_labels, CLASS_NUM, true, &result_row.at<float>(0, 0), &result_row.at<float>(0, 1)); temp_labels.clear(); for (size_t i = 0; i < test_dis.size(); ++i) { if (test_dis[i] > threshold_) { temp_labels.push_back(0); } else { temp_labels.push_back(test_predict_labels[i]); } } EvaluateClassify(test_labels, temp_labels, CLASS_NUM, true, &result_row.at<float>(0, 2), &result_row.at<float>(0, 3)); th_result_eigen.push_back(result_row); } printf("\n"); printf("Done! Saving...\n"); SaveMat(dir + "/th_result_eigen", th_result_eigen); // Test of open-set methods for fisher feature using threshold Mat th_result_fisher(0, 4, CV_32F); printf("Training for different threshold with fisher...\n"); set_use_fisher(true); extractor_->Train(images, labels); extractor_->Extract(images, &feats); knn_classifier_.Train(feats, labels); extractor_->Extract(neg_images, &neg_feats); knn_classifier_.Predict(neg_feats, &neg_train_labels, &neg_distance); mean = 0; deviation = 0; for (auto dis: neg_distance) { mean += dis; deviation += dis * dis; } mean /= neg_distance.size(); deviation = sqrt(deviation / neg_distance.size() - mean * mean); extractor_->Extract(test_images, &test_feats); knn_classifier_.Predict(feats, &predict_labels, &train_dis); EvaluateClassify(labels, predict_labels, CLASS_NUM, true, &result_row.at<float>(0, 0), &result_row.at<float>(0, 1)); knn_classifier_.Predict(test_feats, &test_predict_labels, &test_dis); EvaluateClassify(test_labels, test_predict_labels, CLASS_NUM, true, &result_row.at<float>(0, 2), &result_row.at<float>(0, 3)); th_result_fisher.push_back(result_row); for (float rate = 0; rate <= 5; rate += 0.5) { printf("%0.1f, ", rate); fflush(stdout); threshold_ = mean + rate * deviation; vector<int> temp_labels; for (size_t i = 0; i < train_dis.size(); ++i) { if (train_dis[i] > threshold_) { temp_labels.push_back(0); } else { temp_labels.push_back(predict_labels[i]); } } EvaluateClassify(labels, temp_labels, CLASS_NUM, true, &result_row.at<float>(0, 0), &result_row.at<float>(0, 1)); temp_labels.clear(); for (size_t i = 0; i < test_dis.size(); ++i) { if (test_dis[i] > threshold_) { temp_labels.push_back(0); } else { temp_labels.push_back(test_predict_labels[i]); } } EvaluateClassify(test_labels, temp_labels, CLASS_NUM, true, &result_row.at<float>(0, 2), &result_row.at<float>(0, 3)); th_result_fisher.push_back(result_row); } printf("\n"); printf("Done! Saving...\n"); SaveMat(dir + "/th_result_fisher", th_result_fisher); // Test of open-set methods for eigen feature using negative class images.insert(images.end(), neg_images.begin(), neg_images.end()); labels.insert(labels.end(), neg_labels.begin(), neg_labels.end()); printf("Training for negative class with eigen...\n"); set_use_fisher(false); extractor_->Train(images, labels); extractor_->Extract(images, &feats); knn_classifier_.Train(feats, labels); labels.erase(labels.begin() + neg_images.size(), labels.end()); feats.resize(labels.size()); extractor_->Extract(test_images, &test_feats); Mat neg_result_eigen(1, 4, CV_32F); knn_classifier_.Predict(feats, &predict_labels); EvaluateClassify(labels, predict_labels, CLASS_NUM, true, &neg_result_eigen.at<float>(0, 0), &neg_result_eigen.at<float>(0, 1)); knn_classifier_.Predict(test_feats, &test_predict_labels); EvaluateClassify(test_labels, test_predict_labels, CLASS_NUM, true, &neg_result_eigen.at<float>(0, 2), &neg_result_eigen.at<float>(0, 3)); printf("Done! Saving...\n"); SaveMat(dir + "/neg_result_eigen", neg_result_eigen); // Test of open-set methods for fisher feature using negative class images.insert(images.end(), neg_images.begin(), neg_images.end()); labels.insert(labels.end(), neg_labels.begin(), neg_labels.end()); printf("Training for negative class with fisher...\n"); set_use_fisher(true); extractor_->Train(images, labels); extractor_->Extract(images, &feats); knn_classifier_.Train(feats, labels); labels.erase(labels.begin() + neg_images.size(), labels.end()); feats.resize(labels.size()); extractor_->Extract(test_images, &test_feats); Mat neg_result_fisher(1, 4, CV_32F); knn_classifier_.Predict(feats, &predict_labels); EvaluateClassify(labels, predict_labels, CLASS_NUM, true, &neg_result_fisher.at<float>(0, 0), &neg_result_fisher.at<float>(0, 1)); knn_classifier_.Predict(test_feats, &test_predict_labels); EvaluateClassify(test_labels, test_predict_labels, CLASS_NUM, true, &neg_result_fisher.at<float>(0, 2), &neg_result_fisher.at<float>(0, 3)); printf("Done! Saving...\n"); SaveMat(dir + "/neg_result_fisher", neg_result_fisher); */ Mat feats, neg_feats, test_feats; vector<int> neg_train_labels, predict_labels, test_predict_labels; vector<float> neg_distance; float mean, deviation; vector<float> train_dis; vector<float> test_dis; // Best results for eigen feature Timer timer; timer.Start(); printf("Training for best result with eigen...\n"); set_use_fisher(false); knn_classifier_.set_near_num(5); extractor_->Train(images, labels); extractor_->Extract(images, &feats); knn_classifier_.Train(feats, labels); extractor_->Extract(neg_images, &neg_feats); knn_classifier_.Predict(neg_feats, &neg_train_labels, &neg_distance); mean = 0; deviation = 0; for (auto dis: neg_distance) { mean += dis; deviation += dis * dis; } mean /= neg_distance.size(); deviation = sqrt(deviation / neg_distance.size() - mean * mean); threshold_ = mean + 2.5 * deviation; float t1 = timer.Snapshot(); printf("Time for training PCA: %0.3fs\n", t1); extractor_->Extract(test_images, &test_feats); knn_classifier_.Predict(feats, &predict_labels, &train_dis); for (size_t i = 0; i < train_dis.size(); ++i) { if (train_dis[i] > threshold_) { predict_labels[i] = 0; } } Mat result_mat_train_eigen; vector<float> best_result_train_eigen(2, 0); EvaluateClassify(labels, predict_labels, CLASS_NUM, true, &best_result_train_eigen[0], &best_result_train_eigen[1], &result_mat_train_eigen); knn_classifier_.Predict(test_feats, &test_predict_labels, &test_dis); for (size_t i = 0; i < test_dis.size(); ++i) { if (test_dis[i] > threshold_) { test_predict_labels[i] = 0; } } Mat result_mat_test_eigen; vector<float> best_result_test_eigen(2, 0); EvaluateClassify(test_labels, test_predict_labels, CLASS_NUM, true, &best_result_test_eigen[0], &best_result_test_eigen[1], &result_mat_test_eigen); float t2 = timer.Snapshot(); printf("Time for testing PCA: %0.3fs\n", t2 - t1); printf("Done! Saving...\n"); SaveMat(dir + "/best_result_train_eigen", result_mat_train_eigen, best_result_train_eigen); SaveMat(dir + "/best_result_test_eigen", result_mat_test_eigen, best_result_test_eigen); // Best results for fisher feature t1 = timer.Snapshot(); printf("Training for best result with fisher...\n"); set_use_fisher(true); knn_classifier_.set_near_num(7); extractor_->Train(images, labels); extractor_->Extract(images, &feats); knn_classifier_.Train(feats, labels); extractor_->Extract(test_images, &test_feats); extractor_->Extract(neg_images, &neg_feats); knn_classifier_.Predict(neg_feats, &neg_train_labels, &neg_distance); mean = 0; deviation = 0; for (auto dis: neg_distance) { mean += dis; deviation += dis * dis; } mean /= neg_distance.size(); deviation = sqrt(deviation / neg_distance.size() - mean * mean); threshold_ = mean + 2.5 * deviation; t2 = timer.Snapshot(); printf("Time for training Fisher: %0.3fs\n", t2 - t1); knn_classifier_.Predict(feats, &predict_labels, &train_dis); for (size_t i = 0; i < train_dis.size(); ++i) { if (train_dis[i] > threshold_) { predict_labels[i] = 0; } } Mat result_mat_train_fisher; vector<float> best_result_train_fisher(2, 0); EvaluateClassify(labels, predict_labels, CLASS_NUM, true, &best_result_train_fisher[0], &best_result_train_fisher[1], &result_mat_train_fisher); knn_classifier_.Predict(test_feats, &test_predict_labels, &test_dis); for (size_t i = 0; i < test_dis.size(); ++i) { if (test_dis[i] > threshold_) { test_predict_labels[i] = 0; } } Mat result_mat_test_fisher; vector<float> best_result_test_fisher(2, 0); EvaluateClassify(test_labels, test_predict_labels, CLASS_NUM, true, &best_result_test_fisher[0], &best_result_test_fisher[1], &result_mat_test_fisher); t1 = timer.Snapshot(); printf("Time for testing Fisher: %0.3fs\n", t1 - t2); printf("Done! Saving...\n"); SaveMat(dir + "/best_result_train_fisher", result_mat_train_fisher, best_result_train_fisher); SaveMat(dir + "/best_result_test_fisher", result_mat_test_fisher, best_result_test_fisher); // Restore parameters set_use_fisher(use_fisher_backup); use_threshold_ = use_threshold_backup; img_size_ = img_size_backup; return true; } void KnnSignClassifier::set_use_fisher(bool use_fisher) { if (use_fisher != use_fisher_) { use_fisher_ = use_fisher; if (use_fisher_) { extractor_ = &fisher_extractor_; } else { extractor_ = &eigen_extractor_; } } } bool KnnSignClassifier::TrainThreshold(const Dataset &dataset) { srand(time(NULL)); vector<Mat> neg_images; Size img_size(img_size_, img_size_); printf("Randomly getting negative samples...\n"); if (!dataset.GetRandomNegImage(neg_num_, img_size, &neg_images)) { printf("Fail to get negative samples.\n"); return false; } Mat feats; printf("Extracting features...\n"); extractor_->Extract(neg_images, &feats); vector<float> distance; vector<int> labels; printf("Getting distance with KNN...\n"); knn_classifier_.Predict(feats, &labels, &distance); float mean = 0, deviation = 0; for (auto dis: distance) { mean += dis; deviation += dis * dis; } mean /= distance.size(); deviation = sqrt(deviation / distance.size() - mean * mean); printf("Mean: %0.4f, Std: %0.4f\n", mean, deviation); threshold_ = mean + 2 * deviation; return true; } } // namespace ghk
C++
CL
ba95647b6058049928357d17f65eb43fe47f18afd846e027a877df4f2bcb40f8
#ifndef RGBABUFFER_H #define RGBABUFFER_H #include "RGBAValue.h" // A rectangular buffer containing RGBAValues (float) for rendering the simulation as a texture class RGBABuffer { public: // the raw data RGBAValue<float> *block; // dimensions of the buffer unsigned int width, height; // constructor RGBABuffer(); // destructor ~RGBABuffer(); // resizes the image, destroying any contents void Resize(long Width, long Height); // indexing - retrieves the beginning of a line // array indexing will then retrieve an element RGBAValue<float> * operator [](const int rowIndex); // similar routine for const pointers const RGBAValue<float> * operator [](const int rowIndex) const; }; #endif
C++
CL
31e54934beccfaafd3dff5babf574ce689b939ad91c12c38003a755aaeaf09e9
#if defined( PLAT_PC ) || defined( PLAT_WINDOWS_PHONE ) || defined( PLAT_WINDOWS_8 ) || defined( PLAT_ANDROID ) ////////////////////////////////////////////////////// // INCLUDES ////////////////////////////////////////////////////// #include "common/engine/audio/format/ogginterface.hpp" #include "common/engine/database/database.hpp" #include "common/engine/system/assert.hpp" #include "common/engine/system/memory.hpp" #include "common/engine/system/pathutilities.hpp" #include "common/engine/system/stringutilities.hpp" #include "common/engine/system/utilities.hpp" ////////////////////////////////////////////////////// // CLASS METHODS ////////////////////////////////////////////////////// ////////////////////////////////////////////////////// // CLASS METHODS ////////////////////////////////////////////////////// namespace Audio { OggInterface::OggInterface() : mVorbisInfo( NULL ) , mOggVorbisFile( NULL ) , mFile( NULL ) { } //=========================================================================== OggInterface::~OggInterface() { Clear(); } //=========================================================================== void OggInterface::Clear() { if ( mOggVorbisFile != NULL ) { ov_clear( mOggVorbisFile ); } DELETE_PTR( mOggVorbisFile ); if ( mFile != NULL ) { fclose( mFile ); mFile = NULL; } mVorbisInfo = NULL; } //=========================================================================== OggVorbis_File* OggInterface::Load( const char* filename ) { Clear(); char fullPathFilename[256] = ""; const char* resourcePath = Database::Get()->GetResourcePath(); System::StringCopy( fullPathFilename, 256, resourcePath ); System::StringConcat( fullPathFilename, 256, System::Path::SystemSlash( filename ) ); System::StringConcat( fullPathFilename, 256, ".ogg" ); mFile = System::OpenFile( fullPathFilename, "rb" ); Assert( mFile != NULL, "" ); mOggVorbisFile = NEW_PTR( "Ogg Vorbis File" ) OggVorbis_File; ov_open( mFile, mOggVorbisFile, NULL, 0 ); mVorbisInfo = ov_info( mOggVorbisFile, -1 ); return mOggVorbisFile; } } #endif
C++
CL
392033c6136a48227032914464b2b5e2123d881ad534337d37250f1934dd02e0
/**************************************************************************/ /* Responsibility: */ /* - encapsulates the speech-signal-processing algorithms like */ /* - silence detection */ /* - speaker chage detection */ /* - ... */ /* */ /* Author : Thilo Stadelmann */ /* Date : 10.03.2004 */ /**************************************************************************/ #include "SC_Aux.h" #include "SC_Segmentation_Silence_LNK.h" //==================================================================================================================== // constructor //==================================================================================================================== SC_Segmentation_Silence_LNK::SC_Segmentation_Silence_LNK(SC_TweakableParameters* pTweak) : SC_Segmentation_Silence(pTweak) { } //==================================================================================================================== // destructor //==================================================================================================================== SC_Segmentation_Silence_LNK::~SC_Segmentation_Silence_LNK() { } //==================================================================================================================== // analyze the features of the given audio-segment and mark them as silence/non-silence in the ground truth // use energy (column 0) and zcr (column 1) per frame as the features // pFeatures must be an array of feature-sets as returned by the SC_FeatureHandler->extractFeatures() method (with // the log of the feature-set constants SCLIB_FEATURE_* as indices into the array) //==================================================================================================================== int SC_Segmentation_Silence_LNK::markSilence(SC_GroundTruth *pGT, unsigned long int segmentStart, unsigned long int segmentEnd, SV_Data **pFeatures) { if (pFeatures[sclib::bitPosition(sclib::featureSTE)] == NULL || pFeatures[sclib::bitPosition(sclib::featureSTE)]->Hdr.ID != sclib::featureSTE) { REPORT_ERROR(SVLIB_BadArg, "The LNK silence detector needs ShortTimeEnergy features to operate on!"); return SVLIB_Fail; } else { return ASD(pGT, segmentStart, segmentEnd, pFeatures[sclib::bitPosition(sclib::featureSTE)]); } } //==================================================================================================================== // Adaptive Silence Detector as described in the following paper: // 'Content-Based Movie Analysis And Indexing Based On AudioVisual Cues', Li, Narayanan, Kuo, 2002 (Draft) // // It works like this: // - assume that speech has a higher ernergy-level than background (noise, hopefully silence) // - take all audioframes of a segment, sort them in an array by their frame-energy (desc.) // - the lowest value indicates the lower bound of noise, the highest one the upper bound of speech energy // - the threshold to seperate both classes from each other lies somewhere between them // - quantize the values in energyQuantizationLevel classes // - take the sum of the average energys of the first and last 3 classes and the signal-to-noise-ratio to // compute threshold (the paper doesn't tell how exactly use theses components) // ATTENTION: here's a change to the proposed method: we take the threshold-function by Otsu (see below for // description) //==================================================================================================================== int SC_Segmentation_Silence_LNK::ASD(SC_GroundTruth *pGT, unsigned long int segmentStart, unsigned long int segmentEnd, SV_Data* pEnergy) { unsigned short int y; unsigned long int x, start, end, frameCount = pEnergy->Row; //frameCount = pGT->getAudioFrameCountInScene(segmentStart, segmentEnd, pEnergyZCR->Hdr.frameSize, pEnergyZCR->Hdr.frameStep); //TODO: test if this is equal to pEnergyZCR->Row (should be...) float maximum = 0.0, minimum = std::numeric_limits<float>::max(); float* averageEnergy = new float[pTweak->segmentationSilenceLnk.energyQuantizationLevel]; //average energy per class unsigned int thresholdClass, *quantiCount = new unsigned int[pTweak->segmentationSilenceLnk.energyQuantizationLevel]; //nr. of frames per class float silenceThreshold = 0; double prob; SV_Data* pFrames; //the pFrames-matrix has the following semantics: // pFrames->Mat[][0] => sample-nr of first sample in frame (casted to float) // pFrames->Mat[][1] => energy of this frame, as computed earlier // pFrames->Mat[][2] => nr. of class this frame is quantized to (casted to float) //remove all previous silence tags pGT->setSegment(segmentStart, segmentEnd, sclib::atSilence, false, sclib::noSpeaker, sclib::modeLabelAdd); //copy alle frames of this scene in an array, sort it by energy pFrames = new SV_Data(frameCount, 3); for (x = 0; x < frameCount; x++) { //'<' because the sceneEnd belong to the scene, but due to windowed analysis we loose one frame ?!? pFrames->Mat[x][0] = (float)(segmentStart + pGT->getConverter()->audioFrame2sample(x, pEnergy->Hdr.frameSize, pEnergy->Hdr.frameStep)); pFrames->Mat[x][1] = pEnergy->Mat[x][0]; if (pFrames->Mat[x][1] > maximum) {maximum = pFrames->Mat[x][1];} if (pFrames->Mat[x][1] < minimum) {minimum = pFrames->Mat[x][1];} } sclib::quickSort(pFrames->Mat, 0, frameCount-1, 3, 1); //parameter 3 doesn't mean the length of pFrames, but it's last element!!! //quantize the frames into pTweak->energyQuantizationLevel energy-classes, compute average of each class for (x = 0; x < pTweak->segmentationSilenceLnk.energyQuantizationLevel; x++) { averageEnergy[x] = 0.0; quantiCount[x] = 0; } for (x = 0; x < frameCount; x++) { for (y = 1; y <= pTweak->segmentationSilenceLnk.energyQuantizationLevel; y++) { if ((pFrames->Mat[x][1] >= minimum + (maximum-minimum)*(float)(y - 1)/(float)pTweak->segmentationSilenceLnk.energyQuantizationLevel) && (pFrames->Mat[x][1] < minimum + (maximum-minimum)*(float)y/(float)pTweak->segmentationSilenceLnk.energyQuantizationLevel)) { pFrames->Mat[x][2] = (float)y; averageEnergy[y-1] += pFrames->Mat[x][1]; quantiCount[y-1]++; } } } for (x = 0; x < pTweak->segmentationSilenceLnk.energyQuantizationLevel; x++) { averageEnergy[x] /= (quantiCount > 0) ? (float)(quantiCount[x]) : (float)(1.0); } //calculate the Threshold thresholdClass = otsuThreshold(pTweak->segmentationSilenceLnk.energyQuantizationLevel, quantiCount, frameCount); silenceThreshold = averageEnergy[thresholdClass]; if (silenceThreshold == 0.0) { for (x = thresholdClass-1; x >= 0; x--) { silenceThreshold = averageEnergy[x]; if (silenceThreshold > 0.0) { break; } } if (silenceThreshold == 0.0) { for (x = thresholdClass+1; x <= this->pTweak->segmentationSilenceLnk.energyQuantizationLevel; x++) { silenceThreshold = averageEnergy[x]; if (silenceThreshold > 0.0) { break; } } } } //mark silence for (x = 0; x < frameCount; x++) { start = (unsigned long)floor(pFrames->Mat[x][0]); end = (unsigned long)floor(pFrames->Mat[x][0]) + pEnergy->Hdr.frameSize - 1; if (pFrames->Mat[x][1] < silenceThreshold) { pGT->setSegment(start, end, sclib::atSilence); //co-occurence of speech/noise/silence must be prohibited... but the lnk-v/uv-detector is quite cloesely related to this //silence detector (it labels the more energetic parts of what is here called "silence" more correctly as unvoiced speech) //thus, it still needs the speech/non-speech labels maybe present, whereas in all other situations, they must be removed //the removal of co-occuring speech and silence is cared for in the silence2pause method if (this->pTweak->segmentationHandler.vUvDetectorMode != sclib::algorithm_vud_LNK) { pGT->setSegment(start, end, SC_GroundTruth::getNoiseRelatedTypes(), false, sclib::noSpeaker, sclib::modeLabelRemove); pGT->setSegment(start, end, SC_GroundTruth::getSpeechRelatedTypes(), false, sclib::noSpeaker, sclib::modeLabelRemove); } prob = 1.0 - (pFrames->Mat[x][1] / silenceThreshold); //pseudo-"probability" of this frame being silence } else { prob = (silenceThreshold / pFrames->Mat[x][1]); //pseudo-"probability" of this frame being silence (yes, NOT non-silence; probs shall always tell be for the label being positive...) } pGT->setProbability(start, end, sclib::atSilence, prob); } MFree_1D(averageEnergy); MFree_1D(quantiCount); MFree_0D(pFrames); return SVLIB_Ok; } //==================================================================================================================== // Method to find optimal threshold for separating classed data into 2 distinct classes by minimization of // inter-class variance (originally for binarising grey-scale-images), according to the following paper: // 'A threshold selection method from gray level', N.Otsu, 1979, IEEE Trans. Systems, Man and Cybernetics // // Meaning of parameters: // - classCount: total count of classes // - itemsPerClass: vector of length "classCount", containing count of items per class // - itemCount: total count of items // - return value: class providing the optimal threshold //==================================================================================================================== unsigned int SC_Segmentation_Silence_LNK::otsuThreshold(unsigned int classCount, unsigned int* itemsPerClass, unsigned long int itemCount) { unsigned int k, threshold = classCount / 2; //if everything goes wrong, still a meaningfull value will be returned double totalMean = 0.0, variance = 0.0, maxVariance = 0.0; double zerothCumuMoment = 0.0, firstCumuMoment = 0.0; for(k = 1; k <= classCount; k++) { totalMean += k * (itemsPerClass[k-1] / (double)itemCount); } for(k = 1; k <= classCount; k++) { zerothCumuMoment += itemsPerClass[k-1] / (double)itemCount; firstCumuMoment += k * itemsPerClass[k-1] / (double)itemCount; variance = (totalMean * zerothCumuMoment) - firstCumuMoment; variance *= variance; variance /= zerothCumuMoment * (1 - zerothCumuMoment) + std::numeric_limits<double>::epsilon(); if(variance > maxVariance) { maxVariance = variance; threshold = k; } } return threshold; } //==================================================================================================================== // Returns the width [in ms!!!] of the region in which the found segment-boundaries may lie for a given exact // position; this uncertainty region is due to frame-based anlysis and internal windowsizes, e.g. // Only the factors due to this specific algorithm are taken into account (factors regarding thr ground-truth class // are handled therein) //==================================================================================================================== unsigned long int SC_Segmentation_Silence_LNK::getUncertaintyRegionWidth(void) { unsigned long int width = 0; //factors due to frame-based analysis width += 2 * this->pTweak->featureSte.frameStep; return width; }
C++
CL
0be61e7591d0bc91b7aacc1c14439c1dd6c380b9421fe3a8dacf586eea66ae50
// Copyright (c) 2017 Computer Vision Center (CVC) at the Universitat Autonoma // de Barcelona (UAB). // // This work is licensed under the terms of the MIT license. // For a copy, see <https://opensource.org/licenses/MIT>. #ifndef LIBCARLA_INCLUDED_DISABLE_UE4_MACROS_HEADER # define LIBCARLA_INCLUDED_DISABLE_UE4_MACROS_HEADER #else # error disable-ue4-macros.h should only be included once! #endif // LIBCARLA_INCLUDED_DISABLE_UE4_MACROS_HEADER #pragma push_macro("check") #undef check #if defined(__clang__) # pragma clang diagnostic push # pragma clang diagnostic ignored "-Wmissing-braces" #endif #define LIBCARLA_INCLUDED_FROM_UE4 #ifndef BOOST_ERROR_CODE_HEADER_ONLY # define BOOST_ERROR_CODE_HEADER_ONLY #endif // BOOST_ERROR_CODE_HEADER_ONLY #ifndef BOOST_NO_EXCEPTIONS # define BOOST_NO_EXCEPTIONS #endif // BOOST_NO_EXCEPTIONS // Suppress clang warning. #if defined(__clang__) # ifndef __cpp_coroutines # define __cpp_coroutines 0 # endif // __cpp_coroutines #endif // defined(__clang__) namespace boost { static inline void throw_exception(const std::exception &e) { UE_LOG(LogCarla, Fatal, TEXT("Exception thrown on Boost libraries: %s"), UTF8_TO_TCHAR(e.what())); } } // namespace boost #pragma push_macro("TEXT") #undef TEXT
C++
CL
2b0e517ed20ad61ffabf10f44dbf0ddb57f9c24fc45c755d6c6122d7368d3961
#pragma once #include <memory> // for unique_ptr #include <mutex> // for scoped_lock #include <vector> // for vector #include "AudioTransform.h" // for AudioTransform #include "StreamInfo.h" // for StreamInfo #include "TransformConfig.h" // for TransformConfig namespace bell { class Gain : public bell::AudioTransform { private: float gainFactor = 1.0f; std::vector<int> channels; public: Gain(); ~Gain(){}; float gainDb = 0.0; void configure(std::vector<int> channels, float gainDB); std::unique_ptr<StreamInfo> process( std::unique_ptr<StreamInfo> data) override; void reconfigure() override { std::scoped_lock lock(this->accessMutex); float gain = config->getFloat("gain"); this->channels = config->getChannels(); if (gainDb == gain) { return; } this->configure(channels, gain); } }; } // namespace bell
C++
CL
309352d3f37da1a900231649437d3392371e96312e0a5f5ed0b001591ab74f42
#ifndef SHOWERRECOALGMODULAR_CXX #define SHOWERRECOALGMODULAR_CXX #include "ShowerRecoAlgModular.h" #include "LArUtil/Geometry.h" #include <iomanip> namespace showerreco { // initialize the various algorithms void ShowerRecoAlgModular::Initialize() { for (auto & module : _modules) { module->initialize(); _module_time_v.push_back(0.); _module_ctr_v.push_back(0); } return; } Shower_t ShowerRecoAlgModular::RecoOneShower(const ::protoshower::ProtoShower& proto_shower) { // Run over the shower reco modules: Shower_t result; // Make sure the result shower has the right size of all it's elements auto geom = larutil::Geometry::GetME(); int nPlanes = geom -> Nplanes(); result.fTotalEnergy_v.resize(nPlanes); result.fSigmaTotalEnergy_v.resize(nPlanes); result.fdEdx_v.resize(nPlanes); result.fdQdx_v.resize(nPlanes); result.fSigmadEdx_v.resize(nPlanes); result.fSigmadQdx_v.resize(nPlanes); result.fHitdQdx_v.resize(nPlanes); result.fShoweringLength.resize(nPlanes); // resizing Showering Length Vector result.fTotalMIPEnergy_v.resize(nPlanes); result.fSigmaTotalMIPEnergy_v.resize(nPlanes); result.fPlaneIsBad.resize(nPlanes); Shower_t localCopy = result; for (size_t n = 0; n < _modules.size(); n++) { _watch.Start(); try { _modules[n] -> do_reconstruction(proto_shower, result); } catch (ShowerRecoException e) { result.fPassedReconstruction = false; if (_debug) std::cout << e.what() << std::endl; return result; } _module_time_v[n] += _watch.RealTime(); _module_ctr_v[n] += 1; if (_debug && _verbose) { printChanges(localCopy, result, _modules[n]->name()); localCopy = result; } } // If things are this far, then set the flag to true for passing reco result.fPassedReconstruction = true; return result; } void ShowerRecoAlgModular::AddShowerRecoModule( ShowerRecoModuleBase * module) { _modules.push_back(module); } void ShowerRecoAlgModular::InsertShowerRecoModule(ShowerRecoModuleBase * module, unsigned int index) { if (_modules.size() > index) { _modules.insert(_modules.begin() + index, module); } else { std::cerr << "WARNING: Request to insert module at index " << index << " which is beyond the last index." << std::endl; } } void ShowerRecoAlgModular::InsertShowerRecoModule(ShowerRecoModuleBase * module, std::string name) { for (unsigned int index = 0; index < _modules.size(); index ++) { if (_modules.at(index)->name() == name) { _modules.insert(_modules.begin() + index, module); return; } } std::cerr << "WARNING: Request to insert module after non existing module \"" << name << "\"" << std::endl; } void ShowerRecoAlgModular::ReplaceShowerRecoModule( ShowerRecoModuleBase * module, unsigned int index) { if (_modules.size() > index) { _modules.at(index) = module; } else { std::cerr << "WARNING: Request to remove non existing module at index " << index << std::endl; } } void ShowerRecoAlgModular::ReplaceShowerRecoModule( ShowerRecoModuleBase * module, std::string name) { for (unsigned int index = 0; index < _modules.size(); index ++) { if (_modules.at(index)->name() == name) { _modules.at(index) = module; return; } } std::cerr << "WARNING: Request to remove non existing module \"" << name << "\"" << std::endl; } void ShowerRecoAlgModular::PrintModuleList() { std::cout << "Print the list of modules to run in Shower Reco Alg Modular:\n"; int i = 0; for (auto & module : _modules) { std::cout << "\t" << i << ") " << module -> name() << "\n"; i++; } } void ShowerRecoAlgModular::printChanges(const Shower_t & localCopy, const Shower_t result, std::string moduleName) { bool changed; // Look at each value of Shower_t and if it has changed, print out that change std::cout << "\nPrinting the list of changes made by module " << moduleName << std::endl; // Compare vectors by x/y/z/ values // Doing comparisons in the order of values in Shower_t // Cos Start: if (localCopy.fDCosStart.X() != result.fDCosStart.X() || localCopy.fDCosStart.Y() != result.fDCosStart.Y() || localCopy.fDCosStart.X() != result.fDCosStart.X() ) { std::cout << "\tfDCosStart has changed from (" << localCopy.fDCosStart.X() << ", " << localCopy.fDCosStart.Y() << ", " << localCopy.fDCosStart.Z() << ") to (" << result.fDCosStart.X() << ", " << result.fDCosStart.Y() << ", " << result.fDCosStart.Z() << ") " << std::endl; } // Sigma Cos Start: if (localCopy.fSigmaDCosStart.X() != result.fSigmaDCosStart.X() || localCopy.fSigmaDCosStart.Y() != result.fSigmaDCosStart.Y() || localCopy.fSigmaDCosStart.X() != result.fSigmaDCosStart.X() ) { std::cout << "\tfSigmaDCosStart has changed from (" << localCopy.fSigmaDCosStart.X() << ", " << localCopy.fSigmaDCosStart.Y() << ", " << localCopy.fSigmaDCosStart.Z() << ") to (" << result.fSigmaDCosStart.X() << ", " << result.fSigmaDCosStart.Y() << ", " << result.fSigmaDCosStart.Z() << ") " << std::endl; } // XYZ Start: if (localCopy.fXYZStart.X() != result.fXYZStart.X() || localCopy.fXYZStart.Y() != result.fXYZStart.Y() || localCopy.fXYZStart.X() != result.fXYZStart.X() ) { std::cout << "\tfXYZStart has changed from (" << localCopy.fXYZStart.X() << ", " << localCopy.fXYZStart.Y() << ", " << localCopy.fXYZStart.Z() << ") to (" << result.fXYZStart.X() << ", " << result.fXYZStart.Y() << ", " << result.fXYZStart.Z() << ") " << std::endl; } // Sigma XYZ Start if (localCopy.fSigmaXYZStart.X() != result.fSigmaXYZStart.X() || localCopy.fSigmaXYZStart.Y() != result.fSigmaXYZStart.Y() || localCopy.fSigmaXYZStart.X() != result.fSigmaXYZStart.X() ) { std::cout << "\tfSigmaXYZStart has changed from (" << localCopy.fSigmaXYZStart.X() << ", " << localCopy.fSigmaXYZStart.Y() << ", " << localCopy.fSigmaXYZStart.Z() << ") to (" << result.fSigmaXYZStart.X() << ", " << result.fSigmaXYZStart.Y() << ", " << result.fSigmaXYZStart.Z() << ") " << std::endl; } // Length if (localCopy.fLength != result.fLength) { std::cout << "\tfDCosStart has changed from " << localCopy.fLength << " to " << result.fLength << std::endl; } // BestdQdx if (localCopy.fBestdQdx != result.fBestdQdx) { std::cout << "\tfBestdQdx has changed from " << localCopy.fBestdQdx << " to " << result.fBestdQdx << std::endl; } // Opening Angle if (localCopy.fOpeningAngle != result.fOpeningAngle) { std::cout << "\tfDCosStart has changed from " << localCopy.fOpeningAngle << " to " << result.fOpeningAngle << std::endl; } // Since these should be length = nplanes, checking each plane for change // If changed, print out // Total Energy changed = false; if (localCopy.fTotalEnergy != result.fTotalEnergy) changed = true; if (changed) { std::cout << "\tfTotalEnergy has changed from " << localCopy.fTotalEnergy << " to " << result.fTotalEnergy << std::endl; } //Total Energy vector changed = false; for (unsigned int i = 0; i < localCopy.fTotalEnergy_v.size(); i++) { if (localCopy.fTotalEnergy_v[i] != result.fTotalEnergy_v[i]) { changed = true; break; } } if (changed) { std::cout << "\tfTotalEnergy_v has changed from ("; for (auto & val : localCopy.fTotalEnergy_v ) std::cout << val << " "; std::cout << ") to ("; for (auto & val : result.fTotalEnergy_v ) std::cout << val << " "; std::cout << ")" << std::endl; } // Sigma Total Energy changed = false; if (localCopy.fSigmaTotalEnergy != result.fSigmaTotalEnergy) changed = true; if (changed) { std::cout << "\tfSigmaTotalEnergy has changed from " << localCopy.fSigmaTotalEnergy << " to " << result.fSigmaTotalEnergy << std::endl; } // Sigma Total Energy vector changed = false; for (unsigned int i = 0; i < localCopy.fSigmaTotalEnergy_v.size(); i++) { if (localCopy.fSigmaTotalEnergy_v[i] != result.fSigmaTotalEnergy_v[i]) { changed = true; break; } } if (changed) { std::cout << "\tfSigmaTotalEnergy_v has changed from ("; for (auto & val : localCopy.fSigmaTotalEnergy_v ) std::cout << val << " "; std::cout << ") to ("; for (auto & val : result.fSigmaTotalEnergy_v ) std::cout << val << " "; std::cout << ")" << std::endl; } // dEdx changed = false; if (localCopy.fdEdx != result.fdEdx) changed = true; if (changed) { std::cout << "\tfdEdx has changed from " << localCopy.fdEdx << " to " << result.fdEdx << std::endl; } // dEdx_v changed = false; for (unsigned int i = 0; i < localCopy.fdEdx_v.size(); i++) { if (localCopy.fdEdx_v[i] != result.fdEdx_v[i]) { changed = true; break; } } if (changed) { std::cout << "\tfdEdx_v has changed from ("; for (auto & val : localCopy.fdEdx_v ) std::cout << val << " "; std::cout << ") to ("; for (auto & val : result.fdEdx_v ) std::cout << val << " "; std::cout << ")" << std::endl; } // dQdx changed = false; if (localCopy.fdQdx_v != result.fdQdx_v) changed = true; if (changed) { std::cout << "\tfdQdx has changed from" << localCopy.fdQdx << " to " << result.fdQdx << std::endl; } // dQdx_v changed = false; for (unsigned int i = 0; i < localCopy.fdQdx_v.size(); i++) { if (localCopy.fdQdx_v[i] != result.fdQdx_v[i]) { changed = true; break; } } if (changed) { std::cout << "\tfdQdx_v has changed from ("; for (auto & val : localCopy.fdQdx_v ) std::cout << val << " "; std::cout << ") to ("; for (auto & val : result.fdQdx_v ) std::cout << val << " "; std::cout << ")" << std::endl; } // HitdQdx_v changed = false; for (unsigned int i = 0; i < localCopy.fHitdQdx_v.size(); i++) { for (unsigned int j = 0; j < localCopy.fHitdQdx_v[i].size(); j++) { if (localCopy.fHitdQdx_v[i][j] != result.fHitdQdx_v[i][j]) { changed = true; break; } } } if (changed) { std::cout << "\tfHitdQdx_v has changed from ("; for (auto & val : localCopy.fHitdQdx_v ) for (auto & v : val) std::cout << v << " "; std::cout << ") to ("; for (auto & val : result.fHitdQdx_v ) for (auto & v : val )std::cout << v << " "; std::cout << ")" << std::endl; } // sigma dEdx changed = false; if (localCopy.fSigmadEdx != result.fSigmadEdx) changed = true; if (changed) { std::cout << "\tfSigmadEdx has changed from " << localCopy.fSigmadEdx << " to " << result.fSigmadEdx << std::endl; } // sigma dEdx_v changed = false; for (unsigned int i = 0; i < localCopy.fSigmadEdx_v.size(); i++) { if (localCopy.fSigmadEdx_v[i] != result.fSigmadEdx_v[i]) { changed = true; break; } } if (changed) { std::cout << "\tfSigmadEdx_v has changed from ("; for (auto & val : localCopy.fSigmadEdx_v ) std::cout << val << " "; std::cout << ") to ("; for (auto & val : result.fSigmadEdx_v ) std::cout << val << " "; std::cout << ")" << std::endl; } // sigma dQdx changed = false; if (localCopy.fSigmadQdx != result.fSigmadQdx) changed = true; if (changed) { std::cout << "\tfSigmadQdx has changed from " << localCopy.fSigmadQdx << " to " << result.fSigmadQdx << std::endl; } // sigma dQdx_v changed = false; for (unsigned int i = 0; i < localCopy.fSigmadQdx_v.size(); i++) { if (localCopy.fSigmadQdx_v[i] != result.fSigmadQdx_v[i]) { changed = true; break; } } if (changed) { std::cout << "\tfSigmadQdx_v has changed from ("; for (auto & val : localCopy.fSigmadQdx_v ) std::cout << val << " "; std::cout << ") to ("; for (auto & val : result.fSigmadQdx_v ) std::cout << val << " "; std::cout << ")" << std::endl; } // Total MIP Energy changed = false; for (unsigned int i = 0; i < localCopy.fTotalMIPEnergy_v.size(); i++) { if (localCopy.fTotalMIPEnergy_v[i] != result.fTotalMIPEnergy_v[i]) { changed = true; break; } } if (changed) { std::cout << "\tfTotalMIPEnergy has changed from ("; for (auto & val : localCopy.fTotalMIPEnergy_v ) std::cout << val << " "; std::cout << ") to ("; for (auto & val : result.fTotalMIPEnergy_v ) std::cout << val << " "; std::cout << ")" << std::endl; } // Sigma Total MIP Energy changed = false; for (unsigned int i = 0; i < localCopy.fSigmaTotalMIPEnergy_v.size(); i++) { if (localCopy.fSigmaTotalMIPEnergy_v[i] != result.fSigmaTotalMIPEnergy_v[i]) { changed = true; break; } } if (changed) { std::cout << "\tfSigmaTotalMIPEnergy has changed from ("; for (auto & val : localCopy.fSigmaTotalMIPEnergy_v ) std::cout << val << " "; std::cout << ") to ("; for (auto & val : result.fSigmaTotalMIPEnergy_v ) std::cout << val << " "; std::cout << ")" << std::endl; } if (localCopy.fBestPlane != result.fBestPlane) { std::cout << "\tfBestPlane has changed from " << localCopy.fBestPlane.Plane << " to " << result.fBestPlane.Plane << std::endl; } std::cout << std::endl; } // finalize function void ShowerRecoAlgModular::Finalize(TFile* fout) { // loop through algos and evaluate time-performance std::cout << std::endl << "=================== Time Report =====================" << std::endl; for (size_t n = 0; n < _modules.size(); n++) { double module_time = _module_time_v[n] / ((double)_module_ctr_v[n]); std::cout << std::setw(25) << _modules[n]->name() << "\t Algo Time: " << std::setw(10) << module_time * 1.e6 << " [us/proto_shower]" << "\t Proto-Showers Scanned: " << _module_ctr_v[n] << std::endl; } std::cout << "=====================================================" << std::endl << std::endl; // for each algorithm, get its tree and write it to output if (fout) { fout->cd(); for (auto & module : _modules) { auto tree = module->GetTree(); if (tree) { tree->Write(); } }// for each modular algo }// if output file exists return; } } // showerreco #endif
C++
CL
bd08d43234560d825db7be3d9526b87972a7ee0348932373cd1107ec7c39df3c
/* * Copyright (c) 2010, Georgia Tech Research Corporation * * Humanoid Robotics Lab Georgia Institute of Technology * Director: Mike Stilman http://www.golems.org * * 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 Georgia Tech Research Corporation nor * the names of its contributors may be used to endorse or * promote products derived from this software without specific * prior written permission. * * THIS SOFTWARE IS PROVIDED BY GEORGIA TECH RESEARCH CORPORATION ''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 GEORGIA * TECH RESEARCH CORPORATION 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. */ #ifndef GRIP_GRIPSLIDER_H #define GRIP_GRIPSLIDER_H #include <wx/wx.h> #include <string> using namespace std; DECLARE_EVENT_TYPE(wxEVT_GRIP_SLIDER_CHANGE, -1) class GRIPSlider : public wxPanel { public: GRIPSlider(){} GRIPSlider( wxBitmap bmp, double left, double right, int precision, double initialpos, int lineSize, int pageSize, wxWindow *parent, const wxWindowID id = -1, bool vertical = false, const wxPoint& pos = wxDefaultPosition, const wxSize& size = wxDefaultSize, long style = wxTAB_TRAVERSAL ); GRIPSlider( const char* name, double left, double right, int precision, double initialpos, int lineSize, int pageSize, wxWindow *parent, const wxWindowID id = -1, bool vertical = false, const wxPoint& pos = wxDefaultPosition, const wxSize& size = wxDefaultSize, long style = wxTAB_TRAVERSAL); virtual ~GRIPSlider(){} wxBoxSizer *sizer; wxSlider *track; wxStaticText *lText; wxTextCtrl *rText; wxStaticBitmap *bmpButton; //string name; double pos; double leftBound; double rightBound; double tickfrequency; int prec; void setRange(double left, double right); void setValue(double value, bool sendSignal = true); void updateValue(double value, bool sendSignal = true); void setPrecision(int precision); void OnScroll(wxScrollEvent &evt); void OnEnter(wxCommandEvent &evt); DECLARE_DYNAMIC_CLASS(GRIPSlider) DECLARE_EVENT_TABLE() }; #endif
C++
CL
d03069673087ef3746d1480d2a28a582ce83ba863b9ca7ee0b7f92ccf159d0d9
/* Copyright (c) Stanford University, The Regents of the University of * California, and others. * * All Rights Reserved. * * See Copyright-SimVascular.txt for additional details. * * 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. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A * PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER * OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include <sstream> #include <iostream> #include <ostream> #include <string> typedef std::string string; typedef std::ostream ostream; #include "vtkSmartPointer.h" #include "vtkStructuredPoints.h" #include "vtkImageData.h" #include "vtkPolyData.h" #include "sv3_ITKLset_Macros.h" #ifndef IMGINFO_H_ #define IMGINFO_H_ class ImgInfo { private: int extent[6]; double origin[3]; double spacing[3]; double m_MinValue; double m_MaxValue; public: cvSetMacro(MinValue,double); cvGetMacro(MinValue,double); cvSetMacro(MaxValue,double); cvGetMacro(MaxValue,double); ImgInfo() { m_MinValue = 0; m_MaxValue = 255; int extent[6] = {0,63,0,63,0,0}; double origin[3] = {0,0,0}; double spacing[3] = {1,1,1}; this->SetExtent(extent); this->SetOrigin(origin); this->SetSpacing(spacing); } virtual ~ImgInfo(){} ImgInfo(int extent[6],double origin[3], double spacing[3]) { m_MinValue = 0; m_MaxValue = 255; this->SetExtent(extent); this->SetOrigin(origin); this->SetSpacing(spacing); } ImgInfo(int vextent[6],double vorigin[3], double vspacing[3], double minValue,double maxValue) { m_MinValue = minValue; m_MaxValue = maxValue; this->SetExtent(extent); this->SetOrigin(origin); this->SetSpacing(spacing); } ImgInfo(vtkStructuredPoints* vtksp) { m_MinValue = vtksp->GetScalarTypeMin(); m_MaxValue = vtksp->GetScalarTypeMax(); int extent[6]; double spacing[3]; double origin[3]; vtksp->GetSpacing(spacing); vtksp->GetExtent(extent); vtksp->GetOrigin(origin); this->SetExtent(extent); this->SetOrigin(origin); this->SetSpacing(spacing); } //copy constructor ImgInfo(const ImgInfo& other) { m_MinValue = other.m_MinValue; m_MaxValue = other.m_MinValue; this->SetExtent(extent); this->SetOrigin(origin); this->SetSpacing(spacing); } void SetExtent(int vextent[6]) {for(int i = 0; i < 6;i++) this->extent[i] = vextent[i];} void GetExtent(int *dOut) { const int* extent = this->extent; for(int i = 0; i < 6;i++) dOut[i] = extent[i]; } int *GetExtent() { return this->extent; } void SetOrigin(double vorigin[3]) {for(int i = 0; i < 3; i++) this->origin[i] = vorigin[i];} void GetOrigin(double *dOut) { const double* origin = this->origin; for(int i = 0; i < 3;i++) dOut[i] = origin[i]; } double *GetOrigin() { return this->origin; } void SetSpacing(double vspacing[3]) {for(int i = 0; i < 3; i++) this->spacing[i] = vspacing[i];} void GetSpacing(double *dOut) { const double* spacing = this->spacing; for(int i = 0; i < 3;i++) dOut[i] = spacing[i]; } double *GetSpacing() { return this->spacing; } inline void Print(ostream& os) { os <<"Extent: {"; for(int i = 0;i<6;i++) os <<this->extent[i] << ", "; os <<"}" <<std::endl; os <<"Origin: {"; for(int i = 0;i<3;i++) os <<this->origin[i] << ", "; os <<"}" <<std::endl; os <<"Spacing: {"; for(int i = 0;i<3;i++) os <<this->spacing[i] << ", "; os <<"}" <<std::endl; os <<"MinValue: " << this->m_MinValue; os <<" MaxValue: " << this->m_MaxValue << std::endl; } }; #endif /* IMGINFO_H_ */
C++
CL
197d91e33dce46e2556a43cd5f572722f320d333a996252338c876d74f95cc99
// // compile with: // g++ threadex2.cpp -lpthread -o thread2 // run with: // .\thread2 // #include <stdio.h> #include <stdlib.h> #include <pthread.h> #include <time.h> #include <unistd.h> void *functionC(void *); // initialize mutex pthread_mutex_t mutex1 = PTHREAD_MUTEX_INITIALIZER; int counter = 0; int temp; int main() { int rc1, rc2; //declare the ids of thread 1 and thread 2 pthread_t thread1, thread2; // Create two independent threads each of which will execute functionC if( (rc1=pthread_create( &thread1, NULL, &functionC, NULL)) ) { printf("Thread creation failed: %d\n", rc1); } if( (rc2=pthread_create( &thread2, NULL, &functionC, NULL)) ) { printf("Thread creation failed: %d\n", rc2); } // Wait till threads are completed before main continues (notice however that threads do never return). pthread_join( thread1, NULL); pthread_join( thread2, NULL); exit(0); } void *functionC(void *) { while(1) { // lock mutex (try to see how the behaviour changes if the mutex is present or absent) pthread_mutex_lock( &mutex1 ); temp = counter; temp = temp + 1; // introduce a delay of one second to increase the probability of a preemption to occur sleep(1); counter=temp; // print counter value printf("Counter value: %d\n",counter); // unlock mutex (try to see how the behaviour changes if the mutex is present or absent) pthread_mutex_unlock( &mutex1 ); } } // OPTIONAL: try to define the mutex as a "recursive" (see the slides about the concept of a "recursive mutex"). Each // thread must call the lock function and the unlock function twice to test the mechanism.
C++
CL
45c928a344f92e98146e9c6e05b8c225a8a94e23352ed1dde149695d821a66d0
/************************************************************************************************/ /** * @file KsHardwareBufferManagerDX11.cpp * @brief バッファマネージャ * @author Tsukasa Kato * @date ----/--/-- * @since ----/--/-- * @version 1.0.0 */ /************************************************************************************************/ /*==============================================================================================*/ /* << インクルード >> */ /*==============================================================================================*/ #include "KsDevDX11/KsDevDX11PreCompile.h" #include "KsDevDX11/device/KsHardwareBufferManagerDX11.h" /*==============================================================================================*/ /* << 定義 >> */ /*==============================================================================================*/ /*==============================================================================================*/ /* << 宣言 >> */ /*==============================================================================================*/ /************************************************************************************************/ /* * コンストラクタ */ /************************************************************************************************/ KsHardwareBufferManagerDX11::KsHardwareBufferManagerDX11( KsRenderSystemDX11* _RenderSystem ) : m_RenderSystem( _RenderSystem ) { } /************************************************************************************************/ /* * デストラクタ */ /************************************************************************************************/ KsHardwareBufferManagerDX11::~KsHardwareBufferManagerDX11() { } /************************************************************************************************/ /* * 頂点バッファを生成する * @param vertexSize 頂点サイズ * @param numVertex 頂点数 * @param vertexFormat 頂点フォーマット * @param flags フラグ * @return 頂点バッファのポインタ */ /************************************************************************************************/ KsVertexBuffer* KsHardwareBufferManagerDX11::createVertexBuffer( KsUInt32 vertexSize, KsUInt32 numVertex, KsUInt32 vertexFormat, KsUInt32 flags ) { return new KsVertexBufferDX11( m_RenderSystem, NULL, vertexSize, numVertex, vertexFormat, flags ); } /************************************************************************************************/ /* * 頂点バッファを生成する * @param vertexSize 頂点サイズ * @param numVertex 頂点数 * @param vertexFormat 頂点フォーマット * @param flags フラグ * @return 頂点バッファのポインタ */ /************************************************************************************************/ KsVertexBuffer* KsHardwareBufferManagerDX11::createVertexBuffer( void* pData, KsUInt32 vertexSize, KsUInt32 numVertex, KsUInt32 vertexFormat, KsUInt32 flags ) { return new KsVertexBufferDX11( m_RenderSystem, pData, vertexSize, numVertex, vertexFormat, flags ); } /************************************************************************************************/ /* * インデックスバッファを生成する * @param numIndex インデックス数 * @param flags フラグ * @return インデックスバッファのポインタ */ /************************************************************************************************/ KsIndexBuffer* KsHardwareBufferManagerDX11::createIndexBuffer( KsUInt32 numIndex, KsUInt32 indexFormat, KsUInt32 flags ) { return new KsIndexBufferDX11( m_RenderSystem, NULL, 0, numIndex, indexFormat, flags ); } /************************************************************************************************/ /* * インデックスバッファを生成する * @param numIndex インデックス数 * @param flags フラグ * @return インデックスバッファのポインタ */ /************************************************************************************************/ KsIndexBuffer* KsHardwareBufferManagerDX11::createIndexBuffer( void* pData, KsUInt32 size, KsUInt32 numIndex, KsUInt32 indexFormat, KsUInt32 flags ) { return new KsIndexBufferDX11( m_RenderSystem, pData, size, numIndex, indexFormat, flags ); } /************************************************************************************************/ /* * 定数バッファを生成する * @param pData [in] データ読み込み用のポインタ * @param size [in] データサイズ * @param flags [in] フラグ * @return 定数バッファのポインタ */ /************************************************************************************************/ KsConstantBuffer* KsHardwareBufferManagerDX11::createConstantBuffer( KsUInt32 size, KsUInt32 flags ) { return new KsConstantBufferDX11( m_RenderSystem, NULL, size, flags ); } /************************************************************************************************/ /* * 定数バッファを生成する * @param size [in] バッファサイズ * @param flags [in] フラグ * @return 定数バッファのポインタ */ /************************************************************************************************/ KsConstantBuffer* KsHardwareBufferManagerDX11::createConstantBuffer( void* pData, KsUInt32 size, KsUInt32 flags ) { return new KsConstantBufferDX11( m_RenderSystem, pData, size, flags ); }
C++
CL
fc266c6c53e38dcada487ddbcdff39d1990b690298191bba8e759a19ba754f8f
#pragma once #include <iostream> using namespace std; /* free list NODE */ class Node { public: Node* next; size_t addr; Node(size_t addr); void operator delete(void* ptr); void* operator new(size_t size); }; /* free list */ class LinkedList { public: /* Contractor Distractor. */ LinkedList(size_t memoryBlock); ~LinkedList(); /* Add new node with this addr to linked list. */ void add(size_t addr); /* Return size of lisr */ const size_t& getSize() const; /* Remove first element from linked list */ int removeFirst(); /* Function accepts a parameter if it finds sequence of addresses of length x , it deletes the sequence and returns the first address. */ int removeSequenceIfExist(size_t LengthOfTheSequence); /* Function accepts a index start of secuence and numeber of bits and add sequence of nodes */ void addSequenceIfExist(size_t index, size_t bits); /* getters */ const size_t& getMemoryBlock() const; /* return head of list */ Node* getHead() const; bool removeByAddr(size_t addr); /* ovverided operator new and delete */ void operator delete(void* ptr); void* operator new(size_t size); private: Node* head; size_t listSize; size_t memoryBlock; void deleteList(); };
C++
CL
1dfe6cd7bdae3fc8824ad5c58b822de4627a27d1ca85435cfbcc5065df1efc0a
/* The MIT License (MIT) Copyright (c) 2016 Vasil Kalchev Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /** @file printme helper function*/ #include "LiquidMenu.h" void print_me(uintptr_t address) { DEBUG(F("Line (0x")); DEBUG2(address, OCT); DEBUG(F("): ")); return; address = address; } uint8_t * rotTile(const uint8_t * tile) { uint8_t * newt = new uint8_t[8]; for (int x = 0; x < 8; x++) { uint8_t newb = 0; for (int y = 0 ; y < 8; y++){ newb |= (tile[y] << x) & 0x80; newb >>= 1; } newt[x] = newb; } return newt; }
C++
CL
f8d2ce6ecb97818d5665d96c3567f817038c0174df3d11d633c54de811ff708e
#pragma once // Name: Torchlight3, Version: 4.26.1 /*!!DEFINE!!*/ /*!!HELPER_DEF!!*/ /*!!HELPER_INC!!*/ #ifdef _MSC_VER #pragma pack(push, 0x01) #endif namespace CG { //--------------------------------------------------------------------------- // Classes //--------------------------------------------------------------------------- // WidgetBlueprintGeneratedClass LegendaryAffixCollectionItem.LegendaryAffixCollectionItem_C // 0x00A1 (FullSize[0x0939] - InheritedSize[0x0898]) class ULegendaryAffixCollectionItem_C : public ULegendaryAffixCollectionItemWidget { public: struct FPointerToUberGraphFrame UberGraphFrame; // 0x0898(0x0008) (ZeroConstructor, Transient, DuplicateTransient) class UTLImage* ActiveInSlot; // 0x08A0(0x0008) (BlueprintVisible, ExportObject, ZeroConstructor, InstancedReference, IsPlainOldData, RepSkip, NoDestructor, PersistentInstance, HasGetValueTypeHash) class UAffixListWidget* Affixes; // 0x08A8(0x0008) (BlueprintVisible, ExportObject, ZeroConstructor, InstancedReference, IsPlainOldData, RepSkip, NoDestructor, PersistentInstance, HasGetValueTypeHash) class UTLBorderHighlightable* Border; // 0x08B0(0x0008) (BlueprintVisible, ExportObject, ZeroConstructor, InstancedReference, IsPlainOldData, RepSkip, NoDestructor, PersistentInstance, HasGetValueTypeHash) class UNamedSlot* BottomSlot; // 0x08B8(0x0008) (BlueprintVisible, ExportObject, ZeroConstructor, InstancedReference, IsPlainOldData, RepSkip, NoDestructor, PersistentInstance, HasGetValueTypeHash) class UTLButton* Button; // 0x08C0(0x0008) (BlueprintVisible, ExportObject, ZeroConstructor, InstancedReference, IsPlainOldData, RepSkip, NoDestructor, PersistentInstance, HasGetValueTypeHash) class UTLTextBlock* ClassRequirement; // 0x08C8(0x0008) (BlueprintVisible, ExportObject, ZeroConstructor, InstancedReference, IsPlainOldData, RepSkip, NoDestructor, PersistentInstance, HasGetValueTypeHash) class UOverlay* Container; // 0x08D0(0x0008) (BlueprintVisible, ExportObject, ZeroConstructor, InstancedReference, IsPlainOldData, RepSkip, NoDestructor, PersistentInstance, HasGetValueTypeHash) class UVerticalBox* Contents; // 0x08D8(0x0008) (BlueprintVisible, ExportObject, ZeroConstructor, InstancedReference, IsPlainOldData, RepSkip, NoDestructor, PersistentInstance, HasGetValueTypeHash) class UTLBorder* Dimmer; // 0x08E0(0x0008) (BlueprintVisible, ExportObject, ZeroConstructor, InstancedReference, IsPlainOldData, RepSkip, NoDestructor, PersistentInstance, HasGetValueTypeHash) class UTLImage* EquippedArmor; // 0x08E8(0x0008) (BlueprintVisible, ExportObject, ZeroConstructor, InstancedReference, IsPlainOldData, RepSkip, NoDestructor, PersistentInstance, HasGetValueTypeHash) class UTLImage* EquippedPet; // 0x08F0(0x0008) (BlueprintVisible, ExportObject, ZeroConstructor, InstancedReference, IsPlainOldData, RepSkip, NoDestructor, PersistentInstance, HasGetValueTypeHash) class UTLWidgetSwitcher* EquippedStatusSwitcher; // 0x08F8(0x0008) (BlueprintVisible, ExportObject, ZeroConstructor, InstancedReference, IsPlainOldData, RepSkip, NoDestructor, PersistentInstance, HasGetValueTypeHash) class UTLImage* EquippedWeapon; // 0x0900(0x0008) (BlueprintVisible, ExportObject, ZeroConstructor, InstancedReference, IsPlainOldData, RepSkip, NoDestructor, PersistentInstance, HasGetValueTypeHash) class UTLImage* InSlotArmor; // 0x0908(0x0008) (BlueprintVisible, ExportObject, ZeroConstructor, InstancedReference, IsPlainOldData, RepSkip, NoDestructor, PersistentInstance, HasGetValueTypeHash) class UTLImage* InSlotPet; // 0x0910(0x0008) (BlueprintVisible, ExportObject, ZeroConstructor, InstancedReference, IsPlainOldData, RepSkip, NoDestructor, PersistentInstance, HasGetValueTypeHash) class UTLImage* InSlotWeapon; // 0x0918(0x0008) (BlueprintVisible, ExportObject, ZeroConstructor, InstancedReference, IsPlainOldData, RepSkip, NoDestructor, PersistentInstance, HasGetValueTypeHash) class UInventoryItemIcon_C* InventoryItemIcon; // 0x0920(0x0008) (BlueprintVisible, ExportObject, ZeroConstructor, InstancedReference, IsPlainOldData, RepSkip, NoDestructor, PersistentInstance, HasGetValueTypeHash) class UTLTextBlock* ItemName; // 0x0928(0x0008) (BlueprintVisible, ExportObject, ZeroConstructor, InstancedReference, IsPlainOldData, RepSkip, NoDestructor, PersistentInstance, HasGetValueTypeHash) class UNewFlag_C* NewFlag; // 0x0930(0x0008) (BlueprintVisible, ExportObject, ZeroConstructor, InstancedReference, IsPlainOldData, RepSkip, NoDestructor, PersistentInstance, HasGetValueTypeHash) bool ShowBorder; // 0x0938(0x0001) (Edit, BlueprintVisible, ZeroConstructor, IsPlainOldData, NoDestructor) static UClass* StaticClass() { static auto ptr = UObject::FindClass("WidgetBlueprintGeneratedClass LegendaryAffixCollectionItem.LegendaryAffixCollectionItem_C"); return ptr; } class UAffixListWidget* GetAffixListWidget(); class UInventoryItemBaseWidget* GetItemWidget(); void PreConstruct(bool IsDesignTime); void BlueprintSetup(const struct FItemData& InItemData); void BndEvt__Button_K2Node_ComponentBoundEvent_0_OnButtonClickedEvent__DelegateSignature(); void ExecuteUbergraph_LegendaryAffixCollectionItem(int EntryPoint); }; } #ifdef _MSC_VER #pragma pack(pop) #endif
C++
CL
ba8a37f5f30b7cb28b5f4b892b733b3c385d879f1b2d72e607bf1c6cf615cb69
// Copyright (c) 2015, 2016 Volodymyr Syvochka #include "JsonParser.h" #include "Core/Json/Rjson.h" #include "Core/Memory/TempAllocator.h" #include "Core/Strings/StringUtils.h" #include "Core/FileSystem/File.h" namespace Rio { JsonParser::JsonParser(const char* s) : jsonDocument(s) { RIO_ASSERT_NOT_NULL(s); } JsonParser::JsonParser(File& f) : isFromFile(true) { const size_t size = f.getFileSize() + 1; // for ending zero symbol char* doc = (char*)getDefaultAllocator().allocate(size); f.read(doc, size - 1); // add ending zero doc[size - 1] = '\0'; jsonDocument = doc; } JsonParser::~JsonParser() { if (isFromFile == true) { getDefaultAllocator().deallocate((void*)jsonDocument); } } JsonElement JsonParser::getJsonRoot() { const char* ch = jsonDocument; while ((*ch) && (*ch) <= ' ') { ch++; } return JsonElement(ch); } } // namespace Rio
C++
CL
0ddd957c2d50df5695c3e7c35b643e9c9f45f4b9d474868193d11141eea1fc01
// Authors: // James Walker jwwalker at mtu dot edu // Scott A. Kuhl kuhl at mtu dot edu #include <math.h> #include <string.h> #include <stdlib.h> #include <arpa/inet.h> #include <netinet/in.h> #include <stdio.h> #include <sys/types.h> #include <sys/socket.h> #include <unistd.h> #include <time.h> #include <math.h> #include <pthread.h> #include <string> #include <vector> #define RELAY_LISTEN_PORT 25885 #define SLAVE_LISTEN_PORT 25884 #define BUFLEN 512 char *RELAY_OUT_IP = NULL; // network data int s_R, milliseconds; struct timespec req; pthread_t receiverThread; int so_broadcast = 1; struct sockaddr_in si_me_R, si_other_R; socklen_t slen_R; std::vector<int> s_S; std::vector<struct sockaddr_in> si_other_S; socklen_t slen_S; bool receivedPacket = false; int framesPassed = 0; // state data -- ADD YOUR STATE PARAMETERS THAT NEED TO BE PASSED FROM MASTER TO SLAVE HERE. float rotation; // Exit with error message void error(const char *msg) { perror(msg); exit(1); } void closeProgram() { exit(0); } // Register a callback that is called when the program exits so we can be // sure to close the ports we're using. void exitCallback() { close(s_R); for(int i = 0; i < s_S.size(); i++){ close(s_S[i]); } } // This function receives incoming packets, repackages them, and then forwards them // on the network for consumption by the slaves. It does this in an infinite loop. void * receiver(void *) { char buf[BUFLEN]; std::vector<std::string> splits; while (true) { // receive data if (recvfrom(s_R, buf, BUFLEN, 0, (struct sockaddr*)&si_other_R, &slen_R) == -1) error("ERROR recvfrom()"); receivedPacket = true; framesPassed = 0; for(int i = 0; i < s_S.size(); i++){ if (sendto(s_S[i], buf, BUFLEN, 0, (struct sockaddr*)&si_other_S[i], slen_S) == -1) error ("ERROR sendto()"); } } } // MAIN FUNCTION int main(int argc, char **argv) { if (argc < 2) { printf("USAGE: %s ip-to-send-to\n", argv[0]); return 1; } RELAY_OUT_IP=argv[1]; if (argc > 2) { for(int i = 2; i < argc; i++){ // master init struct sockaddr_in _si_other_S; int _s_S; slen_S=sizeof(_si_other_S); if ((_s_S=socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP)) == -1) error("ERROR socket"); //printf("%i--%s--%d--\n",i,argv[i],_s_S); setsockopt(_s_S, SOL_SOCKET, SO_BROADCAST, &so_broadcast, sizeof(so_broadcast)); memset((char *) &_si_other_S, 0, sizeof(_si_other_S)); _si_other_S.sin_family = AF_INET; _si_other_S.sin_port = htons(atoi(argv[i])); if (inet_aton(RELAY_OUT_IP, &_si_other_S.sin_addr) == 0) { fprintf(stderr, "inet_aton() failed\n"); exit(1); } s_S.push_back(_s_S); si_other_S.push_back(_si_other_S); } } else{ struct sockaddr_in _si_other_S; int _s_S; slen_S=sizeof(_si_other_S); if ((_s_S=socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP)) == -1) error("ERROR socket"); printf("--%d--\n",_s_S); setsockopt(_s_S, SOL_SOCKET, SO_BROADCAST, &so_broadcast, sizeof(so_broadcast)); memset((char *) &_si_other_S, 0, sizeof(_si_other_S)); _si_other_S.sin_family = AF_INET; _si_other_S.sin_port = htons(SLAVE_LISTEN_PORT); if (inet_aton(RELAY_OUT_IP, &_si_other_S.sin_addr) == 0) { fprintf(stderr, "inet_aton() failed\n"); exit(1); } s_S.push_back(_s_S); si_other_S.push_back(_si_other_S); } milliseconds = 16; req.tv_sec = 0; req.tv_nsec = milliseconds * 1000000L; // socket stuff slen_R=sizeof(si_other_R); if ((s_R=socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP)) == -1) error("ERROR socket"); memset((char *) &si_me_R, 0, sizeof(si_me_R)); si_me_R.sin_family = AF_INET; si_me_R.sin_port = htons(RELAY_LISTEN_PORT); si_me_R.sin_addr.s_addr = htonl(INADDR_ANY); int _bind_result = bind(s_R, (struct sockaddr*)&si_me_R, sizeof(si_me_R)); if ( _bind_result == -1) error("ERROR bind"); // listen for updates if (pthread_create(&receiverThread, NULL, &receiver, NULL) != 0) { perror("Can't start thread, terminating"); return 1; } printf("Relay initialization complete\n"); while (true) { usleep(1000000); // The relay automatically shuts itself off if it hasn't received any packets // within a certain time period (>3 seconds if it has already received a packet, // >15 seconds if it hasn't received any packets yet). framesPassed++; if (receivedPacket) { if (framesPassed > 3) exit(EXIT_SUCCESS); } else { if (framesPassed > 15) exit(EXIT_SUCCESS); } } }
C++
CL
187bbcd3149d54c556e27b7ab7f48d01b9da56d292bd62804624d25daf1cf0f3
#pragma once #include "Enemy.h" #include "../SGD Wrappers/SGD_Geometry.h" #include "../SGD Wrappers/SGD_Listener.h" #include "../SGD Wrappers/SGD_Event.h" #include "TimeStamp.h" #include <vector> class Player; class GluttonyGreed : public Enemy, SGD::Listener { private: AIState m_myState = AI_PATROL; float m_StateTimer = 0.0f; std::vector<SGD::Point> m_Waypoints; unsigned int m_currPoint = 0; SGD::Point m_myCurrentway; int m_stolenDAQ = 0; float m_IdleTimer = 3.0f; int m_moneyCount = 0; float m_RushTimer = 3.0f; bool m_setPath = true; Entity* m_Pizza = nullptr; int pizzaCount = 0; float m_HitTimer = 3.0f; int speed; //TimeStamp m_Attacking; TimeStamp m_Tired; TimeStamp m_Run; bool left = true; bool attack = false; bool run = false; bool tired = true; public: GluttonyGreed(); ~GluttonyGreed(); virtual void HandleCollision(const IEntity* pOther) override; virtual void Update(float elapsedTime) override; virtual void Render(void) override; void UpdatePatrol(float elapsedTime); void UpdateAttack(float elapsedTime); //void UpdateAlert(float elapsedTime); void UpdateIdle(float elapsedTime); void SetPizza(Entity* newPizza); void SetMyState(AIState newState) { m_myState = newState; } void SetCurrentPoint(unsigned int newpoint) { m_currPoint = newpoint; } virtual int GetType(void) const override { return ENT_BOSS; } AIState GetMyState()const { return m_myState; } void SetRunAnin(TimeStamp run) { m_Run = run; } //void SetAttackAnin(TimeStamp att) { m_Attacking = att; } void SetTiredAnin(TimeStamp tired) { m_Tired = tired; } void SetPath(bool isPath) { m_setPath = isPath; } //virtual SGD::Rectangle GetRect(void) const override; void AddWayPoint(SGD::Point newPoint){ m_Waypoints.push_back(newPoint); } virtual void HandleEvent(const SGD::Event* pEvent) override; };
C++
CL
597a4920ea8caf84dcaca09cf193da52d140f8d727be751145985b56b355dd99
#include <fstream> // ROOT #include "TMath.h" // Gaudi #include "GaudiKernel/PhysicalConstants.h" #include "GaudiUtils/HistoLabels.h" // Tb/TbKernel #include "TbKernel/TbConstants.h" #include "TbKernel/TbModule.h" // Local #include "TbEffPur.h" using namespace Gaudi::Utils::Histos; DECLARE_ALGORITHM_FACTORY(TbEffPur) //============================================================================= // Standard constructor //============================================================================= TbEffPur::TbEffPur(const std::string& name, ISvcLocator* pSvcLocator) : TbAlgorithm(name, pSvcLocator), m_pitch(0.055), m_nDUTpixels(256), m_nTracks(0), m_nClusters(0), m_nTrackedClusters(0), m_nClustersPassedCentral(0), m_nTracksCentral(0), m_nClustersPassedCorner(0), m_nTracksCorner(0), m_eff(0.), m_pur(0.), m_deadAreaRadius(2.), m_trackAssociated(NULL) { declareProperty("TrackLocation", m_trackLocation = LHCb::TbTrackLocation::Default); declareProperty("VertexLocation", m_vertexLocation = LHCb::TbVertexLocation::Default); declareProperty("ClusterLocation", m_clusterLocation = LHCb::TbClusterLocation::Default); // Parameters. declareProperty("DUTindex", m_DUTindex = 4); declareProperty("GlobalCutXLow", m_xLow = 3); declareProperty("GlobalCutXUp", m_xUp = 9); declareProperty("GlobalCutYLow", m_yLow = 3); declareProperty("GlobalCutYUp", m_yUp = 9); declareProperty("LocalProbabilityCut", m_probCut = 0.5); declareProperty("RResidualCut", m_rResidualCut = 0.1); declareProperty("TResidualCut", m_tResidualCut = 100); declareProperty("ChargeCutLow", m_chargeCutLow = 0); // ... note this global cut enforced at different point to above. declareProperty("ChargeCutUp", m_chargeCutUp = 1000000); declareProperty("LitSquareSide", m_litSquareSide = 0); declareProperty("ViewerOutput", m_viewerOutput = false); declareProperty("ViewerEventNum", m_viewerEvent = 100); declareProperty("TGap", m_tGap = 200); declareProperty("CorrelationTimeWindow", m_correlationTimeWindow = 100); declareProperty("ApplyVeto", m_applyVeto = true); declareProperty("TelescopeClusterVetoDelT", m_telescopeClusterVetoDelT = 30); declareProperty("EdgeVetoDistance", m_edgeVetoDistance = 0.025); m_nEvent = -1; } //============================================================================= // Initialization //============================================================================= StatusCode TbEffPur::initialize() { // Initialise the base class. StatusCode sc = TbAlgorithm::initialize(); if (sc.isFailure()) return sc; // Efficiency objects. m_effX = new TEfficiency("efficiencyX", "efficiencyX", 40, 0.0, 0.11); m_effY = new TEfficiency("efficiencyY", "efficiencyY", 40, 0.0, 0.11); m_effs = new TEfficiency("efficiency", "efficiency", 1, -0.5, 0.5); m_purs = new TEfficiency("purity", "Tb/TbEffPur/pur", 1, -0.5, 0.5); m_effHitmap = new TEfficiency("efficiencyHitmap", "efficiencyHitmap", 64, 0.0, 14.08, 64, 0.0, 14.08); m_purHitmap = new TEfficiency("puritHitmap", "purityHitmap", 64, 0.0, 14.08, 64, 0.0, 14.08); int nBins = 50; m_effHitmapInterPixel = new TEfficiency("efficiencyHitmapInterPixel", "efficiencyHitmapInterPixel", nBins, 0.0, 0.055, nBins, 0.0, 0.055); m_purHitmapInterPixel = new TEfficiency("puritHitmapInterPixel", "purityHitmapInterPixel", nBins, 0.0, 0.055, nBins, 0.0, 0.055); m_effHitmapInterPixelTriple = new TEfficiency("efficiencyHitmapInterPixelTriple", "efficiencyHitmapInterPixelTriple", 150, 0.0, 10*0.055, 20, 0.0, 2*0.055); for (unsigned int i=1; i<5; i++) { std::string name = "efficiencyHitmapInterClusterSize" + std::to_string(i); TEfficiency * e = new TEfficiency(name.c_str(), name.c_str(), nBins, 0.0, 0.055, nBins, 0.0, 0.055); m_effHitmapInterPixelVsSizes.push_back(e); } // Plots for post correlations. m_remainsCorrelationsX = book2D("remainsClusterCorrelationsX", "remainsClusterCorrelationsX", 0, 14, 200, 0, 14, 200); m_remainsCorrelationsY = book2D("remainsClusterCorrelationsY", "remainsClusterCorrelationsY", 0, 14, 200, 0, 14, 200); m_remainsDifferencesXY = book2D("remainsDifferencesXY", "remainsDifferencesXY", -1.5, 1.5, 150, -1.5, 1.5, 150); m_clusterRemainsPositionsLocal = book2D("clusterRemainsPositionsLocal", "clusterRemainsPositionsLocal", -5, 20, 600, -5, 20, 600); m_trackRemainsPositionsLocal = book2D("trackRemainsPositionsLocal", "trackRemainsPositionsLocal", 0, 256, 600, 0, 256, 600); m_clusterRemainsPositionsGlobal = book2D("clusterRemainsPositionsGlobal", "clusterRemainsPositionsGlobal", -5, 20, 600, -5, 20, 600); m_trackRemainsPositionsGlobal = book2D("trackRemainsPositionsGlobal", "trackRemainsPositionsGlobal", -5, 20, 600, -5, 20, 600); m_vetoTracksHitmap = book2D("vetoTrackHitmap", "vetoTrackHitmap", -5, 20, 600, -5, 20, 600); m_vetoClustersHitmap = book2D("vetoClusterHitmap", "vetoClusterHitmap", -5, 20, 600, -5, 20, 600); m_timeResidualVsColumn = book2D("timeResidualVsColumn", "timeResidualVsColumn", 0, 256, 256, -50, 50, 500); // Setup the tools. m_trackFit = tool<ITbTrackFit>("TbTrackFit", "Fitter", this); // h_effVsCharge = new TH2F("effVsCharge", "effVsCharge", 50, 0.5, 1, 20, 0.5, 20.5); // TFile * f = new TFile("/afs/cern.ch/user/d/dsaunder/cmtuser/KEPLER/KEPLER_HEAD/EDR_plots/EfficiencyResults/Eff-S22-Run6309-500V.root", "READ"); // h_effInter = (TH2F*)f->Get("eff_histo"); return StatusCode::SUCCESS; } //============================================================================= // Finalizer //============================================================================= StatusCode TbEffPur::finalize() { m_effs->SetTotalEvents(0, m_nTracks); m_effs->SetPassedEvents(0, m_nTrackedClusters); m_purs->SetTotalEvents(0, m_nClusters); m_purs->SetPassedEvents(0, m_nTrackedClusters); m_eff = m_nTrackedClusters/(1.0*m_nTracks); m_pur = m_nTrackedClusters/(1.0*m_nClusters); std::cout<<"ith ROOT Efficiency: " << m_effs->GetEfficiency(0) << " + " << m_effs->GetEfficiencyErrorUp(0) <<" - "<< m_effs->GetEfficiencyErrorLow(0) <<std::endl; std::cout<<"ith ROOT Purity: " << m_purs->GetEfficiency(0) << " + " << m_purs->GetEfficiencyErrorUp(0) <<" - "<< m_purs->GetEfficiencyErrorLow(0) <<std::endl; std::cout<<"Corner efficiency: "<<m_nClustersPassedCorner/(1.*m_nTracksCorner)<<std::endl; std::cout<<"Central efficiency: "<<m_nClustersPassedCentral/(1.*m_nTracksCentral)<<std::endl; plot(m_eff, "Efficiency", "Efficiency", 0.0, 1, 1); plot(m_pur, "Purity", "Purity", 0.0, 1, 1); plot(m_effs->GetEfficiencyErrorUp(0), "EfficiencyError", "EfficiencyError", 0.0, 1, 1); plot(m_purs->GetEfficiencyErrorUp(0), "PurityError", "PurityError", 0.0, 1, 1); TH2D * h = Gaudi::Utils::Aida2ROOT::aida2root(m_trackRemainsPositionsLocal); double maxBin = h->GetBinContent(h->GetMaximumBin()); double minBin = h->GetBinContent(h->GetMinimumBin()); for (int i=0; i<m_trackRemainsPositionsLocal->xAxis().bins(); i++) { for (int j=0; j<m_trackRemainsPositionsLocal->yAxis().bins(); j++) { plot(m_trackRemainsPositionsLocal->binHeight(i, j), "trackRemainsBins", "trackRemainsBins", minBin, maxBin, int(maxBin-minBin)); } } TFile * f = new TFile("EfficiencyResults.root", "RECREATE"); //m_effs->Write(); m_effHitmapInterPixel->Write(); m_effHitmapInterPixelTriple->Write(); //h_effVsCharge->Write(); //m_effs->CreateHistogram()->Write(); m_effHitmapInterPixel->CreateHistogram()->Write(); m_effHitmapInterPixelTriple->CreateHistogram()->Write(); // for (unsigned int i=0; i<m_effHitmapInterPixelVsSizes.size(); i++) { // m_effHitmapInterPixelVsSizes[i]->Write(); // //m_effHitmapInterPixelVsSizes[i]->CreateHistogram()->Write(); // } f->Close(); return TbAlgorithm::finalize(); } //============================================================================= // Main execution //============================================================================= StatusCode TbEffPur::execute() { m_nEvent++; m_tracks = getIfExists<LHCb::TbTracks>(m_trackLocation); //m_vertices = getIfExists<LHCb::TbVertices>(m_vertexLocation); m_clusters = getIfExists<LHCb::TbClusters>(m_clusterLocation + std::to_string(m_DUTindex)); if (m_clusters->size() < 100 || m_tracks->size() < 100) return StatusCode::SUCCESS; // Matching. effPur(); return StatusCode::SUCCESS; } //============================================================================= // Efficiency finding //============================================================================= void TbEffPur::effPur() { // Non-veto'd containers. std::vector<LHCb::TbCluster*> * cutClusters = new std::vector<LHCb::TbCluster*>(); std::vector<LHCb::TbTrack*> cutTracks; int nClustersPreVeto = m_clusters->size(); int nTracksPreVeto = m_tracks->size(); // Apply veto. if (m_applyVeto) applyVeto(cutClusters, &cutTracks); else fillAllTrackClusters(cutClusters, &cutTracks); m_trackAssociated = new std::vector<bool>(cutTracks.size(), false); //std::cout<<"Fraction tracks not veto'd: "<<cutTracks.size()/(1.0*nTracksPreVeto)<<"\tEvent: "<<m_nEvent<<std::endl; //std::cout<<"Fraction clusters not veto'd: "<<cutClusters->size()/(1.0*nClustersPreVeto)<<"\tEvent: "<<m_nEvent<<std::endl; plot(cutClusters->size()/(1.0*nClustersPreVeto), "clusterFractionVetod", "clusterFractionVetod", 0.0, 1.0, 200); plot(cutTracks.size()/(1.0*nTracksPreVeto), "trackFractionVetod", "trackFractionVetod", 0.0, 1.0, 200); // Do matching. m_nClusters += cutClusters->size(); m_nTracks += cutTracks.size(); trackClusters(cutClusters, &cutTracks); // Viewer options. if (m_nEvent == m_viewerEvent) { if (m_viewerOutput) outputViewerData(); for (LHCb::TbClusters::iterator iclust = cutClusters->begin(); iclust != cutClusters->end(); iclust++) { // if (!(*iclust)->associated()) // std::cout<<"Note: non-associated clusters at hTime: "<<(*iclust)->htime()<<std::endl; } } // Correlate remains. //correlateRemains(&cutTracks, cutClusters); delete cutClusters; delete m_trackAssociated; } //============================================================================= // Global cuts //============================================================================= void TbEffPur::applyVeto(std::vector<LHCb::TbCluster*> * cutClusters, std::vector<LHCb::TbTrack*> * cutTracks) { // Gather all cluster times (over all planes) and sort it ___________________ std::vector<double> allClusterTimes; for (unsigned int i=0; i<m_nPlanes; i++) { LHCb::TbClusters * clusters = getIfExists<LHCb::TbClusters>(m_clusterLocation + std::to_string(i)); for (LHCb::TbClusters::const_iterator it = clusters->begin(); it != clusters->end(); ++it) allClusterTimes.push_back((*it)->htime()); } std::sort(allClusterTimes.begin(), allClusterTimes.end()); // Get big enough gaps in pairs _____________________________________________ std::vector<double> tGapCenters; tGapCenters.push_back(0); for (std::vector<double>::iterator itime = allClusterTimes.begin()+1; itime != allClusterTimes.end(); itime++) { plot((*itime) - (*(itime-1)), "allGapWidths", "allGapWidths", 0.0, 3000.0, 200); if ((*itime) - (*(itime-1)) > m_tGap) { tGapCenters.push_back(0.5*((*itime) + (*(itime-1)))); plot((*itime) - (*(itime-1)), "bigGapWidths", "bigGapWidths", 0.0, 3000.0, 200); } } tGapCenters.push_back(allClusterTimes.back()); counter("nGaps") += tGapCenters.size(); plot(tGapCenters.size(), "nGaps", "nGaps", 0.0, 1000.0, 200); // Loop over these sub events and veto ______________________________________ std::vector<double>::iterator igap; for (igap = tGapCenters.begin(); igap != tGapCenters.end() - 1; igap++) { bool veto = false; if (igap == tGapCenters.begin() || igap == tGapCenters.end() -1) veto = true; // Loop tracks. if (!veto) { for (LHCb::TbTrack* track : *m_tracks) { if (track->htime() > (*igap) && track->htime() < (*(igap+1))) { // Veto on tracks outside cuts. const Gaudi::XYZPoint trackInterceptGlobal = geomSvc()->intercept(track, m_DUTindex); if (!globalCutPosition(trackInterceptGlobal)) veto = true; else if (outsideDUT(trackInterceptGlobal)) veto = true; else if (interceptDeadPixel(trackInterceptGlobal)) veto = true; } } } // Loop vertices. // if (!veto) { // for (LHCb::TbVertex* vertex : *m_vertices) { // if (vertex->htime() > (*igap) && vertex->htime() < (*(igap+1))) { // veto = true; // } // } // } // Loop DUT clusters. if (!veto) { for (const LHCb::TbCluster* cluster : *m_clusters) { if (cluster->htime() > (*igap) && cluster->htime() < (*(igap+1))) { // Veto on clusters outside cuts. Gaudi::XYZPoint clusterInterceptGlobal(cluster->x(), cluster->y(), cluster->z()); if (!globalCutPosition(clusterInterceptGlobal)) veto = true; if (cluster->charge() > m_chargeCutUp || cluster->charge() < m_chargeCutLow) veto = true; } } } // Loop telescope clusters. if (!veto) { for (unsigned int i=0; i<m_nPlanes; i++) { if (i == m_DUTindex) continue; LHCb::TbClusters * clusters = getIfExists<LHCb::TbClusters>(m_clusterLocation + std::to_string(i)); for (LHCb::TbClusters::const_iterator it = clusters->begin(); it != clusters->end()-1; ++it) { if ((*it)->htime() > (*igap) && (*it)->htime() < (*(igap+1))) { double delt = (*it)->htime() - (*(it+1))->htime(); if (fabs(delt) < m_telescopeClusterVetoDelT) { veto = true; break; } } } } } if (!veto) fillTrackClusters(cutClusters, cutTracks, (*igap), (*(igap+1))); else counter("nGapsFiltered") += 1; } } //============================================================================= // Correlate remains //============================================================================= void TbEffPur::correlateRemains(std::vector<LHCb::TbTrack*> * cutTracks, std::vector<LHCb::TbCluster*> * cutClusters) { for (std::vector<LHCb::TbCluster*>::iterator ic = cutClusters->begin(); ic != cutClusters->end(); ++ic) { if (!(*ic)->associated()) { m_clusterRemainsPositionsGlobal->fill((*ic)->x(), (*ic)->y()); m_clusterRemainsPositionsLocal->fill((*ic)->xloc(), (*ic)->yloc()); plot((*ic)->charge(), "chargeClusterRemains", "chargeClusterRemains", 0.0, 1000.0, 125); } } unsigned int i = 0; for (std::vector<LHCb::TbTrack*>::iterator itrack = cutTracks->begin(); itrack != cutTracks->end(); itrack++) { if (!m_trackAssociated->at(i)) { Gaudi::XYZPoint trackIntercept = geomSvc()->intercept((*itrack), m_DUTindex); m_trackRemainsPositionsGlobal->fill(trackIntercept.x(), trackIntercept.y()); auto interceptUL = geomSvc()->globalToLocal(trackIntercept, m_DUTindex); m_trackRemainsPositionsLocal->fill(interceptUL.x()/m_pitch - 0.5, interceptUL.y()/m_pitch - 0.5); } i++; } // Draws correlations plots between non-associated clusters and tracks. for (std::vector<LHCb::TbTrack*>::iterator itrack = cutTracks->begin(); itrack != cutTracks->end(); itrack++) { for (std::vector<LHCb::TbCluster*>::iterator ic = cutClusters->begin(); ic != cutClusters->end(); ++ic) { if ((*ic)->htime() < (*itrack)->htime() - m_correlationTimeWindow) continue; if (!(*ic)->associated()) { //if (m_nEvent == m_viewerEvent) std::cout<<"Impurity at time: "<<(*ic)->htime()<<std::endl; Gaudi::XYZPoint trackIntercept = geomSvc()->intercept((*itrack), m_DUTindex); m_remainsCorrelationsX->fill(trackIntercept.x(), (*ic)->x()); m_remainsCorrelationsY->fill(trackIntercept.y(), (*ic)->y()); plot(trackIntercept.x() - (*ic)->x(), "remainClustDifferencesX", "remainsClustDifferencesX", -1.5, 1.5, 150); plot(trackIntercept.y() - (*ic)->y(), "remainClustDifferencesY", "remainClustDifferencesY", -1.5, 1.5, 150); plot((*itrack)->htime() - (*ic)->htime(), "remainClustDifferencesT", "remainClustDifferencesT", -50, 50, 150); m_remainsDifferencesXY->fill(trackIntercept.y() - (*ic)->y(), trackIntercept.x() - (*ic)->x()); } if ((*ic)->htime() > (*itrack)->htime() + m_correlationTimeWindow) break; } } } //============================================================================= // //============================================================================= void TbEffPur::fillAllTrackClusters(std::vector<LHCb::TbCluster*> * cutClusters, std::vector<LHCb::TbTrack*> * cutTracks) { for (LHCb::TbTrack* track : *m_tracks) cutTracks->push_back(track); for (std::vector<LHCb::TbCluster*>::iterator iClust = m_clusters->begin(); iClust != m_clusters->end(); iClust++) cutClusters->push_back(*iClust); } //============================================================================= // //============================================================================= void TbEffPur::fillTrackClusters(std::vector<LHCb::TbCluster*> * cutClusters, std::vector<LHCb::TbTrack*> * cutTracks, double tlow, double tup) { // Push tracks and clusters inside this time window, which passed the veto. for (LHCb::TbTrack* track : *m_tracks) { if (track->htime() > tlow && track->htime() < tup) { Gaudi::XYZPoint trackIntercept = geomSvc()->intercept(track, m_DUTindex); cutTracks->push_back(track); m_vetoTracksHitmap->fill(trackIntercept.x(), trackIntercept.y()); Gaudi::XYZPoint trackInterceptLocal = geomSvc()->globalToLocal(trackIntercept, m_DUTindex); int row = trackInterceptLocal.y()/m_pitch - 0.5; int col = trackInterceptLocal.x()/m_pitch - 0.5; if (pixelSvc()->isMasked(pixelSvc()->address(col, row), m_DUTindex)) { std::cout<<"Shouldn't be here!"<<std::endl; } } } for (LHCb::TbCluster* cluster : *m_clusters) { if (cluster->htime() > tlow && cluster->htime() < tup) { cutClusters->push_back(cluster); m_vetoClustersHitmap->fill(cluster->x(), cluster->y()); } } } //============================================================================= // Global cuts //============================================================================= void TbEffPur::trackClusters(std::vector<LHCb::TbCluster*> * cutClusters, std::vector<LHCb::TbTrack*> * cutTracks) { for (std::vector<LHCb::TbTrack*>::iterator itrack = cutTracks->begin(); itrack != cutTracks->end(); itrack++) { // Get local position of track. const auto interceptUG = geomSvc()->intercept((*itrack), m_DUTindex); const auto interceptUL = geomSvc()->globalToLocal(interceptUG, m_DUTindex); // Loop over clusters to find the closest. LHCb::TbCluster * closestCluster = NULL; double bestRadialDistance; for (std::vector<LHCb::TbCluster*>::iterator iclust = cutClusters->begin(); iclust != cutClusters->end(); iclust++) { bool match = matchTrackToCluster((*iclust), (*itrack)); double radialDistance = getRadialSeparation((*iclust), (*itrack)); if (match) { if (!closestCluster) { closestCluster = (*iclust); bestRadialDistance = radialDistance; } else if (radialDistance<bestRadialDistance) { closestCluster = (*iclust); bestRadialDistance = radialDistance; } } if ((*iclust)->htime() - (*itrack)->htime() > m_tResidualCut) break; } double trackX = interceptUL.x(); double trackY = interceptUL.y(); if (closestCluster != NULL && closestCluster->charge() > m_chargeCutLow) { closestCluster->setAssociated(true); m_nTrackedClusters++; m_effHitmap->Fill(true, trackX, trackY); m_effX->Fill(true, trackX); m_effY->Fill(true, trackY); if (fmod(trackX, m_pitch)<0.0183 && fmod(trackY, m_pitch) < 0.0183) m_nClustersPassedCorner++; if (fmod(trackX, m_pitch) > 0.0183 && fmod(trackX, m_pitch) < (2*0.0183) && fmod(trackY, m_pitch) > 0.0183 && fmod(trackY, m_pitch) < (2*0.0183)) m_nClustersPassedCentral++; //h_effVsCharge->Fill(h_effInter->Interpolate(fmod(trackX, m_pitch), fmod(trackY, m_pitch)), closestCluster->charge()); // if (trackY > 9.25 && trackY < 10.25) m_effHitmapInterPixel->Fill(true, fmod(trackX, m_pitch), fmod(trackY, m_pitch)); // if (trackX > 28.05 && // trackX < 28.6) m_effHitmapInterPixelTriple->Fill(true, trackX-28.05, fmod(trackY, m_pitch)); m_effHitmapInterPixel->Fill(true, fmod(trackX, m_pitch), fmod(trackY, m_pitch)); m_effHitmapInterPixelTriple->Fill(true, trackX-28.05, fmod(trackY, m_pitch)); if (closestCluster->size() <= m_effHitmapInterPixelVsSizes.size()) m_effHitmapInterPixelVsSizes[closestCluster->size()-1]->Fill(true, fmod(trackX, m_pitch), fmod(trackY, m_pitch)); m_trackAssociated->at(itrack - cutTracks->begin()) = true; plot(closestCluster->x() - interceptUG.x(), "xResidualsClustMinusTrack", "xResidualsClustMinusTrack", -0.2, 0.2, 400); plot(closestCluster->y() - interceptUG.y(), "yResidualsClustMinusTrack", "yResidualsClustMinusTrack", -0.2, 0.2, 400); plot(closestCluster->htime() - (*itrack)->htime(), "hTimeResidualClustMinusTrack", "hTimeResidualClustMinusTrack", -50, 50, 400); if (closestCluster->size() == 1) { auto hits = closestCluster->hits(); int col = (*hits.begin())->col(); m_timeResidualVsColumn->fill(col, closestCluster->htime() - (*itrack)->htime()); } if ((*itrack)->vertexed()) counter("nVerticesCorrelated") += 1; } else { m_effHitmap->Fill(false, trackX, trackY); // if (trackY > 9.25 && trackY < 10.25) m_effHitmapInterPixel->Fill(false, fmod(trackX, m_pitch), fmod(trackY, m_pitch)); // if (trackX > 28.05 && // trackX < 28.6) m_effHitmapInterPixelTriple->Fill(false, trackX-28.05, fmod(trackY, m_pitch)); m_effHitmapInterPixel->Fill(false, fmod(trackX, m_pitch), fmod(trackY, m_pitch)); m_effHitmapInterPixelTriple->Fill(false, trackX-28.05, fmod(trackY, m_pitch)); m_effX->Fill(false, trackX); m_effY->Fill(false, trackY); //std::cout<<"Inefficiency at time: "<<(*itrack)->htime()<<std::endl; } if (fmod(trackX, m_pitch)<0.0183 && fmod(trackY, m_pitch) < 0.0183) m_nTracksCorner++; if (fmod(trackX, m_pitch) > 0.0183 && fmod(trackX, m_pitch) < (2*0.0183) && fmod(trackY, m_pitch) > 0.0183 && fmod(trackY, m_pitch) < (2*0.0183)) m_nTracksCentral++; } } //============================================================================= // //============================================================================= double TbEffPur::getRadialSeparation(LHCb::TbCluster * cluster, LHCb::TbTrack * track) { Gaudi::XYZPoint trackIntercept = geomSvc()->intercept(track, m_DUTindex); double xResidual = cluster->x() - trackIntercept.x(); double yResidual = cluster->y() - trackIntercept.y(); double r2 = xResidual*xResidual + yResidual*yResidual; return pow(r2, 0.5); } //============================================================================= // Local cuts //============================================================================= bool TbEffPur::matchTrackToCluster(LHCb::TbCluster * cluster, LHCb::TbTrack * track) { Gaudi::XYZPoint trackIntercept = geomSvc()->intercept(track, m_DUTindex); double xResidual = cluster->x() - trackIntercept.x(); double yResidual = cluster->y() - trackIntercept.y(); double tResidual = cluster->htime() - track->htime(); double delr = pow(pow(xResidual, 2) + pow(yResidual, 2), 0.5); // if (track->vertexed()) plot(xResidual, "vertexResiduals/X", "vertexResiduals/X", -0.5, 0.5, 200); // if (track->vertexed()) plot(yResidual, "vertexResiduals/Y", "vertexResiduals/Y", -0.5, 0.5, 200); // if (track->vertexed()) plot(tResidual, "vertexResiduals/T", "vertexResiduals/T", -0.5, 0.5, 200); // // if (track->vertexed() && litPixel(cluster, track)) { // plot(xResidual, "vertexResiduals/Xlit", "vertexResiduals/Xlit", -0.5, 0.5, 200); // plot(yResidual, "vertexResiduals/Ylit", "vertexResiduals/Ylit", -0.5, 0.5, 200); // } if (fabs(tResidual) > m_tResidualCut) { counter("nTimeRejected") += 1; return false; } if (delr > m_rResidualCut) { counter("nSpatialRejected") += 1; if (litPixel(cluster, track)) return true; else { counter("nSpatialAndLitRejected") += 1; return false; } } // if (!litPixel(cluster, track)) return false; return true; } //============================================================================= // //============================================================================= bool TbEffPur::interceptDeadPixel(Gaudi::XYZPoint trackInterceptGlobal) { // Find the row and column corresponding to the track intercept. Gaudi::XYZPoint trackInterceptLocal = geomSvc()->globalToLocal(trackInterceptGlobal, m_DUTindex); int row = trackInterceptLocal.y()/m_pitch - 0.5; int col = trackInterceptLocal.x()/m_pitch - 0.5; for (int icol = col - 1; icol != col+2; icol++) { for (int irow = row - 1; irow != row+2; irow++) { if (icol >= 0 && icol <256 && irow>=0 && irow<256) { if (pixelSvc()->isMasked(pixelSvc()->address(icol, irow), m_DUTindex)) { return true; } // if (icol == 17 && irow == 36) { // return true; // } // if (icol == 18 && irow == 36) { // return true; // } // if (icol == 53 && irow == 3) { // return true; // } // if (icol == 54 && irow == 3) { // return true; // } // if (icol == 73 && irow == 26) { // return true; // } // if (icol == 74 && irow == 26) { // return true; // } // if (icol == 19 && irow == 103) { // return true; // } // if (icol == 31 && irow == 106) { // return true; // } // if (icol == 32 && irow == 106) { // return true; // } // if (icol == 38 && irow == 108) { // return true; // } // if (icol == 63 && irow == 95) { // return true; // } // if (icol == 64 && irow == 95) { // return true; // } // if (icol == 103 && irow == 23) { // return true; // } // if (icol == 104 && irow == 23) { // return true; // } // if (icol == 115 && irow == 20) { // return true; // } // if (icol == 116 && irow == 94) { // return true; // } } } } return false; } //============================================================================= // //============================================================================= bool TbEffPur::litPixel(LHCb::TbCluster * cluster, LHCb::TbTrack * track) { // Find the row and column corresponding to the track intercept. Gaudi::XYZPoint trackIntercept = geomSvc()->intercept(track, m_DUTindex); Gaudi::XYZPoint pLocal = geomSvc()->globalToLocal(trackIntercept, m_DUTindex); int row = pLocal.y()/m_pitch - 0.5; int col = pLocal.x()/m_pitch - 0.5; // See if within a pre-defined square of pixels. for (unsigned int i=0; i<cluster->size(); i++) { unsigned int delRow = abs(row - int(cluster->hits()[i]->row())); unsigned int delCol = abs(col - int(cluster->hits()[i]->col())); if (delRow <= m_litSquareSide && delCol <= m_litSquareSide) { counter("nLitPixels") += 1; return true; } } return false; } //============================================================================= // Excluding dead regions. //============================================================================= bool TbEffPur::globalCutPosition(Gaudi::XYZPoint pGlobal) { if (pGlobal.x() < m_xLow + m_edgeVetoDistance) return false; else if (pGlobal.x() > m_xUp - m_edgeVetoDistance) return false; else if (pGlobal.y() < m_yLow + m_edgeVetoDistance) return false; else if (pGlobal.y() > m_yUp - m_edgeVetoDistance) return false; return true; // Inside. } //============================================================================= // Excluding dead regions. //============================================================================= bool TbEffPur::outsideDUT(Gaudi::XYZPoint interceptUG) { const auto interceptUL = geomSvc()->globalToLocal(interceptUG, m_DUTindex); if (interceptUL.x() < 0 + m_edgeVetoDistance || interceptUL.x() > 14.08 - m_edgeVetoDistance || interceptUL.y() < 0 + m_edgeVetoDistance|| interceptUL.y() > 14.08 - m_edgeVetoDistance) return true; return false; } //============================================================================= // Viewer output. //============================================================================= //============================================================================= // Viewer output. //============================================================================= //============================================================================= // Viewer output. //============================================================================= void TbEffPur::outputDeadRegion(unsigned int col, unsigned int row) { std::ofstream myfile; myfile.open("/afs/cern.ch/user/d/dsaunder/KeplerViewerData.dat", std::ofstream::app); std::string outputLine; for (int irow = std::max(int(row-m_deadAreaRadius), 0); irow < std::min(int(row+m_deadAreaRadius+1), m_nDUTpixels); irow++) { for (int icol = std::max(int(col-m_deadAreaRadius), 0); icol < std::min(int(col+m_deadAreaRadius+1), m_nDUTpixels); icol++) { outputLine = "DeadPixel "; const double xLocal = (col-icol) * m_pitch; // Dont want the middle! const double yLocal = (row-irow) * m_pitch; // Dont want the middle! Gaudi::XYZPoint pLocal(xLocal, yLocal, 0.); Gaudi::XYZPoint posn = geomSvc()->localToGlobal(pLocal, m_DUTindex); outputLine += std::to_string(posn.x()) + " "; outputLine += std::to_string(posn.y()) + " "; outputLine += std::to_string(posn.z()) + " "; Gaudi::XYZPoint posn2(pLocal.x() + 0.055, pLocal.y(), 0.); posn = geomSvc()->localToGlobal(posn2, m_DUTindex); outputLine += std::to_string(posn.x()) + " "; outputLine += std::to_string(posn.y()) + " "; outputLine += std::to_string(posn.z()) + " "; Gaudi::XYZPoint posn3(pLocal.x() + 0.055, pLocal.y()+0.055, 0.); posn = geomSvc()->localToGlobal(posn3, m_DUTindex); outputLine += std::to_string(posn.x()) + " "; outputLine += std::to_string(posn.y()) + " "; outputLine += std::to_string(posn.z()) + " "; Gaudi::XYZPoint posn4(pLocal.x(), pLocal.y()+0.055, 0.); posn = geomSvc()->localToGlobal(posn4, m_DUTindex); outputLine += std::to_string(posn.x()) + " "; outputLine += std::to_string(posn.y()) + " "; outputLine += std::to_string(posn.z()) + " "; outputLine += "\n"; myfile << outputLine; } } myfile.close(); } //============================================================================= // Viewer output. //============================================================================= void TbEffPur::outputViewerData() { std::ofstream myfile; myfile.open("/afs/cern.ch/user/d/dsaunder/KeplerViewerData.dat", std::ofstream::app); std::string outputLine; // // // First output the chips. // for (unsigned int i=0; i<m_nPlanes; i++) { // outputLine = "Chip "; // Gaudi::XYZPoint posn1(0., 14.08, 0.); // Gaudi::XYZPoint posn = geomSvc()->localToGlobal(posn1, i); // outputLine += std::to_string(posn.x()) + " "; // outputLine += std::to_string(posn.y()) + " "; // outputLine += std::to_string(posn.z()) + " "; // // Gaudi::XYZPoint posn2(14.08, 14.08, 0.); // posn = geomSvc()->localToGlobal(posn2, i); // outputLine += std::to_string(posn.x()) + " "; // outputLine += std::to_string(posn.y()) + " "; // outputLine += std::to_string(posn.z()) + " "; // // Gaudi::XYZPoint posn3(14.08, 0., 0.); // posn = geomSvc()->localToGlobal(posn3, i); // outputLine += std::to_string(posn.x()) + " "; // outputLine += std::to_string(posn.y()) + " "; // outputLine += std::to_string(posn.z()) + " "; // // Gaudi::XYZPoint posn4(0., 0., 0.); // posn = geomSvc()->localToGlobal(posn4, i); // outputLine += std::to_string(posn.x()) + " "; // outputLine += std::to_string(posn.y()) + " "; // outputLine += std::to_string(posn.z()) + " "; // // outputLine += "\n"; // myfile << outputLine; // } // Clusters. auto ic = m_clusters->begin(); const auto end = m_clusters->end(); for (; ic != end; ++ic) { outputLine = "Cluster "; outputLine += std::to_string((*ic)->x()) + " "; outputLine += std::to_string((*ic)->y()) + " "; outputLine += std::to_string((*ic)->z()) + " "; outputLine += std::to_string((*ic)->htime()) + " "; // if ((*ic)->endCluster() && (*ic)->vertexed()) outputLine += "5 \n"; //if ((*ic)->vertexed()) outputLine += "4 \n"; // else if ((*ic)->endCluster()) outputLine += "3 \n"; if ((*ic)->associated()) outputLine += "2 \n"; // else if ((*ic)->volumed()) outputLine += "1 \n"; else { outputLine += "0 \n"; } myfile << outputLine; } outputLine = "CentralRegion "; outputLine += std::to_string(m_xLow) + " "; outputLine += std::to_string(m_xUp) + " "; outputLine += std::to_string(m_yLow) + " "; outputLine += std::to_string(m_yUp) + " "; outputLine += std::to_string(geomSvc()->module(m_DUTindex)->z()) + " "; myfile << outputLine; // // Its hits. // for (auto hit : (*ic)->hits()) { // outputLine = "Pixel "; // const double xLocal = (hit->col()) * m_pitch; // Dont want the middle! // const double yLocal = (hit->row()) * m_pitch; // Dont want the middle! // Gaudi::XYZPoint pLocal(xLocal, yLocal, 0.); // // Gaudi::XYZPoint posn = geomSvc()->localToGlobal(pLocal, i); // outputLine += std::to_string(posn.x()) + " "; // outputLine += std::to_string(posn.y()) + " "; // outputLine += std::to_string(posn.z()) + " "; // // Gaudi::XYZPoint posn2(pLocal.x() + 0.055, pLocal.y(), 0.); // posn = geomSvc()->localToGlobal(posn2, i); // outputLine += std::to_string(posn.x()) + " "; // outputLine += std::to_string(posn.y()) + " "; // outputLine += std::to_string(posn.z()) + " "; // // Gaudi::XYZPoint posn3(pLocal.x() + 0.055, pLocal.y()+0.055, 0.); // posn = geomSvc()->localToGlobal(posn3, i); // outputLine += std::to_string(posn.x()) + " "; // outputLine += std::to_string(posn.y()) + " "; // outputLine += std::to_string(posn.z()) + " "; // // Gaudi::XYZPoint posn4(pLocal.x(), pLocal.y()+0.055, 0.); // posn = geomSvc()->localToGlobal(posn4, i); // outputLine += std::to_string(posn.x()) + " "; // outputLine += std::to_string(posn.y()) + " "; // outputLine += std::to_string(posn.z()) + " "; // // outputLine += std::to_string(hit->htime()) + " "; // outputLine += std::to_string(hit->ToT()) + " "; // // outputLine += "\n"; // myfile << outputLine; // } myfile.close(); } //============================================================================= // END //=============================================================================
C++
CL
e6d4e91924022e997fa2c27a413d2f95beccf132afb75a6d8cd4e0042e2dfb9b
#ifndef _LOBBY_H_ #define _LOBBY_H_ #include <map> #include <memory> #include "sys/mman.h" #include "../../common/simple_server.h" #include "data_fifo.h" #include "lobby_logic.h" namespace ysd_simple_server { ///////////////////////////////////////////////////////// // Lobby server get data from gateway // server and process them with LobbyLogic then return // them to the gateway server. ///////////////////////////////////////////////////////// class Lobby { typedef std::map<uint16_t, std::unique_ptr<FifoDataPipe>> FIFOSet; public: Lobby (int max_size) : logic_ ( ) { epoll_fd_ = epoll_create1(EPOLL_CLOEXEC); events_.resize(100); // block until gateway server start lua_fifo_fd_ = open(_LUA_FIFO_, O_RDONLY); if (lua_fifo_fd_ == -1) perror("open lua fifo "); epoll_event ev; ev.data.fd = lua_fifo_fd_; ev.events = EPOLLIN | EPOLLET; if (-1 == epoll_ctl(epoll_fd_, EPOLL_CTL_ADD, lua_fifo_fd_, &ev)) perror("epoll add listen gateway "); } ~Lobby ( ) { close(lua_fifo_fd_); unlink(_LUA_FIFO_); close(epoll_fd_); } Lobby (const Lobby& other) = delete; Lobby& operator= (Lobby other) = delete; void Run ( ); private: void UserArrv ( ); void CreateFIFO (unsigned short id); int lua_fifo_fd_; // control info from gateway server int epoll_fd_; // epoll for listen data from gateway server EpollEventSet events_; // events from gateway server FIFOSet fifos_; // recv fifo id to uid std::map<int, int> recvf_uid; LobbyLogic logic_; }; } #endif
C++
CL
1c98d7cbf0b6684cb9ff230faa9e5016056993d8892759857da9df6911266051
//-------------------------------------------------------------------------------------- // File: Blobs.cpp // // A pixel shader effect to mimic metaball physics in image space. // // Copyright (c) Microsoft Corporation. All rights reserved. //-------------------------------------------------------------------------------------- #include "DXUT.h" #include "DXUTcamera.h" #include "DXUTgui.h" #include "DXUTsettingsdlg.h" #include "SDKmisc.h" #include "resource.h" //#define DEBUG_VS // Uncomment this line to debug vertex shaders //#define DEBUG_PS // Uncomment this line to debug pixel shaders //-------------------------------------------------------------------------------------- // Constants //-------------------------------------------------------------------------------------- #define NUM_BLOBS 5 #define FIELD_OF_VIEW ( (70.0f/90.0f)*(D3DX_PI/2.0f) ) #define GAUSSIAN_TEXSIZE 64 #define GAUSSIAN_HEIGHT 1 #define GAUSSIAN_DEVIATION 0.125f //-------------------------------------------------------------------------------------- // Custom types //-------------------------------------------------------------------------------------- // Vertex format for blob billboards struct POINTVERTEX { D3DXVECTOR3 pos; float size; D3DXVECTOR3 color; static const DWORD FVF; }; const DWORD POINTVERTEX::FVF = D3DFVF_XYZ | D3DFVF_PSIZE | D3DFVF_DIFFUSE; // Vertex format for screen space work struct SCREENVERTEX { D3DXVECTOR4 pos; D3DXVECTOR2 tCurr; D3DXVECTOR2 tBack; FLOAT fSize; D3DXVECTOR3 vColor; static const DWORD FVF; }; const DWORD SCREENVERTEX::FVF = D3DFVF_XYZRHW | D3DFVF_TEX4 | D3DFVF_TEXCOORDSIZE2( 0 ) | D3DFVF_TEXCOORDSIZE2( 1 ) | D3DFVF_TEXCOORDSIZE1( 2 ) | D3DFVF_TEXCOORDSIZE3( 3 ); struct CRenderTargetSet { IDirect3DSurface9* apCopyRT[2]; IDirect3DSurface9* apBlendRT[2]; }; //-------------------------------------------------------------------------------------- // Global variables //-------------------------------------------------------------------------------------- ID3DXFont* g_pFont = NULL; // Font for drawing text ID3DXSprite* g_pTextSprite = NULL; // Sprite for batching draw text calls ID3DXEffect* g_pEffect = NULL; // D3DX effect interface CModelViewerCamera g_Camera; // A model viewing camera bool g_bShowHelp = true; // If true, it renders the UI control text CDXUTDialogResourceManager g_DialogResourceManager; // manager for shared resources of dialogs CD3DSettingsDlg g_SettingsDlg; // Device settings dialog CDXUTDialog g_HUD; // dialog for standard controls LPDIRECT3DVERTEXBUFFER9 g_pBlobVB = NULL; // Vertex buffer for blob billboards POINTVERTEX g_BlobPoints[NUM_BLOBS]; // Position, size, and color states LPDIRECT3DTEXTURE9 g_pTexGBuffer[4] = {0}; // Buffer textures for blending effect LPDIRECT3DTEXTURE9 g_pTexScratch = NULL; // Scratch texture LPDIRECT3DTEXTURE9 g_pTexBlob = NULL; // Blob texture D3DFORMAT g_BlobTexFormat; // Texture format for blob texture LPDIRECT3DCUBETEXTURE9 g_pEnvMap = NULL; // Environment map int g_nPasses = 0; // Number of rendering passes required int g_nRtUsed = 0; // Number of render targets used for blending CRenderTargetSet g_aRTSet[2]; // Render targets for each pass D3DXHANDLE g_hBlendTech = NULL; // Technique to use for blending //-------------------------------------------------------------------------------------- // UI control IDs //-------------------------------------------------------------------------------------- #define IDC_TOGGLEFULLSCREEN 1 #define IDC_TOGGLEREF 3 #define IDC_CHANGEDEVICE 4 //-------------------------------------------------------------------------------------- // Forward declarations //-------------------------------------------------------------------------------------- bool CALLBACK IsDeviceAcceptable( D3DCAPS9* pCaps, D3DFORMAT AdapterFormat, D3DFORMAT BackBufferFormat, bool bWindowed, void* pUserContext ); bool CALLBACK ModifyDeviceSettings( DXUTDeviceSettings* pDeviceSettings, void* pUserContext ); HRESULT CALLBACK OnCreateDevice( IDirect3DDevice9* pd3dDevice, const D3DSURFACE_DESC* pBackBufferSurfaceDesc, void* pUserContext ); HRESULT CALLBACK OnResetDevice( IDirect3DDevice9* pd3dDevice, const D3DSURFACE_DESC* pBackBufferSurfaceDesc, void* pUserContext ); void CALLBACK OnFrameMove( double fTime, float fElapsedTime, void* pUserContext ); void CALLBACK OnFrameRender( IDirect3DDevice9* pd3dDevice, double fTime, float fElapsedTime, void* pUserContext ); LRESULT CALLBACK MsgProc( HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam, bool* pbNoFurtherProcessing, void* pUserContext ); void CALLBACK KeyboardProc( UINT nChar, bool bKeyDown, bool bAltDown, void* pUserContext ); void CALLBACK OnGUIEvent( UINT nEvent, int nControlID, CDXUTControl* pControl, void* pUserContext ); void CALLBACK OnLostDevice( void* pUserContext ); void CALLBACK OnDestroyDevice( void* pUserContext ); HRESULT GenerateGaussianTexture(); HRESULT FillBlobVB( D3DXMATRIXA16* pmatWorldView ); HRESULT RenderFullScreenQuad( float fDepth ); void InitApp(); void RenderText(); //-------------------------------------------------------------------------------------- // Entry point to the program. Initializes everything and goes into a message processing // loop. Idle time is used to render the scene. //-------------------------------------------------------------------------------------- INT WINAPI wWinMain( HINSTANCE, HINSTANCE, LPWSTR, int ) { // Enable run-time memory check for debug builds. #if defined(DEBUG) | defined(_DEBUG) _CrtSetDbgFlag( _CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF ); #endif // DXUT will create and use the best device (either D3D9 or D3D10) // that is available on the system depending on which D3D callbacks are set below // Set DXUT callbacks DXUTSetCallbackD3D9DeviceAcceptable( IsDeviceAcceptable ); DXUTSetCallbackD3D9DeviceCreated( OnCreateDevice ); DXUTSetCallbackD3D9DeviceReset( OnResetDevice ); DXUTSetCallbackD3D9FrameRender( OnFrameRender ); DXUTSetCallbackD3D9DeviceLost( OnLostDevice ); DXUTSetCallbackD3D9DeviceDestroyed( OnDestroyDevice ); DXUTSetCallbackMsgProc( MsgProc ); DXUTSetCallbackKeyboard( KeyboardProc ); DXUTSetCallbackFrameMove( OnFrameMove ); DXUTSetCallbackDeviceChanging( ModifyDeviceSettings ); DXUTSetCursorSettings( true, true ); InitApp(); DXUTInit( true, true ); // Parse the command line and show msgboxes DXUTSetHotkeyHandling( true, true, true ); DXUTCreateWindow( L"Blobs" ); DXUTCreateDevice( true, 640, 480 ); DXUTMainLoop(); return DXUTGetExitCode(); } //-------------------------------------------------------------------------------------- // Initialize the app //-------------------------------------------------------------------------------------- void InitApp() { // Initialize dialogs g_SettingsDlg.Init( &g_DialogResourceManager ); g_HUD.Init( &g_DialogResourceManager ); g_HUD.SetCallback( OnGUIEvent ); int iY = 10; g_HUD.AddButton( IDC_TOGGLEFULLSCREEN, L"Toggle full screen", 35, iY, 125, 22 ); g_HUD.AddButton( IDC_TOGGLEREF, L"Toggle REF (F3)", 35, iY += 24, 125, 22 ); g_HUD.AddButton( IDC_CHANGEDEVICE, L"Change device (F2)", 35, iY += 24, 125, 22, VK_F2 ); // Set initial blob states for( int i = 0; i < NUM_BLOBS; i++ ) { g_BlobPoints[i].pos = D3DXVECTOR3( 0.0f, 0.0f, 0.0f ); g_BlobPoints[i].size = 1.0f; } g_BlobPoints[0].color = D3DXVECTOR3( 0.3f, 0.0f, 0.0f ); g_BlobPoints[1].color = D3DXVECTOR3( 0.0f, 0.3f, 0.0f ); g_BlobPoints[2].color = D3DXVECTOR3( 0.0f, 0.0f, 0.3f ); g_BlobPoints[3].color = D3DXVECTOR3( 0.3f, 0.3f, 0.0f ); g_BlobPoints[4].color = D3DXVECTOR3( 0.0f, 0.3f, 0.3f ); } //-------------------------------------------------------------------------------------- // Rejects any D3D9 devices that aren't acceptable to the app by returning false //-------------------------------------------------------------------------------------- bool CALLBACK IsDeviceAcceptable( D3DCAPS9* pCaps, D3DFORMAT AdapterFormat, D3DFORMAT BackBufferFormat, bool bWindowed, void* pUserContext ) { // Skip backbuffer formats that don't support alpha blending IDirect3D9* pD3D = DXUTGetD3D9Object(); if( FAILED( pD3D->CheckDeviceFormat( pCaps->AdapterOrdinal, pCaps->DeviceType, AdapterFormat, D3DUSAGE_QUERY_POSTPIXELSHADER_BLENDING, D3DRTYPE_TEXTURE, BackBufferFormat ) ) ) return false; // No fallback, so need ps2.0 if( pCaps->PixelShaderVersion < D3DPS_VERSION( 2, 0 ) ) return false; // No fallback, so need to support render target if( FAILED( pD3D->CheckDeviceFormat( pCaps->AdapterOrdinal, pCaps->DeviceType, AdapterFormat, D3DUSAGE_RENDERTARGET | D3DUSAGE_QUERY_POSTPIXELSHADER_BLENDING, D3DRTYPE_TEXTURE, BackBufferFormat ) ) ) { return false; } // Check support for pixel formats that are going to be used // D3DFMT_A16B16G16R16F render target if( FAILED( pD3D->CheckDeviceFormat( pCaps->AdapterOrdinal, pCaps->DeviceType, AdapterFormat, D3DUSAGE_RENDERTARGET, D3DRTYPE_TEXTURE, D3DFMT_A16B16G16R16F ) ) ) { return false; } // D3DFMT_R32F render target if( FAILED( pD3D->CheckDeviceFormat( pCaps->AdapterOrdinal, pCaps->DeviceType, AdapterFormat, D3DUSAGE_RENDERTARGET, D3DRTYPE_TEXTURE, D3DFMT_R32F ) ) ) { return false; } return true; } //-------------------------------------------------------------------------------------- // Called right before creating a D3D9 or D3D10 device, allowing the app to modify the device settings as needed //-------------------------------------------------------------------------------------- bool CALLBACK ModifyDeviceSettings( DXUTDeviceSettings* pDeviceSettings, void* pUserContext ) { assert( DXUT_D3D9_DEVICE == pDeviceSettings->ver ); HRESULT hr; IDirect3D9* pD3D = DXUTGetD3D9Object(); D3DCAPS9 caps; V( pD3D->GetDeviceCaps( pDeviceSettings->d3d9.AdapterOrdinal, pDeviceSettings->d3d9.DeviceType, &caps ) ); // If device doesn't support HW T&L or doesn't support 1.1 vertex shaders in HW // then switch to SWVP. if( ( caps.DevCaps & D3DDEVCAPS_HWTRANSFORMANDLIGHT ) == 0 || caps.VertexShaderVersion < D3DVS_VERSION( 1, 1 ) ) { pDeviceSettings->d3d9.BehaviorFlags = D3DCREATE_SOFTWARE_VERTEXPROCESSING; } // Debugging vertex shaders requires either REF or software vertex processing // and debugging pixel shaders requires REF. #ifdef DEBUG_VS if( pDeviceSettings->d3d9.DeviceType != D3DDEVTYPE_REF ) { pDeviceSettings->d3d9.BehaviorFlags &= ~D3DCREATE_HARDWARE_VERTEXPROCESSING; pDeviceSettings->d3d9.BehaviorFlags &= ~D3DCREATE_PUREDEVICE; pDeviceSettings->d3d9.BehaviorFlags |= D3DCREATE_SOFTWARE_VERTEXPROCESSING; } #endif #ifdef DEBUG_PS pDeviceSettings->d3d9.DeviceType = D3DDEVTYPE_REF; #endif // For the first device created if its a REF device, optionally display a warning dialog box static bool s_bFirstTime = true; if( s_bFirstTime ) { s_bFirstTime = false; if( pDeviceSettings->d3d9.DeviceType == D3DDEVTYPE_REF ) DXUTDisplaySwitchingToREFWarning( pDeviceSettings->ver ); } return true; } //-------------------------------------------------------------------------------------- // Create any D3D9 resources that will live through a device reset (D3DPOOL_MANAGED) // and aren't tied to the back buffer size //-------------------------------------------------------------------------------------- HRESULT CALLBACK OnCreateDevice( IDirect3DDevice9* pd3dDevice, const D3DSURFACE_DESC* pBackBufferSurfaceDesc, void* pUserContext ) { HRESULT hr; V_RETURN( g_DialogResourceManager.OnD3D9CreateDevice( pd3dDevice ) ); V_RETURN( g_SettingsDlg.OnD3D9CreateDevice( pd3dDevice ) ); // Query multiple RT setting and set the num of passes required D3DCAPS9 Caps; pd3dDevice->GetDeviceCaps( &Caps ); if( Caps.NumSimultaneousRTs < 2 ) { g_nPasses = 2; g_nRtUsed = 1; } else { g_nPasses = 1; g_nRtUsed = 2; } // Determine which of D3DFMT_R16F or D3DFMT_R32F to use for blob texture IDirect3D9* pD3D; pd3dDevice->GetDirect3D( &pD3D ); D3DDISPLAYMODE DisplayMode; pd3dDevice->GetDisplayMode( 0, &DisplayMode ); if( FAILED( pD3D->CheckDeviceFormat( Caps.AdapterOrdinal, Caps.DeviceType, DisplayMode.Format, D3DUSAGE_RENDERTARGET, D3DRTYPE_TEXTURE, D3DFMT_R16F ) ) ) g_BlobTexFormat = D3DFMT_R32F; else g_BlobTexFormat = D3DFMT_R16F; SAFE_RELEASE( pD3D ); // Initialize the font V_RETURN( D3DXCreateFont( pd3dDevice, 15, 0, FW_BOLD, 1, FALSE, DEFAULT_CHARSET, OUT_DEFAULT_PRECIS, DEFAULT_QUALITY, DEFAULT_PITCH | FF_DONTCARE, L"Arial", &g_pFont ) ); DWORD dwShaderFlags = D3DXFX_NOT_CLONEABLE; #if defined( DEBUG ) || defined( _DEBUG ) dwShaderFlags |= D3DXSHADER_DEBUG; #endif #ifdef DEBUG_VS dwShaderFlags |= D3DXSHADER_FORCE_VS_SOFTWARE_NOOPT; #endif #ifdef DEBUG_PS dwShaderFlags |= D3DXSHADER_FORCE_PS_SOFTWARE_NOOPT; #endif // Read the D3DX effect file WCHAR str[MAX_PATH]; V_RETURN( DXUTFindDXSDKMediaFileCch( str, MAX_PATH, L"Blobs.fx" ) ); V_RETURN( D3DXCreateEffectFromFile( pd3dDevice, str, NULL, NULL, dwShaderFlags, NULL, &g_pEffect, NULL ) ); // Initialize the technique for blending if( 1 == g_nPasses ) { // Multiple RT available g_hBlendTech = g_pEffect->GetTechniqueByName( "BlobBlend" ); } else { // Single RT. Multiple passes. g_hBlendTech = g_pEffect->GetTechniqueByName( "BlobBlendTwoPasses" ); } // Setup the camera's view parameters D3DXVECTOR3 vecEye( 0.0f, 0.0f, -5.0f ); D3DXVECTOR3 vecAt ( 0.0f, 0.0f, -0.0f ); g_Camera.SetViewParams( &vecEye, &vecAt ); return S_OK; } //-------------------------------------------------------------------------------------- // Create any D3D9 resources that won't live through a device reset (D3DPOOL_DEFAULT) // or that are tied to the back buffer size //-------------------------------------------------------------------------------------- HRESULT CALLBACK OnResetDevice( IDirect3DDevice9* pd3dDevice, const D3DSURFACE_DESC* pBackBufferSurfaceDesc, void* pUserContext ) { HRESULT hr; V_RETURN( g_DialogResourceManager.OnD3D9ResetDevice() ); V_RETURN( g_SettingsDlg.OnD3D9ResetDevice() ); if( g_pFont ) V_RETURN( g_pFont->OnResetDevice() ); if( g_pEffect ) V_RETURN( g_pEffect->OnResetDevice() ); // Create a sprite to help batch calls when drawing many lines of text V_RETURN( D3DXCreateSprite( pd3dDevice, &g_pTextSprite ) ); // Create the Gaussian distribution texture V_RETURN( GenerateGaussianTexture() ); // Create the blob vertex buffer V_RETURN( pd3dDevice->CreateVertexBuffer( NUM_BLOBS * 6 * sizeof( SCREENVERTEX ), D3DUSAGE_WRITEONLY | D3DUSAGE_DYNAMIC, SCREENVERTEX::FVF, D3DPOOL_DEFAULT, &g_pBlobVB, NULL ) ); // Create the blank texture V_RETURN( pd3dDevice->CreateTexture( 1, 1, 1, D3DUSAGE_RENDERTARGET, D3DFMT_A16B16G16R16F, D3DPOOL_DEFAULT, &g_pTexScratch, NULL ) ); // Create buffer textures for( int i = 0; i < 4; ++i ) { V_RETURN( pd3dDevice->CreateTexture( pBackBufferSurfaceDesc->Width, pBackBufferSurfaceDesc->Height, 1, D3DUSAGE_RENDERTARGET, D3DFMT_A16B16G16R16F, D3DPOOL_DEFAULT, &g_pTexGBuffer[i], NULL ) ); } // Initialize the render targets if( 1 == g_nPasses ) { // Multiple RT IDirect3DSurface9* pSurf; g_pTexGBuffer[2]->GetSurfaceLevel( 0, &pSurf ); g_aRTSet[0].apCopyRT[0] = pSurf; g_pTexGBuffer[3]->GetSurfaceLevel( 0, &pSurf ); g_aRTSet[0].apCopyRT[1] = pSurf; g_pTexGBuffer[0]->GetSurfaceLevel( 0, &pSurf ); g_aRTSet[0].apBlendRT[0] = pSurf; g_pTexGBuffer[1]->GetSurfaceLevel( 0, &pSurf ); g_aRTSet[0].apBlendRT[1] = pSurf; // 2nd pass is not needed. Therefore all RTs are NULL for this pass. g_aRTSet[1].apCopyRT[0] = NULL; g_aRTSet[1].apCopyRT[1] = NULL; g_aRTSet[1].apBlendRT[0] = NULL; g_aRTSet[1].apBlendRT[1] = NULL; } else { // Single RT, multiple passes IDirect3DSurface9* pSurf; g_pTexGBuffer[2]->GetSurfaceLevel( 0, &pSurf ); g_aRTSet[0].apCopyRT[0] = pSurf; g_pTexGBuffer[3]->GetSurfaceLevel( 0, &pSurf ); g_aRTSet[1].apCopyRT[0] = pSurf; g_pTexGBuffer[0]->GetSurfaceLevel( 0, &pSurf ); g_aRTSet[0].apBlendRT[0] = pSurf; g_pTexGBuffer[1]->GetSurfaceLevel( 0, &pSurf ); g_aRTSet[1].apBlendRT[0] = pSurf; // RT 1 is not available. Therefore all RTs are NULL for this index. g_aRTSet[0].apCopyRT[1] = NULL; g_aRTSet[1].apCopyRT[1] = NULL; g_aRTSet[0].apBlendRT[1] = NULL; g_aRTSet[1].apBlendRT[1] = NULL; } // Set the camera parameters float fAspectRatio = pBackBufferSurfaceDesc->Width / ( FLOAT )pBackBufferSurfaceDesc->Height; D3DXVECTOR3 vEyePt = D3DXVECTOR3( 0.0f, -2.0f, -5.0f ); D3DXVECTOR3 vLookatPt = D3DXVECTOR3( 0.0f, 0.0f, 0.0f ); g_Camera.SetViewParams( &vEyePt, &vLookatPt ); g_Camera.SetProjParams( FIELD_OF_VIEW, fAspectRatio, 1.0f, 100.0f ); g_Camera.SetRadius( 5.0f, 2.0f, 20.0f ); g_Camera.SetWindow( pBackBufferSurfaceDesc->Width, pBackBufferSurfaceDesc->Height ); g_Camera.SetInvertPitch( true ); // Position the on-screen dialog g_HUD.SetLocation( pBackBufferSurfaceDesc->Width - 170, 0 ); g_HUD.SetSize( 170, 170 ); return S_OK; } //----------------------------------------------------------------------------- // Generate a texture to store gaussian distribution results //----------------------------------------------------------------------------- HRESULT GenerateGaussianTexture() { HRESULT hr = S_OK; LPDIRECT3DSURFACE9 pBlobTemp = NULL; LPDIRECT3DSURFACE9 pBlobNew = NULL; IDirect3DDevice9* pd3dDevice = DXUTGetD3D9Device(); // Create a temporary texture LPDIRECT3DTEXTURE9 texTemp; V_RETURN( pd3dDevice->CreateTexture( GAUSSIAN_TEXSIZE, GAUSSIAN_TEXSIZE, 1, D3DUSAGE_DYNAMIC, D3DFMT_R32F, D3DPOOL_DEFAULT, &texTemp, NULL ) ); // Create the gaussian texture V_RETURN( pd3dDevice->CreateTexture( GAUSSIAN_TEXSIZE, GAUSSIAN_TEXSIZE, 1, D3DUSAGE_DYNAMIC, g_BlobTexFormat, D3DPOOL_DEFAULT, &g_pTexBlob, NULL ) ); // Create the environment map TCHAR str[MAX_PATH]; V_RETURN( DXUTFindDXSDKMediaFileCch( str, MAX_PATH, L"lobby\\lobbycube.dds" ) ); V_RETURN( D3DXCreateCubeTextureFromFile( pd3dDevice, str, &g_pEnvMap ) ); // Fill in the gaussian texture data D3DLOCKED_RECT Rect; V_RETURN( texTemp->LockRect( 0, &Rect, 0, 0 ) ); int u, v; float dx, dy, I; float* pBits; for( v = 0; v < GAUSSIAN_TEXSIZE; ++v ) { pBits = ( float* )( ( char* )( Rect.pBits ) + v * Rect.Pitch ); for( u = 0; u < GAUSSIAN_TEXSIZE; ++u ) { dx = 2.0f * u / ( float )GAUSSIAN_TEXSIZE - 1.0f; dy = 2.0f * v / ( float )GAUSSIAN_TEXSIZE - 1.0f; I = GAUSSIAN_HEIGHT * ( float )exp( -( dx * dx + dy * dy ) / GAUSSIAN_DEVIATION ); *( pBits++ ) = I; // intensity } } texTemp->UnlockRect( 0 ); // Copy the temporary surface to the stored gaussian texture V_RETURN( texTemp->GetSurfaceLevel( 0, &pBlobTemp ) ); V_RETURN( g_pTexBlob->GetSurfaceLevel( 0, &pBlobNew ) ); V_RETURN( D3DXLoadSurfaceFromSurface( pBlobNew, 0, 0, pBlobTemp, 0, 0, D3DX_FILTER_NONE, 0 ) ); SAFE_RELEASE( pBlobTemp ); SAFE_RELEASE( pBlobNew ); SAFE_RELEASE( texTemp ); return S_OK; } //----------------------------------------------------------------------------- // Fill the vertex buffer for the blob objects //----------------------------------------------------------------------------- HRESULT FillBlobVB( D3DXMATRIXA16* pmatWorldView ) { HRESULT hr = S_OK; UINT i = 0; // Loop variable SCREENVERTEX* pBlobVertex; V_RETURN( g_pBlobVB->Lock( 0, 0, ( void** )&pBlobVertex, D3DLOCK_DISCARD ) ); POINTVERTEX blobPos[ NUM_BLOBS ]; for( i = 0; i < NUM_BLOBS; ++i ) { // Transform point to camera space D3DXVECTOR4 blobPosCamera; D3DXVec3Transform( &blobPosCamera, &g_BlobPoints[i].pos, pmatWorldView ); blobPos[i] = g_BlobPoints[i]; blobPos[i].pos.x = blobPosCamera.x; blobPos[i].pos.y = blobPosCamera.y; blobPos[i].pos.z = blobPosCamera.z; } int posCount = 0; for( i = 0; i < NUM_BLOBS; ++i ) { D3DXVECTOR4 blobScreenPos; // For calculating billboarding D3DXVECTOR4 billOfs( blobPos[i].size,blobPos[i].size,blobPos[i].pos.z,1 ); D3DXVECTOR4 billOfsScreen; // Transform to screenspace const D3DXMATRIX* pmatProjection = g_Camera.GetProjMatrix(); D3DXVec3Transform( &blobScreenPos, &blobPos[i].pos, pmatProjection ); D3DXVec4Transform( &billOfsScreen, &billOfs, pmatProjection ); // Project D3DXVec4Scale( &blobScreenPos, &blobScreenPos, 1.0f / blobScreenPos.w ); D3DXVec4Scale( &billOfsScreen, &billOfsScreen, 1.0f / billOfsScreen.w ); D3DXVECTOR2 vTexCoords[] = { D3DXVECTOR2( 0.0f, 0.0f ), D3DXVECTOR2( 1.0f, 0.0f ), D3DXVECTOR2( 0.0f, 1.0f ), D3DXVECTOR2( 0.0f, 1.0f ), D3DXVECTOR2( 1.0f, 0.0f ), D3DXVECTOR2( 1.0f, 1.0f ), }; D3DXVECTOR4 vPosOffset[] = { D3DXVECTOR4( -billOfsScreen.x, -billOfsScreen.y, 0.0f, 0.0f ), D3DXVECTOR4( billOfsScreen.x, -billOfsScreen.y, 0.0f, 0.0f ), D3DXVECTOR4( -billOfsScreen.x, billOfsScreen.y, 0.0f, 0.0f ), D3DXVECTOR4( -billOfsScreen.x, billOfsScreen.y, 0.0f, 0.0f ), D3DXVECTOR4( billOfsScreen.x, -billOfsScreen.y, 0.0f, 0.0f ), D3DXVECTOR4( billOfsScreen.x, billOfsScreen.y, 0.0f, 0.0f ), }; const D3DSURFACE_DESC* pBackBufferSurfaceDesc = DXUTGetD3D9BackBufferSurfaceDesc(); // Set constants across quad for( int j = 0; j < 6; ++j ) { // Scale to pixels D3DXVec4Add( &pBlobVertex[posCount].pos, &blobScreenPos, &vPosOffset[j] ); pBlobVertex[posCount].pos.x *= pBackBufferSurfaceDesc->Width; pBlobVertex[posCount].pos.y *= pBackBufferSurfaceDesc->Height; pBlobVertex[posCount].pos.x += 0.5f * pBackBufferSurfaceDesc->Width; pBlobVertex[posCount].pos.y += 0.5f * pBackBufferSurfaceDesc->Height; pBlobVertex[posCount].tCurr = vTexCoords[j]; pBlobVertex[posCount].tBack = D3DXVECTOR2( ( 0.5f + pBlobVertex[posCount].pos.x ) * ( 1.0f / pBackBufferSurfaceDesc->Width ), ( 0.5f + pBlobVertex[posCount].pos.y ) * ( 1.0f / pBackBufferSurfaceDesc->Height ) ); pBlobVertex[posCount].fSize = blobPos[i].size; pBlobVertex[posCount].vColor = blobPos[i].color; posCount++; } } g_pBlobVB->Unlock(); return hr; } //-------------------------------------------------------------------------------------- // Handle updates to the scene. This is called regardless of which D3D API is used //-------------------------------------------------------------------------------------- void CALLBACK OnFrameMove( double fTime, float fElapsedTime, void* pUserContext ) { HRESULT hr; static bool bPaused = false; // Update the camera's position based on user input g_Camera.FrameMove( fElapsedTime ); // Pause animatation if the user is rotating around if( !IsIconic( DXUTGetHWND() ) ) { if( g_Camera.IsBeingDragged() && !DXUTIsTimePaused() ) DXUTPause( true, false ); if( !g_Camera.IsBeingDragged() && DXUTIsTimePaused() ) DXUTPause( false, false ); } // Get the projection & view matrix from the camera class D3DXMATRIXA16 mWorldView; D3DXMATRIXA16 mWorldViewProjection; D3DXMatrixMultiply( &mWorldView, g_Camera.GetWorldMatrix(), g_Camera.GetViewMatrix() ); D3DXMatrixMultiply( &mWorldViewProjection, &mWorldView, g_Camera.GetProjMatrix() ); // Update the effect's variables. Instead of using strings, it would // be more efficient to cache a handle to the parameter by calling // ID3DXEffect::GetParameterByName V( g_pEffect->SetMatrix( "g_mWorldViewProjection", &mWorldViewProjection ) ); // Animate the blobs float pos = ( float )( 1.0f + cos( 2 * D3DX_PI * fTime / 3.0f ) ); g_BlobPoints[1].pos.x = pos; g_BlobPoints[2].pos.x = -pos; g_BlobPoints[3].pos.y = pos; g_BlobPoints[4].pos.y = -pos; FillBlobVB( &mWorldView ); } //-------------------------------------------------------------------------------------- // Render the scene using the D3D9 device //-------------------------------------------------------------------------------------- void CALLBACK OnFrameRender( IDirect3DDevice9* pd3dDevice, double fTime, float fElapsedTime, void* pUserContext ) { if( g_SettingsDlg.IsActive() ) { g_SettingsDlg.OnRender( fElapsedTime ); return; } HRESULT hr; LPDIRECT3DSURFACE9 apSurfOldRenderTarget[2] = { NULL, NULL }; LPDIRECT3DSURFACE9 pSurfOldDepthStencil = NULL; LPDIRECT3DSURFACE9 pGBufSurf[4]; // Clear the render target and the zbuffer V( pd3dDevice->Clear( 0, NULL, D3DCLEAR_TARGET | D3DCLEAR_ZBUFFER, D3DCOLOR_ARGB( 0, 45, 50, 170 ), 1.0f, 0 ) ); // Render the scene if( SUCCEEDED( pd3dDevice->BeginScene() ) ) { // Get the initial device surfaces V( pd3dDevice->GetRenderTarget( 0, &apSurfOldRenderTarget[0] ) ); // Only RT 0 should've been set. V( pd3dDevice->GetDepthStencilSurface( &pSurfOldDepthStencil ) ); // Turn off Z V( pd3dDevice->SetRenderState( D3DRS_ZENABLE, D3DZB_FALSE ) ); V( pd3dDevice->SetDepthStencilSurface( NULL ) ); // Clear the blank texture LPDIRECT3DSURFACE9 pSurfBlank; V( g_pTexScratch->GetSurfaceLevel( 0, &pSurfBlank ) ); V( pd3dDevice->SetRenderTarget( 0, pSurfBlank ) ); V( pd3dDevice->Clear( 0, NULL, D3DCLEAR_TARGET, D3DCOLOR_ARGB( 0, 0, 0, 0 ), 1.0f, 0 ) ); SAFE_RELEASE( pSurfBlank ); // Clear temp textures int i; for( i = 0; i < 2; ++i ) { V( g_pTexGBuffer[i]->GetSurfaceLevel( 0, &pGBufSurf[i] ) ); V( pd3dDevice->SetRenderTarget( 0, pGBufSurf[i] ) ); V( pd3dDevice->Clear( 0, NULL, D3DCLEAR_TARGET, D3DCOLOR_ARGB( 0, 0, 0, 0 ), 1.0f, 0 ) ); } for( i = 2; i < 4; ++i ) V( g_pTexGBuffer[i]->GetSurfaceLevel( 0, &pGBufSurf[i] ) ); V( pd3dDevice->SetStreamSource( 0, g_pBlobVB, 0, sizeof( SCREENVERTEX ) ) ); V( pd3dDevice->SetFVF( SCREENVERTEX::FVF ) ); // Render the blobs UINT iPass, nNumPasses; V( g_pEffect->SetTechnique( g_hBlendTech ) ); for( i = 0; i < NUM_BLOBS; ++i ) { // Copy bits off of render target into scratch surface [for blending]. V( g_pEffect->SetTexture( "g_tSourceBlob", g_pTexScratch ) ); V( g_pEffect->SetTexture( "g_tNormalBuffer", g_pTexGBuffer[0] ) ); V( g_pEffect->SetTexture( "g_tColorBuffer", g_pTexGBuffer[1] ) ); if( SUCCEEDED( g_pEffect->Begin( &nNumPasses, 0 ) ) ) { for( iPass = 0; iPass < nNumPasses; iPass++ ) { for( int rt = 0; rt < g_nRtUsed; ++rt ) V( pd3dDevice->SetRenderTarget( rt, g_aRTSet[iPass].apCopyRT[rt] ) ); V( g_pEffect->BeginPass( iPass ) ); V( pd3dDevice->DrawPrimitive( D3DPT_TRIANGLELIST, i * 6, 2 ) ); V( g_pEffect->EndPass() ); } V( g_pEffect->End() ); } // Render the blob V( g_pEffect->SetTexture( "g_tSourceBlob", g_pTexBlob ) ); V( g_pEffect->SetTexture( "g_tNormalBuffer", g_pTexGBuffer[2] ) ); V( g_pEffect->SetTexture( "g_tColorBuffer", g_pTexGBuffer[3] ) ); if( SUCCEEDED( g_pEffect->Begin( &nNumPasses, 0 ) ) ) { for( iPass = 0; iPass < nNumPasses; iPass++ ) { for( int rt = 0; rt < g_nRtUsed; ++rt ) V( pd3dDevice->SetRenderTarget( rt, g_aRTSet[iPass].apBlendRT[rt] ) ); V( g_pEffect->BeginPass( iPass ) ); V( pd3dDevice->DrawPrimitive( D3DPT_TRIANGLELIST, i * 6, 2 ) ); V( g_pEffect->EndPass() ); } V( g_pEffect->End() ); } } // Restore initial device surfaces V( pd3dDevice->SetDepthStencilSurface( pSurfOldDepthStencil ) ); for( int rt = 0; rt < g_nRtUsed; ++rt ) V( pd3dDevice->SetRenderTarget( rt, apSurfOldRenderTarget[rt] ) ); // Light and composite blobs into backbuffer V( g_pEffect->SetTechnique( "BlobLight" ) ); V( g_pEffect->Begin( &nNumPasses, 0 ) ); for( iPass = 0; iPass < nNumPasses; iPass++ ) { V( g_pEffect->BeginPass( iPass ) ); for( i = 0; i < NUM_BLOBS; ++i ) { V( g_pEffect->SetTexture( "g_tSourceBlob", g_pTexGBuffer[0] ) ); V( g_pEffect->SetTexture( "g_tColorBuffer", g_pTexGBuffer[1] ) ); V( g_pEffect->SetTexture( "g_tEnvMap", g_pEnvMap ) ); V( g_pEffect->CommitChanges() ); V( RenderFullScreenQuad( 1.0f ) ); } V( g_pEffect->EndPass() ); } V( g_pEffect->End() ); RenderText(); V( g_HUD.OnRender( fElapsedTime ) ); V( pd3dDevice->EndScene() ); } for( int rt = 0; rt < g_nRtUsed; ++rt ) SAFE_RELEASE( apSurfOldRenderTarget[rt] ); SAFE_RELEASE( pSurfOldDepthStencil ); for( int i = 0; i < 4; ++i ) { SAFE_RELEASE( pGBufSurf[i] ); } } //----------------------------------------------------------------------------- // Render a quad at the specified tranformed depth //----------------------------------------------------------------------------- HRESULT RenderFullScreenQuad( float fDepth ) { SCREENVERTEX aVertices[4]; IDirect3DDevice9* pd3dDevice = DXUTGetD3D9Device(); const D3DSURFACE_DESC* pBackBufferSurfaceDesc = DXUTGetD3D9BackBufferSurfaceDesc(); aVertices[0].pos = D3DXVECTOR4( -0.5f, -0.5f, fDepth, fDepth ); aVertices[1].pos = D3DXVECTOR4( pBackBufferSurfaceDesc->Width - 0.5f, -0.5f, fDepth, fDepth ); aVertices[2].pos = D3DXVECTOR4( -0.5f, pBackBufferSurfaceDesc->Height - 0.5f, fDepth, fDepth ); aVertices[3].pos = D3DXVECTOR4( pBackBufferSurfaceDesc->Width - 0.5f, pBackBufferSurfaceDesc->Height - 0.5f, fDepth, fDepth ); aVertices[0].tCurr = D3DXVECTOR2( 0.0f, 0.0f ); aVertices[1].tCurr = D3DXVECTOR2( 1.0f, 0.0f ); aVertices[2].tCurr = D3DXVECTOR2( 0.0f, 1.0f ); aVertices[3].tCurr = D3DXVECTOR2( 1.0f, 1.0f ); aVertices[0].vColor = aVertices[1].vColor = aVertices[2].vColor = aVertices[3].vColor = D3DXVECTOR3(0,0,0); for( int i = 0; i < 4; ++i ) { aVertices[i].tBack = aVertices[i].tCurr; aVertices[i].tBack.x += ( 1.0f / pBackBufferSurfaceDesc->Width ); aVertices[i].tBack.y += ( 1.0f / pBackBufferSurfaceDesc->Height ); aVertices[i].fSize = 0.0f; } pd3dDevice->SetFVF( SCREENVERTEX::FVF ); pd3dDevice->DrawPrimitiveUP( D3DPT_TRIANGLESTRIP, 2, aVertices, sizeof( SCREENVERTEX ) ); return S_OK; } //-------------------------------------------------------------------------------------- // Render the help and statistics text. This function uses the ID3DXFont interface for // efficient text rendering. //-------------------------------------------------------------------------------------- void RenderText() { // The helper object simply helps keep track of text position, and color // and then it calls pFont->DrawText( g_pSprite, strMsg, -1, &rc, DT_NOCLIP, g_clr ); // If NULL is passed in as the sprite object, then it will work however the // pFont->DrawText() will not be batched together. Batching calls will improves performance. CDXUTTextHelper txtHelper( g_pFont, g_pTextSprite, 15 ); // Output statistics txtHelper.Begin(); txtHelper.SetInsertionPos( 5, 5 ); txtHelper.SetForegroundColor( D3DXCOLOR( 1.0f, 1.0f, 0.0f, 1.0f ) ); txtHelper.DrawTextLine( DXUTGetFrameStats( DXUTIsVsyncEnabled() ) ); txtHelper.DrawTextLine( DXUTGetDeviceStats() ); txtHelper.SetForegroundColor( D3DXCOLOR( 1.0f, 1.0f, 1.0f, 1.0f ) ); // Draw help if( g_bShowHelp ) { const D3DSURFACE_DESC* pd3dsdBackBuffer = DXUTGetD3D9BackBufferSurfaceDesc(); txtHelper.SetInsertionPos( 10, pd3dsdBackBuffer->Height - 15 * 6 ); txtHelper.SetForegroundColor( D3DXCOLOR( 1.0f, 0.75f, 0.0f, 1.0f ) ); txtHelper.DrawTextLine( L"Controls (F1 to hide):" ); txtHelper.SetInsertionPos( 40, pd3dsdBackBuffer->Height - 15 * 5 ); txtHelper.DrawTextLine( L"Rotate model: Left mouse button\n" L"Rotate camera: Right mouse button\n" L"Zoom camera: Mouse wheel scroll\n" ); } else { txtHelper.SetForegroundColor( D3DXCOLOR( 1.0f, 1.0f, 1.0f, 1.0f ) ); txtHelper.DrawTextLine( L"Press F1 for help" ); } txtHelper.End(); } //-------------------------------------------------------------------------------------- // Handle messages to the application //-------------------------------------------------------------------------------------- LRESULT CALLBACK MsgProc( HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam, bool* pbNoFurtherProcessing, void* pUserContext ) { // Always allow dialog resource manager calls to handle global messages // so GUI state is updated correctly *pbNoFurtherProcessing = g_DialogResourceManager.MsgProc( hWnd, uMsg, wParam, lParam ); if( *pbNoFurtherProcessing ) return 0; if( g_SettingsDlg.IsActive() ) { g_SettingsDlg.MsgProc( hWnd, uMsg, wParam, lParam ); return 0; } // Give the dialogs a chance to handle the message first *pbNoFurtherProcessing = g_HUD.MsgProc( hWnd, uMsg, wParam, lParam ); if( *pbNoFurtherProcessing ) return 0; // Pass all remaining windows messages to camera so it can respond to user input g_Camera.HandleMessages( hWnd, uMsg, wParam, lParam ); return 0; } //-------------------------------------------------------------------------------------- // Handle key presses //-------------------------------------------------------------------------------------- void CALLBACK KeyboardProc( UINT nChar, bool bKeyDown, bool bAltDown, void* pUserContext ) { if( bKeyDown ) { switch( nChar ) { case VK_F1: g_bShowHelp = !g_bShowHelp; break; case VK_F2: if( DXUTIsTimePaused() ) DXUTPause( false, false ); } } } //-------------------------------------------------------------------------------------- // Handles the GUI events //-------------------------------------------------------------------------------------- void CALLBACK OnGUIEvent( UINT nEvent, int nControlID, CDXUTControl* pControl, void* pUserContext ) { switch( nControlID ) { case IDC_TOGGLEFULLSCREEN: DXUTToggleFullScreen(); break; case IDC_TOGGLEREF: DXUTToggleREF(); break; case IDC_CHANGEDEVICE: g_SettingsDlg.SetActive( !g_SettingsDlg.IsActive() ); break; } } //-------------------------------------------------------------------------------------- // Release D3D9 resources created in the OnD3D9ResetDevice callback //-------------------------------------------------------------------------------------- void CALLBACK OnLostDevice( void* pUserContext ) { g_DialogResourceManager.OnD3D9LostDevice(); g_SettingsDlg.OnD3D9LostDevice(); if( g_pFont ) g_pFont->OnLostDevice(); if( g_pEffect ) g_pEffect->OnLostDevice(); SAFE_RELEASE( g_pTextSprite ); SAFE_RELEASE( g_pBlobVB ); SAFE_RELEASE( g_pTexScratch ); SAFE_RELEASE( g_pTexBlob ); SAFE_RELEASE( g_pEnvMap ); for( int p = 0; p < 2; ++p ) for( int i = 0; i < 2; ++i ) { SAFE_RELEASE( g_aRTSet[p].apCopyRT[i] ); SAFE_RELEASE( g_aRTSet[p].apBlendRT[i] ); } for( UINT i = 0; i < 4; i++ ) { SAFE_RELEASE( g_pTexGBuffer[i] ); } } //-------------------------------------------------------------------------------------- // Release D3D9 resources created in the OnD3D9CreateDevice callback //-------------------------------------------------------------------------------------- void CALLBACK OnDestroyDevice( void* pUserContext ) { g_DialogResourceManager.OnD3D9DestroyDevice(); g_SettingsDlg.OnD3D9DestroyDevice(); SAFE_RELEASE( g_pEffect ); SAFE_RELEASE( g_pFont ); }
C++
CL
6dd1df9cc43a630b3f15a532fc41e85ab502d1595901f27b1bdb12f8e9538940
/** * \file * \version $Id: NpcTrade.h $ * \author * \date * \brief Npc买卖对话框 * * */ #ifndef _NpcTrade_h_ #define _NpcTrade_h_ #include "zType.h" #include "zRWLock.h" #include "zDatabase.h" /** * \brief NPC买卖 * */ class NpcTrade { public: enum { NPC_BUY_OBJECT = 1, ///买 NPC_SELL_OBJECT = 2, ///卖 NPC_REPAIR_OBJECT = 4, ///修理 NPC_MAKE_OBJECT = 8, ///打造 NPC_UPDATE_OBJECT = 16, ///改造 NPC_MERGE_OBJECT = 32, ///合成 NPC_ENCHANCE_OBJECT = 64, //镶嵌 NPC_MERGE_SOUL_OBJECT = 128, //魂魄合成 NPC_HOLE_OBJECT = 256, //打孔 NPC_STORE_OBJECT = 512, //仓库 NPC_DECOMPOSE_OBJECT = 1024, //分解 }; struct NpcItem { DWORD id; ///物品编号 WORD kind; ///物品类型 WORD lowLevel; ///最低等级 WORD level; ///最高等级 WORD itemlevel; ///购买物品的等级 WORD action; ///动作类型 NpcItem() { id = 0; kind = 0; lowLevel = 0; level = 0; itemlevel = 0; action = 0; } }; ~NpcTrade() { final(); } /** * \brief 得到唯一实例 * * * \return npc买卖系统 */ static NpcTrade &getInstance() { if (NULL == instance) instance = new NpcTrade(); return *instance; } /** * \brief 卸载唯一实例 * */ static void delInstance() { SAFE_DELETE(instance); } bool init(); bool getNpcMenu(const DWORD npcid, char *menuTxt); bool verifyNpcAction(const DWORD npcid, const NpcItem &item); private: NpcTrade() {}; void final(); static NpcTrade *instance; typedef __gnu_cxx::hash_multimap<DWORD, NpcItem> NpcItemMultiMap; /** * \brief npc对话框 * */ struct NpcDialog { DWORD npcid; ///Npc编号 char menu[6144]; ///菜单内容 NpcItemMultiMap items; ///物品动作 NpcDialog() { npcid = 0; bzero(menu, sizeof(menu)); } NpcDialog(const NpcDialog& nd) { npcid = nd.npcid; bcopy(nd.menu, menu, sizeof(menu)); for(NpcItemMultiMap::const_iterator it = nd.items.begin(); it != nd.items.end(); it++) { items.insert(*it); } } }; typedef __gnu_cxx::hash_multimap<DWORD, NpcDialog> NpcDialogMultiMap; NpcDialogMultiMap dialogs; zRWLock rwlock; }; #endif
C++
CL
7aa06aaf83ba1a4342ac44dcf32de11aaf1fe2ec06e929e2fd97a60a17d1780f
/****************************************************************************** @File XESeqAnimController.h @Version 1.0 @Created 2017,12, 22 @HISTORY: ******************************************************************************/ #ifndef XE_SEQ_ANIM_CONTROLLER_H #define XE_SEQ_ANIM_CONTROLLER_H #include "XMath3D.h" #include "XEAnimController.h" //in a uniform time unit- microsecond. //animation controller of the sequence. class XESequencerInstance; class XEUserNodeInstance; class XEKeyframeBase; class XESeqAnimController :public XEAnimController { public: class Listener : public XEAnimController::Listener { public: virtual ~Listener() {} virtual void Ls_KeyframeTrigger(xfloat32 nMillisecond, const XEKeyframeBase* pKeyframe){} }; XESeqAnimController(); virtual ~XESeqAnimController(); public: void BroadcastKeyframeTrigger(const XEKeyframeBase* pKeyframe); X_FORCEINLINE void SetSequencer(XESequencerInstance* pSequencerIns){ m_pSequencerIns = pSequencerIns; } X_FORCEINLINE XESequencerInstance* GetSequencer(){ return m_pSequencerIns; } public: virtual void Tick(xfloat32 fInterval) override; virtual xint32 GetTimeLength() const override; virtual void SetTime(xint32 nTime) override; void GetNodeTimeLength(XEUserNodeInstance* pNodeIns, xint32& nTimeLen) const; private: XESequencerInstance* m_pSequencerIns; }; #endif // XE_SEQ_ANIM_CONTROLLER_H
C++
CL
e744c068e0cc3958c84bb327cb31184af9fc48b5784504c13e0850ae44e167bd
/*********************** File Name : Texture.h Description : define the Texture class which contain functions to create a texture and store it within an instance of this class Author : Sakyawira Nanda Ruslim Mail : [email protected] ********************/ #pragma once #include <glew.h> #include <SOIL.h> #include <vector> #include <gtc/type_ptr.hpp> #include "ShaderLoader.h" class Texture { public: Texture(const char * textureDir); ~Texture() = default; GLuint GetID(); private: GLuint textureID; };
C++
CL
151023bddf56e2432b5481c46528184f49a3152e30797601f271c6d7c65d4f42
// Somewhat general implementation of Monte Carlo Tree Search. Only for games that the rewards are all provided at the termination of the game (could easily be adapted though). // Note: final rewards should have |r| <= 1. Need to provide a number of functions to define the game logic. // What needs to be provided: // - A class for the game state. should include an integer denoting players go (0,1,...) in variable plyrsGo // - A class for the possible actions. (probably easiest to use an integer in many cases). // - A function getActions(state) (returns vector of actions available) // - A function getNextState(state, int) // - A function defaultPolicy(state, vector<int> actions) // - A function selectionEvaluation(double,int, int) that evaluates how we select "intelligently" (e.g. UCB1) // - A function isTerminal(state) // - A function assignRewards(state) that evaluates the terminal state and determines which player won. //e.g. usage: // currentGame Game(state); // Game.initialize; // Game.playNGames(N); // A moveToMake = Game.bestInitialAction(); // Game.cleanUp(); // Game.playNGames(N); //play again from the next state that's actually been chosen. #include <functional> #include <vector> #include <algorithm> #include <math.h> #include <random> #ifndef MCTS_H #define MCTS_H template<class S, class A> struct node; //forward declaration //this class is a link between states, i.e. from state S, if we take the action corresponding to this link we get to state S'. template <class S, class A> struct link { node<S,A> *parentState; //pointer to "parent" state node<S,A> *nextState; //pointer to next state. double totReward = 0; //stores the sum of rewards when visiting this link. int nTotal = 0; //total number of times this link has been used. }; //node in the game tree. template <class S, class A> struct node { S gameState; node<S,A> *prevNode; int prevAction; //action index which led to this state. std::vector<A> availableActions; std::vector<link<S,A>> availableLinks; bool allActionsTried = false; // have all available actions from this node been tried. int nVisits = 0; //number of times this node has been visited. }; //main game class template <class S, class A> struct currentGame { currentGame(S initState, int players); //constructor node<S,A> rootNode; //current node of the game, from which we will explore possible futures. node<S,A> *currentNode; //current node being considered. int nPlayers; std::vector<double> gameRewards; //stores the reward for each player. std::function< std::vector<A>(S &) > getActions; //return a vector of possible actions from the given state std::function< S(S &, A & ) > getNextState; //given a state S and an action A, return the resulting state. std::function< S(S &, std::vector<A> &) > defaultPolicy; //the "default" policy, i.e. what action is selected without using MCTS (usually random unless there is some "expert knowledge" that can be added). std::function< double(double, int, int) > selectionEvaluation; //provide a function for evaluating how to select moves (e.g. UCB1) std::function< bool(S &) > isTerminal; //check if state reached is terminal. std::function< std::vector<double>(S &) > assignRewards; //apply to a terminal state and return the reward for each player void initialize(); // set up available actions from root node etc. void selection(); //cycle through the game tree selecting actions "intelligently" for as long as we can. void expansion(); //once we can use selection no more, expand from this node. void finishSimulation(); //run simulation to end. void backpropagation(); //backpropagate the result back up the tree. void playNGames(int N); //run N games from the current root node. A bestInitialAction(); //returns the best current action from the root node. void deleteNode(node<S, A> *cNode); //delete node from memory. void cleanUp(); //deletes all of the tree which does not correspond to what's left after the best available current action. }; //constructor for the main game. template <class S, class A> currentGame<S,A>::currentGame(S initState, int players) { nPlayers = players; //number of players rootNode.gameState = initState; rootNode.prevNode = NULL; rootNode.prevAction = NULL; } //initialize the root node (available actions and the states these lead to). template <class S, class A> void currentGame<S,A>::initialize() { rootNode.availableActions = getActions(rootNode.gameState); for (int i = 0; i < rootNode.availableActions.size(); i++) { link<S,A> newLink; newLink.parentState = &rootNode; // S nextState = getNextState(rootNode.gameState, rootNode.availableActions[i]); newLink.nextState = new node<S,A>; // newLink.nextState.gameState = nextState; rootNode.availableLinks.push_back(newLink); } } //run "selection" according to selectionEvaluation until we need to expand the tree. template <class S, class A> void currentGame<S,A>::selection() { currentNode = &rootNode; //start at the root. while (currentNode->allActionsTried) { double maxValue = -99999999999; int maxInd, counter = 0; for (auto & nextLink : currentNode->availableLinks) { double moveValue = selectionEvaluation(nextLink.totReward, nextLink.nTotal, nextLink.parentState->nVisits); if (moveValue > maxValue) { maxInd = counter; maxValue = moveValue; } counter++; } currentNode = currentNode->availableLinks[maxInd].nextState; if (isTerminal(currentNode->gameState)) break; } } // expansion - expand the game tree when we can no longer select intelligently. template <class S, class A> void currentGame<S,A>::expansion() { //check which actions haven't been tried yet from this state: std::vector<int> unTried; for (int i = 0; i < currentNode->availableLinks.size(); i++) { if (currentNode->availableLinks[i].nTotal == 0) { unTried.push_back(i); } } std::random_shuffle(unTried.begin(), unTried.end()); // randomly choose which untried action to expand. if (unTried.size() == 1) { //then we are trying to final untried action here. currentNode->allActionsTried = true; } int actionTaken = unTried[0]; //select action we are expanding on //update currentNode S newState = getNextState(currentNode->gameState, currentNode->availableActions[actionTaken]); auto newNode = currentNode->availableLinks[actionTaken].nextState; newNode->gameState = newState; // fill in new state. newNode->prevNode = currentNode; newNode->prevAction = actionTaken; newNode->availableActions = getActions(newState); for (int i = 0; i < newNode->availableActions.size(); i++) { link<S,A> newLink; newLink.parentState = newNode; newLink.nextState = new node<S,A>; newNode->availableLinks.push_back(newLink); } currentNode = newNode; } //run simulation to the end from current Node. template <class S, class A> void currentGame<S,A>::finishSimulation() { S currState = currentNode->gameState; while (!isTerminal(currState)) { //currState.printState(); //can be useful for debugging to have this function. currState = defaultPolicy(currState, getActions(currState)); } gameRewards = assignRewards(currState); } //backpropagation phase template <class S, class A> void currentGame<S,A>::backpropagation() { //current node should still be the node after the expansion was made, and we backpropagate from here. while (currentNode->prevNode != NULL) { int pAction = currentNode->prevAction; currentNode = currentNode->prevNode; currentNode->nVisits++; currentNode->availableLinks[pAction].nTotal++; currentNode->availableLinks[pAction].totReward += gameRewards[currentNode->gameState.plyrsGo]; } } //carry out the actual simulations: template<class S, class A> void currentGame<S,A>::playNGames(int N) { //should already be initialized. for (int i = 0; i < N; i++) { selection(); if (!isTerminal(currentNode->gameState)) { expansion(); finishSimulation(); } else { gameRewards = assignRewards(currentNode->gameState); } backpropagation(); } } //return best current move (from the root node, i.e. which initial move is best) template <class S, class A> A currentGame<S,A>::bestInitialAction() { double maxValue = -9999999999999.0; A maxMove; for (int i = 0; i < rootNode.availableLinks.size(); i++) { double moveValue = rootNode.availableLinks[i].totReward / ((double)rootNode.availableLinks[i].nTotal); //std::cout << "move " << i << ": " << moveValue << std::endl; if (moveValue > maxValue) { maxValue = moveValue; maxMove = rootNode.availableActions[i]; } } std::cout << std::endl; return maxMove; } //clear node from memory, and all of the children nodes as well. template <class S, class A> void currentGame<S, A>::deleteNode(node<S, A> *cNode) { if (!isTerminal(cNode->gameState)) { for (int i = 0; i < cNode->availableLinks.size(); i++) { deleteNode(cNode->availableLinks.nextState); } } delete cNode; } //once a move has been chosen, clear the parts of the tree that are no longer in use and change the root node to the new state. template <class S, class A> void currentGame<S, A>::cleanUp() { double maxVal = -99999999999999.0; int maxInd; for (int i = 0; i < rootNode.availableLinks.size(); i++) { double val = rootNode.availableLinks[i].totReward / rootNode.availableLinks[i].nTotal; if (val > maxVal) { maxVal = val; maxInd = i; } } for (int i = 0; i < rootNode.availableLinks.size(); i++) { if (i == maxInd) continue; deleteNode(rootNode.availableLinks[i].nextState); } rootNode = *(rootNode.availableLinks[maxInd].nextState); } #endif
C++
CL
6d192d92715e892aa7ff73687f502a125c6e3428bfafb8c2c21d6479cbc0aad4